Skip to content

26 — Pain & Stats Module

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):

CapabilitySlugTierRoute
Vital Signs (standalone)vitals_trackingFamily, Complete/vitals
Pain & Stats (body map, mind, trends; vitals embedded on Complete)pain_trackingComplete only/pain

Phase: Extractable (post-refactor)


  1. Vision
  2. Deployment Modes
  3. Subscription & Access Control
  4. Three Pillars
  5. Roles & Permissions
  6. UX & Navigation
  7. Trend Analysis
  8. Clinical Health Tiers
  9. Database Schema
  10. API Design
  11. Backend Architecture
  12. Frontend Architecture
  13. Body Map — Polygon Zone System
  14. Branding & White-label Config
  15. Integration Points
  16. Implementation Notes

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).


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_settings row (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_prefix separates localStorage keys from any co-deployed app

Note: The standalone_mode flag in tenant_pain_settings is provisioned but the API routing branches for patient-less tenant-scoped access are not yet implemented. See the Implementation Notes section.


Backend module gates (main.py):

RouterDependencyModule slug
vitals.py_vitalsvitals_tracking
pain.py, mind.py_painpain_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)”
ViewportControlsWhat 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 ] rowBody: 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'.

mapTypeBody illustrationSkeletonPain recording
BodyFull opacity; no skeletonHiddenSame 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 panelsSame 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 sideHotspot-based bone regions

Baked in frontend/src/components/pain/skeletonCalibTypes.ts (percentage-based — scales with panel width on any screen):

ConstantPurpose
SKEL_CALIB_FEMALEOverlay alignment for female body art (calibrated 2026-05-22)
SKEL_CALIB_MALEOverlay 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 for SKEL_CALIB_* constants; not shipped in production builds.
  • SkeletonMapOverlay.tsx — renders /skeleton-front.png or /skeleton-back.png inside each BodyMap side panel using transform: scale() (avoids Tailwind max-width: 100% on images blocking scale).
  • BodyMap props: frontSkeletonOverlay, backSkeletonOverlay, bodyImageOpacity, allowBodyOverflow, boneOverlayMode (bone mode only).
  • Bone mode hit testing (2026-06-02): skeleton overlay is pointer-events-none; the side panel is pointer-events-none so the Body / Bone / Mind pill row (PainLayerToggle, z-30 in PainBodyMapTab) stays clickable when the scaled skeleton extends above the figure. Pain taps attach to the body image only (pointer-events-auto on 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_layer so carried-forward bone entries land on the Bone view, not the Body view
  • Historical navigation: browse any past date

Body pain and bone pain are kept fully independent at three levels:

LayerBody view (mapType = 'body')Bone view (mapType = 'skeleton')
Databody_layer ∈ {'front','back','surface'}body_layer ∈ {'front-skeleton','back-skeleton','skeleton'}
Map rendermapEntries filtered to body-layer rows only — bone dots never appear over the bodymapEntries 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).

  • Three vital types: Pulse (bpm), SpO₂ (%), Temperature (°C/°F)
  • Multiple readings per day at different times (each has an HH:MM timestamp)
  • Per-vital-type unique constraint at the minute level (prevents accidental duplicates)
  • Delete individual readings
  • 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)

