Skip to content

09 — Auto-Dispense & Medication Schedule Module

Stack and requirements for this area: 02-REQUIREMENTS.md §3.3, §7.4 (medication schedule / batch dispense) and 01-ARCHITECTURE.md.

Status: Implemented in this repository. Primary UI route: /medication-schedule (nav: Scheduled Doses). /auto-dispense redirects there. The screen combines week calendar, medication group management (with unassigned medicines), and dispense actions — broader than the “cards for today only” mock in early sections of this doc, but uses the same dispense-view and dispense APIs. Module slug: medication_dispensing (extends existing module; no new slug required). Depends on: medication_dispensing active. Linking schedule items to patient_scripts for stock requires prescription_management; otherwise dispense rows omit script_id. Related code: backend/routers/medication_groups.py, frontend/src/pages/MedicationSchedule.tsx, Dashboard.tsx (Medications today).

  • Multi-select bulk add (long-press / hover checkbox) may not match §11.2 exactly — verify MedicationSchedule.tsx before assuming parity.
  • Dedicated /dispense page: not separate; schedule + dispense share /medication-schedule.

The Auto-Dispense feature gives carers a fast, low-friction workflow for recording that a patient’s scheduled medications have been given. Rather than navigating the full log-dose form for each medicine, the carer sees today’s medication schedule grouped by time of day and can record an entire group with a single confirmed tap.

The manual log-dose flow is not replaced by this feature. Both are permanent, equally accessible, first-class features. See Section 12 for the non-negotiable coexistence requirements that govern this.

Every auto-dispense action writes to the existing dispensings table, preserving the full audit trail. Stock on hand (from linked scripts) decrements automatically. Missed or overdue doses are surfaced so nothing is overlooked.


TermMeaning
Medication groupA named, time-anchored set of medications a patient takes together — e.g. “Morning pills (08:00)”. Belongs to a patient.
Schedule itemA single medicine + dose within a medication group — e.g. “Metformin 500mg, 2 tablets, with food”.
Auto-dispenseRecording one or more dispensings from the schedule view with minimal interaction.
Group dispenseA single confirmed carer action that creates one dispensings row per undispensed item in a group, all sharing a dispense_batch_id.
Dispensed todayA schedule item for which a dispensings row exists with date = today and scheduled_item_id = this item for this patient.
OverdueA scheduled item whose group scheduled_time was more than 30 minutes ago and which has not been dispensed today.
Missed doseA scheduled item that was not dispensed on a given day. Surfaced retrospectively; never auto-created as a dispensings row.

3. Core design principle — manual and auto coexist

Section titled “3. Core design principle — manual and auto coexist”

This principle takes precedence over all convenience and automation design decisions.

The manual log-dose flow is not a legacy fallback. It is the audit-grade record of what actually happened. The auto-dispense flow is a convenience mechanism that creates those records faster. No automated process, background job, or system inference may ever create a dispensings row on behalf of a carer. Every dispense record — regardless of how it was initiated — must trace back to an explicit, confirmed human action.


FieldTypeNotes
idSERIAL PK
tenant_idINTEGER FK → tenantsIsolation.
patient_idINTEGER FK → patients ON DELETE CASCADE
nameTEXTCarer-defined label: “Morning pills”, “Lunchtime”, “Evening”, “Bedtime”.
scheduled_timeTEXT24h time string e.g. "08:00". Used for ordering and overdue detection.
sort_orderINTEGER DEFAULT 0Display order when multiple groups exist.
activeBOOLEAN DEFAULT TRUEInactive groups hidden from dispense view; history retained.
created_byINTEGER FK → users
created_atTIMESTAMPTZ DEFAULT NOW()
updated_atTIMESTAMPTZ DEFAULT NOW()

Indexes: (tenant_id, patient_id), (patient_id, active).


FieldTypeNotes
idSERIAL PK
group_idINTEGER FK → medication_groups ON DELETE CASCADE
tenant_idINTEGER FK → tenantsFor query convenience.
patient_idINTEGER FK → patientsFor query convenience.
medicine_idINTEGER FK → medicinesMedicine from tenant formulary.
script_idINTEGER FK → patient_scripts, nullableIf set, dispensing this item deducts from the linked script’s stock.
dose_amountDOUBLE PRECISIONQuantity per dose (e.g. 2.0 tablets, 5.0 ml).
unitTEXTe.g. "tablet", "ml". Defaults to linked medicine’s unit.
instructionsTEXT, nullablee.g. “with food”, “sublingual”. Shown on dispense card.
sort_orderINTEGER DEFAULT 0Order within the group.
activeBOOLEAN DEFAULT TRUEInactive items hidden; history retained.
created_byINTEGER FK → users
created_atTIMESTAMPTZ DEFAULT NOW()
updated_atTIMESTAMPTZ DEFAULT NOW()

