08 — Prescription Management Module
Status: Implemented in this repository (API + web UI + LM Studio pipeline). Treat this document as the behavioural spec; where the app differs (e.g. extra endpoints or fields), 02-REQUIREMENTS.md §3.4, §7.5 and the code win. Stack and requirements for this area: 01-ARCHITECTURE.md and 02-REQUIREMENTS.md §3.4, §7.5.
Module slug:
prescription_managementDepends on:medication_dispensingmust be active for the tenant. Related code:backend/routers/scripts.py,backend/services/lmstudio.py,backend/services/images.py,frontend/src/pages/Scripts.tsx,ScriptDetail.tsx, scan flow components underfrontend/src/components/.
Scan queue (Phase B6 — done 2026-06-02): Jobs live in PostgreSQL (
scan_jobs, V075).services/scan_queue.pyis a facade overscan_queue_pg.py(enqueue,claim_job,complete_job,fail_job).workers/scan_worker.pyclaims withFOR UPDATE SKIP LOCKED; SSE usesLISTEN/pg_notify. Redis is not used for scan durability or result delivery. See 04-ROADMAP B6 and 01-ARCHITECTURE.md § Prescription scanning.
Implementation notes (code vs original spec text)
Section titled “Implementation notes (code vs original spec text)”| Topic | In code |
|---|---|
| Stock formula | With manual baseline (last_physical_count + last_physical_count_at, V112): on hand = baseline + pharmacy fills since audit − dispensings since audit. Without baseline: legacy fills×qty + stock_adjustment − lifetime dispensings. PATCH pills_available sets baseline via clock_timestamp(). POST …/fills sets baseline to prior on-hand + quantity_added (new pack not reduced by historical dose log). stock_count_needed (V114): admin-only banner on Home/Medications when dose log > 0 and on-hand ≤ 0; prescription_stock_count in Care alerts (bell); tap → edit with How many doses do you have available? highlighted; row auto-clears when a positive count is saved (inline sync). Mark done only if handled without updating stock. StockCountGuidancePanel on Log Dose (form + success) / schedule — never block dispensing. Stock setup “complete” requires quantity_per_fill and total_fills_authorised both > 0. |
| Dose log (backend only) | total_dispensed / total_dispensed_all_time — used for stock mismatch alerts, not shown on family UI. |
| Medications list card | Doses available + countdown bar (green / amber within 5 of threshold / red). total_stock_on_hand on medicine-summary matches computed on-hand for every status (including exhausted). Exhausted = no repeats left, not zero tablets. |
| Extra API | GET /api/patients/{id}/scripts/medicine-summary — aggregates scripts per medicine for the Scripts page. |
| Script status | Includes archived (migration V005) to hide scripts from the default list without deleting history. |
| Image upload | New-script wizard uploads via POST …/scripts/{id}/image after create (Scripts.tsx). EditScriptModal has no image re-attach UI. Files stored under UPLOADS_DIR/<tenant_id>/; DB holds bare filename; served via authenticated GET …/scripts/{id}/image. Missing file on disk shows “Prescription image is unavailable.” in ScriptDetail.tsx (not a re-attach prompt). |
| LM Studio auth | LMSTUDIO_API_KEY in backend/.env (dev) or .env.production (VPS). services/lmstudio.py sends Authorization: Bearer … on every /v1/chat/completions call. HTTP 401 surfaces a message pointing at the env var. Probe: scripts/test-lmstudio.ps1. |
1. Purpose
Section titled “1. Purpose”The Prescription Management module gives care teams a single place to record, track, and act on a patient’s prescribed medications. A carer photographs a script or a dispensed medication label; the system extracts the structured data, associates it with the patient, and uses it to maintain a running stock count. As stock depletes or fills near exhaustion, the dashboard surfaces timely alerts so carers can arrange a pharmacy collection or a doctor visit before medication runs out.
2. Clinical standards alignment
Section titled “2. Clinical standards alignment”The data model in this module is intentionally aligned with the FHIR R5 clinical standard:
| LynCareOS concept | FHIR equivalent | Notes |
|---|---|---|
patient_scripts | MedicationRequest | The prescription / order |
script_fills | MedicationDispense | Each pharmacy collection |
dispensings | MedicationAdministration | Each dose administered |
This alignment means future interoperability with My Health Record (AU) or any FHIR-compliant system is achievable without reworking the core data model.
3. Module gating
Section titled “3. Module gating”| Slug | Dependency |
|---|---|
prescription_management | Included on all paid tiers (Essential, Family, Complete). Requires medication_dispensing for dose/stock linkage. |
require_module("prescription_management") must wrap all prescription endpoints.
Active-prescription caps (max_medicines in tiers.json, counted as patient_scripts with status = 'active'): Essential 2 · Family 5 · Complete unlimited. Creating beyond the cap raises HTTP 402 LIMIT_MEDICINES with an upgrade hint (enforce_active_medicine_limit → <UpgradeGate>).
4. Definitions
Section titled “4. Definitions”| Term | Meaning in this system |
|---|---|
| Script | A prescription issued by a licensed prescriber authorising a medicine for a named patient. AU: PBS script. Other jurisdictions: Rx, prescription. |
| Fill | A single collection of the script from a pharmacy. One fill provides a defined quantity (e.g. 28 tablets). |
| Total fills authorised | The total number of fills the script permits. In Australia (PBS): original dispensing + number of repeats shown on the script. Example: “5 repeats” = 6 total fills authorised. Terminology varies by country; the field captures the total collectable count. |
| Fills completed | How many fills have been collected to date against this script. Starts at 0; incremented each time a carer records a pharmacy collection. |
| Stock on hand | Current available supply from this script. API-computed (stock_on_hand): with manual baseline, baseline + fills/dispensings after last_physical_count_at; otherwise legacy lifetime formula. |
| Doses available (admin) | Physical dose count on hand after audit (unit from script). PATCH pills_available persists last_physical_count + last_physical_count_at (authoritative; overrides prior dose-log history for on-hand). |
| Low stock threshold | A carer-configurable unit count below which a stock-low alert fires. Default: 7 units. |
5. Access control requirements
Section titled “5. Access control requirements”| ID | Requirement |
|---|---|
| REQ-SCRIP-SEC-01 | A script record is scoped to a patient and a tenant. It must never be readable or writable by any user outside that tenant. |
| REQ-SCRIP-SEC-02 | A user may only read or create scripts for patients where they hold an active patient_access row (role carer or observer). |
| REQ-SCRIP-SEC-03 | observer role users may read scripts and view images. They may not create, edit, record fills, or delete. |
| REQ-SCRIP-SEC-04 | carer role users may create scripts, record fills, and edit non-clinical fields (notes, thresholds). They may not delete a script that has dispensing history. |
| REQ-SCRIP-SEC-05 | Tenant admin users may manage all scripts for all patients within their tenant. |
| REQ-SCRIP-SEC-06 | Super-admin may access any tenant’s scripts via X-Tenant-ID as with other resources. |
| REQ-SCRIP-SEC-07 | Script image files must be stored under a path that is not publicly guessable (UUID-based path). Direct URL access without authentication must be refused. |
| REQ-SCRIP-SEC-08 | EXIF metadata must be stripped from all uploaded images before storage. |
| REQ-SCRIP-SEC-09 | Medicine pickers / dropdowns shown when creating or editing a script (and elsewhere in the carer UI) must be patient-scoped per REQ-MED-14 — they call GET /api/patients/{id}/medicines, not the tenant-wide GET /api/medicines. This prevents another patient’s medicine names from appearing as suggestions when a carer is creating a script for the active patient. The medicines table itself remains tenant-wide by schema; the filter is applied at the read path. |
6. Data model requirements
Section titled “6. Data model requirements”6.1 patient_scripts table
Section titled “6.1 patient_scripts table”| Field | Type | Notes |
|---|---|---|
id | SERIAL PK | |
tenant_id | INTEGER FK → tenants | Isolation; required. |
patient_id | INTEGER FK → patients | Patient this script belongs to. |
medicine_id | INTEGER FK → medicines, nullable | Linked to formulary medicine if matched; null if unmatched. |
medicine_name_raw | TEXT | Drug name as extracted from image or entered by carer. Always stored even when medicine_id is set. |
strength | TEXT | e.g. "500mg", "10mg/5ml". From extraction or carer input. |
form | TEXT | e.g. "tablet", "capsule", "liquid". |
dose_instructions | TEXT | e.g. "1 tablet twice daily with food". Free text from script. |
unit | TEXT | Dispensing unit: "tablet", "ml", etc. Defaults to "tablet". |
quantity_per_fill | INTEGER, nullable | Units provided per fill (e.g. 28 tablets). Required before fill stock tracking is active. |
total_fills_authorised | INTEGER, nullable | Total fills permitted by this script (original + repeats). Required before fill tracking is active. |
fills_completed | INTEGER DEFAULT 0 | Fills collected to date. |
low_stock_threshold | INTEGER DEFAULT 7 | Units below which a stock-low alert fires. |
prescriber_name | TEXT, nullable | From extraction or carer input. |
prescriber_practice | TEXT, nullable | From extraction or carer input. |
issued_date | TEXT, nullable | Date script was issued (TEXT, matching date convention in schema). |
expiry_date | TEXT, nullable | Date script expires. AU standard: 12 months for standard scripts, 3 months for controlled drugs. |
image_url | TEXT, nullable | Path/URL of stored image. |
image_stored_at | TIMESTAMPTZ, nullable | When the image was persisted. |
scan_status | TEXT CHECK (unscanned, scanned, confirmed, manual) | scanned = extraction run; confirmed = carer reviewed and accepted; manual = entered without scan. |
scan_raw_text | TEXT, nullable | Raw OCR / vision model output retained for audit. |
scan_confidence | REAL, nullable | Overall 0.0–1.0 confidence from extraction model. Null if manual entry. |
status | TEXT CHECK (active, paused, exhausted, expired, superseded) | See status lifecycle below. |
notes | TEXT, nullable | Freeform carer notes. |
created_by | INTEGER FK → users | Carer who created the record. |
created_at | TIMESTAMPTZ DEFAULT NOW() | |
updated_at | TIMESTAMPTZ DEFAULT NOW() |
Indexes: (tenant_id, patient_id), (patient_id, status), (expiry_date).
Script status lifecycle
Section titled “Script status lifecycle”| Status | Meaning |
|---|---|
active | Script is current and fills may be recorded. |
paused | Medication temporarily on hold (e.g. patient hospitalised, prescriber instruction). No fills or dispensings expected. Alerts are suppressed. |
exhausted | fills_completed = total_fills_authorised. No further pharmacy fills; physical doses on hand may still be > 0 and are shown on the card. |
expired | expiry_date is in the past and script is not exhausted. |
superseded | A new script for the same medicine has been issued. This record is read-only and retained for history. |
6.2 script_fills table
Section titled “6.2 script_fills table”Each pharmacy collection is recorded here. Provides audit history of when stock was added.
| Field | Type | Notes |
|---|---|---|
id | SERIAL PK | |
script_id | INTEGER FK → patient_scripts ON DELETE CASCADE | |
fill_number | INTEGER | Which fill this is (1 = first collection). Set to the new fills_completed value after increment. |
quantity_added | INTEGER | Units added. Typically equals quantity_per_fill; may differ for partial pharmacy supplies. |
collected_by | INTEGER FK → users | Carer who recorded the collection. |
collected_at | TIMESTAMPTZ DEFAULT NOW() | |
notes | TEXT, nullable | e.g. pharmacy name, cost, partial supply reason. |
Constraint: UNIQUE (script_id, fill_number).
6.3 Additions to dispensings (migration)
Section titled “6.3 Additions to dispensings (migration)”Applied via a separate migration file — not by modifying
schema.sql. See 01-ARCHITECTURE.md for migration conventions.
| Column | Type | Notes |
|---|---|---|
patient_id | INTEGER FK → patients, nullable | Associates the dispensing with a patient for stock deduction. Required for stock tracking; NULL for legacy rows. |
script_id | INTEGER FK → patient_scripts, nullable | When set, this dispensing deducts from the script’s stock on hand. |
7. Vision model integration
Section titled “7. Vision model integration”7.1 LM Studio configuration
Section titled “7.1 LM Studio configuration”The extraction pipeline calls a local LM Studio instance running Qwen2.5-VL 7B via its
OpenAI-compatible API. All calls are made server-side from FastAPI using httpx.AsyncClient.
The model server is never called directly from the browser.
| Config key | Default | Purpose |
|---|---|---|
LMSTUDIO_BASE_URL | http://192.168.7.104:1234 | LM Studio server address |
LMSTUDIO_API_KEY | (empty) | Bearer token from LM Studio Settings → API when server authentication is enabled |
LMSTUDIO_MODEL | qwen/qwen2.5-vl-7b | Model identifier as registered in LM Studio |
LMSTUDIO_TIMEOUT_CONNECT | 10 | Seconds to establish TCP connection. Fails fast if LM Studio is down. |
LMSTUDIO_TIMEOUT_READ | 120 | Seconds waiting for inference response. Set high — vision model inference on a large prescription image can take 10–40 s; this provides headroom for GPU load and complex images. |
LMSTUDIO_TIMEOUT_WRITE | 30 | Seconds to upload the image in the request body. |
All keys above are loaded from backend/.env and backend/config.py (production VPS also
layers .env.production). After changing LMSTUDIO_*, restart scan_worker (and
app if using Docker) so containers pick up new values.
The scanning endpoint must return a structured error (not crash) if LM Studio is unreachable, returns HTTP 401/403 (missing or invalid token), or times out, so carers can fall back to manual entry. All other API routes are unaffected by LM Studio availability.
7.2 Request format
Section titled “7.2 Request format”Images are sent to POST {LMSTUDIO_BASE_URL}/v1/chat/completions as base64-encoded
content parts in the OpenAI vision message format, with
Authorization: Bearer {LMSTUDIO_API_KEY} when the key is set (required on LM Studio
0.3+ servers with authentication enabled). EXIF metadata is stripped from the image
bytes before base64 encoding. The prompt instructs the model to return a strict JSON
object with null for any field it cannot extract from the image.
7.3 Confidence scoring
Section titled “7.3 Confidence scoring”Qwen2.5-VL does not natively emit per-field confidence scores. The implementation must derive confidence from the model’s output: fields that are absent, ambiguous in the response, or that required a fallback parse receive lower confidence scores. The three-tier display thresholds (≥0.85 / 0.70–0.84 / <0.70) are applied by the backend before returning the response to the frontend.
8. Scanning requirements
Section titled “8. Scanning requirements”| ID | Requirement |
|---|---|
| REQ-SCRIP-SCAN-01 | The system must accept an image upload (JPEG or PNG; maximum 15 MB) of either a printed prescription document or a dispensed medication label on packaging. |
| REQ-SCRIP-SCAN-02 | The upload endpoint must be authenticated; the calling user must have carer access to the target patient. |
| REQ-SCRIP-SCAN-03 | The image must be processed synchronously. The API must respond with extracted fields; background processing (fire-and-forget) is not acceptable — carers need immediate feedback to review and correct fields. |
| REQ-SCRIP-SCAN-04 | The extraction pipeline must return at minimum: medicine_name_raw, strength, form, dose_instructions, prescriber_name, issued_date, and a per-field or overall scan_confidence. Missing fields are returned as null. |
| REQ-SCRIP-SCAN-05 | EXIF metadata must be stripped from the image before storage. |
| REQ-SCRIP-SCAN-06 | The original image must be stored and associated with the patient_scripts row. It must not be deleted after processing. |
| REQ-SCRIP-SCAN-07 | The raw extraction text (scan_raw_text) must be stored on the record for audit purposes regardless of whether the extraction succeeded cleanly. |
| REQ-SCRIP-SCAN-08 | The API must return extracted fields without saving the script record. The carer reviews and confirms on the frontend; a separate confirm/save call persists the record. Unreviewed extraction data must never enter the database as a confirmed record. |
| REQ-SCRIP-SCAN-09 | A carer may create a script record entirely without scanning (manual entry). scan_status is set to manual and scan_confidence is null. |
| REQ-SCRIP-SCAN-10 | If extraction fails or times out, the API returns a structured error. The frontend must offer “Try again” and “Enter details manually” — the carer must never face a dead end. |
| REQ-SCRIP-SCAN-11 | A carer may re-scan an existing script (e.g. to attach a clearer image). The image and scan fields are updated; a re-scan does not reset fills_completed or fill history. |
Extraction confidence tiers
Section titled “Extraction confidence tiers”Based on validated open source prescription recognition systems, three tiers apply:
| Tier | Confidence range | UI treatment |
|---|---|---|
| Verified | ≥ 0.85 | No flag. Field shown normally. |
| Review recommended | 0.70 – 0.84 | Amber border + “Please verify” label below field. |
| Manual verification required | < 0.70 | Amber border + “Unclear in image — please enter manually” label. |
9. Script lifecycle requirements
Section titled “9. Script lifecycle requirements”| ID | Requirement |
|---|---|
| REQ-SCRIP-LIFE-01 | After carer review and confirmation, scan_status is set to confirmed (or manual) and the record is persisted with status = active. |
| REQ-SCRIP-LIFE-02 | fills_completed starts at 0 on creation. A script with fills_completed = 0 has no stock. Alerts must not fire for zero-fill scripts. |
| REQ-SCRIP-LIFE-03 | When fills_completed = total_fills_authorised, status is automatically set to exhausted. No further fills may be recorded. |
| REQ-SCRIP-LIFE-04 | When expiry_date is in the past and status is not exhausted or superseded, status is set to expired. This transition is applied lazily on next load (no background sweep required for V1). |
| REQ-SCRIP-LIFE-05 | A script may be set to paused by a carer or admin when the medication is temporarily on hold. All stock-based alerts are suppressed while paused. Fills and dispensings may not be recorded against a paused script. |
| REQ-SCRIP-LIFE-06 | A script may be marked superseded by an admin or carer when a new script for the same medicine is issued. A superseded script is read-only. |
| REQ-SCRIP-LIFE-07 | A script with dispensing history may not be hard-deleted. It may only be archived via status change. |
10. Fill management requirements
Section titled “10. Fill management requirements”| ID | Requirement |
|---|---|
| REQ-SCRIP-FILL-01 | A single prominently placed action (“Script collected” or “Record fill”) is available on the script detail screen when status = active and fills_completed < total_fills_authorised. |
| REQ-SCRIP-FILL-02 | The fill action must complete in 3 taps or fewer from the script detail screen: tap button → review pre-filled confirmation → confirm. This is the maximum acceptable interaction count for a routine care action. |
| REQ-SCRIP-FILL-03 | The confirmation shows: fill number (e.g. “Fill 2 of 6”), quantity to be added (pre-populated from quantity_per_fill, editable for partial pharmacy supplies), optional notes, and on hand after collection (prior on-hand + quantity — dose log history does not reduce the new pack). |
| REQ-SCRIP-FILL-04 | On confirmation: a script_fills row is inserted; fills_completed is incremented; last_physical_count is set to prior on-hand + quantity_added and last_physical_count_at to clock_timestamp() (new pack not reduced by historical dose log); stock_adjustment zeroed; updated_at set. |
| REQ-SCRIP-FILL-05 | A fill event is undoable by a tenant admin within the same calendar day, provided no dispensings have been logged against this script since the fill was recorded. This prevents accidental double-fill entries. |
| REQ-SCRIP-FILL-06 | Fill history (all script_fills rows) must be visible on the script detail screen: fill number, date collected, quantity, carer name. |
| REQ-SCRIP-FILL-07 | Partial fills (where quantity_added < quantity_per_fill) are supported. The carer edits the quantity field in the confirmation. A visual indicator on the fill history row distinguishes partial fills. |
11. Stock tracking requirements
Section titled “11. Stock tracking requirements”| ID | Requirement |
|---|---|
| REQ-SCRIP-STOCK-01 | Stock on hand is a derived value, never stored. Calculated as: (fills_completed × quantity_per_fill) + stock_adjustment − SUM(dispensings.volume WHERE dispensings.script_id = this script), rounded to a whole unit. stock_adjustment defaults to 0; admins reconcile via PATCH pills_available (physical count). |
| REQ-SCRIP-STOCK-02 | Stock tracking is only active when both quantity_per_fill and total_fills_authorised are set. If either is null, the script detail screen must indicate that stock tracking requires these fields and provide a direct edit action. |
| REQ-SCRIP-STOCK-03 | When a carer logs a dose via the manual log-dose form for a medicine that has an active linked script for the patient, the system must prompt: “Associate with [script name]?” This is optional — the carer may skip — but the prompt must appear. |
| REQ-SCRIP-STOCK-04 | When the association is accepted, dispensings.script_id and dispensings.patient_id are set and the dispensing deducts from stock on hand. |
12. Notification and alert requirements
Section titled “12. Notification and alert requirements”| ID | Notification | Trigger | Severity | Recipients |
|---|---|---|---|---|
| REQ-SCRIP-NOTIF-01 | Stock running low | stock_on_hand ≤ low_stock_threshold after any dispensing is recorded against this script. | Amber | All carers with patient_access to this patient. |
| REQ-SCRIP-NOTIF-02 | Approaching last fill | fills_completed = total_fills_authorised − 1 (penultimate fill just recorded). | Amber | All carers with patient_access. Message: “One fill remaining — consider arranging a doctor visit or phone consult for a new script.” |
| REQ-SCRIP-NOTIF-03 | Last fill collected | fills_completed = total_fills_authorised (script now exhausted). | Red | All carers with patient_access. |
| REQ-SCRIP-NOTIF-04 | Script expired | status transitions to expired. | Red | All carers with patient_access. |
| REQ-SCRIP-NOTIF-05 | Stock exhausted | stock_on_hand = 0 AND fills_completed = total_fills_authorised. | Red | All carers with patient_access. |
| REQ-SCRIP-NOTIF-06 | Stock count needed | stock_on_hand = 0, stock tracking complete (or physical baseline), lifetime dose log > 0. | Amber | Tenant admin / super_admin only on Home and Medications. Inline guidance on Log Dose / schedule dispense for all carers; dispensing never blocked. |
Alert rendering rules:
- Alerts appear as banner chips on the Dashboard and Medications (
/scripts), scoped to the active patient. - Alerts are computed from script state (fills, stock, status) on each
GET …/scripts/alerts— not stored rows. stock_lowonly when bothquantity_per_fillandtotal_fills_authorisedare set (REQ-SCRIP-STOCK-02). If either is missing after at least one fill, showstock_tracking_incomplete(amber) with deep link to script detail?setup=stock(admin opens Edit).- After Script collected (
POST …/fills), the UI refetches alerts viascriptsEvents(see 01-ARCHITECTURE.md — Prescription script alerts). - Alerts are suppressed for scripts with
status = paused,superseded, orarchived. - Amber alerts use
amber-*tokens; red alerts usered-*. Consistent with03-DESIGN-SYSTEM.md. - Done (2026-06-03): per-user Ignore on each banner — 3-day snooze via
script_alert_dismissals(V105);POST …/scripts/alerts/dismiss. Snooze clears when the underlying condition resolves. UI:ScriptAlertBanneron Dashboard and Medications. - Pending: Dashboard nav badge count for script alerts.
- Future phases may route alerts to push notifications (Phase 4 infrastructure).
Implementation note (2026-06-03): Banners still clear immediately when underlying state changes (fill, stock edit). Ignore is for carers who want to defer the reminder without fixing stock yet. Home refetch uses cancelled requests so stale “0 units” copy does not overwrite a fresh alerts response after returning from Medications.
13. API shape (planned endpoints)
Section titled “13. API shape (planned endpoints)”All endpoints require prescription_management module and patient access checks.
| Method | Path | Purpose |
|---|---|---|
POST | /api/patients/{id}/scripts/scan | Upload image; returns extracted fields. Does not save. |
POST | /api/patients/{id}/scripts | Create a script record (post-review). |
GET | /api/patients/{id}/scripts | List scripts for patient (active first; filterable by status). |
GET | /api/patients/{id}/scripts/{script_id} | Script detail including fill history and derived stock on hand. |
PATCH | /api/patients/{id}/scripts/{script_id} | Update editable fields (notes, thresholds, medicine_id, status). |
POST | /api/patients/{id}/scripts/{script_id}/fills | Record a fill. |
DELETE | /api/patients/{id}/scripts/{script_id}/fills/{fill_id} | Undo fill (admin, same-day, no subsequent dispensings). |
GET | /api/patients/{id}/scripts/{script_id}/image | Serve stored image (authenticated, patient-access-gated). |
GET | /api/patients/{id}/scripts/alerts | Active stock/expiry alerts for this patient (respects per-user dismiss snooze). |
POST | /api/patients/{id}/scripts/alerts/dismiss | Snooze one alert for the current user (3 days). Body: { script_id, alert_type }. |
14. Scanning flow UX requirements
Section titled “14. Scanning flow UX requirements”| ID | Requirement |
|---|---|
| REQ-SCRIP-UX-01 | The scan flow entry point is in the Medications section. A “Scan script” button is accessible from the medicines list and from the log-dose flow. It must not require more than one tap to reach from either location. |
| REQ-SCRIP-UX-02 | Image capture supports both camera (mobile) and file upload (desktop) via <input type="file" accept="image/*" capture="environment">. No separate modes or toggles. |
| REQ-SCRIP-UX-03 | A full-width preview of the captured image is shown before upload, with “Retake / Choose different” and “Use this image” actions. The preview must be large enough for the carer to confirm the image is legible before submitting. |
| REQ-SCRIP-UX-04 | Once the carer confirms the image, all interactive elements are disabled and a staged progress indicator is shown with a visible label that updates through three named stages: “Uploading image…” → “Processing image…” → “Extracting details…”. A bare unlabelled spinner does not meet this requirement. |
| REQ-SCRIP-UX-04a | If extraction fails or times out, the progress indicator is replaced with a clear inline error message and two options: “Try again” and “Enter details manually”. The carer must never be left at a dead end. |
| REQ-SCRIP-UX-05 | On successful extraction, the review screen displays the captured image and extracted fields simultaneously. On mobile: image occupies approximately the top 40% of the screen; form occupies the remainder and is independently scrollable. On desktop (lg:): image in left column, form in right column. |
| REQ-SCRIP-UX-05a | The image on the review screen is pinch-zoomable on mobile. A “View full size” tap opens the image in a full-screen overlay. |
| REQ-SCRIP-UX-05b | Every extracted field is rendered as an editable input pre-populated with the extracted value. No field is read-only on the review screen. |
| REQ-SCRIP-UX-05c | Fields are visually flagged per the confidence tier table in Section 7. High-confidence fields (≥0.85) show no special treatment. |
| REQ-SCRIP-UX-05d | quantity_per_fill and total_fills_authorised are grouped under a “Stock tracking” label. If either is missing post-scan, both inputs are highlighted amber with: “Required for stock tracking.” |
| REQ-SCRIP-UX-06 | A low-prominence “Clear all extracted fields” action allows the carer to reset the form to blank for fully manual entry without deleting each field individually. |
| REQ-SCRIP-UX-07 | The review form has a single primary action: “Save prescription”. Enabled once medicine_name_raw is non-empty. All other fields are optional at save time. |
| REQ-SCRIP-UX-08 | The original script image is accessible from the script detail screen at any time, in a full-screen viewer with a download option. Carers must always be able to refer to the original if the extracted data is questioned. |
| REQ-SCRIP-UX-09 | The script detail screen shows: status badge, stock on hand with a visual progress bar (units remaining / total available from fills so far), fills used / total authorised, next recommended action (e.g. “Record fill”, “Arrange new script”), and the fill history list. |
| REQ-SCRIP-UX-10 | In Australia, the total_fills_authorised field label includes a helper note: “PBS: original dispensing + number of repeats on script.” This note is display-only and does not enforce any AU-specific logic. |
15. Non-functional requirements (module-specific)
Section titled “15. Non-functional requirements (module-specific)”| ID | Requirement |
|---|---|
| REQ-SCRIP-NFR-01 | Script images are PII/PHI. They must never be served without authentication and patient_access validation. UUID-based paths or equivalent must prevent URL guessing. |
| REQ-SCRIP-NFR-02 | EXIF data must be stripped on ingest (REQ-SCRIP-SEC-08). |
| REQ-SCRIP-NFR-03 | The extraction endpoint must have a timeout and return a structured error on failure so carers can proceed manually. A failed scan must never block script creation. |
| REQ-SCRIP-NFR-04 | stock_on_hand is never stored; always derived at query time to remain consistent with the dispensing record. |
| REQ-SCRIP-NFR-05 | Scripts may reference medicines not yet in the tenant formulary. medicine_id is nullable; medicine_name_raw is always available. An admin may link a script to a formulary medicine at any time after creation. |
| REQ-SCRIP-NFR-06 | No automated process may create a dispensings row on behalf of a carer. Every dispense record must trace to an explicit human confirmation action. |
16. Out of scope (this module, V1)
Section titled “16. Out of scope (this module, V1)”- Electronic prescription integration (eRx, MedView AU) — future.
- Controlled drug / Schedule 8 restricted prescriber workflows — future.
- Prescription cost or PBS claim tracking — future.
- Push notifications for script alerts (deferred to Phase 4 infrastructure).
- Automated doctor appointment booking — future.
- Drug interaction checking or clinical decision support — out of scope for this platform.
- Expiry sweep as a scheduled background job — lazy expiry check on load is acceptable for V1.