# 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` Status 2026-10-10: moves A and B done in Step 5 (`state/persistence.ts`, Report v3 in `packages/domain/report`); move C pending (Cloud reports). 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 Status 2026-10-10: points 1, 2, 4, 5 and 6 done (Steps 4, 4b, 5). Point 3 differs: ids are stable slugs, not UUIDs (BDR-031/034). The renderer emits elements from the document's geometry, not attributes on legacy elements (docs/ANNOTATION-RENDERING.md). 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 ``/`` 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 Status 2026-10-10: Step 5 took the sheet as export input and attached v3 with v2 import; points 2 (sheet snapshot in the attachment), 3 (server import) and 5 (branding object) stay for Step 6. 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: , 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 `.` 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/legacy-import/ (generated baseline, no SQL) 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) │ curation changeset (supabase/seed/anatomical-sheets/equine/curation/, authored, Step 4c) ▼ supabase/seed/anatomical-sheets/equine/draft/ (generated working revision) document.json, assets/horse.svg (one cleaned drawing), CHANGELOG.md, REVIEW-REPORT.md, review/*.svg │ equine_draft.sql (idempotent, converging; never publishes) ▼ anatomical_sheets "Faunosteo / Cheval / Fiche anatomique officielle" (platform-owned, private) anatomical_sheet_versions DRAFT until a platform admin publishes after the professional review storage: anatomical-sheet-assets/.svg (content-addressed, operator upload) ``` 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.