05 — Developer Guide
Conventions, workflows, and commands for working on LynCareOS. Read existing code before adding new code — the repository is the source of truth; this guide points to the patterns that are actually used.
Related: 01-ARCHITECTURE.md (stack and Docker), 02-REQUIREMENTS.md (solution scope), 03-DESIGN-SYSTEM.md (UI), 14-FRONTEND-PRESENTATION-STACK.md (presentation tools), 04-ROADMAP.md (phases and gaps).
Version: 1.72
Last Updated: 2026-08-05 17:38:42
1. Repository layout
Section titled “1. Repository layout”LynCareOS/├── backend/ Python FastAPI app│ ├── main.py App factory, CORS, routers, static SPA; lifespan opens DB + tenant scheduler│ ├── run_server.py Dev server (Windows-friendly; port 8021)│ ├── config.py Environment variables (incl. LM Studio, uploads)│ ├── database.py Pool, get_db(), init_db(), MODULES tuple│ ├── billing/ tiers.json (Stripe bundles) · module_delivery.json (UX readiness)│ │ module_delivery.py — live/partial/planned helpers│ ├── auth.py JWT, dependencies (tenant, module, patient, …)│ ├── models.py Pydantic models (where used)│ ├── schema.sql Idempotent DDL supplement (PostgreSQL)│ ├── schema/lyncareos_v1_baseline.sql Full v1 baseline (greenfield init_db)│ ├── migrations/ Active VNNN__*.sql + runner.py; pre-v1 in archive/pre-v1/│ ├── seed_admin.py Super-admin seed script│ ├── requirements.txt│ ├── care_modules/ Feature-flagged Care Profile board plugins (flags, manifests, board API)│ ├── routers/ Feature routers (`/api/...` — not `/api/v1/`)│ │ New: condition_packs.py · observations.py · help_requests.py│ ├── services/ Domain services (lmstudio, images, shopping_service, care_shifts_service, …)│ │ New: field_crypto.py · scan_queue_pg.py · condition_packs_service.py│ │ observations_service.py · help_requests_service.py · patient_scripts_service.py│ ├── repositories/ Pure SQL functions extracted from routers (care_shifts, alerts, pain, shopping)│ │ New: condition_packs.py · observations.py · help_requests.py · medication_groups.py│ ├── scripts/ Seeds, catalog tooling, CI gates (check_router_sql.py), one-off fix scripts│ └── tests/ pytest (see §9)├── frontend/ React + Vite + TypeScript│ ├── src/│ │ ├── pages/ Route-level screens│ │ ├── components/ Shared UI + feature folders (shopping/, sleep/, calendar/, medication-schedule/, …)│ │ │ New: condition-packs/ · observations/│ │ │ Pain UI: pain/BodyMap.tsx · PainBodyMapTab.tsx — **2D only** (no 3D in launch bundle)│ │ │ integrations/README.md — stub for future plug-in host files (no imports yet)│ │ ├── care-modules/ Care board plugins (cancer, breathing) — lazy when VITE flag set│ │ ├── context/ Auth, theme, module, patient; careModuleFlags = hook only│ │ ├── hooks/ e.g. useAuthenticatedImage│ │ ├── lib/api.ts fetch wrappers, token storage; re-exports OpenAPI + manual types│ │ ├── lib/api.types.ts Auto-generated from openapi/openapi.json (do not edit)│ │ ├── lib/api.contracts.ts Named Schema aliases for api.ts and feature code│ │ ├── lib/moduleDelivery.ts live/partial/planned labels (imports billing/module_delivery.json)│ │ ├── lib/types/ Domain-scoped TypeScript types split from api.ts (types/care.ts, …)│ │ ├── components/billing/ ModuleAccessRow.tsx — Subscriptions entitlement + delivery labels│ │ └── main.tsx├── packages/ Plug-in modules (not imported by production frontend build)│ └── clinical-anatomy/ @lyncareos/clinical-anatomy — 3D body/skeleton turntable (WIP)│ src/ ClinicalAnatomyViewer, region3dMap, hostAdapter│ public/models/ GLB assets + licenses.json│ demo/ Standalone preview — `npm run dev` → http://localhost:5175│ README.md Plug-in contract; see docs/plans/2026-05-31-anatomy-viewer-r3f.md│ ├── index.html│ ├── vite.config.ts Dev proxy `/api` → backend│ ├── tailwind.config.js│ └── package.json├── docker-compose.yml postgres, pgbouncer, redis, app, scan_worker (all with profile `production`); volumes for DB, uploads, Redis├── dev-start.ps1 Postgres + backend + Vite (Windows); dev-stop.ps1├── start.ps1 Unified start/stop (production or -Dev)└── docs/ Architecture, requirements, roadmap, runbook, …There is no root npm workspace linking packages/* into frontend today — the production app builds from frontend/ only. New UI goes under pages/ and components/ following neighbours. New API code: add a routers/*.py (or extend one), wire in main.py, and extend lib/api.ts.
1.1 Pain & Stats vs clinical_anatomy (2026-05-31)
Section titled “1.1 Pain & Stats vs clinical_anatomy (2026-05-31)”| Surface | Location | Launch |
|---|---|---|
| Pain Record (2D) | components/pain/PainBodyMapTab.tsx, BodyMap.tsx | Shipped — /pain |
| 3D anatomy | packages/clinical-anatomy/ | Not wired — slug clinical_anatomy is planned in module_delivery.json |
- Production does not depend on
@google/model-viewer(removed fromfrontend/package.json). - Do not add 3D code under
components/pain/; future plug-in uses one lazy file undersrc/integrations/andtoPainRegionTapHandler()from the package. - Preview 3D:
cd packages/clinical-anatomy && npm install && npm run dev(place GLBs inpublic/models/first). - Module spec: 26-PAIN-STATS-MODULE.md §13 · Plan: 2026-05-31-anatomy-viewer-r3f.md
2. Prerequisites
Section titled “2. Prerequisites”| Tool | Notes |
|---|---|
| Python | 3.11+ locally; Docker production image uses 3.12 |
| Node.js | 18+ (Docker frontend build uses Node 22) |
| Docker | For PostgreSQL in dev; for full stack with --profile production |
| PostgreSQL | 16 — via Compose locally, or your own instance with a valid DATABASE_URL |
3. Local development (recommended flow)
Section titled “3. Local development (recommended flow)”3.1 Start PostgreSQL
Section titled “3.1 Start PostgreSQL”From the repo root:
docker compose up -d postgresWait until the container is healthy (docker compose ps). Default database: lyncareos, user/password: lyncare/lyncare (override via env).
Dev vs local UAT vs cloud production (isolation)
Section titled “Dev vs local UAT vs cloud production (isolation)”Canonical names: 00-INDEX.md — Terminology.
- Development (
lyncareos_dev), local UAT (full Docker stack on your PC — profileproduction, DB name oftenlyncareos), and production (the designated operations host — live subscribers) are different hosts. The app only followsDATABASE_URL— there is no magic switch. - They never share data unless someone misconfigures (e.g. pasting a production DSN into
backend/.env) or restores a dump across tiers. Do not point a dev laptop at the production database for casual work. - Local Compose UAT uses a Docker volume on your PC (
lyncare_pg_data). Production on the operations host uses Docker volumes on that machine (see 03%20-%20DEPLOYMENT%20AND%20PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md) — not your dev laptop’s disk. DATABASE_URLmust match the host port Compose publishes when using Docker Postgres. Default is oftenlocalhost:5433(seePOSTGRES_HOST_PORT). For daily dev withdev-start.ps1, uselyncareos_dev, not the UAT DSN.
3.2 Backend
Section titled “3.2 Backend”cd backendpython -m venv venv.\venv\Scripts\Activate.ps1pip install -r requirements.txtcopy .env.example .env# Edit .env — DATABASE_URL, SECRET_KEY, ADMIN_* for seed_admin, etc.Apply schema and seed (first time or after empty DB):
python -c "import asyncio; from database import init_db; asyncio.run(init_db())"python seed_admin.pyRun the API on port 8021 (matches Vite proxy default and run_server.py):
python run_server.pyAlternative (manual):
uvicorn main:app --reload --host 127.0.0.1 --port 8021On Windows, run_server.py sets WindowsSelectorEventLoopPolicy before uvicorn starts — required for psycopg async. Linux/Docker use the Dockerfile CMD (no special loop).
3.3 Frontend
Section titled “3.3 Frontend”cd ..\frontendnpm installnpm run dev- Dev server: http://localhost:5173 (override with
VITE_PORT). - API calls use
/api/...; Vite proxies/apitoVITE_API_URLor http://localhost:8021 (vite.config.ts).
3.4 One-shot startup (Windows)
Section titled “3.4 One-shot startup (Windows)”.\dev-start.ps1— native Postgres check, backend (run_server.pyon 8021), Vite. Logs:backend.log,frontend.log. Stop with.\dev-stop.ps1. Does not startscan_worker— for prescription scans in dev, run Redis (defaultredis://localhost:6379/0) and in a second terminal:cd backend; .\venv\Scripts\python.exe -m workers.scan_worker..\start.ps1— alternative: local UAT full stack (docker compose --profile production) or-Devfor dev servers; readsPORT/DEV_PORTfrombackend/.env(defaults align with.env.example).
4. Docker full-stack run (local UAT)
Section titled “4. Docker full-stack run (local UAT)”Build and run Postgres + app (API + built SPA in one container) on the workstation — not the live production stack on the operations host:
docker compose --profile production up -d --build- App listens on 8020 on the host; API + SPA same origin.
- Compose sets
DATABASE_URLto thepostgresservice,ENVIRONMENT=production,UPLOADS_DIR=/app/uploads, and mountslyncare_uploadsso uploads survive restarts. env_file: backend/.envloads secrets and tunables — keepSECRET_KEY,ALLOWED_ORIGINS, and LM Studio URLs in that file for container runs.
See 01-ARCHITECTURE.md for volumes, image stages, and edge/TLS notes.
5. Environment variables (backend)
Section titled “5. Environment variables (backend)”Copy backend/.env.example → backend/.env. Key variables:
| Variable | Purpose |
|---|---|
DATABASE_URL | PostgreSQL DSN — for local Compose, use the published host port (often localhost:5433, see POSTGRES_HOST_PORT in root .env / docker-compose.yml; not the in‑container 5432 unless you intentionally run Postgres on 5432 on the host) |
SECRET_KEY | JWT signing; required when ENVIRONMENT=production (local UAT container or cloud) |
ENVIRONMENT | development (default) or production (stricter checks — applies to both local UAT Docker and the operations host; it does not by itself mean “live traffic”) |
ALLOWED_ORIGINS | Comma-separated CORS origins; required for containerised runs with real origins (use * only for local dev) |
ACCESS_TOKEN_EXPIRE_HOURS / REFRESH_TOKEN_EXPIRE_DAYS | JWT lifetimes |
GOOGLE_CLIENT_ID | Optional Google sign-in (backend); pair with VITE_GOOGLE_CLIENT_ID on the client |
DB_POOL_MIN / DB_POOL_MAX | Connection pool size (defaults 2 / 10) |
HOST / PORT | Uvicorn bind when running manually; 8020 in Docker image |
DEV_PORT | Documented in .env.example for local dev (8021) — used by start.ps1 / Vite proxy; not used by the Docker CMD |
LMSTUDIO_BASE_URL | Prescription scan (default in config.py); server-side only. Docker on Windows reaching LM Studio on the LAN: use the host LAN IP (e.g. http://192.168.7.104:1234), not a stale address — restart scan_worker after edits. |
LMSTUDIO_API_KEY | Bearer token from LM Studio Settings → API when server auth is on. Never commit; set in backend/.env (dev) or .env.production (VPS). |
LMSTUDIO_MODEL | Vision model id (e.g. Qwen2.5-VL) |
LMSTUDIO_TIMEOUT_* | Connect / read / write timeouts for scan requests |
Connectivity check (from repo root): .\scripts\test-lmstudio.ps1 — probes GET {LMSTUDIO_BASE_URL}/v1/models.
| UPLOADS_DIR | Prescription, shopping, and dispensing images; Docker: /app/uploads volume. New files go under /app/uploads/<tenant_id>/ (bare UUID filename in DB). Legacy flat files at /app/uploads/<filename> are still served until migrated (backend/scripts/migrate_uploads_to_tenant_dirs.py). Contact attachments: contact_attachments/<tenant_id>/. |
| ICONSCOUT_CLIENT_ID / ICONSCOUT_SECRET_KEY | Optional — catalog asset scripts only, not required to run the app |
| CARE_MODULE_BOARDS_ENABLED | false — when true, enables /api/care-modules/* board APIs |
| CARE_MODULE_PREVIEW_USER_IDS | Default 1 — comma-separated user IDs who receive feature_flags.care_module_boards on /subscriptions/active |
Frontend optional: frontend/.env — VITE_GOOGLE_CLIENT_ID, VITE_API_URL (proxy target for /api, default http://localhost:8021), VITE_PORT.
6. Backend patterns
Section titled “6. Backend patterns”6.1 Routers
Section titled “6.1 Routers”- Use
APIRouterwith aprefixsuch as/api/auth,/api/medicines,/api(care shifts), etc. Do not invent/api/v1/unless the whole codebase is migrated consistently. - Patient-scoped routes that do not fit under a single prefix (e.g.
/api/patients/{id}/medication-groups,/api/patients/{id}/dispense) use a secondAPIRouterwithout a prefix on the same module — seemedication_groupsandscriptsrouters wired inmain.py(no separatemedicinesrouter after V103). - Inject
AsyncConnectionviaDepends(get_db); useawait db.commit()after writes. - Attach the right
Depends(...)fromauth.py:get_current_user,require_approved,require_tenant_member,require_tenant_admin,require_patient_access,require_module("…"), etc. - SPA catch-all:
main.pyservesindex.htmlfor any unmatched path with HTTP 200. When checking whether an API route exists (tests, probes), assertContent-Type: application/json— not status code alone. A missing route returns HTML, not 404.
6.2 SQL
Section titled “6.2 SQL”- Parameterized queries only —
%splaceholders, never f-string SQL with user input. dict_row— rows are dict-like;dict(row)is common in handlers.
6.3 Schema changes
Section titled “6.3 Schema changes”- Greenfield databases:
init_db()appliesbackend/schema/lyncareos_v1_baseline.sqlonce (whenpublic.tenantsis missing), then the migration runner, then idempotentschema.sql. - Brownfield databases (dev, VPS): baseline is skipped; pending active migrations run, then
schema.sql. Pre-v1 SQL lives inbackend/migrations/archive/pre-v1/— never add new files there. - Incremental changes after v1: add
V002__…,V003__…, etc. underbackend/migrations/with idempotent statements (ADD COLUMN IF NOT EXISTS, etc.).migrations/runner.pyapplies pending active files in order and records them inschema_migrations. This is the standard path for new tables/columns used in production. - Document every forward migration: append a row to 11-DATABASE-SAFETY-AND-MIGRATIONS.md §1a in the same change set; add a
§2xsubsection there when the migration needs more than a one-line summary. Mirror new columns/tables inbackend/schema.sqlfor greenfield installs. - Apply on dev:
.\migrate.ps1 -Target Devfrom repo root (setsDATABASE_URL→lyncareos_dev). Do not run barepython -m migrations.runnerwithout-Target— default config may point at wrong database. Full rules: 11-DATABASE-SAFETY-AND-MIGRATIONS.md. - Avoid editing only
CREATE TABLEinschema.sqlfor databases that already exist — existing DBs need migrations (or manualALTER) to pick up changes. - After adding a migration, run
.\migration-audit.ps1 -Target Devand ensure greenfield rehearsal still passes if baseline DDL changed (24-V1-DATABASE-BASELINE-AND-CUTOVER.md).
6.4 Errors
Section titled “6.4 Errors”Use HTTPException(status_code, detail) for client-facing failures. Let unexpected errors surface as 500 only when truly unhandled (FastAPI default).
6.5 Patient scripts as the medication entity (V103, REQ-MED-14)
Section titled “6.5 Patient scripts as the medication entity (V103, REQ-MED-14)”Migration V103__merge_medicines_into_scripts.sql removed the tenant medicines table and routers/medicines.py. Each medication is a patient_scripts row (medicine_name_raw, color_hex, as_needed, stock/fills). Schedule items and dispensings reference script_id only.
| Layer | File | Responsibility |
|---|---|---|
| Repository | repositories/patient_scripts.py | Script row helpers, stock derivation, enrich (partial — more SQL in service during B3) |
| Service | services/patient_scripts_service.py | CRUD, fills, scan queue, alerts (stock_count_needed when dose log > 0 and on-hand ≤ 0), dismiss snooze, medicine-summary (total_stock_on_hand for all statuses) |
| Router | routers/scripts.py | Thin HTTP — GET/POST/PATCH /api/patients/{id}/scripts/* |
| Schedule / dispense | routers/medication_groups.py → services/medication_groups_service.py | Groups, dispense-view, batch dispense (script_id on items) |
When adding a medicine picker or schedule row: use api.scripts.list(patientId) (frontend) / patient-scoped script list — never a tenant-wide catalogue. Legacy /admin/medicines redirects to /scripts in the SPA.
D23 (per-patient catalogue migration) is resolved by V103 — see 32-KNOWN-DEBTS-REGISTER.md.
6.6 Active-patient isolation for aggregates, export, and audit (REQ-MED-15)
Section titled “6.6 Active-patient isolation for aggregates, export, and audit (REQ-MED-15)”REQ-MED-14 scoped pickers; REQ-MED-15 extends the rule to everything that aggregates, charts, counts, exports, or audits clinical data. The “currently selected person” lives only in frontend PatientContext, so the frontend must pass patient_id and the backend must validate and apply it.
- Backend: dispensing-analytics endpoints,
/api/alerts+/api/alerts/open-count,/api/billing/export/download, and/api/audittake an optionalpatient_id. When present, callensure_patient_access(ctx, patient_id, db)then filter onpatient_id(analytics share the_scope_dispensingshelper inrouters/analytics.py). When omitted, the legacy account/member scope is retained for admin tooling and the cancellation-portability export. - Frontend: any carer-facing page that charts/aggregates/exports must read
usePatient().activePatient, passactivePatient.idto the API, includeactivePatient?.idin theuseEffectdependencies (so it refetches on person-switch), and render nothing until a person is selected. Examples:Dashboard.tsx,Analytics.tsx,AlertInbox.tsx,AlertContext.tsx,admin/ExportData.tsx,History.tsx(audit tab). - Never add a new chart/aggregate endpoint that scopes only by
tenant_idor by all-allocated-patients when a single person is selectable in the UI.
Regression: tests/test_patient_analytics_isolation.py. Plan: docs/plans/2026-05-29-active-patient-isolation-sweep.md.
6.7 First-dose adverse reaction follow-through (REQ-MED-16)
Section titled “6.7 First-dose adverse reaction follow-through (REQ-MED-16)”When extending dispensing or alert flows:
- Detection —
first_dose_reaction_service.maybe_prompt_after_dispense(); keyed by patient + normalized medicine name (notscript_id). - Prompt —
FirstDoseReactionModalon Log Dose, Medication Schedule, and Alert inbox (Answer action). - Yes path —
respond_to_check(observed=true)→ resolvesfirst_dose_reaction, callsalert_adverse_reaction_reported(), returns check row. - Detail modal —
AdverseReactionDetailModalloads contacts viaapi.keyContacts.listContacts(patientId)(not.list()). Clinical roles fromlib/contactRoles.ts: GP, Specialist, Palliative Specialist, Nurse, Pharmacist — Call (tel:) / Email (mailto:) when phone or email present. - History —
History.tsxmergesapi.firstDoseReactions.listLog()with dispensings; reaction rows use coral styling; More menu label Dispensing and Adverse Reactions History Log. - Tests —
backend/tests/test_first_dose_reactions.py(includes urgent alert on Yes);test_key_contacts.py::test_palliative_specialist_role_tag(V005).
Do not block generic resolve on adverse_reaction_reported — only first_dose_reaction requires structured response.
Key Contacts roles: import labels from lib/contactRoles.ts; do not duplicate ROLE_LABELS in pages.
7. Frontend patterns
Section titled “7. Frontend patterns”7.1 Data loading
Section titled “7.1 Data loading”The app uses fetch through src/lib/api.ts (request() with token refresh on 401). _tryRefresh() on bootstrap: POST /api/auth/refresh returns 204 when no refresh cookie is present (logged-out shell — not an error); 200 with tokens when the cookie is valid. Pages typically use useEffect + useState (or context) — there is no TanStack Query in package.json. New code may continue this pattern or introduce a data library only with an explicit team decision and dependency addition.
Rule: Only 401 should clear tokens and force login; 403 means “forbidden”, not “session dead” (see api.ts).
Dev auth pitfalls (2026-06-03): Access tokens live only in memory (tokenStore in api.ts). Use one dev URL consistently (http://localhost:5173, not 127.0.0.1) so the HttpOnly lyncare_refresh cookie round-trips through the Vite proxy (cookieDomainRewrite). After HMR reloads api.ts, AuthContext re-runs refresh when user is set but the in-memory token was cleared — otherwise Layout fires /patients etc. and the console shows 401 until you log in again. Hard refresh or re-login also fixes a stale session.
ESLint enforces no bare fetch() in pages/components. Two approved escape hatches are exported from lib/api.ts:
| Helper | When to use |
|---|---|
uploadForm<T>(path, fields) | Multipart file uploads - handles FormData, token refresh, and 401 session clear identically to JSON request() |
requestRaw(url, options?) | Pre-auth flows only (e.g. Stripe complete-signup) where no Bearer token exists and the caller must inspect raw status codes (e.g. 202 Retry-After). On failure, parse structured payment errors via lib/paymentOutcome.ts — do not surface raw detail strings to users. |
Never introduce a bare fetch() call in a page or component - extend one of the helpers above or open a discussion first.
request(path) path rule: pass paths without the /api prefix — request() prepends /api automatically (fetch(\/api${path}`)). Correct: request(‘/admin/alert-settings’)→/api/admin/alert-settings. Wrong: request(‘/api/admin/alert-settings’)→/api/api/…, which hits the SPA fallback and returns HTML with HTTP 200 (JSON parse then fails silently or shows a generic load error). When adding new api.* helpers, match existing call sites (/patients/…, /alerts/…, not /api/patients/…`).
7.1a Subscriptions page — entitlement vs delivery (2026-06-26)
Section titled “7.1a Subscriptions page — entitlement vs delivery (2026-06-26)”Route: /subscriptions (pages/admin/Subscriptions.tsx) — tenant members can view; admins upgrade/cancel.
| Concept | Source | UI |
|---|---|---|
| Entitlement | subscriptions rows + tiers.json | Plan includes the slug |
| Delivery | backend/billing/module_delivery.json | Whether the product surface is live today |
Labels (components/billing/ModuleAccessRow.tsx via lib/moduleDelivery.ts):
- Active —
livemodule, entitled - Included — rolling out —
partial(e.g.custom_observations,family_help) - Coming soon —
plannedtier placeholders (e.g.clinical_anatomy— not intiers.jsonuntil productised)
Page layout (top to bottom on Subscriptions.tsx, 2026-06-26):
| Order | Section | Contents |
|---|---|---|
| 1 | Your plan | CurrentPlanCard — tier name, price, limits, renewal |
| 2 | Module access | Entitled modules (partitionSubscriptionsForDisplay → moduleAccess) |
| 3 | Upgrade plan | PlanUpgradePanel — tier dropdown (admins only, when upgrades exist) |
| 4 | Unlock with an upgrade | Live/partial slugs not on the current plan (hidden on Complete) |
| 5 | Care Profiles | Add a Care Profile purchase grid (ConditionPackCard) when condition_templates is enabled |
| 6 | Coming soon | planned delivery slugs the tenant does not yet own |
| — | Cancel subscription | Admin link at bottom |
Horizontal dividers separate major sections. If my-tier fails to load, the page falls back to a flat Module access grid with no split (see Subscriptions.tsx subscriptionGroups).
Excluded from module grids: condition_templates is omitted from Module access, Unlock with an upgrade, and Coming soon (SUBSCRIPTIONS_MODULE_ACCESS_EXCLUDE in lib/moduleDelivery.ts). Care Profiles are the dedicated commerce surface; per-patient apply is via dev QA panel or API until a new family workflow ships (archetype / Our care pattern UI withdrawn 2026-06-26).
Card order within each grid:
| Section | Sort rule |
|---|---|
| Module access | Order of slugs in current_tier.modules (sortSubscriptionsByCurrentPlan) — matches backend/billing/tiers.json for that plan. Add-ons not on the plan sort after plan modules, alphabetically. |
| Coming soon / Unlock with an upgrade | Cheapest tier that includes the slug, then alphabetical within the band (sortSubscriptionsByTierHierarchy) |
Do not sort Module access by tier band on Complete (or any plan) — that scatters cards into Essential → Family → Complete groupings even when the subscriber owns everything.
Retired route: /care-archetypes redirects to /subscriptions (exploratory browse page removed 2026-06-26).
Tests: frontend/src/test/lib/moduleTierUpgrade.test.ts, moduleDelivery.test.ts
Do not use the word Subscribed for partial modules. ModuleGate still enforces entitlement from /api/subscriptions/active; delivery labels are honesty for marketing reconciliation only.
When shipping a module to live, edit module_delivery.json (live array + primary_routes), mirror in moduleDelivery.ts (imports the JSON), run python scripts/generate_delivery_register.py, and add MODULE_META in routers/subscriptions.py if missing.
API contract: GET /api/modules/available → delivery[slug].status is live | partial | planned.
7.1b Post-checkout pages (signup billing UX)
Section titled “7.1b Post-checkout pages (signup billing UX)”| Route | Component | Notes |
|---|---|---|
/billing/success | BillingSuccess.tsx | POSTs session_id to /api/stripe/complete-signup; retries on 202; uses parsePaymentOutcome() / fetchCheckoutOutcome() on errors |
/billing/cancel | BillingCancel.tsx | Confirms no charge via GET /api/stripe/checkout-outcome when session_id is present |
| — | lib/paymentOutcome.ts | Shared outcome types, API fetch, pricing retry URL, support mailto builder |
User-visible copy must come from user_message on the outcome object, not HTTP status text. Branch CTAs on charged: Try again → marketing pricing when false; Sign in + support when true.
7.1c Prescription script alert banners (2026-06-03)
Section titled “7.1c Prescription script alert banners (2026-06-03)”Surfaces: Dashboard.tsx (Home), Scripts.tsx (Medications) for computed banners. stock_count_needed also raises a durable prescription_stock_count row in care_alerts (bell inbox, admin-only list/count) via alert_script_sync.py — deep_link /scripts/{id}?setup=stock&patientId={id}.
| Piece | Location |
|---|---|
| Banner UI | components/scripts/ScriptAlertBanner.tsx — tap row → script detail; Ignore → api.scripts.dismissAlert |
| Copy + routes | lib/scriptAlerts.ts |
| Refetch after fill/edit | lib/scriptsEvents.ts — call notifyScriptsChanged() from fill modal, edit save, etc. |
| Home stale-data guard | Dashboard.tsx — abort prior scripts.alerts fetch on scriptsDataGen bump; pageshow when bfcache restores |
When adding a new alert type, extend: backend get_script_alerts + SCRIPT_ALERT_TYPES + migration CHECK + ScriptAlert TypeScript union + scriptAlertSubtitle().
Care alerts bell (stock mismatch): alert_script_sync.py upserts or auto-resolves prescription_stock_count when stock_count_needed_for_script is false (e.g. after pills_available PATCH with on-hand > 0). Sync is awaited on the request via alert_script_hooks.await_sync_prescription_stock_count_alert — do not rely on background-only sync before the client refetches. AlertContext + AlertInbox refresh on scriptsEvents / dispensingsEvents (badge even when inbox closed). repositories/alerts.py hides this type from non-admins. Tap → ?setup=stock → emphasizeStockField. Mark done = handled without updating stock; closing edit without save must not clear the row.
Carer-facing stock labels (lib/scriptStock.ts — use these constants, not internal API names):
| Label | API field | Meaning for carers |
|---|---|---|
| Doses available | stock_on_hand / total_stock_on_hand | What the family has on hand now (card + detail). |
| How many doses do you have available? | pills_available PATCH | Edit modal label (DOSES_ON_HAND_PROMPT) — ask for a physical count; do not show lifetime doses logged. |
| Last counted | last_physical_count + last_physical_count_at | Last physical stock-take baseline. |
total_dispensed remains on the API for alert logic only — not shown to carers.
7.1c Stream 2–3 modules (partial delivery)
Section titled “7.1c Stream 2–3 modules (partial delivery)”Gated with ModuleGate in App.tsx. Discoverability is mostly via More (More.tsx) except where noted.
| Route | Module slug | Component | Notes |
|---|---|---|---|
/observations | custom_observations | Observations.tsx → ObservationDashboard | Requires usePatient().activePatient; API under observationsApi in lib/api.ts |
/help-requests | family_help | HelpRequests.tsx | Also listed in More when module enabled |
/planning-ahead | care_pathways (planned D31) | — | Not shipped. Spec 33; mockup docs/01 - BUSINESS REQUIRMENTS/assets/planning-ahead-mockup.html |
Care archetypes (no standalone route): seven coordination patterns via GET /api/condition-packs/archetypes; no family UI as of 2026-06-26 (CarePatternPanel + ArchetypeOnboarding removed; Add Person is demographics only). Purchase/unlock via Care Profiles on /subscriptions. Legacy /care-archetypes → redirect /subscriptions.
Update backend/billing/module_delivery.json (partial / planned copy + primary_routes) and run python scripts/generate_delivery_register.py when changing delivery labels. Add care_pathways to planned at D31 kickoff.
7.1d Admin alert settings
Section titled “7.1d Admin alert settings”| Route | Component | Notes |
|---|---|---|
/admin/alerts | AlertSettings.tsx | Admin-only (AdminGate); loads api.alerts.getSettings() → GET /api/admin/alert-settings |
Channel toggles include family_help (V093). Non-admins are redirected before the page mounts; a 403 from the API means the session user is not a tenant admin.
After deploy, no user action is required — mid-session browsers auto-recover from stale lazy chunks via lib/lazyWithReload.ts, and the service worker reinstalls on every deploy because npm run build stamps CACHE_NAME with the current main-bundle hash (see frontend/scripts/inject-sw-version.mjs). The SW_UPDATED postMessage triggers the reload chain in index.html. If you see a stale shell anyway, check that the /sw.js response from app.lyncareos.com carries Cache-Control: no-cache and cf-cache-status: DYNAMIC; if either is wrong, the Cloudflare Cache Rule lyncareos-sw-bypass has regressed. Full strategy: docs/plans/2026-05-29-spa-deploy-resilience.md.
Agent / release owner checklist: Treat cache verification as part of “deploy complete”, not optional. After deploy.ps1 succeeds, confirm (1) a new CACHE_NAME in live sw.js, (2) index.html no-store headers, (3) API smoke 200 — see 20-PRODUCTION-DEPLOYMENT-GUIDE.md §6. A hung local push-to-production.ps1 (e.g. Docker UAT backup) does not update production; never kill VPS processes to unstick a workstation script.
7.1e Patient selection (PatientContext)
Section titled “7.1e Patient selection (PatientContext)”PatientProvider stores lyncareos_active_patient in localStorage. On each patient-list fetch it validates the stored id against the live tenant list before exposing activePatientId — stale ids from dev or another tenant are replaced with the first accessible patient (or cleared when the list is empty). Do not read localStorage for patient id in components; use usePatient().
7.1f Default landing — Home (/)
Section titled “7.1f Default landing — Home (/)”Post-login and long-absence return always land on Home (Dashboard), not Calendar.
| Mechanism | File | Behaviour |
|---|---|---|
| Login / register / tenant switch | lib/loginTenantFlow.ts, lib/awayCalendar.ts → resolveHomePathAfterLogin() | Always returns / (after touchAwayBaseline()) |
| Tab return / shell ready after ≥10 min away | components/Layout.tsx + lib/awayCalendar.ts | navigate('/', { replace: true }) when wasAwayLongEnoughForHome(); does not override an early nav click during module load (shouldApplyAwayHomeRedirect) |
| Away timestamp | markAppBackgrounded() on visibilitychange hidden, pagehide, logout (AuthContext) | Stored in localStorage key lyncareos_last_away_at |
Legacy name awayCalendar.ts is retained; calendar-specific landing was removed 2026-05-30.
7.1h Care Module plugins (cancer / breathing) — feature-flagged
Section titled “7.1h Care Module plugins (cancer / breathing) — feature-flagged”| Route | Slug required on patient | Notes |
|---|---|---|
/care/cancer-at-home | cancer_at_home | Cancer Board V2 — CancerTodayContextPanel (Actions for today · Your treatment — cc-card + existing pickers; no Comfort mode toggle) → status summary → Today’s care plan (day/mode-driven) → date strip → Daily status (inline 8-spoke radar; Because + Next fork) → Other cancer tasks today → Watch closely → Activated across LynCareOS → Clinic and handover |
/calendar | care board slug on patient | CalendarFocusDayPanel — action pills for the focus date from the module manifest’s calendar_actions; tapping one writes date-scoped care_tasks. CalendarDayCell shows each applied action’s manifest icon in the month grid (via GET …/calendar-actions/range). Replaced the read-only CareActionsForTodayBlock (deleted 2026-07-31). See 15-CARE-CALENDAR-COMPOSITION.md |
/care/cancer-at-home/visit-prep | cancer_at_home | Week at home, in brief — abbreviated bullet lines (story.lines); questions queue with Discussed checkboxes (visit_prep_discussed); Larger text toggle (CANC-H02 lite) |
/care/breathing | breathing_difficulties | Phase A shell + daily breathing bundle |
Enable locally (user id 1 only by default):
CARE_MODULE_BOARDS_ENABLED=trueCARE_MODULE_PREVIEW_USER_IDS=1
# frontend/.envVITE_CARE_MODULE_BOARDS=trueRestart backend and npm run dev. Apply the matching Care Profile (pack slug) to the active patient — not the care situation alone. See §7.1i.
Platform super-admin (is_super_admin): must still receive feature_flags.care_module_boards from GET /api/subscriptions/active (fixed in ModuleContext 2026-06-04). Previously boards were forced off for super-admin accounts — sidebar Cancer board and Home strips never appeared for Peter even with flags on.
Production launch (base app only): leave both board flags false / unset.
Do not add care boards to tiers.json or module_delivery.json live until product sign-off.
Cancer hub API (api.careModules in frontend/src/lib/api.ts):
| Method | Path | Purpose |
|---|---|---|
| GET | /api/patients/{id}/care-modules/board?slug= | Manifest, zone, hub — tiles[].visual, primary_cta_visual, enriched catalog.treatment_modes / today_day_types (icons) |
| POST | …/events?slug= | Capture step |
| POST | …/sessions/complete?slug= | Complete session |
| PATCH | …/settings?slug= | Hub settings (cancer_at_home only in MVP) |
| GET | …/visit-prep?slug= | Visit prep aggregate — { story, summary, settings }; story.lead / story.sublead + story.lines[] from build_visit_prep_story() (paragraphs mirrors lines) |
| GET | …/dashboard-chips?slug= | Home Cancer today chips — e.g. Infusion visit packing: 2 of 6 ready (not US “chair day” jargon) |
| GET | …/dashboard-panel?slug= | Home Care board panel — chips, actions_for_today[], treatment_modes[] for CareBoardDashboardPanel |
| GET | …/comfort-checkin/dates?slug=&days= | ISO dates with at least one comfort check-in (default 90 days) |
| GET | …/comfort-checkin/spoke-averages?slug= | Rolling mean per spoke (1–4); days = longest fallback window with data (30 → 20 → 10 → 5 → 2) |
| GET | …/comfort-checkin/week-series?slug=&anchor= | Mon–Sun merged spoke levels for the calendar week containing anchor (ISO date); powers hub status narrative |
| GET | …/comfort-checkin?slug=&date=&capture_instance_id= | Board default: merged latest value per spoke across all instances on care_date; completed if any instance on that date completed. Optional capture_instance_id scopes to one instance (tools). Response capture_instance_id = write target (instance on the most recent comfort event that day). Hub loads without the query param. |
Capture pop-ups (all FP modules): step wizards use CaptureSession → CareCaptureOverlay (frontend/src/components/care-capture/). Portals to document.body, z-[1100], scroll lock, opaque bg-canvas (not bg-background). Responsive: phone = full screen; tablet = centred card ~85% width + dim backdrop; desktop (lg+) = ~50% of main column width (min(32rem, calc((min(100vw-15rem,64rem)-4rem)/2))), centred over the board (lg:pl-60 for sidebar). Pass key={sessionId} when switching bundles. Visit prep / log dose use routes, not the overlay.
Capture layouts (manifest-driven):
layout | UX | Example session |
|---|---|---|
wizard (default) | One question per screen; review step at end | fever_pathway, chair_day_ack, tablet_safety |
stacked | All steps on one screen (overlay — legacy) | cancer_symptom_bundle, comfort_round — prefer inline radar on hub |
Daily status (inline radar, preserved in V2): CancerComfortDateStrip on CareBoardPage — pick any day; recorded days show a dot. InlineComfortCheckIn (id="cancer-daily-status", aria-label="Daily status") — CancerComfortRadar + CancerComfortRadarChart (ECharts 8-spoke radar: Energy · Pain · Eating · Breath · Mood · Sleep · Fever · Treatment). Tap a dot on any spoke to score 1–4 (centre → edge); per-spoke axis label colours; health gradient web red (centre) → amber → indigo → green (edge); comfort score 8–32 (sum of eight spoke points). Solid polygon = selected day; dashed = Past N-day average from comfortSpokeAverages() (not static targets). Maps manifest segmented_bar steps via cancerRadarConfig.ts; postStep (POST …/events) on each tap (immediate DB write). When all eight spokes are saved in UI, completeSession runs automatically (no Save daily status button). Retrospective days: changing one or two spokes still shows the full spider — GET merges latest per spoke across instances; unchanged spokes keep prior event values. After complete: tap any dot to change a score (chart stays editable). Writes send care_date + capture_instance_id from the snapshot write target. Sessions: cancer_symptom_bundle (default) / comfort_round (Comfort mode). Symptom tile hidden when inline check-in shown. Scroll: board entry and route changes scroll Layout <main> via scrollAppMainToTop / scrollAppMainToElement (not window / indiscriminate scrollIntoView).
Radar files (do not modify in V2 work): cancer/cancerRadarConfig.ts, cancer/radarTapGeometry.ts, lib/radarHealth.ts, components/CancerComfortDateStrip.tsx, components/CancerComfortRadar.tsx, components/CancerComfortRadarChart.tsx. Removed from hub: spoke pills, ComfortSpiderDiagram, side-panel level picker, hub-mounted CareFlowRail.
Cancer Board V2 model + sections (2026-06-10): Pure builders in cancer/cancerBoardV2Model.ts derive V2 UI from existing hub state (no new APIs in Phase 1). Presentational sections in cancer/components/:
| Section | Component | Builder / behaviour |
|---|---|---|
| Context (top) | CancerTodayContextPanel.tsx | cc-card wrapping CancerDayPicker + CancerModeToggle (treatment modes only); patch today_day_type / treatment_modes + scroll #cancer-today-plan |
| Status summary | CancerStatusSummary.tsx | buildWeeklyStatusCopy() in comfortWeekInsightNarrative.ts — Mon–Sun spoke insights from comfortCheckinWeekSeries(anchor = careDate) (1–7 days; per-spoke trends, deterioration questions, when-to-call hints); fallback buildStatusReason(hub, zoneLabel) only when the week has no daily status days; hub red/amber alerts prefix narrative |
Editing status narrative copy: All carer-facing insight strings live in comfortWeekInsightNarrative.ts (LEVEL_PHRASE, SPOKE_GUIDE, template rotation per spoke). Deterministic — no LLM. Priority: urgent spokes (e.g. severe breath, fever/chills) first; up to four non-duplicate sentences. Unit tests: frontend/src/test/lib/comfortWeekInsightNarrative.test.ts. Spoke concern colours on the radar use the same metadata in cancerRadarConfig.ts (including inverted fever_worry scale).
| Today’s care plan | CancerTodayPlan.tsx | buildTodayPlan(hub), buildPlanSubtitle(hub) — open by default; day/mode steps only (no daily status or breakthrough review cards — see sections below) |
| Daily status | InlineComfortCheckIn.tsx | existing radar wrapper (unchanged geometry) |
| Other cancer tasks today | CollapsibleSection #cancer-other-tasks | hub tiles (renamed from “More for today”) |
| Watch closely | CancerWatchClosely.tsx | buildWatchItems(hub) — site-aware (brain → neuro; lung/oxygen → equipment) |
| Activated across LynCareOS | CancerActivatedAcrossLynCareOS.tsx | buildActivationItems(hub) |
| Clinic and handover | CancerClinicHandover.tsx | buildClinicLines(hub, zoneLabel, zone) |
Care Flow Loop (after daily status save): Hub guides the carer without overlay layers.
| Piece | File | Behaviour |
|---|---|---|
| Flow steps | cancer/cancerCareFlow.ts | buildCancerCareFlow({ checkInDue, checkInComplete, primaryCta, dayLabel }) → { steps, nextFork }; resolvePainLogFork(painLabel, breakthroughLogRoute) after high pain spoke |
| Step rail | components/CareFlowRail.tsx | Not mounted on hub (component retained for future generic extraction) |
| Because | components/BecauseLine.tsx | Prefix “What this tells us:”; copy from buildComfortBecauseLine() (Energy + Pain labels) |
| Next fork | components/NextStepFork.tsx | Do now / Later / Skip after completeSession |
| Wiring | CareBoardPage.tsx | handlePlanAction / handleWatchAction for V2 sections; handleForkAction: session → openSession, route → navigate, expand → scroll #cancer-daily-status or open #cancer-other-tasks; refreshComfortSnapshot on date change (merged GET, no capture_instance_id param); refetch after each spoke + after auto-complete; checkinVersion remounts radar when snapshot updates |
Frontend tests: frontend/src/test/lib/cancerBoardV2Model.test.ts — run npm test -- cancerBoardV2Model.
Home dashboard panel: CareBoardDashboardPanel on / when preview flags + matching care_profile_slug. Below 540px: Care board title then icon grid; 540px+: title left, icons clustered right.
Calendar focus day (2026-07-31): CalendarFocusDayPanel on /calendar — sits under the month grid and follows the focus date, not today. Tapping a date focuses it; holding for 450ms opens the scheduling sheet as before. CalendarActionPills renders the patient’s care-module calendar_actions; tapping a pill applies its task bundle to the focus date via POST …/care-modules/calendar-actions and tapping again undoes it. Tasks are date-scoped (shift_id null when nobody is rostered) and readable through GET /patients/{id}/care-tasks?start=&end=. Action pills follow the care-module preview allow-list; the tasks they create do not. Replaced the read-only CareActionsForTodayBlock. File map: 15-CARE-CALENDAR-COMPOSITION.md.
Calendar module task responses (2026-07-31): Module tasks are not checkbox-only. Each manifest task carries prompt + response_kind; the UI renders ModuleTaskResponseButtons (Yes/No, Taken/Not taken/N/A, Arranged/Not yet arranged, etc.). Answers persist with PATCH /api/care-tasks/{id} { "response_code": "<code>" } — requires V027 on dev (.\migrate.ps1 -Target Dev). Option sets: backend/care_modules/calendar_task_responses.py and frontend/src/lib/calendarModuleTaskResponses.ts (keep in sync). After changing Pydantic fields, run OpenAPI export + npm run generate:types. Rows created before V027 lack response_kind until the action is re-applied on that date.
Calendar month grid — care-module icons (2026-07-31): When a pill is applied, CalendarDayCell renders the action’s icon key (same mapping as the home care-board strip: careProfileIcon / CARE_PROFILE_ICON_MAP in care-modules/shared/careProfileVisual.ts). useCalendarModuleActionsRange loads GET /api/patients/{id}/care-modules/calendar-actions/range?slug=&start=&end= once per displayed month; careModuleDayIconKeys() in lib/calendarViewHelpers.ts picks applied actions for each ISO date (fallback: careModuleSlugIconKey() when module tasks exist but the range call has not run). Up to CAL_DAY_MODULE_ICON_LIMIT (5 in lib/calendarPageConstants.ts — matches the five calendar_actions on cancer_at_home; raise when a module ships more day types). Below Tailwind lg (CALENDAR_DAY_CELL_COMPACT_MODULE_ICONS_QUERY, max-width 1023px — phones and tablets), careModuleDayIconsForViewport() shows one module icon (careModuleSlugIconKey) whenever any action is applied; lg+ (desktop) shows one icon per applied action. General free-text / shift tasks still use the ClipboardList marker via dayActivityIndicators() (now includes date-scoped tasks from listForRange, not only shift-attached rows). Pill apply/undo refreshes the range through CARE_CALENDAR_ACTIONS_CHANGED and the focus-day onTasksChanged hook.
QA (Cancer Board V2): Load /care/cancer-at-home → page opens at top (title), not mid-board → confirm Actions for today + Your treatment at top (cc-card pickers) → tap a day type → Today’s care plan updates and page scrolls to it → toggle a treatment mode → plan gains/loses mode steps → pick today on date strip → tap all eight spokes → What this tells us / Next fork appear after auto-complete → tap a plan step or watch-row action → Other cancer tasks today expands when fork/plan directs there. Pick a past day with data → change one spoke → confirm all eight spokes still render. Tap a spoke again — score updates without a separate “another check-in” button.
Mockup: support-flow-mockup.html. Extraction (later): generic rail/fork moves to care-modules/shared/ after Cancer sign-off.
Widgets: traffic_light_3, emoji_face_5, segmented_bar (overlay / tile sessions). Configure in manifests/{slug}.json → capture_sessions.
Care board routes: CareModuleRoutes.tsx wraps each lazy page in Suspense (PageLoadingSpinner) + ErrorBoundary (labelled fallback, e.g. “Cancer board unavailable”). Layout also wraps <Outlet> in Suspense — belt-and-braces for lazy chunks.
Dev QA: After editing CareBoardPage.tsx, if Vite logs Could not Fast Refresh (export removed), hard-refresh (Ctrl+Shift+R) or restart npm run dev before retesting /care/cancer-at-home.
Pattern for new plugins: add care-modules/{slug}/CareBoardPage.tsx, entry in registry.ts, manifest JSON under backend/care_modules/manifests/, route in CareModuleRoutes.tsx — all behind the same flags. Optional hub service + care_module_patient_settings row per slug. Hub pages should default missing hub.* arrays (tiles, modes, alerts) to [] and show useCareBoard().error when the board API fails. New capture bundles: add capture_sessions in manifest JSON only (optional "layout": "stacked", per-step "widget": "segmented_bar"); UI reuses CaptureSession. Cancer check-in: _primary_cta() default → cancer_symptom_bundle; gentle/palliative → comfort_round; visit prep counts both session ids.
7.1i Care situation vs Care Profile (common QA confusion)
Section titled “7.1i Care situation vs Care Profile (common QA confusion)”| Layer | UI label | Example | Persisted on patient | Loads labels / boards |
|---|---|---|---|---|
| Care situation | Archetype card (“✓ Selected”) | The Breath-by-Breath | patients.archetype_id | No — story classifier only |
| Care Profile | Pack apply / dropdown | Breathing difficulties, Cancer at Home | patients.care_profile_slug, care_start_applied_at | Yes — apply_care_start_pack() |
Where to apply a profile
| Flow | Path |
|---|---|
| New person | People in care → Add Person → PatientCareStartWizard (demographics only) |
| Existing person | No family UI — use dev QA panel or PATCH …/care-pattern / POST …/care-start until workflow redesign |
| Dev one-tap (user id 1 only) | Person detail → Care profile QA (dev) panel → Breathing / Cancer buttons |
Day-one bootstrap (care_start_bootstrap.py): On new person create → four medication time slots (08:00, 12:00, 20:00, 00:00). On Care Profile apply → same slots (idempotent) + sample Paracetamol (pain) on paid packs (price_aud > 0, not free starter) + profile shopping lists with suggested items (SHOPPING_LISTS_BY_PACK_SLUG in seed_catalog.py; visible on Complete /shopping). Surfaces: Medication schedule, Log a dose, Shopping. Not the Care Module board tiles in FP specs (those are Phase B+).
Setting patients.archetype_id (API or future UI) does not load labels or boards until a Care Profile is applied. Boards need care_profile_slug ∈ { cancer_at_home, breathing_difficulties } plus preview flags (§7.1h).
7.1j Peter tenant — Care Profile + board QA (dev)
Section titled “7.1j Peter tenant — Care Profile + board QA (dev)”For manual testing on tenant slug peter (login as Peter, choose peter — not test-card-*):
.\scripts\seed-dev-peter-care-qa.ps1Script: backend/scripts/seed_dev_peter_care_qa.py (idempotent). It:
- Activates
condition_templatesandcustom_observationsonpeter(Subscriptions shows all Care Profile cards) - Grants admin_grant access to all active packs
- Ensures QA — Breathing board and QA — Cancer board people with profiles pre-applied
After seed: hard refresh or re-login → Subscriptions → switch active person to a QA row → Home → Open care board chip (user id 1, flags in §7.1h). Sidebar also shows Cancer board / Breathing board when the active person has the matching care_profile_slug.
If schedule / shopping are empty but reason codes exist: profile was applied before day-one bootstrap shipped. Re-apply the pack (dev QA panel or API), re-run .\scripts\seed-dev-peter-care-qa.ps1, or:
cd backendpython -m scripts.backfill_care_bootstrapWhere to see each layer (QA Cancer):
| Layer | Route / UI |
|---|---|
| Cancer hub (Board V2) | /care/cancer-at-home — context panel + status summary + Today’s care plan + date strip + Daily status (8-spoke radar) + Other cancer tasks + Watch closely + Activated across LynCareOS + Clinic and handover |
| Visit prep | /care/cancer-at-home/visit-prep — abbreviated week summary; show phone at desk |
| Home discovery | CareBoardDashboardPanel on Dashboard + sidebar Cancer board |
| Medication time slots + sample med | Scheduled Doses (/medication-schedule) — Care Start bootstrap |
| Profile shopping lists | Shopping (/shopping) — Complete tier / shopping module |
| PRN reason codes | Log a dose, More → Reason codes |
Cancer MVP (Part 5) ships: visual hub, infusion visit packing, fever pathway, visit prep + discussed toggles, dashboard strip, calendar oncology appointment_type (V016) with hub day sync, breakthrough /log deep link + tile sparkline, primary-site tips, comfort override banner. Still not shipped: full B–H workflows, deep site modules (CANC-T02–T12), radiation/immuno irAE tiles — see FP-cancer-at-home.
Cancer hub layout (Board V2): Header — patient name + cc-btn-soft Home; title row + CancerPrimarySitePicker (right). Body — CancerTodayContextPanel (cc-card; CancerDayPicker + CancerModeToggle — sets today_day_type / treatment_modes; scrolls to plan; day/treatment pills colour-coded; plan step left border matches linked pill) → CancerStatusSummary (weekly spoke insight for Mon–Sun week of selected careDate) → CancerTodayPlan (open; buildTodayPlan / buildPlanSubtitle — day-type + mode steps only) → optional comfort override + site tip → CancerComfortDateStrip → InlineComfortCheckIn / Daily status (8-spoke ECharts radar; per-tap save + auto completeSession; past N-day average overlay) → BecauseLine (What this tells us:) + NextStepFork → CollapsibleSection: Other cancer tasks today (#cancer-other-tasks) → CancerWatchClosely (includes breakthrough pain row) → CancerActivatedAcrossLynCareOS → CancerClinicHandover.
Comfort mode (gentle_mode): Backend setting still affects tile visibility, comfort override banner, and comfort-first plan when active — but no UI toggle on the hub context panel (removed 2026-06-10). Distinct from the Comfort / palliative focus treatment-mode chip. Backend copy: GENTLE_MODE_COPY in cancer_defaults.py.
Hub tile telemetry: cancer_board_visual.enrich_tiles() — infusion/line progress; symptom due/last; breakthrough 24h/7d + last_dose + 7d sparkline; breakthrough tile routes via hub.breakthrough_log_route (/log?reason_type_id=…&source=cancer); secondary Week story → visit prep.
Calendar ↔ hub (CANC-B01 lite): AddShiftForm optional oncology type chips → POST /patients/{id}/appointments with appointment_type. Hub reads today’s typed appointments → today.calendar_suggested_day_type, today.effective_day_type (manual Actions for today selection wins when today_day_type is not none); calendar suggestion also appears as a step in CancerTodayPlan.
Log a dose — Cancer context: LogDose.tsx reads ?reason_type_id= or ?reason=breakthrough&source=cancer and pre-selects reason chip; shows banner when source=cancer.
Analytics (Cancer): GET /api/analytics/by-reason?reason_pattern=breakthrough&patient_id=; GET /api/analytics/care-module-events?slug=cancer_at_home&patient_id= — hub also embeds metrics.breakthrough_trend_7d / checkin_trend_7d.
Tests: backend/tests/test_care_modules_cancer.py (7 cases incl. breakthrough route, calendar sync); backend/tests/test_visit_prep_narrative.py; backend/tests/test_cancer_board_effects.py.
7.1k Reason codes — per patient (V014)
Section titled “7.1k Reason codes — per patient (V014)”PRN reason types are not a shared tenant catalogue. Each row in reason_types has patient_id (required after V014).
| Surface | Behaviour |
|---|---|
| API | GET /api/reason-types?patient_id={id} — required; ensure_patient_access |
| Care Start apply | apply_care_start_pack() inserts missing labels for that patient only |
| Tier limit | max_reason_types counts per person in care, not per household |
| Log a dose / History | api.reasonTypes.list(activePatient.id); clears selected reason on patient switch |
| More → Reason codes | Admin UI scoped to active patient from header switcher |
Medical descriptions (V013): pack_reason_types.description and reason_types.description for cancer_at_home and breathing_difficulties — source REASON_MEDICAL_DESCRIPTION_BY_PACK in seed_catalog.py. Shown on Reason codes admin, Log a dose (selected chip), and pack Preview modal.
Do not call GET /api/reason-types without patient_id — returns 422.
7.1g Auth branding and in-app brand assets
Section titled “7.1g Auth branding and in-app brand assets”Unauthenticated routes and the desktop sidebar share the Calm Care login mockup pattern — illustrated backdrop, Heartmark 2, tri-colour wordmark — not the legacy glossy in-app PNG icon.
| Asset / component | Path | Use |
|---|---|---|
| Heartmark 2 | frontend/public/brand/lyncareos-heart-mark.png | Login, register, desktop sidebar, mobile top bar, Getting Started hero back-layer |
| Auth backdrop (portrait + wide) | auth-welcome-bg-portrait.png, auth-welcome-bg.png | AuthWelcomeBackdrop — portrait on phones, wide on sm:+ |
| Getting Started hero | getting-started-hero.png | Welcome block on GettingStarted.tsx |
| Tab favicon + PWA icons | favicon.ico, favicon-16/32/48.png, icons/icon-192.png, icons/icon-512.png | Browser tab + iOS home screen + manifest — same cache ?v= in index.html and manifest.json |
| Tri-colour wordmark | components/brand/BrandWordmark.tsx | Lyn #2b3138 · Care #1f9dec · OS #2cbebe — auth + desktop sidebar + mobile top bar |
AuthShell / AuthBrandHeader / AuthIconField | components/auth/ | Column layout · mark + wordmark + tagline · icon-inset fields |
| Glossy app icon (PNG) | BRAND_APP_ICON_SRC in lib/brandAssets.ts | Legacy in-app reference — not login/sidebar |
| Line-art house mark (legacy) | lyncareos-login-mark.png | Superseded on login by Heartmark 2; retained in repo |
Asset regenerators (frontend/scripts/ — rerun after changing a source in Branding/):
| Script | Source | Output |
|---|---|---|
build_brand_mark.py | Branding/lyncareos-heart-mark-2.png | public/brand/lyncareos-heart-mark.png |
build_auth_bg.py | generated landscape art | auth-welcome-bg[-portrait].png |
build_gs_hero.py | gs-hand-element-raw.png + heart mark | getting-started-hero.png |
build_favicon.py | Branding/lyncareos tab icon.png | favicon.ico, favicon-16/32/48.png, icons/icon-192.png, icons/icon-512.png |
build_login_mark.py | Branding/LyncareOS house icon.png | lyncareos-login-mark.png (legacy) |
Auth pages keep the light welcome backdrop when the app shell is in dark mode.
Constants live in frontend/src/lib/brandAssets.ts (cache-bust with ?v= on change).
Pages: Login.tsx, Register.tsx (extend PendingApproval.tsx when restyled).
Sign-in uses cc-btn-primary + arrow; Google button label Continue with Google
(GoogleSignInButton text="continue_with").
Reference mockup: docs/02 - ARCHITECTURE_DESIGN/assets/calmcare/lyncareos-login-onboarding.png.
Getting Started: /getting-started (admin-only shortcut on More; 8-step checklist).
Brand touchpoint parity (mandatory when changing logo/wordmark):
| Surface | Component / file |
|---|---|
| Login / register | AuthBrandHeader.tsx |
| Desktop shell | DesktopSidebar.tsx |
| Mobile shell | MobileTopBar.tsx |
| Browser tab | favicon.* + index.html |
| PWA / iOS home screen | icons/icon-192.png, icons/icon-512.png, manifest.json |
Automated gate: cd frontend && node scripts/check-brand-touchpoints.mjs (also runs in npm run validate:architecture and deploy.ps1 before npm run build). Do not deploy after updating only one surface — the 2026-05-30 mobile miss was incomplete implementation, not a deploy-script bug; deploy.ps1 faithfully shipped the repo as-is.
7.2 Components
Section titled “7.2 Components”- Prefer named
functioncomponents at module level; keep hooks unconditional at the top. - Tailwind + shared classes in
index.css(btn-primary,card,nav-link, …). See 03-DESIGN-SYSTEM.md. - Dark mode:
classstrategy on<html>viaThemeContext— pairdark:variants with light styles.
Week at a glance helpers (frontend/src/lib/weekGlanceHelpers.ts, tests in weekGlanceHelpers.test.ts):
Pure functions for the Dashboard WeekAtAGlance widget (components/dashboard/WeekAtAGlance.tsx). Keep all Monday-based week maths and per-day aggregation here — the component only fetches and renders.
weekDaysForOffset(offset, today?)— sevenDateobjects (Mon→Sun) for current/adjacent weeksmonthsTouchedByWeek(days)— distinct{ year, month }pairs when a week straddles a boundary (drives dual month fetches)formatWeekRangeTitle(days)— compact caption (25–31 May,29 Jun – 5 Jul, …)buildWeekGlance(days, shifts, appointments, today?)— per-day shift/appointment counts +carerChips(deduped bycarer_id, ordered by time slot)carerChipLetter(carerName, displayName)— first letter of login username, fallback display nameWEEK_GLANCE_MAX_CARER_CHIPS = 2— max initials shown per day cell (+ overflow badge)
Widget fetches via api.shifts.list + api.appointments.list for each month touched, merges with dedupeById, and navigates to /calendar?date= on day tap. Gated on Dashboard by care_calendar module (or super-admin). Footer uses truncate whitespace-nowrap on the summary so Open calendar stays aligned on one row on mobile.
Calendar scroll-anchor pills (frontend/src/pages/Calendar.tsx):
Filter pills (All, Appointments, Tasks, Handovers) are scroll anchors, not content filters — every list section stays mounted. handleCalFilterClick calls computeRegionScrollTop to place the target region under the sticky dock; a trailing spacer (scrollSpacerPx) lets the last section scroll fully into view.
Shared day date strip (frontend/src/components/ui/DayDateStrip.tsx):
Horizontal month ribbon used on date-scoped pages — swipe/scroll days, prev/next month, Today jump, emerald dot when daysWithData contains that ISO date. Helpers in lib/dateStripHelpers.ts (selectableDaysInMonth, updateDaysWithDataSet, localTodayIso).
| Wrapper | Page / widget | Labels |
|---|---|---|
components/pain/PainDateStrip.tsx | Pain & Stats | “with pain” |
components/vitals/VitalsDateStrip.tsx | Vital Signs | “with vitals” |
components/medication-schedule/MedScheduleDateStrip.tsx | Medication Schedule (/medication-schedule) | “with doses” |
Direct DayDateStrip | Dashboard ScheduledDosesStrip | “with doses” |
Do not build a one-off week picker for these flows — use DayDateStrip (or a thin preset wrapper). The dashboard This week widget (WeekAtAGlance) is the exception: it uses weekGlanceHelpers for Mon–Sun week navigation, not DayDateStrip.
Vital Signs — intake/output capture (mobile-first) (components/vitals/*, page VitalsTracking.tsx):
| Topic | Where | Notes |
|---|---|---|
| Presentation stack | 14-FRONTEND-PRESENTATION-STACK.md | Canonical tools + component map |
| Mobile breakpoint | hooks/useMatchMedia.ts | useVitalsCaptureMobile() → max-width: 639px |
| Chart mobile | useChartMobileLayout() | max-width: 767px; shared intakeOutputChartBase() in lib/chartTheme.ts |
| Capture sheet | VitalsCaptureSheet.tsx + StickyActionBar.tsx | Full-screen on mobile; inline cc-surface-float on desktop |
| Urine beaker | UrineVolumeBeaker.tsx + urineBeakerConstants.ts | Do not change interior geometry / shell PNG after sign-off |
| New capture defaults | lib/urineCaptureDefaults.ts | urineCaptureDefaults() — keep out of component file for fast refresh |
| Motion | motion/react + usePrefersReducedMotion.ts | Sheet enter, colour knob layoutId, volume number; no Motion on slider thumb drag |
| Theme tokens | lib/vitalsTheme.ts | VITALS_CAPTURE_CARD, section icon classes |
| E2E smoke | e2e/vitals-capture-mobile.spec.ts | Viewport 390×844 |
| a11y | e2e/a11y.spec.ts | Includes /vitals route |
Quality gates before merge (vitals UI):
cd frontendnpm run validate:architecturenpm run lint:strictnpm run testnpm run buildnpm run test:a11y # requires dev stack + Playwright auth envMedication Schedule — Calm Care pill organiser (pages/MedicationSchedule.tsx):
Presentation helpers in lib/medScheduleCalmCare.ts (slotVisualMeta, slotGivenProgressLabel) map time slots to Morning/Midday/Evening/Night icons only (no daypart background tints). Slot cards use standard cc-card + shadow-soft: 4px left border is sage-500 when all scheduled doses for that slot are recorded for the day, otherwise the admin-assigned group color_hex. Per-medicine round status circles: pending/overdue show the scheduled dose_amount via ScheduleDoseCircleLabel (components/medication-schedule/ScheduleDoseCircleLabel.tsx); dispensed shows a sage check. Coral ring = overdue. Footer legend: sample number in circle = scheduled pending; sage tick = dispensed. Batch record uses the sky-gradient circle in the slot header. Date navigation uses MedScheduleDateStrip; daysWithDoses is loaded from GET /dispensings?date_from=…&date_to=… (90-day window, same pattern as ScheduledDosesStrip). PRN block is a normal cc-card with an amber left-border accent. CellSheet saves dose via addItem / updateItem; handleCellSaved merges into groups[].items so the circle updates without a full reload.
Unified Medications page (pages/Scripts.tsx, nav label Medications, route /scripts):
Prescriptions and tenant medicine catalogue share one surface — MedicationCard shows Doses available (summary.total_stock_on_hand from medicine-summary — same for active and exhausted) Last counted when last_physical_count_at is set (LastPhysicalCountLine), plus the countdown bar (stockCountdownBar() in lib/scriptStock.ts). When status === 'exhausted', show EXHAUSTED_REPEATS_LABEL; do not strike through the medicine name (strikethrough only for archived / superseded). Stock numbers come from the API only (services/script_stock.py); do not use totalDispensedFromScript() for production UI. After Log Dose, dispensingsEvents triggers notifyScriptsChanged() so the card refreshes. FillModal (record_fill) sets server baseline to prior on-hand + quantity_added; preview On hand after collection — historical dose log does not reduce a new pack. MedicineModal handles catalogue fields. Admin manual dose shortcuts (ManualDoseShortcutsSection.tsx) sit at the top (max 4). Legacy /admin/medicines → /scripts.
Stock data sources: List card reads GET …/scripts/medicine-summary; edit modal uses PatientScript from GET …/scripts (total_dispensed on enriched script rows). dispensingsEvents calls notifyScriptsChanged() after Log Dose / schedule dispense so Medications stock lines refresh.
ScriptDetail: Archive retires a prescription; stock block shows doses available, countdown bar, LastPhysicalCountLine. EditScriptModal: PATCH pills_available; field label DOSES_ON_HAND_PROMPT; numeric fields via lib/numericField.ts. ?setup=stock (and Care alerts prescription_stock_count deep link) opens edit for admins with emphasizeStockField — modal scrolls to DOSES_ON_HAND_PROMPT and shows an amber highlight when on-hand is 0 or needsStockCountGuidance(script). Same highlight when opening edit from Medications at zero on-hand (scroll only when emphasizeStockField). Prescription computed banners: Ignore 3 days (V105/V114); Home refetch via scriptsEvents.ts. Care alerts bell lists prescription_stock_count for admins only; saving a positive on-hand count clears the row without Mark done. Members use inline StockCountGuidancePanel on Log Dose / schedule.
Log a dose — Calm Care manual entry (pages/LogDose.tsx):
Stacked section cards via components/logDose/LogDoseSection.tsx for When, Dose amount, and Reason. Medicine is a plain heading plus a 2×2 grid of per-patient quick-pick pills with an optional Other medicines dropdown below. Quick picks are configured in place — the Edit quick picks / Choose quick medications link beside the Medicine heading opens LogDoseQuickMedsModal (max 4, GET/PATCH /api/patients/{id}/log-dose-settings, persisted to patients.manual_dose_quick_script_ids). There is no Medications settings screen for this; the log-dose link is the only entry point. On desktop Log a dose is itself a pop-up (LogDosePageShell, z-sheet), so the quick-picks dialog must stay on the z-dialog rung — see 04-OVERLAY-REGISTER.md §Stacking ladder. Cancer hub deep link: URL params reason_type_id, reason=breakthrough, source=cancer pre-select the breakthrough reason chip and show a context banner. When needsStockCountGuidance(script) (0 on hand but dose log or fills show activity), StockCountGuidancePanel on the form explains the mismatch — dose logging is not blocked; admins get Update doses on hand → /scripts/{id}?setup=stock. After Record dose, the success view refetches the script and shows the same panel when guidance still applies; admins see a note that Home / Medications also show the stock_count_needed banner. stock_count_needed requires dose log > 0 — not shown when both on-hand and dose log are zero. Dose amount via centred +/− stepper (lib/logDoseHelpers.ts). Primary action cc-btn-accent “Record dose”.
Shopping — Calm Care list + add-items sheet (pages/Shopping.tsx, components/shopping/*):
| Surface | Key files | Notes |
|---|---|---|
| Active list | ShoppingListRow.tsx, ActiveItemList.tsx, SwipeActionRow.tsx | Rows inside cc-card. Desktop: rounded-xl icon well, inline ± quantity, sage purchase check, remove. Mobile (≤639px): wrap row in SwipeActionRow — swipe right Purchased, swipe left Remove; qty via tap → BottomSheet stepper. Do not add a fifth inline control on mobile. |
| List state | Shopping.tsx | After fetchLists, reconcile activeListId against server lists; reset list/item state on patientId change. On item fetch 404 (“Shopping list not found”), re-fetch lists — do not leave a stale tab id pointing at a deleted list. |
| Add flow | AddItemsSheet.tsx, CategoryBrowser.tsx | Mobile apricot FAB / desktop dashed Add items opens BottomSheet. Search + category browse live in the sheet only. Category picker: compact cc-card tiles (rounded-2xl). Subcategory filters: compact horizontal cc-chip row (!min-h-[30px], text-xs, 14px icons). |
| Catalog tiles | CatalogItemTile.tsx, CatalogAddProductTile | Uniform picker cards: rounded-2xl surface, fixed 34×34 rounded-xl icon well + 10px two-line label. Grid constants (CATALOG_TILE_GRID, CATALOG_TILE_ICON_PX, CATALOG_TILE_ICON_WELL_EXTRA) exported from the same module — import for any new browse/search grids. |
| Icons | IconResolver.tsx | Resolves emoji → svg/url raster → substitute → cart. Catalog pickers (CatalogItemTile, PurchasedTile, CategoryBrowser) must pass loadPriority="eager". On mount, sync rasterReady from img.complete && naturalWidth > 0 so cached assets are not left at opacity-0 behind the pulse placeholder. |
| List tabs | ShoppingListTabs.tsx | cc-chip row inside a soft card. |
| Purchased history | PurchasedSection.tsx, PurchasedTile.tsx | Collapsed by default; expanded horizontal strip of tiles matching CatalogItemTile proportions (imports CATALOG_TILE_* constants — do not reintroduce legacy tinted catalogListTileScheme cards or full-bleed square photos). |
| Dashboard nudge | ShoppingDashboardWidget.tsx | Calm Care card on Dashboard.tsx when shopping module enabled. |
| Legacy / tests | ShoppingItemCard.tsx | Tile grid retained for unit tests — do not wire back as the primary list UI. |
Real-time sync: hooks/useShoppingSync.ts (SSE shopping_list_updated). Product spec: 06-SHOPPING-MODULE.md · Design: 03-DESIGN-SYSTEM.md §8.
Rule: All catalog add/search grids in the add-items flow must use CATALOG_TILE_GRID so every product tile stays the same cell size. Shopping card surfaces use rounded-2xl / rounded-xl wells — do not use circular .cc-icon-chip on list rows, catalog tiles, or category pickers; reserve .cc-chip for horizontal filter rows (list tabs, subcategories).
7.3 Types and OpenAPI contracts (REQ-PLAT-10)
Section titled “7.3 Types and OpenAPI contracts (REQ-PLAT-10)”Pipeline (run after backend model or route schema changes):
cd backendpython scripts/export_openapi.py # writes openapi/openapi.json
cd ..\frontendnpm run generate:types # writes src/lib/api.types.tsnpm run check:types-drift # fails if api.types.ts is staleCommit openapi/openapi.json and frontend/src/lib/api.types.ts together. CI job openapi-contracts enforces both with git diff.
| File | Role |
|---|---|
openapi/openapi.json | Committed OpenAPI export (offline input for generation) |
lib/api.types.ts | Auto-generated — never hand-edit |
lib/api.contracts.ts | Stable export type X = Schema<'X'> aliases; add new aliases here |
lib/api.ts | request() helpers; import type from contracts for types used inside this file, plus export type { … } for consumers |
Rules:
- New request/response shapes: add or extend Pydantic models in
backend/models.pyand wireresponse_modelon routes when possible, then re-run export +generate:types. - Do not redefine in
api.tsa shape that already exists inapi.contracts.ts/ OpenAPI — alias it instead. - Response-only shapes not yet in OpenAPI (no
response_model) stay as manual interfaces inapi.tsuntil the backend exposes them in the schema. - Domain splits under
lib/types/<domain>.tscontinue (Phase 0 H-07). Request bodies intypes/care.tsnow come fromapi.contracts.ts(ShiftCreate,AppointmentCreate, …). Entity types without OpenAPI schemas (CareShift,PatientAppointment) remain manual.
When adding types in api.ts, use both import type (local scope for request<T>()) and export type (for other modules). Re-export-only blocks do not satisfy tsc inside api.ts. Run cd frontend && npm run build before scripts/deploy.ps1.
7.4 Production deploy (VPS)
Section titled “7.4 Production deploy (VPS)”From repo root:
.\scripts\push-to-production.ps1 # default — dev + Docker UAT + VPS (see doc 20 §2b).\migration-audit.ps1 -Target Vps -NonInteractive # repo vs live schema_migrations.\scripts\deploy.ps1 # VPS only — build, backup, push, migrate on startup, smoke test7.4a Where the SPA is cached (browser vs Cloudflare)
Section titled “7.4a Where the SPA is cached (browser vs Cloudflare)”| Surface | Serves from | Invalidation on app deploy |
|---|---|---|
app.lyncareos.com | VPS Docker (backend/main.py static + API) via Cloudflare Tunnel | Automatic — see below |
lyncareos.com marketing | Cloudflare Pages | Separate — scripts/deploy-marketing-pages.ps1 |
The clinical SPA is not on Cloudflare Pages. Do not run a Cloudflare cache purge for app UI releases — the pipeline below handles it:
- Hashed bundles — Vite emits new
assets/*.js/*.cssfilenames each build. - Service worker version —
frontend/scripts/inject-sw-version.mjsreplaces__BUILD_ID__in builtsw.jssoCACHE_NAMEchanges every build. - Origin headers —
backend/main.pysetsno-cache, no-store, must-revalidateonindex.htmlandsw.jsso Cloudflare/browser revalidate every request. - Client reload —
frontend/index.htmlregisters the SW, pollsreg.update()every 5 minutes and on tab visibility, and callssafeReload()onSW_UPDATED/controllerchange(deferring while the user is typing in a form).
/api/* is network-only in the service worker — data is always fresh from the API.
7.4b Post-deploy verification (required for screen/UI releases)
Section titled “7.4b Post-deploy verification (required for screen/UI releases)”After deploy.ps1 completes, verify before announcing the release:
curl.exe -s https://app.lyncareos.com/sw.js | Select-String CACHE_NAMEcurl.exe -sI https://app.lyncareos.com/ | Select-String -Pattern "cache-control|cf-cache-status"curl.exe -s -o NUL -w "%{http_code}" https://app.lyncareos.com/api/billing/tiersCACHE_NAMEmust differ from the previous deploy — unchanged hash means mid-session users may not auto-refresh.index.htmlmust returnCache-Control: no-cache, no-store, must-revalidate.- Mid-session smoke (optional but recommended): keep a tab open before deploy; after deploy, navigate to a lazy route — expect a brief reload, not a stale-chunk error card.
Full checklist: 20-PRODUCTION-DEPLOYMENT-GUIDE.md §6. Background: docs/plans/2026-05-29-spa-deploy-resilience.md.
7.4c Local deploy pipeline vs production
Section titled “7.4c Local deploy pipeline vs production”push-to-production.ps1 runs on the workstation. If it hangs during Docker UAT backup (db-backup.ps1), production is unchanged until deploy.ps1 step 5 finishes on the VPS. Recover by stopping the local PowerShell process and fixing Docker Desktop — do not kill production containers outside the normal vps-pull-and-start.sh --redeploy path inside deploy.ps1.
If the release includes V090+ and production has not been backfilled: .\scripts\production-migration-preflight.ps1 -RunBackfillIfNeeded runs automatically inside deploy.ps1, or run it manually first.
After first PHI backfill without explicit keys: .\scripts\production-phi-pin.ps1 on VPS (also runs at end of deploy.ps1 when keys are missing); on dev, .\scripts\dev-phi-pin.ps1 for backend/.env.
If email login fails after pinning PHI keys (username login still works): run python seed_admin.py or python -m migrations.scripts.repair_phi_email_indexes from backend/. See ../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md §401 email after PHI.
V1 baseline cutover (brownfield → squashed schema): one-time per environment — dev: .\scripts\v1-baseline\Invoke-V1Cutover-Dev.ps1; production: .\scripts\v1-baseline\Invoke-V1Cutover-Vps.ps1 (includes deploy + backup). Runbook: 24-V1-DATABASE-BASELINE-AND-CUTOVER.md. Normal releases after cutover use deploy.ps1 + forward V00N__… migrations only.
See [04 - OPERATIONS/11-DATABASE-SAFETY-AND-MIGRATIONS.md §7](../04 - OPERATIONS/11-DATABASE-SAFETY-AND-MIGRATIONS.md) and 03%20-%20DEPLOYMENT%20AND%20PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md §5.
- Avoid
any; use explicit interfaces andunknownwith narrowing where needed.
Scripts API (api.scripts in lib/api.ts — post-V103 medication surface):
| Method | Endpoint / helper | Use when |
|---|---|---|
list(patientId, …) | GET /api/patients/{id}/scripts | All carer-facing pages — Medications list, schedule matrix, Log Dose picker, chart legend |
create / update / … | POST|PATCH /api/patients/{id}/scripts | New or edit prescription (name, colour, PRN, fills) |
medicineSummary / alerts | GET …/medicine-summary, …/alerts | Stock/expiry summaries on Medications page |
Rule: Scope every call by patient_id from PatientContext. Reload when activePatient?.id changes. Schedule/dispense use api.medicationGroups and script_id on schedule items — not medicine_id.
Frontend regression: frontend/src/test/components/MedicationSchedule.test.tsx (calls listForPatient with active patient id, never the tenant-wide list).
Shared Core Principles (alerts, realtime, hooks)
Section titled “Shared Core Principles (alerts, realtime, hooks)”Care alert surfaces — when to use which
| Surface | Use when | Examples |
|---|---|---|
Team inbox (care_alerts + bell) | Cross-module operational item the care team should see and resolve | Shopping list count, overdue dose, script stock count (admin), help board |
In-page banner (/scripts/alerts, etc.) | Contextual guidance on the page the user is already on | Script stock count prompt on Medications; member-visible; per-user dismiss |
| Both | Same domain condition, different audience/UX | Script stock: bell (admin inbox) + banner (all roles on Scripts) — share script_stock_evaluator, do not merge UI |
Realtime — SSE vs CustomEvent
| Mechanism | Use when | Examples |
|---|---|---|
| Redis SSE | Multi-device / multi-user sync for one patient scope | Shopping list (useShoppingSync) |
| Postgres NOTIFY SSE | Long-running job progress | Prescription scan queue |
| Browser CustomEvent | Same-tab cache invalidation after mutation | SCRIPTS_CHANGED_EVENT, DISPENSINGS_CHANGED_EVENT → refresh bell count, Scripts list |
Care alert modes
| Mode | Behaviour | Examples |
|---|---|---|
| sync | Recompute domain state; upsert or auto-resolve when cleared | shopping, overdue_dose, prescription_stock_count |
| event | Fire on mutation; dedup per entity | pain, mind, calendar, help, shift cancel |
| scheduled | APScheduler triggers sync/raise | shift reminder, overdue hourly sweep |
Adding a new alert type (target pattern)
- Register a handler in
services/alert_registry.py(signal type → handler config). - From domain code, call
emit_alert_signal(AlertSignal(...))after HTTP commit — do not callalert_servicedirectly from new code. - Sync handlers: one open row per dedup key; use
auto_resolve_by_dedupwhen condition clears. - Document channel key in
tenant_notification_settingsandAlertSettings.tsxif tenant-toggleable.
Alert-type inventory (current)
| alert_type | mode | channel | dedup_key | delivery | emit signal / call site |
|---|---|---|---|---|---|
shopping | sync | shopping | shopping:{patient_id} | background | shopping.changed ← shopping_service |
overdue_dose | sync | overdue_dose | overdue_dose:{patient_id}:{dose_date} | background + cron | dose.dispensed, scheduler sweep |
prescription_stock_count | sync | master only | prescription_stock_count:{patient_id}:{script_id} | background | script.stock_changed |
body_pain_high | event | body_pain_high | body_pain_high:{patient_id}:{date} | background | pain.recorded |
mind_elevated | event | mind_elevated | mind_elevated:{patient_id}:{date} | background | mind.recorded |
calendar_events | event | calendar_events | calendar_events:{patient_id}:{entity_id}:{date} | background | calendar.changed |
handover_notes | event | handover_notes | handover_notes:{shift_id} | background | shift.handover |
shift_cancelled | event | shift_cancelled | shift_cancelled:{shift_id} | background | shift.cancelled |
shift_reminder | scheduled | shift_reminder | shift_reminder:{patient_id}:{carer_id}:{date} | scheduled | APScheduler |
new_help_request | event | family_help | new_help_request:{request_id} | background | help.created |
help_request_taken | event | family_help | help_request_taken:{request_id} | background | help.taken |
module_purchase_request | event | module_purchase_requests | module_purchase_request:{module} | background | module.purchase_requested |
Post-commit runner: schedule_after_commit in services/post_commit.py (pool connection via alert_tasks.run_alert_task).
Care alerts API (api.alerts in lib/api.ts — paths are without /api; see §7.1):
list({ status, patient_id, limit })—GET /api/alertsopenCount(patientId)— badge count for active patient;AlertContextpolls every 60s and onscriptsEvents/dispensingsEventsresolve(id, note?)—POST /api/alerts/{id}/resolve(carers/admins only — observers get403)getSettings()/updateSettings(patch)—GET|PATCH /api/admin/alert-settings(tenant admin; includesfamily_helpchannel)
Alert types in UI (AlertRow.tsx): shift/calendar/handover/shopping/pain/mind/overdue dose; prescription_stock_count (Pill icon, admin-only in list/count); new_help_request and help_request_taken (HandHeart icon). prescription_stock_count deep_link → /scripts/{id}?setup=stock&patientId={id}; sync via alert_script_sync.py after dispense or pills_available PATCH. Overdue dose shows one inbox row per patient per day; when metadata.miss_count > 1, a numeric badge appears beside the title (body text also states the count, e.g. “3 scheduled doses not recorded”). Shopping shows one inbox row per patient; body states the live active-item count (e.g. “4 items on the shopping list.”); auto-resolves when all items are purchased or removed.
Overdue dose backend (after dispense or hourly sweep): alert_dose_sync.sync_overdue_dose_alert_for_patient — do not call alert_overdue_dose per group. Hooks: schedule_refresh_overdue_dose_alert in alert_dose_hooks.py. Requires migration V100 on the target database.
Shopping alert backend (after add/purchase/unpurchase/remove/recurring reset): alert_shopping_sync.sync_shopping_alert_for_patient — do not raise one alert per item. Entry point: alert_service.alert_shopping_item → sync; scheduled from shopping_service._schedule_shopping_alert_sync. Dedup key: shopping:{patient_id}; metadata: item_count.
Authenticated provider tree (App.tsx protected routes):
ProtectedRoute → ModuleProvider → PatientProvider → AlertProvider → Layout → <Outlet />ModuleContext (ModuleContext.tsx): one GET /api/subscriptions/active on login — activeModules plus careModuleBoards from feature_flags.
Care boards (CareModuleFlagsContext.tsx): export useCareModuleFlags() only — no CareModuleFlagsProvider. The hook must run under ModuleProvider (e.g. CareBoardDashboardChip, CareBoardGate). Do not reintroduce a second provider; it caused useCareModuleFlags must be used inside <CareModuleFlagsProvider> when auth refresh failed or HMR left a stale tree.
Troubleshooting: 502 on /api/auth/refresh = Vite proxy cannot reach the backend — restart run_server.py and confirm VITE_API_URL in frontend/.env.
Condition packs API (conditionPacksApi in lib/api.ts, V077–V078):
listArchetypes()— seven care archetypes for onboardinglistPacks()— all Care Profiles withhas_access,can_purchase,price_display, andbilling_currencyper tenant. Backend: one cached Frankfurter lookup per currency per list (seeaud_minor_units_per_audinstripe_service.py).previewPack(packId)— pack metadata + seed lists; Subscriptions UI showsfeature_bulletson the card and a marketing-first preview forcancer_at_home(V012)purchasePack(packId)— Stripe Checkout for one-time profile unlockapi.patients.careStart.apply/.recommended/.patchCarePattern— Care Start apply, recommended pack, non-destructive pattern correction (C5c).- Backend:
services/care_start_service.py,services/care_start_checkout.py(signup bundle + first-patient auto-apply),routers/care_start.py(prefix/patients, mounted at/apiand/api/v1). - UI:
PatientCareStartWizard.tsxon Add Person — demographics only (2026-06-26);CareProfileQaPanel.tsx(dev, user id 1) for one-tap apply;CarePatternPanel.tsxandArchetypeOnboarding.tsxdeleted. No standalone/care-archetypespage (redirect →/subscriptions). - Signup bundle:
POST /api/stripe/start-signupoptionalcare_start_pack_slug,care_start_bundle,archetype_slug→ Stripe metadata →tenants.pending_care_start_pack_slugat provision. - Migrations:
V006–V014on dev (11-DATABASE-SAFETY §2i–§2n); apply with.\migrate.ps1 -Target Dev. - Tests:
backend/tests/test_care_start.py,test_care_start_checkout.py,test_condition_pack_billing.py,test_medicines.py(per-patient reason list).
Reason types API (api.reasonTypes):
list(patientId)—GET /api/reason-types?patient_id=create({ patient_id, name, description, color_hex, display_order, active })— admin only
Dev performance: If every page feels slow with Redis stopped, confirm middleware/rate_limit.py uses memory:// when IS_PRODUCTION is false. Start Redis (docker compose up redis -d) for SSE tickets and FX cache. Subscriptions loads catalog, tier, and packs in parallel (Subscriptions.tsx).
Observations API (observationsApi in lib/api.ts):
listTypes(patientId)— observation types enabled for a patient (seeded from condition packs)record(patientId, payload)— saves a single observation reading; returnsthreshold_breachflagtrend(patientId, typeId, window)— rolling mean + σ band (Bollinger-style) for a time window
Family help requests API (helpRequestsApi in lib/api.ts):
listTypes()— 25 default request types grouped by categorylist(patientId, status)— open / taken / completed requests for one patientcreate(patientId, body)— post a new help request; service commits thenschedule_alert→alert_help_request(new_help_request)take(patientId, id)— volunteer takes ownership; resolves opennew_help_request:{id}alert and raiseshelp_request_takencomplete(patientId, id)— mark as donecancel(patientId, id)— requester cancels an open request
Raise alerts from the backend via emit_alert_signal(AlertSignal(...)) after commit — handlers run on a pool connection through schedule_after_commit (requires app lifespan / open pool — not available in pytest savepoint tests; call sync/handler functions on the test db fixture instead). Legacy direct alert_service.* calls are deprecated. APScheduler overdue-dose sweep uses alert_scheduler.py → registry / alert_dose_sync.py.
Pain entries API (api.pain in lib/api.ts, V082 + V092):
body_layeron create/update — allowed values:front,back,front-skeleton,back-skeleton,skeleton(legacy),mind,surface- Responses always include
body_layer(required on read) - Bone overlay mode in
PainBodyMapTabsavesfront-skeleton/back-skeleton; requires migration V092 on the target database - Bone overlay UI:
BodyMapboneOverlayModelimits interactive hits to the body<img>; layer pills sit in az-30header above the map (see 26-PAIN-STATS-MODULE.md §4.1)
Observations API (observationsApi in lib/api.ts, added V079):
getTypes(patientId)— list availableObservationTypeentries for this patient (universal + archetype-specific)list(patientId, { obsTypeId?, from?, to? })— time-seriesPatientObservationentriescreate(patientId, { observation_type_id, obs_date, obs_time, value_number?, value_text?, value_boolean?, notes? })— record one observationgetTrend(patientId, obsTypeId, window)— Bollinger-band trend series (ObsTrendPoint[])delete(patientId, obsId)— soft-delete (is_active = false)
Types: ObservationType, PatientObservation, ObsTrendPoint, ObsValueType, CaptureWidget.
Sleep trend helpers (frontend/src/lib/sleepTrendHelpers.ts, tests in sleepTrendHelpers.test.ts):
Pure functions for 10-day rolling bedtime / wake-time curves. Their only renderer was the legacy SleepGrid.tsx, removed 2026-07-28 when the Sleep Pattern recording surface moved to SleepDayClock.tsx (see doc 02-REQUIREMENTS.md REQ-SLEEP-03) — the calculation still lives here and is still tested, but nothing currently renders it. Re-wire onto the clock (e.g. a small trend chip) or retire via the reconciliation doc before relying on this again.
SLEEP_TREND_ROLLING_DAYS = 10— trailing window size for the smoothed curvesSLEEP_SESSION_MAX_GAP_MINS = 30— awake gap above which contiguous blocks split into separate sessionsBEDTIME_EARLIEST_MINS = 16 * 60,WAKE_WINDOW_START_MINS = 4 * 60,WAKE_WINDOW_END_MINS = 11 * 60,MAIN_SLEEP_MIN_MINS = 4 * 60— anchor windows and minimum main-sleep durationmergeWithinGapTolerance(intervals, maxGapMins)— generic interval merge; same helper drives both bedtime and wake derivationsgetDayBedtime(dayEntries)— anchors on the latest evening start (≥ 16:00), then walks earlier same-day blocks back through any ≤ 30-minute awake gaps to find the true bedtimegetDayWakeTime(dayEntries, allEntries, date)— anchors on the latest morning end inside 04:00–11:00 (with ≥ 4-hour duration including overnight continuation from the previous day’s 24:00 entry), then extends through later blocks connected by ≤ 30-minute gaps
SleepGrid clips the smoothed curve at min(today, last calendar row with any logged sleep) so the line never runs into empty rows.
Help requests API (helpRequestsApi in lib/api.ts, added V080):
list(patientId)— open and recent help requests for the patient’s care circlecreate(patientId, payload)— post a new help requestoffer(requestId)— volunteer to fulfil a requestclose(requestId)— mark request fulfilled
8. Invitation and approval flows
Section titled “8. Invitation and approval flows”When changing registration or approvals:
- Invited users: often
users.status = pendingandtenant_memberships.status = inviteduntil an admin approves. - Approval should update both
users.status = approvedandtenant_memberships.status = activein a coherent way (see existingusersrouter). - Invitation tokens: single-use, expiry — validate before accepting.
Pending count for admins: use the lightweight GET /api/users/pending-count (or equivalent) rather than loading the full user list for a badge.
9. Testing
Section titled “9. Testing”cd backend.\venv\Scripts\Activate.ps1$env:TEST_DATABASE_URL = "postgresql://lyncare:lyncare@localhost:5432/lyncareos_test"pytest -m "not slow"TEST_DATABASE_URL(defaultpostgresql://lyncare:lyncare@localhost:5432/lyncareos_test) — seetests/conftest.py. Conftest applieslyncareos_v1_baseline.sqlon an empty test DB, otherwiseschema.sql; seeds active migrations only; isolates each test with savepoints.- CI runs the same command on Postgres 16 (
pytest -m "not slow"— 64 modules, ~797 tests). Live Stripe API tests are@pytest.mark.slow— run locally only whenSTRIPE_SECRET_KEY=sk_test_…is set. - D6 prep:
python scripts/d6_router_test_coverage.pyprints router SQL baseline vs test-file mapping. - Run tests before merging non-trivial backend changes.
- Backend suites include (non-exhaustive):
test_auth_routes.py,test_care.py,test_dispensings.py,test_prescriptions.py,test_medication_schedule.py,test_medicines_patient_isolation.py(REQ-MED-14 cross-patient leak guard),test_analytics.py,test_patient_analytics_isolation.py(REQ-MED-15 analytics/alerts/export/audit isolation),test_auto_dispense.py,test_first_dose_reactions.py(REQ-MED-16),test_key_contacts.py,test_shopping.py,test_catalog_admin.py,test_migration_runner.py,test_lm_studio.py,test_user_module_access.py,test_v029_sleep_subscription_backfill.py, and others underbackend/tests/. - Analytics MV in tests:
tests/conftest.pypatchesrefresh_analytics_dispensing_summaryto refresh on the per-testdbconnection (savepoint-visible).create_dispensing()also refreshes after direct inserts. Production uses the pool withREFRESH … CONCURRENTLYwhen autocommit allows. - Essential tier QA (dev):
.\scripts\seed-dev-essential-tenant.ps1— createsessentialqa/EssentialQA1!onlyncareos_devwith Essential-only modules (backend/scripts/seed_dev_essential_tenant.py). RequiresDATABASE_URLinbackend/.envpointing atlyncareos_dev. - Peter Care Profile + board QA (dev):
.\scripts\seed-dev-peter-care-qa.ps1— prepares tenantpeterfor Subscriptions catalogue + cancer/breathing board testing (backend/scripts/seed_dev_peter_care_qa.py). See §7.1j.
PHI field encryption tests (V091 schema)
Section titled “PHI field encryption tests (V091 schema)”After migration V091, plaintext identity columns (users.email, patients.name/dob, tenants.name, care_groups.name) no longer exist. Tests must use tests/conftest.py helpers — never raw INSERT into those columns:
| Helper | Use when |
|---|---|
insert_phi_user | Need only a user row |
insert_phi_tenant | Need a tenant for an existing owner |
insert_phi_patient | Need a patient with encrypted name/DOB |
provision_phi_account | User + tenant + membership in one call |
create_user_and_login | Full account + JWT (uses PHI helpers internally) |
create_patient / create_member_in_tenant | Wrappers around PHI insert helpers |
Regression suite: tests/test_phi_field_encryption.py (30 tests, @pytest.mark.regression).
python -m pytest tests/test_phi_field_encryption.py -m regression -vNote: pending_signups.email and medication_groups.name are unchanged — only the four identity tables above were encrypted.
Frontend: cd frontend → npm run test (Vitest), npm run test:e2e (Playwright). The unit suite is green at 233 passing.
Test environment shims (src/test/setup.ts): jsdom omits some DOM APIs that real components call. The setup file polyfills matchMedia, URL.createObjectURL, localStorage, and Element.prototype.scrollIntoView (a no-op) — the last is required by any component that calls scrollIntoView in a layout effect (e.g. components/ui/DayDateStrip.tsx). Add the shim here rather than per-test when introducing a component that uses an unimplemented jsdom API.
10. Lint and typecheck
Section titled “10. Lint and typecheck”cd frontendnpm run lintnpm run buildnpm run build runs tsc -b and Vite build — catches many TS errors.
11. Git conventions
Section titled “11. Git conventions”Branches: feature/…, fix/…, docs/…, chore/…
Commits (Conventional Commits style):
feat(dispensings): add filter by medicinefix(auth): preserve session on 403 responsesdocs: align developer guide with Docker portsBefore opening a PR:
- Frontend:
npm run buildandnpm run lintpass - Backend:
pytestwhere applicable - New API routes have correct auth / tenant / module dependencies
- No stray
console.logor secrets - Schema changes handled for new and existing DBs (DDL +
IF NOT EXISTSalters as needed)
12. Anti-patterns (do not introduce)
Section titled “12. Anti-patterns (do not introduce)”Backend
- SQL built with string concatenation from user input
- Skipping
commit()after mutations - Public endpoints that return tenant-scoped data without auth
- Hard-coded secrets (use
config.py/ env)
Frontend
- Treating 403 like 401 for session handling
- Storing secrets in source
- Inline
style={{}}when Tailwind can express the rule (exception: dynamic colours from API, e.g. profile swatches)
General
- Assuming
/api/v1/or a monorepo shared package exists in this repo — they do not - Registering Care Module board routes without checking
CARE_BOARDS_BUILD_ENABLED/ serverfeature_flags— boards must remain optional for launch - Treating Care Profile pack unlock as sufficient to show board UI without
CARE_MODULE_BOARDS_ENABLED— commerce and plugin UI are separate layers
13. AI / assistant contributors
Section titled “13. AI / assistant contributors”- Read
docs/02-REQUIREMENTS.md,01-ARCHITECTURE.md,04-ROADMAP.md, and this guide before large changes. - Search for an existing pattern (router, page, component) and extend it.
- Prefer editing existing files over adding parallel structures.
- Do not change API response shapes without updating
lib/api.tsand callers in the same change. Database is master — persist mutations through the API; do not treat the browser as the source of truth for clinical data. - Match style of the file you edit (quotes, formatting).
14. Body Map Zone Calibration Tool
Section titled “14. Body Map Zone Calibration Tool”The Pain Tracking feature uses a set of predefined rectangular zones (x1, y1 → x2, y2 as image-percentage coordinates) to translate a tap position on the body image into an anatomical label (e.g. “Left Tricep”, “Lower Back Centre”). Because male and female images have different proportions and framing, each gender maintains its own independent zone set.
Zones are defined in:
frontend/src/components/pain/BodyMap.tsxas four arrays:
| Constant | Scope |
|---|---|
FRONT_ZONES_MALE | Male, front view |
BACK_ZONES_MALE | Male, back view |
FRONT_ZONES_FEMALE | Female, front view |
BACK_ZONES_FEMALE | Female, back view |
14.1 Activating the calibration tool
Section titled “14.1 Activating the calibration tool”The tool is development-only — it is gated by import.meta.env.DEV and is completely absent from production builds. There is no visible button — it is activated by keyboard shortcut to keep the UI clean during normal development.
- Start the dev servers (
.\dev-start.ps1ornpm run dev). - Log in and navigate to the Pain Tracking page (
/pain). - Select a patient whose gender matches the image you want to calibrate.
- Press
Ctrl+Shift+K— the calibration overlay appears immediately. - Press
Ctrl+Shift+Kagain (or follow the on-screen prompt) to exit.
14.2 Calibration workflow
Section titled “14.2 Calibration workflow”┌─────────────────────────────────────────────────────┐│ ⚙ Calibrate Zones [Male] [Female] ││ ││ ┌──────────────────────────────────────────────┐ ││ │ Body image with coloured dot per zone │ ││ │ Each dot is DRAGGABLE — label shown nearby │ ││ └──────────────────────────────────────────────┘ ││ ││ Coordinate readout panel (appears after first drag) ││ cx= 51.7 cy= 6.0 ← MOVED ││ ... ││ [Copy all] │└─────────────────────────────────────────────────────┘- Select gender using the
[Male]/[Female]toggle that appears while calibrating. Calibrate one gender at a time. - Drag each dot to the visual centre of the anatomical region on the body image. The dot label identifies which zone it represents.
- After moving a dot the readout panel appears below the gender toggle, listing
cx(horizontal %) andcy(vertical %) for every zone. Zones you moved are marked← MOVED. - Click Copy all to copy the full coordinate block to the clipboard.
- Paste the block into this conversation or share it with the team.
Tip: Calibrate front and back separately — use the front image to refine all front zones, then switch to the back view by tapping the back body image (or scrolling to it) and dragging those dots.
14.3 Applying calibration output to the code
Section titled “14.3 Applying calibration output to the code”The coordinate readout gives cx / cy — the zone centre as a percentage of the image container width and height. To convert to the x1, y1, x2, y2 rectangle used in the zone arrays:
halfW = half the zone's visual width (estimate from anatomy — typically 7–10 for narrow zones, 14–18 for wide ones like head/abdomen)halfH = half the zone's visual height (typically 4–8)
x1 = cx − halfW x2 = cx + halfWy1 = cy − halfH y2 = cy + halfHPaste the coordinate block as a user message and the AI assistant will compute the new x1, y1, x2, y2 values and update the correct constant in BodyMap.tsx. Zones that are not marked ← MOVED can be left unchanged.
14.4 Adding new zones
Section titled “14.4 Adding new zones”To add a new anatomical region (e.g. “Left Tricep”):
- Add a new
Zoneentry to the relevant array(s) inBodyMap.tsxwith estimated coordinates. - Place the entry before any broader zone it should override (zones are tested in order; first match wins).
- Run the calibration tool to drag the new dot into position.
- Apply the output coordinates using §14.3.
Both gender variants (_MALE and _FEMALE) must be updated — zones are not shared between genders.
14.5 Scalability and screen resolution
Section titled “14.5 Scalability and screen resolution”All coordinates are stored as percentages of the image container, not pixels. The hotspot overlay uses the same percentage-based left / top CSS positioning. This means:
- Zone detection and hotspot placement scale automatically with any container size.
- The female image applies a
scale(1.05) translateY(-5.5%)transform — zone coordinates for female images are calibrated after this transform is applied, so no manual adjustment is needed when the scale constant changes.
14.6 Re-calibration triggers
Section titled “14.6 Re-calibration triggers”Re-run calibration whenever:
- Body images are replaced or re-cropped.
- The
FEMALE_SCALEorFEMALE_OFFSET_Yconstants inBodyMap.tsxare changed. - New zones are added to a view.
- User feedback indicates a tap lands on the wrong label.
14.7 Future body types — children and babies
Section titled “14.7 Future body types — children and babies”The calibration system is designed to be extended. Planned future variants:
| Variant | Images needed | Zone arrays to add |
|---|---|---|
| Child — male | Child Male Front.png, Child Male Back.png | FRONT_ZONES_CHILD_MALE, BACK_ZONES_CHILD_MALE |
| Child — female | Child Female Front.png, Child Female Back.png | FRONT_ZONES_CHILD_FEMALE, BACK_ZONES_CHILD_FEMALE |
| Baby / infant | Baby Front.png, Baby Back.png | FRONT_ZONES_BABY, BACK_ZONES_BABY |
Key anatomical differences to account for:
- Infant and child proportions differ significantly from adults — the head is proportionally much larger, limbs shorter relative to torso, and the abdomen more prominent. Zones cannot be copied from adult arrays; a full calibration pass is required for each new body type.
- Infant zone vocabulary will differ — for example, fontanelle region (head), nappy area, and fewer granular limb sub-zones. Plan the slug names and labels before beginning calibration.
- The
arm-back/ tricep split may not apply to infants — a single zone per arm is likely sufficient.
Code changes required when adding a new body type:
- Add the transparent PNG images to
frontend/public/(orassets/). - Extend the
gender(or introduce a newbodyType) prop type inBodyMap.tsxandPainTracking.tsx. - Add the zone constant arrays and extend
getZones()to branch on the new type. - Add the new images to the
BodyMaprender logic with appropriate scale/offset constants (use the calibration tool to determine these). - Extend the
Patientmodel / schema / DB column to capture the body type selection (e.g.body_type: 'adult' | 'child' | 'baby'or derive it fromdate_of_birthautomatically). - Run the calibration tool for each new view (front and back) and apply coordinates using §14.3.
Image production guidelines for new body types:
- Generate all variants (child male front, child male back, child female front, child female back, baby front, baby back) in a single AI image at identical proportions before extracting individuals — this ensures consistent scale across the set, exactly as was done for the adult male/female images.
- Export as transparent PNGs with no background.
- Target the same canvas height as the adult images so the image containers remain a consistent size across patient types.
15. Database backup and restore
Section titled “15. Database backup and restore”For operational backup/restore scripts and volume safety, see [../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md](../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md) and repo scripts db-backup.ps1 / db-restore.ps1 where applicable.