Indexes: (group_id), (patient_id, active), (medicine_id).


Applied via a separate migration file — not by modifying schema.sql.

ColumnTypeNotes
patient_idINTEGER FK → patients, nullablePatient association. Required for stock deduction and auto-dispense matching. NULL for legacy rows.
script_idINTEGER FK → patient_scripts, nullableLinks to script for stock deduction.
scheduled_item_idINTEGER FK → medication_schedule_items, nullableSet when the dispensing originated from the auto-dispense view. NULL for manual doses.
dispense_batch_idINTEGER, nullableShared across all dispensings from a single group-dispense action. NULL for individual or manual doses.

dispense_batch_id is a plain auto-increment integer. No separate dispense_batches table is required for V1 — batch metadata (who, when, which group) is derivable from the constituent rows.


5. Medication schedule management requirements

Section titled “5. Medication schedule management requirements”
IDRequirement
REQ-AD-SCHED-01A tenant admin or carer with carer patient access may create, edit, and deactivate medication groups and schedule items.
REQ-AD-SCHED-02A patient may have multiple medication groups. No hard limit, though UI must not degrade on mobile with many groups.
REQ-AD-SCHED-03A medication group requires a name and a scheduled time. Both are editable after creation.
REQ-AD-SCHED-04A group with zero active items is not shown in the dispense view.
REQ-AD-SCHED-05A schedule item links to a medicine from the tenant formulary. dose_amount and unit default to the medicine’s unit but are overridable per item.
REQ-AD-SCHED-06A schedule item may optionally link to a patient_script. When linked, dispensing the item deducts from that script’s stock.
REQ-AD-SCHED-07Deactivating a schedule item preserves all historical dispensings linked to it. The item no longer appears in the dispense view.
REQ-AD-SCHED-08Setting up medication groups is entirely optional. The app must be fully functional for medication tracking using only the manual log-dose flow. No prompts, warnings, or empty-state messages should imply a carer is doing something wrong by not using groups.

IDRequirement
REQ-AD-VIEW-01The auto-dispense view is patient-scoped. It shows today’s active medication groups for the active patient. carer and observer roles may view; only carer role may trigger dispensing.
REQ-AD-VIEW-02Groups are displayed sorted by scheduled_time ascending, then sort_order.
REQ-AD-VIEW-03Each group card shows: group name, scheduled time, and stacked schedule items. Each item shows: medicine name, dose amount, unit, and instructions.
REQ-AD-VIEW-04Each schedule item shows one of three states for today: Pending, Dispensed, or Overdue.
REQ-AD-VIEW-05Overdue is triggered when current time is more than 30 minutes past the group’s scheduled_time and the item is not dispensed today.
REQ-AD-VIEW-06Overdue items use amber-* warning colours. A fully-dispensed overdue group reverts to a neutral/success state.
REQ-AD-VIEW-07After any dispense action, the affected items transition to Dispensed state without a full page reload. Optimistic UI with revert on failure.
REQ-AD-VIEW-08The auto-dispense view is accessible from the Dashboard and from the Medications section within one tap of either.

IDRequirement
REQ-AD-SINGLE-01A carer may tap any Pending or Overdue schedule item to mark it as dispensed.
REQ-AD-SINGLE-02Tapping a pending item presents a minimal inline confirmation (not a full modal): medicine name, dose, and dispense time (defaulting to now, editable). One confirm tap completes the action.
REQ-AD-SINGLE-03On confirmation: a dispensings row is created with date = today, time = confirmed time, medicine_id, volume = dose_amount, patient_id, scheduled_item_id, dispense_batch_id = null.
REQ-AD-SINGLE-04A dispensed item shows a checkmark and the time and carer name.
REQ-AD-SINGLE-05An already-dispensed item may not be re-tapped for the same day. Corrections use the standard dispense history flow.
REQ-AD-SINGLE-06If the item has a linked script_id, stock on hand for that script is recalculated (derived) after the dispense.

