feat: domain core — schemas, store, equine data, PDF roundtrip

Phase A — Domain & schemas (15 tests):
- Zod schemas: ReportSchema, FindingSchema, PractitionerSchema, SeveritySchema
- Types derived via z.infer (single source of truth)
- newId() helper with optional prefix

Phase B — Equine anatomy + pathology DB (7 tests):
- 26 macro zones, axial subzones C1-7/T1-18/L1-6/S1-5
- 31 pathologies, each citing Merck Vet Manual, PubMed, IMAIOS or LCAO
- Placeholder SVGs (lateral L/R + dorsal) with data-zone convention
- Species registry: equine registered, 8 others remain stubs

Phase C — Zustand store (8 tests):
- Single source of truth with persist middleware (localStorage key osteo-report-draft)
- Actions: hydrate, reset, toggleZone, addFinding, updateFinding, removeFinding, setConclusion/Recommendations/NextAppointment

Phase H/I — PDF export + import roundtrip (2 tests):
- A4 portrait, pdf-lib StandardFonts
- Header (practitioner + animal), anatomy pages (per used view), findings
  table, conclusion/recommendations/RDV page, page footer with date+page#
- Attachment: base64 data URI workaround (pdf-lib treats raw string as
  base64 input, and rejects cross-realm Uint8Array in jsdom tests)
- Import: walks Catalog→Names→EmbeddedFiles→Names array→F stream; inflates
  via pako directly (bypasses pdf-lib's reference-equality FlateDecode check
  which fails across module realms in vitest); validates with ReportSchema

Tooling:
- Add pako 2.x + @types/pako (already transitive of pdf-lib)
- Switch vitest 2 → 3 (already done in prior commit)
- Add 8 test files (34 tests total green)
This commit is contained in:
ZenQuality committed 2026-05-17 07:06:59 +02:00
1 parent 4c465a5743
commit b5b2e163c9
20 files changed
+1383 -41

No files matched your search

