26 — Pain & Stats Module
Complete Product Specification
Section titled “Complete Product Specification”Version: 1.9
Status: Production (implemented)
Last Updated: 2026-05-31 16:23:30
Master requirements: 02-REQUIREMENTS.md §3.6, §3.9, §7.7, §7.10. Tier matrix: 23-SUBSCRIPTION-TIER-ENTITLEMENTS-MATRIX.md §2, §7, §10.
Module slugs (two gates):
| Capability | Slug | Tier | Route |
|---|---|---|---|
| Vital Signs (standalone) | vitals_tracking | Family, Complete | /vitals |
| Pain & Stats (body map, mind, trends; vitals embedded on Complete) | pain_tracking | Complete only | /pain |
Phase: Extractable (post-refactor)
Table of Contents
Section titled “Table of Contents”- Vision
- Deployment Modes
- Subscription & Access Control
- Three Pillars
- Roles & Permissions
- UX & Navigation
- Trend Analysis
- Clinical Health Tiers
- Database Schema
- API Design
- Backend Architecture
- Frontend Architecture
- Body Map — Polygon Zone System
- Branding & White-label Config
- Integration Points
- Implementation Notes
1. Vision
Section titled “1. Vision”Pain & Stats is a clinical-grade symptom and vitals tracking module for care environments. It gives carers a fast, visual way to record where pain occurs, how severe it is, the patient’s mental state, and their vital signs — then surfaces 30-day trends so care teams can spot patterns over time.
The module is designed to run embedded in LynCareOS or as a separately branded, standalone application targeting different clinical markets (e.g. palliative care, aged care, rehabilitation, paediatric).
2. Deployment Modes
Section titled “2. Deployment Modes”Mode A — Integrated (default)
Section titled “Mode A — Integrated (default)”Pain & Stats is one module within LynCareOS. The shared shell provides auth, patient context, navigation, and subscription management. The module slug pain_tracking must be active in the tenant’s subscription.
- Route:
/pain - Auth: LynCareOS session (JWT cookie)
- Patient context: provided by
PatientContext - Tenant settings:
tenant_pain_settingsrow (optional)
Mode B — Standalone (reserved, standalone_mode = true)
Section titled “Mode B — Standalone (reserved, standalone_mode = true)”The module can be extracted into a separate deployment with its own brand. In standalone mode:
- Auth is provided by a separate identity service (same session mechanism)
- No LynCareOS shell — the module renders its own nav and layout
- Tenant settings override module label, images, and feature flags
storage_key_prefixseparates localStorage keys from any co-deployed app
Note: The
standalone_modeflag intenant_pain_settingsis provisioned but the API routing branches for patient-less tenant-scoped access are not yet implemented. See the Implementation Notes section.
3. Subscription & Access Control
Section titled “3. Subscription & Access Control”Backend module gates (main.py):
| Router | Dependency | Module slug |
|---|---|---|
vitals.py | _vitals | vitals_tracking |
pain.py, mind.py | _pain | pain_tracking |
pain_settings.py | (auth only) | No module gate — tenant settings readable without subscription |
Requests without the required module return 403 (or 402 at tier capacity boundaries).
Frontend module gates: <ModuleGate slug="vitals_tracking"> for /vitals; <ModuleGate slug="pain_tracking"> for /pain. Super-admins bypass gates.
Nav visibility: Layout.tsx uses useModule('vitals_tracking') and useModule('pain_tracking') separately.
Per-user access: Tenant admins can grant or revoke per-user module access via tenant_user_module_access.
4. Three Pillars (Body / Bone overlay — C8, 2026-05-22)
Section titled “4. Three Pillars (Body / Bone overlay — C8, 2026-05-22)”4.1 Body Map (Pain)
Section titled “4.1 Body Map (Pain)”Layer selector (responsive)
Section titled “Layer selector (responsive)”| Viewport | Controls | What the user sees |
|---|---|---|
| Desktop (>767px) | [ Body ] [ Bone ] [ Mind ] | Front and back body diagrams side by side in BodyMap.tsx. No per-side Front/Back pills — both panels are always visible. |
| Mobile (≤767px) | [ Body ] [ Bone ] [ Mind ]; when Bone is active, an extra [ Front ] [ Back ] row | Body: one panel at a time with BodyMap’s built-in Front/Back tabs. Bone: SkeletonBodyMap for the active side only. |
State: mapType: 'body' | 'skeleton'; on mobile bone mode only, activeSide: 'front' | 'back'.
Body vs Bone display
Section titled “Body vs Bone display”mapType | Body illustration | Skeleton | Pain recording |
|---|---|---|---|
| Body | Full opacity; no skeleton | Hidden | Same polygon zones as today (BodyMap.tsx); body_layer = tapped side ('front' / 'back') |
| Bone (desktop) | Semi-transparent (bodyOpacity from gender calib) | Transparent PNG overlaid on both front and back panels | Same zone tap targets as body — skeleton is visual only; body_layer = '{side}-skeleton', anatomy_type = 'bone' |
| Bone (mobile) | N/A (standalone skeleton view) | SkeletonBodyMap.tsx hotspot map for active side | Hotspot-based bone regions |
Per-gender skeleton overlay constants
Section titled “Per-gender skeleton overlay constants”Baked in frontend/src/components/pain/skeletonCalibTypes.ts (percentage-based — scales with panel width on any screen):
| Constant | Purpose |
|---|---|
SKEL_CALIB_FEMALE | Overlay alignment for female body art (calibrated 2026-05-22) |
SKEL_CALIB_MALE | Overlay alignment for male body art (calibrated 2026-05-22) |
getSkelCalibForGender(gender) | Runtime lookup by patient gender |
Female (SKEL_CALIB_FEMALE): scalePct 135, frontOffsetXPct 2, backOffsetXPct -0.5, offsetYPct -19.5, bodyOpacity 0.25, skeletonOpacity 0.95.
Male (SKEL_CALIB_MALE): scalePct 130, frontOffsetXPct 0, backOffsetXPct 0.5, offsetYPct -16, bodyOpacity 0.25, skeletonOpacity 0.95.
Desktop overlay implementation:
SkeletonCalibPanel.tsx— dev-only (import.meta.env.DEV) alignment UI forSKEL_CALIB_*constants; not shipped in production builds.SkeletonMapOverlay.tsx— renders/skeleton-front.pngor/skeleton-back.pnginside eachBodyMapside panel usingtransform: scale()(avoids Tailwindmax-width: 100%on images blocking scale).BodyMapprops:frontSkeletonOverlay,backSkeletonOverlay,bodyImageOpacity,allowBodyOverflow,boneOverlayMode(bone mode only).- Bone mode hit testing (2026-06-02): skeleton overlay is
pointer-events-none; the side panel ispointer-events-noneso the Body / Bone / Mind pill row (PainLayerToggle,z-30inPainBodyMapTab) stays clickable when the scaled skeleton extends above the figure. Pain taps attach to the body image only (pointer-events-autoon the<img>). - Independent Front X / Back X offsets in calib constants (back skeleton can be nudged left/right separately).
Skeleton PNG assets: Source files in assets/ are processed to transparent 430×940 canvases (same aspect as body art) at frontend/public/skeleton-front.png and skeleton-back.png.
Mobile SkeletonBodyMap.tsx: Used only on narrow viewports in bone mode — 16 tappable hotspots per side, pain 0–10 bar above the figure (not below the feet).
Migration V082__pain_body_layer.sql added body_layer column and index (patient_id, body_layer, date DESC).
V092__pain_body_layer_skeleton_sides.sql extended the CHECK so bone-overlay saves accept 'front-skeleton' and 'back-skeleton' (V082 allowed only 'skeleton', which caused DB constraint errors against PainBodyMapTab). Allowed values: 'front', 'back', 'front-skeleton', 'back-skeleton', 'skeleton' (legacy), 'mind', 'surface'.
Body map interaction (all layers):
- Tap any region to record a pain level (0–10 colour scale)
- One entry per region per body layer per date (replaces on repeat tap)
- Tap near an existing dot without a level selected → delete that entry (the delete-radius check is layer-scoped so tapping a bone dot can’t remove a body dot at the same coordinate)
- Carry-forward: if today has no entries, offer to copy from the most recent prior day — preserves the original
body_layerso carried-forward bone entries land on the Bone view, not the Body view - Historical navigation: browse any past date
Layer separation (hardened 2026-05-28)
Section titled “Layer separation (hardened 2026-05-28)”Body pain and bone pain are kept fully independent at three levels:
| Layer | Body view (mapType = 'body') | Bone view (mapType = 'skeleton') |
|---|---|---|
| Data | body_layer ∈ {'front','back','surface'} | body_layer ∈ {'front-skeleton','back-skeleton','skeleton'} |
| Map render | mapEntries filtered to body-layer rows only — bone dots never appear over the body | mapEntries filtered to bone-layer rows only — body dots never appear over the skeleton |
| Entries list | “Body Pain” section card | “Bone Pain” section card (rendered by PainEntrySection) |
The list endpoint GET /api/patients/{id}/pain returns body_layer on every row so the UI can route entries correctly on reload (regression test in tests/test_pain.py::test_pain_list_returns_body_layer_for_body_and_bone).
Switching between Body and Bone is a ~300 ms cross-fade: the body image opacity transitions between full and bodyOpacity, SkeletonMapOverlay is always mounted and toggles its wrapper opacity via the visible prop, and PainHotspot dots fade in via the animate-pain-hotspot-in keyframe (index.css).
4.2 Vital Signs
Section titled “4.2 Vital Signs”- Three vital types: Pulse (bpm), SpO₂ (%), Temperature (°C/°F)
- Multiple readings per day at different times (each has an
HH:MMtimestamp) - Per-vital-type unique constraint at the minute level (prevents accidental duplicates)
- Delete individual readings
4.3 Mental State (Mind)
Section titled “4.3 Mental State (Mind)”- Seven clinical domains: Mood, Anxiety, Fear, Cognition, Behaviour/Engagement, Sleep, Coping
- Each domain scored 0–4 with narrative level descriptions
- One assessment per patient per date (upsert semantics)
- Accessed via the Mind control in the layer toolbar (mobile) or the floating Mind pill on the body map (desktop only)
5. Roles & Permissions
Section titled “5. Roles & Permissions”| Action | Observer | Carer | Tenant Admin | Super Admin |
|---|---|---|---|---|
| View pain entries | ✓ | ✓ | ✓ | ✓ |
| Record pain entry | — | ✓ | ✓ | ✓ |
| Delete pain entry | — | ✓ | ✓ | ✓ |
| View vitals | ✓ | ✓ | ✓ | ✓ |
| Record vital | — | ✓ | ✓ | ✓ |
| Delete vital | — | ✓ | ✓ | ✓ |
| View mind assessment | ✓ | ✓ | ✓ | ✓ |
| Save mind assessment | — | ✓ | ✓ | ✓ |
| View trend charts | ✓ | ✓ | ✓ | ✓ |
| Update module settings | — | — | ✓ | ✓ |
6. UX & Navigation
Section titled “6. UX & Navigation”Page layout: Two-tab design (Body Map / Trend) with a date navigator at the top.
Date navigator: Step backward/forward one day; “Back to today” shortcut. Future dates are blocked.
Body Map tab:
- Desktop:
[ Body ] [ Bone ] [ Mind ]— front and back shown together; bone mode overlays calibrated skeleton PNGs on both panels with a faded body underneath - Mobile:
[ Body ] [ Bone ] [ Mind ]; Front | Back row appears only in bone mode; body mode uses in-map Front/Back tabs - Layer transition: switching Body ⇄ Bone cross-fades the body PNG, the skeleton overlay, and the pain hotspots over ~300 ms (see §4.1 Layer separation)
- Pain 0–10 bar: above the figure on mobile (avoids feet and scores clipping off the bottom); below the map on desktop (tucked into transparent padding under the feet)
- Mobile figure size: body map capped at
62dvwwidth (NARROW_MAP_MAX_W_CLASSinBodyMap.tsx) so the full body fits on small phones - Vital Signs cards (3-column) + chronological readings list below the map (scrollable region on mobile)
- Today’s Pain Entries list: split into two cards — “Body Pain” and “Bone Pain” — regardless of the active map view, so carers always see both record sets without toggling. Empty sections render a quiet placeholder (“No body pain entries recorded.”) rather than disappearing.
Trend tab:
- Three category buttons (Body / Mind / Vitals) — configurable via tenant settings
- Filter chips act as the legend (coloured pills toggling each data series)
- 30-day trend chart for the selected category
- 30-day summary card below the chart
Persistence: Filter selections and active trend category are saved to localStorage using the tenant’s storage_key_prefix.
Theme: All chart tooltips respect the app’s light/dark theme via chartColors(isDark) from lib/chartTheme.ts.
7. Trend Analysis
Section titled “7. Trend Analysis”Body Trend
Section titled “Body Trend”Line chart, one series per body region. Filter chips are coloured to match the chart lines (using LINE_COLOURS from PainTrendChart). Tooltip shows pain score in the corresponding pain-severity colour.
Mind Trend
Section titled “Mind Trend”Line chart, one series per mental state domain. Tooltip shows the narrative description for each score (not the numeric value). Domain colours defined in MIND_DOMAINS.
Vitals Trend
Section titled “Vitals Trend”Three stacked sparkline charts (Pulse / SpO₂ / Temperature). Each shows:
- A shaded band between the day’s min and max readings
- Boundary lines for min and max
- Scatter dots for intermediate readings (readings between min and max for that day)
Tooltip shows the reading value plus its clinical health tier label and description.
8. Clinical Health Tiers
Section titled “8. Clinical Health Tiers”Five-tier system from Normal → Critical. Based on NHS/Cleveland Clinic adult resting values.
Pulse (bpm)
Section titled “Pulse (bpm)”| Tier | Range |
|---|---|
| Normal | 60–100 |
| Watch | 50–59 or 101–110 |
| Caution | 40–49 or 111–130 |
| Concerning | 31–39 or 131–150 |
| Critical | ≤30 or >150 |
SpO₂ (%)
Section titled “SpO₂ (%)”| Tier | Range |
|---|---|
| Normal | ≥95 |
| Watch | 93–94 |
| Caution | 90–92 |
| Concerning | 85–89 |
| Critical | <85 |
Temperature (°C)
Section titled “Temperature (°C)”| Tier | Range |
|---|---|
| Normal | 36.1–37.5 |
| Watch | 35.5–36.0 or 37.6–38.0 |
| Caution | 35.0–35.4 or 38.1–38.9 |
| Concerning | 34.5–34.9 or 39.0–39.9 |
| Critical | <34.5 or ≥40.0 |
9. Database Schema
Section titled “9. Database Schema”All tables are created by the migration files listed below. The consolidated bootstrap migration V059__pain_module_bundle.sql re-runs all DDL idempotently for standalone deployments.
patient_pain_entries
Section titled “patient_pain_entries”Created in V050__pain_tracking.sql.
| Column | Type | Notes |
|---|---|---|
| id | SERIAL PK | |
| tenant_id | INTEGER FK | → tenants |
| patient_id | INTEGER FK | → patients |
| date | TEXT | YYYY-MM-DD |
| body_region | TEXT | zone slug |
| region_label | TEXT | display name |
| body_side | TEXT | ‘front’ or ‘back’ |
| anatomy_type | TEXT | muscle/bone/joint/organ/tissue/nerve |
| body_layer | TEXT | 'front'|'back'|'front-skeleton'|'back-skeleton'|'skeleton' (legacy)|'mind'|'surface' — V082 column; V092 CHECK |
| pain_level | SMALLINT | 0–10 |
| indicator_x_pct | REAL | hotspot x (% of image width) |
| indicator_y_pct | REAL | hotspot y (% of image height) |
| notes | TEXT | nullable |
| recorded_by | INTEGER FK | → users |
| created_at / updated_at | TIMESTAMPTZ |
Indexes: idx_pain_patient_date, idx_pain_tenant, idx_pain_region_date, patient_pain_entries_layer_date (patient_id, body_layer, date DESC) — added V082
patient_vitals
Section titled “patient_vitals”Created in V050__pain_tracking.sql + V051__V053__V055__V057 amendments.
| Column | Type | Notes |
|---|---|---|
| id | SERIAL PK | |
| tenant_id / patient_id | INTEGER FK | |
| date | TEXT | YYYY-MM-DD |
| recorded_time | TEXT | HH:MM, NOT NULL, DEFAULT ‘00:00’ |
| pulse_bpm | SMALLINT | nullable, 20–300 |
| spo2_pct | SMALLINT | nullable, 30–100 |
| temp_celsius | REAL | nullable, 30–45 |
| recorded_by | INTEGER FK | |
| created_at / updated_at | TIMESTAMPTZ |
Partial unique indexes (one per vital type to allow multi-vital readings at different times):
uq_vitals_pulse_timeon(tenant_id, patient_id, date, recorded_time) WHERE pulse_bpm IS NOT NULLuq_vitals_spo2_time— same, WHERE spo2_pct IS NOT NULLuq_vitals_temp_time— same, WHERE temp_celsius IS NOT NULL
patient_mind_entries
Section titled “patient_mind_entries”Created in V054__mind_tracking.sql.
| Column | Type | Notes |
|---|---|---|
| id | SERIAL PK | |
| tenant_id / patient_id | INTEGER FK | |
| date | TEXT | YYYY-MM-DD |
| mood / anxiety / fear / cognition / behaviour / sleep / coping | SMALLINT | nullable, 0–4 |
| recorded_by | INTEGER FK | |
| created_at / updated_at | TIMESTAMPTZ |
Unique constraint: (tenant_id, patient_id, date) — one assessment per day.
tenant_pain_settings
Section titled “tenant_pain_settings”Created in V058__pain_module_settings.sql.
| Column | Type | Default | Notes |
|---|---|---|---|
| tenant_id | INTEGER PK FK | → tenants | |
| module_label | TEXT | ‘Pain & Stats’ | display name |
| module_description | TEXT | null | |
| enable_body_map | BOOLEAN | true | |
| enable_vitals | BOOLEAN | true | |
| enable_mind | BOOLEAN | true | |
| standalone_mode | BOOLEAN | false | reserved for future |
| storage_key_prefix | TEXT | ‘lc’ | localStorage namespace |
| updated_at | TIMESTAMPTZ | now() |
10. API Design
Section titled “10. API Design”All endpoints are prefixed /api and gated on pain_tracking module.
Pain Entries
Section titled “Pain Entries”| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /patients/{id}/pain?date= | patient_access | List entries for a date |
| GET | /patients/{id}/pain/trend?region=&days= | patient_access | Single-region trend |
| GET | /patients/{id}/pain/trend/all?days= | patient_access | All-region trend |
| GET | /patients/{id}/pain/latest?before= | patient_access | Carry-forward source |
| POST | /patients/{id}/pain | carer_role | Create entry |
| DELETE | /patients/{id}/pain/{entry_id} | carer_role | Delete entry |
Vitals
Section titled “Vitals”| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /patients/{id}/vitals?date= | patient_access | List readings |
| GET | /patients/{id}/vitals/trend?days= | patient_access | Raw readings for band chart |
| POST | /patients/{id}/vitals/{date} | carer_role | Create reading |
| DELETE | /patients/{id}/vitals/{entry_id} | carer_role | Delete reading |
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /patients/{id}/mind?date= | patient_access | Get assessment (null if none) |
| PUT | /patients/{id}/mind/{date} | carer_role | Create or update assessment |
| GET | /patients/{id}/mind/trend?days= | patient_access | Domain scores over N days |
Module Settings
Section titled “Module Settings”| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /pain/settings | tenant_member | Tenant settings (merged with defaults) |
| PATCH | /pain/settings | tenant_admin | Update settings |
11. Backend Architecture
Section titled “11. Backend Architecture”The module follows the Router → Service → Repository pattern used by the Shopping module.
routers/pain.py — thin FastAPI route handlers (pain entries)routers/vitals.py — thin FastAPI route handlers (vitals)routers/mind.py — thin FastAPI route handlers (mind)routers/pain_settings.py — settings GET/PATCH
services/pain_service.py — pain entry business logicservices/vitals_service.py — vitals business logic (conflict handling)services/mind_service.py — mind state business logic
repositories/pain.py — all SQL for pain, vitals, mind, settings
schemas/pain.py — PainEntryCreate (includes body_layer: str = 'surface'), VitalsCreate, MindEntryUpsert, PainSettingsPatchAuth dependencies applied at router-registration level in main.py:
_pain = [Depends(require_module("pain_tracking"))]app.include_router(pain_router.router, dependencies=_pain)app.include_router(vitals_router.router, dependencies=_pain)app.include_router(mind_router.router, dependencies=_pain)app.include_router(pain_settings_router.router) # auth-only, no module gateVitals conflict detection: vitals_service.create_vital catches psycopg.errors.UniqueViolation and maps the constraint name to a human-readable vital label for the 409 response.
body_layer wiring (fixed 2026-05-21): body_layer is now propagated end-to-end: PainEntryCreate schema → insert_pain_entry repo (body_layer column in INSERT + RETURNING) → pain_service.create_pain_entry → PainEntry TypeScript interface (lib/api.ts). Prior to this fix, all pain entries were stored with the DB default 'surface' regardless of the front/back/skeleton view selection. The PainEntry TypeScript interface now has body_layer: string as a required response field.
Follow-up fix (2026-05-28): repositories/pain.py::get_pain_entries was silently omitting body_layer from its SELECT — newly inserted rows carried it back via RETURNING, but every reload or date change arrived without it, which made the body-vs-bone deduplication and the new layer-filtered render path inconsistent across navigations. body_layer is now in the SELECT alongside the other entry fields, satisfying the published PainEntry contract. Regression test: tests/test_pain.py::test_pain_list_returns_body_layer_for_body_and_bone posts one body-layer and one bone-layer entry on the same region+side and asserts both come back as distinct rows with the right body_layer.
Audit trail (added 2026-05-21): write_audit() is called in the same transaction as every mutation across all clinical routers: vitals_service (CREATE/DELETE), pain_service (CREATE/DELETE), mind_service (CREATE/EDIT), sleep.py (bulk day replace), medicines.py (CREATE/EDIT/DELETE), patient_appointments.py (CREATE/EDIT/DELETE).
Date window SQL fragment: repositories/pain.py defines _DAYS_AGO as a reusable SQL constant used in all trend queries to avoid repetition.
12. Frontend Architecture
Section titled “12. Frontend Architecture”pages/PainTracking.tsx — thin shell (~100 lines), date nav + tab state
components/pain/ PainDateNavigator.tsx — date navigation header PainBodyMapTab.tsx — Body Map tab; responsive Body/Bone/Mind selector; desktop bone overlay; mobile layout (pain bar above map); layer-aware filtering (bodyEntries / boneEntries via BODY_LAYERS + BONE_LAYERS sets); two-section entries list rendered by the in-file PainEntrySection helper skeletonCalibTypes.ts — SKEL_CALIB_FEMALE / SKEL_CALIB_MALE (per-gender overlay) SkeletonMapOverlay.tsx — desktop skeleton PNG overlay (transform scale); always mounted, `visible` prop cross-fades opacity (~300 ms) with a subtle inward scale-out on hide SkeletonCalibPanel.tsx — dev-only overlay sliders (user ID 1) SkeletonBodyMap.tsx — mobile bone mode: skeleton PNG + hotspot overlays PainTrendTab.tsx — Trend tab content BodyMap.tsx — interactive illustrated body diagram; skeleton overlay slots + bodyImageOpacity (always numeric with 300 ms opacity transition); PainHotspot dots use the `animate-pain-hotspot-in` keyframe defined in index.css PainScaleBar.tsx — 0–10 pain level selector VitalsBar.tsx — vital cards + readings list VitalEntryModal.tsx — time+value entry popup MindModal.tsx — 7-domain mental state modal PainTrendChart.tsx — body pain line chart MindTrendChart.tsx — mental state line chart VitalsTrendChart.tsx — high/low band charts (Bollinger-style) PainLevelBadge.tsx — circular pain level badge PainFaceIcon.tsx — pain face emoji icon painColors.ts — pain severity colour mapping
hooks/ usePainConfig.ts — fetch + merge tenant settings usePainDateData.ts — fetch pain/vitals for a date usePainTrends.ts — fetch trend data + filter state
config/ painModuleConfig.ts — static build-time config + dynamic typeData flow:
PainTracking → usePainConfig → api.pain.getSettings → tenant_pain_settingsPainBodyMapTab → usePainDateData → api.pain + api.vitalsPainTrendTab → usePainTrends → api.pain.trendAll + api.mind.trend + api.vitals.trend13. Branding & White-label Config
Section titled “13. Branding & White-label Config”Static config (build-time, config/painModuleConfig.ts)
Section titled “Static config (build-time, config/painModuleConfig.ts)”Change PAIN_STATIC_CONFIG in the deployed codebase to rebrand without API changes:
| Key | Default | Purpose |
|---|---|---|
bodyMapImageBase | /images/body | Body diagram image prefix |
headImageBase | /images/head | Head image prefix for Mind modal |
tabBodyMapLabel | '🫀 Body Map' | Body Map tab button text |
tabTrendLabel | '📈 Trend' | Trend tab button text |
trendBodyLabel | '🫀 Body' | Body category button |
trendMindLabel | '🧠 Mind' | Mind category button |
trendVitalsLabel | '📟 Vitals' | Vitals category button |
Dynamic config (runtime, tenant_pain_settings via API)
Section titled “Dynamic config (runtime, tenant_pain_settings via API)”Tenant admins can change at runtime:
| Key | Default | Purpose |
|---|---|---|
module_label | 'Pain & Stats' | Page title + nav label |
module_description | — | Shown on subscription/upgrade screens |
enable_body_map | true | Show/hide Body Map pillar |
enable_vitals | true | Show/hide Vital Signs |
enable_mind | true | Show/hide Mental State |
standalone_mode | false | Reserved for standalone deployment |
storage_key_prefix | 'lc' | localStorage namespace |
Remaining hardcoded items (future work)
Section titled “Remaining hardcoded items (future work)”MIND_DOMAINSlabel and narrative strings inMindModal.tsx— would need a factory function accepting overrides from configVITAL_CONFIGStier labels/descriptions inVitalsTrendChart.tsx— same patternPAIN_COLORS/PAIN_LABELSinpainColors.tsLINE_COLOURSinPainTrendChart.tsx- LynCareOS shell brand (
Layout.tsx) — requires a separate tenant branding API
13. Body Map — Polygon Zone System
Section titled “13. Body Map — Polygon Zone System”File:
frontend/src/components/pain/BodyMap.tsx
Overview
Section titled “Overview”Each anatomical region (zone) is defined as an 8-point polygon stored as percentages of the image-container element (0–100 × 0–100). Because the coordinates are percentages — not pixels — zones automatically scale to any screen size without JavaScript intervention. The same numbers describe the same proportional area on a 1080p desktop, a 390 px iPhone, or anything in between.
Why polygons instead of rectangles?
Section titled “Why polygons instead of rectangles?”The original implementation used axis-aligned rectangles (x1, y1, x2, y2). Rectangle zones overlap on small screens (especially mobile) because the body image is narrow; adjacent rectangular zones frequently share edges or corners, causing taps near boundaries to resolve to the wrong region.
8-point polygons allow each zone to follow the body’s natural contours — a tapered forearm, a curved shoulder, a narrow ankle — reducing overlap and giving accurate region detection even at small image widths.
The 8-point format
Section titled “The 8-point format”Points are ordered clockwise from the top-centre:
index 0 = N (top-centre) index 1 = NE (top-right) index 2 = E (mid-right) index 3 = SE (bottom-right) index 4 = S (bottom-centre) index 5 = SW (bottom-left) index 6 = W (mid-left) index 7 = NW (top-left)A zone definition looks like:
{ slug: 'shin-left', label: 'Left Shin', pts: [ [36.0,70.0], [44.0,70.0], [44.0,75.5], [44.0,81.0], [36.0,81.0], [28.0,81.0], [28.0,75.5], [28.0,70.0]] }r() bootstrap helper
Section titled “r() bootstrap helper”The r(slug, label, x1, y1, x2, y2) function converts an axis-aligned rectangle into an 8-point polygon (the 8 points are the 4 corners plus 4 edge midpoints). All existing zones start as r() calls seeded from the original calibrated rectangle values. Once a zone is reshaped via the calibration tool, replace its r() call with a literal pts array. Zones that are naturally rectangular can stay as r() calls permanently.
Hit-testing
Section titled “Hit-testing”Region detection uses a ray-casting point-in-polygon algorithm. A ray is cast from the tap coordinate in the +X direction; the number of polygon edges it crosses determines inside/outside. Works correctly for any convex or concave simple polygon.
Zones are tested in array order; the first matching zone wins. Where two zones overlap (e.g. groin / hip), place the higher-priority zone earlier in the array.
If no zone matches (e.g. a tap in the image margin), the fallback resolves to the zone whose centroid is nearest the tap point. This ensures every tap produces a valid region.
Calibration tool (dev user ID 1 only)
Section titled “Calibration tool (dev user ID 1 only)”The calibration tool is restricted to user ID 1 and is available in all environments (not just DEV) so that calibration can be done against the production image if needed.
Activating calibration:
- Log in as user ID 1.
- Go to the Pain & Stats page.
- Click the ⚙ Cal pill in the top-right corner of the body map. The overlay appears immediately.
What you see:
- All zone polygons rendered as coloured outlines over the body image.
- Zone labels at each polygon’s centroid (clickable).
- At the bottom: Group Transform sliders.
Editing a single zone:
- Click a zone label to select it.
- Eight handle dots appear at the N/NE/E/SE/S/SW/W/NW positions.
- Drag any handle to move that vertex to the correct anatomical position on the image.
- Click the label again (or click a different zone) to deselect.
Group Transform (bulk resize for new body types):
| Control | Effect |
|---|---|
| Scale X | Stretches/compresses ALL zones horizontally around the origin |
| Scale Y | Stretches/compresses ALL zones vertically around the origin |
| Origin X | Horizontal anchor point for the scale (default 50 = centre) |
| Origin Y | Vertical anchor point for the scale (default 50 = centre) |
The group transform is a live preview — it does not permanently change the zone coordinates until you click Bake ↓. After baking, the scale is folded into the per-zone data in calibPoints and the sliders reset to 1.0/1.0. You can then fine-tune individual zones on top.
Copying calibrated values:
The readout panel above the map (shown in PainBodyMapTab.tsx) updates in real time as you drag. Click 📋 Copy all to copy the paste-ready output.
The output format is:
// Calibrated zones — MALE// === FRONT === { slug: 'shin-left', label: 'Left Shin', pts: [[36.0,70.0],...] }, { slug: 'shin-right', label: 'Right Shin', pts: [[64.0,70.0],...] },Paste these into the appropriate zone array in BodyMap.tsx to replace the r() calls.
Adding a new body type
Section titled “Adding a new body type”Use this process when introducing a new image variant (e.g. a shorter, wider body shape, a child body, or a different gender variant):
-
Prepare images — Generate at identical canvas dimensions to the existing set. Both front and back views needed. Export as transparent PNG at
frontend/public/images/body-{variant}-front.pngandbody-{variant}-back.png. -
Extend the type system — Modify the
genderprop type (or introduce a separatebodyTypeprop) inBodyMap.tsx,PainBodyMapTab.tsx, andPainTracking.tsx. -
Seed zone arrays — Add new arrays (e.g.
FRONT_ZONES_CHILD_MALE) usingr()calls with the existing adult values as starting coordinates. -
Extend
getZones()— Branch on the new type to return the new arrays. -
Calibrate with Group Transform first — In calibration mode, use the Scale X / Scale Y sliders to bulk-resize the existing zones to approximately fit the new image (e.g. narrow and shorten for a child). Then bake and fine-tune individual zones.
-
Fine-tune individual zones — Select each zone, drag the 8 handles to match the actual anatomy visible in the image.
-
Bake final output — Copy the readout and paste the updated
ptsvalues into the new zone array constants.
Library evaluation — why we build our own
Section titled “Library evaluation — why we build our own”The following open-source body-map libraries were evaluated before building the custom component:
| Library | npm | Status | Why we didn’t use it |
|---|---|---|---|
react-body-map | ✓ | Active | SVG-only; no custom image layer; no free-placement hotspots; anatomy fixed to one adult male outline |
react-muscle-highlighter | ✓ | Active (Jan 2026) | Muscle-group focus (fitness/physio); fixed SVG diagrams; no custom images; no arbitrary pain-point placement |
react-body-highlighter | ✓ | Active | Same SVG-only ancestry (react-native-body-highlighter); same limitations; no polygon editing |
body-muscles | ✓ | Active | 70+ regions, framework-agnostic, but imperative DOM API (not idiomatic React); fixed anatomy; no custom images |
Decision: build custom. LynCareOS requires:
- (a) Custom photographic body images — real photos, not clip art outlines; required for brand appeal and for body-type variants.
- (b) Free-placement pain hotspots — the exact tap coordinate is stored, not just the region slug. This allows precise visualisation of where within a region the pain is felt.
- (c) Editable polygon zones — zones must be calibrated against the specific photos used, as no external library’s SVG coordinates will align with a custom photographic image.
- (d) Group transform for body-type scaling — none of the libraries provide a way to adapt their fixed regions across body-type variants.
None of the evaluated libraries support (a)–(d) together. The custom implementation (~650 lines) gives full control at the cost of a one-time build effort.
Clinical anatomy (separate module)
Section titled “Clinical anatomy (separate module)”Pain & Stats production Record view is 2D only (BodyMap + skeleton PNG overlay). The experimental 3D turntable was decoupled on 2026-05-31 into:
- Package:
packages/clinical-anatomy/(@lyncareos/clinical-anatomy) - Billing slug (planned):
clinical_anatomyinbackend/billing/module_delivery.json - Plan: 2026-05-31-anatomy-viewer-r3f.md
- Debts: 32 D29 / D30
The main frontend does not import the package at launch. Owner preview: cd packages/clinical-anatomy && npm run dev (port 5175). Future Pain integration uses a single lazy host file under frontend/src/integrations/ and toPainRegionTapHandler() — no body3d/ folder under components/pain/.
14. Branding & White-label Config
Section titled “14. Branding & White-label Config”What the module depends on (coupling to LynCareOS)
Section titled “What the module depends on (coupling to LynCareOS)”| Dependency | File(s) | Notes |
|---|---|---|
| Patient context | PatientContext | activePatient.id and gender |
| Theme | ThemeContext | resolvedTheme for chart colours |
| Auth | auth.py require_patient_access, require_carer_role, require_module | Standard LynCareOS auth deps |
| Module system | ModuleContext, ModuleGate, subscriptions table | Standard module integration |
| Chart theme | lib/chartTheme.ts | chartColors(isDark) utility |
| API client | lib/api.ts | Shared request() helper |
| UI components | components/ui/ClockPickerField.tsx | Used by VitalEntryModal |
What other modules depend on (reverse coupling)
Section titled “What other modules depend on (reverse coupling)”None. Pain & Stats does not export APIs or components consumed by other modules.
Removing Pain & Stats from LynCareOS
Section titled “Removing Pain & Stats from LynCareOS”To safely extract, remove or stub these points:
- Delete
routers/pain.py,vitals.py,mind.py,pain_settings.py(backend) - Delete
services/pain_service.py,vitals_service.py,mind_service.py - Delete
repositories/pain.py,schemas/pain.py - Remove
_painregistrations and imports frommain.py - Remove
pain_trackingfromMODULESindatabase.py - Remove
pain_trackingfromMODULE_METAinsubscriptions.py - Delete
pages/PainTracking.tsxandcomponents/pain/(frontend) - Remove
/painroute andpain_trackingentries fromApp.tsx,Layout.tsx,Settings.tsx,admin/Subscriptions.tsx,ModuleUpgrade.tsx - Remove
api.pain,api.vitals,api.mind, and related types fromapi.ts
15. Implementation Notes
Section titled “15. Implementation Notes”Known gaps for full standalone deployment
Section titled “Known gaps for full standalone deployment”-
Standalone auth mode:
standalone_mode = truein tenant settings is not yet enforced. When implementing, the backend needs auth branches that skip patient context and use tenant-wide scope (see Shopping module’s standalone mode for the pattern). -
MIND_DOMAINS / VITAL_CONFIGS configurability: Clinical narrative strings are hardcoded. To fully white-label, these should accept overrides via the tenant settings API (add columns or a JSON blob to
tenant_pain_settings). -
Shell branding: The LynCareOS nav shell uses the hardcoded “LynCareOS” brand. Standalone deployments will provide their own shell. The
Layout.tsxnav label for Pain & Stats reads fromconfig.module_labelviausePainConfig(). -
Body map images: The white-label deployment must provide its own body diagram images at
${bodyMapImageBase}-${gender}-${side}.png. The existing PNG files at/images/body-*.pngare LynCareOS assets.
Migration strategy for existing deployments
Section titled “Migration strategy for existing deployments”The migration V058__pain_module_settings.sql is idempotent (CREATE TABLE IF NOT EXISTS). Running it on an existing database is safe. No data migration is required — existing tenants will use the default settings automatically since no row exists in tenant_pain_settings until they customise.
Calibration mode (user ID 1 only)
Section titled “Calibration mode (user ID 1 only)”Calibration tools are restricted to the user whose database ID is 1 (user.id === 1 from useAuth()). They are available in all environments so alignment can be verified against production images.
Body map zone calibration (PainBodyMapTab.tsx → BodyMap.tsx):
- Activated by clicking the ⚙ Cal pill (top-right corner of the body map).
- Keyboard shortcut:
Ctrl+Shift+K(still functional). - Shows the SVG polygon overlay with zone labels, 8-handle editing, and Group Transform sliders.
- Full workflow documented in Section 13.
Skeleton overlay calibration (SkeletonCalibPanel.tsx, desktop bone mode only):
- Activated by clicking the 🦴 Skel pill (next to Zones / Cal on the map).
- Male / Female toggle in the panel — calibrate each gender separately; paste into
SKEL_CALIB_MALEorSKEL_CALIB_FEMALEinskeletonCalibTypes.ts. - Sliders: Scale, Front X, Back X (independent), Y (both), Body opacity, Skeleton opacity.
- Copy values emits paste-ready TypeScript for the active gender constant.
- Uses
transform: scale()for sizing;allowBodyOverflowonBodyMapprevents clipping while tuning.
Head image calibration (MindModal.tsx):
- Activated by clicking the ⚙ sprocket button in the MindModal header.
- Drag the head image to reposition it relative to the crown lines.
- Female-only (calibration readout shows
headOverlapandmarginLeft— paste back into theheadOverlapandimgMarginLeftconstants inMindModal.tsx).
Migration notes for existing calibrated zone values
Section titled “Migration notes for existing calibrated zone values”The original zone system used (x1, y1, x2, y2) rectangles. The new system uses 8-point polygons generated via the r() helper with the same rectangle values, so no behaviour change occurs on first deploy. The shapes start rectangular and improve as you calibrate them. Hit-testing is identical for rectangular polygons (ray-casting over a rectangle gives the same result as the old bounds check).