IDRequirement
REQ-AD-GROUP-01Each group card shows a “Dispense all” button when one or more items are Pending or Overdue.
REQ-AD-GROUP-02When all items in a group are already dispensed today, the button is hidden and replaced with an “All dispensed” indicator.
REQ-AD-GROUP-03Tapping the group button presents a group confirmation: group name, list of items about to be dispensed with doses, and a single editable dispense time applied to all items. One confirm tap completes the action.
REQ-AD-GROUP-04On confirmation, one dispensings row is created per undispensed item, all sharing a new dispense_batch_id. Already-dispensed items are excluded.
REQ-AD-GROUP-05Batch creation is a single database transaction. If any insert fails, all inserts are rolled back. No partial group dispenses are persisted.
REQ-AD-GROUP-06A group dispense batch is undoable by a tenant admin within the same calendar day, provided none of the batch’s rows have been individually edited since creation. Undo deletes all dispensings rows sharing that dispense_batch_id.
REQ-AD-GROUP-07In the dispense history view, a group batch is identifiable as such: “Morning pills — group dispense, 3 items, 08:14 by Sarah”. Individual rows within the batch are also independently visible.

8.1 First-dose adverse reaction check (REQ-MED-16)

Section titled “8.1 First-dose adverse reaction check (REQ-MED-16)”

When any dispense path creates the first-ever dose for a patient + medicine name, the product must:

IDRequirement
REQ-AD-FDR-01Return first_dose_reaction_prompt (single dispense / manual log) or first_dose_reaction_prompts[] (group dispense) in the API response when triggered.
REQ-AD-FDR-02Show FirstDoseReactionModal immediately after dispense with: “Has there been any observable adverse reaction after this medicine was given?” — No / Yes (+ note). Ask me later leaves the shared care alert open.
REQ-AD-FDR-03Raise first_dose_reaction care alert for the whole team; alert cannot be resolved with generic Done — must use structured response (POST /api/first-dose-reactions/{id}/respond).
REQ-AD-FDR-04After No, never prompt again for that patient + medicine (stored in patient_medicine_first_dose_checks).
REQ-AD-FDR-05On Yes, resolve first_dose_reaction and raise urgent adverse_reaction_reported alert for the whole team (same notification channel as first-dose).
REQ-AD-FDR-06Show AdverseReactionDetailModal after save: exact reaction note, Seek medical advice., clinical Key Contacts (GP, Specialist, Palliative Specialist, Nurse, Pharmacist) with Call (tel:) / Email (mailto:) when phone or email is present.
REQ-AD-FDR-07Record observed reactions in Dispensing and Adverse Reactions History Log (GET /api/patients/{id}/adverse-reaction-log); merged timeline on /history; deep link from alert: /history?patientId={id}&adverseReaction={check_id}.

IDRequirement
REQ-AD-MISSED-01Scheduled items with no dispensings row for a given day are treated as missed doses. They are never auto-created as dispensings rows.
REQ-AD-MISSED-02The dispense history view supports filtering to show days where any scheduled item has no corresponding dispensings row.
REQ-AD-MISSED-03Missed doses from the previous day are surfaced on the Dashboard the following morning as an informational item using blue-* or neutral styling. This does not block the carer and does not escalate to a warning.
REQ-AD-MISSED-04A missed dose from a prior day may not be backdated via the auto-dispense view. Late recording of a dose uses the manual log-dose flow, which accepts any date and time.

All endpoints require medication_dispensing module and patient access checks.

MethodPathPurpose
GET/api/patients/{id}/medication-groupsList active groups with items.
POST/api/patients/{id}/medication-groupsCreate a group.
PATCH/api/patients/{id}/medication-groups/{group_id}Edit name, time, sort order, active.
DELETE/api/patients/{id}/medication-groups/{group_id}Deactivate group.
POST/api/patients/{id}/medication-groups/{group_id}/itemsAdd a schedule item.
PATCH/api/patients/{id}/medication-groups/{group_id}/items/{item_id}Edit dose, instructions, script link, active.
DELETE/api/patients/{id}/medication-groups/{group_id}/items/{item_id}Deactivate item.
POST/api/patients/{id}/medication-groups/reorderBatch reorder groups. Body: { group_ids: [3, 1, 2] }. Atomic.
POST/api/patients/{id}/medication-groups/{group_id}/items/reorderBatch reorder items within a group. Body: { item_ids: [5, 2, 8] }. Atomic.
GET/api/patients/{id}/dispense-view?date=Today’s groups with per-item dispensed state (Pending / Dispensed / Overdue). Core view endpoint.
POST/api/patients/{id}/dispenseRecord a single item dispense. Body: { scheduled_item_id, time, date }.
POST/api/patients/{id}/dispense-groupRecord a group dispense. Body: { group_id, time, date }. Returns dispense_batch_id.
DELETE/api/patients/{id}/dispense-batch/{batch_id}Undo group dispense (admin, same-day, unedited rows only).

11.0 Patient-scoped medicine list (REQ-MED-14)

