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.
| Term | Meaning |
|---|
| Medication group | A named, time-anchored set of medications a patient takes together — e.g. “Morning pills (08:00)”. Belongs to a patient. |
| Schedule item | A single medicine + dose within a medication group — e.g. “Metformin 500mg, 2 tablets, with food”. |
| Auto-dispense | Recording one or more dispensings from the schedule view with minimal interaction. |
| Group dispense | A single confirmed carer action that creates one dispensings row per undispensed item in a group, all sharing a dispense_batch_id. |
| Dispensed today | A schedule item for which a dispensings row exists with date = today and scheduled_item_id = this item for this patient. |
| Overdue | A scheduled item whose group scheduled_time was more than 30 minutes ago and which has not been dispensed today. |
| Missed dose | A scheduled item that was not dispensed on a given day. Surfaced retrospectively; never auto-created as a dispensings row. |
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.
| Field | Type | Notes |
|---|
id | SERIAL PK | |
tenant_id | INTEGER FK → tenants | Isolation. |
patient_id | INTEGER FK → patients ON DELETE CASCADE | |
name | TEXT | Carer-defined label: “Morning pills”, “Lunchtime”, “Evening”, “Bedtime”. |
scheduled_time | TEXT | 24h time string e.g. "08:00". Used for ordering and overdue detection. |
sort_order | INTEGER DEFAULT 0 | Display order when multiple groups exist. |
active | BOOLEAN DEFAULT TRUE | Inactive groups hidden from dispense view; history retained. |
created_by | INTEGER FK → users | |
created_at | TIMESTAMPTZ DEFAULT NOW() | |
updated_at | TIMESTAMPTZ DEFAULT NOW() | |
Indexes: (tenant_id, patient_id), (patient_id, active).
| Field | Type | Notes |
|---|
id | SERIAL PK | |
group_id | INTEGER FK → medication_groups ON DELETE CASCADE | |
tenant_id | INTEGER FK → tenants | For query convenience. |
patient_id | INTEGER FK → patients | For query convenience. |
medicine_id | INTEGER FK → medicines | Medicine from tenant formulary. |
script_id | INTEGER FK → patient_scripts, nullable | If set, dispensing this item deducts from the linked script’s stock. |
dose_amount | DOUBLE PRECISION | Quantity per dose (e.g. 2.0 tablets, 5.0 ml). |
unit | TEXT | e.g. "tablet", "ml". Defaults to linked medicine’s unit. |
instructions | TEXT, nullable | e.g. “with food”, “sublingual”. Shown on dispense card. |
sort_order | INTEGER DEFAULT 0 | Order within the group. |
active | BOOLEAN DEFAULT TRUE | Inactive items hidden; history retained. |
created_by | INTEGER FK → users | |
created_at | TIMESTAMPTZ DEFAULT NOW() | |
updated_at | TIMESTAMPTZ DEFAULT NOW() | |
Indexes: (group_id), (patient_id, active), (medicine_id).
Applied via a separate migration file — not by modifying schema.sql.
| Column | Type | Notes |
|---|
patient_id | INTEGER FK → patients, nullable | Patient association. Required for stock deduction and auto-dispense matching. NULL for legacy rows. |
script_id | INTEGER FK → patient_scripts, nullable | Links to script for stock deduction. |
scheduled_item_id | INTEGER FK → medication_schedule_items, nullable | Set when the dispensing originated from the auto-dispense view. NULL for manual doses. |
dispense_batch_id | INTEGER, nullable | Shared 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.
| ID | Requirement |
|---|
| REQ-AD-SCHED-01 | A tenant admin or carer with carer patient access may create, edit, and deactivate medication groups and schedule items. |
| REQ-AD-SCHED-02 | A patient may have multiple medication groups. No hard limit, though UI must not degrade on mobile with many groups. |
| REQ-AD-SCHED-03 | A medication group requires a name and a scheduled time. Both are editable after creation. |
| REQ-AD-SCHED-04 | A group with zero active items is not shown in the dispense view. |
| REQ-AD-SCHED-05 | A 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-06 | A schedule item may optionally link to a patient_script. When linked, dispensing the item deducts from that script’s stock. |
| REQ-AD-SCHED-07 | Deactivating a schedule item preserves all historical dispensings linked to it. The item no longer appears in the dispense view. |
| REQ-AD-SCHED-08 | Setting 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. |
| ID | Requirement |
|---|
| REQ-AD-VIEW-01 | The 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-02 | Groups are displayed sorted by scheduled_time ascending, then sort_order. |
| REQ-AD-VIEW-03 | Each group card shows: group name, scheduled time, and stacked schedule items. Each item shows: medicine name, dose amount, unit, and instructions. |
| REQ-AD-VIEW-04 | Each schedule item shows one of three states for today: Pending, Dispensed, or Overdue. |
| REQ-AD-VIEW-05 | Overdue 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-06 | Overdue items use amber-* warning colours. A fully-dispensed overdue group reverts to a neutral/success state. |
| REQ-AD-VIEW-07 | After any dispense action, the affected items transition to Dispensed state without a full page reload. Optimistic UI with revert on failure. |
| REQ-AD-VIEW-08 | The auto-dispense view is accessible from the Dashboard and from the Medications section within one tap of either. |
| ID | Requirement |
|---|
| REQ-AD-SINGLE-01 | A carer may tap any Pending or Overdue schedule item to mark it as dispensed. |
| REQ-AD-SINGLE-02 | Tapping 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-03 | On 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-04 | A dispensed item shows a checkmark and the time and carer name. |
| REQ-AD-SINGLE-05 | An already-dispensed item may not be re-tapped for the same day. Corrections use the standard dispense history flow. |
| REQ-AD-SINGLE-06 | If the item has a linked script_id, stock on hand for that script is recalculated (derived) after the dispense. |
| ID | Requirement |
|---|
| REQ-AD-GROUP-01 | Each group card shows a “Dispense all” button when one or more items are Pending or Overdue. |
| REQ-AD-GROUP-02 | When all items in a group are already dispensed today, the button is hidden and replaced with an “All dispensed” indicator. |
| REQ-AD-GROUP-03 | Tapping 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-04 | On confirmation, one dispensings row is created per undispensed item, all sharing a new dispense_batch_id. Already-dispensed items are excluded. |
| REQ-AD-GROUP-05 | Batch creation is a single database transaction. If any insert fails, all inserts are rolled back. No partial group dispenses are persisted. |
| REQ-AD-GROUP-06 | A 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-07 | In 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. |
When any dispense path creates the first-ever dose for a patient + medicine name, the product must:
| ID | Requirement |
|---|
| REQ-AD-FDR-01 | Return first_dose_reaction_prompt (single dispense / manual log) or first_dose_reaction_prompts[] (group dispense) in the API response when triggered. |
| REQ-AD-FDR-02 | Show 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-03 | Raise 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-04 | After No, never prompt again for that patient + medicine (stored in patient_medicine_first_dose_checks). |
| REQ-AD-FDR-05 | On 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-06 | Show 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-07 | Record 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}. |
| ID | Requirement |
|---|
| REQ-AD-MISSED-01 | Scheduled 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-02 | The dispense history view supports filtering to show days where any scheduled item has no corresponding dispensings row. |
| REQ-AD-MISSED-03 | Missed 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-04 | A 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.
| Method | Path | Purpose |
|---|
GET | /api/patients/{id}/medication-groups | List active groups with items. |
POST | /api/patients/{id}/medication-groups | Create 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}/items | Add 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/reorder | Batch reorder groups. Body: { group_ids: [3, 1, 2] }. Atomic. |
POST | /api/patients/{id}/medication-groups/{group_id}/items/reorder | Batch 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}/dispense | Record a single item dispense. Body: { scheduled_item_id, time, date }. |
POST | /api/patients/{id}/dispense-group | Record 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). |
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.
| ID | Requirement |
|---|
| REQ-AD-MGMT-01 | The 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-02 | Groups zone renders each group as a card: name, scheduled time, and stacked member medicines. |
| REQ-AD-MGMT-03 | Unassigned medicines zone renders each medicine as a row: name, unit, and an indicator if it has an active linked script. |
| REQ-AD-MGMT-04 | When all medicines are assigned, the Unassigned zone is hidden with a contextual hint: “All medicines are in a group.” |
| REQ-AD-MGMT-05 | When no groups exist, the Groups zone is replaced with a prominent empty state and a single primary action: “Create first group”. |
| REQ-AD-MGMT-06 | On lg: and above, Groups and Unassigned zones may display side-by-side. Below lg:, they stack vertically (Groups above Unassigned). |
| ID | Requirement |
|---|
| REQ-AD-MGMT-07 | Long-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-08 | On desktop, a checkbox is revealed on hover for each unassigned medicine row. Clicking it activates multi-select mode. |
| REQ-AD-MGMT-09 | In multi-select mode, tapping any medicine row toggles its selection. |
| REQ-AD-MGMT-10 | While 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-13 | Exiting multi-select mode removes all checkboxes and returns to default state. |
| REQ-AD-MGMT-14 | Multi-select is limited to the Unassigned zone. Medicines inside a group are managed from within the group card. |
| ID | Requirement |
|---|
| REQ-AD-MGMT-15 | Each 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-16 | Within 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-17 | Each 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-18 | Tapping 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. |
| ID | Requirement |
|---|
| REQ-AD-MGMT-19 | Drag-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-20 | Dragging a medicine item via its handle reorders it within its group, updating sort_order on drop. |
| REQ-AD-MGMT-21 | Use 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-22 | While dragging, the item renders as a floating ghost chip. The drop target is indicated by a visual gap in the list. |
| REQ-AD-MGMT-23 | Dragging an item from one group card and dropping it into another is supported in V1. |
| REQ-AD-MGMT-24 | Group cards themselves may be reordered by dragging the card header, updating medication_groups.sort_order. |
| REQ-AD-MGMT-25 | Sort 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-26 | A 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. |
| ID | Requirement |
|---|
| REQ-AD-MGMT-27 | The drag handle (≡) must be a minimum 44×44px touch target. |
| REQ-AD-MGMT-28 | The multi-select action bar must clear env(safe-area-inset-bottom) to avoid being hidden by the iOS home bar. |
| REQ-AD-MGMT-29 | Scheduled 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-30 | Swipe-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-31 | During 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. |
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.
| ID | Requirement |
|---|
| REQ-AD-MANUAL-01 | The 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-02 | A 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-03 | A 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-04 | All 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-05 | Stock 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-06 | The 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-07 | The 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-08 | The 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-09 | No 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. |
| ID | Requirement |
|---|
| REQ-AD-DASH-01 | The 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-02 | The section shows a count summary: e.g. “3 of 5 doses given today” with a progress indicator. |
| REQ-AD-DASH-03 | If any item is Overdue, the section header uses amber-* warning styling and shows the overdue count. |
| REQ-AD-DASH-04 | The section links directly to the auto-dispense view within one tap. |
| REQ-AD-DASH-05 | Missed 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).