ActionObserverCarerTenant AdminSuper 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——✓✓

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 62dvw width (NARROW_MAP_MAX_W_CLASS in BodyMap.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.


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.

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.

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.


Five-tier system from Normal → Critical. Based on NHS/Cleveland Clinic adult resting values.

TierRange
Normal60–100
Watch50–59 or 101–110
Caution40–49 or 111–130
Concerning31–39 or 131–150
Critical≤30 or >150
TierRange
Normal≥95
Watch93–94
Caution90–92
Concerning85–89
Critical<85
TierRange
Normal36.1–37.5
Watch35.5–36.0 or 37.6–38.0
Caution35.0–35.4 or 38.1–38.9
Concerning34.5–34.9 or 39.0–39.9
Critical<34.5 or ≥40.0

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.

Created in V050__pain_tracking.sql.

ColumnTypeNotes
idSERIAL PK
tenant_idINTEGER FK→ tenants
patient_idINTEGER FK→ patients
dateTEXTYYYY-MM-DD
body_regionTEXTzone slug
region_labelTEXTdisplay name
body_sideTEXT‘front’ or ‘back’
anatomy_typeTEXTmuscle/bone/joint/organ/tissue/nerve
body_layerTEXT'front'|'back'|'front-skeleton'|'back-skeleton'|'skeleton' (legacy)|'mind'|'surface' — V082 column; V092 CHECK
pain_levelSMALLINT0–10
indicator_x_pctREALhotspot x (% of image width)
indicator_y_pctREALhotspot y (% of image height)
notesTEXTnullable
recorded_byINTEGER FK→ users
created_at / updated_atTIMESTAMPTZ

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

Created in V050__pain_tracking.sql + V051__V053__V055__V057 amendments.

ColumnTypeNotes
idSERIAL PK
tenant_id / patient_idINTEGER FK
dateTEXTYYYY-MM-DD
recorded_timeTEXTHH:MM, NOT NULL, DEFAULT ‘00:00’
pulse_bpmSMALLINTnullable, 20–300
spo2_pctSMALLINTnullable, 30–100
temp_celsiusREALnullable, 30–45
recorded_byINTEGER FK
created_at / updated_atTIMESTAMPTZ

Partial unique indexes (one per vital type to allow multi-vital readings at different times):

  • uq_vitals_pulse_time on (tenant_id, patient_id, date, recorded_time) WHERE pulse_bpm IS NOT NULL
  • uq_vitals_spo2_time — same, WHERE spo2_pct IS NOT NULL
  • uq_vitals_temp_time — same, WHERE temp_celsius IS NOT NULL

Created in V054__mind_tracking.sql.

ColumnTypeNotes
idSERIAL PK
tenant_id / patient_idINTEGER FK
dateTEXTYYYY-MM-DD
mood / anxiety / fear / cognition / behaviour / sleep / copingSMALLINTnullable, 0–4
recorded_byINTEGER FK
created_at / updated_atTIMESTAMPTZ

Unique constraint: (tenant_id, patient_id, date) — one assessment per day.

Created in V058__pain_module_settings.sql.

ColumnTypeDefaultNotes
tenant_idINTEGER PK FK→ tenants
module_labelTEXT‘Pain & Stats’display name
module_descriptionTEXTnull
enable_body_mapBOOLEANtrue
enable_vitalsBOOLEANtrue
enable_mindBOOLEANtrue
standalone_modeBOOLEANfalsereserved for future
storage_key_prefixTEXT‘lc’localStorage namespace
updated_atTIMESTAMPTZnow()

All endpoints are prefixed /api and gated on pain_tracking module.

MethodPathAuthDescription
GET/patients/{id}/pain?date=patient_accessList entries for a date
GET/patients/{id}/pain/trend?region=&days=patient_accessSingle-region trend
GET/patients/{id}/pain/trend/all?days=patient_accessAll-region trend
GET/patients/{id}/pain/latest?before=patient_accessCarry-forward source
POST/patients/{id}/paincarer_roleCreate entry
DELETE/patients/{id}/pain/{entry_id}carer_roleDelete entry
MethodPathAuthDescription
GET/patients/{id}/vitals?date=patient_accessList readings
GET/patients/{id}/vitals/trend?days=patient_accessRaw readings for band chart
POST/patients/{id}/vitals/{date}carer_roleCreate reading
DELETE/patients/{id}/vitals/{entry_id}carer_roleDelete reading
MethodPathAuthDescription
GET/patients/{id}/mind?date=patient_accessGet assessment (null if none)
PUT/patients/{id}/mind/{date}carer_roleCreate or update assessment
GET/patients/{id}/mind/trend?days=patient_accessDomain scores over N days
MethodPathAuthDescription
GET/pain/settingstenant_memberTenant settings (merged with defaults)
PATCH/pain/settingstenant_adminUpdate settings

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 logic
services/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, PainSettingsPatch

Auth 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 gate

Vitals 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.


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 type

Data flow:

PainTracking → usePainConfig → api.pain.getSettings → tenant_pain_settings
PainBodyMapTab → usePainDateData → api.pain + api.vitals
PainTrendTab → usePainTrends → api.pain.trendAll + api.mind.trend + api.vitals.trend

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:

KeyDefaultPurpose
bodyMapImageBase/images/bodyBody diagram image prefix
headImageBase/images/headHead 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:

KeyDefaultPurpose
module_label'Pain & Stats'Page title + nav label
module_description—Shown on subscription/upgrade screens
enable_body_maptrueShow/hide Body Map pillar
enable_vitalstrueShow/hide Vital Signs
enable_mindtrueShow/hide Mental State
standalone_modefalseReserved for standalone deployment
storage_key_prefix'lc'localStorage namespace
  • MIND_DOMAINS label and narrative strings in MindModal.tsx — would need a factory function accepting overrides from config
  • VITAL_CONFIGS tier labels/descriptions in VitalsTrendChart.tsx — same pattern
  • PAIN_COLORS / PAIN_LABELS in painColors.ts
  • LINE_COLOURS in PainTrendChart.tsx
  • LynCareOS shell brand (Layout.tsx) — requires a separate tenant branding API

File: frontend/src/components/pain/BodyMap.tsx

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.

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.

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]
] }

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.

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.


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:

  1. Log in as user ID 1.
  2. Go to the Pain & Stats page.
  3. 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:

  1. Click a zone label to select it.
  2. Eight handle dots appear at the N/NE/E/SE/S/SW/W/NW positions.
  3. Drag any handle to move that vertex to the correct anatomical position on the image.
  4. Click the label again (or click a different zone) to deselect.