Section titled “11.0 Patient-scoped medicine list (REQ-MED-14)”

The medicine list that populates the row matrix inside each time-slot card, the “Unassigned medicines” zone, and the inline pickers must be patient-scoped — only medicines actually used by the active patient (union of active scripts, active schedule items, and any dispensings) are returned. Source: GET /api/patients/{patient_id}/medicines.

The legacy tenant-wide GET /api/medicines must never be called from the carer-facing Schedule page. Doing so re-introduces the cross-patient catalogue leak that was reproduced 2026-05-29 (carer on PETA’s schedule could see Mum’s medicines listed in every time slot). Regression tests live at backend/tests/test_medicines_patient_isolation.py and frontend/src/test/components/MedicationSchedule.test.tsx (calls listForPatient with active patient id, never the tenant-wide list).

Empty-state copy on the Schedule screen reflects the patient scope (“No fixed-time medicines on file for this patient yet.”), not the tenant catalogue.


IDRequirement
REQ-AD-MGMT-01The schedule management screen has two visual zones: Groups (above) and Unassigned medicines (below). A medicine is “unassigned” if it belongs to no active group for this patient.
REQ-AD-MGMT-02Groups zone renders each group as a card: name, scheduled time, and stacked member medicines.
REQ-AD-MGMT-03Unassigned medicines zone renders each medicine as a row: name, unit, and an indicator if it has an active linked script.
REQ-AD-MGMT-04When all medicines are assigned, the Unassigned zone is hidden with a contextual hint: “All medicines are in a group.”
REQ-AD-MGMT-05When no groups exist, the Groups zone is replaced with a prominent empty state and a single primary action: “Create first group”.
REQ-AD-MGMT-06On lg: and above, Groups and Unassigned zones may display side-by-side. Below lg:, they stack vertically (Groups above Unassigned).

IDRequirement
REQ-AD-MGMT-07Long-pressing any medicine in the Unassigned zone (500ms hold) activates multi-select mode. All unassigned rows show checkboxes; the long-pressed item is pre-selected.
REQ-AD-MGMT-08On desktop, a checkbox is revealed on hover for each unassigned medicine row. Clicking it activates multi-select mode.
REQ-AD-MGMT-09In multi-select mode, tapping any medicine row toggles its selection.
REQ-AD-MGMT-10While one or more items are selected, a persistent action bar slides up from the bottom of the screen (mobile) or appears as a toolbar (desktop). The bar shows: count of selected items, “Add to existing group” (if groups exist), “Create new group”, and “Cancel”. The bar must clear env(safe-area-inset-bottom) on mobile.
REQ-AD-MGMT-11“Create new group” presents a minimal form: group name (required) and scheduled time (required). Confirming creates the group and moves selected medicines in as schedule items with their default units.
REQ-AD-MGMT-12“Add to existing group” presents a bottom sheet (mobile) or dropdown (desktop) listing existing groups by name and time.
REQ-AD-MGMT-13Exiting multi-select mode removes all checkboxes and returns to default state.
REQ-AD-MGMT-14Multi-select is limited to the Unassigned zone. Medicines inside a group are managed from within the group card.

IDRequirement
REQ-AD-MGMT-15Each group card has an overflow/edit menu providing: “Edit group” (rename, change time), “Add medicine to group” (opens medicine picker), and “Delete group” (moves members to Unassigned; confirmation required).
REQ-AD-MGMT-16Within a group card, each medicine item has a drag handle (≡ icon) on the trailing edge. This is the only target that initiates a drag. Touching anywhere else does not drag.
REQ-AD-MGMT-17Each medicine item in a group has a remove action (× button or swipe-to-remove on mobile) that moves it back to Unassigned.
REQ-AD-MGMT-18Tapping a medicine item (not the handle, not remove) opens an inline edit for that item’s dose_amount and instructions, scoped to this item in this group only.

