2026-05-29 — Medicine row source fix (patient-scoped medicines list)
Version: 1.1 Last Updated: 2026-05-29 14:45:53 Owner: Engineering Status: Approved — runtime-verified, implementation in progress Estimated change size: ~200 LOC backend + ~80 LOC frontend + 3 docs
Pre-implementation evidence (added in v1.1): Bug reproduced via backend/tests/test_medicines_cross_patient_leak_repro.py (2026-05-29 14:55). GET /api/medicines returned both PETA’s and Mum’s medicines when called from a tenant with two patients. The patient-scoped endpoint path proposed below does not currently match any router — it falls through to the SPA catch-all and serves index.html with HTTP 200. See §9 risk register for the implications.
1. Problem
Section titled “1. Problem”On the Medication Schedule page (/medication-schedule), expanding any time slot (e.g. PETA’s 8:00 slot) displays one row for every active medicine in the tenant catalogue, including medicines that exist only because they were added for a different patient in the same tenant (e.g. Mum). The cells inside those rows are correctly empty for the active patient, but the medicine names themselves appear under the wrong patient, which violates carer expectations and the multi-patient isolation principle (“a patient’s medications should never appear under another patient”).
The same defect produces visible cross-patient leakage on:
LogDosepage — manual dose medicine picker shows the full tenant catalogue.Dashboardchart/legend — medicine list is tenant-wide.Historypage — medicine filter dropdown shows the full tenant catalogue.Settings → Medicines— admin list shows the full tenant catalogue.
Why it happens
Section titled “Why it happens”api.medicines.list() (no patient parameter) returns every active row from the tenant-wide medicines table. MedicationSchedule.tsx then iterates over that list to render rows inside each slot expansion. The data layer is patient-correct (patient_scripts, medication_schedule_items, dispensings all have patient_id NOT NULL), but the row source for the picker UIs is not.
Key evidence:
backend/routers/medicines.pyline 34–44:GET /api/medicinesfilters bytenant_idonly.frontend/src/pages/MedicationSchedule.tsxline 1161:api.medicines.list()called with no patient.frontend/src/pages/MedicationSchedule.tsxline 739–741, 880, 1029: rows in each slot mapped from the full tenant catalogue.
2. Goal
Section titled “2. Goal”When the active patient is X, every medicine picker / row matrix / dropdown in the carer-facing UI must display only the medicines that exist for patient X, defined as the union of medicines referenced by patient X’s:
- active
patient_scripts, - active
medication_schedule_items(any group, any time slot), - any
dispensingsever recorded.
The medicines table schema does not change in this fix. (Full per-patient medicines.patient_id migration is deferred — see §11 Out of scope.)
3. New requirement to add
Section titled “3. New requirement to add”Add to docs/01 - BUSINESS REQUIRMENTS/02-REQUIREMENTS.md under §“Medication & dispensing”:
REQ-MED-14 — Patient-scoped medicines list. Every medicine list, picker, row matrix, or dropdown shown to a carer or admin in a patient-scoped page must display only medicines used by the active patient (union of patient’s scripts, schedule items, and dispensing history). The tenant-wide
medicinestable remains the storage model; this is a read-path filter. Admin entry points that explicitly manage the catalogue (e.g. create a new medicine) may opt in to the tenant-wide view with a visible “Tenant catalogue” badge — but no carer-facing flow may display medicines outside the active patient’s usage set.
4. Backend changes
Section titled “4. Backend changes”4.1 New repository (backend/repositories/medicines.py)
Section titled “4.1 New repository (backend/repositories/medicines.py)”Extract existing medicine SQL from backend/routers/medicines.py into a proper repository layer (currently violates the Router → Service → Repository rule). Add a new function:
async def list_medicines_for_patient( conn: AsyncConnection, tenant_id: int, patient_id: int, *, include_inactive: bool = False,) -> list[dict]: """ Return medicines used by the patient, defined as the union of medicines referenced by the patient's active scripts, active schedule items, or any historical dispensings.
Tenant isolation: every sub-query filters by tenant_id. Patient isolation: every sub-query filters by patient_id. """Implementation: single SQL with UNION over the three sources joined to medicines:
SELECT m.* FROM medicines mWHERE m.tenant_id = %s AND (%s OR m.active = TRUE) AND m.id IN ( SELECT medicine_id FROM patient_scripts WHERE tenant_id = %s AND patient_id = %s AND status = 'active' AND medicine_id IS NOT NULL UNION SELECT medicine_id FROM medication_schedule_items WHERE tenant_id = %s AND patient_id = %s AND active = TRUE UNION SELECT medicine_id FROM dispensings WHERE tenant_id = %s AND patient_id = %s )ORDER BY m.name4.2 New service (backend/services/medicines_service.py)
Section titled “4.2 New service (backend/services/medicines_service.py)”Thin orchestration: validate inputs, call repository, return dicts. No business logic beyond that today.
4.3 New router endpoint
Section titled “4.3 New router endpoint”Add to backend/routers/medicines.py:
@router.get("/api/patients/{patient_id}/medicines", response_model=list[Medicine])async def list_medicines_for_patient_route( patient_id: int, include_inactive: bool = Query(False), access: dict = Depends(require_patient_access), db: AsyncConnection = Depends(get_db),): return await medicines_service.list_for_patient( db, access["tenant_id"], patient_id, include_inactive=include_inactive )Module gate stays require_module("medication_dispensing") via existing _med chain in main.py.
4.4 Existing tenant endpoint kept (admin only)
Section titled “4.4 Existing tenant endpoint kept (admin only)”GET /api/medicines is retained for the admin catalogue management screen and for the create flow (so admins can browse the full catalogue to avoid duplicate names). It continues to enforce require_tenant_admin for writes; reads remain require_tenant_member but a follow-up sprint can tighten this to admin-only if you want.
4.5 Migration / data changes
Section titled “4.5 Migration / data changes”None. No DB schema changes in this fix.
5. Frontend changes
Section titled “5. Frontend changes”5.1 frontend/src/lib/api.ts
Section titled “5.1 frontend/src/lib/api.ts”Add patient-scoped helper:
medicines: { list: () => request<Medicine[]>('/medicines'), // existing, admin listForPatient: (patientId: number, includeInactive = false) => request<Medicine[]>( `/patients/${patientId}/medicines${includeInactive ? '?include_inactive=true' : ''}`, ), ... // unchanged}5.2 Switch all carer-facing callers
Section titled “5.2 Switch all carer-facing callers”Replace api.medicines.list() with api.medicines.listForPatient(activePatient.id) and add activePatient?.id to the relevant useCallback / useEffect deps in:
| File | Change |
|---|---|
frontend/src/pages/MedicationSchedule.tsx (line 1161) | swap call; deps already include activePatient?.id |
frontend/src/pages/LogDose.tsx (line 212) | swap call; add activePatient?.id to useEffect deps; reload picker on patient switch |
frontend/src/pages/Dashboard.tsx (uses medicines.list() for chart legend) | swap call; reload on patient switch |
frontend/src/pages/History.tsx (uses medicines.list() for filter dropdown) | swap call; reload on patient switch; also fix the separate dispensings-without-patient leak (REQ-MED-14 row-source rule + add patient_id: activePatient.id to api.dispensings.list) |
frontend/src/pages/Settings.tsx | swap call to listForPatient; add “Caring for: |
5.3 Settings → Medicines admin page
Section titled “5.3 Settings → Medicines admin page”Becomes patient-scoped by default (per user decision 2026-05-29). Admins still need a way to manage the underlying catalogue:
- The page header reads “Medicines for {activePatient.name}”.
- Tenant admins see a read-only “Tenant catalogue” sub-section beneath the per-patient list, populated by
api.medicines.list(), that displays catalogue medicines not yet used by the active patient. From here an admin can “Add to {activePatient.name}” which creates the catalogue medicine (if new) and immediately adds it to the patient’s schedule (or simply marks it as in-scope by inserting a placeholder schedule item — final UX TBD; default behaviour will be “create the medicine and open the Add Schedule Item flow”). - This sub-section is hidden for non-admin carers.
5.4 Empty-state copy
Section titled “5.4 Empty-state copy”MedicationSchedule.tsx slot expansion (line 877): change
“No fixed-time medicines in the catalogue.”
to
“No medicines have been added for {activePatient.name} yet.”
with an admin-only “Add medicine” button that opens the script scan flow or schedule editor.
6. Tests
Section titled “6. Tests”6.1 Backend (backend/tests/)
Section titled “6.1 Backend (backend/tests/)”New file test_medicines_patient_isolation.py:
- Create tenant T, patients A and B.
- Create medicine
M_A_onlyand attach to a script for patient A. - Create medicine
M_B_onlyand attach to a schedule item for patient B. - Create medicine
M_shared, attach a dispensing for both A and B. GET /api/patients/{A}/medicines→ exactly{M_A_only, M_shared}.GET /api/patients/{B}/medicines→ exactly{M_B_only, M_shared}.- Admin and non-admin carer both produce the same list.
- Patient access denied (no
patient_accessrow, non-admin) → 403.
Extend test_dispensings.py:
- Admin calling
GET /api/dispensingswithoutpatient_idno longer returns cross-patient rows (we will tightenappend_dispensing_patient_scope_for_memberin this change — see §10 follow-up).
6.2 Frontend (Vitest)
Section titled “6.2 Frontend (Vitest)”New file frontend/src/pages/__tests__/MedicationSchedule.patientScope.test.tsx:
- Mock
api.medicationGroups.listandapi.medicines.listForPatientso the picker returns only[paracetamol]for patient A. - Render
MedicationSchedulewith active patient A. - Expand the only group.
- Assert the slot panel contains exactly one row (
Paracetamol) — no other medicine names. - Switch active patient to B (mocks now return
[atorvastatin]). - Assert only
Atorvastatinrow visible.
7. Documentation updates
Section titled “7. Documentation updates”| File | Change |
|---|---|
docs/01 - BUSINESS REQUIRMENTS/02-REQUIREMENTS.md | Add REQ-MED-14 (text in §3 above). Bump version to 3.18, update Last Updated. Add changelog row. |
docs/01 - BUSINESS REQUIRMENTS/09-AUTO-DISPENSE-MODULE.md | Replace any mention of “tenant medicines catalogue” with “patient medicines list” in the row-source description. |
docs/01 - BUSINESS REQUIRMENTS/08-PRESCRIPTIONS-MODULE.md | Add cross-reference noting that medicines created by the scan flow remain in the tenant catalogue but appear in the patient list immediately because of REQ-MED-14. |
docs/01 - BUSINESS REQUIRMENTS/32-KNOWN-DEBTS-REGISTER.md | Open or close a debt entry referencing this fix (D-MED-14). |
docs/02 - ARCHITECTURE_DESIGN/01-ARCHITECTURE.md | One paragraph in the data-access section noting that medicines are a tenant catalogue with patient-scoped read views. |
scripts/generate_delivery_register.py re-run | Refresh 31-REQUIREMENTS-CODE-MARKETING-RECONCILIATION.md after REQ-MED-14 ships as Done. |
8. Acceptance criteria
Section titled “8. Acceptance criteria”- On
/medication-schedulewith PETA active, expanding any time slot shows only medicines used by PETA (zero rows for Mum’s medicines). - Switching to Mum reloads the rows and shows only Mum’s medicines.
- Manual
/log-dosepicker shows only the active patient’s medicines. /historymedicine filter shows only the active patient’s medicines./settingsMedicines page is patient-scoped with a “Caring for:” header; admin “Tenant catalogue” sub-section visible only to admins. - New backend test file passes (
test_medicines_patient_isolation.py). - New frontend test passes (
MedicationSchedule.patientScope.test.tsx). ruff check .clean;npm run validate:architectureclean;npm run lint:strictclean.pytest tests/ -xclean.- No DB migration introduced; production data untouched.
9. Risk register
Section titled “9. Risk register”| Risk | Likelihood | Mitigation |
|---|---|---|
| The union query is slower than a flat tenant SELECT | Low | All three child tables have indexes on (tenant_id, patient_id); the medicines.id IN (...) lookup is bounded by the patient’s usage set (typically < 50 rows). Add an explain test if any tenant exceeds 100 medicines. |
| A medicine the patient used to take but is now deactivated disappears from a historical view | Low | The union includes any dispensings ever recorded, so historical views still resolve. include_inactive=true flag added for completeness. |
| A new medicine created via the scan flow does not immediately appear in the patient’s list | Medium | The scan create path inserts both the medicines row and the patient_scripts row in the same transaction → the script-union sub-query picks it up immediately. Verified by extending test_prescriptions.py. |
| Tenant admin cannot add a brand-new medicine type that has never been used by any patient | Medium | Settings → Medicines admin sub-section (“Tenant catalogue”) preserves this entry point. |
| Existing tests assume tenant-wide medicines visibility | Low | Run full test suite; fix any assertion that depended on cross-patient visibility — these are bugs disguised as tests. |
SPA catch-all (main.py:357-362) serves index.html with HTTP 200 for any unmatched API path | Confirmed during verification | Any “does this API exist?” probe in this repo must check Content-Type for application/json — status-code-only checks will misreport. The new GET /api/patients/{patient_id}/medicines route must include an explicit content-type assertion in its test. |
10. Follow-ups (separate PRs, not in this change)
Section titled “10. Follow-ups (separate PRs, not in this change)”- History page dispensings leak:
api.dispensings.list({ date_from, date_to })withoutpatient_idis called for tenant admins and returns cross-patient rows. Fix in this same PR if it stays small; otherwise immediately after. - Auth helper tightening:
append_dispensing_patient_scope_for_memberis a no-op for admins, so the History list endpoint silently returns cross-patient data for admins. Add a server-side default: when nopatient_idis provided, return only the requesting user’s last-active patient (or 400). Out of scope for this PR unless trivial. - Manual-dose quick-picks (
manual_dose_quick_medicine_ids): currently a tenant-level array; should become per-patient. Tracked separately.
11. Out of scope
Section titled “11. Out of scope”- Adding
patient_idto themedicinestable. The full schema migration was discussed earlier (“Option B”) and is the correct long-term answer. It is deferred because:- The read-path filter in this fix removes 100% of the visible carer leakage.
- The schema migration has production-data risk that requires a separate plan, dry-run on a copy of prod, and a maintenance window.
- Changing tier limits on
max_medicines. - Anything in the Shopping module’s pharmacy lists (already patient-scoped at the list level; medicine references are name-only, not FK).
- Anything in
services/export_v2.py(export is admin-only and explicitly tenant-wide).
12. Rollback plan
Section titled “12. Rollback plan”This change is purely additive at the API level (new endpoint, no removal) and switches the read path of five frontend pages. To roll back:
- Revert the frontend commits (the new endpoint can stay; nothing else references it).
- Optionally revert the new backend endpoint.
- No DB rollback required.
Time-to-rollback: < 10 minutes.
13. Execution order
Section titled “13. Execution order”- Plan reviewed and approved.
- Add REQ-MED-14 to
02-REQUIREMENTS.md. - Create
backend/repositories/medicines.py,backend/services/medicines_service.py. - Add
GET /api/patients/{patient_id}/medicinestobackend/routers/medicines.py. - Write
test_medicines_patient_isolation.py, runpytest. - Update
frontend/src/lib/api.ts. - Update the five frontend pages.
- Write Vitest, run
npm run test. - Manual smoke test: PETA / Mum on Schedule, LogDose, History, Settings.
- Update remaining docs (08, 09, 32, 01-ARCHITECTURE).
- Run delivery register generator.
- Commit.
14. Approval
Section titled “14. Approval”This plan is not yet implemented. Awaiting confirmation from the user to proceed.
Reply “approved” to execute steps 2–12 in order, or request edits to this plan.