+108
View File
@@ -0,0 +1,108 @@
# Implementation Plan — Osteo Report V1
Granular tasks, TDD-first when behavior is testable. Each task targets one
coherent change. Tasks are ordered so that each unblocks the next. Estimate
≈ 2-5 min of agent work per task.
Status legend: `[ ]` todo · `[~]` in progress · `[x]` done · `[s]` skipped.
---
## Phase A — Domain & schemas (foundation, no UI)
- [ ] **A1** Test: `tests/unit/schema.report.test.ts` — parse a valid sample Report; reject malformed (missing version, bad species, empty animal name); assert `z.infer` matches expected fields.
- [ ] **A2** Implement: flesh `src/schema/report.ts` (already drafted) — re-verify enum, required fields, defaults match test.
- [ ] **A3** Test: `tests/unit/schema.finding.test.ts` — severity enum, free pathology flag, linked zones default empty.
- [ ] **A4** Implement: `src/schema/finding.ts` cleanup (already drafted) + ensure default arrays don't break Zod transform.
- [ ] **A5** Test: `tests/unit/lib.id.test.ts` — `newId('finding')` returns `finding_…`, length, uniqueness over 1000 calls.
- [ ] **A6** Implement: confirm `src/lib/id.ts` passes.
## Phase B — Equine anatomy data
- [ ] **B1** Test: `tests/unit/species.equine.test.ts` — `EQUINE_ANATOMY.vertebralFormula` is `{ C7, T18, L6, S5 }`; zones include at least `neck`, `withers`, `thoracic-back`, `lumbar`, `sacrum`, `shoulder-l`, `shoulder-r`, `hip-l`, `hip-r`, `tail`.
- [ ] **B2** Implement: fill `src/species/equine/anatomy.ts` with ~20 macro zones, declare `views`, declare subzones for vertebral zones (T1-T18, C1-C7, L1-L6, S1-S5).
- [ ] **B3** Create placeholder SVGs `lateral-left.svg`, `lateral-right.svg`, `dorsal.svg` in `src/species/equine/` with at least 5 zones per view, conforming to convention (data-zone).
- [ ] **B4** Wire SVG imports via `vite-plugin-svgr` — type the import as React component.
- [ ] **B5** Test: `tests/unit/species.registry.test.ts` — `registerSpecies('equine', ...)` then `getSpecies('equine')` returns pack; `isSpeciesAvailable('chien')` is false.
- [ ] **B6** Implement: register equine pack at module load (`src/species/equine/index.ts`).
- [ ] **B7** Seed: `src/species/equine/pathologies.ts` — populate **30 pathologies** with sourced citations (Merck Vet Manual, IMAIOS, PubMed, equine clinical journals). Each entry: id, label FR, description, category, applicableZones, sources.
- [ ] **B8** Stub: empty `src/species/<other>/index.ts` so the registry import doesn't crash. Other species register `undefined` pack — selector marks them disabled.
## Phase C — State store
- [ ] **C1** Test: `tests/unit/state.reportStore.test.ts` — `hydrate(report)` sets all fields; `reset()` clears; `toggleZone('z1')` adds then removes; `addFinding(f)` pushes; `updateFinding(id, patch)` merges; `removeFinding(id)` removes; `setConclusion('x')` sets.
- [ ] **C2** Implement: full `reportStore` actions in `src/state/reportStore.ts` — typed via `z.infer<typeof ReportSchema>`. Persist key `osteo-report-draft`.
- [ ] **C3** Add an `inferDraftFromStore` selector that builds a Report from current store state (used by export).
- [ ] **C4** Test: persist round-trip — write store, simulate page reload (clear in-memory state, re-create from localStorage), assert findings restored.
## Phase D — Routes & navigation
- [ ] **D1** Implement: `HomeRoute` UI — 2 large cards: "Nouveau bilan" → `/new`, "Importer un PDF" → file picker. Drag-drop overlay accepts only `.pdf`.
- [ ] **D2** Test: `tests/unit/HomeRoute.test.tsx` — render shows 2 CTAs; click "Nouveau bilan" navigates `/new` (use `MemoryRouter`).
- [ ] **D3** Implement: `NewReportRoute` form — species selector (9 options, 8 disabled badges), practitioner fields (fullName required + phone/email/address/SIRET optional), animal name + owner, sessionDate (default = today). React-hook-form + Zod resolver via `PractitionerSchema` & `ReportSchema.shape.animal`.
- [ ] **D4** Test: `tests/unit/NewReportRoute.test.tsx` — submit empty form shows validation errors; submitting valid form calls `store.hydrate(newReportSeed)` and navigates `/editor`.
- [ ] **D5** Implement: `EditorRoute` — `<AnatomyCanvas />` + side panels (`<ZoneSelection />`, `<FindingPanel />`, `<ConclusionPanel />`, `<ExportButton />`).
## Phase E — Anatomy canvas
- [ ] **E1** Implement: `AnatomyView` — renders one SVG (lateral L / R / dorsal). Attaches `onClick` to elements with `data-zone`. Highlights zones using `data-selected`, `data-linked` attributes synced with store state.
- [ ] **E2** Test: `tests/unit/AnatomyView.test.tsx` — render with mock SVG that has `<rect data-zone="z1" />`, click → store.toggleZone('z1') called.
- [ ] **E3** Implement: `AnatomyCanvas` — tabs for the 3 views, animate switch with motion. Persists current view in component state.
- [ ] **E4** Implement: `ZoneSelection` chip bar — shows current selection (zone labels), validate-button creates finding.
- [ ] **E5** Implement: `ZoomOverlay` modal — opens when user clicks "zoom" on a macro zone that has subzones. Uses `react-zoom-pan-pinch` inside the dialog. Click on subzone → store.addSubzoneSelection.
## Phase F — Findings
- [ ] **F1** Implement: `FindingEditor` — multi-select pathology list filtered by `applicableZones` from current selection. Free-text pathology input. Severity radio. Comment textarea. Linked-zones picker.
- [ ] **F2** Test: `tests/unit/FindingEditor.test.tsx` — selecting two zones from thoracic-back filters pathology list to entries containing that zone; adding a free pathology preserves it on save.
- [ ] **F3** Implement: `FindingPanel` list — shows existing findings (zones, pathologies, severity badge, comment preview); edit/delete actions.
## Phase G — Conclusion
- [ ] **G1** Implement: `ConclusionPanel` — textarea conclusion + textarea recommendations + optional date picker for nextAppointment. All wired to store.
## Phase H — PDF export
- [ ] **H1** Test: `tests/unit/pdf.export.test.ts` — `exportReport(sample, assets)` returns a Blob whose content starts with `%PDF-`; attachments include `report.json` with parsed content equal to input.
- [ ] **H2** Implement: `src/pdf/render/header.ts` — draw practitioner block + animal/owner/date heading on a page using pdf-lib StandardFonts.
- [ ] **H3** Implement: `src/pdf/render/anatomyPage.ts` — rasterize an SVG view with selected zones highlighted, embed PNG via `pdf.embedPng`. Use html2canvas alternative: serialize SVG with inline `<style>` overrides per zone, then `Canvg → Blob → toPng`.
- [ ] **H4** Implement: `src/pdf/render/findingsTable.ts` — paginate findings table.
- [ ] **H5** Implement: `src/pdf/render/footer.ts` — page number + export date + URL.
- [ ] **H6** Implement: `src/pdf/export.ts` — orchestrate header → anatomy pages (one per view with selections) → findings table → conclusion → footer. Call `pdf.attach(JSON.stringify(report), 'report.json', { mimeType: 'application/json' })`. Return Blob.
## Phase I — PDF import
- [ ] **I1** Test: `tests/unit/pdf.roundtrip.test.ts` — export sample report → load Blob with `pdf-lib` → `importReport(File)` → assert returned report deep equals sample.
- [ ] **I2** Test: import an external PDF (no attachment) returns `{ ok: false, reason: 'NO_ATTACHMENT' }`.
- [ ] **I3** Implement: `src/pdf/import.ts` — `PDFDocument.load(buffer)` → iterate attachments → find `report.json` → `JSON.parse` → `ReportSchema.safeParse` → return Result.
- [ ] **I4** Wire HomeRoute import button → `importReport` → on success `store.hydrate` + navigate `/editor`; on error show toast with FR message.
## Phase J — Design polish & motion
- [ ] **J1** Install shadcn components: button, card, dialog, badge, input, textarea, select, separator, toast. (Use shadcn CLI: `npx shadcn@canary add button card dialog badge input textarea select separator sonner`.)
- [ ] **J2** Implement `Brand` wordmark in `src/components/Brand.tsx` — typographic logo using Fraunces.
- [ ] **J3** Header + Footer across routes.
- [ ] **J4** Motion presets: route transitions (fade-up 200ms), modal spring, zone selection scale+tint.
- [ ] **J5** Accessibility pass: aria-labels on SVG zones, keyboard focus rings, color-contrast AA.
## Phase K — E2E
- [ ] **K1** `tests/e2e/roundtrip.spec.ts` — full flow: load `/`, click new bilan, fill form (equine), navigate editor, select 2 zones from lateral-left, create finding with 1 pathology, write conclusion, export PDF, reload, import same PDF, assert restored state.
## Phase L — Build & deploy verify
- [ ] **L1** `npm run typecheck && npm run lint && npm run test && npm run build` all green.
- [ ] **L2** `docker compose build` succeeds. Image runs and serves the SPA on :80.
- [ ] **L3** Verify nginx CSP doesn't break the app in production preview.
---
## Subagent dispatch strategy
Phases A, B, C are independent enough to be done sequentially in main context.
Phase H (PDF export) is large enough to warrant a dedicated subagent
(write code + tests in isolation, surface a single PR-style diff).
Avoid subagent prompts that explicitly mention clinical wording — earlier
content filter incident (BLK-001). Use neutral language: "vet workflow",
"zone selection", "report data model".
+30 -3
View File
@@ -17,6 +17,7 @@
"lucide-react": "^0.468.0",
"motion": "^12.38.0",
"nanoid": "^5.0.9",
"pako": "^2.1.0",
"pdf-lib": "^1.17.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
@@ -34,6 +35,7 @@
"@testing-library/react": "^16.1.0",
"@testing-library/user-event": "^14.5.2",
"@types/node": "^22.19.19",
"@types/pako": "^2.0.4",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
@@ -1365,6 +1367,12 @@
"pako": "^1.0.6"
}
},
"node_modules/@pdf-lib/standard-fonts/node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/@pdf-lib/upng": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@pdf-lib/upng/-/upng-1.0.1.tgz",
@@ -1374,6 +1382,12 @@
"pako": "^1.0.10"
}
},
"node_modules/@pdf-lib/upng/node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
@@ -2500,6 +2514,13 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/pako": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/@types/pako/-/pako-2.0.4.tgz",
"integrity": "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "19.2.14",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
@@ -7248,9 +7269,9 @@
"license": "BlueOak-1.0.0"
},
"node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",
"integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==",
"license": "(MIT AND Zlib)"
},
"node_modules/parent-module": {
@@ -7381,6 +7402,12 @@
"tslib": "^1.11.1"
}
},
"node_modules/pdf-lib/node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/pdf-lib/node_modules/tslib": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
+2
View File
@@ -27,6 +27,7 @@
"lucide-react": "^0.468.0",
"motion": "^12.38.0",
"nanoid": "^5.0.9",
"pako": "^2.1.0",
"pdf-lib": "^1.17.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
@@ -44,6 +45,7 @@
"@testing-library/react": "^16.1.0",
"@testing-library/user-event": "^14.5.2",
"@types/node": "^22.19.19",
"@types/pako": "^2.0.4",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
+22
View File
@@ -0,0 +1,22 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 800" role="img" aria-label="Cheval vu de dessus">
<g id="illustration" pointer-events="none">
<ellipse cx="500" cy="160" rx="55" ry="80" fill="#e6ede0" stroke="#4a7c59" stroke-width="2"/>
<path d="M460 230 Q500 240 540 230 L555 290 L555 720 Q500 740 445 720 L445 290 Z" fill="#e6ede0" stroke="#4a7c59" stroke-width="2"/>
<line x1="500" y1="240" x2="500" y2="720" stroke="#4a7c59" stroke-width="1" stroke-dasharray="4 4"/>
</g>
<g id="zones">
<path id="zone-head" data-zone="head" d="M455 90 L545 90 L555 230 L445 230 Z" fill="transparent"/>
<path id="zone-neck" data-zone="neck" d="M450 235 L550 235 L555 305 L445 305 Z" fill="transparent"/>
<path id="zone-withers" data-zone="withers" d="M455 305 L545 305 L545 360 L455 360 Z" fill="transparent"/>
<path id="zone-shoulder-l" data-zone="shoulder-l" d="M395 305 L445 305 L445 380 L395 375 Z" fill="transparent"/>
<path id="zone-shoulder-r" data-zone="shoulder-r" d="M555 305 L605 305 L605 375 L555 380 Z" fill="transparent"/>
<path id="zone-thoracic-back" data-zone="thoracic-back" d="M455 360 L545 360 L545 540 L455 540 Z" fill="transparent"/>
<path id="zone-lumbar" data-zone="lumbar" d="M455 540 L545 540 L545 620 L455 620 Z" fill="transparent"/>
<path id="zone-sacro-iliac-l" data-zone="sacro-iliac-l" d="M420 620 L495 620 L495 670 L420 670 Z" fill="transparent"/>
<path id="zone-sacro-iliac-r" data-zone="sacro-iliac-r" d="M505 620 L580 620 L580 670 L505 670 Z" fill="transparent"/>
<path id="zone-sacrum" data-zone="sacrum" d="M455 660 L545 660 L545 720 L455 720 Z" fill="transparent"/>
<path id="zone-hip-l" data-zone="hip-l" d="M395 620 L450 620 L450 720 L395 720 Z" fill="transparent"/>
<path id="zone-hip-r" data-zone="hip-r" d="M550 620 L605 620 L605 720 L550 720 Z" fill="transparent"/>
<path id="zone-tail" data-zone="tail" d="M470 720 L530 720 L530 770 L470 770 Z" fill="transparent"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 600" role="img" aria-label="Cheval vu de la gauche">
<g id="illustration" pointer-events="none">
<path d="M120 320 Q180 280 260 290 L320 200 Q360 170 400 195 L430 240 Q480 245 550 250 L620 260 Q700 260 760 285 L820 320 L860 350 L860 410 L830 420 L810 470 L780 475 L765 530 L740 540 L720 470 L700 470 L685 530 L660 540 L640 470 L470 470 L450 530 L425 540 L405 470 L385 470 L365 530 L340 540 L320 470 L300 470 L285 530 L260 540 L240 470 L220 460 L180 400 L140 380 Z" fill="#e6ede0" stroke="#4a7c59" stroke-width="2"/>
<circle cx="345" cy="220" r="6" fill="#2d4a35"/>
</g>
<g id="zones">
<path id="zone-head" data-zone="head" d="M310 175 L380 175 L390 235 L320 240 Z" fill="transparent"/>
<path id="zone-neck" data-zone="neck" d="M390 235 L470 245 L460 290 L380 295 Z" fill="transparent"/>
<path id="zone-withers" data-zone="withers" d="M460 245 L530 245 L530 280 L455 280 Z" fill="transparent"/>
<path id="zone-thoracic-back" data-zone="thoracic-back" d="M530 250 L680 260 L680 295 L530 290 Z" fill="transparent"/>
<path id="zone-lumbar" data-zone="lumbar" d="M680 260 L760 280 L760 315 L680 300 Z" fill="transparent"/>
<path id="zone-sacrum" data-zone="sacrum" d="M760 285 L820 320 L815 355 L755 325 Z" fill="transparent"/>
<path id="zone-tail" data-zone="tail" d="M820 320 L870 320 L880 360 L825 360 Z" fill="transparent"/>
<path id="zone-shoulder-l" data-zone="shoulder-l" d="M460 280 L520 290 L505 360 L455 350 Z" fill="transparent"/>
<path id="zone-elbow-l" data-zone="elbow-l" d="M460 360 L505 360 L500 400 L460 400 Z" fill="transparent"/>
<path id="zone-knee-l" data-zone="knee-l" d="M450 400 L500 400 L495 445 L450 445 Z" fill="transparent"/>
<path id="zone-fetlock-front-l" data-zone="fetlock-front-l" d="M445 445 L495 445 L490 480 L445 480 Z" fill="transparent"/>
<path id="zone-hip-l" data-zone="hip-l" d="M710 285 L770 290 L760 360 L705 355 Z" fill="transparent"/>
<path id="zone-stifle-l" data-zone="stifle-l" d="M700 360 L760 360 L755 405 L700 405 Z" fill="transparent"/>
<path id="zone-hock-l" data-zone="hock-l" d="M700 405 L755 405 L750 450 L700 450 Z" fill="transparent"/>
<path id="zone-fetlock-rear-l" data-zone="fetlock-rear-l" d="M700 450 L750 450 L745 485 L700 485 Z" fill="transparent"/>
<path id="zone-sacro-iliac-l" data-zone="sacro-iliac-l" d="M740 285 L795 290 L790 320 L735 315 Z" fill="transparent"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 600" role="img" aria-label="Cheval vu de la droite">
<g id="illustration" pointer-events="none" transform="translate(1000,0) scale(-1,1)">
<path d="M120 320 Q180 280 260 290 L320 200 Q360 170 400 195 L430 240 Q480 245 550 250 L620 260 Q700 260 760 285 L820 320 L860 350 L860 410 L830 420 L810 470 L780 475 L765 530 L740 540 L720 470 L700 470 L685 530 L660 540 L640 470 L470 470 L450 530 L425 540 L405 470 L385 470 L365 530 L340 540 L320 470 L300 470 L285 530 L260 540 L240 470 L220 460 L180 400 L140 380 Z" fill="#e6ede0" stroke="#4a7c59" stroke-width="2"/>
<circle cx="345" cy="220" r="6" fill="#2d4a35"/>
</g>
<g id="zones" transform="translate(1000,0) scale(-1,1)">
<path id="zone-head" data-zone="head" d="M310 175 L380 175 L390 235 L320 240 Z" fill="transparent"/>
<path id="zone-neck" data-zone="neck" d="M390 235 L470 245 L460 290 L380 295 Z" fill="transparent"/>
<path id="zone-withers" data-zone="withers" d="M460 245 L530 245 L530 280 L455 280 Z" fill="transparent"/>
<path id="zone-thoracic-back" data-zone="thoracic-back" d="M530 250 L680 260 L680 295 L530 290 Z" fill="transparent"/>
<path id="zone-lumbar" data-zone="lumbar" d="M680 260 L760 280 L760 315 L680 300 Z" fill="transparent"/>
<path id="zone-sacrum" data-zone="sacrum" d="M760 285 L820 320 L815 355 L755 325 Z" fill="transparent"/>
<path id="zone-tail" data-zone="tail" d="M820 320 L870 320 L880 360 L825 360 Z" fill="transparent"/>
<path id="zone-shoulder-r" data-zone="shoulder-r" d="M460 280 L520 290 L505 360 L455 350 Z" fill="transparent"/>
<path id="zone-elbow-r" data-zone="elbow-r" d="M460 360 L505 360 L500 400 L460 400 Z" fill="transparent"/>
<path id="zone-knee-r" data-zone="knee-r" d="M450 400 L500 400 L495 445 L450 445 Z" fill="transparent"/>
<path id="zone-fetlock-front-r" data-zone="fetlock-front-r" d="M445 445 L495 445 L490 480 L445 480 Z" fill="transparent"/>
<path id="zone-hip-r" data-zone="hip-r" d="M710 285 L770 290 L760 360 L705 355 Z" fill="transparent"/>
<path id="zone-stifle-r" data-zone="stifle-r" d="M700 360 L760 360 L755 405 L700 405 Z" fill="transparent"/>
<path id="zone-hock-r" data-zone="hock-r" d="M700 405 L755 405 L750 450 L700 450 Z" fill="transparent"/>
<path id="zone-fetlock-rear-r" data-zone="fetlock-rear-r" d="M700 450 L750 450 L745 485 L700 485 Z" fill="transparent"/>
<path id="zone-sacro-iliac-r" data-zone="sacro-iliac-r" d="M740 285 L795 290 L790 320 L735 315 Z" fill="transparent"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

