Medicines¶
Medicines with a schedule, a dose log and a stock count. The web UI, the chat tools (loryth-mcp) and the Android app's native reminders all use the routes on this page; keep them in step.
The server keeps the record. It does not ring: the phone keeps a copy of the next days' doses and schedules its reminders itself.
Words¶
| Word | Meaning |
|---|---|
| Medicine | Something the user takes. scheduled (times on chosen days) or as_needed (no times, no reminders). |
| Time | One scheduled time of a medicine: time, amount, and optionally a window end until and a critical_at time. |
| Dose | One planned intake: medicine + local day + time. It is pending until a record says taken or skipped. |
| Stock change | A pack added (pack) or the count set by hand (correction). |
Times are local wall-clock strings "HH:MM" (24 hours). Days are local dates "YYYY-MM-DD". Routes that need "today" take the IANA tz query parameter, like the rest of Health (default UTC). Amounts and stock are numbers in steps of 0.25; whole values are written without a decimal point (9, not 9.0).
Routes¶
All under the gateway prefix /api/v1/health. Responses use the usual {"status": "success", "data": ...} envelope. DELETE returns 204. Unknown or another user's ids return 404. Rule violations return 422 with a string code in detail:
| Code | When |
|---|---|
invalid_schedule | kind, days, starts_on, ends_on or times break a rule listed under Medicine |
not_scheduled | An answer names a dose that is not planned on that day |
invalid_status | An as-needed intake (time: null) is not taken |
invalid_amount | A pack with amount 0 |
invalid_timezone | tz is not an IANA zone |
A body with a wrong type, an unknown key or a value outside its range (a name over 120 characters, color: 8, an amount that is not a multiple of 0.25, a time that is not HH:MM) returns FastAPI's usual 422, where detail is a list.
| Method and path | Purpose |
|---|---|
GET /medicines?tz= | All medicines: scheduled first, then as needed, each group by name |
POST /medicines?tz= | Create. Body: MedicineCreate. 201 |
GET /medicines/{uuid}?tz= | One medicine with stock_changes and history |
PUT /medicines/{uuid}?tz= | Replace the editable fields. Body: MedicineBody |
DELETE /medicines/{uuid} | Delete the medicine, its doses and stock changes |
POST /medicines/{uuid}/stock?tz= | Body {"kind": "pack" \| "correction", "amount": n}. A pack adds amount and becomes pack_size; a correction sets the stock to amount. Returns the medicine |
GET /medicines/days/{day}?tz= | The day's doses: MedicineDay |
PUT /medicines/doses?tz= | Answer a dose. Body: DoseAnswer. Returns DoseResult |
DELETE /medicines/doses/{uuid} | Undo an answer; a taken dose goes back on the stock |
GET /medicines/settings | Reminder settings |
PUT /medicines/settings | Replace reminder settings |
GET /medicines/devices | Phones registered for reminders |
POST /medicines/devices | Body {"name": "Galaxy A35"}. 201 with {"device": Device, "key": "lhd_..."}. The key is shown once; only its SHA-256 is stored |
DELETE /medicines/devices/{uuid} | Revoke the device's key |
GET /device/medicines/plan?tz=&days= | Device key. The next days local days (1-8, default 3) of doses: DevicePlan |
POST /device/medicines/answers?tz= | Device key. Body {"answers": [DeviceAnswer, ...]} (1-100). Returns {"results": [{"ok": true} \| {"ok": false, "code": "..."}]} in order |
The two /device/... routes are in the AuthenticationMiddleware public_paths. They read Authorization: Device <key>, hash it and look the device up; IAM is not called. A missing, unknown or revoked key returns 401 {"detail": {"code": "invalid_device_key"}}. Each accepted call updates the device's last_seen_at.
Static paths (/medicines/days/..., /medicines/doses, /medicines/settings, /medicines/devices) are registered before /medicines/{uuid}.
POST /medicines, PUT /medicines/{uuid} and POST /medicines/{uuid}/stock return the same shape as GET /medicines/{uuid}, with stock_changes and history. GET /medicines returns the plain Medicine shape.
Shapes¶
Medicine¶
{
"uuid": "6f0c...",
"name": "Wellbutrin",
"strength": "150 mg",
"form": "tablet",
"color": 2,
"unit": {"one": "tablet", "many": "tablets"},
"kind": "scheduled",
"days": {"mode": "daily"},
"starts_on": "2026-11-19",
"ends_on": null,
"paused": false,
"times": [
{"time": "11:00", "amount": 1, "until": "13:00", "critical_at": "12:30"}
],
"reminders": {"snooze": true, "last_call": false},
"stock": 9,
"pack_size": 60,
"low_days": 7,
"low_count": null,
"days_left": 9,
"runs_out_on": "2026-11-30",
"low": false,
"created_at": "2026-11-19T08:00:00Z",
"updated_at": "2026-11-21T08:04:00Z"
}
form:tablet,capsule,softgel,drops,other.unitis derived from it: tablet(s), capsule(s), softgel(s), drop(s), dose(s).color: slot 0-7 into the theme's categorical palette (category0-category7).days:{"mode": "daily"},{"mode": "weekdays", "weekdays": [0, 2, 4]}(0 is Monday, at least one) or{"mode": "interval", "every": 2}(every N days counted fromstarts_on, N 2-60).times: 1-12 forscheduled, sorted bytime, eachtimeonce; empty foras_needed.untilis later thantime.critical_atis later thantimeand, whenuntilis set, not later than it. Windows do not cross midnight.amountis 0.25-100. A body may list the times in any order, and weekdays in any order or twice; the server sorts them and lists each weekday once.reminders.snooze: the phone repeats the reminder and offers Snooze.reminders.last_call: the last repeat is an alarm. Both default to true. A critical call is per time (critical_at).days_left: whole days the stock covers at the schedule's average daily amount (the amounts of one day, times the chosen weekdays over 7, or divided by the interval), rounded down; 0 when the stock is zero or below. It is null foras_needed, for a paused medicine and when the schedule uses nothing (ends_onis before today).runs_out_onis today (intz) plusdays_left, and null whendays_leftis.low: forscheduled,days_left <= low_daysand the stock does not cover the rest of the course whenends_onis set. The rest of the course is the planned doses from today throughends_onthat have no record yet, so a course whose last dose was just taken is not low. Foras_needed,low_countis set andstock <= low_count.- The stock may go below zero when more is taken than was counted; clients show "None left".
MedicineBody (PUT): name (1-120), strength (up to 60, or null), form, color, kind, days, starts_on, ends_on, paused, times, reminders, pack_size, low_days (1-60), low_count. Unknown keys are rejected. MedicineCreate (POST) is the same plus optional stock (default 0), recorded as a first correction when above zero.
Only name is required. A key left out takes its default, on PUT too, since PUT replaces: strength null, form tablet, color 0, kind scheduled, days daily, ends_on null, paused false, times empty (so a scheduled medicine must send them), reminders both true, pack_size null, low_days 7, low_count null. starts_on left out is today (in tz) on POST and stays as it was on PUT. pack_size is above 0; stock, low_count and stock amounts are 0-100000. PUT never changes the stock or the dose records.
GET /medicines/{uuid} adds:
{
"stock_changes": [
{"kind": "pack", "amount": 60, "stock_after": 69, "at": "2026-10-23T09:12:00Z"}
],
"history": [
{"day": "2026-11-08", "doses": [{"time": "08:00", "status": "taken", "taken_at": "2026-11-08T06:03:00Z"}]}
]
}
stock_changes holds the ten newest, newest first. history covers the 14 local days ending today, oldest first: always 14 entries, with doses: [] on a day with none. A scheduled dose with no record is missed on a day before today and pending today. Missed doses are only inferred from the day the schedule was last changed or resumed; earlier days list recorded doses only. An as-needed medicine lists its taken records with time: null, after any doses with a time, oldest first.
When a dose counts as scheduled¶
A dose is scheduled on a day when the medicine is scheduled and not paused, the day is within starts_on..ends_on and matches days, and the day is not before the day the schedule last changed. That last day is:
- the day the medicine was created (in
tz), even whenstarts_onis earlier, so a medicine added today has no missed doses and nopreviousyet; - the day of a PUT that changes
kind,days,starts_on,ends_onor the set oftimevalues, or that turnspausedoff. Changing only names, amounts,until,critical_at, reminders or stock settings keeps it.
The day view, history, previous, the device plan and the not_scheduled check all use this one rule. A paused medicine has no scheduled doses on any day. A record stays on its day whatever happens to the schedule later.
Dose¶
{
"medicine": {
"uuid": "6f0c...", "name": "Wellbutrin", "strength": "150 mg", "form": "tablet",
"color": 2, "unit": {"one": "tablet", "many": "tablets"}, "stock": 9
},
"day": "2026-11-21",
"time": "11:00",
"until": "13:00",
"critical_at": "12:30",
"amount": 1,
"status": "pending",
"uuid": null,
"taken_at": null,
"source": null,
"snooze": true,
"last_call": false,
"previous": {"day": "2026-11-20", "time": "11:00", "status": "skipped"}
}
status:pending,takenorskipped.uuid,taken_atandsource(app,chatorphone) are set once answered.taken_atis when the answer was given, for a skipped dose too.amountis the recorded amount once answered, the time's amount before.snoozeandlast_callare the medicine'sreminders.- A recorded dose whose time is no longer in the schedule is still listed on its day, with
untilandcritical_atnull. An as-needed intake hastime,until,critical_atandpreviousnull. previous: the scheduled dose of the same medicine before this one: an earlier time the same day, else the last time of the previous scheduled day (looking back at most 60 days, not before the schedule last changed). Itsstatusistaken,skipped,missed(no record, day before today) orpending(no record, today). Null when there is none.
MedicineDay¶
{
"day": "2026-11-21",
"doses": [],
"as_needed": [],
"low": [
{"medicine": {"uuid": "...", "name": "Magnesium", "...": "..."}, "stock": 9, "days_left": 4, "runs_out_on": "2026-11-25"}
]
}
doses are the scheduled doses of that day, by time then name, together with any recorded doses of that day whose time is no longer scheduled. as_needed are the as-needed doses taken that day (time: null), oldest first. low lists medicines whose low flag is set, by name, whatever the day. An as-needed entry has days_left and runs_out_on null.
DoseAnswer and DoseResult¶
{"medicine_uuid": "6f0c...", "day": "2026-11-21", "time": "11:00", "status": "taken", "taken_at": "2026-11-21T10:04:00Z", "amount": 1, "source": "app"}
medicine_uuidandstatus(takenorskipped) are required.daydefaults to today (intz);timeleft out is null.timeset: the dose must be a scheduled dose of that medicine on that day, else 422not_scheduled. One record per (medicine, day, time); answering again replaces it. A dose that already has a record can be answered again even when its time has since left the schedule.time: null: an as-needed intake, always a new record,statusmust betaken; any medicine accepts one, a scheduled medicine too.taken_atdefaults to now.amount(0.25-100) defaults to the time's amount, or 1 for as-needed.sourcedefaults toapp; chat tools sendchat. An answer with the same status as the record keeps the recordedamountandtaken_atunless it sends its own.- Stock: a record that becomes
takenlowers the stock by its amount; one that stops beingtaken(replaced byskipped, or deleted) raises it again. Repeating the same answer changes nothing.
DoseResult is {"dose": Dose, "stock": 8}.
Settings¶
snooze_steps: 1-6 waits in minutes (1-240). alarm_sentence: up to 140 characters, shown on last and critical calls. show_names: false hides medicine names on the lock screen and watch. Defaults as above when never saved.
Device, DevicePlan, DeviceAnswer¶
Device: {"uuid", "name", "created_at", "last_seen_at"}. name is 1-60 characters. The list leaves out revoked devices, oldest first; revoking one twice returns 404.
{
"generated_at": "2026-11-21T12:06:00Z",
"tz": "Europe/Athens",
"settings": {"snooze_steps": [10, 20, 40], "alarm_sentence": "", "low_stock_time": "10:00", "show_names": true},
"days": [{"day": "2026-11-21", "doses": []}, {"day": "2026-11-22", "doses": []}],
"low": []
}
days starts at today in tz; doses and low have the MedicineDay shapes.
DeviceAnswer: {"medicine_uuid", "day", "time", "status": "taken" | "skipped", "at": "2026-11-21T10:04:00Z"}. Answers are applied in order with source: "phone", the time's amount and at as taken_at (now when left out); one that cannot be applied reports ok: false with its code and does not fail the rest: not_found for an unknown or another user's medicine, not_scheduled for a dose that is not planned (or time: null: the phone only answers planned doses). Sending the same batch again changes nothing. A dose already answered in the app or in chat keeps that answer: the phone only offers buttons for doses it believes are open, so such an upload was given against an old copy and reports ok: false with already_answered without changing anything. A malformed body (no answers, more than 100, a bad uuid or status) returns 422 for the whole batch.
What clients work out¶
The server reports pending; clients turn it into what the user sees, from the local clock and snooze_steps:
| State | When (for a pending dose on local day D) |
|---|---|
| Later | D is today and now is before time |
| Due | D is today, time has come, and now is before the late point |
| Overdue | D is today and the late point has passed |
| Missed | D is before today, or a later dose of the same medicine that day has come due |
The late point is until when the time has a window, otherwise time plus the sum of snooze_steps. Overdue and missed doses can still be answered.
Amounts are shown without trailing zeros, 0.5 as "½" and 1.5 as "1½", followed by the unit: "1 tablet", "2 capsules", "½ tablet".
When previous.status is skipped, missed or pending, every surface that shows the dose says so: "Previous dose skipped (08:00)", "Previous dose missed (yesterday 22:00)", "Earlier dose still open (08:00)".
Phone reminders¶
The Android app registers a device (POST /medicines/devices) and hands the key to its native MedicineReminders plugin, which stores it encrypted. Native code then fetches the plan every 15 minutes, when the app opens and just before a reminder rings, and uploads answers given on notifications and widgets.
For one pending dose with time T, steps s1..sn, and its snooze, last_call and critical_at values, the phone alerts as follows:
- Reminder at T.
- With
snooze: up to n more alerts. Alert k+1 comesskminutes after the later of alert k and the last press of Snooze. The last one is a last call whenlast_callis true, otherwise an ordinary reminder. - Without
snoozebut withlast_call: one last call at T plus the sum of the steps. - With
critical_at: a critical call at that time, whatever was snoozed. - Nothing after
until, and nothing once the dose is answered anywhere.
Last and critical calls use the alarm channel and take the screen; reminders use the reminder channel. Doses that alert at the same moment with the same T share one notification.
The plugin methods the UI calls (@loryth-ui/platform, Android only):
| Method | Arguments | Returns |
|---|---|---|
status | — | {configured, deviceId, notifications: "granted" \| "denied" \| "prompt", exactAlarms, fullScreen, batteryUnrestricted, lastSyncAt, lastError} |
configure | {serverUrl, deviceId, deviceKey} | — (stores them, syncs, schedules) |
stop | — | — (forgets the key, cancels alarms, notifications and widget content) |
syncNow | — | — (uploads answers, fetches the plan, reschedules; call after any change to medicines, doses or settings) |
snoozed | — | {doses: [{medicineUuid, day, time, until}]} (until is an ISO instant) |
snooze | {medicineUuid, day, time} | {until} (ISO instant, or null when no further alert is planned) |
openSoundSettings | {kind: "reminder" \| "alarm"} | — (Android's settings page for that notification channel) |
openFullScreenSettings | — | — |
openBatterySettings | — | — |
lastSyncAt is an ISO instant or null; lastError is a short code or null.
Symptom remedies¶
A person can add any of their medicines to a symptom's remedy list. Recording a medicine remedy use creates one dose through DoseLedger and lowers stock in the same transaction. The use carries its time, optional episode and optional outcome (yes, partly, no, unsure). Removing the use removes that dose and restores stock; undoing the dose also removes the linked use. Do not send a second dose answer for the same intake. Scheduled doses and reminders keep their existing rules; a remedy intake is an extra intake with no planned time. Correcting a use's used_at through PATCH moves the same dose's taken_at and local day in the supplied tz (default UTC), through DoseLedger in the same transaction. Its amount and stock stay unchanged. The new time must not be in the future or outside the linked episode's start/end, when present. An as-needed medicine may still be taken without a symptom or episode through PUT /medicines/doses.
The Health contract lists the remedy/use routes, request fields, aggregate outcomes and revision handling. Today reads the medicine dose states and as-needed intakes through GET /medicines/days/{day} with the same tz as its Health day.
Imported historical medicine uses have dose text as strength and amount 1. Their dose day uses UTC. Imported medicines start with zero stock before these historical doses are subtracted, because this model requires a stock count; no as-needed low-count alert is configured. Existing medicines, doses, stock changes, schedules and reminders are preserved by the migration.