IDRequirement
REQ-AD-MGMT-19Drag-and-drop reordering is implemented using @dnd-kit/sortable (@dnd-kit/core + @dnd-kit/sortable + @dnd-kit/utilities). Do not use react-beautiful-dnd (unmaintained, known touch issues) or HTML5 drag-and-drop (does not work on mobile).
REQ-AD-MGMT-20Dragging a medicine item via its handle reorders it within its group, updating sort_order on drop.
REQ-AD-MGMT-21Use PointerSensor with default activation constraints (250ms delay, 5px tolerance for touch). This prevents accidental drags during normal page scroll and does not need to be overridden.
REQ-AD-MGMT-22While dragging, the item renders as a floating ghost chip. The drop target is indicated by a visual gap in the list.
REQ-AD-MGMT-23Dragging an item from one group card and dropping it into another is supported in V1.
REQ-AD-MGMT-24Group cards themselves may be reordered by dragging the card header, updating medication_groups.sort_order.
REQ-AD-MGMT-25Sort order is persisted via a batch reorder endpoint — the entire new order is sent as an array of IDs in a single POST .../reorder request on drop. Individual per-item sort updates are not used (avoids race conditions on rapid drag). Optimistic UI: visual order updates immediately; reverts on failure with an error toast.
REQ-AD-MGMT-26A keyboard-accessible sort alternative must exist using @dnd-kit’s keyboard sensor: each drag-handle element exposes “Move up” / “Move down” accessible button actions for screen reader users.

IDRequirement
REQ-AD-MGMT-27The drag handle (≡) must be a minimum 44×44px touch target.
REQ-AD-MGMT-28The multi-select action bar must clear env(safe-area-inset-bottom) to avoid being hidden by the iOS home bar.
REQ-AD-MGMT-29Scheduled time input uses native <input type="time"> on mobile for the OS time picker. A styled custom picker may be used on desktop.
REQ-AD-MGMT-30Swipe-to-remove (swipe left on a group item) is a supported gesture on mobile. A destructive “Remove” label is revealed on partial swipe; full swipe or tap confirms.
REQ-AD-MGMT-31During an active drag, page scroll is disabled. Scroll is re-enabled on drag end. This is handled by @dnd-kit natively but must be verified on iOS Safari.

12. Manual dispense coexistence requirements (non-negotiable)

Section titled “12. Manual dispense coexistence requirements (non-negotiable)”

These requirements take precedence over any auto-dispense convenience design. The manual log-dose flow is a permanent first-class feature that may never be demoted, hidden, or treated as a fallback.

IDRequirement
REQ-AD-MANUAL-01The manual log-dose entry point must remain in the primary navigation at the same level it occupies today, regardless of whether medication groups are configured.
REQ-AD-MANUAL-02A tenant with medication_dispensing active but zero medication groups must have full, unimpaired access to all medication tracking features via the manual flow.
REQ-AD-MANUAL-03A carer may use manual logging and auto-dispense interchangeably on the same day for the same patient and medicines. No mode-switching; both paths are always available simultaneously.
REQ-AD-MANUAL-04All dashboard metrics that reference dispense counts must aggregate all dispensings rows for the patient and date regardless of origin. No separate counters by method.
REQ-AD-MANUAL-05Stock deduction from a linked script must function identically for manually logged and auto-dispensed doses. The manual log-dose form must present the same script-association prompt when the selected medicine has an active linked script.
REQ-AD-MANUAL-06The auto-dispense view must attempt to resolve same-day manual dispensings against scheduled items. If a dispensings row exists today for the same patient_id and medicine_id and the dispense time falls within 60 minutes of the group’s scheduled_time, the scheduled item displays as dispensed with a visual indicator distinguishing “auto-dispensed” from “manually logged”.
REQ-AD-MANUAL-07The resolve logic in REQ-AD-MANUAL-06 is display-only. It does not retroactively set scheduled_item_id on any dispensings row. The original manual record is never modified.
REQ-AD-MANUAL-08The history and audit views show all dispensings in a single unified list with origin indicated (auto-dispensed / group-dispensed / manual / batch ID). No separate history tabs per method.
REQ-AD-MANUAL-09No automated process, background job, or system inference may create a dispensings row on behalf of a carer. Every dispense record must trace to an explicit, confirmed human action.

IDRequirement
REQ-AD-DASH-01The Dashboard shows a “Medications today” section for the active patient when medication_dispensing is active and at least one medication group exists.
REQ-AD-DASH-02The section shows a count summary: e.g. “3 of 5 doses given today” with a progress indicator.
REQ-AD-DASH-03If any item is Overdue, the section header uses amber-* warning styling and shows the overdue count.
REQ-AD-DASH-04The section links directly to the auto-dispense view within one tap.
REQ-AD-DASH-05Missed dose notifications from the previous day appear within the medications section, not as a separate dashboard card.

  • PRN (as-needed) medication scheduling — all schedule items are regular, time-based. Ad hoc doses use the manual log-dose flow.
  • Dose rounding or half-tablet logic.
  • Drug interaction checking or clinical decision support.
  • Pharmacy integration or electronic dispensing records.
  • Carer shift-aware filtering of the dispense view — revisit when Phase 4 cover requests are implemented.
  • Configurable overdue threshold (fixed at 30 minutes for V1).