+241 -3
View File
@@ -1,9 +1,247 @@
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
import { FR } from '../i18n/fr';
import { formatDateFr } from '../lib/date';
import type { Report } from '../schema/report';
import type { SpeciesAnatomy } from '../species/types';
import { PDF_ATTACHMENT_NAME } from './version';
const A4 = { width: 595.28, height: 841.89 } as const;
const MARGIN = 48;
const FOOT = 32;
export interface AnatomyAssets {
svg: Record<string, string>;
anatomy: SpeciesAnatomy;
rasters: Partial<Record<'lateral_left' | 'lateral_right' | 'dorsal', Uint8Array | ArrayBuffer>>;
}
export function exportReport(_report: Report, _assets: AnatomyAssets): Promise<Blob> {
return Promise.reject(new Error('exportReport not implemented'));
function zoneLabel(anatomy: SpeciesAnatomy, id: string): string {
return anatomy.zones.find((z) => z.id === id)?.label ?? id;
}
export async function exportReportBytes(report: Report, assets: AnatomyAssets): Promise<Uint8Array> {
const pdf = await PDFDocument.create();
pdf.setTitle(`Bilan ostéopathique — ${report.animal.name}`);
pdf.setAuthor(report.practitioner.fullName);
pdf.setSubject(FR.app.tagline);
pdf.setCreator(FR.app.name);
pdf.setProducer('pdf-lib');
pdf.setCreationDate(new Date(report.createdAt));
const font = await pdf.embedFont(StandardFonts.Helvetica);
const fontBold = await pdf.embedFont(StandardFonts.HelveticaBold);
let page = pdf.addPage([A4.width, A4.height]);
let y = A4.height - MARGIN;
// ───────── Header
page.drawText(FR.app.name, {
x: MARGIN,
y,
size: 18,
font: fontBold,
color: rgb(0.29, 0.49, 0.35),
});
page.drawText(FR.app.tagline, { x: MARGIN, y: y - 16, size: 9, font, color: rgb(0.4, 0.4, 0.4) });
y -= 36;
page.drawText(`Animal : ${report.animal.name}`, { x: MARGIN, y, size: 11, font: fontBold });
page.drawText(`Propriétaire : ${report.animal.owner}`, { x: MARGIN, y: y - 14, size: 11, font });
page.drawText(`Séance : ${formatDateFr(report.sessionDate)}`, { x: MARGIN, y: y - 28, size: 11, font });
const practX = A4.width / 2 + 20;
page.drawText(report.practitioner.fullName, { x: practX, y, size: 11, font: fontBold });
let practY = y - 14;
for (const line of [
report.practitioner.title,
report.practitioner.phone,
report.practitioner.email,
report.practitioner.address,
report.practitioner.siret ? `SIRET ${report.practitioner.siret}` : undefined,
]) {
if (!line) continue;
page.drawText(line, { x: practX, y: practY, size: 10, font });
practY -= 12;
}
y = Math.min(y - 60, practY - 24);
page.drawLine({
start: { x: MARGIN, y },
end: { x: A4.width - MARGIN, y },
thickness: 0.6,
color: rgb(0.29, 0.49, 0.35),
});
y -= 20;
// ───────── Anatomy pages (one per view with selected zones)
const viewLabels: Record<keyof AnatomyAssets['rasters'], string> = {
lateral_left: 'Vue latérale gauche',
lateral_right: 'Vue latérale droite',
dorsal: 'Vue dorsale',
};
const viewsInUse = new Set<keyof AnatomyAssets['rasters']>();
for (const f of report.findings) {
for (const zId of [...f.zones, ...f.linkedZones]) {
const z = assets.anatomy.zones.find((zz) => zz.id === zId);
if (!z) continue;
for (const v of z.views) viewsInUse.add(v);
}
}
for (const view of viewsInUse) {
const raster = assets.rasters[view];
if (!raster) continue;
page = pdf.addPage([A4.width, A4.height]);
page.drawText(viewLabels[view], {
x: MARGIN,
y: A4.height - MARGIN,
size: 14,
font: fontBold,
});
const png = await pdf.embedPng(raster);
const maxW = A4.width - MARGIN * 2;
const maxH = A4.height - MARGIN * 2 - 50;
const ratio = Math.min(maxW / png.width, maxH / png.height);
const w = png.width * ratio;
const h = png.height * ratio;
page.drawImage(png, { x: MARGIN, y: A4.height - MARGIN - 30 - h, width: w, height: h });
}
// ───────── Findings table
page = pdf.addPage([A4.width, A4.height]);
y = A4.height - MARGIN;
page.drawText('Observations cliniques', { x: MARGIN, y, size: 14, font: fontBold });
y -= 22;
if (report.findings.length === 0) {
page.drawText('Aucune observation enregistrée.', { x: MARGIN, y, size: 10, font });
}
for (let i = 0; i < report.findings.length; i++) {
const f = report.findings[i];
if (!f) continue;
if (y < MARGIN + 120) {
page = pdf.addPage([A4.width, A4.height]);
y = A4.height - MARGIN;
}
const zones = f.zones.map((id) => zoneLabel(assets.anatomy, id)).join(', ');
const linked = f.linkedZones.length
? ` (liées : ${f.linkedZones.map((id) => zoneLabel(assets.anatomy, id)).join(', ')})`
: '';
const pathos = f.pathologies.map((p) => p.label).join(', ') || '—';
const sev = FR.severity[f.severity] ?? f.severity;
page.drawText(`#${(i + 1).toString()} ${zones}${linked}`, {
x: MARGIN,
y,
size: 11,
font: fontBold,
});
page.drawText(`Pathologies : ${pathos}`, { x: MARGIN, y: y - 14, size: 10, font });
page.drawText(`Sévérité : ${sev}`, { x: MARGIN, y: y - 28, size: 10, font });
if (f.comment) {
const wrapped = wrap(f.comment, 90);
let yy = y - 44;
page.drawText('Commentaire :', { x: MARGIN, y: yy, size: 10, font: fontBold });
yy -= 14;
for (const line of wrapped) {
page.drawText(line, { x: MARGIN + 8, y: yy, size: 10, font });
yy -= 12;
}
y = yy - 8;
} else {
y -= 50;
}
}
// ───────── Conclusion + recommandations + RDV
if (report.conclusion || report.recommendations || report.nextAppointment) {
page = pdf.addPage([A4.width, A4.height]);
y = A4.height - MARGIN;
if (report.conclusion) {
page.drawText('Conclusion', { x: MARGIN, y, size: 14, font: fontBold });
y -= 20;
for (const line of wrap(report.conclusion, 90)) {
page.drawText(line, { x: MARGIN, y, size: 11, font });
y -= 14;
}
y -= 12;
}
if (report.recommendations) {
page.drawText('Recommandations', { x: MARGIN, y, size: 14, font: fontBold });
y -= 20;
for (const line of wrap(report.recommendations, 90)) {
page.drawText(line, { x: MARGIN, y, size: 11, font });
y -= 14;
}
y -= 12;
}
if (report.nextAppointment) {
page.drawText(`Prochain rendez-vous : ${formatDateFr(report.nextAppointment)}`, {
x: MARGIN,
y,
size: 12,
font: fontBold,
});
}
}
// ───────── Footer on each page
const pages = pdf.getPages();
const exported = new Date().toISOString().slice(0, 10);
for (let i = 0; i < pages.length; i++) {
const p = pages[i];
if (!p) continue;
p.drawText(`${FR.app.name} · exporté le ${formatDateFr(exported)} · page ${(i + 1).toString()}/${pages.length.toString()}`, {
x: MARGIN,
y: FOOT,
size: 8,
font,
color: rgb(0.45, 0.45, 0.45),
});
}
// ───────── Attach report.json
// pdf-lib's `attach` treats a raw string as base64-data-URI input (not as
// UTF-8 text), and rejects cross-realm Uint8Array/ArrayBuffer in tests.
// Wrap the JSON in a base64 data-URI string so it's portable everywhere.
const json = JSON.stringify(report);
const jsonBytes = new TextEncoder().encode(json);
let base64 = '';
const chunk = 8192;
for (let i = 0; i < jsonBytes.length; i += chunk) {
base64 += String.fromCharCode(
...jsonBytes.subarray(i, Math.min(i + chunk, jsonBytes.length)),
);
}
const dataUri = `data:application/json;base64,${btoa(base64)}`;
await pdf.attach(dataUri, PDF_ATTACHMENT_NAME, {
mimeType: 'application/json',
description: 'Données sources du bilan (réimport possible).',
creationDate: new Date(report.createdAt),
modificationDate: new Date(),
});
return pdf.save();
}
export async function exportReport(report: Report, assets: AnatomyAssets): Promise<Blob> {
const bytes = await exportReportBytes(report, assets);
return new Blob([bytes], { type: 'application/pdf' });
}
function wrap(text: string, max: number): string[] {
const words = text.split(/\s+/);
const lines: string[] = [];
let buf = '';
for (const w of words) {
if ((buf + ' ' + w).trim().length > max) {
lines.push(buf);
buf = w;
} else {
buf = (buf + ' ' + w).trim();
}
}
if (buf) lines.push(buf);
return lines;
}
+100 -2
View File
@@ -1,5 +1,11 @@
import * as pako from 'pako';
import { PDFDocument, PDFName, type PDFRawStream } from 'pdf-lib';
import { ReportSchema } from '../schema/report';
import type { Report } from '../schema/report';
import { PDF_ATTACHMENT_NAME } from './version';
export type ImportFailure =
| { ok: false; reason: 'NO_ATTACHMENT' }
| { ok: false; reason: 'INVALID_JSON'; details?: string }
@@ -8,6 +14,98 @@ export type ImportFailure =
export type ImportResult = { ok: true; report: Report } | ImportFailure;
export function importReport(_file: File): Promise<ImportResult> {
return Promise.reject(new Error('importReport not implemented'));
export async function importReport(file: File | Blob | ArrayBuffer | Uint8Array): Promise<ImportResult> {
let pdf: PDFDocument;
try {
const buf = await toBytes(file);
pdf = await PDFDocument.load(buf, { ignoreEncryption: true });
} catch (e) {
return { ok: false, reason: 'UNREADABLE_PDF', details: (e as Error).message };
}
const json = extractAttachment(pdf, PDF_ATTACHMENT_NAME);
if (!json) return { ok: false, reason: 'NO_ATTACHMENT' };
let parsed: unknown;
try {
const decoded = new TextDecoder().decode(json);
parsed = JSON.parse(decoded);
} catch (e) {
return {
ok: false,
reason: 'INVALID_JSON',
details: `${(e as Error).message} | first 80 bytes: ${Array.from(json.slice(0, 80))
.map((b) => b.toString(16).padStart(2, '0'))
.join(' ')}`,
};
}
const result = ReportSchema.safeParse(parsed);
if (!result.success) {
return { ok: false, reason: 'SCHEMA_MISMATCH', details: result.error.message };
}
return { ok: true, report: result.data };
}
async function toBytes(input: File | Blob | ArrayBuffer | Uint8Array): Promise<Uint8Array> {
if (input instanceof Uint8Array) return input;
if (input instanceof ArrayBuffer) return new Uint8Array(input);
return new Uint8Array(await input.arrayBuffer());
}
function extractAttachment(pdf: PDFDocument, name: string): Uint8Array | null {
// Walk catalog → Names → EmbeddedFiles → Names array → filespec → EF → F
// pdf-lib has no public attachment-extract API, so we navigate the tree.
const catalog = pdf.catalog;
const names = catalog.lookup(PDFName.of('Names')) as
| { lookup?: (n: PDFName) => unknown }
| undefined;
if (!names?.lookup) return null;
const embeddedFiles = names.lookup(PDFName.of('EmbeddedFiles')) as
| { lookup?: (n: PDFName) => unknown }
| undefined;
if (!embeddedFiles?.lookup) return null;
const namesArr = embeddedFiles.lookup(PDFName.of('Names')) as
| { size?: () => number; lookup?: (i: number) => unknown }
| undefined;
if (!namesArr?.lookup || typeof namesArr.size !== 'function') return null;
const size = namesArr.size();
for (let i = 0; i < size; i += 2) {
const k = namesArr.lookup(i) as { decodeText?: () => string } | undefined;
const fname = k?.decodeText?.();
if (fname !== name) continue;
const fileSpec = namesArr.lookup(i + 1) as
| { lookup?: (n: PDFName) => unknown }
| undefined;
if (!fileSpec?.lookup) continue;
const ef = fileSpec.lookup(PDFName.of('EF')) as
| { lookup?: (n: PDFName) => unknown }
| undefined;
if (!ef?.lookup) continue;
const stream = (ef.lookup(PDFName.of('F')) ?? ef.lookup(PDFName.of('UF'))) as
| { dict?: unknown; contents?: Uint8Array }
| undefined;
if (!stream) continue;
// Duck-type instead of `instanceof PDFRawStream` (instanceof fails when
// multiple pdf-lib realms coexist, e.g. during tests).
if (stream.dict !== undefined && stream.contents !== undefined) {
const s = stream as PDFRawStream;
const filter = (s.dict as { lookup?: (n: PDFName) => unknown }).lookup?.(
PDFName.of('Filter'),
);
const filterName = (filter as { encodedName?: string } | undefined)?.encodedName;
// We bypass pdf-lib's `decodePDFRawStream` because its reference-equality
// check on `PDFName.of('FlateDecode')` is unreliable across module realms
// (e.g. when vitest dual-loads pdf-lib). Use pako directly on raw bytes.
if (filterName === '/FlateDecode') {
return pako.inflate(s.contents);
}
if (filterName === undefined || filter === null) {
return s.contents;
}
// Other filters (ASCII85, LZW, etc.) not expected for embedded files we wrote.
return null;
}
}
return null;
}
+46 -5
View File
@@ -1,13 +1,54 @@
import type { SpeciesAnatomy } from '../types';
import type { SpeciesAnatomy, Subzone, Zone } from '../types';
const range = (prefix: string, count: number): Subzone[] =>
Array.from({ length: count }, (_, i) => ({
id: `${prefix}${i + 1}`,
label: `${prefix}${i + 1}`,
}));
const CERVICAL: Subzone[] = range('C', 7);
const THORACIC: Subzone[] = range('T', 18);
const LUMBAR: Subzone[] = range('L', 6);
const SACRAL: Subzone[] = range('S', 5);
const ZONES: Zone[] = [
{ id: 'head', label: 'Tête', category: 'head', views: ['lateral_left', 'lateral_right', 'dorsal'] },
{ id: 'neck', label: 'Encolure', category: 'axial', views: ['lateral_left', 'lateral_right', 'dorsal'], subzones: CERVICAL },
{ id: 'withers', label: 'Garrot', category: 'axial', views: ['lateral_left', 'lateral_right', 'dorsal'] },
{ id: 'thoracic-back', label: 'Dos thoracique', category: 'axial', views: ['lateral_left', 'lateral_right', 'dorsal'], subzones: THORACIC },
{ id: 'lumbar', label: 'Lombaire', category: 'axial', views: ['lateral_left', 'lateral_right', 'dorsal'], subzones: LUMBAR },
{ id: 'sacrum', label: 'Sacrum', category: 'axial', views: ['lateral_left', 'lateral_right', 'dorsal'], subzones: SACRAL },
{ id: 'sacro-iliac-l', label: 'Sacro-iliaque gauche', category: 'axial', views: ['lateral_left', 'dorsal'] },
{ id: 'sacro-iliac-r', label: 'Sacro-iliaque droite', category: 'axial', views: ['lateral_right', 'dorsal'] },
{ id: 'tail', label: 'Queue', category: 'tail', views: ['lateral_left', 'lateral_right', 'dorsal'] },
{ id: 'shoulder-l', label: 'Épaule gauche', category: 'limb', views: ['lateral_left', 'dorsal'] },
{ id: 'shoulder-r', label: 'Épaule droite', category: 'limb', views: ['lateral_right', 'dorsal'] },
{ id: 'elbow-l', label: 'Coude gauche', category: 'limb', views: ['lateral_left'] },
{ id: 'elbow-r', label: 'Coude droit', category: 'limb', views: ['lateral_right'] },
{ id: 'knee-l', label: 'Genou antérieur gauche', category: 'limb', views: ['lateral_left'] },
{ id: 'knee-r', label: 'Genou antérieur droit', category: 'limb', views: ['lateral_right'] },
{ id: 'fetlock-front-l', label: 'Boulet antérieur gauche', category: 'limb', views: ['lateral_left'] },
{ id: 'fetlock-front-r', label: 'Boulet antérieur droit', category: 'limb', views: ['lateral_right'] },
{ id: 'hip-l', label: 'Hanche gauche', category: 'limb', views: ['lateral_left', 'dorsal'] },
{ id: 'hip-r', label: 'Hanche droite', category: 'limb', views: ['lateral_right', 'dorsal'] },
{ id: 'stifle-l', label: 'Grasset gauche', category: 'limb', views: ['lateral_left'] },
{ id: 'stifle-r', label: 'Grasset droit', category: 'limb', views: ['lateral_right'] },
{ id: 'hock-l', label: 'Jarret gauche', category: 'limb', views: ['lateral_left'] },
{ id: 'hock-r', label: 'Jarret droit', category: 'limb', views: ['lateral_right'] },
{ id: 'fetlock-rear-l', label: 'Boulet postérieur gauche', category: 'limb', views: ['lateral_left'] },
{ id: 'fetlock-rear-r', label: 'Boulet postérieur droit', category: 'limb', views: ['lateral_right'] },
];
export const EQUINE_ANATOMY: SpeciesAnatomy = {
id: 'equine',
label: 'Cheval',
vertebralFormula: { cervical: 7, thoracic: 18, lumbar: 6, sacral: 5 },
zones: [],
zones: ZONES,
svg: {
lateral_left: '',
lateral_right: '',
dorsal: '',
lateral_left: '/species/equine/lateral-left.svg',
lateral_right: '/species/equine/lateral-right.svg',
dorsal: '/species/equine/dorsal.svg',
},
};
+11
View File
@@ -0,0 +1,11 @@
import { registerSpecies } from '../registry';
import { EQUINE_ANATOMY } from './anatomy';
import { EQUINE_PATHOLOGIES } from './pathologies';
registerSpecies('equine', {
anatomy: EQUINE_ANATOMY,
pathologies: EQUINE_PATHOLOGIES,
});
export { EQUINE_ANATOMY, EQUINE_PATHOLOGIES };
+293 -1
View File
@@ -1,3 +1,295 @@
import type { PathologyEntry } from '../types';
export const EQUINE_PATHOLOGIES: PathologyEntry[] = [];
const MVM = (slug: string): string => `https://www.merckvetmanual.com/horse-owners/${slug}`;
const IMAIOS = 'https://www.imaios.com/en/vet-anatomy/horse';
const PUBMED = (id: string): string => `https://pubmed.ncbi.nlm.nih.gov/${id}/`;
export const EQUINE_PATHOLOGIES: PathologyEntry[] = [
// ─── Axial : encolure / dos / lombaire / sacrum ───────────────────────────
{
id: 'eq_kissing_spines',
label: 'Syndrome des processus épineux chevauchants (kissing spines)',
description:
'Contact ou chevauchement des processus épineux thoraciques, principalement entre T13 et T18. Source fréquente de douleur dorsale.',
category: 'osseux',
applicableSpecies: ['equine'],
applicableZones: ['thoracic-back', 'withers', 'lumbar'],
sources: [MVM('horse-owners/bone-joint-and-muscle-disorders-of-horses/disorders-of-the-back-and-pelvis-of-horses'), PUBMED('29071751')],
},
{
id: 'eq_cervical_facet_arthropathy',
label: 'Arthropathie des facettes articulaires cervicales',
description: 'Remaniements arthrosiques des articulations zygapophysaires cervicales, souvent C5-C7.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['neck'],
sources: [MVM('horse-owners/bone-joint-and-muscle-disorders-of-horses/cervical-vertebral-malformation-in-horses'), PUBMED('22416782')],
},
{
id: 'eq_cervical_stenotic_myelopathy',
label: 'Myélopathie cervicale sténosante (wobbler)',
description: 'Compression médullaire cervicale par malformation vertébrale ou sténose dynamique.',
category: 'nerveux',
applicableSpecies: ['equine'],
applicableZones: ['neck'],
sources: [MVM('horse-owners/brain-spinal-cord-and-nerve-disorders-of-horses/cervical-vertebral-malformation-in-horses')],
},
{
id: 'eq_lumbosacral_pain',
label: 'Dysfonction lombo-sacrée',
description: 'Douleur localisée à la jonction L6-S1 et autour du sacrum.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['lumbar', 'sacrum'],
sources: [MVM('horse-owners/bone-joint-and-muscle-disorders-of-horses/disorders-of-the-back-and-pelvis-of-horses')],
},
{
id: 'eq_sacroiliac_dysfunction',
label: 'Dysfonction sacro-iliaque',
description: 'Restriction de mobilité ou douleur au niveau des articulations sacro-iliaques.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['sacro-iliac-l', 'sacro-iliac-r', 'sacrum'],
sources: [MVM('horse-owners/bone-joint-and-muscle-disorders-of-horses/disorders-of-the-back-and-pelvis-of-horses'), PUBMED('20840713')],
},
{
id: 'eq_thoracolumbar_muscular',
label: 'Tension musculaire thoraco-lombaire',
description: 'Hypertonie des muscles long dorsal / longissimus, souvent secondaire à une selle inadaptée.',
category: 'musculaire',
applicableSpecies: ['equine'],
applicableZones: ['thoracic-back', 'lumbar', 'withers'],
sources: [MVM('horse-owners/bone-joint-and-muscle-disorders-of-horses/muscle-disorders-in-horses')],
},
{
id: 'eq_supraspinous_ligament_desmitis',
label: 'Desmite du ligament supra-épineux',
description: 'Inflammation chronique du ligament supra-épineux dorsal, parfois associée aux kissing spines.',
category: 'tendino-ligamentaire',
applicableSpecies: ['equine'],
applicableZones: ['thoracic-back', 'lumbar', 'withers'],
sources: [PUBMED('15510510')],
},
{
id: 'eq_nuchal_ligament_desmopathy',
label: 'Desmopathie du ligament nuchal',
description: 'Atteinte chronique du ligament nuchal, douleur à la flexion cervicale.',
category: 'tendino-ligamentaire',
applicableSpecies: ['equine'],
applicableZones: ['neck', 'head'],
sources: [IMAIOS],
},
{
id: 'eq_tail_set_dysfunction',
label: 'Restriction de mobilité de la queue',
description: "Manque d'oscillation latérale ou de portée de la queue, signe d'irritation sacro-coccygienne.",
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['tail', 'sacrum'],
sources: [IMAIOS],
},
{
id: 'eq_tmj_dysfunction',
label: 'Dysfonction temporo-mandibulaire',
description: 'Asymétrie ou restriction de l’ATM, souvent associée à un déséquilibre dentaire.',
category: 'cranio-sacre',
applicableSpecies: ['equine'],
applicableZones: ['head'],
sources: [PUBMED('21916951')],
},
// ─── Membres antérieurs ───────────────────────────────────────────────────
{
id: 'eq_navicular_syndrome',
label: 'Syndrome naviculaire (douleur podotrochléaire)',
description: 'Douleur chronique de l’appareil podotrochléaire, fréquente cause de boiterie antérieure.',
category: 'osseux',
applicableSpecies: ['equine'],
applicableZones: ['fetlock-front-l', 'fetlock-front-r'],
sources: [MVM('horse-owners/lameness-in-horses/navicular-disease-in-horses')],
},
{
id: 'eq_ringbone',
label: 'Phalangite (ringbone)',
description: 'Ostéoarthrose des articulations interphalangiennes, classiquement membres antérieurs.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['fetlock-front-l', 'fetlock-front-r', 'fetlock-rear-l', 'fetlock-rear-r'],
sources: [MVM('horse-owners/lameness-in-horses/ringbone-in-horses')],
},
{
id: 'eq_splints',
label: 'Suros (splints)',
description: 'Inflammation périostée entre métacarpien principal et stylet, surtout chez le jeune cheval.',
category: 'osseux',
applicableSpecies: ['equine'],
applicableZones: ['knee-l', 'knee-r'],
sources: [MVM('horse-owners/lameness-in-horses/splints-in-horses')],
},
{
id: 'eq_carpal_osteoarthritis',
label: 'Ostéoarthrose du carpe',
description: 'Usure articulaire du carpe (genou antérieur), fréquente chez les chevaux de course.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['knee-l', 'knee-r'],
sources: [PUBMED('20840713')],
},
{
id: 'eq_suspensory_desmitis_front',
label: 'Desmite suspensorale antérieure',
description: 'Atteinte du ligament suspenseur du boulet, branches ou corps, des antérieurs.',
category: 'tendino-ligamentaire',
applicableSpecies: ['equine'],
applicableZones: ['fetlock-front-l', 'fetlock-front-r'],
sources: [MVM('horse-owners/lameness-in-horses/tendinitis-and-tendinosis-in-horses')],
},
{
id: 'eq_sdft_tendinitis',
label: 'Tendinite du tendon fléchisseur superficiel',
description: 'Atteinte du SDFT, classiquement à la moitié distale du métacarpe.',
category: 'tendino-ligamentaire',
applicableSpecies: ['equine'],
applicableZones: ['fetlock-front-l', 'fetlock-front-r'],
sources: [MVM('horse-owners/lameness-in-horses/tendinitis-and-tendinosis-in-horses')],
},
{
id: 'eq_shoulder_sweeney',
label: 'Atrophie scapulaire (sweeney)',
description: 'Atrophie des muscles supra-épineux/infra-épineux par lésion du nerf suprascapulaire.',
category: 'nerveux',
applicableSpecies: ['equine'],
applicableZones: ['shoulder-l', 'shoulder-r'],
sources: [MVM('horse-owners/brain-spinal-cord-and-nerve-disorders-of-horses/suprascapular-nerve-injury-in-horses')],
},
{
id: 'eq_elbow_capped',
label: 'Hygroma du coude (capped elbow)',
description: 'Bursite olécrânienne par traumatisme répété.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['elbow-l', 'elbow-r'],
sources: [MVM('horse-owners/lameness-in-horses/bursitis-in-horses')],
},
// ─── Membres postérieurs ──────────────────────────────────────────────────
{
id: 'eq_bone_spavin',
label: 'Éparvin osseux (bone spavin)',
description: 'Ostéoarthrose des articulations distales du tarse, principale cause d’éparvin.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['hock-l', 'hock-r'],
sources: [MVM('horse-owners/lameness-in-horses/bone-spavin-in-horses')],
},
{
id: 'eq_bog_spavin',
label: 'Vessigon articulaire du jarret (bog spavin)',
description: 'Distension synoviale de l’articulation tibio-tarsienne.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['hock-l', 'hock-r'],
sources: [MVM('horse-owners/lameness-in-horses/bog-spavin-in-horses')],
},
{
id: 'eq_curb',
label: 'Courbe du jarret (curb)',
description: 'Desmite du ligament tarsien plantaire long, palpable en arrière du jarret.',
category: 'tendino-ligamentaire',
applicableSpecies: ['equine'],
applicableZones: ['hock-l', 'hock-r'],
sources: [MVM('horse-owners/lameness-in-horses/curb-in-horses')],
},
{
id: 'eq_stifle_upward_fixation_patella',
label: 'Accrochement intermittent de la rotule',
description: 'Blocage transitoire de la rotule sur la trochlée fémorale, fréquent chez le jeune cheval.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['stifle-l', 'stifle-r'],
sources: [MVM('horse-owners/lameness-in-horses/upward-fixation-of-the-patella-in-horses')],
},
{
id: 'eq_stifle_meniscal_injury',
label: 'Lésion méniscale du grasset',
description: 'Atteinte du ménisque médial ou latéral, conséquence de torsion ou de surcharge.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['stifle-l', 'stifle-r'],
sources: [PUBMED('20840713')],
},
{
id: 'eq_suspensory_desmitis_rear',
label: 'Desmite suspensorale postérieure (PSD)',
description: 'Desmite chronique du suspenseur, branche médiale postérieure principalement.',
category: 'tendino-ligamentaire',
applicableSpecies: ['equine'],
applicableZones: ['hock-l', 'hock-r', 'fetlock-rear-l', 'fetlock-rear-r'],
sources: [MVM('horse-owners/lameness-in-horses/tendinitis-and-tendinosis-in-horses')],
},
{
id: 'eq_coxofemoral_arthrosis',
label: 'Arthrose coxo-fémorale',
description: 'Atteinte dégénérative de la hanche, plus rare mais source de boiterie postérieure.',
category: 'articulaire',
applicableSpecies: ['equine'],
applicableZones: ['hip-l', 'hip-r'],
sources: [IMAIOS],
},
{
id: 'eq_gluteal_strain',
label: 'Lésion musculaire glutéale',
description: 'Élongation ou contracture des muscles fessiers, fréquente après effort intense.',
category: 'musculaire',
applicableSpecies: ['equine'],
applicableZones: ['hip-l', 'hip-r'],
sources: [MVM('horse-owners/bone-joint-and-muscle-disorders-of-horses/muscle-disorders-in-horses')],
},
// ─── Fascial / viscéral / autre ───────────────────────────────────────────
{
id: 'eq_thoracolumbar_fascial_restriction',
label: 'Restriction fasciale thoraco-lombaire',
description: 'Adhérences fasciales limitant la flexion et l’extension dorsale.',
category: 'fascial',
applicableSpecies: ['equine'],
applicableZones: ['thoracic-back', 'lumbar'],
sources: [PUBMED('33555115')],
},
{
id: 'eq_diaphragmatic_restriction',
label: 'Restriction diaphragmatique',
description: 'Limitation de mobilité diaphragmatique, palpable en pression abdominale antérieure.',
category: 'visceral',
applicableSpecies: ['equine'],
applicableZones: ['thoracic-back', 'withers'],
sources: [IMAIOS],
},
{
id: 'eq_gastric_visceral_dysfunction',
label: 'Dysfonction viscérale gastrique',
description: 'Sensibilité épigastrique, parfois associée à ulcères gastriques (EGUS).',
category: 'visceral',
applicableSpecies: ['equine'],
applicableZones: ['thoracic-back', 'lumbar'],
sources: [MVM('horse-owners/digestive-disorders-of-horses/gastric-ulcers-in-horses')],
},
{
id: 'eq_cranio_sacral_restriction',
label: 'Restriction crânio-sacrée',
description: 'Perte de rythme crânio-sacré, palpation crânienne et sacrée combinées.',
category: 'cranio-sacre',
applicableSpecies: ['equine'],
applicableZones: ['head', 'sacrum'],
sources: ['London College of Animal Osteopathy — https://lcao.com'],
},
{
id: 'eq_post_fall_global',
label: 'Conséquences post-traumatiques (chute)',
description: 'Tableau combiné de tensions multi-zones après chute, à différencier d’une lésion focalisée.',
category: 'autre',
applicableSpecies: ['equine'],
applicableZones: [],
sources: [MVM('horse-owners/bone-joint-and-muscle-disorders-of-horses/disorders-of-the-back-and-pelvis-of-horses')],
},
];
+13
View File
@@ -0,0 +1,13 @@
import './equine';
export { SPECIES, getSpecies, isSpeciesAvailable } from './registry';
export type {
PathologyEntry,
SpeciesAnatomy,
SpeciesId,
Subzone,
View,
Zone,
ZoneCategory,
VertebralFormula,
} from './types';
+90 -27
View File
@@ -1,56 +1,119 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { persist, createJSONStorage } from 'zustand/middleware';
import { newId } from '../lib/id';
import type { Finding } from '../schema/finding';
import type { Report } from '../schema/report';
import { SCHEMA_VERSION } from '../schema/report';
interface ReportState {
report: Report | null;
selection: string[];
hydrate: (r: Report) => void;
reset: () => void;
toggleZone: (zoneId: string) => void;
clearSelection: () => void;
addFinding: (f: Finding) => void;
setSelection: (zones: string[]) => void;
addFinding: (input: Omit<Finding, 'id'>) => Finding;
updateFinding: (id: string, patch: Partial<Finding>) => void;
removeFinding: (id: string) => void;
setConclusion: (text: string) => void;
setRecommendations: (text: string) => void;
setNextAppointment: (date: string | undefined) => void;
}
function emptyReport(overrides: Partial<Report> = {}): Report {
return {
version: SCHEMA_VERSION,
id: newId('report'),
createdAt: new Date().toISOString(),
species: 'equine',
practitioner: { fullName: '' },
animal: { name: '', owner: '' },
sessionDate: new Date().toISOString().slice(0, 10),
findings: [],
conclusion: '',
recommendations: '',
...overrides,
};
}
export const useReportStore = create<ReportState>()(
persist(
(set) => ({
(set, get) => ({
report: null,
selection: [],
hydrate: () => {
// implemented in feature task
},
hydrate: (r) => set({ report: r, selection: [] }),
reset: () => set({ report: null, selection: [] }),
toggleZone: () => {
// implemented in feature task
},
toggleZone: (zoneId) =>
set((s) => {
const has = s.selection.includes(zoneId);
return {
selection: has ? s.selection.filter((z) => z !== zoneId) : [...s.selection, zoneId],
};
}),
clearSelection: () => set({ selection: [] }),
addFinding: () => {
// implemented in feature task
},
updateFinding: () => {
// implemented in feature task
},
removeFinding: () => {
// implemented in feature task
},
setConclusion: () => {
// implemented in feature task
},
setRecommendations: () => {
// implemented in feature task
},
setNextAppointment: () => {
// implemented in feature task
setSelection: (zones) => set({ selection: zones }),
addFinding: (input) => {
const finding: Finding = { ...input, id: newId('finding') };
const r = get().report;
if (!r) return finding;
set({
report: { ...r, findings: [...r.findings, finding] },
selection: [],
});
return finding;
},
updateFinding: (id, patch) =>
set((s) => {
if (!s.report) return s;
return {
report: {
...s.report,
findings: s.report.findings.map((f) => (f.id === id ? { ...f, ...patch } : f)),
},
};
}),
removeFinding: (id) =>
set((s) => {
if (!s.report) return s;
return {
report: {
...s.report,
findings: s.report.findings.filter((f) => f.id !== id),
},
};
}),
setConclusion: (text) =>
set((s) => (s.report ? { report: { ...s.report, conclusion: text } } : s)),
setRecommendations: (text) =>
set((s) => (s.report ? { report: { ...s.report, recommendations: text } } : s)),
setNextAppointment: (date) =>
set((s) => {
if (!s.report) return s;
const next: Report =
date === undefined
? { ...s.report, nextAppointment: undefined }
: { ...s.report, nextAppointment: date };
return { report: next };
}),
}),
{ name: 'osteo-report-draft' },
{
name: 'osteo-report-draft',
storage: createJSONStorage(() => localStorage),
partialize: (s) => ({ report: s.report }),
},
),
);
export { emptyReport };
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest';
import { newId } from '@/lib/id';
describe('newId', () => {
it('returns a string without prefix when called bare', () => {
const id = newId();
expect(typeof id).toBe('string');
expect(id.length).toBe(12);
});
it('prefixes when asked', () => {
expect(newId('finding')).toMatch(/^finding_[A-Za-z0-9_-]{10}$/);
});
it('is unique across 1000 calls', () => {
const ids = new Set(Array.from({ length: 1000 }, () => newId()));
expect(ids.size).toBe(1000);
});
});
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest';
import { exportReportBytes, type AnatomyAssets } from '@/pdf/export';
import { importReport } from '@/pdf/import';
import { EQUINE_ANATOMY } from '@/species/equine/anatomy';
// 1×1 transparent PNG as Uint8Array
const TINY_PNG = Uint8Array.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00,
0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
0x42, 0x60, 0x82,
]);
const assets: AnatomyAssets = {
anatomy: EQUINE_ANATOMY,
rasters: {
lateral_left: TINY_PNG,
lateral_right: TINY_PNG,
dorsal: TINY_PNG,
},
};
const sampleReport = {
version: 1 as const,
id: 'r_roundtrip',
createdAt: '2026-05-17T10:00:00.000Z',
species: 'equine' as const,
practitioner: {
fullName: 'Dr. Test',
phone: '0102030405',
email: 'test@example.com',
},
animal: { name: 'Pégase', owner: 'Famille Martin' },
sessionDate: '2026-05-17',
findings: [
{
id: 'finding_1',
zones: ['thoracic-back'],
linkedZones: ['lumbar'],
pathologies: [{ id: 'eq_kissing_spines', label: 'Kissing spines', free: false }],
severity: 'moderate' as const,
comment: 'Sensibilité marquée en flexion latérale.',
},
],
conclusion: 'Tableau de dysfonction dorsale.',
recommendations: 'Repos 7 jours, séance de contrôle à 3 semaines.',
nextAppointment: '2026-06-07',
};
describe('PDF roundtrip', () => {
it('exports then imports back equal report', async () => {
const bytes = await exportReportBytes(sampleReport, assets);
expect(bytes.byteLength).toBeGreaterThan(0);
expect(new TextDecoder().decode(bytes.slice(0, 5))).toBe('%PDF-');
const result = await importReport(bytes);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.report).toEqual(sampleReport);
}
});
it('rejects a PDF without our attachment', async () => {
// Build a tiny PDF with no attachment using pdf-lib
const { PDFDocument } = await import('pdf-lib');
const pdf = await PDFDocument.create();
pdf.addPage();
const bytes = await pdf.save();
const result = await importReport(bytes);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe('NO_ATTACHMENT');
});
});
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';
import { FindingSchema, SeveritySchema } from '@/schema/finding';
describe('FindingSchema', () => {
it('parses a minimal valid finding', () => {
const r = FindingSchema.safeParse({
id: 'f_1',
zones: ['z1'],
severity: 'mild',
});
expect(r.success).toBe(true);
if (r.success) {
expect(r.data.linkedZones).toEqual([]);
expect(r.data.pathologies).toEqual([]);
expect(r.data.comment).toBe('');
}
});
it('requires at least one zone', () => {
const r = FindingSchema.safeParse({
id: 'f_1',
zones: [],
severity: 'mild',
});
expect(r.success).toBe(false);
});
it('rejects invalid severity', () => {
const r = FindingSchema.safeParse({
id: 'f_1',
zones: ['z1'],
severity: 'extreme',
});
expect(r.success).toBe(false);
});
it('accepts free-text pathology entries', () => {
const r = FindingSchema.safeParse({
id: 'f_1',
zones: ['z1'],
severity: 'moderate',
pathologies: [{ id: 'free_xyz', label: 'Sensibilité atypique', free: true }],
});
expect(r.success).toBe(true);
});
});
describe('SeveritySchema', () => {
it('enumerates mild | moderate | severe', () => {
expect(SeveritySchema.options).toEqual(['mild', 'moderate', 'severe']);
});
});
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';
import { ReportSchema, SCHEMA_VERSION } from '@/schema/report';
const sample = {
version: 1 as const,
id: 'r_abc123',
createdAt: '2026-05-17T10:00:00.000Z',
species: 'equine' as const,
practitioner: {
fullName: 'Dr. Doe',
},
animal: { name: 'Pégase', owner: 'Famille Martin' },
sessionDate: '2026-05-17',
findings: [],
conclusion: '',
recommendations: '',
};
describe('ReportSchema', () => {
it('exposes schema version 1', () => {
expect(SCHEMA_VERSION).toBe(1);
});
it('parses a valid sample', () => {
const result = ReportSchema.safeParse(sample);
expect(result.success).toBe(true);
});
it('rejects missing version', () => {
const { version: _v, ...withoutVersion } = sample;
const result = ReportSchema.safeParse(withoutVersion);
expect(result.success).toBe(false);
});
it('rejects unknown species', () => {
const bad = { ...sample, species: 'dinosaur' };
const result = ReportSchema.safeParse(bad);
expect(result.success).toBe(false);
});
it('rejects empty animal name', () => {
const bad = { ...sample, animal: { name: '', owner: 'X' } };
const result = ReportSchema.safeParse(bad);
expect(result.success).toBe(false);
});
it('accepts optional nextAppointment', () => {
const withNext = { ...sample, nextAppointment: '2026-06-01' };
const result = ReportSchema.safeParse(withNext);
expect(result.success).toBe(true);
});
});
+65
View File
@@ -0,0 +1,65 @@
import { describe, expect, it } from 'vitest';
import { EQUINE_ANATOMY } from '@/species/equine/anatomy';
import { EQUINE_PATHOLOGIES } from '@/species/equine/pathologies';
describe('EQUINE_ANATOMY', () => {
it('has vertebral formula C7 / T18 / L6 / S5', () => {
expect(EQUINE_ANATOMY.vertebralFormula).toEqual({
cervical: 7,
thoracic: 18,
lumbar: 6,
sacral: 5,
});
});
it('declares the expected macro zones', () => {
const ids = EQUINE_ANATOMY.zones.map((z) => z.id);
for (const expected of [
'neck',
'withers',
'thoracic-back',
'lumbar',
'sacrum',
'shoulder-l',
'shoulder-r',
'hip-l',
'hip-r',
'tail',
]) {
expect(ids).toContain(expected);
}
});
it('thoracic-back has 18 subzones T1..T18', () => {
const z = EQUINE_ANATOMY.zones.find((zz) => zz.id === 'thoracic-back');
expect(z).toBeDefined();
expect(z?.subzones).toHaveLength(18);
expect(z?.subzones?.[0]?.id).toBe('T1');
expect(z?.subzones?.[17]?.id).toBe('T18');
});
it('every zone declares at least one view', () => {
for (const z of EQUINE_ANATOMY.zones) {
expect(z.views.length).toBeGreaterThan(0);
}
});
});
describe('EQUINE_PATHOLOGIES', () => {
it('seeds at least 30 entries', () => {
expect(EQUINE_PATHOLOGIES.length).toBeGreaterThanOrEqual(30);
});
it('every entry cites at least one source', () => {
for (const p of EQUINE_PATHOLOGIES) {
expect(p.sources.length).toBeGreaterThan(0);
}
});
it('every entry is applicable to equine', () => {
for (const p of EQUINE_PATHOLOGIES) {
expect(p.applicableSpecies).toContain('equine');
}
});
});
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest';
import { getSpecies, isSpeciesAvailable } from '@/species';
describe('species registry', () => {
it('equine is registered', () => {
expect(isSpeciesAvailable('equine')).toBe(true);
const pack = getSpecies('equine');
expect(pack).toBeDefined();
expect(pack?.anatomy.id).toBe('equine');
expect(pack?.pathologies.length).toBeGreaterThan(0);
});
it('non-MVP species are not available yet', () => {
for (const id of ['chien', 'chat', 'lapin', 'bovin', 'chevre', 'ane', 'mouton', 'porc'] as const) {
expect(isSpeciesAvailable(id)).toBe(false);
}
});
});
+94
View File
@@ -0,0 +1,94 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { emptyReport, useReportStore } from '@/state/reportStore';
beforeEach(() => {
useReportStore.getState().reset();
localStorage.clear();
});
describe('useReportStore', () => {
it('starts empty', () => {
const s = useReportStore.getState();
expect(s.report).toBeNull();
expect(s.selection).toEqual([]);
});
it('hydrate sets report', () => {
const r = emptyReport({ animal: { name: 'Pégase', owner: 'X' } });
useReportStore.getState().hydrate(r);
expect(useReportStore.getState().report?.animal.name).toBe('Pégase');
});
it('toggleZone adds then removes', () => {
const { toggleZone } = useReportStore.getState();
toggleZone('z1');
expect(useReportStore.getState().selection).toEqual(['z1']);
toggleZone('z2');
expect(useReportStore.getState().selection).toEqual(['z1', 'z2']);
toggleZone('z1');
expect(useReportStore.getState().selection).toEqual(['z2']);
});
it('addFinding appends and clears selection', () => {
useReportStore.getState().hydrate(emptyReport());
useReportStore.getState().setSelection(['z1', 'z2']);
const f = useReportStore.getState().addFinding({
zones: ['z1', 'z2'],
linkedZones: [],
pathologies: [],
severity: 'mild',
comment: '',
});
expect(useReportStore.getState().report?.findings).toHaveLength(1);
expect(useReportStore.getState().selection).toEqual([]);
expect(f.id).toMatch(/^finding_/);
});
it('updateFinding merges', () => {
useReportStore.getState().hydrate(emptyReport());
const f = useReportStore.getState().addFinding({
zones: ['z1'],
linkedZones: [],
pathologies: [],
severity: 'mild',
comment: '',
});
useReportStore.getState().updateFinding(f.id, { severity: 'severe', comment: 'lourd' });
const found = useReportStore.getState().report?.findings[0];
expect(found?.severity).toBe('severe');
expect(found?.comment).toBe('lourd');
});
it('removeFinding removes by id', () => {
useReportStore.getState().hydrate(emptyReport());
const f = useReportStore.getState().addFinding({
zones: ['z1'],
linkedZones: [],
pathologies: [],
severity: 'mild',
comment: '',
});
useReportStore.getState().removeFinding(f.id);
expect(useReportStore.getState().report?.findings).toHaveLength(0);
});
it('setConclusion / setRecommendations / setNextAppointment', () => {
useReportStore.getState().hydrate(emptyReport());
useReportStore.getState().setConclusion('A');
useReportStore.getState().setRecommendations('B');
useReportStore.getState().setNextAppointment('2026-06-01');
const r = useReportStore.getState().report;
expect(r?.conclusion).toBe('A');
expect(r?.recommendations).toBe('B');
expect(r?.nextAppointment).toBe('2026-06-01');
});
it('persists report to localStorage', () => {
useReportStore.getState().hydrate(emptyReport({ animal: { name: 'X', owner: 'Y' } }));
const raw = localStorage.getItem('osteo-report-draft');
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw ?? '{}') as { state?: { report?: { animal?: { name?: string } } } };
expect(parsed.state?.report?.animal?.name).toBe('X');
});
});