Group Transform (bulk resize for new body types):

ControlEffect
Scale XStretches/compresses ALL zones horizontally around the origin
Scale YStretches/compresses ALL zones vertically around the origin
Origin XHorizontal anchor point for the scale (default 50 = centre)
Origin YVertical 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.


Use this process when introducing a new image variant (e.g. a shorter, wider body shape, a child body, or a different gender variant):

  1. 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.png and body-{variant}-back.png.

  2. Extend the type system — Modify the gender prop type (or introduce a separate bodyType prop) in BodyMap.tsx, PainBodyMapTab.tsx, and PainTracking.tsx.

  3. Seed zone arrays — Add new arrays (e.g. FRONT_ZONES_CHILD_MALE) using r() calls with the existing adult values as starting coordinates.

  4. Extend getZones() — Branch on the new type to return the new arrays.

  5. 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.

  6. Fine-tune individual zones — Select each zone, drag the 8 handles to match the actual anatomy visible in the image.

  7. Bake final output — Copy the readout and paste the updated pts values 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:

LibrarynpmStatusWhy we didn’t use it
react-body-map✓ActiveSVG-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✓ActiveSame SVG-only ancestry (react-native-body-highlighter); same limitations; no polygon editing
body-muscles✓Active70+ 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.


Pain & Stats production Record view is 2D only (BodyMap + skeleton PNG overlay). The experimental 3D turntable was decoupled on 2026-05-31 into:

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/.


What the module depends on (coupling to LynCareOS)

Section titled “What the module depends on (coupling to LynCareOS)”
DependencyFile(s)Notes
Patient contextPatientContextactivePatient.id and gender
ThemeThemeContextresolvedTheme for chart colours
Authauth.py require_patient_access, require_carer_role, require_moduleStandard LynCareOS auth deps
Module systemModuleContext, ModuleGate, subscriptions tableStandard module integration
Chart themelib/chartTheme.tschartColors(isDark) utility
API clientlib/api.tsShared request() helper
UI componentscomponents/ui/ClockPickerField.tsxUsed 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.

To safely extract, remove or stub these points:

  1. Delete routers/pain.py, vitals.py, mind.py, pain_settings.py (backend)
  2. Delete services/pain_service.py, vitals_service.py, mind_service.py
  3. Delete repositories/pain.py, schemas/pain.py
  4. Remove _pain registrations and imports from main.py
  5. Remove pain_tracking from MODULES in database.py
  6. Remove pain_tracking from MODULE_META in subscriptions.py
  7. Delete pages/PainTracking.tsx and components/pain/ (frontend)
  8. Remove /pain route and pain_tracking entries from App.tsx, Layout.tsx, Settings.tsx, admin/Subscriptions.tsx, ModuleUpgrade.tsx
  9. Remove api.pain, api.vitals, api.mind, and related types from api.ts

  1. Standalone auth mode: standalone_mode = true in 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).

  2. 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).

  3. Shell branding: The LynCareOS nav shell uses the hardcoded “LynCareOS” brand. Standalone deployments will provide their own shell. The Layout.tsx nav label for Pain & Stats reads from config.module_label via usePainConfig().

  4. 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-*.png are 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 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_MALE or SKEL_CALIB_FEMALE in skeletonCalibTypes.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; allowBodyOverflow on BodyMap prevents 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 headOverlap and marginLeft — paste back into the headOverlap and imgMarginLeft constants in MindModal.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).