Merge feature/step-01-characterisation-tests into develop
This commit is contained in:
commit
c8d48ab4cc
33 files changed
+6018
-8577
No files matched your search
@@ -35,3 +35,10 @@ Method: /tour full pipeline on faunosteo — semgrep floor ×3 + cso posture (it
|
|||||||
Result: re-verify PASS (0 findings on 20 modified files); checks green throughout (typecheck, lint 0, 174/174, build, docker run non-root). Convergence honest: it2 surfaced 1 new tuning note (min-release-age 1440 < 10080 rec) → triaged open → it3 semgrep identical → converged at 3-iteration bound.
|
Result: re-verify PASS (0 findings on 20 modified files); checks green throughout (typecheck, lint 0, 174/174, build, docker run non-root). Convergence honest: it2 surfaced 1 new tuning note (min-release-age 1440 < 10080 rec) → triaged open → it3 semgrep identical → converged at 3-iteration bound.
|
||||||
Anomaly: both Phase A agents died mid-run on "monthly spend limit" — SendMessage to same agentId resumed from transcript, zero rework. PostToolUse hook false-positived 3× on 'dangerouslySetInnerHTML' as prose inside audit REPORTS (not code).
|
Anomaly: both Phase A agents died mid-run on "monthly spend limit" — SendMessage to same agentId resumed from transcript, zero rework. PostToolUse hook false-positived 3× on 'dangerouslySetInnerHTML' as prose inside audit REPORTS (not code).
|
||||||
Action: none blocking. Consider excluding .claude/audits/*.md from sink-pattern hook scan.
|
Action: none blocking. Consider excluding .claude/audits/*.md from sink-pattern hook scan.
|
||||||
|
|
||||||
|
## EVAL-005 | 2026-10-08 | Step 1 characterisation suite (91 cases)
|
||||||
|
|
||||||
|
Method: 7 files on real assets (SVG, catalog, fixtures), oracle = audit tables (06 §4, 05 §2.4). Run typecheck/test/lint/build.
|
||||||
|
Result: 271/271 green, 0 src change. Audit figures all confirmed (26 mappings score 0, 792/612/41, 48 attrs…).
|
||||||
|
Anomalies: 4 assertions wrong on first run, all test-side (census regex, stale closure, ZONES drawn as bullet rows not ' · ' line, attachment names in object streams). None app-side.
|
||||||
|
Action: LRN-033. Known quirks pinned as "KNOWN:" tests (orphan findings, no_attachment cause lost, sphenoid id, fuzzy FR pairs).
|
||||||
@@ -165,3 +165,9 @@ fix(editor) 2803cf7 — pathology-editor.html 404 in prod (faunosteo.com/patholo
|
|||||||
## 2026-07-12
|
## 2026-07-12
|
||||||
|
|
||||||
/tour full sweep — branch chore/tour-2026-07-12, 11 commits, UNMERGED (human review pending). Security: CVE deps patched (pnpm audit 0), SVG import sanitized both editors, container non-root (BREAKING: PORT >=1024), nginx:1.31-alpine pin, min-release-age guard. Clean: -93 lines dead code (canvg dep dropped), 3 dedup extracts, i18n dead keys purged. Docs synced (README/DEPLOY/CHANGELOG, incl. stale origin/master). 6 bugs quarantined -> BUGS-FOUND.md (worst: B-3 draft mirror write-only). 4 reconcile suggestions pending /reconcile. Report: .claude/audits/TOUR.md. LRN-030/031, EVAL-004 captured.
|
/tour full sweep — branch chore/tour-2026-07-12, 11 commits, UNMERGED (human review pending). Security: CVE deps patched (pnpm audit 0), SVG import sanitized both editors, container non-root (BREAKING: PORT >=1024), nginx:1.31-alpine pin, min-release-age guard. Clean: -93 lines dead code (canvg dep dropped), 3 dedup extracts, i18n dead keys purged. Docs synced (README/DEPLOY/CHANGELOG, incl. stale origin/master). 6 bugs quarantined -> BUGS-FOUND.md (worst: B-3 draft mirror write-only). 4 reconcile suggestions pending /reconcile. Report: .claude/audits/TOUR.md. LRN-030/031, EVAL-004 captured.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2026-10-08
|
||||||
|
|
||||||
|
SaaS migration kickoff. Step 0: 8 docs in docs/development/ (27-step plan, domain map, FE/BE arch, migration, tests, 9 open questions) — user validated + decided: no external users, no v2 compat obligation, equine only, 2 SVG assets kept, import anomalies into draft (no silent fix), self-hosted Supabase on adequate infra, design decisions gated by user (ChatGPT), manual report points confirmed. Step 1: 91 characterisation tests, 2 golden fixtures, CHARACTERIZATION_REPORT.md; 271/271, typecheck/lint/build green; host had no pnpm → corepack (LRN-032). Both committed on feature/step-01-characterisation-tests, validated.
|
||||||
@@ -244,3 +244,18 @@ nginx:alpine default = master root, workers nginx. Listen port >=1024 → USER n
|
|||||||
vite + @vitejs/plugin-react-swc + @tailwindcss/vite sat in dependencies → `pnpm audit --prod` reported their CVEs as prod findings. Build-time-only packages belong in devDependencies; SPA runtime imports none of them.
|
vite + @vitejs/plugin-react-swc + @tailwindcss/vite sat in dependencies → `pnpm audit --prod` reported their CVEs as prod findings. Build-time-only packages belong in devDependencies; SPA runtime imports none of them.
|
||||||
**Why:** tour 2026-07-12 cso posture audit — all 3 "prod" advisories were build-toolchain. Moved 187dfb5; build+tests green, prod audit clean.
|
**Why:** tour 2026-07-12 cso posture audit — all 3 "prod" advisories were build-toolchain. Moved 187dfb5; build+tests green, prod audit clean.
|
||||||
**How to apply:** scaffold check: anything imported only by vite.config / build pipeline → devDependencies. Then `pnpm audit --prod` reflects real runtime surface. Docker multi-stage unaffected (builder installs all).
|
**How to apply:** scaffold check: anything imported only by vite.config / build pipeline → devDependencies. Then `pnpm audit --prod` reflects real runtime surface. Docker multi-stage unaffected (builder installs all).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## LRN-032 | 2026-10-08 | pnpm via corepack prepare, not ~/.local/bin
|
||||||
|
|
||||||
|
Dev host: no pnpm on PATH, no node_modules, Node 24.21 (CLAUDE.md said Node 20 + `~/.local/bin/pnpm`, both stale). `corepack prepare pnpm@10.13.1 --activate` + `corepack pnpm <cmd>` works, zero global install, same pin as Dockerfile (BLK-005). Suite 271/271 on Node 24.
|
||||||
|
Apply: never `export PATH=…` in Bash tool (denied); call `corepack pnpm`. Pin `packageManager` in package.json so corepack picks version alone.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## LRN-033 | 2026-10-08 | Characterise legacy via DOM + prototype spies, no refactor
|
||||||
|
|
||||||
|
Untestable seams (click chain inside route, PDF text) pinned without touching src: render route in MemoryRouter + mock `@/anatomy/svgLoader` to parse real files, dispatch bubbling click on `[data-anno-id]`; `vi.spyOn(PDFPage.prototype,'drawText')` captures every drawn string (pdf-lib has no extractor); attachment dicts via `doc.context.enumerateIndirectObjects()` + `String(obj)` (object streams hide names from raw bytes). Standalone HTML tool: slice functions by text markers, `new Function(src)` → parity test.
|
||||||
|
Trap: store set outside React then click = stale closure; drive state through UI (collapse card) and `waitFor`.
|
||||||
|
Apply: any "tests before migration" step on untested legacy code.
|
||||||
@@ -44,6 +44,14 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## SaaS migration (plan: docs/development/IMPLEMENTATION_PLAN.md)
|
||||||
|
|
||||||
|
- [x] Step 0 — preparation docs in docs/development/ (2026-10-08, validated)
|
||||||
|
- [x] Step 1 — characterisation tests: 7 files / 91 cases, 2 golden fixtures, docs/development/CHARACTERIZATION_REPORT.md; 271/271, typecheck, lint, build green (2026-10-08, branch feature/step-01-characterisation-tests, awaiting validation)
|
||||||
|
- [ ] Step 2 — monorepo workspace (next, on validation)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Phase A — DONE (kept for reference)
|
## Phase A — DONE (kept for reference)
|
||||||
|
|
||||||
- [x] Scaffold (deps, configs, Docker, schemas, stubs)
|
- [x] Scaffold (deps, configs, Docker, schemas, stubs)
|
||||||
|
|||||||
@@ -0,0 +1,198 @@
|
|||||||
|
# Backend architecture (Supabase strategy)
|
||||||
|
|
||||||
|
Status: Step 0 deliverable, 2026-10-08. Conceptual only. No migration, table,
|
||||||
|
policy or function is created by this document. Table and function names
|
||||||
|
follow `faunosteo-business-architecture.md` §4–§20.
|
||||||
|
|
||||||
|
## 1. Components and what runs where
|
||||||
|
|
||||||
|
```text
|
||||||
|
Browser (apps/app, anon key + user JWT)
|
||||||
|
│ tables via RLS, RPC (security definer), Storage signed URLs
|
||||||
|
▼
|
||||||
|
Supabase (self-hosted on Scaleway at launch, §31)
|
||||||
|
├─ Auth (GoTrue): email/password, Google, Apple, OTP, phone
|
||||||
|
├─ PostgreSQL: schemas public / private / audit, RLS, functions, pg_cron
|
||||||
|
├─ Storage: private buckets, storage.objects policies
|
||||||
|
├─ Edge Functions (Deno): public endpoints, webhooks, signed-URL issuance
|
||||||
|
└─ Realtime (optional): report sync state
|
||||||
|
Worker (apps/worker, service key, same host)
|
||||||
|
└─ jobs table in PostgreSQL, no Redis
|
||||||
|
public-web (anon key, SSR)
|
||||||
|
└─ public views / RPCs only
|
||||||
|
```
|
||||||
|
|
||||||
|
The browser never holds a service-role key, admin credential, storage master
|
||||||
|
key or third-party refresh token (§17.1).
|
||||||
|
|
||||||
|
## 2. Auth
|
||||||
|
|
||||||
|
| Need | Mechanism | Note |
|
||||||
|
|---|---|---|
|
||||||
|
| Email/password, magic link/OTP | GoTrue built-in | strong password policy configured server-side |
|
||||||
|
| Google, Apple | GoTrue OAuth providers | Apple requires a paid developer account and a services id: dependency to confirm |
|
||||||
|
| Phone verification | GoTrue phone OTP needs an SMS provider (Twilio, MessageBird, Vonage) | cost and EU processing to confirm; see `OPEN_QUESTIONS.md` Q7 |
|
||||||
|
| Email verification | GoTrue, mandatory before professional features | |
|
||||||
|
| MFA | GoTrue TOTP; mandatory for owner/admin/moderator/support roles, enforced by RLS helper `has_mfa()` on admin tables | |
|
||||||
|
| Roles | `profile_roles` table, never JWT custom claims as the only source (claims can lag) | helpers read the table |
|
||||||
|
| Impersonation | dedicated RPC issuing a short-lived scoped session, audited, banner in UI (§17.5) | after MVP core |
|
||||||
|
|
||||||
|
`profiles.id = auth.users.id`, created by a trigger on `auth.users` insert.
|
||||||
|
|
||||||
|
## 3. PostgreSQL layout
|
||||||
|
|
||||||
|
| Schema | Content | Exposure |
|
||||||
|
|---|---|---|
|
||||||
|
| `public` | tables exposed to PostgREST, all with RLS enabled, separate SELECT/INSERT/UPDATE/DELETE policies | browser, public-web, worker |
|
||||||
|
| `private` | security-definer helper functions, internal tables (counters, job queue, route cache), triggers | not exposed to PostgREST |
|
||||||
|
| `audit` | `audit_logs`, append-only, insert via `private.log_event()` | read by admins through a view |
|
||||||
|
|
||||||
|
Conventions fixed now so every step follows them:
|
||||||
|
|
||||||
|
- UUID primary keys (`gen_random_uuid()`), `created_at` / `updated_at` with a shared trigger, soft delete `deleted_at` where the architecture names it.
|
||||||
|
- Enums as PostgreSQL `enum` types when the value set is closed by the business (report status, appointment status), `text` + CHECK when the set is expected to grow (document types).
|
||||||
|
- JSONB documents (`reports.current_document`, `anatomical_sheet_versions.content_jsonb`) carry their own `schema_version` and are validated by the matching Zod schema at the application boundary and by a CHECK on `schema_version` in SQL. SQL does not re-implement Zod.
|
||||||
|
- Every table exposed to the browser: RLS enabled, no `USING (true)` policy for `authenticated`, no anonymous policy on core tables (§17.4).
|
||||||
|
|
||||||
|
## 4. RLS strategy
|
||||||
|
|
||||||
|
### 4.1 Helpers
|
||||||
|
|
||||||
|
Security-definer functions in `private`, `STABLE`, `search_path` pinned,
|
||||||
|
`SET row_security = off` inside where they read tables that have policies
|
||||||
|
referencing them (prevents recursion), one index per access path they use:
|
||||||
|
|
||||||
|
```text
|
||||||
|
private.is_platform_owner(uid) private.is_platform_admin(uid)
|
||||||
|
private.is_platform_moderator(uid) private.is_support(uid)
|
||||||
|
private.is_org_member(uid, org) private.is_org_manager(uid, org)
|
||||||
|
private.is_org_practitioner(uid, org)
|
||||||
|
private.can_view_client(uid, client) private.can_view_animal(uid, animal)
|
||||||
|
private.can_view_report(uid, report) private.can_edit_report(uid, report)
|
||||||
|
private.can_use_sheet(uid, sheet) private.can_fork_sheet(uid, sheet)
|
||||||
|
private.has_active_entitlement(uid, capability text)
|
||||||
|
```
|
||||||
|
|
||||||
|
Each helper ships with pgTAP tests in the same migration step: positive case,
|
||||||
|
negative case, expired grant, revoked grant, wrong organization.
|
||||||
|
|
||||||
|
### 4.2 Policy rules per domain (summary of §17.3)
|
||||||
|
|
||||||
|
| Table family | SELECT | INSERT/UPDATE/DELETE |
|
||||||
|
|---|---|---|
|
||||||
|
| `profiles` | own row; admins via view | own row; roles only through RPC |
|
||||||
|
| `organizations`, `organization_members` | members | managers/owners through RPC (`add_member`, `remove_member`, `set_role`) so that "secretary cannot self-grant practitioner" is one place |
|
||||||
|
| `clients`, `client_contacts`, `client_consents` | `can_view_client` | create by the practitioner who starts the relationship; core identity edits restricted (open question Q6) |
|
||||||
|
| `animals` | `can_view_animal` | practitioner with an active relationship or grant |
|
||||||
|
| `reports` | `can_view_report` | `can_edit_report` for drafts; completion and numbering only via RPC |
|
||||||
|
| `report_revisions` | same as parent report | insert via RPC/trigger only |
|
||||||
|
| `anatomical_sheets` | public metadata through a view; full row for creator, grantee, or follower of a public sheet | creator only; publish via RPC |
|
||||||
|
| `anatomical_sheet_versions` | `can_use_sheet` on the parent | insert draft by creator; published rows immutable (trigger raises on UPDATE of `content_jsonb` when `status = published`) |
|
||||||
|
| `practitioner_follows`, `sheet_usage_grants` | involved parties | own follows; grants by sheet creator or org manager |
|
||||||
|
| `appointments` and agenda tables | owner scope; public availability through RPC only | booking through RPC with row locks |
|
||||||
|
| `plans`, `subscriptions`, `entitlement_grants` | own / org manager | Stripe webhook (service) and admin RPC only |
|
||||||
|
| `audit.audit_logs` | admins | append-only via `private.log_event` |
|
||||||
|
| `storage.objects` | per bucket policy calling the owning domain's helper | upload paths validated against `assets` rows |
|
||||||
|
|
||||||
|
### 4.3 Public endpoints
|
||||||
|
|
||||||
|
Public profile, sheet discovery, availability and booking are security-definer
|
||||||
|
RPCs or narrow views returning approved columns (§17.4). The anon role gets
|
||||||
|
EXECUTE on those functions and nothing else.
|
||||||
|
|
||||||
|
## 5. Storage
|
||||||
|
|
||||||
|
Buckets, all private: `avatars`, `logos`, `professional-documents`,
|
||||||
|
`client-files`, `animal-files`, `report-files`, `anatomical-sheets`, `imports`.
|
||||||
|
|
||||||
|
Object key: `<resource-type>/<resource-id>/<asset-id>/<safe-filename>`. The
|
||||||
|
`assets` table is authoritative; `storage.objects` policies call the owning
|
||||||
|
helper (`can_view_report` for `report-files/...`). Reads go through signed
|
||||||
|
URLs issued by an RPC/Edge Function after the same check.
|
||||||
|
|
||||||
|
SVG pipeline (§15.3): upload lands in a quarantine prefix with
|
||||||
|
`assets.sanitization_status = pending`; a server sanitizer (Edge Function or
|
||||||
|
worker) rewrites the file (strip `<script>`, `<foreignObject>`, `on*`,
|
||||||
|
`javascript:`/external hrefs, `<use>` to external documents, CSS `url()`),
|
||||||
|
stores the clean bytes under the final key and sets `status = clean`. Policies
|
||||||
|
only allow reading `clean` assets to anyone other than the uploader. The
|
||||||
|
current 10-line client sanitizer stays as a pre-check in the editor, not as
|
||||||
|
the boundary.
|
||||||
|
|
||||||
|
Archive (§15.4, §16): S3-compatible cold storage with lifecycle rules, no
|
||||||
|
Object Lock by default. Out of MVP core; designed at the data-lifecycle step.
|
||||||
|
|
||||||
|
## 6. Edge Functions vs PostgreSQL functions vs worker
|
||||||
|
|
||||||
|
Decision rule for each server-side behaviour:
|
||||||
|
|
||||||
|
| Put it in | When |
|
||||||
|
|---|---|
|
||||||
|
| PostgreSQL function / trigger (RPC) | Needs transactional guarantees with the data: report numbering, completion + quota, booking slot lock, grant evaluation, version publication, GC preconditions |
|
||||||
|
| Edge Function | Needs HTTP from outside or secrets: Stripe webhooks, public widget endpoints, signed-URL issuance, calendar OAuth callbacks, email send trigger, SVG sanitization (small files), import preflight (small files) |
|
||||||
|
| Worker | Long or scheduled: reminders, expiry sweeps (unless `pg_cron`), calendar sync, route cache, long imports, archive, GC sweeps, server PDF (later) |
|
||||||
|
|
||||||
|
Self-hosted note: Edge Functions on a self-hosted stack run in the
|
||||||
|
`edge-runtime` container and must be deployed by hand. The first steps lean
|
||||||
|
on PostgreSQL functions, which the CLI migrates and tests natively. See
|
||||||
|
`OPEN_QUESTIONS.md` Q2 on VPS sizing.
|
||||||
|
|
||||||
|
## 7. Migrations
|
||||||
|
|
||||||
|
- Supabase CLI, `supabase/migrations/<timestamp>_<name>.sql`, forward-only,
|
||||||
|
one or more per implementation step, reviewed in the step's PR.
|
||||||
|
- A migration never edits an applied migration; corrections are new migrations.
|
||||||
|
- Each migration that adds a table also adds: RLS enable, policies, indexes
|
||||||
|
listed in §32 of the architecture, pgTAP tests, and regenerated types.
|
||||||
|
- `supabase db reset` must succeed from zero on CI, then `supabase test db`,
|
||||||
|
then the app test suite (§36).
|
||||||
|
- Seed data (`supabase/seed/`): species list, plans, the official equine sheet
|
||||||
|
v1 produced by the importer from the two SVGs and the catalog. Seeds are
|
||||||
|
idempotent and versioned like migrations.
|
||||||
|
- Production changes follow expand/contract when a column is renamed or
|
||||||
|
dropped (the `deprecation-and-migration` skill applies).
|
||||||
|
|
||||||
|
## 8. SQL tests
|
||||||
|
|
||||||
|
pgTAP under `supabase/tests/`, run by `supabase test db`:
|
||||||
|
|
||||||
|
- helper function unit tests (one file per helper);
|
||||||
|
- per-table RLS tests: as user A, as user B, as org member, as anon, as
|
||||||
|
service; each verifies both the allowed rows and the denied rows;
|
||||||
|
- transactional rules: numbering under concurrency (two sessions), booking
|
||||||
|
double-request, completion beyond quota, publish-then-update raises;
|
||||||
|
- immutability and GC preconditions for sheet versions.
|
||||||
|
|
||||||
|
Representative cross-tenant cases are a release gate (§30).
|
||||||
|
|
||||||
|
## 9. Generated types
|
||||||
|
|
||||||
|
`supabase gen types typescript --local > packages/supabase/src/database.types.ts`
|
||||||
|
after every migration. CI regenerates and fails on diff. Zod schemas in
|
||||||
|
`packages/domain` remain the contract for JSONB documents; generated types
|
||||||
|
cover columns and RPC signatures.
|
||||||
|
|
||||||
|
## 10. What must stay server-side (brief §19, architecture principles 6–13)
|
||||||
|
|
||||||
|
1. Authorization: every read/write of client, animal, report, sheet, grant.
|
||||||
|
2. Report numbering, completion, free-plan quota, 5-day free edit window.
|
||||||
|
3. Sheet version immutability, publication, deprecation, garbage collection.
|
||||||
|
4. Explicit `annotation → finding zone` mapping validation on publish (no fuzzy at runtime).
|
||||||
|
5. Booking slot evaluation, pending-request limits, expiry, race protection.
|
||||||
|
6. Entitlement computation and Stripe state.
|
||||||
|
7. Referral eligibility and caps.
|
||||||
|
8. Client candidate matching and sharing consent flows.
|
||||||
|
9. SVG sanitization and signed URL issuance.
|
||||||
|
10. Import preflight, quota check and atomic commit.
|
||||||
|
11. Audit logging, impersonation, moderation.
|
||||||
|
12. Archive and deletion workflows.
|
||||||
|
|
||||||
|
## 11. Observability and operations (minimum for MVP)
|
||||||
|
|
||||||
|
- Structured logs without clinical data or secrets; request correlation id
|
||||||
|
propagated to `audit_logs`.
|
||||||
|
- Daily DB backup + monthly retained copy; restore rehearsed before the first
|
||||||
|
paying cohort (§31, §38).
|
||||||
|
- Dependency audit (`pnpm audit`) and secret scan (gitleaks hook already in
|
||||||
|
`.githooks`) in CI.
|
||||||
|
- Security headers at the reverse proxy and in nginx (hardening step).
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# Characterisation report (plan Step 1)
|
||||||
|
|
||||||
|
Status: done 2026-10-08, branch `feature/step-01-characterisation-tests`.
|
||||||
|
Scope: a tested photograph of the current application before any SaaS
|
||||||
|
transformation. No file under `src/`, `public/`, `scripts/`, `docker/` was
|
||||||
|
changed. Commands run on this host: Node 24.21.0, pnpm 10.13.1 (corepack),
|
||||||
|
dependencies installed from the lockfile.
|
||||||
|
|
||||||
|
## 1. Results
|
||||||
|
|
||||||
|
| Command | Result |
|
||||||
|
|---|---|
|
||||||
|
| `pnpm test:run` | 39 files, 271 tests green (180 pre-existing + 91 new) |
|
||||||
|
| `pnpm typecheck` | 0 errors |
|
||||||
|
| `pnpm lint` | 0 errors, 0 warnings |
|
||||||
|
| `pnpm build` | OK (chunk-size warning pre-existing) |
|
||||||
|
|
||||||
|
## 2. Files added
|
||||||
|
|
||||||
|
| File | Cases | Characterises |
|
||||||
|
|---|---|---|
|
||||||
|
| `tests/fixtures/report-v2.full.json` | fixture | Golden Report v2 with every zone kind (plain hinge, bilateral both sides, spine with vertebrae, detail-popup), catalog findings with vet flag and side, free text, severity, comment, conclusion, recommendations, dated next appointment. Real `data-anno-id` and catalog paths. |
|
||||||
|
| `tests/fixtures/report-v2.minimal.json` | fixture | Smallest valid v2 report. |
|
||||||
|
| `tests/fixtures/README.md` | doc | Fixture contract: never edited to make a test pass. |
|
||||||
|
| `tests/unit/char.catalog.test.ts` | 13 | `pathologies.json`: byte parity of the two copies, Zod acceptance, schema_version, species, the 26 zone keys in order, `zone.id === key`, 3 categories per zone, root-category id convention with the **known** `sphenoid → ssb-dysfunctions` anomaly, 792 nodes / 612 leaves / depth 3 / 228+384, 41 vet flags all on leaves, 62 `description_fr`, 0 `description_en`, 0 `sources`, sibling-only id uniqueness (26× `anamnesis`, 11× `amplitude-asymmetry`), three `anamnesis` content variants (8/9/9 zones). |
|
||||||
|
| `tests/unit/char.svgCatalogLink.test.ts` | 18 | Raw attribute census of both SVGs (48/48/18/47/47/18/5/1), five category slugs, 27 distinct ids, `Horse_head.svg` = same drawing + different viewBox, the full 26-row mapping table annotation → catalog zone with score 0 in EN and FR, trigger unmatched, no orphan zone, substring rule unreachable, the two FR pairs inside the fuzzy tolerance (distances 5 and 3), opens-detail ↔ manifest coherence, spine helpers on the real file (region → polygon id, spawn, collect order, detail-sourced exclusion). |
|
||||||
|
| `tests/unit/char.pathologyEditor.test.ts` | 8 | The inline matcher of `public/pathology-editor.html` evaluated from the file and compared to `zoneMatch.ts` on all 27 annotations + edge labels (LRN-026 parity test), `generateId` slug rules, 76/76 inline translation keys disjoint from the app dictionary, shared `osteo:locale` key, hard-coded `SPECIES_CONFIG` pointing at existing files, zero `src/` imports, noindex, no Zod. |
|
||||||
|
| `tests/unit/char.clickChain.test.tsx` | 12 | `EditorRoute` through the DOM on the real SVGs: disclaimer once per session (`osteo:disclaimer-shown`), plain toggle add/remove and `data-state="current"`, collapsed-card fallback (click re-activates the last observation and is lost), detail trigger opens the modal and is never a zone, zones clicked in the modal carry `detailSourceId: 'head'`, spine click adds + opens the picker on the right tab and never toggles off, cancel leaves a zone without vertebrae, picker spawns another region and prunes to zero, bilateral left / right / both and "both present → clear both", ✕ removal keeps orphan findings (**known**, BDR-019), one picker per (catalog zone, side) and raw-id badge for the unnamed trigger. |
|
||||||
|
| `tests/unit/char.pdfFull.test.ts` | 15 | Export of the full fixture: page count, title/author metadata, re-fetch of SVGs and logos at export time, ZONES as bullet rows with `(C3, C4)` / `(Gauche)` suffixes, one `CONSTATS — <ZONE>` section per (zone, side) with snapshot labels and the `(!)` marker, free findings / severity / comment / view captions, conclusion page and header identity on every page, EN variant with identical attachment, deep-equal roundtrip, attachment dictionaries (`/F (osteo-report.json)`, `/AFRelationship /Data`, `/Desc` UTF-16 "Faunosteo state v2", `/Subtype /application#2Fjson`, Flate), pdf-lib 1.17.1 has no `getAttachments` so the traversal is the production path, `incompatible_version` with `foundVersion 3`, foreign attachment and Zod-invalid attachment both reported as `no_attachment` (**known**), orphan finding printed under its zone, unknown ids printed raw. |
|
||||||
|
| `tests/unit/char.schemaPersistence.test.ts` | 13 | Zod: fixtures accepted unchanged, unknown keys stripped, version literal 2, unbounded vertebra index (C99), French severity enum, orphan findings accepted, unknown species accepted, duplicate boneId with sides / detail. Persistence: full fixture mirrored to and restored from `osteo:draft`, `hydrateReport` does not revalidate, `initReport` shape, `osteo:lastPractitioner`, `osteo:locale`. |
|
||||||
|
| `tests/unit/char.i18nSpecies.test.tsx` | 12 | Dynamic keys (`severity.*`, `vertebra.region.*`, `home.import.error_*` with `{version}`, `pdf.section.*`/`pdf.view.*`), 71 `svg_editor.*` keys, label fallbacks, registry = equine only with the committed formula, catalog loader species id, `NewReportRoute` select defaults to equine with one option, scaffold script quirks (`schema_version '1.1'`, T13 default). |
|
||||||
|
|
||||||
|
Pre-existing tests reused as-is: all 32 files (180 cases). They already
|
||||||
|
cover: SVG parser rules and counts (`anatomy.*`), zoneMatch on a synthetic
|
||||||
|
catalog, spineZones on synthetic bones, VertebraPicker, FindingsTreePicker,
|
||||||
|
schemas, store actions and draft mirror, practitioner cache, locale,
|
||||||
|
dictionary parity, minimal PDF roundtrip, attachment extraction and the 16 MiB
|
||||||
|
inflate cap, `buildZoneLabels`, `rasterizeSvg`, UI primitives.
|
||||||
|
|
||||||
|
## 3. Behaviours characterised (summary)
|
||||||
|
|
||||||
|
- Report: schema acceptance boundary, store init/hydrate, persistence keys, draft restore.
|
||||||
|
- Anatomy: real SVG attributes and categories, id spaces, parser output, spine region inference and sync on real data.
|
||||||
|
- Findings: catalog structure, counts, conventions, anomalies, SVG ↔ catalog link table, matcher behaviour and fragile pairs.
|
||||||
|
- Pathology editor: matcher parity, id generation, translations, config, isolation.
|
||||||
|
- Click chain: every branch of `onZoneClick` and the three pickers' effect on the store.
|
||||||
|
- PDF: full export text, pages, attachment format, import error kinds, degradation on missing assets.
|
||||||
|
- i18n: dynamic keys, fallbacks, dictionary surface tied to legacy tools.
|
||||||
|
- Special cases: detail trigger, orphan findings, disclaimer flag, unbounded vertebra index, unknown species, foreign attachments.
|
||||||
|
|
||||||
|
## 4. Behaviours NOT characterised, and why
|
||||||
|
|
||||||
|
| Area | Reason | Where it will be covered |
|
||||||
|
|---|---|---|
|
||||||
|
| SVG editor (`SvgEditorRoute.tsx`, 1858 lines) | Vanilla DOM inside a `useEffect`, state in the DOM, drag/mouse geometry depends on `getScreenCTM` which happy-dom does not implement. Testing it would require rewriting it (forbidden in this step). | Replaced by the merged editor (plan Step 17); its operations are listed in audit 03 §2 and become reference tests of the new model. |
|
||||||
|
| Pathology editor DOM behaviour (tree add/edit/delete, dirty flag, download) | 1700 lines of imperative DOM in an IIFE with no export; only the pure functions were extracted by text. | Merged editor findings panel (Step 17). |
|
||||||
|
| Real rasterisation (`rasterizeSvg` on the real SVG) | No canvas in happy-dom; a 1×1 PNG stub is used. The existing `pdf.svgToPng` test covers the function with mocks. | Playwright raster hash at the PDF step (Step 6) or later e2e. |
|
||||||
|
| Visual PDF layout (positions, wrapping, pagination) | Only drawn strings are captured, not coordinates. | PDF golden comparison by extracted text stays; layout is a visual QA item. |
|
||||||
|
| Vertex-level SVG geometry | `cx/cy/points` are never read by the app; no behaviour to pin. | Importer tests (Step 4) when geometry becomes data. |
|
||||||
|
| `window.alert` on export failure, download anchor click | Side effects of the route; no value in pinning. | e2e. |
|
||||||
|
| Browser e2e (real routing, file input import, download) | No Playwright in the repo; adding it is tooling work outside this step. | See §6. |
|
||||||
|
|
||||||
|
## 5. Problems discovered (none fixed, by rule)
|
||||||
|
|
||||||
|
1. **Host tooling**: this machine had no `pnpm` and no `node_modules`; CLAUDE.md says pnpm is at `~/.local/bin/pnpm`, which does not exist. Node is 24.21.0, not 20. Used `corepack prepare pnpm@10.13.1` (the Dockerfile pin). CLAUDE.md note is stale.
|
||||||
|
2. **Import error cause lost**: a Zod-invalid attachment and a foreign JSON attachment both surface as `no_attachment` (audit 08 B.2, pinned as known).
|
||||||
|
3. **ZONES rendering**: the ' · ' joined value is split back into bullet rows by the renderer; harmless, but the dictionary-level `pdf.empty` fallback is printed when an observation has findings but no zone.
|
||||||
|
4. **Fuzzy tolerance**: the FR pairs fetlock ant./post. and sacral/caudal are inside the Levenshtein threshold (5 ≤ 7, 3 ≤ 4); unreachable today only because EN labels are exact.
|
||||||
|
5. **Scaffold script** writes `schema_version '1.1'` and a mixed formula (known, script slated for removal).
|
||||||
|
6. **README** still says 174 tests (actual before this step: 180). Not edited in this step to keep the diff to tests and docs; corrected at Step 2 with the workspace move.
|
||||||
|
|
||||||
|
## 6. To cover in a future e2e suite
|
||||||
|
|
||||||
|
- Full flow: `/` → `/new` → `/editor` → zones of each kind → findings → export → download → re-import from `/`.
|
||||||
|
- Session persistence across a real reload (sessionStorage) and language switch mid-edit.
|
||||||
|
- Detail modal interactions with real pointer events (tooltip hidden on the trigger).
|
||||||
|
- PDF opened in a viewer: attachment visible, pages readable, raster images present.
|
||||||
|
- Mobile viewport layout of the editor.
|
||||||
|
|
||||||
|
## 7. Known obsolescence
|
||||||
|
|
||||||
|
Tests in `char.clickChain.test.tsx` and `char.pdfFull.test.ts` are written
|
||||||
|
against the current route and export signatures. Plan Step 5 (zone service,
|
||||||
|
document v3) and Step 6 (PDF v3) will replace them one-to-one; each deleted
|
||||||
|
test must name its replacement in the commit message (TEST_STRATEGY.md §6).
|
||||||
|
`char.pathologyEditor.test.ts` and the `svg_editor.*` key count die with the
|
||||||
|
legacy editors (Step 17). `char.catalog.test.ts` and
|
||||||
|
`char.svgCatalogLink.test.ts` become the oracle of the legacy importer
|
||||||
|
(Step 4) and survive as long as the seed files exist.
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
# Domain map
|
||||||
|
|
||||||
|
Status: Step 0 deliverable, 2026-10-08. Derived from
|
||||||
|
`faunosteo-business-architecture.md` §2, §4–§20, §24 and confronted with the
|
||||||
|
current code (`docs/faunosteo-audit/`). No SQL here: entity names are the
|
||||||
|
conceptual tables of the architecture document, listed so that each
|
||||||
|
implementation step knows which domain it touches.
|
||||||
|
|
||||||
|
Conventions used below:
|
||||||
|
|
||||||
|
- "Entities" = the persisted concepts of the domain (future tables or JSONB documents).
|
||||||
|
- "Depends on" = another domain whose rows this domain references (foreign keys or RPC calls).
|
||||||
|
- "Reuse" = code in the current repository that survives into this domain (see `REPOSITORY_MIGRATION_MAP.md`).
|
||||||
|
- "Server-only" = business rules that must run in PostgreSQL/RLS/RPC, never in the browser (architecture §17, §36; brief §19).
|
||||||
|
|
||||||
|
## 0. Domain dependency graph
|
||||||
|
|
||||||
|
```text
|
||||||
|
┌────────────┐
|
||||||
|
│ Identity │ profiles, roles
|
||||||
|
└─────┬──────┘
|
||||||
|
┌──────────────┼───────────────────────┬────────────────┐
|
||||||
|
▼ ▼ ▼ ▼
|
||||||
|
┌───────────────┐ ┌─────────────┐ ┌──────────────┐ ┌──────────────┐
|
||||||
|
│ Professional │ │Organizations│ │ Billing & │ │Administration│
|
||||||
|
│ Verification │ │ (cabinet) │ │ Entitlements │ │ audit, mod. │
|
||||||
|
└───────────────┘ └──────┬──────┘ └──────┬───────┘ └──────────────┘
|
||||||
|
│ │ (capabilities)
|
||||||
|
┌────────────────┼────────────────────┼─────────────┐
|
||||||
|
▼ ▼ ▼ ▼
|
||||||
|
┌─────────┐ ┌──────────┐ ┌────────────┐ ┌──────────┐
|
||||||
|
│ Clients │────▶│ Animals │───────▶│ Reports │ │ Booking │
|
||||||
|
└─────────┘ └──────────┘ └─────┬──────┘ └────┬─────┘
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
┌──────────────────┐ ┌──────────┐ ┌──────────┐
|
||||||
|
│ Anatomical Sheets│ │ Travel │ │ Calendar │
|
||||||
|
│ (sheet, version) │ └──────────┘ └──────────┘
|
||||||
|
└────────┬─────────┘
|
||||||
|
▼
|
||||||
|
┌───────────┐
|
||||||
|
│ Community │ follow, grants, fork, moderation
|
||||||
|
└───────────┘
|
||||||
|
|
||||||
|
Cross-cutting: Files (Storage metadata), Notifications, Imports,
|
||||||
|
Public Profile (SEO), Education (post-MVP).
|
||||||
|
```
|
||||||
|
|
||||||
|
Reading rule: an arrow means "needs rows from". Reports need an Animal and a
|
||||||
|
Sheet Version; Community needs Sheets and Identity; Booking needs Clients,
|
||||||
|
Animals, Identity and (optionally) Organizations.
|
||||||
|
|
||||||
|
## 1. Identity
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `profiles` (= `auth.users.id`), `profile_roles` (additive roles: practitioner, student, professor, owner, admin, moderator, support), `platform_invitations` |
|
||||||
|
| Depends on | Supabase Auth (email/password, Google, Apple, OTP/magic link, phone verification) |
|
||||||
|
| Depended on by | every other domain |
|
||||||
|
| Server-only | role grants (admin action, never a browser update), phone/email verification state, invitation acceptance |
|
||||||
|
| Reuse | `localeStore` (locale preference becomes `profiles.locale`), `practitionerCache` content shape (name, cabinet, contact, SIRET) seeds the profile form, `ConfigProvider` for runtime Supabase config |
|
||||||
|
| Notes | One human = one account; roles are additive (architecture §2.1). Phone verification needs an SMS provider: dependency and cost to confirm (`OPEN_QUESTIONS.md` Q7). |
|
||||||
|
|
||||||
|
## 2. Professional Verification
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `professional_verifications` (status pending/verified/rejected/expired, SIRET, professional identifier, C2V references), `professional_documents` (RC Pro, C2V proof, other; asset reference, expiry) |
|
||||||
|
| Depends on | Identity, Files (document assets), Administration (review by owner/admin, audit log) |
|
||||||
|
| Depended on by | Billing & Entitlements (verified status gates professional capabilities), Public Profile (verification badge) |
|
||||||
|
| Server-only | status transitions, automatic expiry when a time-bounded document lapses, reviewer identity |
|
||||||
|
| Reuse | none; the current app has no identity verification. `PractitionerSchema.siret` is the only overlap. |
|
||||||
|
| Notes | Required documents and acceptance criteria are a legal decision before launch (§5). What an unverified account may do is ambiguous (`OPEN_QUESTIONS.md` C6). |
|
||||||
|
|
||||||
|
## 3. Organizations (Cabinet)
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `organizations`, `organization_members` (owner, manager, secretary, practitioner; `billing_source` seat/personal) |
|
||||||
|
| Depends on | Identity, Files (logo), Billing (seats) |
|
||||||
|
| Depended on by | Reports (`ownership_scope = organization`), Clients/Animals (grants to an organization), Booking (org-scoped services), Community (grants to an organization), Anatomical Sheets (private sheet shared with an org) |
|
||||||
|
| Server-only | membership changes, "secretary cannot self-grant practitioner", one cabinet-paid seat per practitioner at a time |
|
||||||
|
| Reuse | none. `Practitioner.cabinet` free text in the report is the only trace of the concept. |
|
||||||
|
|
||||||
|
## 4. Clients
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `clients` (global person record, optional `auth_user_id`), `client_contacts` (multiple email/phone, normalized, verified), `client_consents` (purpose, legal text version, granted/revoked), `client_access_grants` (grantee user/org, scope, expiry, revocation) |
|
||||||
|
| Depends on | Identity (grantees), Organizations (grantees), Administration (audit of consent changes) |
|
||||||
|
| Depended on by | Animals, Reports (through Animal), Booking, Notifications (document delivery), Imports |
|
||||||
|
| Server-only | candidate matching on normalized contacts without revealing another practitioner's relationship, consent recording with legal text version, grant evaluation |
|
||||||
|
| Reuse | `OwnerSchema` (`{ name }`) is the only current owner data; it becomes the identity snapshot inside the report document. |
|
||||||
|
| Notes | A *global* client record shared across practitioners is the single most sensitive design choice of the model. See `OPEN_QUESTIONS.md` C4 and Q6. |
|
||||||
|
|
||||||
|
## 5. Animals
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `animals` (client, species, name, breed, sex, neutered, birth date, identification number, weight, colour, photo asset, notes, deceased fields), `animal_access_grants` |
|
||||||
|
| Depends on | Clients, Anatomical Sheets (species reference; species is a first-class list, not a sheet), Files (photo) |
|
||||||
|
| Depended on by | Reports, Booking (appointment for an animal), Imports |
|
||||||
|
| Server-only | grant evaluation, update rights (owner-controlled vs practitioner-after-consultation, ambiguous in MVP without client accounts: `OPEN_QUESTIONS.md` C5) |
|
||||||
|
| Reuse | `AnimalSchema` (`speciesId`, `name`, `breed`, `age`) as the identity snapshot inside the report document; `AnimalForm` as the "new animal" dialog shell. |
|
||||||
|
| Notes | Principle 1: an Animal is not an Anatomical Sheet. The animal carries `species_id`; the report chooses a sheet version for that species. |
|
||||||
|
|
||||||
|
## 6. Anatomical Sheets
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `species` (list: id, labels), `anatomical_sheets` (identity, creator, visibility, status, provenance `based_on_sheet_id`/`based_on_version_id`, `current_version_id`), `anatomical_sheet_versions` (version number, status draft/published/deprecated, `document_schema_version`, `content_jsonb`, assets, publication metadata), sheet assets in Storage (SVG per view) |
|
||||||
|
| Canonical document (JSONB) | `schema_version`, `species_id`, `vertebral_config` (ordered regions: code, label FR/EN, count), `views[]` (id, kind main/detail, `parent_view_id`, `opened_by_annotation_id`, `view_box`, `svg_asset_id`), `annotations[]` (stable id, view id, kind point/zone/detail-trigger, category id, names FR/EN, laterality, special, geometry), `categories[]` (id, label, colour), `finding_tree.zones{}` (current `ZoneFindings` shape), `annotation_finding_map[]` (annotation id → finding zone id), `scope_disclaimer`, legacy id map (old `data-anno-id` → new id) kept for migration only |
|
||||||
|
| Depends on | Identity (creator), Files (SVG assets), Community (visibility/grants read at use time), Billing (private visibility add-on) |
|
||||||
|
| Depended on by | Reports (exact version reference), Community, Animals (species list), Imports (none) |
|
||||||
|
| Server-only | version immutability once published, version numbering, garbage collection preconditions (no report, no fork, no grant, no pending process), SVG sanitization before any other user can read the asset, "can use / can fork" evaluation |
|
||||||
|
| Reuse | `parseSvgBones` (importer and renderer), `findings.ts` schema (finding tree), `zoneMatch.ts` (importer only), `regionFromLabel` (importer only), `AnatomyCanvas`, `DetailModal`, `VertebraPicker`, `FindingsTreePicker`, the two equine SVGs and the catalog as seed, the tree-edit behaviour of `pathology-editor.html` and the annotation operations of `SvgEditorRoute` as functional references |
|
||||||
|
| Notes | Rules 2–8 of the brief (§18) all live here. The current code has no sheet object at all (audit 02 §6): no id, no version, no author, no persisted SVG ↔ catalog link. |
|
||||||
|
|
||||||
|
## 7. Reports
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `reports` (report number, animal, practitioner, organization nullable, ownership scope, status draft/completed/archived, report date, `anatomical_sheet_version_id`, `current_document`, revision counter, `completed_at`, `free_edit_until`, soft delete), `report_revisions` (document snapshots with reason), `report_access_grants`, `practitioner_report_counters` (row-locked numbering), report PDF artifacts (Files) |
|
||||||
|
| Report document (JSONB) | current `Report` v2 shape evolved to v3: observations with zones keyed by `annotationId` + `viewId`, vertebrae with region code, findings with snapshots, free text, severity, comment, conclusion, recommendations, next appointment, identity snapshots (practitioner, animal, client), `localAnnotations[]` (report-only points, see `OPEN_QUESTIONS.md` Q6), locale used for the last PDF |
|
||||||
|
| Depends on | Animals (and Clients through them), Identity, Organizations, Anatomical Sheets (exact version), Billing & Entitlements (quota, free edit window), Files (PDF artifacts) |
|
||||||
|
| Depended on by | Community (shared report revisions), Booking (appointment ↔ report link, optional), Imports, Notifications (secure sending to the owner) |
|
||||||
|
| Server-only | report numbering, completion (quota check, `free_edit_until`), revision checkpoints, "deleted completed reports still count", shared-practitioner revision acceptance, import quota preflight |
|
||||||
|
| Reuse | `reportStore` actions (observation CRUD, setters), `ObservationCard`, `ObservationList`, pickers, `ConclusionPanel`, `NextAppointmentPicker`, `pdf/*` pipeline, `Report` v2 schema as adapter input |
|
||||||
|
| Notes | Principle 3/4: a report references an exact sheet version. Autosave writes `current_document`; revisions are checkpoints (§9.1). |
|
||||||
|
|
||||||
|
## 8. Community
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `practitioner_follows`, `sheet_usage_grants` (use / fork, user or org grantee, expiry), `community_reports` (profile/sheet reports, moderation status), public counters (followers, sheet usage) |
|
||||||
|
| Depends on | Identity, Anatomical Sheets, Organizations (grantees), Administration (moderation roles) |
|
||||||
|
| Depended on by | Reports (which sheets a practitioner may select), Public Profile (follow counts, discovery) |
|
||||||
|
| Server-only | "follow grants use of a public sheet", "private sheet needs explicit grant", fork provenance recording, moderation actions by owner/admin/moderator only (support excluded) |
|
||||||
|
| Reuse | none directly. |
|
||||||
|
| Notes | Mandatory for the commercial MVP (§33). No likes/comments/ratings. |
|
||||||
|
|
||||||
|
## 9. Booking (Agenda)
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `service_types`, `locations`, `availability_rules`, `availability_exceptions`, `appointments` (status machine requested/confirmed/rejected/cancelled/completed/no_show, request expiry, deposit state, travel minutes, source), `intake_forms`, `intake_questions`, `appointment_intake_answers`, `booking_widget_tokens` |
|
||||||
|
| Depends on | Identity, Organizations, Clients, Animals, Travel, Calendar Sync (blocking events), Notifications (reminders, confirmations) |
|
||||||
|
| Depended on by | Public Profile (booking entry point), Notifications |
|
||||||
|
| Server-only | slot evaluation, pending-request expiry rules (48h / 24h / 1h), one pending request per client per practitioner flow, race-safe slot locking, auto vs manual confirmation, widget token validation |
|
||||||
|
| Reuse | `NextAppointmentPicker` as the only link from a report to a future appointment. |
|
||||||
|
| Notes | Expiry rules implemented in one database function (§10). |
|
||||||
|
|
||||||
|
## 10. Travel
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `travel_profiles` (base location, return policy, routing provider, default buffers), `travel_pricing_rules`, route cache |
|
||||||
|
| Depends on | Booking (locations, appointments), an external routing provider behind a `RoutingProvider` interface |
|
||||||
|
| Depended on by | Booking (availability evaluation) |
|
||||||
|
| Server-only | final availability check at booking time (never trust client-computed travel) |
|
||||||
|
| Reuse | none. |
|
||||||
|
|
||||||
|
## 11. Calendar Sync
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `external_calendar_connections` (provider google / apple_ics, encrypted refresh credentials), `external_calendar_events` (blocking state, checksum) |
|
||||||
|
| Depends on | Identity, Booking, worker (sync jobs), Notifications (conflict alerts) |
|
||||||
|
| Server-only | credential storage and refresh, sync jobs, conflict detection; external event details never exposed to clients |
|
||||||
|
| Reuse | none. |
|
||||||
|
|
||||||
|
## 12. Files (Storage)
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `assets` (bucket, object key, owner scope, resource type/id, mime, size, checksum, sanitization status), buckets `avatars/ logos/ professional-documents/ client-files/ animal-files/ report-files/ anatomical-sheets/ imports/` |
|
||||||
|
| Depends on | Identity, and every owning domain for access rules |
|
||||||
|
| Depended on by | Verification, Clients, Animals, Reports (PDF artifacts), Anatomical Sheets (SVG), Imports, Public Profile (photos, logos) |
|
||||||
|
| Server-only | object key generation (`<resource>/<resource-id>/<asset-id>/<safe-filename>`), signed URL issuance, SVG sanitization and quarantine, `storage.objects` RLS |
|
||||||
|
| Reuse | `sanitizeSvg` (10 lines in `SvgEditorRoute` and duplicated in `pathology-editor.html`) as the *client-side* pre-check only; the server sanitizer is new. |
|
||||||
|
|
||||||
|
## 13. Billing & Entitlements
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `plans`, `subscriptions` (user or organization subscriber, Stripe ids, status, period, cancel at period end), `subscription_seats`, `entitlement_grants` (student, invited, promo, admin, professor), `referrals` (referrer, referred, status, reward months, yearly cap), function `get_effective_entitlements(user_id)` |
|
||||||
|
| Depends on | Identity, Organizations, Professional Verification, Stripe (webhooks), Administration (overrides audited) |
|
||||||
|
| Depended on by | Reports (quota, `reports.write`, `reports.edit_after_free_window`), Community (`community.publish_sheet`), Booking (`booking.manage`), Public Profile (`profile.public`), Anatomical Sheets (private visibility add-on) |
|
||||||
|
| Server-only | everything: effective entitlement computation, free lifetime quota (5 completed reports, deletions and imports count), 5-day free edit window, referral eligibility (verified email + phone, max 5/year), seat exclusivity |
|
||||||
|
| Reuse | none. |
|
||||||
|
| Notes | The entitlement engine is needed *before* Stripe: the free plan and admin/invited grants must exist when cloud reports ship. The plan therefore splits "entitlement skeleton" (early) from "Stripe billing" (late). |
|
||||||
|
|
||||||
|
## 14. Imports
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `import_jobs`, `import_files`, `import_raw_records`, `import_mappings`, `import_errors`, `import_unmapped_data` ("Données importées") |
|
||||||
|
| Depends on | Identity, Clients, Animals, Reports, Files, Billing (quota preflight), worker (long imports) |
|
||||||
|
| Depended on by | none |
|
||||||
|
| Server-only | preflight (read-only), quota check before commit, atomic commit (no partial slip of 20 reports on a free account), duplicate candidates never auto-merged |
|
||||||
|
| Reuse | `pdf/import.ts` path becomes one adapter ("Faunosteo PDF v2/v3"); `zoneMatch` as a mapping suggestion helper for legacy reports. |
|
||||||
|
|
||||||
|
## 15. Notifications
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `notification_jobs` (PostgreSQL-backed queue), `email_templates` (FR/EN), delivery log |
|
||||||
|
| Depends on | Identity, Booking, Reports, an `EmailProvider` abstraction, worker |
|
||||||
|
| Depended on by | Booking (confirmations, reminders), Reports (secure document delivery), Verification (status emails), Billing (invoices) |
|
||||||
|
| Server-only | sending, retries, secure link token generation |
|
||||||
|
| Reuse | none. |
|
||||||
|
|
||||||
|
## 16. Administration
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `audit_logs` (actor, action, resource, org, target user, sanitized metadata, correlation id), impersonation sessions (short-lived, audited), moderation queue (Community), legal documents and acceptance versions |
|
||||||
|
| Depends on | Identity (owner/admin/moderator/support roles), every domain that emits audit events |
|
||||||
|
| Depended on by | Verification (review), Community (moderation), Billing (overrides) |
|
||||||
|
| Server-only | all of it; admin MFA mandatory |
|
||||||
|
| Reuse | none. |
|
||||||
|
|
||||||
|
## 17. Public Profile (SEO)
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `public_practitioner_profiles` (slug, public name, bio, photo, logo, locations as permitted, services, prices, intervention zones, species, social links, verification status, published flag), public views/RPCs exposing only approved columns |
|
||||||
|
| Depends on | Identity, Verification, Organizations, Booking (services, locations), Files (photo, logo), Community (follow counts) |
|
||||||
|
| Depended on by | `apps/public-web`, Booking widget |
|
||||||
|
| Server-only | column allow-list in the public view, no clinical/client data reachable anonymously |
|
||||||
|
| Reuse | brand components for the platform shell only. |
|
||||||
|
|
||||||
|
## 18. Education (post-MVP, designed now)
|
||||||
|
|
||||||
|
| Item | Content |
|
||||||
|
|---|---|
|
||||||
|
| Entities | `student_professor_links`, `student_access_periods`, student-owned educational reports |
|
||||||
|
| Depends on | Identity (student/professor roles), Reports, Billing (student entitlement), Anatomical Sheets |
|
||||||
|
| Notes | Must not be built in the MVP, but `profile_roles` and `entitlement_grants` are shaped so it fits later without migration pain. |
|
||||||
|
|
||||||
|
## 19. Reuse matrix (current code → domain)
|
||||||
|
|
||||||
|
| Current module | Target domain |
|
||||||
|
|---|---|
|
||||||
|
| `domain/schema/findings.ts` | Anatomical Sheets (finding tree) |
|
||||||
|
| `domain/schema/observation.ts`, `report.ts` | Reports (document v3) |
|
||||||
|
| `domain/schema/animal.ts`, `practitioner.ts` | Reports (identity snapshots); Animals / Identity (form shells) |
|
||||||
|
| `anatomy/svgConvention.ts` | Anatomical Sheets (importer + renderer) |
|
||||||
|
| `lib/zoneMatch.ts`, `lib/spineZones.regionFromLabel` | Anatomical Sheets (importer only), Imports (suggestions) |
|
||||||
|
| `lib/spineZones.collect/sync` | Reports (spine interaction) |
|
||||||
|
| `state/reportStore.ts` | Reports (editor session + persistence adapter) |
|
||||||
|
| `components/observation/*`, `canvas/*` | Reports (editor UI), Anatomical Sheets (editor preview) |
|
||||||
|
| `pdf/*` | Reports (PDF artifact), Imports (PDF adapter) |
|
||||||
|
| `i18n/*` | cross-cutting |
|
||||||
|
| `public/species/equine/*` | Anatomical Sheets (official equine seed v1) |
|
||||||
|
| `public/pathology-editor.html`, `SvgEditorRoute.tsx` | Anatomical Sheets (behavioural reference for the merged editor, then deleted) |
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
# Frontend architecture (target)
|
||||||
|
|
||||||
|
Status: Step 0 deliverable, 2026-10-08. Proposal only; the repository is not
|
||||||
|
transformed by this document.
|
||||||
|
|
||||||
|
## 1. Starting point
|
||||||
|
|
||||||
|
The private application is a Vite 7 + React 19 SPA, TypeScript strict,
|
||||||
|
Tailwind v4, Zustand 5, Zod 3, pdf-lib, served by nginx from a Docker image.
|
||||||
|
Six routes (`/`, `/new`, `/editor`, `/svg-editor`, `/editors`, `*`) plus the
|
||||||
|
static `/pathology-editor.html`. No auth, no backend, state in
|
||||||
|
`sessionStorage`/`localStorage` (BDR-001, audit 01 §2).
|
||||||
|
|
||||||
|
The architecture document asks to keep this app "close to its working form"
|
||||||
|
(§21.1, §21.3) and to serve public SEO pages server-side (§21.2). Both are
|
||||||
|
compatible with the current code; neither requires a rewrite.
|
||||||
|
|
||||||
|
## 2. Is `apps/app`, `apps/public-web`, `apps/worker` right for this repository?
|
||||||
|
|
||||||
|
Short answer: yes for the three units, no for creating them all on day one.
|
||||||
|
|
||||||
|
| Unit | Verdict | Why |
|
||||||
|
|---|---|---|
|
||||||
|
| `apps/app` (Vite React, private) | Adopt at the first structural step | It *is* the current app. Moving it under `apps/` while it has 82 source files and 32 test files is cheap; doing it after packages and a second app exist is not. |
|
||||||
|
| `apps/public-web` (Next.js) | Adopt, but only at the "Public profile + public site" step | Nothing public exists before practitioner profiles. Creating an empty Next.js app earlier adds a toolchain to maintain with no deliverable behind it. |
|
||||||
|
| `apps/worker` (Node) | Adopt, but only at the "Agenda / Notifications" step | Until reminders, appointment expiry and calendar sync exist, every job can be a PostgreSQL function or `pg_cron` job inside Supabase (architecture §22.3 says "start with PostgreSQL-backed jobs"). |
|
||||||
|
|
||||||
|
Alternatives considered and rejected:
|
||||||
|
|
||||||
|
- **Single Next.js app for everything.** Rejected: rewrite of the editor and PDF pipeline, SSR brings no value to a clinical tool behind auth, contradicts §21.3.
|
||||||
|
- **Keep the app at the repository root, add `apps/public-web` beside it.** Rejected: path aliases (`@/*`), Docker build context, tsconfig includes and Vitest config would all special-case the root app; `pnpm-workspace.yaml` already exists at the root (it only holds `allowBuilds` today), so the workspace is one line away.
|
||||||
|
- **Astro for the public site** (global rule: Astro by default for informational sites). Viable: Astro with the Node adapter can render practitioner profiles from Supabase. The approved architecture names Next.js, mainly for `@supabase/ssr`. This is a visible choice for a later step and is logged in `OPEN_QUESTIONS.md` (Q8), not decided here. It does not affect the private app.
|
||||||
|
|
||||||
|
Target tree (end state; intermediate states have fewer entries):
|
||||||
|
|
||||||
|
```text
|
||||||
|
apps/
|
||||||
|
app/ Vite React private application (current src/, public/, tests/)
|
||||||
|
public-web/ Next.js (or Astro SSR) public pages, created at the public-profile step
|
||||||
|
worker/ Node worker, created at the agenda/notifications step
|
||||||
|
packages/
|
||||||
|
domain/ Zod schemas: report document v3, sheet document, species, entitlements
|
||||||
|
anatomy/ sheet model helpers, legacy SVG importer, renderer helpers, spine logic
|
||||||
|
pdf/ export/import/attachment, render helpers (browser-only rasteriser)
|
||||||
|
i18n/ FR/EN dictionaries, useT
|
||||||
|
supabase/ client factory, generated Database types, typed RPC wrappers
|
||||||
|
ui/ primitives (only when public-web needs them)
|
||||||
|
config/ runtime config resolution (env.js / process.env)
|
||||||
|
supabase/
|
||||||
|
config.toml, migrations/, functions/, seed/, tests/
|
||||||
|
docker/
|
||||||
|
docs/
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. Private application (`apps/app`)
|
||||||
|
|
||||||
|
### 3.1 Route plan
|
||||||
|
|
||||||
|
Target routes (§21.3) and what replaces what:
|
||||||
|
|
||||||
|
| Target route | Replaces | Step introduced |
|
||||||
|
|---|---|---|
|
||||||
|
| `/app` → redirect to `/app/dashboard` | `/` (HomeRoute) | Auth shell |
|
||||||
|
| `/app/dashboard` | HomeRoute | Auth shell (empty), filled at Cloud reports |
|
||||||
|
| `/app/clients`, `/app/clients/:clientId` | nothing | Clients / Animals |
|
||||||
|
| `/app/animals/:animalId` | NewReportRoute (creation entry) | Clients / Animals |
|
||||||
|
| `/app/reports/:reportId` | `/editor` | Cloud reports |
|
||||||
|
| `/app/anatomy`, `/app/anatomy/:sheetId/editor` | `/svg-editor`, `/editors`, `/pathology-editor.html` | Editor merge |
|
||||||
|
| `/app/community` | nothing | Community |
|
||||||
|
| `/app/calendar` | nothing | Agenda |
|
||||||
|
| `/app/profile/edit`, `/app/settings`, `/app/billing` | nothing | Identity / Billing |
|
||||||
|
| `/app/admin/*` | nothing | Administration |
|
||||||
|
|
||||||
|
Transition rule: legacy routes keep working until the step that replaces them
|
||||||
|
lands, then redirect for one release, then disappear. The "local-only" flow
|
||||||
|
(no account, sessionStorage draft) is retired at the Cloud reports step; there
|
||||||
|
is no customer install base to preserve (CHANGELOG 0.1.0, architecture §23.4).
|
||||||
|
|
||||||
|
### 3.2 Layers
|
||||||
|
|
||||||
|
```text
|
||||||
|
UI (routes, components)
|
||||||
|
↓ calls
|
||||||
|
application services (apps/app/src/services/*) one function per use case, no React
|
||||||
|
↓ calls
|
||||||
|
packages/supabase typed client (RPC, tables, storage)
|
||||||
|
↓
|
||||||
|
PostgreSQL / RLS / Edge Functions
|
||||||
|
```
|
||||||
|
|
||||||
|
Rule (architecture §21.5): no business rule in a component. Today the click
|
||||||
|
chain lives in `EditorRoute.tsx` (`onZoneClick`, lines 290–320, plus four
|
||||||
|
handlers). It becomes `services/zoneInteraction.ts`, pure, tested, and the
|
||||||
|
route only wires events to it.
|
||||||
|
|
||||||
|
### 3.3 State
|
||||||
|
|
||||||
|
Pattern (§21.4): **server data via a query cache, editor session via Zustand**.
|
||||||
|
|
||||||
|
- Add TanStack Query (`@tanstack/react-query`) for lists and records (clients,
|
||||||
|
animals, reports index, sheets, profile). Dependency declared at the Auth
|
||||||
|
shell step; stated purpose: cache, invalidation, loading states. Not
|
||||||
|
installed in Step 0.
|
||||||
|
- `reportStore` keeps the in-memory report document and its actions. Its
|
||||||
|
`sessionStorage` subscription becomes one implementation of a persistence
|
||||||
|
adapter:
|
||||||
|
|
||||||
|
```text
|
||||||
|
ReportPersistence
|
||||||
|
load(reportId): Promise<ReportDocument | null>
|
||||||
|
save(reportId, document, meta): Promise<SaveAck> // SaveAck carries server revision
|
||||||
|
subscribe(onRemoteChange)
|
||||||
|
```
|
||||||
|
|
||||||
|
Implementations in order of appearance: `sessionStoragePersistence` (today),
|
||||||
|
`supabasePersistence` (Cloud reports), `outboxPersistence` (IndexedDB queue
|
||||||
|
wrapping the Supabase one, Offline step). The UI shows sync state from the
|
||||||
|
adapter and never claims "saved" before the server ack (§Prompt 5).
|
||||||
|
- Sheet-version content loaded for a report is read-only in the editor; it is
|
||||||
|
cached by the query layer keyed on `sheet_version_id` (immutable, so cache
|
||||||
|
forever).
|
||||||
|
|
||||||
|
### 3.4 Anatomy rendering
|
||||||
|
|
||||||
|
`AnatomyCanvas` keeps inline SVG + delegated click on `data-anno-id`. The
|
||||||
|
renderer takes a canonical view (SVG text from Storage + annotations from the
|
||||||
|
document) and emits the `data-anno-*` attributes itself, so `parseSvgBones`
|
||||||
|
and the click delegation are unchanged. Detail views open through
|
||||||
|
`parent_view_id` / `opened_by_annotation_id` instead of the hard-coded
|
||||||
|
`details.head` map.
|
||||||
|
|
||||||
|
### 3.5 Editors
|
||||||
|
|
||||||
|
The SVG editor (vanilla DOM in `useEffect`, 1858 lines, zero tests) and the
|
||||||
|
pathology editor (static HTML, 1700 lines, zero tests) are not ported. The
|
||||||
|
merged Anatomical Sheet editor is written against the canonical document:
|
||||||
|
`load document → edit model → render SVG → serialize` (§23.2). The two old
|
||||||
|
tools stay reachable and untouched until the merged editor passes their
|
||||||
|
functional reference tests (audit 03 §2 and 05 §3.5 enumerate every
|
||||||
|
operation), then are deleted in the same step.
|
||||||
|
|
||||||
|
### 3.6 Runtime configuration
|
||||||
|
|
||||||
|
`window.__APP_CONFIG__` written by `docker/entrypoint.sh` stays the mechanism.
|
||||||
|
New keys: `supabaseUrl`, `supabaseAnonKey`, `publicWebUrl`, later tenant
|
||||||
|
branding. The anon key is public; RLS is the boundary. No service-role key
|
||||||
|
ever reaches `env.js`.
|
||||||
|
|
||||||
|
### 3.7 Offline
|
||||||
|
|
||||||
|
MVP target is network-interruption safety (§26): IndexedDB outbox for unsynced
|
||||||
|
report changes, visible sync state, automatic retry, conflict → conflict
|
||||||
|
revision chosen by the user. No full offline mirror.
|
||||||
|
|
||||||
|
## 4. Public site (`apps/public-web`)
|
||||||
|
|
||||||
|
Scope: landing, practitioner public profiles (`/osteopathe/<slug>`), search,
|
||||||
|
sheet discovery pages, later blog and SEO landing pages (§27). Reads only
|
||||||
|
public views/RPCs with the anon key; never a broad SELECT on core tables.
|
||||||
|
Supabase SSR adapter isolated in one module (the package is beta, §21.2).
|
||||||
|
Framework decision (Next.js per architecture vs Astro per global rule) is
|
||||||
|
taken at that step, see `OPEN_QUESTIONS.md` Q8.
|
||||||
|
|
||||||
|
## 5. Worker (`apps/worker`)
|
||||||
|
|
||||||
|
Node process, same Scaleway host, PostgreSQL-backed job table, no Redis
|
||||||
|
(§22.3). Jobs: reminders, appointment expiry (if not `pg_cron`), calendar
|
||||||
|
sync, route cache refresh, long imports, archive, sheet garbage collection.
|
||||||
|
Introduced when the first job that cannot be a SQL function exists.
|
||||||
|
|
||||||
|
## 6. Shared packages: contents, dependencies, reason, risk
|
||||||
|
|
||||||
|
| Package | Contents (from current code) | Depends on | Why extract | Risk |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `packages/domain` | `schema/report.ts` (v2 kept as input, v3 added), `observation.ts`, `findings.ts`, sheet document schema, species, entitlement capability names | zod | Shared by app, public-web (sheet discovery), worker (imports, GC), Edge Functions (validation) | Low. Pure Zod. Must stay free of DOM and Vite (`import.meta.glob` is excluded). |
|
||||||
|
| `packages/anatomy` | `svgConvention.ts`, `labels.ts`, generalized `spineZones.ts`, legacy importer (uses `zoneMatch.ts`, `regionFromLabel`), sheet renderer helpers | domain, DOM (`DOMParser`) | Importer runs in a Node script (seed) and in the app (editor import); renderer in app and later server PDF | Medium. DOM dependency: Node needs `linkedom`/`happy-dom` for the importer. Keep DOM-free functions separate from DOM-bound ones inside the package. |
|
||||||
|
| `packages/pdf` | `export.ts`, `import.ts`, `attachment.ts`, `render/*`, `fonts.ts` | domain, anatomy, pdf-lib, browser `Image`/`canvas` | Used by app now, by worker later for server-side PDFs | High for the server path: `svgToPng` is browser-only. Extract with a `Rasterizer` interface so a server implementation can be added without touching page layout. |
|
||||||
|
| `packages/i18n` | `fr.ts`, `en.ts`, `index.ts`, `useT.ts`, `types.ts` | react (for `useT` only) | public-web and the worker's emails need the same strings | Low. Split `useT` (React) from the dictionaries so the worker does not pull React. |
|
||||||
|
| `packages/supabase` | client factories (browser, SSR, service for worker), generated `database.types.ts`, typed RPC wrappers | @supabase/supabase-js | Single place for generated types and auth helpers | Medium. Generated file must be CI-checked against migrations; three client flavours must not share the service key. |
|
||||||
|
| `packages/ui` | `components/ui/*`, `styles/tokens.css` | react, tailwind | Only when public-web reuses them | Low, but premature before public-web exists. |
|
||||||
|
| `packages/config` | `config/env.ts` resolution (window config vs process.env) | none | app, public-web, worker read the same keys | Low. |
|
||||||
|
|
||||||
|
Extraction order follows need, not the list: `domain` and `anatomy` first
|
||||||
|
(the sheet model is pure code and unblocks the seed), `pdf` and `i18n` next,
|
||||||
|
`supabase` with the first DB step, `ui`/`config` with public-web.
|
||||||
|
|
||||||
|
## 7. Where the current app trusts the frontend (brief §19)
|
||||||
|
|
||||||
|
Everything, since there is no backend. The items that matter because they
|
||||||
|
become multi-tenant:
|
||||||
|
|
||||||
|
| Trusted today | File | Target boundary |
|
||||||
|
|---|---|---|
|
||||||
|
| Practitioner identity typed in a form (name, cabinet, contact, SIRET) | `PractitionerForm.tsx`, `practitionerCache.ts` | profile + verification rows; report snapshot copied server-side at creation |
|
||||||
|
| Any PDF with a `osteo-report*.json` attachment becomes a report after a shape-only Zod parse | `pdf/import.ts`, `attachment.ts` | import RPC validates ownership, species/sheet existence, quota, then inserts |
|
||||||
|
| `speciesId` free string selects the sheet | `AnimalSchema.speciesId`, `NewReportRoute.tsx:20` default `'equine'` | `reports.anatomical_sheet_version_id` FK + `can_use_sheet` policy |
|
||||||
|
| SVG sanitization of uploaded files | `SvgEditorRoute.tsx:511-520`, `pathology-editor.html:1127-1136` | server-side sanitizer before an asset becomes readable by others (§15.3) |
|
||||||
|
| Catalog edits replace production data by manual file copy | `pathology-editor.html` download → `src/` + `public/` | sheet version publish RPC with schema validation and immutability |
|
||||||
|
| Disclaimer acknowledgement | `sessionStorage['osteo:disclaimer-shown']` | legal acceptance recorded with `legal_text_version` when it carries legal weight |
|
||||||
|
| Quota / plan | nothing exists | `get_effective_entitlements` + `complete_report` RPC |
|
||||||
|
| Locale | `localStorage['osteo:locale']` | fine to keep client-side; mirrored to profile for emails |
|
||||||
|
|
||||||
|
## 8. Things that must not change in the first structural step
|
||||||
|
|
||||||
|
- Behaviour of the six routes and the static editor.
|
||||||
|
- `pnpm typecheck`, `pnpm test:run` (180 cases), `pnpm lint`, `pnpm build`, Docker build all green with identical semantics.
|
||||||
|
- Public asset paths `/species/equine/*` (still fetched by three tools until the sheet seed exists).
|
||||||
@@ -0,0 +1,634 @@
|
|||||||
|
# Faunosteo SaaS: implementation plan
|
||||||
|
|
||||||
|
Status: Step 0 deliverable, 2026-10-08. Main document of `docs/development/`.
|
||||||
|
Companion documents: `REPOSITORY_MIGRATION_MAP.md` (what happens to each
|
||||||
|
current file), `DOMAIN_MAP.md` (future domains), `FRONTEND_ARCHITECTURE.md`,
|
||||||
|
`BACKEND_ARCHITECTURE.md`, `MIGRATION_STRATEGY.md` (how modules evolve),
|
||||||
|
`TEST_STRATEGY.md`, `OPEN_QUESTIONS.md` (contradictions and questions).
|
||||||
|
|
||||||
|
Reference product/architecture: `faunosteo-business-architecture.md`
|
||||||
|
(2026-10-07). Reference of current behaviour: `docs/faunosteo-audit/`
|
||||||
|
(frozen at `83e40af`). The code is the source of truth for what the app
|
||||||
|
does today; the architecture document is the source of truth for what it
|
||||||
|
must become. Where the two disagree, `OPEN_QUESTIONS.md` records it.
|
||||||
|
|
||||||
|
## 1. How to read the plan
|
||||||
|
|
||||||
|
- Steps follow the real dependency order, not the commercial sprint order of
|
||||||
|
the architecture document (§35). The mapping to those sprints is given in
|
||||||
|
§6.
|
||||||
|
- Every step is a testable deliverable: it ends in a known state with
|
||||||
|
automated tests, a manual validation script and a Definition of Done. No
|
||||||
|
step is "half of a feature".
|
||||||
|
- Steps marked `∥` can run in parallel with the step named.
|
||||||
|
- Each step is one gitflow branch (`feature/<nn>-<slug>` off `develop`,
|
||||||
|
merged on explicit human signal); long steps may be split into
|
||||||
|
sub-branches that each leave `develop` green. Branch names are in §7.
|
||||||
|
- The invariants of the brief (§18 rules 1–8, §19 security) are restated at
|
||||||
|
the step where they become enforceable.
|
||||||
|
- Effort is not estimated in hours here; the "size" column in §5 gives a
|
||||||
|
relative order of magnitude.
|
||||||
|
|
||||||
|
## 2. Guiding principles for every step
|
||||||
|
|
||||||
|
1. `pnpm typecheck && pnpm test:run && pnpm lint` green before any commit; for
|
||||||
|
DB steps also `supabase db reset && supabase test db` (architecture §36).
|
||||||
|
2. A step that adds a table adds its RLS policies, indexes, pgTAP tests and
|
||||||
|
regenerated types in the same branch.
|
||||||
|
3. The UI is never the security boundary; every rule listed in
|
||||||
|
`BACKEND_ARCHITECTURE.md` §10 is implemented in PostgreSQL or a server
|
||||||
|
function.
|
||||||
|
4. No deletion of user data. Soft delete, revisions, archive.
|
||||||
|
5. Legacy modules are deleted at the step named in
|
||||||
|
`REPOSITORY_MIGRATION_MAP.md`, in the same branch that makes them dead.
|
||||||
|
|
||||||
|
## 3. Steps
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 0
|
||||||
|
Name: Preparation and technical plan
|
||||||
|
Objective: Confront target architecture, audit and code; produce docs/development/.
|
||||||
|
Dependencies: none
|
||||||
|
Changes expected: docs/development/* only (this set). No application file.
|
||||||
|
Tests: none
|
||||||
|
Manual validation: documents reviewed by the developer; open questions answered or deferred explicitly.
|
||||||
|
Definition of Done: the 8 documents exist; Step 1 can start without further analysis.
|
||||||
|
Risks: plan built on an audit frozen at 83e40af; two later commits (audit merge, hooks) do not touch src/.
|
||||||
|
Status: DONE 2026-10-08.
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 1
|
||||||
|
Name: Characterisation tests on the current application
|
||||||
|
Objective: Pin the behaviour that the migration must preserve, on real data, without changing application code.
|
||||||
|
Dependencies: Step 0
|
||||||
|
Changes expected:
|
||||||
|
- tests/unit/*: click chain (onZoneClick branches), spine sync on real Horse.svg,
|
||||||
|
SVG ↔ catalog strict mapping table (27 annotations → 26 zones), opens-detail ↔
|
||||||
|
manifest coherence, matcher parity app vs pathology-editor.html, catalog copies
|
||||||
|
byte parity, catalog invariants (incl. the sphenoid/ssb-dysfunctions anomaly
|
||||||
|
asserted as known), full PDF roundtrip with every zone kind + text assertions,
|
||||||
|
traverseForJsonAttachment fallback, orphan findings behaviour, registry/AnimalForm.
|
||||||
|
- tests/fixtures/report-v2.full.json, report-v2.minimal.json (golden).
|
||||||
|
- README test count corrected (174 → actual).
|
||||||
|
- No file under src/ or public/ changes.
|
||||||
|
Tests: the new tests themselves; existing 180 untouched and green.
|
||||||
|
Manual validation: pnpm test:run shows the new count; open one golden fixture and check it describes a realistic report.
|
||||||
|
Definition of Done: ≈230–250 green cases; TEST_STRATEGY.md §2 table fully checked; CI (if present) green.
|
||||||
|
Risks: happy-dom limits on canvas/Image for the roundtrip (mitigation: deterministic rasterizer stub + a separate Playwright check later); tests that encode a bug as expected behaviour must be labelled "known" in their name.
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 2
|
||||||
|
Name: Monorepo workspace
|
||||||
|
Objective: Move the app to apps/app under a pnpm workspace with zero behaviour change; add CI.
|
||||||
|
Dependencies: Step 1
|
||||||
|
Changes expected:
|
||||||
|
- apps/app/{src,public,tests,index.html,vite.config.ts,vitest.config.ts,tsconfig*.json,eslint.config.js,package.json}
|
||||||
|
- root: pnpm-workspace.yaml (packages: apps/*, packages/*), package.json scripts delegating
|
||||||
|
(pnpm -r typecheck/test:run/lint/build), shared prettier/editorconfig.
|
||||||
|
- Dockerfile build context and paths updated; docker/nginx.conf and entrypoint.sh unchanged in behaviour.
|
||||||
|
- CI pipeline file for the forge in use (none exists today): typecheck, lint, test, build, docker build.
|
||||||
|
- packages/ directory created empty (no package yet; YAGNI).
|
||||||
|
Tests: full suite green from apps/app; docker image builds and serves / and /pathology-editor.html.
|
||||||
|
Manual validation: pnpm dev from root; open /, /new, /editor, /svg-editor, /editors, /pathology-editor.html; export a PDF; docker compose up --build and repeat on :8080.
|
||||||
|
Definition of Done: identical behaviour, same test count, CI green on the branch, DEPLOY.md paths updated.
|
||||||
|
Risks: path alias and Vite public dir regressions (caught by the e2e manual script); git history of moved files (use git mv in one commit).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 3
|
||||||
|
Name: Supabase foundation
|
||||||
|
Objective: Local Supabase stack, migration system, test harness, generated types, first protected table, audit log skeleton.
|
||||||
|
Dependencies: Step 2. Deployment target depends on OPEN_QUESTIONS Q2 (local work is unaffected).
|
||||||
|
Changes expected:
|
||||||
|
- supabase/config.toml, supabase/migrations/0001_foundation.sql: schemas private/audit,
|
||||||
|
updated_at trigger, private.log_event(), audit.audit_logs (append-only), profiles table
|
||||||
|
+ auth.users trigger + RLS (own row), private.is_platform_owner/admin/moderator/support
|
||||||
|
reading profile_roles (table created here, writes only via RPC stub).
|
||||||
|
- supabase/tests/: pgTAP harness, tests for profiles RLS and role helpers.
|
||||||
|
- packages/supabase: browser client factory, generated database.types.ts, CI diff check.
|
||||||
|
- packages/config: runtime config keys supabaseUrl/anonKey (env.js + entrypoint.sh extended).
|
||||||
|
- CI: supabase start, db reset, test db, gen types diff.
|
||||||
|
- .env.example: placeholders only.
|
||||||
|
Tests: pgTAP green; a vitest integration test signs in a seeded user and reads only their profile.
|
||||||
|
Manual validation: supabase start; create two users in Studio; verify each sees one profile row via the REST API with their JWT; anon sees none.
|
||||||
|
Definition of Done: "authenticated request can hit a protected table safely" (architecture Sprint 0 exit criteria); docs/development/BACKEND_ARCHITECTURE.md conventions applied.
|
||||||
|
Risks: self-hosted vs managed decision (Q2) changes the deploy runbook, not the code; pgTAP learning curve; Supabase CLI version pinned in package.json devDependencies.
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 4 (∥ Step 3)
|
||||||
|
Name: Canonical anatomical sheet model and legacy importer
|
||||||
|
Objective: Define the AnatomicalSheetDocument (pure Zod) and build the deterministic importer that turns the two equine SVGs + catalog into a seed document with stable ids and explicit mappings.
|
||||||
|
Dependencies: Step 1 (mapping table and special-case tests), Step 2 (workspace)
|
||||||
|
Changes expected:
|
||||||
|
- packages/domain: sheet document schema (schema_version, species_id, vertebral_config as ordered region list, views, annotations, categories, finding_tree reusing findings.ts, annotation_finding_map, scope_disclaimer, legacy_id_map), species schema.
|
||||||
|
- packages/anatomy: svgConvention.ts and labels.ts moved; legacy/ importer (uses zoneMatch and regionFromLabel once); renderer helper that emits data-anno-* from a document; spineZones generalised to region codes (old label-based function kept in legacy/).
|
||||||
|
- supabase/seed/anatomical-sheets/equine/v1/{document.json, legacy-id-map.json, assets/, IMPORT-REPORT.md} generated by a script (pnpm seed:equine), checksums of source SVGs recorded.
|
||||||
|
- Decisions on OPEN_QUESTIONS Q5 and Q9 applied in the importer (defaults: two assets; ssb-dysfunctions under sphenoid renamed with a logged note).
|
||||||
|
- apps/app untouched (still uses the registry).
|
||||||
|
Tests: importer reproduces the Step 1 mapping table exactly; every audit 07 special case has a test; document Zod rejects duplicate annotation ids, dangling view parents, mapping to unknown zones, published schema mismatches; idempotency (running twice yields byte-identical output).
|
||||||
|
Manual validation: open IMPORT-REPORT.md: 27 annotations, 26 mapped, 1 detail trigger, 5 spine zones with region codes C/T/L/S/Cd, 9 bilateral, 2 views; diff document.json against docs/faunosteo-audit/anatomical-sheet-example.json for sanity.
|
||||||
|
Definition of Done: seed document committed; packages/domain and packages/anatomy have no DOM import outside anatomy/dom/*; no runtime code imports zoneMatch outside legacy/.
|
||||||
|
Risks: subtle divergences between parser and importer on the detail trigger (no name, category kept); Horse_head.svg id space overlaps if a future file reuses ids (mitigated by per-view id scoping in the importer).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 5
|
||||||
|
Name: Application on the canonical sheet (local, no backend)
|
||||||
|
Objective: Make apps/app run on the seed document instead of the manifest/registry, with report document v3 and the zone-interaction service extracted. Still single-user, still sessionStorage.
|
||||||
|
Dependencies: Step 4
|
||||||
|
Changes expected:
|
||||||
|
- packages/domain: report document v3 (zones by annotationId+viewId, region codes, anatomicalSheetVersionId, identity snapshots, localAnnotations, locale of last export); v2ToV3 adapter using legacy-id-map; v2 schema retained as input.
|
||||||
|
- apps/app: SheetProvider interface with a bundled implementation over the seed; AnatomyCanvas/DetailModal on views; ObservationCard uses annotation_finding_map (matcher import removed); VertebraPicker tabs from vertebral_config; services/zoneInteraction.ts extracted from EditorRoute and unit-tested; reportStore split (pure actions + sessionStoragePersistence adapter) and holding v3; draft migration on load; registry.ts and species/equine/* deleted (SvgEditorRoute and AnimalForm read SheetProvider).
|
||||||
|
- PDF still works through a thin shim (labels from the document) until Step 6; no public/species fetch remains except the SVG asset bytes served from public/ until Step 13.
|
||||||
|
Tests: Step 1 characterisation tests pass unchanged or are migrated one-to-one with the replacing test named; v2ToV3 on golden fixtures; zoneInteraction service tests (all branches); no-import-of-zoneMatch lint test.
|
||||||
|
Manual validation: full manual flow (new report → zones of each kind → findings → PDF export → import) in FR and EN; refresh keeps the draft; a v2 draft left in sessionStorage is migrated.
|
||||||
|
Definition of Done: identical user-visible behaviour; registry gone; EditorRoute under 300 lines; CLAUDE.md folder map updated.
|
||||||
|
Risks: largest refactor of the app core; mitigated by Step 1 tests and by keeping the shim for PDF; v2 drafts in the wild (none expected).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 6
|
||||||
|
Name: PDF pipeline v3 (snapshot-based export, attachment v3, import)
|
||||||
|
Objective: Export from (document, sheet snapshot, branding, locale) with no fetch; attachment carries sheet reference and snapshot; import v3 and v2.
|
||||||
|
Dependencies: Step 5. Gate: explicit confirmation before editing pdf/import.ts and pdf/attachment.ts (CLAUDE.md).
|
||||||
|
Changes expected:
|
||||||
|
- packages/pdf: export/import/attachment/render moved; new signature; Branding object replaces hard-coded logos/URLs; Rasterizer interface with the browser implementation; attachment v3 format documented in docs/PDF-FORMAT.md (written for real).
|
||||||
|
- apps/app: export passes the snapshot from SheetProvider; import detects v2 vs v3 and routes v2 through v2ToV3.
|
||||||
|
Tests: golden text extraction for the full fixture (FR/EN); attachment v3 roundtrip; render with a snapshot only (no provider) proves rule 8 feasibility; v2 PDF from Step 1 fixture imports and re-exports as v3; vet marker still WinAnsi-safe.
|
||||||
|
Manual validation: export the demo report, open in two viewers, check pages, open the attachment list and confirm osteo-report*.json; import the file on a fresh tab; import a v2 PDF produced before Step 5.
|
||||||
|
Definition of Done: no fetch in packages/pdf; docs/PDF-FORMAT.md complete; size of attachment < 250 KB for the equine demo.
|
||||||
|
Risks: snapshot size growth with future sheets (mitigate: snapshot subset = only views and annotations referenced + finding zones referenced); viewers that strip attachments (visible PDF remains the archive).
|
||||||
|
```
|
||||||
|
|
||||||
|
Milestone A (after Step 6): release 0.2.0 "canonical sheet + PDF v3", still a
|
||||||
|
local tool. Everything above has no backend and can ship to faunosteo.com
|
||||||
|
as-is.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 7
|
||||||
|
Name: Identity: Auth, profiles, roles, app shell
|
||||||
|
Objective: Login, email verification, profile, roles; the private app gains the /app shell and a query layer.
|
||||||
|
Dependencies: Step 3, Step 2
|
||||||
|
Changes expected:
|
||||||
|
- supabase: migrations for profile_roles RPCs (grant/revoke by owner/admin only), platform_invitations, MFA enforcement helper for admin roles; GoTrue config: email/password, OTP, Google, Apple (provider ids from env), phone (per OPEN_QUESTIONS Q7, may ship later).
|
||||||
|
- apps/app: /login, /app/* guarded routes, /app/dashboard (empty), /app/profile/edit; TanStack Query added (dependency declared); session handling; locale synced to profiles.locale; legacy routes still reachable and unauthenticated (local tool mode) until Step 14.
|
||||||
|
Tests: pgTAP for roles RPC (self-grant denied, admin grant audited); integration: sign-up → verify → login → profile update; component tests for forms.
|
||||||
|
Manual validation: create account, verify email (Inbucket locally), log in with Google (test credentials), edit profile, log out; confirm an unauthenticated user cannot read profiles via REST.
|
||||||
|
Definition of Done: architecture Sprint 1 identity part; audit_logs receives role changes.
|
||||||
|
Risks: Apple sign-in setup cost; phone provider pending (Q7).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 8
|
||||||
|
Name: Files foundation (Storage)
|
||||||
|
Objective: Asset metadata table, private buckets, object key convention, signed URL RPC, storage.objects policies, SVG quarantine/sanitizer.
|
||||||
|
Dependencies: Step 7
|
||||||
|
Changes expected:
|
||||||
|
- supabase: assets table (+ sanitization_status), buckets created by migration, storage policies calling private helpers, RPC issue_signed_url(asset_id), Edge Function or SQL-only sanitizer for SVG (decision at the step: SQL cannot parse XML safely; prefer an Edge Function or the worker if Q2 rules out edge-runtime).
|
||||||
|
- packages/supabase: upload helper (client → bucket path from assets row).
|
||||||
|
- apps/app: avatar upload on the profile page as the first consumer.
|
||||||
|
Tests: pgTAP: a user cannot read another user's object; quarantined SVG unreadable by others; signed URL denied without access; unit tests for the sanitizer on hostile SVG fixtures (script, foreignObject, on*, javascript:, external use/href, CSS url()).
|
||||||
|
Manual validation: upload avatar; copy the object URL and open it logged out (denied); upload a hostile SVG as a sheet asset and verify it is rewritten.
|
||||||
|
Definition of Done: all eight buckets exist and are private; architecture §15.1–15.3 implemented.
|
||||||
|
Risks: direct-to-bucket uploads bypassing the assets row (mitigate: insert policy on storage.objects requires a matching assets row).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 9 (∥ Step 10)
|
||||||
|
Name: Professional verification
|
||||||
|
Objective: Verification workflow with documents, admin review, expiry.
|
||||||
|
Dependencies: Step 7, Step 8
|
||||||
|
Changes expected:
|
||||||
|
- supabase: professional_verifications, professional_documents, status RPCs (submit, review), expiry job (pg_cron or SQL function called by the future worker), audit events.
|
||||||
|
- apps/app: /app/profile/verification (submit SIRET, identifiers, upload RC Pro/C2V), /app/admin/verifications (review list, approve/reject with reason).
|
||||||
|
Tests: pgTAP for transitions (only admins review; user cannot set verified), document expiry moves status to expired; integration for the full flow.
|
||||||
|
Manual validation: submit as practitioner, review as admin, see the badge; backdate a document expiry and run the job.
|
||||||
|
Definition of Done: unverified accounts blocked from the capabilities decided in OPEN_QUESTIONS C6.
|
||||||
|
Risks: legal acceptance criteria not final (documents list may change: keep document_type open text + CHECK).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 10 (∥ Step 9)
|
||||||
|
Name: Organizations (cabinets)
|
||||||
|
Objective: Organization creation, membership roles, personal vs organization context in the app.
|
||||||
|
Dependencies: Step 7
|
||||||
|
Changes expected:
|
||||||
|
- supabase: organizations, organization_members, RPCs add_member/remove_member/set_role, helpers is_org_member/manager/practitioner, seat exclusivity constraint (one cabinet-paid seat per user, enforced at Step 11 with billing_source).
|
||||||
|
- apps/app: /app/settings/organization, member management, context switcher (personal / cabinet) stored in session.
|
||||||
|
Tests: pgTAP: secretary cannot self-promote; non-member sees nothing; manager manages; integration: create cabinet, invite by email, accept.
|
||||||
|
Manual validation: two accounts, one cabinet, switch context, verify visibility of the other member's profile only.
|
||||||
|
Definition of Done: architecture Sprint 2 minus seats billing.
|
||||||
|
Risks: context leakage into later queries (every report/client query must take the context explicitly; enforce by a service-layer signature, not a global).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 11
|
||||||
|
Name: Entitlement engine skeleton (no Stripe)
|
||||||
|
Objective: plans, entitlement_grants, get_effective_entitlements(user), capability names; free launch plan by default; admin/invited/promo grants.
|
||||||
|
Dependencies: Step 7, Step 9, Step 10
|
||||||
|
Changes expected:
|
||||||
|
- supabase: plans (seeded: free_launch, individual_monthly, individual_yearly, cabinet_base placeholder), subscriptions and subscription_seats tables created empty (Stripe fills them at Step 23), entitlement_grants, function get_effective_entitlements, helper has_active_entitlement(uid, capability), capability catalogue documented (reports.write, reports.complete, reports.edit_after_free_window, community.publish_sheet, booking.manage, profile.public, sheet.private_visibility).
|
||||||
|
- apps/app: capabilities hook; UI hides what the user lacks (not a boundary).
|
||||||
|
Tests: pgTAP matrix: free user, verified free user, invited grant with expiry, admin role; expired grant yields nothing.
|
||||||
|
Manual validation: grant an invited entitlement to a user via admin RPC and watch capabilities change.
|
||||||
|
Definition of Done: no is_paid boolean anywhere; every later feature reads capabilities.
|
||||||
|
Risks: capability list drift (keep it as one SQL enum + one TS const checked by a test).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 12
|
||||||
|
Name: Clients and animals
|
||||||
|
Objective: Global client records, contacts, consents, access grants; animals with deceased status and files; species list.
|
||||||
|
Dependencies: Step 7, Step 8, Step 10, decisions on OPEN_QUESTIONS C4/C5/Q6
|
||||||
|
Changes expected:
|
||||||
|
- supabase: species, clients, client_contacts (normalized), client_consents, client_access_grants, client_relationships (practitioner/org ↔ client, with per-relationship notes), animals, animal_access_grants; helpers can_view_client/animal; candidate-match RPC returning only "a record may exist" without identifying the other relationship; consent recording with legal_text_version.
|
||||||
|
- apps/app: /app/clients list/detail, new client + contacts + consent capture, /app/animals/:animalId with photo and files, deceased flow, sharing request flow (secure email link; delivery stubbed until Step 19).
|
||||||
|
Tests: pgTAP: cross-practitioner isolation, grant expiry/revocation, org member access, candidate match leaks nothing; integration: create client/animal, share, revoke.
|
||||||
|
Manual validation: two practitioners; the second cannot see the first's client until a grant exists; revoke and verify.
|
||||||
|
Definition of Done: architecture Sprint 3; rule 1 (animal ≠ sheet) visible in the model (animals.species_id only).
|
||||||
|
Risks: the global-client design (C4) if confirmed as plain shared rows; GDPR consent texts not final (version column from day one).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 13 (∥ Steps 9–12)
|
||||||
|
Name: Anatomical sheets in the database and official equine seed
|
||||||
|
Objective: Sheet and version tables with immutability, SVG assets in Storage, seed of the official equine sheet v1, SheetProvider over Supabase, read-only sheet library in the app.
|
||||||
|
Dependencies: Step 3, Step 4, Step 8
|
||||||
|
Changes expected:
|
||||||
|
- supabase: anatomical_sheets, anatomical_sheet_versions (content_jsonb + schema CHECK), immutability trigger on published rows, version numbering RPC, deprecate RPC, GC function with the four preconditions (no report, no fork, no grant, no pending process) returning candidates only (deletion job at Step 18), helpers can_use_sheet/can_fork_sheet (creator-only for now), seed script uploading the two SVG assets and inserting v1 published.
|
||||||
|
- packages/supabase: typed accessors; apps/app: SheetProvider.supabase replaces the bundled seed in production builds (bundled kept for tests), /app/anatomy read-only list and preview.
|
||||||
|
Tests: pgTAP: UPDATE on published content raises; v2 numbering; GC preconditions each individually; non-creator cannot read a private sheet; integration: seed is idempotent and byte-faithful (checksums).
|
||||||
|
Manual validation: open /app/anatomy, see "Faunosteo / Cheval / officielle v1", preview both views, click zones (no report yet).
|
||||||
|
Definition of Done: rules 4–7 enforced in SQL; public/species/* no longer fetched by apps/app (nginx /species/ rule removed); SvgEditorRoute loads assets through signed URLs.
|
||||||
|
Risks: seed drift vs the committed document.json (CI compares); storage policy for public sheets to be widened at Step 18 only.
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 14
|
||||||
|
Name: Cloud reports
|
||||||
|
Objective: Reports persisted in PostgreSQL with autosave, revisions, numbering, completion, quota and free edit window; the local-only flow retired.
|
||||||
|
Dependencies: Step 5, Step 11, Step 12, Step 13
|
||||||
|
Changes expected:
|
||||||
|
- supabase: reports, report_revisions, practitioner_report_counters, RPCs create_report(animal, sheet_version, context), autosave_report(id, document, base_revision) returning revision no, checkpoint_revision(reason), complete_report (quota: 5 lifetime completed incl. deleted and imported; sets free_edit_until = +5 days for free plan), restore_revision, copy_previous_report, soft delete; helpers can_view_report/can_edit_report; RLS; indexes of architecture §32.
|
||||||
|
- apps/app: /app/dashboard (recent reports), /app/animals/:id → "new report" (choose sheet: official, own, followed later), /app/reports/:reportId editor on supabasePersistence, sync indicator, revision history + restore, completion dialog; routes /, /new, /editor removed; HomeRoute/NewReportRoute/practitionerCache deleted; PDF export uses profile/org branding.
|
||||||
|
Tests: pgTAP: numbering under two concurrent sessions, 6th completion denied on free, deleted completed still counts, edit after window denied, revisions created on checkpoints only, org-owned report visibility; integration: create → autosave → complete → reopen; unit: persistence contract shared with sessionStorage adapter.
|
||||||
|
Manual validation: full consultation flow with two accounts (personal and cabinet context); kill the network mid-edit and confirm the UI reports unsaved (offline handling itself is Step 16).
|
||||||
|
Definition of Done: architecture Sprint 4 except IndexedDB fallback; rules 3–4 visible (reports.anatomical_sheet_version_id NOT NULL FK).
|
||||||
|
Risks: autosave write volume (throttle 2 s + diff check); report document size with localAnnotations; migration of the sessionStorage draft of existing users (one-time import prompt).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 15
|
||||||
|
Name: PDF artifacts and cloud import
|
||||||
|
Objective: Store generated PDFs as report artifacts; import PDFs into the account through a server-validated path; render historical reports even if the sheet is gone.
|
||||||
|
Dependencies: Step 6, Step 14. Gate: confirmation before touching import/attachment code again.
|
||||||
|
Changes expected:
|
||||||
|
- supabase: report_pdf_artifacts (asset, locale, revision no, sha256), RPC import_report(attachment json, target animal) doing: version check, Zod validation server-side (plpgsql cannot run Zod → validate in an Edge Function or accept the attachment into a staging row and validate in the app with a server re-check of the invariants that matter: sheet version exists or snapshot-only version created, quota, ownership), snapshot-only version creation (read-only, status deprecated, flagged snapshot_only) when the referenced version no longer exists.
|
||||||
|
- apps/app: download/open artifact list on a report; import flow from the dashboard with quota preflight message and pricing redirect.
|
||||||
|
Tests: pgTAP: import beyond quota denied before any insert; snapshot-only version is never selectable for new reports; integration: export → delete sheet version (as admin) → import → PDF re-renders.
|
||||||
|
Manual validation: export, import into a second account (denied: wrong animal/owner), import into own account, check artifact list.
|
||||||
|
Definition of Done: rule 8 (historical restorable) demonstrated by test; PDF v2 import decision (Q1) applied.
|
||||||
|
Risks: Zod validation location (server vs client) must be decided per Q2; duplicate imports (idempotency by report id + sha256).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 16
|
||||||
|
Name: Offline safety for the report editor
|
||||||
|
Objective: IndexedDB outbox, visible sync state, retry, conflict revisions.
|
||||||
|
Dependencies: Step 14
|
||||||
|
Changes expected:
|
||||||
|
- apps/app: outboxPersistence wrapping supabasePersistence; sync state machine (synced / pending / offline / conflict); conflict → server keeps both as revisions (reason conflict) and the user picks.
|
||||||
|
- supabase: autosave_report rejects stale base_revision with a typed error; RPC resolve_conflict.
|
||||||
|
Tests: unit: outbox replay order, dedupe, stale base handling; Playwright: go offline, edit, go online, verify revision; two tabs editing the same report.
|
||||||
|
Manual validation: airplane mode scenario on a phone-sized viewport; reload during offline keeps edits.
|
||||||
|
Definition of Done: architecture §26 MVP target; no claim of "saved" before ack.
|
||||||
|
Risks: IndexedDB quota and private-mode browsers (fallback to memory with a warning).
|
||||||
|
```
|
||||||
|
|
||||||
|
Milestone B (after Step 16): release 0.5.0 "cloud reports", internal beta
|
||||||
|
with the practitioner client. Steps 17–18 can start before B.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 17 (∥ Steps 14–16)
|
||||||
|
Name: Anatomical sheet editor (merge of SVG editor and findings editor)
|
||||||
|
Objective: One structured editor on the canonical document: views, points/zones, categories, laterality, vertebral config, detail view creation, finding tree, annotation ↔ zone mapping, draft/publish/deprecate; personal sheets and official sheet maintenance; old tools deleted.
|
||||||
|
Dependencies: Step 13 (tables), Step 5 (document), decisions Q4/Q5/C8
|
||||||
|
Changes expected:
|
||||||
|
- apps/app: /app/anatomy (library: official, own), /app/anatomy/new, /app/anatomy/:sheetId/editor with SheetEditorStore (document + selection + mode + undo), canvas tools (select/point/polygon, drag, vertex edit), properties panel, categories panel, views panel (create detail view from zone: bbox + margin → view_box, child view), vertebral config panel, findings panel (tree edit from pathology-editor behaviour + validation), mapping panel (annotation → finding zone, suggestions from zoneMatch allowed here as a helper), publish flow (new immutable version), deprecate.
|
||||||
|
- Deleted in the same branch: SvgEditorRoute.tsx, svg-editor.css, svg_editor.* keys, EditorsRoute, public/pathology-editor.html, public/species/equine/pathologies.json, scripts/scaffold-species.mjs.
|
||||||
|
- supabase: draft uniqueness (one draft per sheet), publish RPC validating the document (mapping targets exist, no dangling views) and uploading assets, personal-sheet creation RPC.
|
||||||
|
Tests: one test per legacy operation (audit 03 §2, 05 §3.5) on the new model; detail-view geometry; publish creates v+1 and v1 reports still render (regression from Step 15 fixtures); pgTAP for draft uniqueness and publish validation.
|
||||||
|
Manual validation: fork-free scenario: create a personal sheet from scratch for a second species (dog, 3 points, 1 spine zone, 1 detail), publish, create a report on it, PDF; then edit the official sheet as admin, publish v2, open an old report (still v1).
|
||||||
|
Definition of Done: architecture Sprint 6 (except "promote manual point", added once Q6 is answered); REPOSITORY_MIGRATION_MAP REPLACE items for the editors closed.
|
||||||
|
Risks: largest UI step; split into sub-branches (canvas tools / panels / publish) each merged green behind a "beta" flag; feature parity gaps with the vanilla tool found late (mitigate with the reference tests first).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 18
|
||||||
|
Name: Community
|
||||||
|
Objective: Follow, public sheet discovery, use permission by follow, private sheet grants (use/fork), fork with provenance, reporting/moderation, sheet-version garbage collection.
|
||||||
|
Dependencies: Step 17, Step 10, Step 11 (community.publish_sheet, sheet.private_visibility)
|
||||||
|
Changes expected:
|
||||||
|
- supabase: practitioner_follows, sheet_usage_grants, community_reports, fork RPC (copies current version content into a new sheet, records based_on_*), helpers can_use_sheet/can_fork_sheet extended (public + follow, private + grant), public sheet discovery view, counters, GC job (pg_cron) deleting deprecated versions that pass the four preconditions and logging it.
|
||||||
|
- apps/app: /app/community (discover, follow), sheet library shows followed creators' sheets, grant management on private sheets, report/moderate UI (moderator role only).
|
||||||
|
Tests: pgTAP: unfollow revokes use for new reports but existing reports keep their version; private sheet invisible without grant; fork never mutates source; GC never deletes a referenced version; support role cannot moderate.
|
||||||
|
Manual validation: three accounts: creator publishes, follower uses, third cannot; creator makes it private, grants use to follower only; fork; deprecate v1 unused → GC removes it; deprecate a used version → kept.
|
||||||
|
Definition of Done: architecture Sprint 11; principle 10 (forks never mutate source) tested.
|
||||||
|
Risks: discovery performance (indexes §32); GC race with an in-flight report creation (take a row lock on the version during create_report).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 19
|
||||||
|
Name: Notifications foundation and worker
|
||||||
|
Objective: Email provider abstraction, PostgreSQL job queue, apps/worker, transactional templates FR/EN, secure links.
|
||||||
|
Dependencies: Step 7, Step 12 (document delivery to clients), decision Q7 (provider)
|
||||||
|
Changes expected:
|
||||||
|
- apps/worker: Node service, service-role client, job loop on private.jobs (SKIP LOCKED), EmailProvider interface + one implementation, retry/backoff, no clinical data in logs.
|
||||||
|
- supabase: private.jobs, email delivery log, secure_links (token hash, purpose, expiry).
|
||||||
|
- packages/i18n split (dictionaries without React) for templates.
|
||||||
|
- Docker: worker service in compose.
|
||||||
|
Tests: unit: queue semantics, template rendering; integration: enqueue → worker sends to Inbucket; secure link single-use and expiry.
|
||||||
|
Manual validation: trigger "send report to owner" and receive the secure link locally.
|
||||||
|
Definition of Done: first job that is not SQL runs in the worker; architecture §22.3–22.4.
|
||||||
|
Risks: provider deliverability (SPF/DKIM at DNS); worker single instance (acceptable at launch).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 20
|
||||||
|
Name: Agenda core
|
||||||
|
Objective: Services, locations, availability rules/exceptions, appointments with status machine, server-authoritative booking with expiry and one-pending-per-client, manual creation, cancellation/reschedule, intake forms.
|
||||||
|
Dependencies: Step 12, Step 19, Step 11 (booking.manage)
|
||||||
|
Changes expected:
|
||||||
|
- supabase: service_types, locations, availability_rules, availability_exceptions, appointments, intake_forms/questions/answers, RPCs request_booking (row lock on practitioner-day, one pending per client), confirm/reject/cancel/reschedule, expiry function (48h / 24h if <72h / 1h if <25h) run by pg_cron, availability RPC (server-side evaluation; travel buffers as fixed minutes until Step 21).
|
||||||
|
- apps/app: /app/calendar (week view), services/locations settings, manual appointment, intake form builder (default templates per species).
|
||||||
|
Tests: pgTAP: double request on the same slot (one wins), second pending request by the same client denied, expiry rules at each boundary, status transitions; unit: expiry rule mirror in TS; integration: full booking lifecycle.
|
||||||
|
Manual validation: book as a client via a test page (public UI comes at Step 22), confirm as practitioner, reminder enqueued (Step 19).
|
||||||
|
Definition of Done: architecture Sprint 8; principle 13 (race-safe) tested.
|
||||||
|
Risks: timezone handling (store timestamptz, practitioner tz on profile); calendar UI effort (consider a maintained library, declared at the step).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 21
|
||||||
|
Name: Travel engine and external calendars
|
||||||
|
Objective: RoutingProvider abstraction with cache, travel before/after, return-to-base, per-appointment override, Google two-way sync, Apple ICS, conflict alerts.
|
||||||
|
Dependencies: Step 20, Step 19 (worker, alerts)
|
||||||
|
Changes expected:
|
||||||
|
- supabase: travel_profiles, travel_pricing_rules, route_cache, external_calendar_connections (encrypted credentials, server only), external_calendar_events, availability RPC extended with travel.
|
||||||
|
- apps/worker: routing provider adapter (one provider chosen after evaluation; interface first), calendar sync jobs, conflict detection.
|
||||||
|
- Edge Function or worker endpoint for Google OAuth callback.
|
||||||
|
Tests: unit: engine with a mocked provider (previous location → travel → appointment → travel → next); pgTAP: external events block slots, titles never exposed; integration: ICS feed import.
|
||||||
|
Manual validation: two appointments 30 km apart; the availability RPC refuses the gap; connect a Google test calendar and see the block.
|
||||||
|
Definition of Done: architecture Sprint 9; no provider name in business logic.
|
||||||
|
Risks: provider cost/quota; refresh token storage (pgsodium or app-level encryption, decided at the step).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 22
|
||||||
|
Name: Public web and booking widget
|
||||||
|
Objective: apps/public-web with landing, practitioner public profile, search, SEO; booking widget (iframe + token).
|
||||||
|
Dependencies: Step 7, Step 9, Step 20, decision Q8 (framework)
|
||||||
|
Changes expected:
|
||||||
|
- supabase: public_practitioner_profiles, public views/RPCs (approved columns only), booking_widget_tokens, public booking RPCs rate-limited.
|
||||||
|
- apps/public-web: SSR pages /, /osteopathe/<slug>, /osteopathes-animaliers/<region|city|species>, sitemap, metadata; booking UI used both on the profile and inside the widget iframe (postMessage height/theme).
|
||||||
|
- Docker: public-web service; nginx/proxy routes.
|
||||||
|
Tests: pgTAP: anon sees only published profiles and approved columns, never clients/animals/reports; e2e: book from the public page; widget on a static test site.
|
||||||
|
Manual validation: publish a profile, open it logged out, book; embed the widget script in a local HTML page; revoke the token.
|
||||||
|
Definition of Done: architecture Sprint 10; SEO checks (/seo, /web-validate) pass on the public pages.
|
||||||
|
Risks: SEO data leak via views (allow-list columns, tested); framework choice (Q8).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 23
|
||||||
|
Name: Billing (Stripe) and referral
|
||||||
|
Objective: Stripe customers/subscriptions for individual monthly/yearly, entitlement engine fed by webhooks, billing history, cabinet seat groundwork, referral rewards with anti-fraud prerequisites.
|
||||||
|
Dependencies: Step 11, Step 10, Step 7 (verified email + phone for referral), Step 19 (emails)
|
||||||
|
Changes expected:
|
||||||
|
- supabase: subscriptions filled by webhook, subscription_seats, referrals, webhook idempotency table, invoice links; get_effective_entitlements covers active subscriptions and referral months.
|
||||||
|
- Edge Function stripe-webhook (signature check, idempotent); checkout session creation RPC/Edge.
|
||||||
|
- apps/app: /app/billing (plan, invoices, cancel at period end), pricing page redirect from quota blocks, referral code and status.
|
||||||
|
Tests: pgTAP: entitlement with active/cancelled/past-due subscription; referral cap 5/year; reward only after referred becomes paying; unit: webhook handler idempotency; integration with Stripe test clocks.
|
||||||
|
Manual validation: subscribe in test mode, see capability change, cancel, hit period end with a test clock.
|
||||||
|
Definition of Done: architecture Sprint 12; principle 12 (limits server-side) complete.
|
||||||
|
Risks: Stripe tax/TTC handling (Stripe Tax decision); seat pricing not fixed (groundwork only).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 24
|
||||||
|
Name: Import framework
|
||||||
|
Objective: Staging model, adapters (generic CSV/XLSX/JSON/ZIP, Faunosteo PDF v2/v3, Animalib/Kiwi when samples exist), read-only preflight, mapping review, duplicate candidates, quota check, atomic commit, "Données importées".
|
||||||
|
Dependencies: Step 15 (PDF import), Step 12, Step 11, Step 19 (long imports in worker)
|
||||||
|
Changes expected:
|
||||||
|
- supabase: import_jobs, import_files, import_raw_records, import_mappings, import_errors, import_unmapped_data; commit RPC in one transaction; quota preflight.
|
||||||
|
- apps/worker: ImportAdapter interface (detect/inspect/map/validate/transform/commit), generic adapters; vendor adapters behind feature flags until samples are obtained.
|
||||||
|
- apps/app: /app/settings/import wizard (upload → preview → duplicates → confirm), "Données importées" panel on client/animal.
|
||||||
|
Tests: adapters on fixture files; pgTAP: commit is atomic (20 reports on a free account roll back entirely); duplicates never auto-merged; traceability of every transformed field.
|
||||||
|
Manual validation: import a CSV with a duplicate client; confirm the review; check unmapped data is visible.
|
||||||
|
Definition of Done: architecture Sprint 13 minus vendor adapters pending samples.
|
||||||
|
Risks: vendor formats unknown (do not guess; adapters wait for samples).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 25
|
||||||
|
Name: Administration, audit and legal documents
|
||||||
|
Objective: Admin console (verification review already exists), audit log viewer, impersonation with banner and expiry, moderation queue UI, legal document versions and acceptance, admin MFA mandatory.
|
||||||
|
Dependencies: Step 7, Step 9, Step 18, Step 23
|
||||||
|
Changes expected:
|
||||||
|
- supabase: impersonation_sessions RPC (short-lived, audited), legal_documents + acceptances, MFA requirement helper enforced on admin tables.
|
||||||
|
- apps/app: /app/admin/* (users, roles, verifications, moderation, audit, entitlement overrides).
|
||||||
|
Tests: pgTAP: impersonation expires and is logged; admin without MFA denied; acceptance versioning; moderation role matrix.
|
||||||
|
Manual validation: impersonate a test user, see the banner, act, check the audit entry.
|
||||||
|
Definition of Done: architecture §17.5, §29 complete.
|
||||||
|
Risks: scope creep of the admin UI (minimum needed by support).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 26
|
||||||
|
Name: Data lifecycle: export, deletion, archive
|
||||||
|
Objective: Account data export, deletion workflow with hot retention, archive package to S3-compatible storage, sheet-version GC in production mode, restoration from archive.
|
||||||
|
Dependencies: Step 19 (worker), Step 23 (subscription states), Step 15 (artifacts)
|
||||||
|
Changes expected:
|
||||||
|
- apps/worker: export job (JSON + files manifest + checksums), archive job (lifecycle rules, no Object Lock), restore job; supabase: account_lifecycle states (active, restricted, archived, deleted), minimal archive pointer.
|
||||||
|
- apps/app: data export request, account deletion request.
|
||||||
|
Tests: unit: manifest/checksum; integration: export → delete → restore on staging; GC and archive never delete a version referenced by an archived report before its legal retention.
|
||||||
|
Manual validation: run the full cycle on a test account with artifacts.
|
||||||
|
Definition of Done: architecture §16; rule 8 at account level.
|
||||||
|
Risks: legal retention durations not final (parameters, not code).
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 27
|
||||||
|
Name: Production hardening and first-cohort release
|
||||||
|
Objective: Full RLS and storage audit, cross-tenant scenarios, security headers/CSP, rate limiting, backup/restore rehearsal, monitoring, dependency audit, performance checks with realistic seed, legal validation checklist.
|
||||||
|
Dependencies: all previous steps
|
||||||
|
Changes expected:
|
||||||
|
- supabase/tests: full RLS matrix generated from the table list; cross-tenant scenarios of architecture Prompt 10 as e2e; EXPLAIN ANALYZE on §32 indexes with a 10k-report seed.
|
||||||
|
- nginx/proxy: CSP, HSTS, frame-ancestors for the widget origin list; rate limits on public RPCs.
|
||||||
|
- ops: backup verification job, monitoring/alerting, runbooks (deploy, restore, rotate keys).
|
||||||
|
- DEPLOY.md rewritten for the full stack.
|
||||||
|
Tests: everything green; audit findings each with severity, scenario, fix and regression test (no blind fixes).
|
||||||
|
Manual validation: restore the production backup on staging; penetration checklist walked by a second person.
|
||||||
|
Definition of Done: architecture §38 Definition of Done satisfied except items that are legal (tracked separately); release 1.0.0.
|
||||||
|
Risks: findings reopening earlier steps (budget time for one iteration).
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. Dependency graph
|
||||||
|
|
||||||
|
```text
|
||||||
|
Step 0 ─▶ Step 1 ─▶ Step 2 ─┬─▶ Step 3 (Supabase foundation) ─┬─▶ Step 7 (Identity) ─┬─▶ Step 8 (Files) ─┬─▶ Step 9 (Verification) ─┐
|
||||||
|
│ │ ├─▶ Step 10 (Orgs) ─┼──────────────────────────┼─▶ Step 11 (Entitlements)
|
||||||
|
│ │ │ │ │
|
||||||
|
└─▶ Step 4 (Sheet model, ∥ 3) ─▶ Step 5 (App on sheet) ─▶ Step 6 (PDF v3) └─▶ Step 12 (Clients/Animals) ◀┘
|
||||||
|
│ │
|
||||||
|
└────────── Step 13 (Sheets in DB, needs 3+4+8) ──────┤
|
||||||
|
▼
|
||||||
|
Step 14 (Cloud reports: 5+11+12+13) ─▶ Step 15 (PDF artifacts: 6+14) ─▶ Step 16 (Offline)
|
||||||
|
│
|
||||||
|
Step 17 (Editor merge: 13+5, ∥ 14–16) ─▶ Step 18 (Community: 17+10+11) │
|
||||||
|
│
|
||||||
|
Step 19 (Notifications/worker: 7+12) ─▶ Step 20 (Agenda: 12+19+11) ─▶ Step 21 (Travel/calendars) ─▶ Step 22 (Public web + widget: 7+9+20)
|
||||||
|
│
|
||||||
|
Step 23 (Billing: 11+10+19) ─▶ Step 24 (Imports: 15+12+11+19) ─▶ Step 25 (Admin: 7+9+18+23) ─▶ Step 26 (Lifecycle: 19+23+15) ─▶ Step 27 (Hardening)
|
||||||
|
```
|
||||||
|
|
||||||
|
Per-step table (depends on / unblocks / main risk):
|
||||||
|
|
||||||
|
| Step | Depends on | Unblocks | Main risk |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 Characterisation tests | 0 | 2, 4, 5 | encoding bugs as expected behaviour |
|
||||||
|
| 2 Workspace | 1 | 3, 4 | path regressions |
|
||||||
|
| 3 Supabase foundation | 2 | 7, 13 | hosting decision (Q2) |
|
||||||
|
| 4 Sheet model + importer | 1, 2 | 5, 13 | special cases missed (audit 07) |
|
||||||
|
| 5 App on sheet, document v3 | 4 | 6, 14, 17 | core refactor size |
|
||||||
|
| 6 PDF v3 | 5 | 15 | attachment size, import gate |
|
||||||
|
| 7 Identity | 3 | 8, 9, 10, 11, 12, 19, 22 | OAuth/phone providers |
|
||||||
|
| 8 Files | 7 | 9, 12, 13 | bypassing assets row |
|
||||||
|
| 9 Verification | 7, 8 | 11, 22, 25 | legal criteria |
|
||||||
|
| 10 Organizations | 7 | 11, 12, 18, 23 | context leakage |
|
||||||
|
| 11 Entitlements | 7, 9, 10 | 14, 18, 20, 23, 24 | capability drift |
|
||||||
|
| 12 Clients/Animals | 7, 8, 10 | 14, 19, 20, 24 | global client design (C4) |
|
||||||
|
| 13 Sheets in DB | 3, 4, 8 | 14, 17 | seed drift |
|
||||||
|
| 14 Cloud reports | 5, 11, 12, 13 | 15, 16, 24 | autosave volume, quota correctness |
|
||||||
|
| 15 PDF artifacts + import | 6, 14 | 24, 26 | server validation location |
|
||||||
|
| 16 Offline | 14 | B milestone | IndexedDB edge cases |
|
||||||
|
| 17 Editor merge | 13, 5 | 18 | parity with vanilla tools |
|
||||||
|
| 18 Community | 17, 10, 11 | 22 (counts), 25 | GC race |
|
||||||
|
| 19 Notifications/worker | 7, 12 | 20, 21, 23, 24, 26 | deliverability |
|
||||||
|
| 20 Agenda | 12, 19, 11 | 21, 22 | timezones, race |
|
||||||
|
| 21 Travel/calendars | 20, 19 | 22 | provider cost |
|
||||||
|
| 22 Public web + widget | 7, 9, 20 | 27 | SEO data leak |
|
||||||
|
| 23 Billing | 11, 10, 7, 19 | 24, 25, 26 | tax, idempotency |
|
||||||
|
| 24 Imports | 15, 12, 11, 19 | 27 | unknown vendor formats |
|
||||||
|
| 25 Admin | 7, 9, 18, 23 | 27 | scope |
|
||||||
|
| 26 Lifecycle | 19, 23, 15 | 27 | legal durations |
|
||||||
|
| 27 Hardening | all | 1.0.0 | reopening earlier steps |
|
||||||
|
|
||||||
|
Parallel tracks a single developer can interleave: (A) 3 → 7 → 8 → 9/10 → 11
|
||||||
|
→ 12; (B) 4 → 5 → 6; (C) 13 → 17 → 18 once A reaches 8. Track B has no
|
||||||
|
backend and can ship to the live site at any time (Milestone A).
|
||||||
|
|
||||||
|
## 5. Migration difficulty ranking (brief §8)
|
||||||
|
|
||||||
|
| Class | Migration | Why |
|
||||||
|
|---|---|---|
|
||||||
|
| CRITICAL | Anatomical sheet model + legacy importer (Steps 4, 13) | Replaces the implicit sheet (four sources, no id, no version, fuzzy link) with the object every report references; a mistake here is baked into immutable v1 and into every report's annotation ids. |
|
||||||
|
| CRITICAL | Report document v3 + persistence split (Steps 5, 14) | Changes the identity space of zones (`boneId` → `annotationId`), the region model, and the store; this is the clinical core and had zero tests on its click chain. |
|
||||||
|
| CRITICAL | RLS and helpers (Steps 3, 7–14) | The only security boundary of a multi-tenant clinical database; a wrong policy is a data breach, not a bug. |
|
||||||
|
| CRITICAL | Client/animal permissions (Step 12) | Global client records across practitioners plus consent and sharing; the design itself is flagged (C4). |
|
||||||
|
| CRITICAL | PDF portability (Steps 6, 15) | The PDF is the long-term archive and the import path handles user data; rule 8 depends on it. |
|
||||||
|
| IMPORTANT | Editor merge (Step 17) | Large UI with two untested legacy references, but no data risk: the document model and tables already exist. |
|
||||||
|
| IMPORTANT | Agenda + travel + calendars (Steps 20–21) | Server-authoritative engine with concurrency rules; new domain, no legacy. |
|
||||||
|
| IMPORTANT | Community (Step 18) | Permission model on sheets and garbage collection with four preconditions. |
|
||||||
|
| IMPORTANT | Billing + entitlements (Steps 11, 23) | Server-side limits; the skeleton must exist early or quota logic gets re-implemented. |
|
||||||
|
| IMPORTANT | Offline (Step 16) | Conflict semantics; limited scope by design. |
|
||||||
|
| IMPORTANT | Imports (Step 24) | Atomicity and quota; vendor formats unknown. |
|
||||||
|
| LOW | Workspace move (Step 2), i18n package, UI package, public site (Step 22), notifications (Step 19), admin UI (Step 25) | Mechanical or greenfield with clear contracts. |
|
||||||
|
|
||||||
|
## 6. Mapping to the architecture's sprints (§35)
|
||||||
|
|
||||||
|
| Architecture sprint | Plan steps |
|
||||||
|
|---|---|
|
||||||
|
| 0 Foundation | 2, 3 (+ 1 as prerequisite) |
|
||||||
|
| 1 Auth/profile/verification | 7, 9 |
|
||||||
|
| 2 Organizations | 10 (+ seats in 23) |
|
||||||
|
| 3 Clients/animals | 12 (+ files 8) |
|
||||||
|
| 4 Cloud reports | 14, 16 (+ entitlements 11) |
|
||||||
|
| 5 Sheet data model | 4, 13 |
|
||||||
|
| 6 Editor merge | 17 |
|
||||||
|
| 7 PDF + portability | 6, 15 |
|
||||||
|
| 8 Agenda core | 20 |
|
||||||
|
| 9 Travel + calendars | 21 |
|
||||||
|
| 10 Public profile + widget | 22 |
|
||||||
|
| 11 Community | 18 |
|
||||||
|
| 12 Billing + referral | 23 (+ 11) |
|
||||||
|
| 13 Migration engine | 24 |
|
||||||
|
| 14 Hardening | 25, 26, 27 |
|
||||||
|
|
||||||
|
The plan pulls the sheet model (sprint 5) and PDF (sprint 7) *before* cloud
|
||||||
|
reports because a cloud report must reference a sheet version from its first
|
||||||
|
row, and pulls entitlements before reports because the quota is part of
|
||||||
|
completion.
|
||||||
|
|
||||||
|
## 7. Branches (gitflow, no branch created in Step 0)
|
||||||
|
|
||||||
|
| Step | Branch | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| 0 | `chore/step-00-implementation-plan` | docs only (`.claude/**` exempt rule does not cover `docs/`, so a chore branch) |
|
||||||
|
| 1 | `feature/step-01-characterisation-tests` | |
|
||||||
|
| 2 | `feature/step-02-monorepo-workspace` | one `git mv` commit, one config commit |
|
||||||
|
| 3 | `feature/step-03-supabase-foundation` | |
|
||||||
|
| 4 | `feature/step-04-sheet-model-importer` | |
|
||||||
|
| 5 | `feature/step-05-app-on-sheet-v3` | may split: `-a-zone-service`, `-b-document-v3`, `-c-sheet-provider` |
|
||||||
|
| 6 | `feature/step-06-pdf-v3` | confirmation gate on import/attachment |
|
||||||
|
| 7–13 | `feature/step-07-identity` … `feature/step-13-sheets-db-seed` | |
|
||||||
|
| 14 | `feature/step-14-cloud-reports` | sub-branches: `-a-tables-rpc`, `-b-editor-persistence`, `-c-retire-local-flow` |
|
||||||
|
| 15–16 | `feature/step-15-pdf-artifacts-import`, `feature/step-16-offline-outbox` | |
|
||||||
|
| 17 | `feature/step-17-sheet-editor` | sub-branches `-a-canvas`, `-b-panels`, `-c-publish-delete-legacy` |
|
||||||
|
| 18–26 | `feature/step-18-community` … `feature/step-26-data-lifecycle` | |
|
||||||
|
| 27 | `release/1.0.0` after `feature/step-27-hardening` | |
|
||||||
|
| Milestones | `release/0.2.0` after Step 6, `release/0.5.0` after Step 16 | cut via `/release-candidate` |
|
||||||
|
| Fixes | `bugfix/*` off develop; `hotfix/*` only for the live site | |
|
||||||
|
|
||||||
|
Every branch is pushed at `start` and on every commit (gitflow hooks); `finish`
|
||||||
|
only on explicit human signal.
|
||||||
|
|
||||||
|
## 8. Risk register (brief §11)
|
||||||
|
|
||||||
|
| Risk | Class | Where | Mitigation |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Data loss during persistence switch (sessionStorage → Supabase) | CRITICAL | Step 14 | one-time draft import prompt; drafts never deleted client-side until server ack; revisions from day one |
|
||||||
|
| Identifier model change (`data-anno-id` → stable annotation ids; `boneId` → `annotationId`) | CRITICAL | Steps 4, 5 | deterministic importer + committed legacy id map + Step 1 mapping table as oracle; v2 adapter tested on golden fixtures |
|
||||||
|
| SVG assets: duplicated head file, opaque ids, degraded slugs, trigger without category, client-only sanitizer | CRITICAL | Steps 4, 8, 13, 17 | importer runs only on committed files; slugs preserved verbatim; server sanitizer + quarantine; per-view id scoping |
|
||||||
|
| Finding mappings: fuzzy match at runtime, duplicate node ids across zones, `ssb-dysfunctions` anomaly | CRITICAL | Steps 4, 5 | explicit `annotation_finding_map` validated on publish; paths anchored at zone; anomaly fixed before v1 (Q9) |
|
||||||
|
| Historical reports unreadable after sheet changes | CRITICAL | Steps 13, 15 | immutable versions, FK from report, snapshot in PDF, snapshot-only version on import, GC preconditions tested |
|
||||||
|
| PDF: attachment format change, import of user data, browser-only rasteriser | CRITICAL | Steps 6, 15 | v3 format documented, v2 adapter, confirmation gate, Rasterizer interface |
|
||||||
|
| RLS mistakes | CRITICAL | every DB step | helper + pgTAP per table, full matrix at Step 27, no `USING (true)` for authenticated on core tables |
|
||||||
|
| Multi-tenant leakage via organization context | CRITICAL | Steps 10, 14 | context passed explicitly to services; org-scoped tests |
|
||||||
|
| Storage: direct uploads bypass metadata; signed URL leakage | IMPORTANT | Step 8 | insert policy requires assets row; short-lived signed URLs |
|
||||||
|
| Offline conflicts overwriting server data | IMPORTANT | Step 16 | stale base rejection, conflict revisions, user choice |
|
||||||
|
| Agenda race conditions and expiry errors | IMPORTANT | Step 20 | row locks, single SQL expiry function, boundary tests |
|
||||||
|
| Route/travel provider lock-in or cost | IMPORTANT | Step 21 | `RoutingProvider` interface, cache, provider chosen after evaluation |
|
||||||
|
| Community: GC deleting a referenced version; private sheet exposure | IMPORTANT | Step 18 | preconditions in one function with tests; grants evaluated in helpers |
|
||||||
|
| Billing: webhook replay, entitlement drift | IMPORTANT | Steps 11, 23 | idempotency table, single `get_effective_entitlements` |
|
||||||
|
| Imports: partial commits on free accounts, silent merges | IMPORTANT | Step 24 | one transaction, duplicate review mandatory |
|
||||||
|
| Hosting under-provisioned for self-hosted Supabase | IMPORTANT | Step 3 deploy | Q2 before deploying; local work unaffected |
|
||||||
|
| Phone/email providers undecided | IMPORTANT | Steps 7, 19 | interfaces first; email-only verification until Q7 |
|
||||||
|
| Vocabulary collision (Observation) in new UI strings | LOW | all UI steps | fixed in C7 |
|
||||||
|
| Workspace move regressions | LOW | Step 2 | manual script + CI |
|
||||||
|
| Public site framework choice | LOW | Step 22 | Q8, isolated app |
|
||||||
|
|
||||||
|
## 9. Deliverable checklist per step (applies to every step)
|
||||||
|
|
||||||
|
1. Plan line in `.claude/tasks/TODO.md` with sub-tasks checked as they land.
|
||||||
|
2. Branch per §7; commits in Conventional Commits with the allowed scopes
|
||||||
|
(`schema`, `store`, `anatomy`, `pdf`, `editor`, `home`, `new`, `ui`,
|
||||||
|
`config`, `species`, `i18n`, `docker`, `docs`, `tests`, `chore`; new scopes
|
||||||
|
`supabase`, `app`, `worker`, `public-web`, `domain` to be added to
|
||||||
|
CLAUDE.md at Step 2).
|
||||||
|
3. Tests listed in the step green; `TEST_STRATEGY.md` §3 row satisfied.
|
||||||
|
4. Manual validation script executed and its result written in the PR / TODO note.
|
||||||
|
5. Docs touched: CLAUDE.md folder map, `docs/development/*` if the plan changed, domain docs.
|
||||||
|
6. Registries: decisions (BDR) for each visible design choice, learnings, blockers.
|
||||||
|
7. Definition of Done met; otherwise the step is not merged.
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
# Migration strategy: current SPA → SaaS architecture
|
||||||
|
|
||||||
|
Status: Step 0 deliverable, 2026-10-08. Describes *how* the existing code
|
||||||
|
evolves without a big-bang rewrite. The step-by-step schedule is in
|
||||||
|
`IMPLEMENTATION_PLAN.md`; this document explains the mechanics behind it.
|
||||||
|
|
||||||
|
## 1. Principles
|
||||||
|
|
||||||
|
1. **Adapters, not rewrites** (architecture principle 15). Every module that
|
||||||
|
survives gets an interface at its edge; old and new implementations coexist
|
||||||
|
behind it until the old one has no caller.
|
||||||
|
2. **Characterisation tests first.** No module is refactored before its
|
||||||
|
observable behaviour is pinned by tests on real data (`TEST_STRATEGY.md` §2).
|
||||||
|
3. **The canonical sheet document is pure code before it is a table.** It can
|
||||||
|
be built, tested and used by the PDF pipeline with no database, which
|
||||||
|
decouples the anatomy refactor from the Supabase foundation.
|
||||||
|
4. **One identity space change, done once.** Legacy `data-anno-id` values are
|
||||||
|
mapped to stable ids by the importer, the mapping is stored in the seed
|
||||||
|
sheet, and no runtime code ever consults legacy ids again.
|
||||||
|
5. **Delete at a named step.** Each replaced module has the step at which it is
|
||||||
|
removed written in `REPOSITORY_MIGRATION_MAP.md`.
|
||||||
|
|
||||||
|
## 2. `reportStore`
|
||||||
|
|
||||||
|
Today: Zustand store holding `Report | null`, 14 actions, a `subscribe` that
|
||||||
|
mirrors every change to `sessionStorage['osteo:draft']`, restore on boot via
|
||||||
|
`ReportSchema.safeParse` (`reportStore.ts:42-56`, `159-167`).
|
||||||
|
|
||||||
|
Evolution in three moves:
|
||||||
|
|
||||||
|
| Move | Change | Behaviour preserved by |
|
||||||
|
|---|---|---|
|
||||||
|
| A. Split actions from persistence | Actions become pure functions on a report document (`addObservation(doc)`, `updateObservation(doc, i, obs)`...). The store calls them. The `subscribe` mirror moves behind `ReportPersistence` with `sessionStoragePersistence` as the only implementation. | `state.reportStore.*`, `state.draftMirror`, `state.reportStore.restore` tests unchanged |
|
||||||
|
| B. Document v3 | The store holds a v3 document (`annotationId`/`viewId` zones, region codes, `anatomicalSheetVersionId`, identity snapshots, `localAnnotations`). A `v2ToV3(report, sheetSeed)` adapter in `packages/domain` converts legacy drafts and PDF attachments using the seed's legacy id map. | adapter tests on golden v2 fixtures |
|
||||||
|
| C. Server persistence | `supabasePersistence` saves `current_document` through an `autosave_report` RPC (throttled, returns revision no), loads by id, subscribes to remote changes. `outboxPersistence` (IndexedDB) wraps it for offline. Sync state exposed to the UI. | contract tests shared by all three adapters |
|
||||||
|
|
||||||
|
`activeObservationIndex`, `setActiveObservation` and the per-observation
|
||||||
|
UI state stay client-only.
|
||||||
|
|
||||||
|
## 3. Anatomy domain
|
||||||
|
|
||||||
|
Today: four sources with no common object (manifest TS, two SVG files
|
||||||
|
fetched from `public/`, catalog JSON bundled), link by fuzzy label at render
|
||||||
|
time (audit 02 §1, 06 §1).
|
||||||
|
|
||||||
|
Evolution:
|
||||||
|
|
||||||
|
1. **Canonical document type** in `packages/domain`: `AnatomicalSheetDocument`
|
||||||
|
(Zod). `vertebral_config` is an *ordered list* of regions
|
||||||
|
`{ code, label_fr, label_en, count }`, not the fixed `C/T/L/S/Cd` object
|
||||||
|
(removes the hard-coded five-region assumption, §23.2; the architecture's
|
||||||
|
own §7.2 example still shows the fixed object, flagged in
|
||||||
|
`OPEN_QUESTIONS.md` C1).
|
||||||
|
2. **Legacy importer** in `packages/anatomy/legacy`: input = SVG texts +
|
||||||
|
manifest-like descriptor + catalog JSON; output = canonical document +
|
||||||
|
assets list + `legacy_id_map`. It reuses `parseSvgBones`, `zoneMatch`
|
||||||
|
(once, to propose `annotation_finding_map`), `regionFromLabel` (once, to
|
||||||
|
set `region_code` on spine annotations). It must reproduce every special
|
||||||
|
case of audit 07: `vertebral-precision`, `bilateral`, `opens-detail`
|
||||||
|
trigger without name, detail view with its own id space, `ssb-dysfunctions`
|
||||||
|
duplicate category id under `sphenoid`, node ids unique only among
|
||||||
|
siblings, `anamnesis` three variants, missing `description_en`.
|
||||||
|
3. **Stable ids**: UUID v4 per annotation, view, category; `legacy_id` kept
|
||||||
|
on each annotation for the seed only. Finding node ids stay as authored
|
||||||
|
(unique among siblings) because `Finding.path` is anchored at the zone;
|
||||||
|
a `node_uid` can be added later without breaking paths.
|
||||||
|
4. **Renderer**: given a view (SVG text) and the document, emits the
|
||||||
|
`data-anno-*` attributes from the document (not from the file), so
|
||||||
|
`AnatomyCanvas` and `parseSvgBones` keep working. The SVG asset becomes a
|
||||||
|
drawing; the annotations are data. For the equine seed, annotations are
|
||||||
|
initially the same `<circle>`/`<polygon>` elements present in the files;
|
||||||
|
the renderer may inject them from `geometry` instead once the editor
|
||||||
|
writes geometry.
|
||||||
|
5. **Runtime link**: `ObservationCard` resolves the findings subtree through
|
||||||
|
`annotation_finding_map`; `matchZoneFindings` is no longer imported by
|
||||||
|
`src/`. A test asserts that.
|
||||||
|
6. **Registry removal**: `getSpecies()` callers (`EditorRoute`, `export.ts`,
|
||||||
|
`observationPage.ts`, `SvgEditorRoute`, `AnimalForm`) switch to a
|
||||||
|
`SheetProvider` interface (`getVersion(id)`), first implemented over the
|
||||||
|
seed document bundled in the app, then over Supabase. `registry.ts` and
|
||||||
|
`import.meta.glob` are deleted when the bundled implementation goes.
|
||||||
|
|
||||||
|
## 4. PDF
|
||||||
|
|
||||||
|
Today: `exportReportToPdf(report, { locale })` re-fetches SVGs from
|
||||||
|
`public/`, re-parses them for labels, reloads the catalog through the
|
||||||
|
registry, rasterises in the browser, attaches the raw `Report` JSON.
|
||||||
|
|
||||||
|
Evolution:
|
||||||
|
|
||||||
|
1. Signature becomes `exportReportToPdf(doc, sheetSnapshot, branding, { locale })`.
|
||||||
|
Labels come from `sheetSnapshot.annotations`; views from
|
||||||
|
`sheetSnapshot.views` (+ SVG text); zone names for findings from
|
||||||
|
`sheetSnapshot.finding_tree`. No fetch, no registry.
|
||||||
|
2. Attachment v3: `{ attachment_version: 3, report_document, sheet_version_ref:
|
||||||
|
{ sheet_id, version_id, version_number }, sheet_snapshot: <subset needed
|
||||||
|
to render>, exported_at, locale }`. Filename still starts with
|
||||||
|
`osteo-report` (import compatibility). Size: equine SVGs are 142 KB + 136 KB
|
||||||
|
and the catalog 170 KB; Flate keeps the attachment under 200 KB.
|
||||||
|
3. Import v3 validates the attachment, then the server import RPC checks
|
||||||
|
ownership, sheet version existence (or recreates a *snapshot-only*
|
||||||
|
read-only version when the sheet is gone, which is how rule 8 "historical
|
||||||
|
data restorable" is honoured), quota, and inserts.
|
||||||
|
4. Import v2 (current PDFs) goes through `v2ToV3` with the seed legacy map.
|
||||||
|
Whether that path is production or dev-only depends on `OPEN_QUESTIONS.md`
|
||||||
|
Q1. CLAUDE.md's "ask before changing `importReportFromPdf` /
|
||||||
|
`extractReportJson`" is honoured as an explicit confirmation gate inside
|
||||||
|
the PDF step.
|
||||||
|
5. Branding (`header.ts`, `footer.ts`, `logo.ts`) takes a `Branding` object
|
||||||
|
(platform + tenant). Hard-coded `faunosteo.com`, `zenquality.fr`,
|
||||||
|
Instagram links move into that object.
|
||||||
|
6. Server-side PDF stays out of scope until a `Rasterizer` interface exists;
|
||||||
|
`svgToPng` is the browser implementation.
|
||||||
|
|
||||||
|
## 5. SVG editor
|
||||||
|
|
||||||
|
Today: 1858-line vanilla DOM tool inside `useEffect([locale])`, DOM is the
|
||||||
|
database, export = serialize DOM (audit 03).
|
||||||
|
|
||||||
|
Strategy: **not ported, replaced**, in this order:
|
||||||
|
|
||||||
|
1. Write the functional reference as tests against the canonical document
|
||||||
|
(one test per operation of audit 03 §2: load, select, create point,
|
||||||
|
create polygon, edit names/category/laterality/radius/opacity, drag,
|
||||||
|
vertex insert/delete, delete, category add/rename/colour/delete/special,
|
||||||
|
detail trigger, export).
|
||||||
|
2. Build the new editor on `apps/app` with a proper model
|
||||||
|
(`SheetEditorStore` in Zustand: document + selection + mode + undo stack),
|
||||||
|
rendering through the same `AnatomyCanvas` renderer. Features the old tool
|
||||||
|
lacks and the architecture requires: create detail view from a selected
|
||||||
|
zone (bounding box + margin → `view_box`, child view with
|
||||||
|
`parent_view_id`), vertebral configuration editing, draft/publish flow,
|
||||||
|
stable ids.
|
||||||
|
3. Keep `/svg-editor` reachable until the reference tests pass on the new
|
||||||
|
editor, then delete `SvgEditorRoute.tsx`, `svg-editor.css` and the
|
||||||
|
`svg_editor.*` i18n keys in one commit.
|
||||||
|
|
||||||
|
Known traps carried from the audit: `applyEdit` strips `data-anno-category`
|
||||||
|
from detail triggers, which the app parser refuses (audit 10 C8); category
|
||||||
|
slugs with degraded accents are opaque ids and must be preserved verbatim by
|
||||||
|
the importer; `fixDuplicateIds` renames ids by category, which would break
|
||||||
|
`boneId` references, so the importer must run on the *committed* files, never
|
||||||
|
on an editor re-export.
|
||||||
|
|
||||||
|
## 6. Findings (pathology) editor
|
||||||
|
|
||||||
|
Today: static `public/pathology-editor.html`, hard-coded `SPECIES_CONFIG`,
|
||||||
|
inline matcher copy, download-only output, no Zod validation (audit 05 §3).
|
||||||
|
|
||||||
|
Strategy: its tree-editing behaviour (add root category, add child, edit,
|
||||||
|
delete with descendant count, sources rows, id generation by slug with `-2`
|
||||||
|
suffix) becomes the "findings" panel of the merged editor, operating on
|
||||||
|
`finding_tree` of the same document, with Zod validation before save and the
|
||||||
|
explicit `annotation_finding_map` edited in the same panel (click an
|
||||||
|
annotation → see/assign its finding zone). Missing abilities listed in audit
|
||||||
|
05 §3.6 (rename/delete zone, reorder, move node, edit `scope_disclaimer`)
|
||||||
|
are added here. The static file and the `public/species/equine/pathologies.json`
|
||||||
|
copy are deleted at the same step as the SVG editor. If an external domain
|
||||||
|
expert uses the static tool today (`OPEN_QUESTIONS.md` Q4), it stays
|
||||||
|
deployed read-only one release longer.
|
||||||
|
|
||||||
|
## 7. i18n
|
||||||
|
|
||||||
|
Today: flat FR/EN dicts in `src/i18n`, parity test, `useT` hook; 76 inline
|
||||||
|
keys in `pathology-editor.html`.
|
||||||
|
|
||||||
|
Evolution: move to `packages/i18n` when a second consumer exists, split
|
||||||
|
dictionaries (no React) from `useT` (React), add namespaces for new domains
|
||||||
|
(`clients.*`, `agenda.*`, `billing.*`, `community.*`, `admin.*`) keeping the
|
||||||
|
`<area>.<key>` convention and the parity test. Sheet content (zone names,
|
||||||
|
finding labels, descriptions) stays data inside the document, bilingual by
|
||||||
|
field, never dictionary keys. Emails rendered by the worker use the same
|
||||||
|
dictionaries. Locale persists in `profiles.locale` and still in
|
||||||
|
`localStorage` for the anonymous public site.
|
||||||
|
|
||||||
|
## 8. Species and seed migration (architecture §23.3)
|
||||||
|
|
||||||
|
```text
|
||||||
|
public/species/equine/Horse.svg + Horse_head.svg + src/domain/species/equine/pathologies.json
|
||||||
|
│ legacy importer (packages/anatomy/legacy), deterministic
|
||||||
|
▼
|
||||||
|
supabase/seed/anatomical-sheets/equine/v1/
|
||||||
|
document.json canonical sheet document (stable ids, explicit mapping, region codes)
|
||||||
|
legacy-id-map.json old data-anno-id → annotation id, old detail key 'head' → view id
|
||||||
|
assets/ the two SVG files, byte-identical to public/ (checksums recorded)
|
||||||
|
│ seed script (idempotent)
|
||||||
|
▼
|
||||||
|
anatomical_sheets "Faunosteo / Cheval / Fiche anatomique officielle"
|
||||||
|
anatomical_sheet_versions v1, published, immutable
|
||||||
|
storage: anatomical-sheets/<sheet-id>/<version-id>/<asset-id>/Horse.svg ...
|
||||||
|
```
|
||||||
|
|
||||||
|
Normalisations performed once, logged in the seed report (§23.5): duplicate
|
||||||
|
category id `ssb-dysfunctions` under `sphenoid` (kept as-is or renamed per
|
||||||
|
`OPEN_QUESTIONS.md` Q9), degraded category slugs (kept verbatim as ids,
|
||||||
|
labels taken from `data-anno-category-name` when present), missing
|
||||||
|
`description_en` (left empty), detail trigger `zone-mpby55kd` (becomes a
|
||||||
|
`detail-trigger` annotation with no finding mapping), `Horse_head.svg` as a
|
||||||
|
separate asset or a `view_box` on the main asset (Q5).
|
||||||
|
|
||||||
|
## 9. Data and compatibility rules during the transition
|
||||||
|
|
||||||
|
- Report v2 drafts in `sessionStorage` are converted on first load after the
|
||||||
|
v3 step; failure to convert keeps the draft untouched and shows a message.
|
||||||
|
- PDF v2 import remains available at least until the first production
|
||||||
|
release of the SaaS (dev adapter mandatory, production support per Q1).
|
||||||
|
- The `/species/equine/*` public paths keep being served until the three
|
||||||
|
consumers (report editor, SVG editor, pathology editor) have moved; the
|
||||||
|
nginx `no-cache` rule is removed with them.
|
||||||
|
- No step deletes data; soft delete and revisions only. Physical deletion is
|
||||||
|
limited to sheet-version garbage collection under the four preconditions
|
||||||
|
of rule 7 (§16).
|
||||||
|
|
||||||
|
## 10. Rollback
|
||||||
|
|
||||||
|
Each step is a feature branch merged into `develop` behind a working state.
|
||||||
|
Database steps are forward-only migrations with a rehearsed `supabase db
|
||||||
|
reset` on staging; rollback of a released DB step is a new migration
|
||||||
|
(contract phase), never a revert of an applied one. Frontend steps that
|
||||||
|
switch persistence keep the previous adapter selectable by runtime config for
|
||||||
|
one release.
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
# Open questions, contradictions and flagged decisions
|
||||||
|
|
||||||
|
Status: Step 0 deliverable, 2026-10-08. Two lists: (A) contradictions,
|
||||||
|
ambiguities or technically risky points found when confronting
|
||||||
|
`faunosteo-business-architecture.md` with the code and the audit, and (B)
|
||||||
|
questions for the developer that change architecture or development order.
|
||||||
|
Items that are merely interesting are left out.
|
||||||
|
|
||||||
|
## A. Contradictions, ambiguities, risky decisions
|
||||||
|
|
||||||
|
### C1. Vertebral formula shape (architecture §7.2 vs §23.2)
|
||||||
|
|
||||||
|
§7.2 shows `"vertebral_formula": { "C": 7, "T": 13, "L": 7, "S": 3, "Cd": 20 }`,
|
||||||
|
the same fixed five-key object as today's `VertebralFormula`. §23.2 asks to
|
||||||
|
"remove hard-coded five-region assumptions from generic domain code". The
|
||||||
|
canonical document must use an ordered list of regions `{ code, label_fr,
|
||||||
|
label_en, count }` and the report must store the region code, otherwise the
|
||||||
|
report schema keeps the `z.enum(['C','T','L','S','Cd'])` of
|
||||||
|
`observation.ts:7`. This plan assumes the ordered list. See also Q3.
|
||||||
|
|
||||||
|
### C2. Report-only manual points vs "report references an immutable sheet version" (§3.2 step 7, rule 3)
|
||||||
|
|
||||||
|
"A manually created point exists only in this report until promoted to a
|
||||||
|
personal sheet." Such a point is not in any sheet version, so the report
|
||||||
|
document must carry `localAnnotations[]` (geometry, view id, names, optional
|
||||||
|
finding free text) and the PDF must render them. The architecture does not
|
||||||
|
say where they live or how promotion rewrites the report (does the report
|
||||||
|
then reference a *new* version of the personal sheet?). Decision needed
|
||||||
|
before the report document v3 is frozen. See Q6.
|
||||||
|
|
||||||
|
### C3. Worker on day one (§21.1) vs PostgreSQL-backed jobs first (§22.3)
|
||||||
|
|
||||||
|
Not a contradiction in substance, but the monorepo tree lists `apps/worker`
|
||||||
|
as if it existed from the start. The plan creates it at the first job that
|
||||||
|
cannot be a SQL function (reminders / calendar sync).
|
||||||
|
|
||||||
|
### C4. Global client record shared across practitioners (§2.3, §6)
|
||||||
|
|
||||||
|
`clients` is "a global Faunosteo person record, not a copy per practitioner".
|
||||||
|
Two practitioners with a care relationship to the same person then edit the
|
||||||
|
same `first_name`/`last_name`/`notes_general`. Risks: one practitioner's edit
|
||||||
|
silently changes another's records; `notes_general` is clinical-adjacent and
|
||||||
|
must not be shared by default. The architecture also requires that identity
|
||||||
|
matching never reveals another relationship. The plan assumes: core identity
|
||||||
|
fields editable only by the creating practitioner or the claimed client
|
||||||
|
account, per-relationship notes in a separate table, and a verification flow
|
||||||
|
for linking. Q6 asks for confirmation. **Technically dangerous if left as a
|
||||||
|
plain shared row.**
|
||||||
|
|
||||||
|
### C5. Animal update rights "owner-controlled" (§17.3) with no client accounts in MVP (§20)
|
||||||
|
|
||||||
|
In the MVP the owner has no login. The rule "update is owner-controlled, with
|
||||||
|
practitioner update permitted only after a consultation context or explicit
|
||||||
|
owner permission" is unenforceable as written. Plan assumption: the
|
||||||
|
practitioner who created the animal (or an org member with the relationship)
|
||||||
|
can update it; owner control starts with the client portal (post-MVP).
|
||||||
|
|
||||||
|
### C6. What an unverified account may do (§3.1, §5)
|
||||||
|
|
||||||
|
"A non-verified account must not access full professional functionality."
|
||||||
|
Ambiguous: may it create clients/animals and drafts? May it complete a report?
|
||||||
|
Plan assumption: unverified = can set up profile, cabinet invitation
|
||||||
|
acceptance, browse public sheets; cannot create clients/animals/reports.
|
||||||
|
Affects the entitlement capability list. Confirm.
|
||||||
|
|
||||||
|
### C7. Vocabulary collision on "Observation" (audit 05 §1)
|
||||||
|
|
||||||
|
In the code an `Observation` is a group of zones + findings + severity +
|
||||||
|
comment; in the catalog "Observations / motifs de consultation" is a finding
|
||||||
|
category; the architecture lists "finding/observation/anamnesis tree". The
|
||||||
|
product vocabulary must fix one word for each before UI strings and schema
|
||||||
|
names are created in the SaaS. Plan uses: *Observation* = the report block
|
||||||
|
(unchanged), *Finding* = a leaf, *Finding category* = a tree root.
|
||||||
|
|
||||||
|
### C8. Multiple drafts per sheet (§7.1)
|
||||||
|
|
||||||
|
`anatomical_sheet_versions.status ∈ {draft, published, deprecated}` and
|
||||||
|
`current_version_id` on the sheet. Nothing says whether a sheet may hold more
|
||||||
|
than one draft at a time or who may edit a draft (creator only? org
|
||||||
|
members?). Plan assumption: at most one draft per sheet, editable by the
|
||||||
|
creator; a unique partial index enforces it.
|
||||||
|
|
||||||
|
### C9. Detail view storage: separate SVG asset vs viewBox on the parent asset (§7.3 vs audit 04)
|
||||||
|
|
||||||
|
`Horse_head.svg` is a full copy of `Horse.svg` with a different `viewBox` and
|
||||||
|
its own overlays (audit 04 §2). §7.2 gives every view its own
|
||||||
|
`svg_asset_id`. The future editor's "create detail from a zone" naturally
|
||||||
|
produces a `view_box` on the *same* asset. Plan assumption: `svg_asset_id`
|
||||||
|
nullable on detail views; null means "render the parent asset with this
|
||||||
|
`view_box`". The equine seed may keep two assets to stay byte-faithful to the
|
||||||
|
source files. Q5 asks which.
|
||||||
|
|
||||||
|
### C10. Edge Functions on self-hosted Supabase (§22.2, §31) on a 1 vCPU / 1 GB VPS (DEPLOY.md)
|
||||||
|
|
||||||
|
The current runbook provisions 1 vCPU / 1 GB. A self-hosted Supabase stack
|
||||||
|
(Postgres, GoTrue, PostgREST, Storage, Kong, Studio, edge-runtime, Realtime,
|
||||||
|
imgproxy) needs several GB of RAM and is operationally heavy for one person.
|
||||||
|
Either the VPS is upgraded, or the launch uses managed Supabase from day one
|
||||||
|
(the architecture's "stage 2" contract is the same schema anyway). This
|
||||||
|
changes Step 3 and the deploy runbook. Q2.
|
||||||
|
|
||||||
|
### C11. Free-plan quota counted on "completed" reports but editing a completed report is allowed 5 days (§1.2)
|
||||||
|
|
||||||
|
Consistent, but note the interaction with revisions: a restore of an old
|
||||||
|
revision after the 5-day window is an edit and must be denied for free
|
||||||
|
accounts. The plan treats *any* write to a completed report as
|
||||||
|
`reports.edit_after_free_window` after `free_edit_until`.
|
||||||
|
|
||||||
|
### C12. SVG sanitization "server-side before becoming available to others" (§15.3) vs direct-to-Storage uploads
|
||||||
|
|
||||||
|
Supabase Storage uploads go straight from the browser to the bucket. The
|
||||||
|
sanitizer must therefore run between upload and publication (quarantine
|
||||||
|
prefix + status column + policy), not "on upload". Designed in
|
||||||
|
`BACKEND_ARCHITECTURE.md` §5; flagged because a naive implementation would
|
||||||
|
ship the client sanitizer as the boundary, which the audit already marks
|
||||||
|
insufficient (F1).
|
||||||
|
|
||||||
|
### C13. CLAUDE.md rules that the migration necessarily breaks
|
||||||
|
|
||||||
|
- "domain/schema/*.ts are the data contracts, never change without bumping version": honoured (v3).
|
||||||
|
- "Ask before any change to importReportFromPdf or extractReportJson": honoured as a confirmation gate in the PDF step.
|
||||||
|
- "Never modify anatomy SVGs in public/species/": honoured; the importer reads, never writes them.
|
||||||
|
- "Each entry needs ≥1 source with citation": violated today by all 792 nodes (audit 05 §2.4). Either the rule is relaxed for the official seed or sources are authored before publication. Plan assumption: relaxed, `sources` optional, a warning in the editor.
|
||||||
|
- "React SPA exception" (BDR-001): still valid for `apps/app`; the public site is the SSR part.
|
||||||
|
|
||||||
|
### C14. Report locale not persisted (BDR-014) vs stored PDF artifacts
|
||||||
|
|
||||||
|
Server-stored PDFs must record the locale they were rendered in (artifact
|
||||||
|
metadata), otherwise re-rendering from the snapshot cannot reproduce the
|
||||||
|
document. Not a schema change on the report document; an artifact column.
|
||||||
|
|
||||||
|
## B. QUESTIONS POUR LE DEVELOPPEUR
|
||||||
|
|
||||||
|
Only questions whose answer changes the architecture or the order of work.
|
||||||
|
|
||||||
|
### Q1. Are there Faunosteo PDFs (report v2) in real use that must import into the SaaS?
|
||||||
|
|
||||||
|
- What: whether practitioners (or the client osteopath) hold exported PDFs today.
|
||||||
|
- Why: decides if the `v2ToV3` + legacy-id reconciliation path is production code with its own UI (quota, mapping review) or a dev-only adapter kept for regression tests (architecture §23.4 assumes no install base; CHANGELOG 0.1.0 says the same, but faunosteo.com is live per TODO Phase C).
|
||||||
|
- How to answer: ask the client; check the live site usage if any analytics exist (none in the repo).
|
||||||
|
|
||||||
|
### Q2. Hosting target for the first steps: self-hosted Supabase on an upgraded VPS, or managed Supabase?
|
||||||
|
|
||||||
|
- What: RAM/CPU available on the Scaleway VPS, and whether running the full Supabase Docker stack (plus Edge Functions) is acceptable operationally.
|
||||||
|
- Why: changes Step 3 (local dev is identical, but the deploy runbook, backups, Edge Function deployment and cost differ), and whether Edge Functions are used at all before the agenda/widget steps.
|
||||||
|
- How to answer: `DEPLOY.md` says 1 vCPU / 1 GB; confirm the plan for the box (`free -m`, `nproc` on the VPS) and the budget.
|
||||||
|
|
||||||
|
### Q3. Must the vertebral model support non-mammalian layouts (birds) in the MVP data model?
|
||||||
|
|
||||||
|
- What: the species list. README cites dog, cat, goat, cow, pig, rabbit, donkey, sheep; TODO Phase D cites "chicken". Birds have fused regions (notarium, synsacrum, pygostyle).
|
||||||
|
- Why: with an ordered region list (C1) any mammal fits; birds need fused/variable regions and change the picker. Deciding now avoids a document schema v2 right after launch.
|
||||||
|
- How to answer: product decision; the model in this plan (ordered region list with free codes) covers birds if region labels are free, so the answer only affects the picker UI.
|
||||||
|
|
||||||
|
### Q4. Is `public/pathology-editor.html` used today by an external domain expert?
|
||||||
|
|
||||||
|
- What: BDR-022 mentions a "domain expert" authoring the catalog; audit 11 could not tell whether the static tool is their workflow.
|
||||||
|
- Why: if yes, it must keep working against a JSON export of the official sheet during the editor-merge step and gets a documented export/import bridge; if no, it is deleted with the SVG editor.
|
||||||
|
- How to answer: ask the expert; check whether any `pathologies-equine-<timestamp>.json` exports exist outside the repo.
|
||||||
|
|
||||||
|
### Q5. Equine seed: two SVG assets (byte-faithful to `Horse.svg` and `Horse_head.svg`) or one asset + `view_box` for the head?
|
||||||
|
|
||||||
|
- What: storage shape of the official sheet v1.
|
||||||
|
- Why: affects the sheet document schema (`svg_asset_id` nullable), the renderer, the PDF detail view, and the "create detail view" editor feature. Two assets keep the files untouched; one asset halves storage and matches the future editor.
|
||||||
|
- How to answer: product/technical choice; recommendation is nullable `svg_asset_id` and two assets for v1 only.
|
||||||
|
|
||||||
|
### Q6. Report-only manual points and shared client records: where do they live?
|
||||||
|
|
||||||
|
- What: (a) schema and rendering of points created inside a report and not in any sheet (C2); (b) edit rights on global client core fields and whether `notes_general` is shared (C4).
|
||||||
|
- Why: both freeze the report document v3 and the client RLS, which are the two hardest migrations.
|
||||||
|
- How to answer: product decision. Recommendation: (a) `localAnnotations[]` in the report document, rendered in the PDF, promotion creates a new personal-sheet version and rewrites the report to reference it; (b) core identity editable by creator or claimed client only, notes per relationship.
|
||||||
|
|
||||||
|
### Q7. Phone verification and transactional email providers
|
||||||
|
|
||||||
|
- What: which SMS provider and which email provider (EU processing).
|
||||||
|
- Why: phone verification is a sign-up gate (§3.1) and a referral prerequisite; without a provider decision Step 7 ships email-only verification and the referral rules cannot be tested end-to-end.
|
||||||
|
- How to answer: business decision; GoTrue supports Twilio, MessageBird, Vonage, Textlocal.
|
||||||
|
|
||||||
|
### Q8. Public site framework: Next.js (architecture §21.2) or Astro SSR (global rule "Astro by default")?
|
||||||
|
|
||||||
|
- What: the framework of `apps/public-web`.
|
||||||
|
- Why: toolchain, Docker image, SEO tooling for the public-profile step. Does not affect the private app.
|
||||||
|
- How to answer: decide at that step; default to Next.js as approved unless the global rule is meant to override.
|
||||||
|
|
||||||
|
### Q9. Catalog anomalies to normalise or preserve in the official seed
|
||||||
|
|
||||||
|
- What: `sphenoid.categories[0].id === 'ssb-dysfunctions'` (same id as under `ssb`), degraded category slugs (`charni-res-vert-brales`, `cadrans-du-cr-ne`), zero `sources`, zero `description_en`.
|
||||||
|
- Why: the importer is deterministic and the seed v1 is immutable once published; renaming later means v2 of the official sheet. Finding paths in future reports anchor on these ids.
|
||||||
|
- How to answer: domain expert review of `docs/faunosteo-audit/05-findings-editor.md` §2.4; recommendation: fix the `ssb-dysfunctions` id to `sphenoid-dysfunctions` before v1 (no report references it yet), keep slugs verbatim with human labels.
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
# Repository migration map
|
||||||
|
|
||||||
|
Status: Step 0 deliverable, 2026-10-08. Branch `develop` at `2ae1e48`.
|
||||||
|
Sources: `faunosteo-business-architecture.md` (target), `docs/faunosteo-audit/`
|
||||||
|
(current behaviour, audited at `83e40af`), direct reading of `src/`, `public/`,
|
||||||
|
`docker/`, `tests/`, `scripts/`.
|
||||||
|
|
||||||
|
Verdict vocabulary:
|
||||||
|
|
||||||
|
| Verdict | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| KEEP | Used as-is in the target, possibly moved into a package |
|
||||||
|
| REFACTOR | Same responsibility, internals or contract change |
|
||||||
|
| REPLACE | A new implementation takes over; the old one is deleted at a named step |
|
||||||
|
| REMOVE LATER | Dead in the target; deleted once nothing imports it |
|
||||||
|
|
||||||
|
"Weight" is the importance of the area for the migration: HIGH means the SaaS
|
||||||
|
cannot ship without migrating it, LOW means it is cosmetic or self-contained.
|
||||||
|
|
||||||
|
## 1. Application shell (`src/app`, `src/config`, `src/main.tsx`)
|
||||||
|
|
||||||
|
| File | Responsibility | Depends on | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| `app/App.tsx` | BrowserRouter, 6 routes, footer toggle | routes, ConfigProvider | HIGH | REFACTOR | Routes move under `/app/*` with an auth guard; legacy routes redirect during transition. |
|
||||||
|
| `app/routes/HomeRoute.tsx` | New report / import PDF entry | pdf/import, reportStore | MEDIUM | REPLACE | Becomes `/app/dashboard`; PDF import becomes a server-validated flow (quota, ownership). |
|
||||||
|
| `app/routes/NewReportRoute.tsx` | Practitioner / animal / owner form, `initReport()` | reportStore, practitionerCache, report forms | MEDIUM | REPLACE | In the target a report is created from an Animal record and a sheet version, not from free-text identity fields. |
|
||||||
|
| `app/routes/EditorRoute.tsx` (552 lines) | Report editor: loads SVG + detail SVGs, click chain `onZoneClick` (detail → fallback observation → spine → bilateral → toggle), export | anatomy/*, species registry, reportStore, spineZones, pdf/export, components | HIGH | REFACTOR | The click chain is the core clinical behaviour and has zero tests (audit 13 §4). Extract it into a pure "zone interaction" service before touching persistence. Asset loading (`loadSvg('/species/...')`) is replaced by sheet-version content. |
|
||||||
|
| `app/routes/SvgEditorRoute.tsx` (1858 lines) | Vanilla DOM SVG annotation tool wrapped in `useEffect([locale])` | species registry, localeStore, i18n, svg-editor.css | HIGH | REPLACE | Replaced by the structured Anatomical Sheet editor (plan step "Editor merge"). Kept running untouched until then. Extraction candidates listed in audit 11 §7. |
|
||||||
|
| `app/routes/EditorsRoute.tsx` | Links to the two editors | i18n | LOW | REMOVE LATER | Disappears with the merged editor. |
|
||||||
|
| `app/routes/NotFoundRoute.tsx` | 404 | i18n | LOW | KEEP | |
|
||||||
|
| `app/providers/ConfigProvider.tsx`, `config/env.ts` | Runtime identity config (`window.__APP_CONFIG__` > `VITE_APP_*` > defaults) | entrypoint.sh | MEDIUM | REFACTOR | Same mechanism extended with `supabaseUrl`, `supabaseAnonKey`, `publicWebUrl`. Anon key is public by design; service keys never enter this path. |
|
||||||
|
|
||||||
|
## 2. Domain (`src/domain`)
|
||||||
|
|
||||||
|
| File | Responsibility | Depends on | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| `schema/report.ts` | `Report` v2 (literal `version: 2`), `NextAppointment` | observation, practitioner, animal | HIGH | REFACTOR | Becomes the report *document* schema v3: adds `anatomicalSheetVersionId`, `localAnnotations`, identity snapshots; drops free-text practitioner identity as source of truth. v2 kept as an input type for the adapter. |
|
||||||
|
| `schema/observation.ts` | `Observation`, `ObservationZone` (`boneId`, `detailSourceId`, `vertebrae`, `side`), `Finding` (`zoneId`, `path`, snapshots) | zod | HIGH | REFACTOR | `boneId` → `annotationId` (stable id from the sheet), `detailSourceId` → `viewId`, `VertebralRegionSchema` enum → region code validated against the sheet's vertebral config. `Finding` gains nothing but is linked to the zone through the sheet's explicit mapping. |
|
||||||
|
| `schema/findings.ts` | Catalog schema: `SpeciesFindings`, `ZoneFindings`, recursive `FindingNode`, `SourceRef` | zod | HIGH | KEEP | Becomes the `finding_tree` section of the canonical sheet document. snake_case retained (BDR-009). Add node-id uniqueness and `schema_version` checks that the current schema lacks (audit 05 §2.2). |
|
||||||
|
| `schema/animal.ts`, `schema/practitioner.ts` | Free-text identity blocks inside the report | zod | MEDIUM | REPLACE | Animals and practitioners become DB entities. The report document keeps an identity *snapshot* for PDF reproducibility, so a reduced form of these schemas survives as `snapshot` sub-schemas. |
|
||||||
|
| `species/types.ts` (`SpeciesManifest`, `VertebralFormula`) | Compiled manifest contract | findings | HIGH | REPLACE | Replaced by the canonical sheet document (views, annotations, vertebral config, finding tree). |
|
||||||
|
| `species/registry.ts` | `import.meta.glob` auto-discovery of manifests | Vite | HIGH | REMOVE LATER | Vite-specific, bundle-time. Gone once sheets are DB rows. Deleted at the "Sheets in DB" step. |
|
||||||
|
| `species/equine/index.ts`, `vertebrae.ts`, `pathologies.ts`, `pathologies.json` | The implicit equine "sheet" (manifest, formula, catalog) | registry | HIGH | REPLACE | Become **seed input** for the official equine sheet v1. The files move to `supabase/seed/anatomical-sheets/equine/` and are read by the importer, never by the runtime. |
|
||||||
|
|
||||||
|
## 3. State (`src/state`)
|
||||||
|
|
||||||
|
| File | Responsibility | Depends on | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| `reportStore.ts` | Zustand store, actions, `sessionStorage` mirror `osteo:draft`, restore on boot | schema/report, lib/id, lib/dates | HIGH | REFACTOR | Split into (a) pure reducer-style actions on a report document and (b) a persistence adapter interface. Current sessionStorage mirror becomes one adapter; Supabase autosave and IndexedDB outbox become two others. See `MIGRATION_STRATEGY.md` §2. |
|
||||||
|
| `localeStore.ts` | `'fr' \| 'en'`, persisted `osteo:locale` | zustand | LOW | KEEP | Later also synced to `profiles.locale`. |
|
||||||
|
| `practitionerCache.ts` | `localStorage` prefill of practitioner block | schema/practitioner | LOW | REMOVE LATER | Replaced by the authenticated profile. |
|
||||||
|
|
||||||
|
## 4. Anatomy (`src/anatomy`)
|
||||||
|
|
||||||
|
| File | Responsibility | Depends on | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| `svgConvention.ts` (`parseSvgBones`, `getBoneIdFromEvent`) | DOM walk of `data-anno-*`, `SvgConventionError` | DOM | HIGH | KEEP | Pure DOM, no fetch. Reused twice: by the seed importer (legacy SVG → canonical document) and by the runtime canvas (click delegation on `data-anno-id`, which the renderer re-emits from the canonical document). |
|
||||||
|
| `svgLoader.ts` (`loadSvg(publicPath)`) | `fetch` + `DOMParser` | fetch | MEDIUM | REFACTOR | Becomes `parseSvgText(text)`; the source (public path today, Storage signed URL or inlined content tomorrow) is passed by the caller. Four call sites (audit 01 §3). |
|
||||||
|
| `labels.ts`, `i18n/pickLocaleLabel.ts` | FR/EN fallback label | i18n | LOW | KEEP | |
|
||||||
|
| `types.ts` (`Bone`, `BoneState`, `SvgConventionError`) | Parsed element model | DOM | MEDIUM | REFACTOR | `Bone` is the *legacy* parsed shape. The canonical `Annotation` type (stable id, view id, kind, geometry, category id, laterality, special) lives in the domain package; `Bone` stays as importer input. |
|
||||||
|
|
||||||
|
## 5. Components (`src/components`)
|
||||||
|
|
||||||
|
| Folder / file | Responsibility | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `ui/*` (Button, Card, Dialog, Input, Label, Select, Textarea, Badge, Chip) | Primitives | LOW | KEEP | Move to `packages/ui` when a second app needs them (public-web). Not before. |
|
||||||
|
| `canvas/AnatomyCanvas.tsx` | Inline SVG, delegated click, `data-state` highlight, tooltip | HIGH | REFACTOR | Accepts SVG text or a canonical view instead of a URL. Tooltip skips `data-anno-opens-detail` elements; keep that behaviour for "detail trigger" annotations. |
|
||||||
|
| `canvas/DetailModal.tsx` | Dialog around a detail `AnatomyCanvas` | MEDIUM | REFACTOR | Generalised to any child view (`parent_view_id`), with a breadcrumb for nested views. |
|
||||||
|
| `observation/ObservationCard.tsx` | Zone badges, pickers per `(tree.id, side)`, severity, comment; **only runtime caller of `matchZoneFindings`** (line 134) | HIGH | REFACTOR | Replace the fuzzy match with the sheet's explicit `annotation_id → finding_zone_id` mapping. Everything else stays. |
|
||||||
|
| `observation/FindingsTreePicker.tsx` | Breadcrumb drill-down over a `ZoneFindings` subtree, emits `Finding` with snapshots | HIGH | KEEP | Pure component on the tree; unchanged by the storage migration. |
|
||||||
|
| `observation/VertebraPicker.tsx` | Region tabs + chip grid from `VertebralFormula`; `REGIONS` hard-coded `C T L S Cd` | HIGH | REFACTOR | Tabs come from the sheet's ordered region list (code, label FR/EN, count). |
|
||||||
|
| `observation/LateralityPicker.tsx`, `SeveritySelector.tsx`, `FreeTextFindingInput.tsx`, `ObservationList.tsx` | Pure UI | MEDIUM | KEEP | |
|
||||||
|
| `report/PractitionerForm.tsx`, `AnimalForm.tsx` | Free-text identity forms; `AnimalForm` lists `getAllSpecies()` | MEDIUM | REPLACE | Replaced by profile data and an Animal/Client picker. `AnimalForm` may survive as the "new animal" dialog with species from DB. |
|
||||||
|
| `report/ReportHeader.tsx`, `ConclusionPanel.tsx`, `NextAppointmentPicker.tsx` | Report editing UI | MEDIUM | KEEP | `NextAppointmentPicker` later links to the Agenda domain. |
|
||||||
|
| `brand/*` (AppHeader, Brand, Footer, LanguageSwitcher) | Branding | LOW | KEEP | Tenant branding (practitioner/cabinet logo) injected via config later. |
|
||||||
|
|
||||||
|
## 6. PDF (`src/pdf`)
|
||||||
|
|
||||||
|
| File | Responsibility | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `export.ts` (`exportReportToPdf`, `buildZoneLabels`, `loadSpeciesFindings`) | Orchestrates pages, re-fetches SVGs and catalog from `public/` and the registry at export time | HIGH | REFACTOR | Inputs become `(reportDocument, sheetVersionContent, branding, locale)`. No fetch of `public/species`, no registry. Labels come from the sheet document, not from a re-parse. |
|
||||||
|
| `import.ts`, `attachment.ts` | Load PDF, extract `osteo-report*.json`, version gate (`!== 2` → typed error), Zod parse, 16 MiB inflate cap | HIGH | REFACTOR | Attachment v3 carries report document + schema version + sheet version id + sheet snapshot. **CLAUDE.md requires asking before changing these two files**: that gate is part of the plan step, not bypassed. |
|
||||||
|
| `render/observationPage.ts` (651 lines) | Rasterises views, draws zone/findings sections; `colorizedSvgString` re-fetches the SVG | HIGH | REFACTOR | Takes view SVG text and annotation ids from the sheet snapshot. Text sections unchanged. |
|
||||||
|
| `render/header.ts`, `footer.ts`, `logo.ts`, `linkAnnotation.ts` | Branding, hard-coded logos and URLs (`faunosteo.com`, `zenquality.fr`, Instagram) | MEDIUM | REFACTOR | Branding becomes a parameter (platform + tenant). |
|
||||||
|
| `render/svgToPng.ts` | `Image` + `canvas` rasteriser | MEDIUM | KEEP | Browser-only. Blocks any server-side PDF generation until replaced (resvg or similar). Server PDF is explicitly "later" in the architecture (§22.3). |
|
||||||
|
| `render/text.ts`, `conclusionPage.ts`, `constants.ts`, `fonts.ts` | Layout helpers, StandardFonts WinAnsi | LOW | KEEP | TTF embedding stays a separate improvement (EVAL-003). |
|
||||||
|
|
||||||
|
## 7. Lib (`src/lib`)
|
||||||
|
|
||||||
|
| File | Responsibility | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `zoneMatch.ts` | Fuzzy FR/EN label match SVG ↔ catalog (EN exact → FR exact → substring → Levenshtein 25 %) | HIGH | KEEP as migration helper, REMOVE from runtime | Moves to the importer. Runtime mapping is explicit (architecture §23.2, principle 5). Its inline copy in `pathology-editor.html` dies with that tool. |
|
||||||
|
| `spineZones.ts` (`regionFromLabel`, `findSpineZoneId`, `collectSpineVertebrae`, `syncSpineZones`) | Spine picker seed/confirm logic; region deduced from label roots | HIGH | REFACTOR | `regionFromLabel` is replaced by an explicit `region_code` on spine annotations in the sheet. `collect`/`sync` logic (BDR-019) is kept, keyed on that code. The importer uses `regionFromLabel` once to populate the code. |
|
||||||
|
| `id.ts`, `dates.ts`, `assert.ts` | Utilities | LOW | KEEP | |
|
||||||
|
|
||||||
|
## 8. i18n (`src/i18n`)
|
||||||
|
|
||||||
|
| File | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `fr.ts`, `en.ts` (flat dicts, parity-tested), `index.ts`, `useT.ts`, `types.ts` | MEDIUM | KEEP | Moves to `packages/i18n` when `public-web` needs shared strings. The 76 inline keys of `pathology-editor.html` are folded in at the editor merge. Sheet content strings (zone names, finding labels) stay *data*, not dictionary keys. |
|
||||||
|
|
||||||
|
## 9. Static assets (`public/`)
|
||||||
|
|
||||||
|
| Path | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `public/species/equine/Horse.svg`, `Horse_head.svg` | HIGH | KEEP as seed input, stop serving at runtime | Never modified (CLAUDE.md). Read once by the importer; bytes uploaded to the `anatomical-sheets` bucket as assets of the official equine sheet v1. `Horse_head.svg` is a full copy of `Horse.svg` with a different `viewBox` (audit 04 §2): see `OPEN_QUESTIONS.md` Q5. |
|
||||||
|
| `public/species/equine/pathologies.json` | HIGH | REMOVE LATER | Second copy of the catalog, read only by `pathology-editor.html`. Dies with it. |
|
||||||
|
| `public/pathology-editor.html` (1700 lines, zero `src/` imports) | HIGH | REPLACE | Kept working untouched until the editor merge step, then deleted. Its tree-edit logic is the reference behaviour for the findings panel of the new editor (audit 11 §7). |
|
||||||
|
| `public/env.js`, `favicon.svg`, `logo-horizontal.svg`, `assets/*.png`, `brand/*.png`, `Paws_in_harmony.svg` | LOW | KEEP | Platform branding. |
|
||||||
|
|
||||||
|
## 10. Scripts
|
||||||
|
|
||||||
|
| Path | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `scripts/scaffold-species.mjs` | LOW | REMOVE LATER | Writes `schema_version '1.1'` and a mixed canine/equine formula (audit 12 §1). Species become DB rows; a "new sheet" action in the editor replaces it. Not worth fixing. |
|
||||||
|
| `logos/generate-sizes.sh` | LOW | KEEP | Brand tooling, out of scope. |
|
||||||
|
|
||||||
|
## 11. Tests (`tests/`)
|
||||||
|
|
||||||
|
32 files under `tests/unit/`, 180 `it(` cases (audit 13; README says 174, stale). `happy-dom`, no e2e. KEEP and EXTEND. The untested areas that gate the migration (click chain, full PDF roundtrip with observations, real SVG ↔ catalog equality, `opens-detail` ↔ manifest coherence, zoneMatch parity, catalog copies parity) are the content of plan Step 1. See `TEST_STRATEGY.md` §2.
|
||||||
|
|
||||||
|
## 12. Docker, nginx, runtime configuration
|
||||||
|
|
||||||
|
| File | Responsibility | Weight | Verdict | Notes |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `Dockerfile` | node:20-alpine build (pnpm 10.13.1 pinned, BLK-005) → nginx:1.31-alpine, non-root, port 8080 | MEDIUM | REFACTOR | Build context becomes the monorepo; builds `apps/app` only. Separate images for `public-web` and `worker` appear with those apps. |
|
||||||
|
| `docker/nginx.conf` | SPA fallback, `/species/` no-cache, `/assets/` immutable, `/env.js` no-store | MEDIUM | REFACTOR | `/species/` rule becomes dead once sheets are served from Storage. Add security headers (CSP, HSTS at the proxy) at the hardening step. |
|
||||||
|
| `docker/entrypoint.sh` | Writes `env.js` from `APP_*` env vars, escapes values, envsubst `PORT` | MEDIUM | REFACTOR | Adds `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `PUBLIC_WEB_URL`. Same escaping discipline (SEC-9). |
|
||||||
|
| `docker-compose.yml`, `.env.example` | Single `app` service | MEDIUM | REFACTOR | Gains the self-hosted Supabase stack (or an external URL), `public-web`, `worker`. `.env.example` grows with placeholders only. |
|
||||||
|
| `DEPLOY.md` | 1 vCPU / 1 GB VPS runbook | MEDIUM | REFACTOR | Self-hosted Supabase does not fit 1 GB (see `OPEN_QUESTIONS.md` Q2). |
|
||||||
|
|
||||||
|
## 13. Documentation
|
||||||
|
|
||||||
|
| File | Verdict | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `docs/ANATOMY-SVG-CONVENTION.md` | REFACTOR | Out of sync with the parser (audit 10 I5: 7 "valid categories" that do not exist, `linked`/`multi` states removed). Becomes "Legacy SVG import convention", scoped to the importer. |
|
||||||
|
| `docs/PATHOLOGIES-FORMAT.md` | REFACTOR | Becomes the `finding_tree` section of the sheet document spec. |
|
||||||
|
| `docs/ADDING-A-SPECIES.md` | REPLACE | Species are created in the editor. |
|
||||||
|
| `docs/PDF-FORMAT.md` | REPLACE | 12-line placeholder today; written for attachment v3. |
|
||||||
|
| `docs/superpowers/*` | KEEP | Historical design records. |
|
||||||
|
| `docs/faunosteo-audit/` | KEEP | Reference for the migration; frozen at `83e40af`. |
|
||||||
|
| `docs/development/` | NEW | This set. |
|
||||||
|
|
||||||
|
## 14. Git, hooks, memory
|
||||||
|
|
||||||
|
`.githooks/`, `.claude/` are untouched by the migration. Note: the working tree
|
||||||
|
has uncommitted edits in `.githooks/post-commit` and `.githooks/post-merge`
|
||||||
|
(manual-push-mode fail-closed change) and the untracked
|
||||||
|
`faunosteo-business-architecture.md`. Neither is part of Step 0.
|
||||||
|
|
||||||
|
## 15. Summary by verdict
|
||||||
|
|
||||||
|
| Verdict | Areas |
|
||||||
|
|---|---|
|
||||||
|
| KEEP | `parseSvgBones`, findings schema, `FindingsTreePicker`, pickers, UI primitives, i18n, PDF render helpers, `svgToPng`, lib utils, tests, seed SVGs |
|
||||||
|
| REFACTOR | `EditorRoute` click chain, `reportStore`, report/observation schemas, `AnatomyCanvas`/`DetailModal`, `ObservationCard` (mapping), `VertebraPicker`, `spineZones`, PDF export/import/attachment/observationPage, Docker/nginx/entrypoint, `ConfigProvider` |
|
||||||
|
| REPLACE | `SvgEditorRoute`, `pathology-editor.html`, species manifest/types, `HomeRoute`/`NewReportRoute`, identity forms, `scaffold-species`, `ADDING-A-SPECIES.md`, `PDF-FORMAT.md` |
|
||||||
|
| REMOVE LATER | `species/registry.ts`, `practitionerCache`, `EditorsRoute`, `public/species/equine/pathologies.json`, runtime use of `zoneMatch` |
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# Test strategy
|
||||||
|
|
||||||
|
Status: Step 0 deliverable, 2026-10-08. Current state: 32 files under
|
||||||
|
`tests/unit/`, 180 `it(` cases, vitest 3 + happy-dom, no browser, no e2e
|
||||||
|
(audit 13). All green per TODO as of 2026-07-12; not re-run in Step 0.
|
||||||
|
|
||||||
|
## 1. Layers
|
||||||
|
|
||||||
|
| Layer | Tool | Location | Runs in |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Unit (pure TS, Zod, services) | vitest | `apps/app/tests/unit`, `packages/*/tests` | CI on every PR |
|
||||||
|
| Component | vitest + @testing-library/react + happy-dom | `apps/app/tests/components` | CI |
|
||||||
|
| Integration (app ↔ local Supabase) | vitest with `supabase start`, test users created via the admin API in a fixture | `apps/app/tests/integration` | CI job with the Supabase stack |
|
||||||
|
| Database (schema, functions, triggers) | pgTAP via `supabase test db` | `supabase/tests/db` | CI, before app tests |
|
||||||
|
| RLS | pgTAP, per table, per role | `supabase/tests/rls` | CI, release gate |
|
||||||
|
| End-to-end | Playwright against `pnpm preview` + local Supabase | `apps/app/e2e` | CI nightly + release gate |
|
||||||
|
| Migration | `supabase db reset` from zero + seed + regression fixtures | CI | every PR touching `supabase/` |
|
||||||
|
| PDF regression | vitest golden tests: text extraction of generated PDFs, attachment roundtrip, raster hash on fixed inputs | `packages/pdf/tests` | CI |
|
||||||
|
| SQL/TS contract | generated types diff check | CI | every PR touching `supabase/` |
|
||||||
|
|
||||||
|
Browser-only code (`svgToPng`, `DOMParser` in the importer) runs under
|
||||||
|
happy-dom where sufficient and under Playwright when real rendering matters
|
||||||
|
(raster hash).
|
||||||
|
|
||||||
|
## 2. Tests required BEFORE migration (plan Step 1)
|
||||||
|
|
||||||
|
These pin the behaviour that later steps must preserve. They are written
|
||||||
|
against the *current* code, on real data, without changing the application.
|
||||||
|
|
||||||
|
| Area | Test to add | Why before |
|
||||||
|
|---|---|---|
|
||||||
|
| Click chain | `EditorRoute.onZoneClick` branches: detail trigger opens modal and is never added; no active observation → fallback then click lost; spine zone adds + opens picker and never removes; bilateral → picker, both sides present → removes both; plain toggle. Extract nothing yet: test through the route with mocked `loadSvg`. | The chain moves to a service in Step 5; zero tests today (audit 13 §4). |
|
||||||
|
| Spine sync on real SVG | `collectSpineVertebrae` / `syncSpineZones` with bones parsed from the real `Horse.svg` (not fixtures). | `regionFromLabel` is replaced by region codes; must prove equivalence. |
|
||||||
|
| SVG ↔ catalog | Parse both real SVGs, run `matchZoneFindings` on all 27 annotations against the 26 catalog zones: 26 score-0 matches, trigger unmatched, zero orphan catalog zones. Table from audit 06 §4 becomes the expected output. | The importer must reproduce exactly this mapping. |
|
||||||
|
| `opens-detail` ↔ manifest | every `data-anno-opens-detail` value is a key of `species.details`, and every key has a trigger. | Becomes `parent_view_id`/`opened_by_annotation_id` invariants. |
|
||||||
|
| Matcher parity | the inline matcher of `pathology-editor.html` (extracted by regex from the file at test time) gives the same result as `zoneMatch.ts` on all 26 + edge labels. | LRN-026 recommendation; protects the editor until deletion. |
|
||||||
|
| Catalog copies parity | `src/.../pathologies.json` byte-equal to `public/species/equine/pathologies.json`. | Guards the dual-copy quirk until removal. |
|
||||||
|
| Catalog invariants | `zone.id === key`, 26 zones, category ids per zone, `requires_vet_referral` only on leaves, the `ssb-dysfunctions` under `sphenoid` anomaly asserted as *known* (so a fix is a deliberate change). | Importer normalisations are tested against these facts. |
|
||||||
|
| Full PDF roundtrip | Export a report with: a plain zone, a bilateral zone both sides, a spine zone with vertebrae, a detail zone, findings with vet flag, free text, severity, comment, conclusion, next appointment; `rasterizeSvg` real under happy-dom or stubbed deterministically; re-import; deep-equal. Then extract page text and assert the `ZONES`, `CONSTATS — <ZONE>`, `(Gauche)`, `(C3, C4)`, `(!)` strings. | Current roundtrip uses `observations: []` (audit 13 §4). The PDF step rewrites the pipeline. |
|
||||||
|
| Attachment fallback | `traverseForJsonAttachment` on a PDF whose attachment was re-saved by another tool. | Untested path handling user data. |
|
||||||
|
| Golden fixtures | `tests/fixtures/report-v2.full.json` (the report above) + `report-v2.minimal.json`, frozen. | Inputs for the `v2ToV3` adapter tests. |
|
||||||
|
| Orphan findings | removing a zone / pruning a region leaves findings; assert current behaviour. | Migration decides to keep or clean (I4). |
|
||||||
|
| Species registry | `getAllSpecies()` returns only equine; `AnimalForm` default `'equine'`. | Replaced by DB species; test is deleted with the registry. |
|
||||||
|
|
||||||
|
Target after Step 1: roughly 230–250 cases, all current ones untouched.
|
||||||
|
|
||||||
|
## 3. Tests per future domain (what each step must ship)
|
||||||
|
|
||||||
|
| Domain | Unit | DB / RLS | Integration / e2e |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Identity | profile form validation, role helpers in TS mirrors | `is_platform_*`, profile trigger, roles RPC denies self-grant | sign-up, verify email, login, logout |
|
||||||
|
| Verification | status machine | expiry trigger, reviewer-only transitions | upload document → pending → admin verifies |
|
||||||
|
| Organizations | none | membership RPC, secretary cannot become practitioner, seat exclusivity | create cabinet, invite, switch context |
|
||||||
|
| Clients / Animals | normalisation of contacts, consent payloads | `can_view_client/animal`, grants expiry/revocation, candidate match reveals nothing cross-tenant | create client+animal, share with another practitioner via consent flow |
|
||||||
|
| Anatomical Sheets | document Zod, importer special cases (audit 07 list), renderer attribute emission, GC preconditions in TS mirror | immutability trigger, numbering, `can_use_sheet`/`can_fork_sheet`, GC function with each precondition | seed equine v1, open it in the editor read-only |
|
||||||
|
| Reports | document v3, `v2ToV3`, zone interaction service, autosave throttling, outbox | numbering concurrency, completion + quota (5th ok, 6th denied, deleted counts, import counts), `free_edit_until`, revisions on checkpoints, restore | create → autosave → complete → PDF → reopen; offline edit → reconnect → conflict revision |
|
||||||
|
| PDF | golden text, attachment v3, snapshot sufficiency (render with the sheet row deleted) | none | export, download, import into another account denied |
|
||||||
|
| Editor merge | one test per legacy operation (audit 03 §2, 05 §3.5), create detail view geometry | publish creates v2, v1 reports still render | annotate, publish, use in a report |
|
||||||
|
| Community | none | follow grants use, unfollow revokes, private needs grant, fork provenance, moderation roles | discover, follow, fork |
|
||||||
|
| Booking / Travel / Calendar | expiry rule function (48/24/1h) as pure TS mirror and SQL, availability engine with provider mock | slot lock under concurrent requests, one pending per client | public booking → practitioner confirms → reminder queued |
|
||||||
|
| Billing | entitlement derivation, referral rules | `get_effective_entitlements`, Stripe webhook idempotency | checkout in Stripe test mode |
|
||||||
|
| Imports | adapters on sample files, duplicate detection | atomic commit, quota preflight | CSV import preview → confirm |
|
||||||
|
| Admin / Audit | none | append-only, impersonation expiry | admin MFA required |
|
||||||
|
| Hardening | header checks, dependency audit | full RLS matrix, storage policy matrix | cross-tenant scenarios (architecture Prompt 10) |
|
||||||
|
|
||||||
|
## 4. Fixtures and data
|
||||||
|
|
||||||
|
- Real equine SVGs and catalog are the primary fixtures for anatomy tests;
|
||||||
|
they are never edited (CLAUDE.md). Synthetic small SVGs cover error paths.
|
||||||
|
- `supabase/seed/test/` provides two practitioners, one cabinet, two clients,
|
||||||
|
three animals, the official sheet, one personal sheet, reports in each
|
||||||
|
status. RLS tests reuse it.
|
||||||
|
- Golden PDFs are compared by extracted text and attachment JSON, not by
|
||||||
|
bytes (pdf-lib dates and ids vary); raster hash only on fixed-size inputs.
|
||||||
|
|
||||||
|
## 5. CI gates
|
||||||
|
|
||||||
|
Per PR: `pnpm typecheck`, `pnpm lint` (0 warnings), `pnpm test:run`,
|
||||||
|
`pnpm build`; when `supabase/` changes: `supabase db reset`, `supabase test
|
||||||
|
db`, types diff. Nightly: Playwright suite. Release: full RLS matrix,
|
||||||
|
backup/restore rehearsal checklist, `pnpm audit`, secret scan.
|
||||||
|
|
||||||
|
## 6. Numbers to track
|
||||||
|
|
||||||
|
Test count per step and a "legacy tests deleted" count, so that deletions are
|
||||||
|
deliberate (each deleted test names the replacing test in its commit).
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,738 +0,0 @@
|
|||||||
# Laterality Support Implementation Plan
|
|
||||||
|
|
||||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
||||||
|
|
||||||
**Goal:** Add bilateral/unpaired laterality to anatomical zones so practitioners can specify left/right side on bilateral structures.
|
|
||||||
|
|
||||||
**Architecture:** New `data-anno-lateral` SVG attribute parsed into `Bone.lateral`. New `side` field on `ObservationZone` schema. LateralityPicker modal triggered on bilateral zone clicks. Side displayed in zone badges and PDF output. SVG editor gets a laterality dropdown.
|
|
||||||
|
|
||||||
**Tech Stack:** React 19, TypeScript strict, Zustand 5, Zod 3, Tailwind v4, pdf-lib, vitest
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 1: Schema + Bone Type — Add `side` to ObservationZone and `lateral` to Bone
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/domain/schema/observation.ts`
|
|
||||||
- Modify: `src/anatomy/types.ts`
|
|
||||||
- Test: `tests/unit/schema.observation.test.ts`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Write failing tests for LateralSideSchema and side field**
|
|
||||||
|
|
||||||
Add to `tests/unit/schema.observation.test.ts`:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import {
|
|
||||||
ObservationSchema,
|
|
||||||
ObservationZoneSchema,
|
|
||||||
LateralSideSchema,
|
|
||||||
VertebraSchema,
|
|
||||||
SeveritySchema,
|
|
||||||
FindingSchema,
|
|
||||||
} from '@/domain/schema/observation'
|
|
||||||
|
|
||||||
describe('LateralSideSchema', () => {
|
|
||||||
it('accepts left and right', () => {
|
|
||||||
expect(LateralSideSchema.parse('left')).toBe('left')
|
|
||||||
expect(LateralSideSchema.parse('right')).toBe('right')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('rejects unknown side', () => {
|
|
||||||
expect(() => LateralSideSchema.parse('both')).toThrow()
|
|
||||||
expect(() => LateralSideSchema.parse('')).toThrow()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('ObservationZoneSchema with side', () => {
|
|
||||||
it('accepts a zone without side (unpaired)', () => {
|
|
||||||
expect(() => ObservationZoneSchema.parse({ boneId: 'sternum' })).not.toThrow()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('accepts a zone with side left', () => {
|
|
||||||
const parsed = ObservationZoneSchema.parse({ boneId: 'knee', side: 'left' })
|
|
||||||
expect(parsed.side).toBe('left')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('accepts a zone with side right', () => {
|
|
||||||
const parsed = ObservationZoneSchema.parse({ boneId: 'knee', side: 'right' })
|
|
||||||
expect(parsed.side).toBe('right')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('accepts two zones with same boneId but different sides', () => {
|
|
||||||
const obs = {
|
|
||||||
id: 'obs-1',
|
|
||||||
zones: [
|
|
||||||
{ boneId: 'knee', side: 'left' },
|
|
||||||
{ boneId: 'knee', side: 'right' },
|
|
||||||
],
|
|
||||||
findings: [],
|
|
||||||
freeTextFindings: [],
|
|
||||||
comment: '',
|
|
||||||
}
|
|
||||||
expect(() => ObservationSchema.parse(obs)).not.toThrow()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run tests to verify they fail**
|
|
||||||
|
|
||||||
Run: `pnpm test:run -- tests/unit/schema.observation.test.ts`
|
|
||||||
Expected: FAIL — `LateralSideSchema` is not exported
|
|
||||||
|
|
||||||
- [ ] **Step 3: Add LateralSideSchema and side field to observation.ts**
|
|
||||||
|
|
||||||
In `src/domain/schema/observation.ts`, add after the `VertebraSchema` definition:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export const LateralSideSchema = z.enum(['left', 'right'])
|
|
||||||
|
|
||||||
export type LateralSide = z.infer<typeof LateralSideSchema>
|
|
||||||
```
|
|
||||||
|
|
||||||
Add `side` to `ObservationZoneSchema`:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export const ObservationZoneSchema = z.object({
|
|
||||||
boneId: z.string().min(1),
|
|
||||||
detailSourceId: z.string().optional(),
|
|
||||||
vertebrae: z.array(VertebraSchema).optional(),
|
|
||||||
side: LateralSideSchema.optional(),
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 4: Add `lateral` field to Bone interface**
|
|
||||||
|
|
||||||
In `src/anatomy/types.ts`, add to `Bone` interface after `special?`:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
lateral?: 'bilateral' | 'unpaired'
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 5: Run tests to verify they pass**
|
|
||||||
|
|
||||||
Run: `pnpm test:run -- tests/unit/schema.observation.test.ts`
|
|
||||||
Expected: ALL PASS
|
|
||||||
|
|
||||||
- [ ] **Step 6: Run full typecheck**
|
|
||||||
|
|
||||||
Run: `pnpm typecheck`
|
|
||||||
Expected: No errors
|
|
||||||
|
|
||||||
- [ ] **Step 7: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/domain/schema/observation.ts src/anatomy/types.ts tests/unit/schema.observation.test.ts
|
|
||||||
git commit -m "feat(schema): add LateralSideSchema and Bone.lateral for laterality support"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 2: SVG Parser — Read `data-anno-lateral` attribute
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/anatomy/svgConvention.ts`
|
|
||||||
- Test: `tests/unit/anatomy.svgConvention.test.ts`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Write failing tests for lateral parsing**
|
|
||||||
|
|
||||||
Add to `tests/unit/anatomy.svgConvention.test.ts`, update the `FIXTURE` and add tests:
|
|
||||||
|
|
||||||
Update `FIXTURE` — add a bilateral element:
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<circle data-anno-id="point-knee" data-anno-name-fr="Genou" data-anno-name-en="Knee"
|
|
||||||
data-anno-category="articulations" data-anno-lateral="bilateral" />
|
|
||||||
```
|
|
||||||
|
|
||||||
Add tests:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
it('captures data-anno-lateral when present', () => {
|
|
||||||
const map = parseSvgBones(svgFromString(FIXTURE))
|
|
||||||
expect(map.get('point-knee')?.lateral).toBe('bilateral')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('leaves lateral undefined when attribute absent', () => {
|
|
||||||
const map = parseSvgBones(svgFromString(FIXTURE))
|
|
||||||
expect(map.get('point-shoulder')?.lateral).toBeUndefined()
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run tests to verify they fail**
|
|
||||||
|
|
||||||
Run: `pnpm test:run -- tests/unit/anatomy.svgConvention.test.ts`
|
|
||||||
Expected: FAIL — `lateral` is undefined for knee
|
|
||||||
|
|
||||||
- [ ] **Step 3: Update parseSvgBones to read data-anno-lateral**
|
|
||||||
|
|
||||||
In `src/anatomy/svgConvention.ts`, in `parseSvgBones()`, add after the `special` read:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const lateral = el.getAttribute('data-anno-lateral') as
|
|
||||||
| 'bilateral'
|
|
||||||
| 'unpaired'
|
|
||||||
| undefined ?? undefined
|
|
||||||
```
|
|
||||||
|
|
||||||
In the `else` branch (new Bone creation), add `lateral` to the object:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
map.set(id, {
|
|
||||||
id,
|
|
||||||
fr,
|
|
||||||
en,
|
|
||||||
category,
|
|
||||||
opensDetail,
|
|
||||||
special,
|
|
||||||
lateral,
|
|
||||||
els: [el],
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
In the `existing` merge branch, add:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
if (lateral && !existing.lateral) {
|
|
||||||
existing.lateral = lateral
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 4: Run tests to verify they pass**
|
|
||||||
|
|
||||||
Run: `pnpm test:run -- tests/unit/anatomy.svgConvention.test.ts`
|
|
||||||
Expected: ALL PASS
|
|
||||||
|
|
||||||
- [ ] **Step 5: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/anatomy/svgConvention.ts tests/unit/anatomy.svgConvention.test.ts
|
|
||||||
git commit -m "feat(anatomy): parse data-anno-lateral attribute from SVG"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 3: i18n — Add laterality translation keys
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/i18n/fr.ts`
|
|
||||||
- Modify: `src/i18n/en.ts`
|
|
||||||
- Test: `tests/unit/i18n.dicts.test.ts` (existing test verifies key parity)
|
|
||||||
|
|
||||||
- [ ] **Step 1: Add keys to fr.ts**
|
|
||||||
|
|
||||||
Add after the vertebra section in `src/i18n/fr.ts`:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
// laterality
|
|
||||||
'lateral.which_side': 'Quel côté ?',
|
|
||||||
'lateral.left': 'Gauche',
|
|
||||||
'lateral.right': 'Droite',
|
|
||||||
'lateral.both': 'Les deux',
|
|
||||||
'lateral.left_short': 'G',
|
|
||||||
'lateral.right_short': 'D',
|
|
||||||
'lateral.bilateral': 'Bilatéral',
|
|
||||||
'lateral.unpaired': 'Impair',
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Add keys to en.ts**
|
|
||||||
|
|
||||||
Add after the vertebra section in `src/i18n/en.ts`:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
// laterality
|
|
||||||
'lateral.which_side': 'Which side?',
|
|
||||||
'lateral.left': 'Left',
|
|
||||||
'lateral.right': 'Right',
|
|
||||||
'lateral.both': 'Both',
|
|
||||||
'lateral.left_short': 'L',
|
|
||||||
'lateral.right_short': 'R',
|
|
||||||
'lateral.bilateral': 'Bilateral',
|
|
||||||
'lateral.unpaired': 'Unpaired',
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: Run i18n key parity test**
|
|
||||||
|
|
||||||
Run: `pnpm test:run -- tests/unit/i18n.dicts.test.ts`
|
|
||||||
Expected: PASS (both dicts have same keys)
|
|
||||||
|
|
||||||
- [ ] **Step 4: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/i18n/fr.ts src/i18n/en.ts
|
|
||||||
git commit -m "feat(i18n): add laterality translation keys (FR/EN)"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 4: LateralityPicker Component
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Create: `src/components/observation/LateralityPicker.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Create LateralityPicker component**
|
|
||||||
|
|
||||||
Create `src/components/observation/LateralityPicker.tsx`:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import Dialog from '@/components/ui/Dialog'
|
|
||||||
import Button from '@/components/ui/Button'
|
|
||||||
import type { LateralSide } from '@/domain/schema/observation'
|
|
||||||
import { useT } from '@/i18n/useT'
|
|
||||||
|
|
||||||
export interface LateralityPickerProps {
|
|
||||||
open: boolean
|
|
||||||
onClose: () => void
|
|
||||||
onSelect: (sides: LateralSide[]) => void
|
|
||||||
title: string
|
|
||||||
/** Sides already present in the active observation for this boneId. */
|
|
||||||
existingSides: LateralSide[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function LateralityPicker({
|
|
||||||
open,
|
|
||||||
onClose,
|
|
||||||
onSelect,
|
|
||||||
title,
|
|
||||||
existingSides,
|
|
||||||
}: LateralityPickerProps) {
|
|
||||||
const t = useT()
|
|
||||||
const hasLeft = existingSides.includes('left')
|
|
||||||
const hasRight = existingSides.includes('right')
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog open={open} onClose={onClose} title={title} size="sm">
|
|
||||||
<div className="space-y-4">
|
|
||||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
|
||||||
{t('lateral.which_side')}
|
|
||||||
</p>
|
|
||||||
<div className="flex gap-3 justify-center">
|
|
||||||
<Button
|
|
||||||
variant={hasLeft ? 'ghost' : 'default'}
|
|
||||||
disabled={hasLeft}
|
|
||||||
onClick={() => onSelect(['left'])}
|
|
||||||
>
|
|
||||||
{t('lateral.left')}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={hasRight ? 'ghost' : 'default'}
|
|
||||||
disabled={hasRight}
|
|
||||||
onClick={() => onSelect(['right'])}
|
|
||||||
>
|
|
||||||
{t('lateral.right')}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={hasLeft && hasRight ? 'ghost' : 'default'}
|
|
||||||
disabled={hasLeft && hasRight}
|
|
||||||
onClick={() => {
|
|
||||||
const sides: LateralSide[] = []
|
|
||||||
if (!hasLeft) sides.push('left')
|
|
||||||
if (!hasRight) sides.push('right')
|
|
||||||
onSelect(sides)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t('lateral.both')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Dialog>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run typecheck**
|
|
||||||
|
|
||||||
Run: `pnpm typecheck`
|
|
||||||
Expected: No errors
|
|
||||||
|
|
||||||
- [ ] **Step 3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/components/observation/LateralityPicker.tsx
|
|
||||||
git commit -m "feat(ui): add LateralityPicker modal component"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 5: EditorRoute — Integrate LateralityPicker into zone click flow
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/app/routes/EditorRoute.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Add laterality state and imports**
|
|
||||||
|
|
||||||
Add imports at top of `EditorRoute.tsx`:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import LateralityPicker from '@/components/observation/LateralityPicker'
|
|
||||||
import type { LateralSide } from '@/domain/schema/observation'
|
|
||||||
```
|
|
||||||
|
|
||||||
Add state after `vertebraTarget` state:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const [lateralTarget, setLateralTarget] = useState<{
|
|
||||||
boneId: string
|
|
||||||
detailSourceId?: string
|
|
||||||
} | null>(null)
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Modify onZoneClick to handle bilateral zones**
|
|
||||||
|
|
||||||
In `onZoneClick()`, after the `vertebral-precision` block and before the unpaired toggle logic, add:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
if (bone.lateral === 'bilateral') {
|
|
||||||
setLateralTarget({
|
|
||||||
boneId,
|
|
||||||
...(detailSourceId ? { detailSourceId } : {}),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: Add LateralityPicker to JSX**
|
|
||||||
|
|
||||||
Add before the closing `</main>` tag, after the VertebraPicker block:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
{lateralTarget && activeObs && (
|
|
||||||
<LateralityPicker
|
|
||||||
open
|
|
||||||
onClose={() => setLateralTarget(null)}
|
|
||||||
title={boneLabel(
|
|
||||||
allBones.get(lateralTarget.boneId),
|
|
||||||
locale,
|
|
||||||
lateralTarget.boneId,
|
|
||||||
)}
|
|
||||||
existingSides={
|
|
||||||
activeObs.zones
|
|
||||||
.filter(
|
|
||||||
(z) =>
|
|
||||||
z.boneId === lateralTarget.boneId &&
|
|
||||||
z.detailSourceId === lateralTarget.detailSourceId &&
|
|
||||||
z.side,
|
|
||||||
)
|
|
||||||
.map((z) => z.side!) as LateralSide[]
|
|
||||||
}
|
|
||||||
onSelect={(sides) => {
|
|
||||||
const fresh =
|
|
||||||
useReportStore.getState().report?.observations[activeIndex]
|
|
||||||
if (!fresh) {
|
|
||||||
setLateralTarget(null)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
let nextZones = [...fresh.zones]
|
|
||||||
for (const side of sides) {
|
|
||||||
const exists = nextZones.some(
|
|
||||||
(z) =>
|
|
||||||
z.boneId === lateralTarget.boneId &&
|
|
||||||
z.detailSourceId === lateralTarget.detailSourceId &&
|
|
||||||
z.side === side,
|
|
||||||
)
|
|
||||||
if (!exists) {
|
|
||||||
nextZones.push({
|
|
||||||
boneId: lateralTarget.boneId,
|
|
||||||
...(lateralTarget.detailSourceId
|
|
||||||
? { detailSourceId: lateralTarget.detailSourceId }
|
|
||||||
: {}),
|
|
||||||
side,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
updateObservation(activeIndex, { ...fresh, zones: nextZones })
|
|
||||||
setLateralTarget(null)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 4: Handle re-click toggle for bilateral zones**
|
|
||||||
|
|
||||||
The current flow in `onZoneClick` for the bilateral case:
|
|
||||||
- If both sides already exist → remove both (toggle off)
|
|
||||||
- If one or zero sides → open picker
|
|
||||||
|
|
||||||
Update the bilateral block:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
if (bone.lateral === 'bilateral') {
|
|
||||||
const sidesPresent = activeObs.zones
|
|
||||||
.filter(
|
|
||||||
(z) =>
|
|
||||||
z.boneId === boneId &&
|
|
||||||
z.detailSourceId === detailSourceId,
|
|
||||||
)
|
|
||||||
.map((z) => z.side)
|
|
||||||
.filter(Boolean) as LateralSide[]
|
|
||||||
|
|
||||||
if (sidesPresent.includes('left') && sidesPresent.includes('right')) {
|
|
||||||
const nextZones = activeObs.zones.filter(
|
|
||||||
(z) =>
|
|
||||||
!(z.boneId === boneId && z.detailSourceId === detailSourceId),
|
|
||||||
)
|
|
||||||
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setLateralTarget({
|
|
||||||
boneId,
|
|
||||||
...(detailSourceId ? { detailSourceId } : {}),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 5: Run typecheck**
|
|
||||||
|
|
||||||
Run: `pnpm typecheck`
|
|
||||||
Expected: No errors
|
|
||||||
|
|
||||||
- [ ] **Step 6: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/app/routes/EditorRoute.tsx
|
|
||||||
git commit -m "feat(editor): integrate LateralityPicker in zone click flow"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 6: ObservationCard — Display side in zone badges
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/components/observation/ObservationCard.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Update describeZone to show side suffix**
|
|
||||||
|
|
||||||
In `ObservationCard.tsx`, update the `describeZone` function:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
function describeZone(
|
|
||||||
z: ObservationZone,
|
|
||||||
bones: Map<string, Bone>,
|
|
||||||
locale: Locale,
|
|
||||||
t: (key: string) => string,
|
|
||||||
): string {
|
|
||||||
const label = boneLabel(bones.get(z.boneId), locale, z.boneId)
|
|
||||||
if (z.vertebrae?.length) {
|
|
||||||
const vs = z.vertebrae
|
|
||||||
.map((v: Vertebra) => `${v.region}${v.index}`)
|
|
||||||
.join(', ')
|
|
||||||
return `${label} (${vs})`
|
|
||||||
}
|
|
||||||
if (z.side) {
|
|
||||||
const sideLabel = t(
|
|
||||||
z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short',
|
|
||||||
)
|
|
||||||
return `${label} (${sideLabel})`
|
|
||||||
}
|
|
||||||
return label
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Update describeZone call sites to pass t**
|
|
||||||
|
|
||||||
In the JSX, update the two places `describeZone` is called:
|
|
||||||
|
|
||||||
In the zone badges list:
|
|
||||||
```tsx
|
|
||||||
{describeZone(z, bones, locale, t)}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: Run typecheck**
|
|
||||||
|
|
||||||
Run: `pnpm typecheck`
|
|
||||||
Expected: No errors
|
|
||||||
|
|
||||||
- [ ] **Step 4: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/components/observation/ObservationCard.tsx
|
|
||||||
git commit -m "feat(ui): display laterality side in zone badges"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 7: PDF Output — Include side in zone labels
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/pdf/render/observationPage.ts`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Update zone label rendering**
|
|
||||||
|
|
||||||
In `addObservationPage()`, find the `zonesText` construction (around line 369-379). Update to include side:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const zonesText = observation.zones
|
|
||||||
.map((z) => {
|
|
||||||
const pair = zoneLabels.get(z.boneId)
|
|
||||||
const label = pair
|
|
||||||
? (locale === 'en' ? pair.en || pair.fr : pair.fr || pair.en) || z.boneId
|
|
||||||
: z.boneId
|
|
||||||
const v = z.vertebrae?.length
|
|
||||||
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
|
|
||||||
: ''
|
|
||||||
const side = z.side
|
|
||||||
? ` (${dict[z.side === 'left' ? 'lateral.left' : 'lateral.right']})`
|
|
||||||
: ''
|
|
||||||
return `${label}${v}${side}`
|
|
||||||
})
|
|
||||||
.join(' · ')
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run typecheck**
|
|
||||||
|
|
||||||
Run: `pnpm typecheck`
|
|
||||||
Expected: No errors
|
|
||||||
|
|
||||||
- [ ] **Step 3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/pdf/render/observationPage.ts
|
|
||||||
git commit -m "feat(pdf): include laterality side in zone labels"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 8: SVG Editor — Add laterality dropdown
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/app/routes/SvgEditorRoute.tsx`
|
|
||||||
- Modify: `src/i18n/fr.ts`
|
|
||||||
- Modify: `src/i18n/en.ts`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Add SVG editor i18n keys**
|
|
||||||
|
|
||||||
In `src/i18n/fr.ts`, add:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
'svg_editor.lateral': 'Latéralité',
|
|
||||||
'svg_editor.lateral_unpaired': 'Impair (pas de côté)',
|
|
||||||
'svg_editor.lateral_bilateral': 'Bilatéral (gauche / droite)',
|
|
||||||
```
|
|
||||||
|
|
||||||
In `src/i18n/en.ts`, add:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
'svg_editor.lateral': 'Laterality',
|
|
||||||
'svg_editor.lateral_unpaired': 'Unpaired (no side)',
|
|
||||||
'svg_editor.lateral_bilateral': 'Bilateral (left / right)',
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Add dropdown to SvgEditorRoute JSX**
|
|
||||||
|
|
||||||
In `SvgEditorRoute.tsx`, inside the `svg-editor-osteo-fields` div, after the category `<select>`, add:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<label>{t('svg_editor.lateral')}</label>
|
|
||||||
<select id="svg-editor-edit-lateral">
|
|
||||||
<option value="">{t('svg_editor.lateral_unpaired')}</option>
|
|
||||||
<option value="bilateral">{t('svg_editor.lateral_bilateral')}</option>
|
|
||||||
</select>
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: Wire up event listener in initSvgEditor**
|
|
||||||
|
|
||||||
In `setupGlobalListeners()`, add the lateral select to the change listener array:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
;['svg-editor-edit-fr', 'svg-editor-edit-en', 'svg-editor-edit-category', 'svg-editor-edit-lateral'].forEach(
|
|
||||||
(id) => {
|
|
||||||
getEl(id).addEventListener('change', applyEdit, sig)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 4: Read lateral in showEditPanel**
|
|
||||||
|
|
||||||
In `showEditPanel()`, after reading category, add:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
;(getEl('svg-editor-edit-lateral') as HTMLSelectElement).value =
|
|
||||||
svgEl.getAttribute('data-anno-lateral') || ''
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 5: Write lateral in applyEdit**
|
|
||||||
|
|
||||||
In `applyEdit()`, after reading `cat`, add:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const lateral = (getEl('svg-editor-edit-lateral') as HTMLSelectElement).value
|
|
||||||
```
|
|
||||||
|
|
||||||
In the siblings loop, inside the non-opens-detail branch (where `data-anno-name-fr` etc. are set), add after the special attribute logic:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
if (lateral) {
|
|
||||||
s.setAttribute('data-anno-lateral', lateral)
|
|
||||||
} else {
|
|
||||||
s.removeAttribute('data-anno-lateral')
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 6: Propagate lateral when creating new elements**
|
|
||||||
|
|
||||||
In `addCircleAt()`, after setting `data-anno-special` on both `hit` and `vis`, add for each:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
if (CATEGORIES[cat]?.lateral) hit.setAttribute('data-anno-lateral', CATEGORIES[cat].lateral!)
|
|
||||||
```
|
|
||||||
|
|
||||||
Wait — categories don't carry lateral. Lateral is per-element, not per-category. New elements start as unpaired (no attribute). The user sets it via the edit panel. No change needed for addCircleAt/finalizePolygon.
|
|
||||||
|
|
||||||
- [ ] **Step 7: Run typecheck and i18n test**
|
|
||||||
|
|
||||||
Run: `pnpm typecheck && pnpm test:run -- tests/unit/i18n.dicts.test.ts`
|
|
||||||
Expected: No errors, i18n parity PASS
|
|
||||||
|
|
||||||
- [ ] **Step 8: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/app/routes/SvgEditorRoute.tsx src/i18n/fr.ts src/i18n/en.ts
|
|
||||||
git commit -m "feat(editor): add laterality dropdown to SVG editor"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 9: Documentation — Update ANATOMY-SVG-CONVENTION.md
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `docs/ANATOMY-SVG-CONVENTION.md`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Add data-anno-lateral to optional attributes table**
|
|
||||||
|
|
||||||
In the "Optional data attributes" table, add a row:
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
| `data-anno-lateral` | `string` | Laterality hint: `bilateral` (zone has left/right instances, e.g. knee) or `unpaired` (no laterality). Default when absent: `unpaired`. Used by the report editor to prompt side selection on bilateral zones. |
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add docs/ANATOMY-SVG-CONVENTION.md
|
|
||||||
git commit -m "docs(anatomy): document data-anno-lateral attribute"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 10: Full Verification
|
|
||||||
|
|
||||||
- [ ] **Step 1: Run full test suite**
|
|
||||||
|
|
||||||
Run: `pnpm test:run`
|
|
||||||
Expected: ALL PASS
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run typecheck**
|
|
||||||
|
|
||||||
Run: `pnpm typecheck`
|
|
||||||
Expected: No errors
|
|
||||||
|
|
||||||
- [ ] **Step 3: Run lint**
|
|
||||||
|
|
||||||
Run: `pnpm lint`
|
|
||||||
Expected: No errors
|
|
||||||
|
|
||||||
- [ ] **Step 4: Build**
|
|
||||||
|
|
||||||
Run: `pnpm build`
|
|
||||||
Expected: Build succeeds
|
|
||||||
@@ -1,760 +0,0 @@
|
|||||||
# Responsive Mobile Fixes — Implementation Plan
|
|
||||||
|
|
||||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
||||||
|
|
||||||
**Goal:** Make Faunosteo SPA fully usable on phone screens (375px+) and polished on tablets (768px+) via surgical CSS/className-only changes.
|
|
||||||
|
|
||||||
**Architecture:** No behavior changes — pure Tailwind class and CSS media query updates across ~12 files. No store, schema, or PDF changes. Existing tests must stay green since only visual layout changes.
|
|
||||||
|
|
||||||
**Tech Stack:** Tailwind CSS v4 (CSS-first), React 19, existing component library
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 1: Dialog viewport clamping
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/components/ui/Dialog.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Update Dialog SIZE map and container classes**
|
|
||||||
|
|
||||||
In `src/components/ui/Dialog.tsx`, replace the SIZE constant and the dialog container/content classes:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
|
|
||||||
sm: 'max-w-sm',
|
|
||||||
md: 'max-w-md',
|
|
||||||
lg: 'max-w-2xl',
|
|
||||||
xl: 'max-w-4xl',
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
with:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
|
|
||||||
sm: 'max-w-sm max-w-[calc(100vw-2rem)]',
|
|
||||||
md: 'max-w-md max-w-[calc(100vw-2rem)]',
|
|
||||||
lg: 'max-w-2xl max-w-[calc(100vw-2rem)]',
|
|
||||||
xl: 'max-w-4xl max-w-[calc(100vw-2rem)]',
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Note: Tailwind applies the last matching utility — `max-w-[calc(100vw-2rem)]` wins on small screens where the named max-width exceeds viewport, and the named max-width wins on large screens where it's smaller. Actually, this won't work — Tailwind just uses specificity/order. Need a different approach.
|
|
||||||
|
|
||||||
Instead, add the viewport clamp directly on the motion.div alongside the SIZE class. Change:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
className={`relative w-full ${SIZE[size]} max-h-[90vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
|
|
||||||
```
|
|
||||||
|
|
||||||
And change the outer container padding from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4">
|
|
||||||
```
|
|
||||||
|
|
||||||
And change the dialog header padding from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<header className="flex items-center justify-between px-6 py-4 border-b border-[var(--color-border)]">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]">
|
|
||||||
```
|
|
||||||
|
|
||||||
And change the dialog body padding from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="px-6 py-4">{children}</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="px-4 sm:px-6 py-3 sm:py-4">{children}</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
The key fix: since all sizes already use `w-full` with `max-w-*`, the dialog box naturally fills available width minus padding. Reducing container padding from `p-4` to `p-3` on small screens gives 6px more breathing room per side. The `max-w-sm` (384px) fits within 375px - 24px = 351px viewport on phones (it doesn't — 384 > 351). The real fix is that `w-full` makes the dialog width = container width = viewport - 2*padding, so the max-w-* values are upper caps that only kick in when there's room.
|
|
||||||
|
|
||||||
Wait — `w-full` with `max-w-md` means the dialog takes min(100%, 448px). On a 375px phone with p-3 (12px each side), available width = 375 - 24 = 351px. `w-full` = 351px which is < 448px, so dialog = 351px. This already works correctly. No extra `max-w-[calc(...)]` needed. The existing `w-full` + `max-w-*` pattern is responsive by design.
|
|
||||||
|
|
||||||
So the actual changes are: tighten padding for mobile comfort + reduce max-h for better mobile viewport fit.
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run tests**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
|
|
||||||
Expected: All tests pass (no behavior change)
|
|
||||||
|
|
||||||
- [ ] **Step 3: Run typecheck**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm typecheck`
|
|
||||||
Expected: No errors
|
|
||||||
|
|
||||||
- [ ] **Step 4: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/components/ui/Dialog.tsx
|
|
||||||
git commit -m "fix(ui): responsive dialog — tighter mobile padding and max-height"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 2: Button touch targets
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/components/ui/Button.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Update SIZES to ensure mobile-friendly touch targets**
|
|
||||||
|
|
||||||
In `src/components/ui/Button.tsx`, change the SIZES constant from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
const SIZES: Record<NonNullable<ButtonProps['size']>, string> = {
|
|
||||||
sm: 'h-8 px-3 text-sm rounded-md',
|
|
||||||
md: 'h-10 px-4 text-base rounded-lg',
|
|
||||||
lg: 'h-12 px-6 text-base rounded-lg',
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
const SIZES: Record<NonNullable<ButtonProps['size']>, string> = {
|
|
||||||
sm: 'h-9 px-3 text-sm rounded-md',
|
|
||||||
md: 'h-10 px-4 text-sm sm:text-base rounded-lg',
|
|
||||||
lg: 'h-12 px-5 sm:px-6 text-base rounded-lg',
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Changes:
|
|
||||||
- `sm`: `h-8` → `h-9` (36px, closer to 44px minimum)
|
|
||||||
- `md`: add responsive text `text-sm sm:text-base`
|
|
||||||
- `lg`: tighter padding on mobile `px-5 sm:px-6`
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run tests**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
|
|
||||||
Expected: All tests pass
|
|
||||||
|
|
||||||
- [ ] **Step 3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/components/ui/Button.tsx
|
|
||||||
git commit -m "fix(ui): increase button sm touch target to 36px, responsive text sizing"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 3: VertebraPicker touch targets
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/components/observation/VertebraPicker.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Increase region tab touch targets**
|
|
||||||
|
|
||||||
In `src/components/observation/VertebraPicker.tsx`, change the region tab button className from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
'rounded-full px-4 py-1.5 text-sm font-medium border',
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
'rounded-full px-4 py-2.5 sm:py-1.5 text-sm font-medium border min-h-[2.75rem]',
|
|
||||||
```
|
|
||||||
|
|
||||||
This ensures 44px minimum height on mobile (py-2.5 = 10px top+bottom + text ≈ 44px), drops back to denser on desktop.
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run tests**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
|
|
||||||
Expected: All tests pass
|
|
||||||
|
|
||||||
- [ ] **Step 3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/components/observation/VertebraPicker.tsx
|
|
||||||
git commit -m "fix(ui): vertebra picker region tabs — 44px touch target on mobile"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 4: SVG editor sidebar responsive stacking
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/styles/svg-editor.css`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Add media query for sidebar stacking**
|
|
||||||
|
|
||||||
In `src/styles/svg-editor.css`, change the `.svg-editor-root` rule from:
|
|
||||||
|
|
||||||
```css
|
|
||||||
.svg-editor-root {
|
|
||||||
display: flex;
|
|
||||||
flex: 1;
|
|
||||||
min-height: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
font-family: var(--font-sans);
|
|
||||||
color: var(--color-ink);
|
|
||||||
background: var(--color-bg);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```css
|
|
||||||
.svg-editor-root {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
flex: 1;
|
|
||||||
min-height: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
font-family: var(--font-sans);
|
|
||||||
color: var(--color-ink);
|
|
||||||
background: var(--color-bg);
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (min-width: 768px) {
|
|
||||||
.svg-editor-root {
|
|
||||||
flex-direction: row;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Then change the `.svg-editor-sidebar` rule from:
|
|
||||||
|
|
||||||
```css
|
|
||||||
.svg-editor-sidebar {
|
|
||||||
width: 380px;
|
|
||||||
background: var(--color-surface);
|
|
||||||
border-left: 1px solid var(--color-border);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```css
|
|
||||||
.svg-editor-sidebar {
|
|
||||||
width: 100%;
|
|
||||||
background: var(--color-surface);
|
|
||||||
border-top: 1px solid var(--color-border);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
overflow: hidden;
|
|
||||||
max-height: 50vh;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (min-width: 768px) {
|
|
||||||
.svg-editor-sidebar {
|
|
||||||
width: 380px;
|
|
||||||
max-height: none;
|
|
||||||
border-top: none;
|
|
||||||
border-left: 1px solid var(--color-border);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Also update `.svg-editor-canvas` to ensure minimum usable height on mobile by changing:
|
|
||||||
|
|
||||||
```css
|
|
||||||
.svg-editor-canvas {
|
|
||||||
flex: 1;
|
|
||||||
position: relative;
|
|
||||||
background: var(--color-surface);
|
|
||||||
overflow: hidden;
|
|
||||||
padding: 10px;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```css
|
|
||||||
.svg-editor-canvas {
|
|
||||||
flex: 1;
|
|
||||||
position: relative;
|
|
||||||
background: var(--color-surface);
|
|
||||||
overflow: hidden;
|
|
||||||
padding: 10px;
|
|
||||||
min-height: 40vh;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (min-width: 768px) {
|
|
||||||
.svg-editor-canvas {
|
|
||||||
min-height: 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Also update the zoom controls for mobile — make buttons bigger:
|
|
||||||
|
|
||||||
```css
|
|
||||||
.svg-editor-zoom-controls button {
|
|
||||||
width: 32px;
|
|
||||||
height: 32px;
|
|
||||||
padding: 0;
|
|
||||||
margin: 0;
|
|
||||||
font-size: 16px;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```css
|
|
||||||
.svg-editor-zoom-controls button {
|
|
||||||
width: 40px;
|
|
||||||
height: 40px;
|
|
||||||
padding: 0;
|
|
||||||
margin: 0;
|
|
||||||
font-size: 18px;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (min-width: 768px) {
|
|
||||||
.svg-editor-zoom-controls button {
|
|
||||||
width: 32px;
|
|
||||||
height: 32px;
|
|
||||||
font-size: 16px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run typecheck and build**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm typecheck && ~/.local/share/pnpm/bin/pnpm build`
|
|
||||||
Expected: Clean
|
|
||||||
|
|
||||||
- [ ] **Step 3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/styles/svg-editor.css
|
|
||||||
git commit -m "fix(ui): SVG editor sidebar stacks below canvas on mobile (<768px)"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 5: AnatomyCanvas height constraint + EditorRoute responsive
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/components/canvas/AnatomyCanvas.tsx`
|
|
||||||
- Modify: `src/app/routes/EditorRoute.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Add responsive classes to AnatomyCanvas wrapper**
|
|
||||||
|
|
||||||
In `src/components/canvas/AnatomyCanvas.tsx`, change the wrapper div from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div
|
|
||||||
data-testid="anatomy-canvas"
|
|
||||||
ref={wrapperRef}
|
|
||||||
className={`svg-canvas relative w-full h-full ${className}`}
|
|
||||||
>
|
|
||||||
<div ref={svgRef} className="w-full h-full" />
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div
|
|
||||||
data-testid="anatomy-canvas"
|
|
||||||
ref={wrapperRef}
|
|
||||||
className={`svg-canvas relative w-full h-full ${className}`}
|
|
||||||
>
|
|
||||||
<div ref={svgRef} className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto" />
|
|
||||||
```
|
|
||||||
|
|
||||||
This ensures the SVG inside doesn't overflow and centers horizontally.
|
|
||||||
|
|
||||||
- [ ] **Step 2: Update EditorRoute grid layout for mobile**
|
|
||||||
|
|
||||||
In `src/app/routes/EditorRoute.tsx`, change the main grid container from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-6 p-6">
|
|
||||||
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
|
|
||||||
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none">
|
|
||||||
```
|
|
||||||
|
|
||||||
The `max-h-[55vh] lg:max-h-none` constrains the SVG canvas on mobile/tablet (single-column) so the observation list is visible without scrolling past the entire SVG. On desktop (lg+, two-column), it fills naturally.
|
|
||||||
|
|
||||||
Also change the observations section from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<section className="space-y-6">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<section className="space-y-4 sm:space-y-6">
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: Run tests**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
|
|
||||||
Expected: All tests pass
|
|
||||||
|
|
||||||
- [ ] **Step 4: Run typecheck**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm typecheck`
|
|
||||||
Expected: No errors
|
|
||||||
|
|
||||||
- [ ] **Step 5: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/components/canvas/AnatomyCanvas.tsx src/app/routes/EditorRoute.tsx
|
|
||||||
git commit -m "fix(ui): constrain anatomy canvas height on mobile, responsive editor spacing"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 6: Responsive typography and padding — HomeRoute + EditorsRoute
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/app/routes/HomeRoute.tsx`
|
|
||||||
- Modify: `src/app/routes/EditorsRoute.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Update HomeRoute**
|
|
||||||
|
|
||||||
In `src/app/routes/HomeRoute.tsx`, change:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<section className="flex-1 grid place-items-center px-6">
|
|
||||||
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
|
|
||||||
<Card className="p-6 space-y-4">
|
|
||||||
<h2 className="font-serif text-2xl">{t('home.new_report.title')}</h2>
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<section className="flex-1 grid place-items-center px-4 sm:px-6">
|
|
||||||
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
|
|
||||||
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
|
|
||||||
<h2 className="font-serif text-xl sm:text-2xl">{t('home.new_report.title')}</h2>
|
|
||||||
```
|
|
||||||
|
|
||||||
And the second card heading too:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<Card className="p-6 space-y-4">
|
|
||||||
<h2 className="font-serif text-2xl">{t('home.import.title')}</h2>
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
|
|
||||||
<h2 className="font-serif text-xl sm:text-2xl">{t('home.import.title')}</h2>
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Update EditorsRoute**
|
|
||||||
|
|
||||||
In `src/app/routes/EditorsRoute.tsx`, change:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<section className="flex-1 grid place-items-center px-6">
|
|
||||||
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
|
|
||||||
<Card className="p-6 space-y-4">
|
|
||||||
<h2 className="font-serif text-2xl">{t('editors.svg.title')}</h2>
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<section className="flex-1 grid place-items-center px-4 sm:px-6">
|
|
||||||
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
|
|
||||||
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
|
|
||||||
<h2 className="font-serif text-xl sm:text-2xl">{t('editors.svg.title')}</h2>
|
|
||||||
```
|
|
||||||
|
|
||||||
And the second card:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<Card className="p-6 space-y-4">
|
|
||||||
<h2 className="font-serif text-2xl">{t('editors.pathology.title')}</h2>
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
|
|
||||||
<h2 className="font-serif text-xl sm:text-2xl">{t('editors.pathology.title')}</h2>
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: Run tests**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
|
|
||||||
Expected: All tests pass
|
|
||||||
|
|
||||||
- [ ] **Step 4: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/app/routes/HomeRoute.tsx src/app/routes/EditorsRoute.tsx
|
|
||||||
git commit -m "fix(ui): responsive padding and typography on home and editors pages"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 7: Responsive typography and padding — NewReportRoute
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/app/routes/NewReportRoute.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Update NewReportRoute responsive classes**
|
|
||||||
|
|
||||||
In `src/app/routes/NewReportRoute.tsx`, change:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="max-w-3xl mx-auto px-6 py-8 space-y-8">
|
|
||||||
<h1 className="font-serif text-3xl">{t('new_report.title')}</h1>
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8">
|
|
||||||
<h1 className="font-serif text-2xl sm:text-3xl">{t('new_report.title')}</h1>
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run tests**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
|
|
||||||
Expected: All tests pass
|
|
||||||
|
|
||||||
- [ ] **Step 3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/app/routes/NewReportRoute.tsx
|
|
||||||
git commit -m "fix(ui): responsive padding and typography on new report page"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 8: Responsive typography — ObservationList + ConclusionPanel
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/components/observation/ObservationList.tsx`
|
|
||||||
- Modify: `src/components/report/ConclusionPanel.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Update ObservationList heading**
|
|
||||||
|
|
||||||
In `src/components/observation/ObservationList.tsx`, change:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<h2 className="font-serif text-xl text-[var(--color-ink)]">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<h2 className="font-serif text-lg sm:text-xl text-[var(--color-ink)]">
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Update ConclusionPanel heading**
|
|
||||||
|
|
||||||
In `src/components/report/ConclusionPanel.tsx`, change:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<h2 className="font-serif text-xl text-[var(--color-ink)]">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<h2 className="font-serif text-lg sm:text-xl text-[var(--color-ink)]">
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: Run tests**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
|
|
||||||
Expected: All tests pass
|
|
||||||
|
|
||||||
- [ ] **Step 4: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/components/observation/ObservationList.tsx src/components/report/ConclusionPanel.tsx
|
|
||||||
git commit -m "fix(ui): responsive typography for observation and conclusion headings"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 9: Footer and AppHeader mobile polish
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/components/brand/Footer.tsx`
|
|
||||||
- Modify: `src/components/brand/AppHeader.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Update Footer spacing**
|
|
||||||
|
|
||||||
In `src/components/brand/Footer.tsx`, change:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<footer className="mt-12 border-t border-neutral-200 bg-neutral-50 py-6 text-center text-sm text-neutral-600">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<footer className="mt-8 sm:mt-12 border-t border-neutral-200 bg-neutral-50 py-4 sm:py-6 text-center text-xs sm:text-sm text-neutral-600">
|
|
||||||
```
|
|
||||||
|
|
||||||
And the flex container from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="flex flex-wrap items-center justify-center gap-4">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="flex flex-wrap items-center justify-center gap-2 sm:gap-4">
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: Update AppHeader padding**
|
|
||||||
|
|
||||||
In `src/components/brand/AppHeader.tsx`, change:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<header className="px-6 py-3 border-b border-[var(--color-border)] flex items-center justify-between bg-[var(--color-surface)]">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<header className="px-3 sm:px-6 py-2 sm:py-3 border-b border-[var(--color-border)] flex items-center justify-between bg-[var(--color-surface)]">
|
|
||||||
```
|
|
||||||
|
|
||||||
And the right-side gap from:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="flex items-center gap-2 sm:gap-4">
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: Run tests**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
|
|
||||||
Expected: All tests pass
|
|
||||||
|
|
||||||
- [ ] **Step 4: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/components/brand/Footer.tsx src/components/brand/AppHeader.tsx
|
|
||||||
git commit -m "fix(ui): responsive footer and header spacing for mobile"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 10: ReportHeader mobile polish
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/components/report/ReportHeader.tsx`
|
|
||||||
|
|
||||||
- [ ] **Step 1: Make report info responsive on mobile**
|
|
||||||
|
|
||||||
In `src/components/report/ReportHeader.tsx`, change:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="text-sm text-right text-[var(--color-ink-muted)]">
|
|
||||||
<div className="text-[var(--color-ink)] font-medium">
|
|
||||||
{report.animal.name} · {report.owner.name}
|
|
||||||
</div>
|
|
||||||
<div>{formatDate(report.date, locale)}</div>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
to:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<div className="text-xs sm:text-sm text-right text-[var(--color-ink-muted)]">
|
|
||||||
<div className="text-[var(--color-ink)] font-medium truncate max-w-[10rem] sm:max-w-none">
|
|
||||||
{report.animal.name} · {report.owner.name}
|
|
||||||
</div>
|
|
||||||
<div className="hidden sm:block">{formatDate(report.date, locale)}</div>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
Changes:
|
|
||||||
- Smaller text on mobile (`text-xs sm:text-sm`)
|
|
||||||
- Truncate long names on narrow screens (`truncate max-w-[10rem]`)
|
|
||||||
- Hide date on very small screens (header is already tight)
|
|
||||||
|
|
||||||
- [ ] **Step 2: Run tests**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
|
|
||||||
Expected: All tests pass
|
|
||||||
|
|
||||||
- [ ] **Step 3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/components/report/ReportHeader.tsx
|
|
||||||
git commit -m "fix(ui): responsive report header — compact on mobile"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 11: Final verification
|
|
||||||
|
|
||||||
- [ ] **Step 1: Run full verification suite**
|
|
||||||
|
|
||||||
Run:
|
|
||||||
```bash
|
|
||||||
cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm typecheck && ~/.local/share/pnpm/bin/pnpm test:run && ~/.local/share/pnpm/bin/pnpm lint && ~/.local/share/pnpm/bin/pnpm build
|
|
||||||
```
|
|
||||||
|
|
||||||
Expected: All clean — typecheck, tests, lint (0 warnings), build success.
|
|
||||||
|
|
||||||
- [ ] **Step 2: Dev server visual check**
|
|
||||||
|
|
||||||
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm dev`
|
|
||||||
|
|
||||||
Open in browser, test at:
|
|
||||||
- 375px width (iPhone SE): all pages, editor, dialogs
|
|
||||||
- 768px width (iPad): editor two-panel, SVG editor with sidebar
|
|
||||||
- 1280px width (desktop): no regressions
|
|
||||||
|
|
||||||
Check:
|
|
||||||
- No horizontal overflow on any page at 375px
|
|
||||||
- Dialogs fit within viewport
|
|
||||||
- SVG editor sidebar stacks below canvas at <768px
|
|
||||||
- AnatomyCanvas constrained in height on single-column layout
|
|
||||||
- All buttons tappable (no tiny targets)
|
|
||||||
- Typography scales appropriately
|
|
||||||
- Footer wraps cleanly
|
|
||||||
|
|
||||||
- [ ] **Step 3: Stop dev server**
|
|
||||||
@@ -1,378 +0,0 @@
|
|||||||
# Osteo Report — MVP Architecture Spec
|
|
||||||
|
|
||||||
Date: 2026-05-18
|
|
||||||
Status: Approved at validation gate #1.
|
|
||||||
|
|
||||||
## Purpose
|
|
||||||
|
|
||||||
Web app for veterinary osteopaths — any praticien who wants to use it — to
|
|
||||||
write session bilans on animal anatomy. The praticien selects a species,
|
|
||||||
clicks anatomical zones on an SVG schematic to build clinical observations
|
|
||||||
(groups of zones sharing one problem), attaches pathologies (curated DB +
|
|
||||||
free-text) and severity per observation, writes a conclusion +
|
|
||||||
recommendations + next RDV, and exports the whole report as a self-contained
|
|
||||||
A4 PDF whose JSON state is carried as a native PDF attachment. Re-importing
|
|
||||||
the PDF restores the state for a follow-up.
|
|
||||||
|
|
||||||
Multi-species by architecture. v1 ships data for the **horse** (équin) only.
|
|
||||||
Adding **dog, cat, goat, cow, pig, rabbit, donkey, sheep** later is a pure
|
|
||||||
data drop: convention-compliant SVG + manifest entry + (eventually)
|
|
||||||
pathology file under `src/domain/species/<id>/`. No code changes required.
|
|
||||||
|
|
||||||
Static SPA, no backend, no auth, no analytics in v1 — the PDF is the only
|
|
||||||
durable artifact. Deployed as a Docker image serving nginx behind a host
|
|
||||||
nginx reverse proxy on Scaleway VPS. Identity strings (site name, brand,
|
|
||||||
footer) come from env vars, never hardcoded. Open-source (MIT).
|
|
||||||
|
|
||||||
v1 data set: equine. v1.1+ data sets: chien, chat, chèvre, vache, cochon,
|
|
||||||
lapin, âne, mouton. Phase 2 also adds multi-praticien accounts +
|
|
||||||
server-side persistence on the same data contract.
|
|
||||||
|
|
||||||
## Stack
|
|
||||||
|
|
||||||
| Concern | Choice | Why |
|
|
||||||
|---|---|---|
|
|
||||||
| Build | Vite 7 + @vitejs/plugin-react-swc | Fast HMR, ESM-native, no Webpack tax. |
|
|
||||||
| UI | React 19 + TypeScript 5 strict | Editor complexity warrants components; React 19's automatic memo + concurrent rendering. |
|
|
||||||
| Styling | Tailwind v4 (CSS-first config) + design tokens in CSS | No PostCSS config, design tokens via @theme. |
|
|
||||||
| State | Zustand 5 | Lighter than Redux, simpler than Context for editor; selectors avoid re-render storms. |
|
|
||||||
| Validation | Zod 3 | Mirrors persisted JSON schema, gives import-time errors. |
|
|
||||||
| PDF | pdf-lib 1.17 | Pure-JS, supports native PDF attachments via `attach()`. |
|
|
||||||
| SVG raster | canvg 4 → canvas → PNG → `embedPng` | A4 print quality at 2× scale. |
|
|
||||||
| Animation | motion 11 | Modal transitions, toasts, observation cards. |
|
|
||||||
| Tests | vitest 3 + happy-dom + RTL | Unit-first; no e2e for MVP. |
|
|
||||||
| Tooling | ESLint 9 flat config, Prettier, pnpm 9, Node 20 | Modern defaults. |
|
|
||||||
| Deploy | Multi-stage Docker → nginx:alpine | Static dist served; entrypoint injects env into runtime config. |
|
|
||||||
|
|
||||||
## Folder tree
|
|
||||||
|
|
||||||
```
|
|
||||||
osteo/
|
|
||||||
├─ public/species/equine/{Horse,Horse_head}.svg
|
|
||||||
├─ src/
|
|
||||||
│ ├─ app/{App,routes/{Home,NewReport,Editor,NotFound}Route,providers/ConfigProvider}.tsx
|
|
||||||
│ ├─ config/env.ts
|
|
||||||
│ ├─ domain/
|
|
||||||
│ │ ├─ schema/{report,observation,practitioner,animal,pathology}.ts
|
|
||||||
│ │ └─ species/{registry,types,equine/{index,vertebrae,pathologies}}.ts
|
|
||||||
│ ├─ state/{reportStore,practitionerCache}.ts
|
|
||||||
│ ├─ anatomy/{svgLoader,svgConvention,types}.ts
|
|
||||||
│ ├─ components/
|
|
||||||
│ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip,Toast}.tsx
|
|
||||||
│ │ ├─ canvas/{AnatomyCanvas,DetailModal,ZoneTooltip}.tsx
|
|
||||||
│ │ ├─ observation/{ObservationList,ObservationCard,ObservationEditor,PathologyPicker,VertebraPicker,SeveritySelector,FreeTextPathologyInput}.tsx
|
|
||||||
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,ConclusionPanel,NextAppointmentPicker}.tsx
|
|
||||||
│ │ └─ brand/Brand.tsx
|
|
||||||
│ ├─ pdf/{export,import,attachment,fonts}.ts + pdf/render/{header,footer,observationPage,conclusionPage,svgToPng}.ts
|
|
||||||
│ ├─ lib/{dates,id,assert}.ts
|
|
||||||
│ ├─ styles/{index,tokens}.css
|
|
||||||
│ └─ main.tsx
|
|
||||||
├─ tests/unit/*.test.ts + tests/setup.ts
|
|
||||||
├─ docs/{ANATOMY-SVG-CONVENTION,ADDING-A-SPECIES,PDF-FORMAT}.md + docs/superpowers/specs/
|
|
||||||
├─ .claude/{tasks/TODO.md,memory/{decisions,learnings,blockers,journal,evals}.md,audits/.gitkeep}
|
|
||||||
├─ Dockerfile, docker-compose.yml, nginx.conf
|
|
||||||
├─ .env.example, .editorconfig, .nvmrc, .prettierrc.json, .gitignore, .dockerignore
|
|
||||||
├─ eslint.config.js, index.html, package.json, tsconfig*.json, vite.config.ts, vitest.config.ts
|
|
||||||
└─ CLAUDE.md, README.md, LICENSE (MIT)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Data model
|
|
||||||
|
|
||||||
```ts
|
|
||||||
type Severity = 'légère' | 'modérée' | 'sévère';
|
|
||||||
|
|
||||||
type Vertebra = { region: 'C' | 'T' | 'L' | 'S' | 'Cd'; index: number };
|
|
||||||
|
|
||||||
type ObservationZone = {
|
|
||||||
boneId: string; // matches data-anno-id from SVG
|
|
||||||
detailSourceId?: string; // when this zone came from a detail pop-up SVG
|
|
||||||
vertebrae?: Vertebra[]; // when boneId is a spine-zone
|
|
||||||
};
|
|
||||||
|
|
||||||
type Observation = {
|
|
||||||
id: string;
|
|
||||||
zones: ObservationZone[];
|
|
||||||
pathologyIds: string[];
|
|
||||||
freeTextPathologies: string[];
|
|
||||||
severity?: Severity;
|
|
||||||
comment: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type Report = {
|
|
||||||
version: 1;
|
|
||||||
id: string;
|
|
||||||
createdAt: string; // ISO
|
|
||||||
date: string; // clinical date (ISO)
|
|
||||||
practitioner: { name: string; cabinet?: string; contact?: string; siret?: string };
|
|
||||||
animal: { speciesId: string; name: string; breed?: string; age?: string };
|
|
||||||
owner: { name: string };
|
|
||||||
observations: Observation[];
|
|
||||||
conclusion: string;
|
|
||||||
recommendations: string;
|
|
||||||
nextAppointment?:
|
|
||||||
| { kind: 'date'; date: string }
|
|
||||||
| { kind: 'period'; text: string };
|
|
||||||
};
|
|
||||||
|
|
||||||
type PathologyCategory =
|
|
||||||
| 'osseux' | 'articulaire' | 'musculaire' | 'tendino-ligamentaire'
|
|
||||||
| 'fascial' | 'visceral' | 'cranio-sacre' | 'nerveux' | 'autre';
|
|
||||||
|
|
||||||
type PathologyRef = {
|
|
||||||
type: 'manual' | 'journal' | 'database' | 'web';
|
|
||||||
citation: string; // human-readable
|
|
||||||
url?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type Pathology = {
|
|
||||||
id: string; // stable kebab-case
|
|
||||||
labelFr: string;
|
|
||||||
description: string;
|
|
||||||
category: PathologyCategory;
|
|
||||||
speciesIds: string[]; // [] = applicable to all species
|
|
||||||
boneIds: string[]; // [] = applicable to all zones
|
|
||||||
sources: PathologyRef[]; // 1+
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
All JSON carries `version: 1`. Future migrations bump the version.
|
|
||||||
|
|
||||||
## SVG convention (source of truth)
|
|
||||||
|
|
||||||
A clickable zone is any element carrying `data-anno-id`. Required data
|
|
||||||
attributes: `data-anno-id`, `data-anno-name-fr`, `data-anno-name-en`, `data-anno-category`.
|
|
||||||
Optional: `data-anno-opens-detail="<id>"`.
|
|
||||||
|
|
||||||
Categories: `articulation` · `charniere` · `spine-zone` · `os` · `os-overlay`
|
|
||||||
· `head` · `cadran-crane`.
|
|
||||||
|
|
||||||
Two rendering patterns are tolerated in the SVG:
|
|
||||||
|
|
||||||
1. **hitbox + visible twin** (articulation, charniere, os-overlay, head):
|
|
||||||
two elements share the same `data-anno-id`. One has `class*="hitbox"`,
|
|
||||||
transparent fill, `pointer-events: all`. The other has `class*="visible"`,
|
|
||||||
colored fill, `pointer-events: none`.
|
|
||||||
2. **single element** (spine-zone, head zone): one polygon carries everything;
|
|
||||||
`pointer-events: all` and `cursor: pointer` directly.
|
|
||||||
|
|
||||||
Parser strategy (`src/anatomy/svgConvention.ts`):
|
|
||||||
- Walk all elements with `data-anno-id`.
|
|
||||||
- Group by `data-anno-id` → one logical `Bone`.
|
|
||||||
- Bone fields: `id`, `fr`, `en`, `category`, `opensDetail?`, `hitboxEls[]`,
|
|
||||||
`visibleEls[]`.
|
|
||||||
- Validate: must have `data-anno-name-fr`, `data-anno-name-en`, `data-anno-category` (in
|
|
||||||
the allowed enum). Throws structured `SvgConventionError` on missing
|
|
||||||
attributes.
|
|
||||||
|
|
||||||
Click handling: a single delegated listener on the root `<svg>` walks up
|
|
||||||
from `event.target` to the nearest element with `data-anno-id`. If
|
|
||||||
`data-anno-opens-detail` is present → open the detail modal mapped via the
|
|
||||||
species manifest. If the bone's category is `spine-zone` → open the
|
|
||||||
vertebra picker. Otherwise add the bone to the current observation.
|
|
||||||
|
|
||||||
Colorization: when the current observation contains a bone, all elements
|
|
||||||
matching that `data-anno-id` get a `data-state` attribute toggled by JS:
|
|
||||||
`current` (solid accent), `linked` (faded dashed border, "in another
|
|
||||||
observation"), `multi` (striped pattern, "in ≥2 observations").
|
|
||||||
|
|
||||||
> MVP scope cut: hover tooltip listing the owning observations is deferred.
|
|
||||||
> Visual state classes alone communicate participation in v1.
|
|
||||||
|
|
||||||
## Detail-popup mechanism
|
|
||||||
|
|
||||||
The mapping `detailId → SVG path` is held in the species manifest:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
// src/domain/species/equine/index.ts
|
|
||||||
export const equine = {
|
|
||||||
id: 'equine',
|
|
||||||
mainSvg: '/species/equine/Horse.svg',
|
|
||||||
details: { head: '/species/equine/Horse_head.svg' },
|
|
||||||
vertebralFormula: { C: 7, T: 18, L: 6, S: 5, Cd: 18 }, // approx Cd cap
|
|
||||||
pathologies: () => import('./pathologies'),
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
When a zone with `data-anno-opens-detail="head"` is clicked, the canvas
|
|
||||||
emits a `requestDetail({id: 'head'})` event handled by `DetailModal`, which
|
|
||||||
loads `/species/equine/Horse_head.svg` and renders it inline. Clicks inside
|
|
||||||
the modal add zones with `detailSourceId: 'head'` to the current
|
|
||||||
observation. The "entry" zone (e.g. the head polygon itself) is never
|
|
||||||
persisted in the report.
|
|
||||||
|
|
||||||
## Vertebra picker
|
|
||||||
|
|
||||||
Triggered when a clicked bone has `data-anno-category="spine-zone"`. Modal with
|
|
||||||
region tabs (Cervicales C1–C7, Thoraciques T1–T18, Lombaires L1–L6,
|
|
||||||
Sacrales S1–S5, Caudales Cd1–Cd18). Each region renders chips in a grid;
|
|
||||||
multi-select; ≥40 px touch targets; per-region "Tout cocher / décocher".
|
|
||||||
Stored as `vertebrae: Vertebra[]` on the `ObservationZone` (replaces the
|
|
||||||
global zone semantically: PDF prints precise vertebrae rather than the
|
|
||||||
bloc).
|
|
||||||
|
|
||||||
If a praticien clicks an individual vertebra (rendered under the same
|
|
||||||
`bone-id` as the bloc), it is treated identically to clicking the
|
|
||||||
spine-zone — opens the picker. Avoids duplicate UI paths.
|
|
||||||
|
|
||||||
## Multi-observation zone overlay
|
|
||||||
|
|
||||||
A bone may belong to several observations. Visual states (`data-state`
|
|
||||||
attribute on matching SVG elements, styled via `src/styles/index.css`):
|
|
||||||
|
|
||||||
- `current` — bone is in the active observation. Solid accent fill.
|
|
||||||
- `linked` — bone is in another observation (not current). Dashed border,
|
|
||||||
faded accent fill.
|
|
||||||
- `multi` — bone is in ≥2 observations. Same fill + heavier stroke to
|
|
||||||
signal sharing.
|
|
||||||
|
|
||||||
> MVP scope cut: per-observation HSL accent cycling (6 clinical-warm tones)
|
|
||||||
> deferred to v1.1. v1 uses a single accent color across all states; PDF
|
|
||||||
> renders per-observation pages, so colour ambiguity does not bleed into
|
|
||||||
> the printed report.
|
|
||||||
|
|
||||||
## PDF format
|
|
||||||
|
|
||||||
A4 portrait (595.28 × 841.89 pt). One pdf-lib document per export. Pages
|
|
||||||
share a header drawer (praticien left block, animal+owner+date right) and a
|
|
||||||
footer drawer (env-driven brand name, export date, page x/y).
|
|
||||||
|
|
||||||
Per observation: one page with
|
|
||||||
- the full main SVG rasterized at 2× scale with that observation's zones
|
|
||||||
colored (canvg writes to canvas → PNG → `embedPng`);
|
|
||||||
- if the observation includes detail-sourced zones (e.g. head): a second
|
|
||||||
rasterization of the detail SVG with those zones colored, placed beside
|
|
||||||
or below the main raster;
|
|
||||||
- a structured block beneath the schematic: zones (with precise vertebrae
|
|
||||||
formatted as "T12, T15"), pathologies (selected + free-text), severity,
|
|
||||||
comment.
|
|
||||||
|
|
||||||
> MVP scope cut: source citations under each cited pathology are deferred
|
|
||||||
> to post-MVP. Pathology IDs/labels render without their `sources[]` block.
|
|
||||||
|
|
||||||
Final page: conclusion, recommendations, next appointment.
|
|
||||||
|
|
||||||
JSON attachment: the full `Report` object is serialized and attached via
|
|
||||||
`pdfDoc.attach(bytes, 'osteo-report.json', { mimeType: 'application/json',
|
|
||||||
description: 'Osteo Report state v1', creationDate, modificationDate,
|
|
||||||
afRelationship: 'Data' })`. Bytes are pretty-printed JSON (UTF-8).
|
|
||||||
|
|
||||||
MVP fonts: pdf-lib standard Helvetica + Helvetica-Bold (body) + Times-Roman
|
|
||||||
(headings). Inter Sans + Fraunces TTF bundling deferred to v1.1 to avoid
|
|
||||||
shipping ~600KB of font assets in the initial Docker image.
|
|
||||||
|
|
||||||
## PDF import
|
|
||||||
|
|
||||||
`pdf-lib loadDocument()` → walk catalog `Names → EmbeddedFiles` tree → find
|
|
||||||
an attachment whose filename starts with `osteo-report` and whose mime is
|
|
||||||
`application/json` (or, fallback, parse-then-validate). Extract the stream,
|
|
||||||
flate-decompress if needed (pako), parse JSON, validate with Zod. On
|
|
||||||
success: hydrate the store and route to `/editor`. On failure: throw
|
|
||||||
`ImportError` with the French message
|
|
||||||
"Ce PDF n'a pas été généré par Osteo Report (pas de données détectées)." and
|
|
||||||
show a toast.
|
|
||||||
|
|
||||||
## Configurable identity
|
|
||||||
|
|
||||||
Env vars consumed at runtime:
|
|
||||||
|
|
||||||
| Name | Default | Use |
|
|
||||||
|---|---|---|
|
|
||||||
| `PORT` | `8080` | nginx listen port. |
|
|
||||||
| `APP_SITE_NAME` | `Osteo Report` | `<title>`. |
|
|
||||||
| `APP_BRAND_NAME` | `Osteo Report` | UI header, hero. |
|
|
||||||
| `APP_FOOTER_NAME` | `Osteo Report` | PDF footer. |
|
|
||||||
| `APP_TAGLINE` | `Bilans d'ostéopathie animalière` | Home tagline. |
|
|
||||||
|
|
||||||
Mechanism: Docker entrypoint templates `index.html` to inject a
|
|
||||||
`<script>window.__APP_CONFIG__ = {...}</script>` tag using container env
|
|
||||||
vars. `src/config/env.ts` reads `window.__APP_CONFIG__` first, falls back
|
|
||||||
to `import.meta.env.VITE_APP_*` build-time values, then to defaults.
|
|
||||||
`ConfigProvider` exposes the resolved config via React context. No identity
|
|
||||||
string is hardcoded in any component.
|
|
||||||
|
|
||||||
## Routes
|
|
||||||
|
|
||||||
- `/` — Home. Two CTAs ("Nouveau bilan", "Importer un PDF"). Quick-resume
|
|
||||||
card if a sessionStorage draft exists.
|
|
||||||
- `/new` — New report form. Species select (equine only for MVP),
|
|
||||||
praticien fields (prefilled from `osteo:lastPractitioner`), animal
|
|
||||||
(name + optional race/age), owner name, date (default today).
|
|
||||||
- `/editor` — Editor. Split layout: anatomy canvas + observation panel.
|
|
||||||
Bottom bar: export button.
|
|
||||||
- `*` — NotFoundRoute.
|
|
||||||
|
|
||||||
## State persistence
|
|
||||||
|
|
||||||
- Zustand store in memory.
|
|
||||||
- sessionStorage mirror (`osteo:draft`) auto-restored on `/editor` if the
|
|
||||||
user reloads accidentally; cleared after export.
|
|
||||||
- localStorage (`osteo:lastPractitioner`) caches the praticien block to
|
|
||||||
prefill next "Nouveau bilan".
|
|
||||||
- No long-term storage. PDF is the only durable artifact.
|
|
||||||
|
|
||||||
## Test strategy
|
|
||||||
|
|
||||||
- vitest + happy-dom.
|
|
||||||
- TDD-first for: schema (Zod parse + reject malformed), store actions, id
|
|
||||||
generator, anatomy convention parser (valid SVG → bones; bad SVG →
|
|
||||||
structured error), pathology DB integrity (every entry validates + has
|
|
||||||
≥1 source), pdf attachment write+extract roundtrip on a fixture file.
|
|
||||||
- UI smoke test: AnatomyCanvas mounts a fixture SVG and emits click for a
|
|
||||||
known bone.
|
|
||||||
- No e2e (no gstack plugin); manual QA in browser before commit.
|
|
||||||
|
|
||||||
## Docker / deploy
|
|
||||||
|
|
||||||
Multi-stage Dockerfile:
|
|
||||||
|
|
||||||
1. **builder** — `node:20-alpine`. `corepack enable && pnpm i --frozen-lockfile && pnpm build`.
|
|
||||||
2. **runner** — `nginx:alpine`. Copy `dist/` to `/usr/share/nginx/html`,
|
|
||||||
custom `nginx.conf` listening on `${PORT:-8080}`, `entrypoint.sh` writes
|
|
||||||
`/usr/share/nginx/html/env.js` from `APP_*` env vars, then runs nginx.
|
|
||||||
|
|
||||||
`docker-compose.yml` exposes `${PORT}:${PORT}` and passes `APP_*` env vars
|
|
||||||
through `env_file`. The host nginx reverse-proxies any subdomain to that
|
|
||||||
port.
|
|
||||||
|
|
||||||
## Open decisions resolved
|
|
||||||
|
|
||||||
| Decision | Resolution |
|
|
||||||
|---|---|
|
|
||||||
| SVG injection | Fetch text → DOMParser → inline render (consistent + CSS-controllable + sandboxing irrelevant since assets are local). |
|
|
||||||
| Vertebra picker UX | Region tabs + chip grid, multi-select, ≥40 px touch targets. |
|
|
||||||
| Multi-obs zone overlay | current / linked / multi states; striped pattern + tooltip. |
|
|
||||||
| Detail SVG trigger | `data-anno-opens-detail` → modal with inline detail SVG, clicks add to current obs. |
|
|
||||||
| SVG → PDF | canvg → canvas @ 2× → PNG → `embedPng`. |
|
|
||||||
| Pathology sources in PDF | Abbreviated citation list below each obs, no raw URLs. |
|
|
||||||
| Brand env vars | Runtime `window.__APP_CONFIG__` + Vite-define fallback. |
|
|
||||||
| MVP scope | Equine only. |
|
|
||||||
| Drag-reorder obs | ↑/↓ buttons, no DnD. |
|
|
||||||
| Practitioner default | localStorage cache. |
|
|
||||||
| State persistence | sessionStorage mirror + PDF for long-term. |
|
|
||||||
| Animation lib | motion 11. |
|
|
||||||
| License | MIT. |
|
|
||||||
|
|
||||||
## Prerequisites / REMAINING
|
|
||||||
|
|
||||||
- Real anatomical SVGs delivered by user at repo root: `Horse.svg` +
|
|
||||||
`Horse_head.svg`. Moved into `public/species/equine/` by the scaffolder.
|
|
||||||
- **Pathology DB authoring — deferred to post-MVP.** v1 ships with an
|
|
||||||
empty `EQUINE_PATHOLOGIES = []` and a relaxed integrity test (length
|
|
||||||
0..100). Pathology picker shows the "aucune pathologie de référence"
|
|
||||||
empty-state; praticien adds entries via free-text. Client osteo (or a
|
|
||||||
Phase 2 multi-user authoring tool) will populate the curated DB once
|
|
||||||
the long-term account architecture is decided.
|
|
||||||
- **Source citations in PDF — deferred to v1.1.** Once the DB exists,
|
|
||||||
re-enable the abbreviated-citation block on each observation page.
|
|
||||||
- **Hover tooltip on canvas — deferred to v1.1.** Visual state classes
|
|
||||||
alone in v1.
|
|
||||||
- **Per-observation HSL accent cycling — deferred to v1.1.** Single
|
|
||||||
accent in v1.
|
|
||||||
- **Inter + Fraunces TTF bundling — deferred to v1.1.** PDF uses standard
|
|
||||||
Helvetica + Times-Roman in v1.
|
|
||||||
- **`docs/ADDING-A-SPECIES.md` — content to be authored** from the
|
|
||||||
observed SVG convention + species manifest pattern (placeholder file
|
|
||||||
exists today).
|
|
||||||
- Final brand name, domain, identity strings.
|
|
||||||
- Phase 2 (out of MVP): user accounts, server persistence, animal history,
|
|
||||||
and curated pathology DB authoring tooling.
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
# B3 — i18n FR/EN (site + PDF) — Design
|
|
||||||
|
|
||||||
**Date:** 2026-05-20
|
|
||||||
**Branch:** `feat/findings-tree-v2`
|
|
||||||
**Status:** Approved → implementation
|
|
||||||
**Cross-refs:** TODO.md Phase B B3; BDR-010 (snapshot labels at selection); BDR-009 (snake_case JSON fields preserved); LRN-012 (sessionStorage once-per-session modal)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Goal
|
|
||||||
|
|
||||||
Add bilingual French / English UI and PDF export to Osteo Report. Practitioner picks the locale; all interface strings and PDF static labels render in that locale. Finding leaf names render via the dual snapshot already stored on each `Finding` (`labelFrSnapshot` / `labelEnSnapshot`).
|
|
||||||
|
|
||||||
Out of scope for this iteration: catalog `description_fr` (vet-expert authoring required) and `scope_disclaimer` (vet legal review). They stay FR-only until an expert provides EN copy.
|
|
||||||
|
|
||||||
## 2. Architecture
|
|
||||||
|
|
||||||
```
|
|
||||||
localeStore (Zustand, persist key osteo:locale)
|
|
||||||
↓ subscribe
|
|
||||||
useT() hook → (key: string) => string // resolves against active dict
|
|
||||||
↓
|
|
||||||
Components/routes import useT, replace hardcoded FR with t('key.path')
|
|
||||||
↓
|
|
||||||
LanguageSwitcher in ReportHeader calls localeStore.setLocale(...)
|
|
||||||
|
|
||||||
formatDate(iso, locale) // src/lib/dates.ts — replaces formatDateFr
|
|
||||||
exportReportToPdf(report, { locale }) // explicit, no default
|
|
||||||
→ static eyebrows/labels via dict snapshot at call time
|
|
||||||
→ findings rendered via labelFrSnapshot or labelEnSnapshot per locale
|
|
||||||
→ header date via formatDate(iso, locale)
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3. File plan
|
|
||||||
|
|
||||||
### New files (`src/`)
|
|
||||||
|
|
||||||
- `src/state/localeStore.ts` — Zustand store `{ locale: Locale, setLocale(l: Locale) }`, persists to `localStorage.osteo:locale`. Default `'fr'` if unset.
|
|
||||||
- `src/i18n/types.ts` — `export type Locale = 'fr' | 'en'`; `export type Dict = Record<string, string>`.
|
|
||||||
- `src/i18n/fr.ts` — FR dict (~60 keys, flat snake_case namespaces e.g. `editor.add_observation`).
|
|
||||||
- `src/i18n/en.ts` — EN equivalents, same keys.
|
|
||||||
- `src/i18n/index.ts` — `export const dicts: Record<Locale, Dict> = { fr, en }`; `export function getDict(locale: Locale): Dict`.
|
|
||||||
- `src/i18n/useT.ts` — `useT(): (key: string) => string`. Subscribes to localeStore. Missing key → returns key literal + `console.warn` (dev only).
|
|
||||||
- `src/components/brand/LanguageSwitcher.tsx` — segmented `FR | EN` toggle, `aria-pressed` per button, calls `setLocale`.
|
|
||||||
|
|
||||||
### Edited files (`src/`)
|
|
||||||
|
|
||||||
- `src/lib/dates.ts` — add `formatDate(iso: string, locale: Locale): string`; remove `formatDateFr` (callers migrate).
|
|
||||||
- `src/components/report/ReportHeader.tsx` — render `<LanguageSwitcher/>` next to Brand.
|
|
||||||
- `src/app/routes/{Home,NewReport,Editor,NotFound}Route.tsx` — strings via `t()`.
|
|
||||||
- `src/components/observation/{FindingsTreePicker,ObservationCard,FreeTextFindingInput,VertebraPicker,SeveritySelector}.tsx` — strings via `t()`; finding leaf label = `locale === 'en' ? labelEnSnapshot : labelFrSnapshot`. The picker tree itself reads `name_fr`/`name_en` from the catalog by current locale.
|
|
||||||
- `src/components/report/{PractitionerForm,AnimalForm,ConclusionPanel,NextAppointmentPicker}.tsx` — strings via `t()`.
|
|
||||||
- `src/pdf/export.ts` — signature changes to `exportReportToPdf(report: Report, opts: { locale: Locale })`. All callers updated.
|
|
||||||
- `src/pdf/render/{header,footer,observationPage,conclusionPage}.ts` — accept `locale` argument; static labels (eyebrows, section titles, "Sévérité", "Conclusion", date prefix, page numbers if any) read from dict; finding labels via correct snapshot; date via `formatDate(_, locale)`.
|
|
||||||
|
|
||||||
### Test files (`tests/unit/`)
|
|
||||||
|
|
||||||
- `state.localeStore.test.ts` (NEW) — 3 tests: default fr, setLocale updates state, persists to localStorage on change.
|
|
||||||
- `i18n.useT.test.tsx` (NEW) — 2 tests: returns dict value for active locale, missing key returns key + warns.
|
|
||||||
- `components.LanguageSwitcher.test.tsx` (NEW) — 2 tests: click toggles store, aria-pressed reflects active locale.
|
|
||||||
- `lib.dates.test.ts` (EDIT) — replace `formatDateFr` cases; cover `formatDate('2026-05-20', 'fr')` → `'20 mai 2026'`; `formatDate(..., 'en')` → `'May 20, 2026'`.
|
|
||||||
- `pdf.export.test.ts` (EDIT) — add roundtrip per locale: export `{ locale: 'fr' }` and `{ locale: 'en' }`, re-import both, assert JSON attachment intact; assert returned PDF bytes differ; minimal byte presence check is unreliable for subset fonts (LRN-016) so cover via the imported JSON only.
|
|
||||||
|
|
||||||
## 4. Dict key conventions
|
|
||||||
|
|
||||||
- Flat namespace `<area>.<key>` (e.g. `editor.add_observation`, `pdf.eyebrow_observation`).
|
|
||||||
- Keys are snake_case English.
|
|
||||||
- Values are the human string.
|
|
||||||
- Both dicts have the **same set of keys** — verify via a single unit test that compares `Object.keys(fr).sort()` to `Object.keys(en).sort()`.
|
|
||||||
|
|
||||||
## 5. Locale resolution rules
|
|
||||||
|
|
||||||
| Source | Behavior |
|
|
||||||
|---|---|
|
|
||||||
| `localStorage.osteo:locale` present and valid | use it |
|
|
||||||
| Missing or invalid | default `'fr'`, do not write back yet |
|
|
||||||
| `setLocale(l)` | update store + write `localStorage.osteo:locale = l` |
|
|
||||||
| `localStorage` write fails | swallow, in-memory only, no user error |
|
|
||||||
|
|
||||||
PDF export does **not** default a locale — caller must pass it. Route layer reads the store at the export call site.
|
|
||||||
|
|
||||||
## 6. Out of scope (explicit)
|
|
||||||
|
|
||||||
- Catalog `description_fr` and `scope_disclaimer` translation (vet-expert / legal pass needed).
|
|
||||||
- Native `input[type=date]` widget labels (browser/OS).
|
|
||||||
- Brand identity strings (env-driven via `useConfig()`).
|
|
||||||
- Zod schema error messages emitted to console (dev-only).
|
|
||||||
|
|
||||||
## 7. Acceptance criteria
|
|
||||||
|
|
||||||
- Switching the locale updates every visible UI string at the next render.
|
|
||||||
- Locale persists across reload (verifiable in QA via DevTools localStorage).
|
|
||||||
- Re-importing a PDF does NOT change the active locale — the imported report uses whatever the store currently holds for next export.
|
|
||||||
- PDF exports in `'fr'` and `'en'` have different static eyebrow / section / date strings; the embedded JSON is byte-identical between the two locales for the same `Report` (locale lives outside the report).
|
|
||||||
- 139 existing tests + 11 new tests = 150+ pass. Lint clean. Typecheck clean. Vite build OK.
|
|
||||||
|
|
||||||
## 8. Risks / open questions
|
|
||||||
|
|
||||||
- **Risk**: forgotten hardcoded FR strings. Mitigation: grep-pass over `src/` after migration for `'É'`, `'è'`, `'à'`, `' du '`, `'pour'` etc. as a heuristic + verify in QA.
|
|
||||||
- **Risk**: changing `formatDateFr` → `formatDate` breaks PDF render. Mitigation: TypeScript will flag every caller; covered by typecheck.
|
|
||||||
- **Open**: should the dict be lazily loaded per locale? Decision: NO — both dicts are tiny (~3KB each), eager import in `i18n/index.ts` keeps the bundle simple. Revisit if dict grows past 50KB.
|
|
||||||
|
|
||||||
## 9. Verification plan
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pnpm typecheck
|
|
||||||
pnpm lint
|
|
||||||
pnpm test:run # 150+ tests green
|
|
||||||
pnpm build # bundle still <1MB main
|
|
||||||
```
|
|
||||||
|
|
||||||
Manual QA after build:
|
|
||||||
1. `pnpm dev` → switch locale → all visible strings update.
|
|
||||||
2. Create a report → export FR PDF → re-import → re-export EN PDF → diff strings.
|
|
||||||
3. Reload → locale persists.
|
|
||||||
@@ -1,387 +0,0 @@
|
|||||||
# Pathology Editor — Design Spec
|
|
||||||
|
|
||||||
**Date**: 2026-05-22
|
|
||||||
**Status**: Draft
|
|
||||||
**Scope**: Standalone HTML tool for editing species pathology JSON via SVG-based zone selection
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Overview
|
|
||||||
|
|
||||||
Single-file standalone HTML tool (`pathology-editor.html` at project root) that lets users visually select anatomical zones on an SVG and edit the corresponding pathology tree in the species JSON. Same architectural pattern as `editor.html` (SVG editor): vanilla JS/CSS, no build step, no dependencies.
|
|
||||||
|
|
||||||
The tool never modifies source files. It works on an in-memory copy and exports a downloadable JSON file.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Layout
|
|
||||||
|
|
||||||
Two-panel horizontal layout, identical to SVG editor:
|
|
||||||
|
|
||||||
| Panel | Width | Content |
|
|
||||||
|-------|-------|---------|
|
|
||||||
| Left (canvas) | flex: 1 | SVG display, click-to-select zones |
|
|
||||||
| Right (sidebar) | 380px | Source picker → zone info → tree editor → export |
|
|
||||||
|
|
||||||
Sidebar is scrollable. Canvas contains the SVG with auto-viewBox (same logic as `editor.html`).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Source Selection
|
|
||||||
|
|
||||||
On launch, sidebar shows source picker with two modes:
|
|
||||||
|
|
||||||
### 3a. Pre-wired list
|
|
||||||
|
|
||||||
Two-step selection:
|
|
||||||
1. **Species dropdown** — lists registered species (MVP: "Cheval" only)
|
|
||||||
2. **View dropdown** — lists available SVGs for selected species
|
|
||||||
|
|
||||||
Hardcoded config (easily extensible):
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const SPECIES_CONFIG = [
|
|
||||||
{
|
|
||||||
id: 'equine',
|
|
||||||
label: 'Cheval',
|
|
||||||
jsonPath: '/species/equine/pathologies.json',
|
|
||||||
views: [
|
|
||||||
{ label: 'Corps complet', svgPath: '/species/equine/Horse.svg' },
|
|
||||||
{ label: 'Tête (détail)', svgPath: '/species/equine/Horse_head.svg' },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
```
|
|
||||||
|
|
||||||
**Pre-requisite**: `pathologies.json` must be copied (or symlinked) to `public/species/equine/pathologies.json` so it's accessible via HTTP when served statically. The source of truth remains `src/domain/species/equine/pathologies.json` — the public copy is read-only for the editor.
|
|
||||||
|
|
||||||
"Charger" button fetches both files. If either fetch fails, show error with HTTP status.
|
|
||||||
|
|
||||||
All views of a species share the same JSON. Switching view reloads SVG only, keeps JSON state.
|
|
||||||
|
|
||||||
### 3b. Manual upload
|
|
||||||
|
|
||||||
Two file inputs:
|
|
||||||
- "Fichier SVG" — accepts `.svg`
|
|
||||||
- "Fichier JSON" — accepts `.json`
|
|
||||||
|
|
||||||
Both required. If only one provided, "Charger" button disabled with message: "Les deux fichiers (SVG et JSON) sont obligatoires."
|
|
||||||
|
|
||||||
Files read via `FileReader` as UTF-8 text.
|
|
||||||
|
|
||||||
### Source switch
|
|
||||||
|
|
||||||
After loading, sidebar transitions to editing mode. A "Changer de source" link at the top returns to the source picker. Switching source discards current edits (with confirmation if modifications exist).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. SVG Display
|
|
||||||
|
|
||||||
### Loading
|
|
||||||
|
|
||||||
Parse SVG text, inject into canvas container as inline SVG. Auto-viewBox: if `viewBox` attribute missing, compute from SVG `width`/`height` or `getBBox()` and set it (same as `editor.html` pattern).
|
|
||||||
|
|
||||||
### Zone detection
|
|
||||||
|
|
||||||
Walk all SVG elements. An element is a clickable zone if it has `data-anno-id` AND at least one of `data-anno-name-fr` or `data-anno-name-en`.
|
|
||||||
|
|
||||||
### Interaction
|
|
||||||
|
|
||||||
- **Hover**: subtle opacity/highlight change on annotated elements
|
|
||||||
- **Click**: select zone (see section 5)
|
|
||||||
- **Selected state**: distinct highlight color (blue outline or fill overlay), persists until another zone clicked
|
|
||||||
|
|
||||||
No editing of SVG content. SVG is read-only visual selector.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Zone Selection Logic
|
|
||||||
|
|
||||||
When user clicks an annotated SVG element:
|
|
||||||
|
|
||||||
### Step 1 — Read SVG attributes
|
|
||||||
|
|
||||||
Extract from clicked element (walk up DOM to find `data-anno-id` parent if needed):
|
|
||||||
- `data-anno-id`
|
|
||||||
- `data-anno-name-fr`
|
|
||||||
- `data-anno-name-en`
|
|
||||||
- `data-anno-opens-detail` (if present)
|
|
||||||
- `data-anno-special` (if present)
|
|
||||||
|
|
||||||
### Step 2 — Special attribute handling
|
|
||||||
|
|
||||||
| Attribute | Behavior |
|
|
||||||
|-----------|----------|
|
|
||||||
| `data-anno-opens-detail` present | Show info message: "Zone de navigation vers un SVG de détail — non éditable ici. Chargez le SVG de détail pour éditer ses zones." Do NOT open tree editor. |
|
|
||||||
| `data-anno-special` present (e.g., `vertebral-precision`) | Treat as normal editable zone. `special` attribute is irrelevant to pathology editing. |
|
|
||||||
|
|
||||||
### Step 3 — Fuzzy match to JSON zone
|
|
||||||
|
|
||||||
Match SVG `name_fr`/`name_en` against `zones[*].name_fr`/`name_en` in loaded JSON.
|
|
||||||
|
|
||||||
Matching algorithm (port from `src/lib/zoneMatch.ts`):
|
|
||||||
|
|
||||||
1. Normalize both strings: `str.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]/g, '')`
|
|
||||||
2. Score pairs (SVG label vs JSON zone label):
|
|
||||||
- Exact match → score 0
|
|
||||||
- Substring containment → score 1
|
|
||||||
- Levenshtein distance ≤ 25% of max length (min 2 edits) → score 2 + distance
|
|
||||||
3. Priority: EN-on-EN first, FR-on-FR second, cross-language last
|
|
||||||
4. Take lowest score. If no candidate below threshold → no match.
|
|
||||||
|
|
||||||
### Step 4 — Result
|
|
||||||
|
|
||||||
| Result | Sidebar action |
|
|
||||||
|--------|---------------|
|
|
||||||
| Match found | Select zone, show tree editor for matched zone |
|
|
||||||
| No match | Show "Aucune zone correspondante dans le JSON" + "Créer cette zone" button |
|
|
||||||
|
|
||||||
### Creating a new zone
|
|
||||||
|
|
||||||
"Créer cette zone" pre-fills:
|
|
||||||
- `id`: generated from `name_en` (fallback `name_fr`) → kebab-case (see section 7 for ID generation)
|
|
||||||
- `name_fr`: from SVG `data-anno-name-fr`
|
|
||||||
- `name_en`: from SVG `data-anno-name-en`
|
|
||||||
- `categories`: empty array `[]`
|
|
||||||
|
|
||||||
Zone added to in-memory JSON `zones` object immediately.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Pathology Tree Editor
|
|
||||||
|
|
||||||
### Zone header
|
|
||||||
|
|
||||||
When a zone is selected, sidebar shows:
|
|
||||||
- Zone name: `name_fr` / `name_en` (read-only display, not editable — zone names come from SVG)
|
|
||||||
- Zone ID: displayed as badge (read-only)
|
|
||||||
- Zone stats: count of categories, total node count
|
|
||||||
|
|
||||||
### Tree display
|
|
||||||
|
|
||||||
Recursive collapsible tree rendering all `categories` and their nested `children`:
|
|
||||||
|
|
||||||
```
|
|
||||||
📁 Dysfonctions ostéopathiques [+ Ajouter enfant] [✏️] [🗑️]
|
|
||||||
📁 Lésions de mobilité [+ Ajouter enfant] [✏️] [🗑️]
|
|
||||||
🔹 En flexion (rotation externe) [✏️] [🗑️]
|
|
||||||
🔹 En extension (rotation interne) [✏️] [🗑️]
|
|
||||||
📁 Lésions intra-osseuses [+ Ajouter enfant] [✏️] [🗑️]
|
|
||||||
🔹 Compression intra-osseuse [✏️] [🗑️]
|
|
||||||
📁 Observations / motifs de consultation [+ Ajouter enfant] [✏️] [🗑️]
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
Visual conventions:
|
|
||||||
- 📁 = node with `children` (category/intermediate) — collapsible
|
|
||||||
- 🔹 = leaf node (no `children` or empty `children`) — selectable by practitioner in main app
|
|
||||||
- Indentation: 20px per level
|
|
||||||
- Collapse state: all collapsed by default, expand on click
|
|
||||||
|
|
||||||
### Node operations
|
|
||||||
|
|
||||||
#### Edit node (✏️)
|
|
||||||
|
|
||||||
Click edit icon → inline form expands below the node:
|
|
||||||
|
|
||||||
| Field | Type | Required |
|
|
||||||
|-------|------|----------|
|
|
||||||
| `name_fr` | text input | yes |
|
|
||||||
| `name_en` | text input | yes |
|
|
||||||
| `description_fr` | textarea | no |
|
|
||||||
| `description_en` | textarea | no |
|
|
||||||
| `requires_vet_referral` | checkbox | no (default false) |
|
|
||||||
| Sources | repeatable row group | no |
|
|
||||||
|
|
||||||
Each source row:
|
|
||||||
- `type`: select dropdown (`manual`, `journal`, `database`, `web`)
|
|
||||||
- `citation`: text input
|
|
||||||
- `url`: text input (optional)
|
|
||||||
- [Remove source] button
|
|
||||||
|
|
||||||
[Add source] button below sources list.
|
|
||||||
|
|
||||||
"Enregistrer" saves changes to in-memory JSON. "Annuler" discards form.
|
|
||||||
|
|
||||||
When saving, `id` is NOT editable — it was set at creation and remains stable.
|
|
||||||
|
|
||||||
#### Add child node (+ Ajouter enfant)
|
|
||||||
|
|
||||||
Available on any node. Opens inline form (same as edit) for the new child.
|
|
||||||
|
|
||||||
On save:
|
|
||||||
- New node inserted as last child of parent
|
|
||||||
- `id` auto-generated from `name_en` (see section 7)
|
|
||||||
- If parent was a leaf (no `children`), it becomes a category (gets `children` array)
|
|
||||||
|
|
||||||
#### Add root category (+ Ajouter catégorie)
|
|
||||||
|
|
||||||
Button at bottom of zone's tree. Creates new top-level category in `categories` array.
|
|
||||||
|
|
||||||
#### Delete node (🗑️)
|
|
||||||
|
|
||||||
Click delete → confirmation dialog: "Supprimer « {name_fr} » et tous ses enfants ({N} nœuds) ?"
|
|
||||||
|
|
||||||
On confirm: remove node and entire subtree from parent's `children` (or from zone's `categories` if root-level).
|
|
||||||
|
|
||||||
### No reordering
|
|
||||||
|
|
||||||
Drag-and-drop reordering excluded from this version. Node order matches JSON array order.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. ID Generation
|
|
||||||
|
|
||||||
Auto-generate `id` for new nodes and zones:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
function generateId(nameEn, nameFr, existingSiblingIds) {
|
|
||||||
const source = (nameEn || nameFr || 'node').trim();
|
|
||||||
let slug = source
|
|
||||||
.normalize('NFD')
|
|
||||||
.replace(/[̀-ͯ]/g, '') // strip accents
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/[^a-z0-9]+/g, '-') // non-alnum → hyphen
|
|
||||||
.replace(/^-|-$/g, ''); // trim leading/trailing hyphens
|
|
||||||
|
|
||||||
if (!slug) slug = 'node';
|
|
||||||
|
|
||||||
// Ensure uniqueness among siblings
|
|
||||||
let candidate = slug;
|
|
||||||
let counter = 2;
|
|
||||||
while (existingSiblingIds.includes(candidate)) {
|
|
||||||
candidate = `${slug}-${counter}`;
|
|
||||||
counter++;
|
|
||||||
}
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. JSON Export
|
|
||||||
|
|
||||||
### Trigger
|
|
||||||
|
|
||||||
"Télécharger JSON" button — always visible in sidebar header area, enabled once source is loaded.
|
|
||||||
|
|
||||||
### Output
|
|
||||||
|
|
||||||
- Full JSON object with all root fields preserved: `schema_version`, `scope_disclaimer`, `species`, `zones`
|
|
||||||
- ALL zones included (modified + unmodified)
|
|
||||||
- UTF-8 encoding, 2-space indentation
|
|
||||||
- Filename: `pathologies-{speciesId}-{YYYYMMDD-HHmmss}.json` (or `pathologies-custom-{timestamp}.json` for manual uploads)
|
|
||||||
|
|
||||||
### Implementation
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const blob = new Blob(
|
|
||||||
[JSON.stringify(jsonData, null, 2)],
|
|
||||||
{ type: 'application/json;charset=utf-8' }
|
|
||||||
);
|
|
||||||
const url = URL.createObjectURL(blob);
|
|
||||||
// trigger download via <a> element
|
|
||||||
```
|
|
||||||
|
|
||||||
### Integrity rules
|
|
||||||
|
|
||||||
- Never drop fields from nodes (even if empty/optional — omit only if truly absent)
|
|
||||||
- Never reorder zone keys (use insertion order from original parse)
|
|
||||||
- `schema_version` preserved as-is (no auto-bump)
|
|
||||||
- Empty `children: []` on a leaf is valid and preserved if originally present
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Unsaved Changes Protection
|
|
||||||
|
|
||||||
Track modification state (dirty flag). When user attempts to:
|
|
||||||
- Switch source → confirm dialog: "Des modifications non enregistrées seront perdues. Continuer ?"
|
|
||||||
- Close/navigate away → `beforeunload` event handler
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. Error Handling
|
|
||||||
|
|
||||||
| Scenario | Behavior |
|
|
||||||
|----------|----------|
|
|
||||||
| SVG fetch fails (pre-wired) | Show error: "Impossible de charger le SVG: {status}" |
|
|
||||||
| JSON fetch fails (pre-wired) | Show error: "Impossible de charger le JSON: {status}" |
|
|
||||||
| JSON parse error | Show error: "Le fichier JSON est invalide: {error.message}" |
|
|
||||||
| JSON missing required root fields | Show error: "Structure JSON invalide: champ '{field}' manquant" |
|
|
||||||
| SVG has no annotated elements | Show warning: "Aucun élément annoté (data-anno-*) trouvé dans ce SVG" |
|
|
||||||
| Uploaded file too large (>10MB) | Show error: "Fichier trop volumineux (max 10 Mo)" |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 11. Styling
|
|
||||||
|
|
||||||
Consistent with `editor.html` aesthetic:
|
|
||||||
- Dark header bar with tool title
|
|
||||||
- White sidebar background, light gray canvas background
|
|
||||||
- System font stack: `-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif`
|
|
||||||
- Buttons: solid background (blue primary, red destructive, gray secondary)
|
|
||||||
- Inputs: bordered, rounded, consistent padding
|
|
||||||
- Tree nodes: hover highlight, selected state with left border accent
|
|
||||||
- Responsive: min-width 900px, below that show a "use larger screen" message
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 12. File Structure
|
|
||||||
|
|
||||||
Single file: `pathology-editor.html` at project root (same level as `editor.html`).
|
|
||||||
|
|
||||||
No external dependencies. All CSS inline in `<style>`. All JS inline in `<script>`.
|
|
||||||
|
|
||||||
Approximate structure:
|
|
||||||
```html
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="fr">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<meta name="robots" content="noindex,nofollow">
|
|
||||||
<title>Faunosteo — Éditeur de pathologies</title>
|
|
||||||
<style>/* all styles */</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<header><!-- title bar --></header>
|
|
||||||
<main>
|
|
||||||
<div id="canvas"><!-- SVG container --></div>
|
|
||||||
<aside id="sidebar"><!-- source picker / tree editor --></aside>
|
|
||||||
</main>
|
|
||||||
<script>/* all logic */</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 13. Out of Scope
|
|
||||||
|
|
||||||
- Node drag-and-drop reordering
|
|
||||||
- Undo/redo history
|
|
||||||
- Multi-zone selection
|
|
||||||
- Zone name editing (names come from SVG, not JSON)
|
|
||||||
- SVG modification or export
|
|
||||||
- Schema version auto-bumping
|
|
||||||
- Diff/merge between JSON versions
|
|
||||||
- Integration as React route (standalone only)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 14. Acceptance Criteria
|
|
||||||
|
|
||||||
1. Pre-wired source loads SVG + JSON from local paths, displays SVG with clickable zones
|
|
||||||
2. Manual upload accepts SVG + JSON files, rejects incomplete uploads
|
|
||||||
3. Clicking annotated SVG zone matches to JSON zone via fuzzy matching
|
|
||||||
4. Clicking `data-anno-opens-detail` zone shows navigation info, not tree editor
|
|
||||||
5. Tree editor displays full recursive hierarchy for selected zone
|
|
||||||
6. Can add node at any level (root category, intermediate, leaf)
|
|
||||||
7. Can edit all node fields (name_fr, name_en, descriptions, vet referral, sources)
|
|
||||||
8. Can delete node with confirmation, removes entire subtree
|
|
||||||
9. New node IDs auto-generated as unique kebab-case slugs
|
|
||||||
10. "Créer cette zone" works for SVG zones with no JSON match
|
|
||||||
11. Downloaded JSON contains all zones (modified + unmodified) with root fields preserved
|
|
||||||
12. Downloaded JSON is valid UTF-8 with 2-space indentation
|
|
||||||
13. Unsaved changes trigger confirmation on source switch and page close
|
|
||||||
14. All error scenarios show user-facing French messages
|
|
||||||
@@ -1,234 +0,0 @@
|
|||||||
# Laterality Support — Design Spec
|
|
||||||
|
|
||||||
**Date**: 2026-05-23
|
|
||||||
**Status**: Approved
|
|
||||||
**Approach**: A — per-zone SVG attribute + inline side picker + separate observation entries
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Problem
|
|
||||||
|
|
||||||
Anatomical zones have no laterality concept. A practitioner clicking "Genou" (knee) creates one observation zone without specifying left or right. Bilateral structures (knee, hip, shoulder) need side differentiation; midline/unpaired structures (spine, sternum) do not.
|
|
||||||
|
|
||||||
## Solution Overview
|
|
||||||
|
|
||||||
Three layers:
|
|
||||||
1. **SVG convention** — new `data-anno-lateral` attribute marks zones as bilateral or unpaired
|
|
||||||
2. **Report schema** — new `side` field on `ObservationZone` records which side
|
|
||||||
3. **UI** — LateralityPicker modal when clicking bilateral zones; badge display shows side
|
|
||||||
|
|
||||||
Backward-compatible: missing attribute = unpaired, `side` field is optional.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. SVG Convention
|
|
||||||
|
|
||||||
New optional attribute on annotated elements:
|
|
||||||
|
|
||||||
| Attribute | Values | Default when absent |
|
|
||||||
|---|---|---|
|
|
||||||
| `data-anno-lateral` | `bilateral` \| `unpaired` | `unpaired` |
|
|
||||||
|
|
||||||
- `bilateral`: zone has left and right instances (e.g. knee, hip, shoulder)
|
|
||||||
- `unpaired`: zone has no laterality (e.g. sternum, sacrum) or laterality is not relevant
|
|
||||||
|
|
||||||
The parser reads and forwards this attribute like `data-anno-special` — optional, opaque string. The `Bone` interface gains a `lateral` field.
|
|
||||||
|
|
||||||
### Validation
|
|
||||||
|
|
||||||
- If present, value must be `bilateral` or `unpaired`. Any other value → `SvgConventionError`.
|
|
||||||
- If absent → treated as `unpaired` at the application level (not by the parser — parser sets `undefined`, app code defaults).
|
|
||||||
|
|
||||||
### Doc update
|
|
||||||
|
|
||||||
`docs/ANATOMY-SVG-CONVENTION.md` gains a row in the optional attributes table.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Schema Changes
|
|
||||||
|
|
||||||
### ObservationZone
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export const LateralSideSchema = z.enum(['left', 'right'])
|
|
||||||
export type LateralSide = z.infer<typeof LateralSideSchema>
|
|
||||||
|
|
||||||
export const ObservationZoneSchema = z.object({
|
|
||||||
boneId: z.string().min(1),
|
|
||||||
detailSourceId: z.string().optional(),
|
|
||||||
vertebrae: z.array(VertebraSchema).optional(),
|
|
||||||
side: LateralSideSchema.optional(),
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- `side` is present only when the bone is bilateral
|
|
||||||
- Unpaired zones never carry `side`
|
|
||||||
- Two zones with same `boneId` but different `side` values are valid (left knee + right knee in same observation)
|
|
||||||
- No schema version bump — `side` is additive and optional; old reports parse cleanly
|
|
||||||
|
|
||||||
### Bone interface
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export interface Bone {
|
|
||||||
id: string
|
|
||||||
fr: string
|
|
||||||
en: string
|
|
||||||
category: BoneCategory
|
|
||||||
opensDetail?: string
|
|
||||||
special?: string
|
|
||||||
lateral?: 'bilateral' | 'unpaired' // NEW
|
|
||||||
els: Element[]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. SVG Parser Changes
|
|
||||||
|
|
||||||
`parseSvgBones()` reads `data-anno-lateral` from SVG elements and sets `Bone.lateral`:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const lateral = el.getAttribute('data-anno-lateral') ?? undefined
|
|
||||||
```
|
|
||||||
|
|
||||||
Merging logic (multiple elements sharing same `data-anno-id`): first non-undefined `lateral` value wins, same pattern as `special` and `opensDetail`.
|
|
||||||
|
|
||||||
No validation of the value in the parser — validation happens at the convention level if desired. The parser is permissive (accepts any string); the application layer checks for known values.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. UX Flow — LateralityPicker
|
|
||||||
|
|
||||||
### Trigger
|
|
||||||
|
|
||||||
When practitioner clicks a bilateral zone (`bone.lateral === 'bilateral'`):
|
|
||||||
|
|
||||||
1. **LateralityPicker** modal opens with three options:
|
|
||||||
- Gauche / Left
|
|
||||||
- Droite / Right
|
|
||||||
- Les deux / Both
|
|
||||||
|
|
||||||
2. Selection behavior:
|
|
||||||
- "Left" → adds `ObservationZone { boneId, side: 'left' }`
|
|
||||||
- "Right" → adds `ObservationZone { boneId, side: 'right' }`
|
|
||||||
- "Both" → adds two entries: `{ boneId, side: 'left' }` + `{ boneId, side: 'right' }`
|
|
||||||
|
|
||||||
3. Duplicate prevention: if a zone with the same `boneId + side + detailSourceId` already exists in the active observation, skip silently.
|
|
||||||
|
|
||||||
4. Re-click behavior: if the zone already has one or both sides in the observation, the picker opens again so the user can add the missing side. If both sides already exist, clicking removes both (toggle off — matching current toggle behavior for unpaired zones).
|
|
||||||
|
|
||||||
### Component
|
|
||||||
|
|
||||||
`src/components/observation/LateralityPicker.tsx`
|
|
||||||
|
|
||||||
- Reuses `Dialog` component for modal shell
|
|
||||||
- Three `Button` components for the choices
|
|
||||||
- Receives `onSelect(sides: LateralSide[])` callback
|
|
||||||
- Small, focused modal — not a full-screen overlay
|
|
||||||
|
|
||||||
### Integration point
|
|
||||||
|
|
||||||
`EditorRoute.onZoneClick()` — after the `opensDetail` check and `vertebral-precision` check, before the toggle logic:
|
|
||||||
|
|
||||||
```
|
|
||||||
if bone.lateral === 'bilateral' → open LateralityPicker
|
|
||||||
→ onSelect callback adds zone(s) with side
|
|
||||||
else → existing toggle logic (unpaired zone)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Zone Badge Display
|
|
||||||
|
|
||||||
In `ObservationCard`, the `describeZone()` function appends a side suffix for bilateral zones:
|
|
||||||
|
|
||||||
- FR: `Genou (G)` for left, `Genou (D)` for right
|
|
||||||
- EN: `Knee (L)` for left, `Knee (R)` for right
|
|
||||||
|
|
||||||
The short labels come from i18n keys `lateral.left_short` / `lateral.right_short`.
|
|
||||||
|
|
||||||
Format: `{zoneName} ({sideShort})`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. SVG Editor Changes
|
|
||||||
|
|
||||||
In the edit panel (`svg-editor-osteo-fields`), a new select dropdown after the category select:
|
|
||||||
|
|
||||||
```html
|
|
||||||
<label>Latéralité / Laterality</label>
|
|
||||||
<select id="svg-editor-edit-lateral">
|
|
||||||
<option value="">Impair / Unpaired</option>
|
|
||||||
<option value="bilateral">Bilatéral / Bilateral</option>
|
|
||||||
</select>
|
|
||||||
```
|
|
||||||
|
|
||||||
Behavior:
|
|
||||||
- Reads `data-anno-lateral` from selected element on select
|
|
||||||
- Writes `data-anno-lateral` attribute on change (removes attribute if "unpaired" selected)
|
|
||||||
- Propagates to sibling elements sharing same `data-anno-id` (same pattern as category/name propagation)
|
|
||||||
- Exported SVG includes the attribute
|
|
||||||
|
|
||||||
### Backward compatibility
|
|
||||||
|
|
||||||
Existing SVGs loaded in the editor: zones without `data-anno-lateral` show "Impair" (default). User can change to "Bilatéral" and re-export.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. PDF Output
|
|
||||||
|
|
||||||
Zone labels in PDF include side when present:
|
|
||||||
|
|
||||||
- FR: `Genou (Gauche)`, `Genou (Droit)`
|
|
||||||
- EN: `Knee (Left)`, `Knee (Right)`
|
|
||||||
|
|
||||||
Uses full side name (not abbreviation) for PDF clarity.
|
|
||||||
|
|
||||||
The `describeZone()` helper used in PDF rendering checks `zone.side` and appends the localized label.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. i18n Keys
|
|
||||||
|
|
||||||
New keys in `src/i18n/fr.ts` and `src/i18n/en.ts`:
|
|
||||||
|
|
||||||
| Key | FR | EN |
|
|
||||||
|---|---|---|
|
|
||||||
| `lateral.which_side` | Quel côté ? | Which side? |
|
|
||||||
| `lateral.left` | Gauche | Left |
|
|
||||||
| `lateral.right` | Droite | Right |
|
|
||||||
| `lateral.both` | Les deux | Both |
|
|
||||||
| `lateral.left_short` | G | L |
|
|
||||||
| `lateral.right_short` | D | R |
|
|
||||||
| `lateral.bilateral` | Bilatéral | Bilateral |
|
|
||||||
| `lateral.unpaired` | Impair | Unpaired |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Scope Exclusions
|
|
||||||
|
|
||||||
- No changes to findings tree — findings are zone-level, same pathologies apply to both sides
|
|
||||||
- No SVG visual differentiation between left/right — same zone highlights for both sides
|
|
||||||
- No auto-detection of laterality from zone names
|
|
||||||
- No report schema version bump — additive optional field
|
|
||||||
- No changes to PDF attachment format — JSON includes `side` field naturally
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. Files Touched
|
|
||||||
|
|
||||||
| File | Change |
|
|
||||||
|---|---|
|
|
||||||
| `src/anatomy/types.ts` | Add `lateral` to `Bone` interface |
|
|
||||||
| `src/anatomy/svgConvention.ts` | Read `data-anno-lateral` in parser |
|
|
||||||
| `src/domain/schema/observation.ts` | Add `LateralSideSchema`, `side` field |
|
|
||||||
| `src/components/observation/LateralityPicker.tsx` | NEW — modal component |
|
|
||||||
| `src/components/observation/ObservationCard.tsx` | Update `describeZone()` |
|
|
||||||
| `src/app/routes/EditorRoute.tsx` | Integrate LateralityPicker in click flow |
|
|
||||||
| `src/app/routes/SvgEditorRoute.tsx` | Add lateral dropdown in edit panel |
|
|
||||||
| `src/i18n/fr.ts` | Add lateral keys |
|
|
||||||
| `src/i18n/en.ts` | Add lateral keys |
|
|
||||||
| `src/pdf/render/observationPage.ts` | Update zone label rendering |
|
|
||||||
| `docs/ANATOMY-SVG-CONVENTION.md` | Document `data-anno-lateral` |
|
|
||||||
| `tests/unit/observation.test.ts` | Test side field parsing |
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
# Responsive / Mobile-First — Surgical Fixes
|
|
||||||
|
|
||||||
**Date**: 2026-05-23
|
|
||||||
**Approach**: A — surgical fixes, no layout redesign
|
|
||||||
**Target**: phone-first (375px+), tablet perfect (768px+)
|
|
||||||
**Baseline score**: 40/100 responsive readiness
|
|
||||||
**Target score**: 80+/100
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
Pure CSS/className changes. Zero store, schema, or PDF impact. ~12-15 files.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Dialog viewport clamping
|
|
||||||
|
|
||||||
**File**: `src/components/ui/Dialog.tsx`
|
|
||||||
|
|
||||||
- All size variants get `max-w-[calc(100vw-2rem)]` so dialogs never exceed viewport
|
|
||||||
- Backdrop padding: `p-4` → `p-2 sm:p-4`
|
|
||||||
- Dialog content padding responsive where needed
|
|
||||||
|
|
||||||
## 2. SVG Editor sidebar — stack on mobile
|
|
||||||
|
|
||||||
**File**: `src/styles/svg-editor.css`
|
|
||||||
|
|
||||||
- Below `md` (768px): sidebar stacks below canvas via `flex-direction: column`
|
|
||||||
- Sidebar width: `380px` → `w-full` on mobile, `380px` on `md+`
|
|
||||||
- Canvas gets min-height to stay usable when stacked
|
|
||||||
|
|
||||||
## 3. AnatomyCanvas — height constraint + touch
|
|
||||||
|
|
||||||
**Files**: `src/components/canvas/AnatomyCanvas.tsx`, `src/app/routes/EditorRoute.tsx`
|
|
||||||
|
|
||||||
- Mobile: `max-h-[60vh]` on canvas wrapper so observations panel stays visible
|
|
||||||
- `overflow-hidden` on wrapper
|
|
||||||
- CSS `touch-action: pan-x pan-y` for native scroll compatibility
|
|
||||||
|
|
||||||
## 4. Touch targets — minimum 40px
|
|
||||||
|
|
||||||
**Files**: `src/components/ui/Button.tsx`, `src/components/observation/VertebraPicker.tsx`, `src/components/ui/Chip.tsx`
|
|
||||||
|
|
||||||
- Button `sm` size: `h-8` → `h-9 sm:h-8` (36px mobile, 32px desktop) — compromise between touch and density
|
|
||||||
- VertebraPicker region tabs: add `min-h-[2.75rem]` (44px)
|
|
||||||
- Any interactive Chip: ensure `min-h-[2.5rem]`
|
|
||||||
|
|
||||||
## 5. Responsive typography
|
|
||||||
|
|
||||||
**Files**: all route components, `ObservationList.tsx`, `ConclusionPanel.tsx`
|
|
||||||
|
|
||||||
Pattern:
|
|
||||||
- Page headings: `text-xl sm:text-2xl md:text-3xl`
|
|
||||||
- Section headings: `text-lg sm:text-xl`
|
|
||||||
- Form legends: `text-lg sm:text-xl`
|
|
||||||
|
|
||||||
## 6. Padding normalization
|
|
||||||
|
|
||||||
**Files**: all route components
|
|
||||||
|
|
||||||
- Route containers: `px-4 sm:px-6`
|
|
||||||
- Gaps: `gap-4 sm:gap-6`
|
|
||||||
- Consistent tightening on phone
|
|
||||||
|
|
||||||
## 7. Editor layout mobile polish
|
|
||||||
|
|
||||||
**File**: `src/app/routes/EditorRoute.tsx`
|
|
||||||
|
|
||||||
- Single-column below `lg`: SVG canvas explicit height cap
|
|
||||||
- Observations section scrollable independently
|
|
||||||
- Sticky observation header on mobile for context
|
|
||||||
|
|
||||||
## 8. Footer + Header
|
|
||||||
|
|
||||||
**Files**: `src/components/brand/Footer.tsx`, `src/components/brand/AppHeader.tsx`
|
|
||||||
|
|
||||||
- Footer: `gap-2 sm:gap-4`
|
|
||||||
- Header: already responsive (tagline hidden <sm) — minimal tweaks if needed
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Out of scope
|
|
||||||
|
|
||||||
- No layout redesign (tab-based editor, bottom sheets, etc.)
|
|
||||||
- No feature gating per viewport
|
|
||||||
- No pinch-zoom gestures on canvas
|
|
||||||
- No SVG editor feature disabling on phone
|
|
||||||
- No PDF or schema changes
|
|
||||||
|
|
||||||
## Success criteria
|
|
||||||
|
|
||||||
- All routes usable on 375px viewport (iPhone SE)
|
|
||||||
- All interactive elements ≥ 40px touch target
|
|
||||||
- No horizontal overflow on any page
|
|
||||||
- Dialogs fit within viewport on all sizes
|
|
||||||
- SVG editor usable (stacked) on tablet
|
|
||||||
- Tests still pass (no behavior changes)
|
|
||||||
File diff suppressed because it is too large.
Load diff
Vendored
+12
@@ -0,0 +1,12 @@
|
|||||||
|
# Test fixtures
|
||||||
|
|
||||||
|
Golden inputs frozen for the characterisation tests (plan Step 1). They describe
|
||||||
|
the Report v2 document as the current application produces it.
|
||||||
|
|
||||||
|
| File | Content |
|
||||||
|
|---|---|
|
||||||
|
| `report-v2.full.json` | One report exercising every zone kind the editor can produce: plain hinge point, bilateral joint with both sides, spine zone with vertebrae, detail-popup zone, catalog findings (with and without vet referral and side), free text, severity, comment, conclusion, recommendations, dated next appointment. `boneId` values are the real `data-anno-id` of `public/species/equine/*.svg`; `zoneId`/`path` values exist in `pathologies.json`. |
|
||||||
|
| `report-v2.minimal.json` | Smallest valid v2 report (no observations). |
|
||||||
|
|
||||||
|
Do not edit these files to make a test pass: they are the behavioural oracle for
|
||||||
|
the Report v2 → v3 adapter and for PDF regression. Add a new fixture instead.
|
||||||
Vendored
+89
@@ -0,0 +1,89 @@
|
|||||||
|
{
|
||||||
|
"version": 2,
|
||||||
|
"id": "fixture-full-v2",
|
||||||
|
"createdAt": "2026-06-01T09:00:00.000Z",
|
||||||
|
"date": "2026-06-01",
|
||||||
|
"practitioner": {
|
||||||
|
"name": "Dr. Claire Dupont",
|
||||||
|
"cabinet": "Cabinet Équi-Ostéo",
|
||||||
|
"contact": "claire@example.test",
|
||||||
|
"siret": "12345678901234"
|
||||||
|
},
|
||||||
|
"animal": {
|
||||||
|
"speciesId": "equine",
|
||||||
|
"name": "Mistral",
|
||||||
|
"breed": "Selle Français",
|
||||||
|
"age": "9 ans"
|
||||||
|
},
|
||||||
|
"owner": { "name": "Jean Martin" },
|
||||||
|
"observations": [
|
||||||
|
{
|
||||||
|
"id": "obs-1",
|
||||||
|
"zones": [
|
||||||
|
{ "boneId": "point-mpbwyyc9" },
|
||||||
|
{ "boneId": "point-mpbwtst0", "side": "left" },
|
||||||
|
{ "boneId": "point-mpbwtst0", "side": "right" }
|
||||||
|
],
|
||||||
|
"findings": [
|
||||||
|
{
|
||||||
|
"zoneId": "c7-t1",
|
||||||
|
"path": ["c7-t1-dysfunctions", "segmental", "fixation"],
|
||||||
|
"labelFrSnapshot": "Fixation de la charnière",
|
||||||
|
"labelEnSnapshot": "Junction fixation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"zoneId": "hip",
|
||||||
|
"path": ["hip-dysfunctions", "articular", "restriction-flexion"],
|
||||||
|
"labelFrSnapshot": "Restriction en flexion",
|
||||||
|
"labelEnSnapshot": "Flexion restriction",
|
||||||
|
"side": "left"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"freeTextFindings": ["Sensibilité au garrot"],
|
||||||
|
"severity": "modérée",
|
||||||
|
"comment": "Réagit à la palpation du garrot."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-2",
|
||||||
|
"zones": [
|
||||||
|
{
|
||||||
|
"boneId": "zone-mpbx5hx2",
|
||||||
|
"vertebrae": [
|
||||||
|
{ "region": "C", "index": 3 },
|
||||||
|
{ "region": "C", "index": 4 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"findings": [
|
||||||
|
{
|
||||||
|
"zoneId": "cervical",
|
||||||
|
"path": ["cervical-observations", "stumbling-proprioceptive"],
|
||||||
|
"labelFrSnapshot": "Trébuchements / déficit proprioceptif rapporté",
|
||||||
|
"labelEnSnapshot": "Reported stumbling / proprioceptive deficit",
|
||||||
|
"requiresVetReferral": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"freeTextFindings": [],
|
||||||
|
"severity": "sévère",
|
||||||
|
"comment": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-3",
|
||||||
|
"zones": [{ "boneId": "point-mpbyo7zq", "detailSourceId": "head" }],
|
||||||
|
"findings": [
|
||||||
|
{
|
||||||
|
"zoneId": "atm",
|
||||||
|
"path": ["atm-observations", "headshaking"],
|
||||||
|
"labelFrSnapshot": "Headshaking (secouement de tête)",
|
||||||
|
"labelEnSnapshot": "Headshaking",
|
||||||
|
"requiresVetReferral": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"freeTextFindings": [],
|
||||||
|
"comment": "Vue détail tête."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"conclusion": "Dysfonction cervico-thoracique avec compensation du bassin.",
|
||||||
|
"recommendations": "Repos 3 jours puis reprise progressive.",
|
||||||
|
"nextAppointment": { "kind": "date", "date": "2026-07-01" }
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"version": 2,
|
||||||
|
"id": "fixture-minimal-v2",
|
||||||
|
"createdAt": "2026-06-01T09:00:00.000Z",
|
||||||
|
"date": "2026-06-01",
|
||||||
|
"practitioner": { "name": "Dr. Dupont" },
|
||||||
|
"animal": { "speciesId": "equine", "name": "Mistral" },
|
||||||
|
"owner": { "name": "Jean Martin" },
|
||||||
|
"observations": [],
|
||||||
|
"conclusion": "",
|
||||||
|
"recommendations": ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
/**
|
||||||
|
* Characterisation (Step 1): the equine findings catalog as it exists today.
|
||||||
|
* Pins the facts of docs/faunosteo-audit/05-findings-editor.md §2.4 so that
|
||||||
|
* the future legacy importer (plan Step 4) can be checked against them, and
|
||||||
|
* so that any deliberate business correction shows up as a test change.
|
||||||
|
*
|
||||||
|
* Reads the files directly (no Zod) to count what is really on disk.
|
||||||
|
*/
|
||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { dirname, resolve } from 'node:path'
|
||||||
|
import { SpeciesFindingsSchema } from '@/domain/schema/findings'
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const SRC_PATH = resolve(HERE, '../../src/domain/species/equine/pathologies.json')
|
||||||
|
const PUBLIC_PATH = resolve(HERE, '../../public/species/equine/pathologies.json')
|
||||||
|
|
||||||
|
interface RawNode {
|
||||||
|
id: string
|
||||||
|
name_fr?: string
|
||||||
|
name_en?: string
|
||||||
|
description_fr?: string
|
||||||
|
description_en?: string
|
||||||
|
requires_vet_referral?: boolean
|
||||||
|
sources?: unknown[]
|
||||||
|
children?: RawNode[]
|
||||||
|
}
|
||||||
|
interface RawZone { id: string; name_fr: string; name_en: string; categories: RawNode[] }
|
||||||
|
interface RawCatalog {
|
||||||
|
schema_version: string
|
||||||
|
scope_disclaimer: string
|
||||||
|
species: { id: string; name_fr: string; name_en: string }
|
||||||
|
zones: Record<string, RawZone>
|
||||||
|
}
|
||||||
|
|
||||||
|
const srcText = readFileSync(SRC_PATH, 'utf8')
|
||||||
|
const catalog = JSON.parse(srcText) as RawCatalog
|
||||||
|
const zoneKeys = Object.keys(catalog.zones)
|
||||||
|
|
||||||
|
function walk(nodes: RawNode[], depth: number, visit: (n: RawNode, depth: number) => void) {
|
||||||
|
for (const n of nodes) {
|
||||||
|
visit(n, depth)
|
||||||
|
if (n.children) walk(n.children, depth + 1, visit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function allNodes(): Array<{ node: RawNode; depth: number; zone: string }> {
|
||||||
|
const out: Array<{ node: RawNode; depth: number; zone: string }> = []
|
||||||
|
for (const key of zoneKeys) {
|
||||||
|
walk(catalog.zones[key].categories, 1, (node, depth) => out.push({ node, depth, zone: key }))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
const isLeaf = (n: RawNode) => !n.children || n.children.length === 0
|
||||||
|
|
||||||
|
describe('catalog copies (src vs public)', () => {
|
||||||
|
it('the two pathologies.json copies are byte-identical (manual sync, no script)', () => {
|
||||||
|
const publicText = readFileSync(PUBLIC_PATH, 'utf8')
|
||||||
|
const md5 = (s: string) => createHash('md5').update(s).digest('hex')
|
||||||
|
expect(md5(publicText)).toBe(md5(srcText))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('the bundled copy passes the Zod schema (boot-time contract)', () => {
|
||||||
|
expect(() => SpeciesFindingsSchema.parse(catalog)).not.toThrow()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('catalog shape (audit 05 §2.4)', () => {
|
||||||
|
it('declares schema_version "2.0" and species equine / Cheval / Horse', () => {
|
||||||
|
expect(catalog.schema_version).toBe('2.0')
|
||||||
|
expect(catalog.species).toEqual({ id: 'equine', name_fr: 'Cheval', name_en: 'Horse' })
|
||||||
|
expect(catalog.scope_disclaimer.length).toBeGreaterThan(50)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('has exactly 26 zones in cranio-caudal insertion order', () => {
|
||||||
|
expect(zoneKeys).toEqual([
|
||||||
|
'parietal', 'frontal', 'sphenoid', 'temporal', 'occipital', 'ssb', 'atm', 'hyoid',
|
||||||
|
'c0-c1', 'cervical', 'c7-t1', 'shoulder', 'elbow', 'fore-fetlock', 'fore-sesamoids',
|
||||||
|
'thoracic', 't18-l1', 'lumbar', 'l6-s1', 'sacral', 'sacroiliac', 'hip', 'stifle',
|
||||||
|
'hock', 'hind-fetlock', 'caudal',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('every zone.id equals its record key (convention, not enforced by Zod)', () => {
|
||||||
|
for (const key of zoneKeys) expect(catalog.zones[key].id).toBe(key)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('every zone has exactly 3 root categories, the third always "anamnesis"', () => {
|
||||||
|
for (const key of zoneKeys) {
|
||||||
|
const cats = catalog.zones[key].categories
|
||||||
|
expect(cats, key).toHaveLength(3)
|
||||||
|
expect(cats[2].id, key).toBe('anamnesis')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('root category ids follow <zone>-dysfunctions / <zone>-observations, except the known sphenoid anomaly', () => {
|
||||||
|
const anomalies: string[] = []
|
||||||
|
for (const key of zoneKeys) {
|
||||||
|
const [dys, obs] = catalog.zones[key].categories
|
||||||
|
if (dys.id !== `${key}-dysfunctions`) anomalies.push(`${key}:${dys.id}`)
|
||||||
|
if (obs.id !== `${key}-observations`) anomalies.push(`${key}:${obs.id}`)
|
||||||
|
}
|
||||||
|
// KNOWN: sphenoid reuses the ssb category id (audit 05 §2.4). The business
|
||||||
|
// correction is deferred to the editor before the first official version
|
||||||
|
// (OPEN_QUESTIONS Q9); the importer must NOT silently fix it.
|
||||||
|
expect(anomalies).toEqual(['sphenoid:ssb-dysfunctions'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('counts 792 nodes, 612 leaves, max depth 3, 228 leaves at depth 2 and 384 at depth 3', () => {
|
||||||
|
const nodes = allNodes()
|
||||||
|
expect(nodes).toHaveLength(792)
|
||||||
|
const leaves = nodes.filter((n) => isLeaf(n.node))
|
||||||
|
expect(leaves).toHaveLength(612)
|
||||||
|
expect(Math.max(...nodes.map((n) => n.depth))).toBe(3)
|
||||||
|
expect(leaves.filter((n) => n.depth === 2)).toHaveLength(228)
|
||||||
|
expect(leaves.filter((n) => n.depth === 3)).toHaveLength(384)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('flags 41 vet-referral nodes, all of them leaves', () => {
|
||||||
|
const flagged = allNodes().filter((n) => n.node.requires_vet_referral === true)
|
||||||
|
expect(flagged).toHaveLength(41)
|
||||||
|
expect(flagged.every((n) => isLeaf(n.node))).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('carries 62 description_fr, 0 description_en, 0 sources (CLAUDE.md "≥1 source" rule not met)', () => {
|
||||||
|
const nodes = allNodes()
|
||||||
|
expect(nodes.filter((n) => typeof n.node.description_fr === 'string')).toHaveLength(62)
|
||||||
|
expect(nodes.filter((n) => typeof n.node.description_en === 'string')).toHaveLength(0)
|
||||||
|
expect(nodes.filter((n) => Array.isArray(n.node.sources))).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('every node has non-empty name_fr and name_en', () => {
|
||||||
|
for (const { node, zone } of allNodes()) {
|
||||||
|
expect(node.name_fr, `${zone}/${node.id}`).toBeTruthy()
|
||||||
|
expect(node.name_en, `${zone}/${node.id}`).toBeTruthy()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('node ids are unique among siblings only (same id reused across zones)', () => {
|
||||||
|
const idCount = new Map<string, number>()
|
||||||
|
for (const { node } of allNodes()) idCount.set(node.id, (idCount.get(node.id) ?? 0) + 1)
|
||||||
|
expect(idCount.get('anamnesis')).toBe(26)
|
||||||
|
expect(idCount.get('trauma-direct')).toBe(26)
|
||||||
|
expect(idCount.get('no-identified-cause')).toBe(26)
|
||||||
|
expect(idCount.get('amplitude-asymmetry')).toBe(11)
|
||||||
|
// sibling uniqueness holds everywhere
|
||||||
|
const checkSiblings = (nodes: RawNode[], where: string) => {
|
||||||
|
const ids = nodes.map((n) => n.id)
|
||||||
|
expect(new Set(ids).size, where).toBe(ids.length)
|
||||||
|
for (const n of nodes) if (n.children) checkSiblings(n.children, `${where}/${n.id}`)
|
||||||
|
}
|
||||||
|
for (const key of zoneKeys) checkSiblings(catalog.zones[key].categories, key)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('anamnesis exists in exactly three content variants (vertebral / appendicular / head)', () => {
|
||||||
|
const variants = new Map<string, string[]>()
|
||||||
|
for (const key of zoneKeys) {
|
||||||
|
const anam = catalog.zones[key].categories[2]
|
||||||
|
const sig = (anam.children ?? []).map((c) => c.id).join(',')
|
||||||
|
variants.set(sig, [...(variants.get(sig) ?? []), key])
|
||||||
|
}
|
||||||
|
expect(variants.size).toBe(3)
|
||||||
|
const groups = [...variants.values()].map((g) => g.length).sort((a, b) => a - b)
|
||||||
|
expect(groups).toEqual([8, 9, 9])
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
/**
|
||||||
|
* Characterisation (Step 1): the zone-click chain of EditorRoute
|
||||||
|
* (onZoneClick → detail / fallback / spine / bilateral / toggle), the
|
||||||
|
* disclaimer-once-per-session rule, the zone removal and the pickers'
|
||||||
|
* integration with the store. Exercised through the rendered route on the
|
||||||
|
* real Horse.svg / Horse_head.svg, with loadSvg mocked to read the files.
|
||||||
|
*
|
||||||
|
* Limitation: the chain lives inside the route component (audit 13 §4, no
|
||||||
|
* unit seam). These tests go through the DOM; plan Step 5 extracts the
|
||||||
|
* chain into a service and will replace them with unit tests one-to-one.
|
||||||
|
*/
|
||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||||
|
import { render, screen, waitFor, within, cleanup } from '@testing-library/react'
|
||||||
|
import userEvent from '@testing-library/user-event'
|
||||||
|
import { MemoryRouter } from 'react-router-dom'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { dirname, resolve } from 'node:path'
|
||||||
|
import EditorRoute from '@/app/routes/EditorRoute'
|
||||||
|
import { useReportStore } from '@/state/reportStore'
|
||||||
|
import { useLocaleStore } from '@/state/localeStore'
|
||||||
|
import { fr } from '@/i18n/fr'
|
||||||
|
import minimal from '../fixtures/report-v2.minimal.json'
|
||||||
|
import type { Report } from '@/domain/schema/report'
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const FILES: Record<string, string> = {
|
||||||
|
'/species/equine/Horse.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8'),
|
||||||
|
'/species/equine/Horse_head.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8'),
|
||||||
|
}
|
||||||
|
|
||||||
|
vi.mock('@/anatomy/svgLoader', () => ({
|
||||||
|
loadSvg: vi.fn(async (path: string) => {
|
||||||
|
const text = FILES[path]
|
||||||
|
if (!text) throw new Error(`unexpected path ${path}`)
|
||||||
|
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
|
||||||
|
return doc.documentElement as unknown as SVGSVGElement
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const HINGE = 'point-mpbwyyc9' // Charnière C7-T1, plain point
|
||||||
|
const HIP = 'point-mpbwtst0' // bilateral
|
||||||
|
const CERVICAL = 'zone-mpbx5hx2' // vertebral-precision
|
||||||
|
const TRIGGER = 'zone-mpby55kd' // opens-detail=head
|
||||||
|
const ATM = 'point-mpbyo7zq' // in Horse_head.svg
|
||||||
|
|
||||||
|
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
|
||||||
|
|
||||||
|
function seedReport(observations: Report['observations'] = []) {
|
||||||
|
useReportStore.setState({ report: null, activeObservationIndex: 0 })
|
||||||
|
useReportStore.getState().initReport({
|
||||||
|
...(minimal as Report),
|
||||||
|
observations,
|
||||||
|
} as Omit<Report, 'id' | 'createdAt' | 'version'>)
|
||||||
|
}
|
||||||
|
|
||||||
|
const zonesOf = (i = 0) => useReportStore.getState().report!.observations[i].zones
|
||||||
|
const activeIndex = () => useReportStore.getState().activeObservationIndex
|
||||||
|
|
||||||
|
async function mount() {
|
||||||
|
const utils = render(
|
||||||
|
<MemoryRouter initialEntries={['/editor']}>
|
||||||
|
<EditorRoute />
|
||||||
|
</MemoryRouter>,
|
||||||
|
)
|
||||||
|
// Main SVG rendered and parsed (bones map ready once the trigger exists).
|
||||||
|
await waitFor(() => expect(document.querySelector(`[data-anno-id="${TRIGGER}"]`)).not.toBeNull())
|
||||||
|
// Give the bones state effect a tick so onZoneClick resolves ids.
|
||||||
|
await waitFor(() => expect(screen.queryByRole('dialog', { name: fr['editor.disclaimer_title'] })).toBeNull())
|
||||||
|
return utils
|
||||||
|
}
|
||||||
|
|
||||||
|
function clickZone(id: string, scope: ParentNode = document) {
|
||||||
|
const els = scope.querySelectorAll(`[data-anno-id="${id}"]`)
|
||||||
|
expect(els.length, id).toBeGreaterThan(0)
|
||||||
|
els[0].dispatchEvent(new Event('click', { bubbles: true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
sessionStorage.clear()
|
||||||
|
sessionStorage.setItem(DISCLAIMER_FLAG, '1')
|
||||||
|
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
|
||||||
|
seedReport()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('disclaimer', () => {
|
||||||
|
it('shows the catalog scope_disclaimer once per session and records the flag', async () => {
|
||||||
|
sessionStorage.removeItem(DISCLAIMER_FLAG)
|
||||||
|
render(
|
||||||
|
<MemoryRouter initialEntries={['/editor']}>
|
||||||
|
<EditorRoute />
|
||||||
|
</MemoryRouter>,
|
||||||
|
)
|
||||||
|
const dialog = await screen.findByRole('dialog', { name: fr['editor.disclaimer_title'] })
|
||||||
|
expect(dialog.textContent).toContain('Aucun diagnostic médical')
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.understood'] }))
|
||||||
|
expect(sessionStorage.getItem(DISCLAIMER_FLAG)).toBe('1')
|
||||||
|
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('plain zone (toggle)', () => {
|
||||||
|
it('adds the zone on first click and removes it on second click', async () => {
|
||||||
|
await mount()
|
||||||
|
clickZone(HINGE)
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HINGE }]))
|
||||||
|
clickZone(HINGE)
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([]))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('highlights the zone of the active observation with data-state="current"', async () => {
|
||||||
|
await mount()
|
||||||
|
clickZone(HINGE)
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(document.querySelector(`[data-anno-id="${HINGE}"]`)?.getAttribute('data-state')).toBe('current'),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('no active observation (fallback)', () => {
|
||||||
|
it('re-activates the last observation and drops the click (user must click again)', async () => {
|
||||||
|
await mount()
|
||||||
|
// Collapse the only card through the UI (sets activeObservationIndex to -1).
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: `${fr['observation.collapse_aria']} 1` }))
|
||||||
|
await waitFor(() => expect(activeIndex()).toBe(-1))
|
||||||
|
clickZone(HINGE)
|
||||||
|
await waitFor(() => expect(activeIndex()).toBe(0))
|
||||||
|
expect(zonesOf()).toEqual([])
|
||||||
|
clickZone(HINGE)
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HINGE }]))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('detail trigger', () => {
|
||||||
|
it('opens the detail modal, never adds the trigger as a zone, and zones clicked inside carry detailSourceId', async () => {
|
||||||
|
await mount()
|
||||||
|
clickZone(TRIGGER)
|
||||||
|
const dialog = await screen.findByRole('dialog', { name: `${fr['editor.detail_title_prefix']}head` })
|
||||||
|
expect(zonesOf()).toEqual([])
|
||||||
|
await waitFor(() => expect(dialog.querySelector(`[data-anno-id="${ATM}"]`)).not.toBeNull())
|
||||||
|
clickZone(ATM, dialog)
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: ATM, detailSourceId: 'head' }]))
|
||||||
|
// Toggle off from inside the modal uses the same (boneId, detailSourceId) identity.
|
||||||
|
clickZone(ATM, dialog)
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([]))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('spine zone (vertebral-precision)', () => {
|
||||||
|
it('adds the zone, opens the picker on the matching region, and never toggles off on re-click', async () => {
|
||||||
|
await mount()
|
||||||
|
clickZone(CERVICAL)
|
||||||
|
const dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
|
||||||
|
expect(zonesOf()).toEqual([{ boneId: CERVICAL }])
|
||||||
|
expect(within(dialog).getByRole('tab', { name: fr['vertebra.region.C'] })).toHaveAttribute('aria-selected', 'true')
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: 'C3' }))
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] }))
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: CERVICAL, vertebrae: [{ region: 'C', index: 3 }] }]))
|
||||||
|
|
||||||
|
clickZone(CERVICAL)
|
||||||
|
await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
|
||||||
|
expect(zonesOf()).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cancelling the picker leaves a spine zone without vertebrae', async () => {
|
||||||
|
await mount()
|
||||||
|
clickZone(CERVICAL)
|
||||||
|
const dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.cancel'] }))
|
||||||
|
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||||
|
expect(zonesOf()).toEqual([{ boneId: CERVICAL }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('picking another region in the picker spawns that region zone and pruning to zero removes a zone', async () => {
|
||||||
|
await mount()
|
||||||
|
clickZone(CERVICAL)
|
||||||
|
let dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: 'C3' }))
|
||||||
|
await userEvent.click(within(dialog).getByRole('tab', { name: fr['vertebra.region.L'] }))
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: 'L2' }))
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] }))
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(zonesOf()).toEqual([
|
||||||
|
{ boneId: CERVICAL, vertebrae: [{ region: 'C', index: 3 }] },
|
||||||
|
{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] },
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
clickZone(CERVICAL)
|
||||||
|
dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: 'C3' })) // uncheck
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] }))
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] }]))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('bilateral zone', () => {
|
||||||
|
it('asks for a side, adds one zone per side, and clears both when both are present', async () => {
|
||||||
|
await mount()
|
||||||
|
clickZone(HIP)
|
||||||
|
let dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' })
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.left'] }))
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HIP, side: 'left' }]))
|
||||||
|
|
||||||
|
clickZone(HIP)
|
||||||
|
dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' })
|
||||||
|
expect(within(dialog).getByRole('button', { name: fr['lateral.left'] })).toBeDisabled()
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.right'] }))
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(zonesOf()).toEqual([
|
||||||
|
{ boneId: HIP, side: 'left' },
|
||||||
|
{ boneId: HIP, side: 'right' },
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
|
||||||
|
clickZone(HIP)
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([]))
|
||||||
|
expect(screen.queryByRole('dialog')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('"both" adds the missing sides only', async () => {
|
||||||
|
await mount()
|
||||||
|
clickZone(HIP)
|
||||||
|
const dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' })
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.both'] }))
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(zonesOf()).toEqual([
|
||||||
|
{ boneId: HIP, side: 'left' },
|
||||||
|
{ boneId: HIP, side: 'right' },
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('zone removal and orphan findings', () => {
|
||||||
|
it('KNOWN: removing a zone via ✕ keeps the findings attached to its catalog zone', async () => {
|
||||||
|
seedReport([
|
||||||
|
{
|
||||||
|
id: 'obs-a',
|
||||||
|
zones: [{ boneId: HINGE }],
|
||||||
|
findings: [
|
||||||
|
{
|
||||||
|
zoneId: 'c7-t1',
|
||||||
|
path: ['c7-t1-dysfunctions', 'segmental', 'fixation'],
|
||||||
|
labelFrSnapshot: 'Fixation de la charnière',
|
||||||
|
labelEnSnapshot: 'Junction fixation',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
freeTextFindings: [],
|
||||||
|
comment: '',
|
||||||
|
},
|
||||||
|
])
|
||||||
|
await mount()
|
||||||
|
const remove = await screen.findByRole('button', {
|
||||||
|
name: `${fr['observation.remove_zone']} Charnière C7-T1 (cervico-thoracique)`,
|
||||||
|
})
|
||||||
|
await userEvent.click(remove)
|
||||||
|
await waitFor(() => expect(zonesOf()).toEqual([]))
|
||||||
|
expect(useReportStore.getState().report!.observations[0].findings).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows one findings picker per (catalog zone, side) resolved by label match', async () => {
|
||||||
|
seedReport([
|
||||||
|
{
|
||||||
|
id: 'obs-b',
|
||||||
|
zones: [
|
||||||
|
{ boneId: HIP, side: 'left' },
|
||||||
|
{ boneId: HIP, side: 'right' },
|
||||||
|
{ boneId: HINGE },
|
||||||
|
{ boneId: TRIGGER },
|
||||||
|
],
|
||||||
|
findings: [],
|
||||||
|
freeTextFindings: [],
|
||||||
|
comment: '',
|
||||||
|
},
|
||||||
|
])
|
||||||
|
await mount()
|
||||||
|
await screen.findByRole('button', { name: /Hanche \(coxo-fémorale\) \(Gauche\)/ })
|
||||||
|
screen.getByRole('button', { name: /Hanche \(coxo-fémorale\) \(Droite\)/ })
|
||||||
|
screen.getByRole('button', { name: /^Charnière C7-T1 \(cervico-thoracique\)$/ })
|
||||||
|
// The trigger has no label and no catalog zone: exactly 3 pickers, and its
|
||||||
|
// badge falls back to the raw boneId.
|
||||||
|
expect(document.querySelectorAll('[aria-controls^="findings-zone-"]')).toHaveLength(3)
|
||||||
|
expect(
|
||||||
|
screen.getByRole('button', { name: `${fr['observation.remove_zone']} ${TRIGGER}` }),
|
||||||
|
).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
/**
|
||||||
|
* Characterisation (Step 1): dictionary keys the runtime builds dynamically
|
||||||
|
* (severity.<fr value>, vertebra.region.<code>, import error kinds, PDF
|
||||||
|
* section labels), label fallbacks, the species registry and the
|
||||||
|
* scaffold script quirks (audit 12 §1).
|
||||||
|
*/
|
||||||
|
import { describe, it, expect, beforeEach } from 'vitest'
|
||||||
|
import { render, screen } from '@testing-library/react'
|
||||||
|
import { MemoryRouter } from 'react-router-dom'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { dirname, resolve } from 'node:path'
|
||||||
|
import { fr } from '@/i18n/fr'
|
||||||
|
import { en } from '@/i18n/en'
|
||||||
|
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||||
|
import { boneLabel } from '@/anatomy/labels'
|
||||||
|
import { SeveritySchema, VertebralRegionSchema } from '@/domain/schema/observation'
|
||||||
|
import { getAllSpecies, getSpecies, speciesLabel } from '@/domain/species/registry'
|
||||||
|
import { EQUINE_VERTEBRAL_FORMULA } from '@/domain/species/equine/vertebrae'
|
||||||
|
import NewReportRoute from '@/app/routes/NewReportRoute'
|
||||||
|
import { useLocaleStore } from '@/state/localeStore'
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||||
|
|
||||||
|
describe('dynamic dictionary keys', () => {
|
||||||
|
it('has a severity.* key for every stored severity value, in both dicts', () => {
|
||||||
|
for (const s of SeveritySchema.options) {
|
||||||
|
expect(fr[`severity.${s}`]).toBeTruthy()
|
||||||
|
expect(en[`severity.${s}`]).toBeTruthy()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('has a vertebra.region.* key for every region code', () => {
|
||||||
|
for (const r of VertebralRegionSchema.options) {
|
||||||
|
expect(fr[`vertebra.region.${r}`]).toBeTruthy()
|
||||||
|
expect(en[`vertebra.region.${r}`]).toBeTruthy()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('has one message per ImportError kind plus a generic one, with a {version} placeholder', () => {
|
||||||
|
for (const k of ['invalid_pdf', 'no_attachment', 'incompatible_version', 'generic']) {
|
||||||
|
expect(fr[`home.import.error_${k}`]).toBeTruthy()
|
||||||
|
expect(en[`home.import.error_${k}`]).toBeTruthy()
|
||||||
|
}
|
||||||
|
expect(fr['home.import.error_incompatible_version']).toContain('{version}')
|
||||||
|
expect(en['home.import.error_incompatible_version']).toContain('{version}')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('exposes the PDF section and view labels used by the renderer', () => {
|
||||||
|
for (const k of [
|
||||||
|
'pdf.section.zones', 'pdf.section.findings_prefix', 'pdf.section.free_findings',
|
||||||
|
'pdf.section.severity', 'pdf.section.comment', 'pdf.section.conclusion',
|
||||||
|
'pdf.section.recommendations', 'pdf.section.next_appointment', 'pdf.view.general',
|
||||||
|
'pdf.view.detail_prefix', 'pdf.empty', 'pdf.title.suffix.bilan', 'pdf.subject',
|
||||||
|
]) {
|
||||||
|
expect(fr[k], k).toBeTruthy()
|
||||||
|
expect(en[k], k).toBeTruthy()
|
||||||
|
}
|
||||||
|
expect(fr['pdf.section.findings_prefix']).toBe('CONSTATS — ')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('carries 71 svg_editor.* keys that die with the SVG editor', () => {
|
||||||
|
expect(Object.keys(fr).filter((k) => k.startsWith('svg_editor.'))).toHaveLength(71)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('label fallbacks', () => {
|
||||||
|
it('pickLocaleLabel falls back to the other language, then to the fallback', () => {
|
||||||
|
expect(pickLocaleLabel('FR', 'EN', 'fr')).toBe('FR')
|
||||||
|
expect(pickLocaleLabel('', 'EN', 'fr')).toBe('EN')
|
||||||
|
expect(pickLocaleLabel('FR', '', 'en')).toBe('FR')
|
||||||
|
expect(pickLocaleLabel('', '', 'en', 'id')).toBe('id')
|
||||||
|
expect(pickLocaleLabel(undefined, undefined, 'fr')).toBe('')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('boneLabel returns the raw fallback for an unknown bone', () => {
|
||||||
|
expect(boneLabel(undefined, 'fr', 'point-x')).toBe('point-x')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('species registry', () => {
|
||||||
|
it('registers exactly one species, equine, with the committed manifest values', () => {
|
||||||
|
expect(getAllSpecies().map((s) => s.id)).toEqual(['equine'])
|
||||||
|
const eq = getSpecies('equine')!
|
||||||
|
expect(speciesLabel(eq, 'fr')).toBe('Cheval')
|
||||||
|
expect(speciesLabel(eq, 'en')).toBe('Horse')
|
||||||
|
expect(eq.vertebralFormula).toEqual({ C: 7, T: 18, L: 6, S: 5, Cd: 18 })
|
||||||
|
expect(EQUINE_VERTEBRAL_FORMULA).toEqual(eq.vertebralFormula)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('the catalog loader resolves the same species id as the manifest', async () => {
|
||||||
|
const m = await getSpecies('equine')!.findings()
|
||||||
|
expect(m.default.species.id).toBe('equine')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('NewReportRoute defaults the species select to equine', () => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
render(
|
||||||
|
<MemoryRouter>
|
||||||
|
<NewReportRoute />
|
||||||
|
</MemoryRouter>,
|
||||||
|
)
|
||||||
|
const select = screen.getByRole('combobox') as HTMLSelectElement
|
||||||
|
expect(select.value).toBe('equine')
|
||||||
|
expect(select.options).toHaveLength(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('scaffold script quirks (audit 12 §1, kept as-is, script slated for removal)', () => {
|
||||||
|
const src = readFileSync(resolve(HERE, '../../scripts/scaffold-species.mjs'), 'utf8')
|
||||||
|
|
||||||
|
it("writes schema_version '1.1' while the horse catalog is at '2.0'", () => {
|
||||||
|
expect(src).toContain("schema_version: '1.1'")
|
||||||
|
})
|
||||||
|
|
||||||
|
it('defaults the vertebral formula to C7 T13 L6 S5 Cd18 (mixed canine/equine)', () => {
|
||||||
|
expect(src).toMatch(/askPositiveInt\('\s*cervical \(C\)', 7\)/)
|
||||||
|
expect(src).toMatch(/askPositiveInt\('\s*thoracic \(T\)', 13\)/)
|
||||||
|
expect(src).toMatch(/askPositiveInt\('\s*lumbar \(L\)', 6\)/)
|
||||||
|
expect(src).toMatch(/askPositiveInt\('\s*sacral \(S\)', 5\)/)
|
||||||
|
expect(src).toMatch(/askPositiveInt\('\s*caudal \(Cd\)', 18\)/)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
})
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
/**
|
||||||
|
* Characterisation (Step 1): public/pathology-editor.html, the standalone
|
||||||
|
* findings editor. Its JavaScript is extracted by text and evaluated so that
|
||||||
|
* the inline matcher, id generator, translations and species config are
|
||||||
|
* pinned without touching the file (BDR-020/021, LRN-026).
|
||||||
|
*
|
||||||
|
* Limitation: the DOM-editing behaviour (tree add/edit/delete, dirty flag,
|
||||||
|
* download) is not executed here; it is described in
|
||||||
|
* docs/faunosteo-audit/05-findings-editor.md §3.5 and will be re-specified
|
||||||
|
* as tests of the merged editor (plan Step 17).
|
||||||
|
*/
|
||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
import { existsSync, readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { dirname, resolve } from 'node:path'
|
||||||
|
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||||||
|
import { matchZoneFindings, normalizeLabel, scorePair } from '@/lib/zoneMatch'
|
||||||
|
import FINDINGS from '@/domain/species/equine/pathologies'
|
||||||
|
import { fr } from '@/i18n/fr'
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const ROOT = resolve(HERE, '../..')
|
||||||
|
const HTML = readFileSync(resolve(ROOT, 'public/pathology-editor.html'), 'utf8')
|
||||||
|
|
||||||
|
function slice(from: string, to: string): string {
|
||||||
|
const a = HTML.indexOf(from)
|
||||||
|
const b = HTML.indexOf(to, a)
|
||||||
|
if (a < 0 || b < 0) throw new Error(`markers not found: ${from} … ${to}`)
|
||||||
|
return HTML.slice(a, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Zone = { id: string; name_fr: string; name_en: string }
|
||||||
|
interface InlineApi {
|
||||||
|
normalizeLabel: (s: string) => string
|
||||||
|
scorePair: (a: string, b: string) => number
|
||||||
|
matchZone: (fr: string, en: string, zones: Zone[]) => Zone | null
|
||||||
|
generateId: (en: string, fr: string, existing: string[]) => string
|
||||||
|
}
|
||||||
|
|
||||||
|
const matcherSrc = slice('function normalizeLabel(s)', '// ── Node stats ──')
|
||||||
|
const inline = new Function(
|
||||||
|
`${matcherSrc}; return { normalizeLabel, scorePair, matchZone, generateId };`,
|
||||||
|
)() as InlineApi
|
||||||
|
|
||||||
|
const translationsSrc = slice('var TRANSLATIONS = ', '\n };') + '\n };'
|
||||||
|
const TRANSLATIONS = new Function(`${translationsSrc} return TRANSLATIONS;`)() as {
|
||||||
|
fr: Record<string, string>
|
||||||
|
en: Record<string, string>
|
||||||
|
}
|
||||||
|
|
||||||
|
const configSrc = slice('var SPECIES_CONFIG = ', '\n ];') + '\n ];'
|
||||||
|
const SPECIES_CONFIG = new Function(`${configSrc} return SPECIES_CONFIG;`)() as Array<{
|
||||||
|
id: string
|
||||||
|
labelKey: string
|
||||||
|
jsonPath: string
|
||||||
|
views: Array<{ labelKey: string; svgPath: string }>
|
||||||
|
}>
|
||||||
|
|
||||||
|
function bones(file: string) {
|
||||||
|
const text = readFileSync(resolve(ROOT, 'public/species/equine', file), 'utf8')
|
||||||
|
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
|
||||||
|
return parseSvgBones(doc.documentElement as unknown as SVGSVGElement)
|
||||||
|
}
|
||||||
|
|
||||||
|
const zones = Object.values(FINDINGS.zones)
|
||||||
|
|
||||||
|
describe('inline matcher parity with src/lib/zoneMatch.ts', () => {
|
||||||
|
const labels: Array<{ fr: string; en: string }> = [
|
||||||
|
...[...bones('Horse.svg').values(), ...bones('Horse_head.svg').values()].map((b) => ({ fr: b.fr, en: b.en })),
|
||||||
|
{ fr: 'Hanche', en: 'Hip' },
|
||||||
|
{ fr: 'ATM', en: 'TMJ' },
|
||||||
|
{ fr: 'Sphenoide', en: 'Sphenoidd' },
|
||||||
|
{ fr: 'Vertèbres sacrales', en: '' },
|
||||||
|
{ fr: '', en: '' },
|
||||||
|
{ fr: 'Boulet ant. (métacarpo-phalangien)', en: 'Fore fetlok' },
|
||||||
|
]
|
||||||
|
|
||||||
|
it('returns the same zone for every real annotation and edge label', () => {
|
||||||
|
for (const l of labels) {
|
||||||
|
const app = matchZoneFindings(l, zones)?.id
|
||||||
|
const editor = inline.matchZone(l.fr, l.en, zones)?.id
|
||||||
|
expect(editor ?? undefined, `${l.fr} / ${l.en}`).toBe(app)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('normalizes and scores identically', () => {
|
||||||
|
for (const s of ['Sphénoïde', 'Charnière C0-C1 (occipito-atloïdienne)', 'Temporomandibular Joint (TMJ)', '']) {
|
||||||
|
expect(inline.normalizeLabel(s)).toBe(normalizeLabel(s))
|
||||||
|
}
|
||||||
|
expect(inline.scorePair('Hip', 'Hip joint')).toBe(scorePair('Hip', 'Hip joint'))
|
||||||
|
expect(inline.scorePair('Sphenoidd', 'Sphenoid')).toBe(scorePair('Sphenoidd', 'Sphenoid'))
|
||||||
|
expect(inline.scorePair('', 'x')).toBe(scorePair('', 'x'))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('inline id generator', () => {
|
||||||
|
it('slugs name_en first, then name_fr, strips accents, suffixes -2 on sibling collision', () => {
|
||||||
|
expect(inline.generateId('Flexion restriction', 'Restriction en flexion', [])).toBe('flexion-restriction')
|
||||||
|
expect(inline.generateId('', 'Tension du splénius', [])).toBe('tension-du-splenius')
|
||||||
|
expect(inline.generateId('Hip', '', ['hip'])).toBe('hip-2')
|
||||||
|
expect(inline.generateId('Hip', '', ['hip', 'hip-2'])).toBe('hip-3')
|
||||||
|
expect(inline.generateId('', '', [])).toBe('node')
|
||||||
|
expect(inline.generateId(' -- ', '', [])).toBe('node')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('inline translations and config', () => {
|
||||||
|
it('fr and en share the same key set (76 keys), independent from the app dictionary', () => {
|
||||||
|
const frKeys = Object.keys(TRANSLATIONS.fr).sort()
|
||||||
|
const enKeys = Object.keys(TRANSLATIONS.en).sort()
|
||||||
|
expect(frKeys).toEqual(enKeys)
|
||||||
|
expect(frKeys).toHaveLength(76)
|
||||||
|
// No shared key space with src/i18n (different naming scheme)
|
||||||
|
expect(frKeys.filter((k) => k in fr)).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shares only the locale storage key with the app', () => {
|
||||||
|
expect(HTML).toContain("localStorage.getItem('osteo:locale')")
|
||||||
|
expect(HTML).toContain("localStorage.setItem('osteo:locale'")
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hard-codes a single species (equine) with two views and the public JSON copy', () => {
|
||||||
|
expect(SPECIES_CONFIG).toHaveLength(1)
|
||||||
|
const [equine] = SPECIES_CONFIG
|
||||||
|
expect(equine.id).toBe('equine')
|
||||||
|
expect(equine.jsonPath).toBe('/species/equine/pathologies.json')
|
||||||
|
expect(equine.views.map((v) => v.svgPath)).toEqual([
|
||||||
|
'/species/equine/Horse.svg',
|
||||||
|
'/species/equine/Horse_head.svg',
|
||||||
|
])
|
||||||
|
for (const p of [equine.jsonPath, ...equine.views.map((v) => v.svgPath)]) {
|
||||||
|
expect(existsSync(resolve(ROOT, 'public', p.slice(1))), p).toBe(true)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('imports nothing from src/ and declares noindex', () => {
|
||||||
|
expect(HTML).not.toMatch(/from\s+['"]\.\.?\/src/)
|
||||||
|
expect(HTML).not.toMatch(/<script[^>]+src=/)
|
||||||
|
expect(HTML).toMatch(/name="robots"\s+content="noindex,\s*nofollow"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('validates only three top-level keys of the loaded JSON (no Zod)', () => {
|
||||||
|
expect(HTML).toMatch(/schema_version/)
|
||||||
|
expect(HTML).not.toMatch(/zod/i)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
/**
|
||||||
|
* Characterisation (Step 1): the full PDF pipeline on the golden fixture
|
||||||
|
* (every zone kind, findings with vet flag and side, free text, severity,
|
||||||
|
* comment, conclusion, next appointment): page count, drawn text, attachment
|
||||||
|
* roundtrip, import error kinds, and the attachment fallback path.
|
||||||
|
*
|
||||||
|
* Text is captured by spying on PDFPage.drawText (pdf-lib has no text
|
||||||
|
* extraction). Rasterization is replaced by a 1×1 PNG: happy-dom has no
|
||||||
|
* canvas. SVG fetches are served from the committed files; logo fetches 404
|
||||||
|
* on purpose to pin the "PDF without logos" degradation.
|
||||||
|
*/
|
||||||
|
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest'
|
||||||
|
import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { dirname, resolve } from 'node:path'
|
||||||
|
import { exportReportToPdf } from '@/pdf/export'
|
||||||
|
import { importReportFromPdf, ImportError } from '@/pdf/import'
|
||||||
|
import { fr } from '@/i18n/fr'
|
||||||
|
import { en } from '@/i18n/en'
|
||||||
|
import full from '../fixtures/report-v2.full.json'
|
||||||
|
import type { Report } from '@/domain/schema/report'
|
||||||
|
|
||||||
|
const ONE_PX_PNG = Uint8Array.from(
|
||||||
|
Buffer.from(
|
||||||
|
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
|
||||||
|
'base64',
|
||||||
|
),
|
||||||
|
)
|
||||||
|
vi.mock('@/pdf/render/svgToPng', () => ({ rasterizeSvg: vi.fn(async () => ONE_PX_PNG) }))
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const FILES: Record<string, string> = {
|
||||||
|
'/species/equine/Horse.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8'),
|
||||||
|
'/species/equine/Horse_head.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8'),
|
||||||
|
}
|
||||||
|
const fetched: string[] = []
|
||||||
|
const realFetch = globalThis.fetch
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||||
|
const url = String(input)
|
||||||
|
fetched.push(url)
|
||||||
|
const text = FILES[url]
|
||||||
|
if (text) return new Response(text, { status: 200, headers: { 'content-type': 'image/svg+xml' } })
|
||||||
|
return new Response('not found', { status: 404 })
|
||||||
|
}) as typeof fetch
|
||||||
|
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||||
|
})
|
||||||
|
afterAll(() => {
|
||||||
|
globalThis.fetch = realFetch
|
||||||
|
})
|
||||||
|
|
||||||
|
const report = full as Report
|
||||||
|
let drawn: string[] = []
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
drawn = []
|
||||||
|
fetched.length = 0
|
||||||
|
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (this: PDFPage, text: string) {
|
||||||
|
drawn.push(text)
|
||||||
|
} as never)
|
||||||
|
})
|
||||||
|
|
||||||
|
/** Rebuilds wrapped values: lines are drawn one by one, joined by a space. */
|
||||||
|
const joined = () => drawn.join(' ').replace(/\s+/g, ' ')
|
||||||
|
|
||||||
|
describe('export on the full fixture (FR)', () => {
|
||||||
|
it('produces one page per observation plus a conclusion page', async () => {
|
||||||
|
const bytes = await exportReportToPdf(report, { locale: 'fr' })
|
||||||
|
const doc = await PDFDocument.load(bytes)
|
||||||
|
expect(doc.getPageCount()).toBe(report.observations.length + 1)
|
||||||
|
expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
|
||||||
|
expect(doc.getAuthor()).toBe('Dr. Claire Dupont')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('re-fetches the SVGs from public/ and the logos at export time (external dependencies)', async () => {
|
||||||
|
await exportReportToPdf(report, { locale: 'fr' })
|
||||||
|
const svgFetches = fetched.filter((u) => u.endsWith('.svg') && u.includes('/species/'))
|
||||||
|
// buildZoneLabels (2) + one colorized view per rendered image (general ×2, head ×1)
|
||||||
|
expect(svgFetches.filter((u) => u.endsWith('Horse.svg')).length).toBeGreaterThanOrEqual(3)
|
||||||
|
expect(svgFetches.filter((u) => u.endsWith('Horse_head.svg')).length).toBeGreaterThanOrEqual(2)
|
||||||
|
expect(fetched.some((u) => u.includes('/assets/') && u.endsWith('.png'))).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('draws the ZONES section as bullet rows with vertebrae and side suffixes', async () => {
|
||||||
|
await exportReportToPdf(report, { locale: 'fr' })
|
||||||
|
expect(drawn).toContain(fr['pdf.section.zones'])
|
||||||
|
const zonesIdx = drawn.indexOf(fr['pdf.section.zones'])
|
||||||
|
// The ' · ' joined value is split back into one row per zone with a bullet glyph.
|
||||||
|
expect(drawn.slice(zonesIdx + 1, zonesIdx + 6)).toEqual([
|
||||||
|
'Charnière C7-T1 (cervico-thoracique)',
|
||||||
|
'•',
|
||||||
|
'Hanche (coxo-fémorale) (Gauche)',
|
||||||
|
'•',
|
||||||
|
'Hanche (coxo-fémorale) (Droite)',
|
||||||
|
])
|
||||||
|
expect(drawn).toContain('Vertèbres cervicales (C3, C4)')
|
||||||
|
expect(drawn).toContain('Articulation Temporo-Mandibulaire (ATM)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('draws one CONSTATS section per (catalog zone, side) with snapshot labels and the (!) vet marker', async () => {
|
||||||
|
await exportReportToPdf(report, { locale: 'fr' })
|
||||||
|
const prefix = fr['pdf.section.findings_prefix']
|
||||||
|
expect(drawn).toContain(`${prefix}CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)`)
|
||||||
|
expect(drawn).toContain(`${prefix}HANCHE (COXO-FÉMORALE) (GAUCHE)`)
|
||||||
|
expect(drawn).toContain(`${prefix}VERTÈBRES CERVICALES`)
|
||||||
|
expect(drawn).toContain(`${prefix}ARTICULATION TEMPORO-MANDIBULAIRE (ATM)`)
|
||||||
|
expect(drawn).toContain('Fixation de la charnière')
|
||||||
|
expect(drawn).toContain('Restriction en flexion')
|
||||||
|
expect(drawn.some((l) => l.startsWith('(!) Trébuchements'))).toBe(true)
|
||||||
|
expect(drawn).toContain('(!) Headshaking (secouement de tête)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('draws free findings, severity, comment, and the view captions', async () => {
|
||||||
|
await exportReportToPdf(report, { locale: 'fr' })
|
||||||
|
expect(drawn).toContain(fr['pdf.section.free_findings'])
|
||||||
|
expect(drawn).toContain('Sensibilité au garrot')
|
||||||
|
expect(drawn).toContain(fr['pdf.section.severity'])
|
||||||
|
expect(drawn).toContain(fr['severity.modérée'])
|
||||||
|
expect(drawn).toContain(fr['severity.sévère'])
|
||||||
|
expect(drawn).toContain(fr['pdf.section.comment'])
|
||||||
|
expect(drawn).toContain('Réagit à la palpation du garrot.')
|
||||||
|
expect(drawn.filter((l) => l === fr['pdf.view.general'])).toHaveLength(2)
|
||||||
|
expect(drawn).toContain(`${fr['pdf.view.detail_prefix']}HEAD`)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('draws the conclusion page and the header identity on every page', async () => {
|
||||||
|
await exportReportToPdf(report, { locale: 'fr' })
|
||||||
|
expect(drawn).toContain(fr['pdf.section.conclusion'])
|
||||||
|
expect(drawn).toContain(fr['pdf.section.recommendations'])
|
||||||
|
expect(drawn).toContain(fr['pdf.section.next_appointment'])
|
||||||
|
expect(joined()).toContain('Dysfonction cervico-thoracique avec compensation du bassin.')
|
||||||
|
expect(drawn.filter((l) => l === 'Dr. Claire Dupont').length).toBe(4)
|
||||||
|
expect(drawn.filter((l) => l.includes('12345678901234')).length).toBe(4)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses the EN snapshots and dictionary when locale=en, same attachment bytes', async () => {
|
||||||
|
const frBytes = await exportReportToPdf(report, { locale: 'fr' })
|
||||||
|
const frDrawn = [...drawn]
|
||||||
|
drawn = []
|
||||||
|
const enBytes = await exportReportToPdf(report, { locale: 'en' })
|
||||||
|
expect(drawn).toContain(en['pdf.section.zones'])
|
||||||
|
expect(drawn).toContain(`${en['pdf.section.findings_prefix']}HIP JOINT (LEFT)`)
|
||||||
|
expect(drawn).toContain('Junction fixation')
|
||||||
|
expect(drawn).toContain('(!) Headshaking')
|
||||||
|
expect(frDrawn).not.toContain('Junction fixation')
|
||||||
|
const a = await importReportFromPdf(frBytes)
|
||||||
|
const b = await importReportFromPdf(enBytes)
|
||||||
|
expect(a).toEqual(b)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('roundtrip and import', () => {
|
||||||
|
it('re-imports the full fixture unchanged (deep equality)', async () => {
|
||||||
|
const bytes = await exportReportToPdf(report, { locale: 'fr' })
|
||||||
|
const imported = await importReportFromPdf(bytes)
|
||||||
|
expect(imported).toEqual(report)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, description "Faunosteo state v2"', async () => {
|
||||||
|
const bytes = await exportReportToPdf(report, { locale: 'fr' })
|
||||||
|
const doc = await PDFDocument.load(bytes)
|
||||||
|
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) => String(o))
|
||||||
|
const filespec = objects.find((s) => s.includes('/Type /Filespec'))!
|
||||||
|
expect(filespec).toContain('/F (osteo-report.json)')
|
||||||
|
expect(filespec).toContain('/AFRelationship /Data')
|
||||||
|
// /Desc is a UTF-16BE hex string: "Faunosteo state v2"
|
||||||
|
expect(filespec).toContain('/Desc <FEFF004600610075006E006F007300740065006F002000730074006100740065002000760032>')
|
||||||
|
const embedded = objects.find((s) => s.includes('/Type /EmbeddedFile'))!
|
||||||
|
expect(embedded).toContain('/Subtype /application#2Fjson')
|
||||||
|
expect(embedded).toContain('/Filter /FlateDecode')
|
||||||
|
expect(objects.some((s) => s.includes('/EmbeddedFiles'))).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pdf-lib 1.17.1 has no getAttachments: the object-traversal fallback IS the import path', async () => {
|
||||||
|
expect(typeof (PDFDocument.prototype as unknown as { getAttachments?: unknown }).getAttachments).toBe('undefined')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reports incompatible_version with the found version for a v3 attachment', async () => {
|
||||||
|
const doc = await PDFDocument.create()
|
||||||
|
doc.addPage()
|
||||||
|
await doc.attach(new TextEncoder().encode(JSON.stringify({ ...report, version: 3 })), 'osteo-report.json', {
|
||||||
|
mimeType: 'application/json',
|
||||||
|
afRelationship: AFRelationship.Data,
|
||||||
|
})
|
||||||
|
const err = await importReportFromPdf(await doc.save()).catch((e) => e)
|
||||||
|
expect(err).toBeInstanceOf(ImportError)
|
||||||
|
expect((err as ImportError).kind).toBe('incompatible_version')
|
||||||
|
expect((err as ImportError).foundVersion).toBe(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('KNOWN: a foreign JSON attachment is picked up by the traversal and fails as no_attachment', async () => {
|
||||||
|
const doc = await PDFDocument.create()
|
||||||
|
doc.addPage()
|
||||||
|
await doc.attach(new TextEncoder().encode('{"hello":1}'), 'other.json', {
|
||||||
|
mimeType: 'application/json',
|
||||||
|
afRelationship: AFRelationship.Data,
|
||||||
|
})
|
||||||
|
const err = await importReportFromPdf(await doc.save()).catch((e) => e)
|
||||||
|
expect(err).toBeInstanceOf(ImportError)
|
||||||
|
expect((err as ImportError).kind).toBe('no_attachment')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('KNOWN: a Zod-invalid report attachment is also reported as no_attachment (cause lost)', async () => {
|
||||||
|
const doc = await PDFDocument.create()
|
||||||
|
doc.addPage()
|
||||||
|
const broken = { ...report, practitioner: { name: '' } }
|
||||||
|
await doc.attach(new TextEncoder().encode(JSON.stringify(broken)), 'osteo-report.json', {
|
||||||
|
mimeType: 'application/json',
|
||||||
|
afRelationship: AFRelationship.Data,
|
||||||
|
})
|
||||||
|
const err = await importReportFromPdf(await doc.save()).catch((e) => e)
|
||||||
|
expect((err as ImportError).kind).toBe('no_attachment')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('an orphan finding (zone removed) is still printed under its catalog zone', async () => {
|
||||||
|
const orphaned: Report = {
|
||||||
|
...report,
|
||||||
|
observations: [{ ...report.observations[0], zones: [] }],
|
||||||
|
}
|
||||||
|
await exportReportToPdf(orphaned, { locale: 'fr' })
|
||||||
|
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)`)
|
||||||
|
expect(drawn).toContain(fr['pdf.empty'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('an unknown boneId is printed raw and an unknown zoneId is printed raw', async () => {
|
||||||
|
const stale: Report = {
|
||||||
|
...report,
|
||||||
|
observations: [
|
||||||
|
{
|
||||||
|
...report.observations[0],
|
||||||
|
zones: [{ boneId: 'point-gone' }],
|
||||||
|
findings: [
|
||||||
|
{
|
||||||
|
zoneId: 'zone-gone',
|
||||||
|
path: ['x'],
|
||||||
|
labelFrSnapshot: 'Snapshot FR',
|
||||||
|
labelEnSnapshot: 'Snapshot EN',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
await exportReportToPdf(stale, { locale: 'fr' })
|
||||||
|
expect(drawn).toContain('point-gone')
|
||||||
|
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}ZONE-GONE`)
|
||||||
|
expect(drawn).toContain('Snapshot FR')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
/**
|
||||||
|
* Characterisation (Step 1): what the Report v2 schema accepts or rejects,
|
||||||
|
* what the browser persistence keeps, and the storage keys the SaaS
|
||||||
|
* migration must read (plan Step 14 one-time draft import).
|
||||||
|
*/
|
||||||
|
import { describe, it, expect, beforeEach } from 'vitest'
|
||||||
|
import { ReportSchema } from '@/domain/schema/report'
|
||||||
|
import { ObservationSchema, VertebraSchema, SeveritySchema } from '@/domain/schema/observation'
|
||||||
|
import { readPersistedDraft, useReportStore } from '@/state/reportStore'
|
||||||
|
import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache'
|
||||||
|
import { useLocaleStore } from '@/state/localeStore'
|
||||||
|
import full from '../fixtures/report-v2.full.json'
|
||||||
|
import minimal from '../fixtures/report-v2.minimal.json'
|
||||||
|
import type { Report } from '@/domain/schema/report'
|
||||||
|
|
||||||
|
describe('Report v2 schema on the golden fixtures', () => {
|
||||||
|
it('accepts both fixtures unchanged', () => {
|
||||||
|
expect(ReportSchema.parse(full)).toEqual(full)
|
||||||
|
expect(ReportSchema.parse(minimal)).toEqual(minimal)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('strips unknown keys silently (forward-compat fields are lost on reimport)', () => {
|
||||||
|
const parsed = ReportSchema.parse({ ...minimal, futureField: 1, animal: { ...minimal.animal, chip: 'x' } })
|
||||||
|
expect(parsed).toEqual(minimal)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects version 1 and 3, accepts only the literal 2', () => {
|
||||||
|
expect(ReportSchema.safeParse({ ...minimal, version: 1 }).success).toBe(false)
|
||||||
|
expect(ReportSchema.safeParse({ ...minimal, version: 3 }).success).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not bound vertebra indexes by the species formula (C99 accepted)', () => {
|
||||||
|
expect(VertebraSchema.safeParse({ region: 'C', index: 99 }).success).toBe(true)
|
||||||
|
expect(VertebraSchema.safeParse({ region: 'X', index: 1 }).success).toBe(false)
|
||||||
|
expect(VertebraSchema.safeParse({ region: 'C', index: 0 }).success).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('stores severities as French enum values', () => {
|
||||||
|
expect(SeveritySchema.options).toEqual(['légère', 'modérée', 'sévère'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepts findings whose zoneId matches no zone of the observation (orphans)', () => {
|
||||||
|
const obs = { ...full.observations[0], zones: [] }
|
||||||
|
expect(ObservationSchema.safeParse(obs).success).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepts a speciesId that no manifest registers (checked only at render time)', () => {
|
||||||
|
expect(ReportSchema.safeParse({ ...minimal, animal: { speciesId: 'dragon', name: 'X' } }).success).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepts two zones with the same boneId and different sides, and the same boneId from main and detail', () => {
|
||||||
|
const obs = {
|
||||||
|
...minimal,
|
||||||
|
observations: [
|
||||||
|
{
|
||||||
|
id: 'o',
|
||||||
|
zones: [
|
||||||
|
{ boneId: 'a', side: 'left' },
|
||||||
|
{ boneId: 'a', side: 'right' },
|
||||||
|
{ boneId: 'a', detailSourceId: 'head' },
|
||||||
|
],
|
||||||
|
findings: [],
|
||||||
|
freeTextFindings: [],
|
||||||
|
comment: '',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
expect(ReportSchema.safeParse(obs).success).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('browser persistence', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
sessionStorage.clear()
|
||||||
|
localStorage.clear()
|
||||||
|
useReportStore.setState({ report: null, activeObservationIndex: 0 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('mirrors the full fixture to sessionStorage["osteo:draft"] and restores it unchanged', () => {
|
||||||
|
useReportStore.getState().hydrateReport(full as Report)
|
||||||
|
const raw = sessionStorage.getItem('osteo:draft')
|
||||||
|
expect(raw).not.toBeNull()
|
||||||
|
expect(JSON.parse(raw!)).toEqual(full)
|
||||||
|
expect(readPersistedDraft()).toEqual(full)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hydrateReport does not revalidate (an invalid report can enter the store, the draft is then unreadable)', () => {
|
||||||
|
const broken = { ...(minimal as Report), version: 7 } as unknown as Report
|
||||||
|
useReportStore.getState().hydrateReport(broken)
|
||||||
|
expect(useReportStore.getState().report?.version).toBe(7)
|
||||||
|
expect(readPersistedDraft()).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('initReport creates one empty observation, a uuid id and version 2', () => {
|
||||||
|
const { observations, ...draft } = minimal as Report
|
||||||
|
void observations
|
||||||
|
useReportStore.getState().initReport({ ...draft, observations: [] } as never)
|
||||||
|
const r = useReportStore.getState().report!
|
||||||
|
expect(r.version).toBe(2)
|
||||||
|
expect(r.id).toMatch(/^[0-9a-f-]{36}$/)
|
||||||
|
expect(r.observations).toHaveLength(1)
|
||||||
|
expect(r.observations[0]).toMatchObject({ zones: [], findings: [], freeTextFindings: [], comment: '' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('caches the practitioner block under localStorage["osteo:lastPractitioner"]', () => {
|
||||||
|
writeCachedPractitioner(full.practitioner)
|
||||||
|
expect(JSON.parse(localStorage.getItem('osteo:lastPractitioner')!)).toEqual(full.practitioner)
|
||||||
|
expect(readCachedPractitioner()).toEqual(full.practitioner)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('persists the locale under localStorage["osteo:locale"] (shared with pathology-editor.html)', () => {
|
||||||
|
useLocaleStore.getState().setLocale('en')
|
||||||
|
expect(localStorage.getItem('osteo:locale')).toBe('en')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
/**
|
||||||
|
* Characterisation (Step 1): the real SVG assets, their attributes, the
|
||||||
|
* SVG ↔ catalog link computed by zoneMatch, the opens-detail ↔ manifest
|
||||||
|
* contract and the spine helpers on the real Horse.svg.
|
||||||
|
* Oracle: docs/faunosteo-audit/06-svg-findings-link.md §4 (full table).
|
||||||
|
*/
|
||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { dirname, resolve } from 'node:path'
|
||||||
|
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||||||
|
import { matchZoneFindings, scorePair, levenshtein, normalizeLabel } from '@/lib/zoneMatch'
|
||||||
|
import {
|
||||||
|
regionFromLabel,
|
||||||
|
findSpineZoneId,
|
||||||
|
collectSpineVertebrae,
|
||||||
|
syncSpineZones,
|
||||||
|
} from '@/lib/spineZones'
|
||||||
|
import { getSpecies } from '@/domain/species/registry'
|
||||||
|
import FINDINGS from '@/domain/species/equine/pathologies'
|
||||||
|
import type { Bone } from '@/anatomy/types'
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const HORSE_TEXT = readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8')
|
||||||
|
const HEAD_TEXT = readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8')
|
||||||
|
|
||||||
|
function parse(text: string): Map<string, Bone> {
|
||||||
|
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
|
||||||
|
return parseSvgBones(doc.documentElement as unknown as SVGSVGElement)
|
||||||
|
}
|
||||||
|
|
||||||
|
const horse = parse(HORSE_TEXT)
|
||||||
|
const head = parse(HEAD_TEXT)
|
||||||
|
const zones = Object.values(FINDINGS.zones)
|
||||||
|
|
||||||
|
/** Expected mapping, audit 06 §4. Trigger zone-mpby55kd is intentionally absent. */
|
||||||
|
const EXPECTED: Record<string, string> = {
|
||||||
|
'point-mpbwrkp0': 'hind-fetlock',
|
||||||
|
'point-mpbwsi9q': 'hock',
|
||||||
|
'point-mpbwt4fa': 'stifle',
|
||||||
|
'point-mpbwtst0': 'hip',
|
||||||
|
'point-mpbwugty': 'sacroiliac',
|
||||||
|
'point-mpbwv4xy': 'shoulder',
|
||||||
|
'point-mpbwvpvt': 'elbow',
|
||||||
|
'point-mpbwwaru': 'fore-fetlock',
|
||||||
|
'point-mpbwwxvn': 'fore-sesamoids',
|
||||||
|
'point-mpbwxnb4': 'l6-s1',
|
||||||
|
'point-mpbwyd9i': 't18-l1',
|
||||||
|
'point-mpbwyyc9': 'c7-t1',
|
||||||
|
'zone-mpbx00jq': 'caudal',
|
||||||
|
'zone-mpbx0xnp': 'sacral',
|
||||||
|
'zone-mpbx1rm9': 'lumbar',
|
||||||
|
'zone-mpbx2rpe': 'thoracic',
|
||||||
|
'zone-mpbx5hx2': 'cervical',
|
||||||
|
'point-mpbykomv': 'parietal',
|
||||||
|
'point-mpbylh35': 'frontal',
|
||||||
|
'point-mpbymcln': 'sphenoid',
|
||||||
|
'point-mpbyn2k3': 'temporal',
|
||||||
|
'point-mpbynls5': 'occipital',
|
||||||
|
'point-mpbyo7zq': 'atm',
|
||||||
|
'point-mpbyphay': 'ssb',
|
||||||
|
'point-mpbyq841': 'hyoid',
|
||||||
|
'point-mpbyqxbg': 'c0-c1',
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('SVG attribute census (raw text, audit 03 §10.H)', () => {
|
||||||
|
const count = (attr: string) =>
|
||||||
|
(HORSE_TEXT.match(new RegExp(`${attr}="`, 'g')) ?? []).length +
|
||||||
|
(HEAD_TEXT.match(new RegExp(`${attr}="`, 'g')) ?? []).length
|
||||||
|
|
||||||
|
it('counts data-anno-* attributes across both files', () => {
|
||||||
|
expect(count('data-anno-id')).toBe(48)
|
||||||
|
expect(count('data-anno-category')).toBe(48)
|
||||||
|
expect(count('data-anno-category-name')).toBe(18)
|
||||||
|
expect(count('data-anno-name-fr')).toBe(47)
|
||||||
|
expect(count('data-anno-name-en')).toBe(47)
|
||||||
|
expect(count('data-anno-lateral')).toBe(18)
|
||||||
|
expect(count('data-anno-special')).toBe(5)
|
||||||
|
expect(count('data-anno-opens-detail')).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses only five category slugs, two of them with degraded accents', () => {
|
||||||
|
const cats = new Set([...horse.values(), ...head.values()].map((b) => b.category))
|
||||||
|
expect([...cats].sort()).toEqual([
|
||||||
|
'articulations', 'cadrans-du-cr-ne', 'charni-res-vert-brales', 'os', 'zone-colonne',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lateral is always "bilateral", special always "vertebral-precision"', () => {
|
||||||
|
const all = [...horse.values(), ...head.values()]
|
||||||
|
expect(all.filter((b) => b.lateral).every((b) => b.lateral === 'bilateral')).toBe(true)
|
||||||
|
expect(all.filter((b) => b.lateral)).toHaveLength(9)
|
||||||
|
expect(all.filter((b) => b.special).every((b) => b.special === 'vertebral-precision')).toBe(true)
|
||||||
|
expect(all.filter((b) => b.special)).toHaveLength(5)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('main and detail id spaces do not overlap (27 distinct ids)', () => {
|
||||||
|
const ids = new Set([...horse.keys(), ...head.keys()])
|
||||||
|
expect(ids.size).toBe(horse.size + head.size)
|
||||||
|
expect(ids.size).toBe(27)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Horse_head.svg is the same drawing as Horse.svg with a different viewBox', () => {
|
||||||
|
expect(HORSE_TEXT).toMatch(/viewBox="0 0 2073\.4 1629\.4"/)
|
||||||
|
expect(HEAD_TEXT).toMatch(/viewBox="60 100 500 380"/)
|
||||||
|
const body = (t: string) => t.split('\n').slice(2, 703).join('\n')
|
||||||
|
expect(body(HEAD_TEXT)).toBe(body(HORSE_TEXT))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('SVG ↔ catalog link (audit 06 §4)', () => {
|
||||||
|
it('maps the 26 named annotations to their catalog zone, exact EN and FR match', () => {
|
||||||
|
const all = new Map([...horse, ...head])
|
||||||
|
for (const [id, zoneId] of Object.entries(EXPECTED)) {
|
||||||
|
const bone = all.get(id)
|
||||||
|
expect(bone, id).toBeDefined()
|
||||||
|
const tree = matchZoneFindings({ fr: bone!.fr, en: bone!.en }, zones)
|
||||||
|
expect(tree?.id, id).toBe(zoneId)
|
||||||
|
expect(scorePair(bone!.en, tree!.name_en), `${id} EN`).toBe(0)
|
||||||
|
expect(scorePair(bone!.fr, tree!.name_fr), `${id} FR`).toBe(0)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves the detail trigger unmatched (no FR/EN name)', () => {
|
||||||
|
const trigger = horse.get('zone-mpby55kd')!
|
||||||
|
expect(trigger.fr).toBe('')
|
||||||
|
expect(trigger.en).toBe('')
|
||||||
|
expect(trigger.opensDetail).toBe('head')
|
||||||
|
expect(trigger.category).toBe('articulations')
|
||||||
|
expect(matchZoneFindings({ fr: trigger.fr, en: trigger.en }, zones)).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves no catalog zone orphaned', () => {
|
||||||
|
const matched = new Set(Object.values(EXPECTED))
|
||||||
|
expect(matched.size).toBe(26)
|
||||||
|
expect(zones.map((z) => z.id).filter((id) => !matched.has(id))).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no normalized EN or FR zone name is a substring of another (substring rule unreachable today)', () => {
|
||||||
|
for (const lang of ['name_en', 'name_fr'] as const) {
|
||||||
|
const norms = zones.map((z) => normalizeLabel(z[lang]))
|
||||||
|
for (let i = 0; i < norms.length; i += 1)
|
||||||
|
for (let j = 0; j < norms.length; j += 1)
|
||||||
|
if (i !== j) expect(norms[i].includes(norms[j]), `${lang} ${zones[i].id} ⊃ ${zones[j].id}`).toBe(false)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('KNOWN: two FR pairs are within the fuzzy tolerance and would collide if EN ever diverged', () => {
|
||||||
|
const d = (a: string, b: string) => levenshtein(normalizeLabel(a), normalizeLabel(b))
|
||||||
|
const fetlock = d('Boulet ant. (métacarpo-phalangien)', 'Boulet post. (métatarso-phalangien)')
|
||||||
|
const spine = d('Vertèbres sacrales', 'Vertèbres caudales')
|
||||||
|
expect(fetlock).toBe(5)
|
||||||
|
expect(spine).toBe(3)
|
||||||
|
expect(scorePair('Boulet ant. (métacarpo-phalangien)', 'Boulet post. (métatarso-phalangien)')).toBe(2 + 5)
|
||||||
|
expect(scorePair('Vertèbres sacrales', 'Vertèbres caudales')).toBe(2 + 3)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('opens-detail ↔ species manifest', () => {
|
||||||
|
const species = getSpecies('equine')!
|
||||||
|
|
||||||
|
it('every opens-detail value is a key of species.details, and every key has one trigger', () => {
|
||||||
|
const triggers = [...horse.values()].filter((b) => b.opensDetail).map((b) => b.opensDetail!)
|
||||||
|
expect(triggers).toEqual(['head'])
|
||||||
|
for (const key of triggers) expect(species.details[key]).toBeDefined()
|
||||||
|
expect(Object.keys(species.details)).toEqual(['head'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('the detail SVG carries no trigger of its own (one level of detail)', () => {
|
||||||
|
expect([...head.values()].some((b) => b.opensDetail)).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('manifest paths point at the two committed files', () => {
|
||||||
|
expect(species.mainSvg).toBe('/species/equine/Horse.svg')
|
||||||
|
expect(species.details.head).toBe('/species/equine/Horse_head.svg')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('spine helpers on the real Horse.svg', () => {
|
||||||
|
it('resolves each region to its zone-colonne polygon by label', () => {
|
||||||
|
expect(findSpineZoneId('C', horse)).toBe('zone-mpbx5hx2')
|
||||||
|
expect(findSpineZoneId('T', horse)).toBe('zone-mpbx2rpe')
|
||||||
|
expect(findSpineZoneId('L', horse)).toBe('zone-mpbx1rm9')
|
||||||
|
expect(findSpineZoneId('S', horse)).toBe('zone-mpbx0xnp')
|
||||||
|
expect(findSpineZoneId('Cd', horse)).toBe('zone-mpbx00jq')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('KNOWN: hinge labels also resolve to a region, but hinges have no special so it is never used', () => {
|
||||||
|
expect(regionFromLabel(horse.get('point-mpbwyyc9')!.fr)).toBe('C')
|
||||||
|
expect(horse.get('point-mpbwyyc9')!.special).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('spawns a lumbar zone from scratch and keeps a joint zone untouched', () => {
|
||||||
|
const next = syncSpineZones([{ boneId: 'point-mpbwtst0', side: 'left' }], [{ region: 'L', index: 2 }], horse)
|
||||||
|
expect(next).toEqual([
|
||||||
|
{ boneId: 'point-mpbwtst0', side: 'left' },
|
||||||
|
{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('collects vertebrae across spine zones with the clicked zone first', () => {
|
||||||
|
const zonesSel = [
|
||||||
|
{ boneId: 'zone-mpbx5hx2', vertebrae: [{ region: 'C' as const, index: 3 }] },
|
||||||
|
{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L' as const, index: 1 }] },
|
||||||
|
]
|
||||||
|
expect(collectSpineVertebrae(zonesSel, horse, 'zone-mpbx1rm9')).toEqual([
|
||||||
|
{ region: 'L', index: 1 },
|
||||||
|
{ region: 'C', index: 3 },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('detail-sourced zones never count as spine zones', () => {
|
||||||
|
const next = syncSpineZones(
|
||||||
|
[{ boneId: 'zone-mpbx5hx2', detailSourceId: 'head' }],
|
||||||
|
[{ region: 'C', index: 1 }],
|
||||||
|
horse,
|
||||||
|
)
|
||||||
|
// passes through untouched, then a fresh cervical zone is spawned
|
||||||
|
expect(next[0]).toEqual({ boneId: 'zone-mpbx5hx2', detailSourceId: 'head' })
|
||||||
|
expect(next[1]).toEqual({ boneId: 'zone-mpbx5hx2', vertebrae: [{ region: 'C', index: 1 }] })
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in new issue
Block a user