diff --git a/apps/app/tests/helpers/legacyLeaves.ts b/apps/app/tests/helpers/legacyLeaves.ts new file mode 100644 index 00000000..0d3ca87e --- /dev/null +++ b/apps/app/tests/helpers/legacyLeaves.ts @@ -0,0 +1,94 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { resolve } from 'node:path' +import { + AnatomicalSheetDocumentSchema, + ReportV2Schema, + type AnatomicalSheetDocument, + type FindingCategory, + type FindingNode, + type ObservationV2, + type ReportV2, +} from '@faunosteo/domain' + +/** + * The legacy catalog as the application's archive knew it: every leaf of the + * generated baseline (`legacy-import/document.json`) becomes a Report v2 + * finding, grouped in one observation per zone. Mirrors the anatomy package + * helper of the same name; both read the committed seed, never a copy. + */ + +const BASELINE = resolve( + fileURLToPath(import.meta.url), + '../../../../../supabase/seed/anatomical-sheets/equine/legacy-import/document.json', +) + +export interface LegacyLeaf { + zoneId: string + path: string[] + name: { fr: string; en: string } + vet: boolean +} + +export function loadLegacyBaseline(): AnatomicalSheetDocument { + return AnatomicalSheetDocumentSchema.parse( + JSON.parse(readFileSync(BASELINE, 'utf8')), + ) +} + +export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] { + const out: LegacyLeaf[] = [] + const walk = ( + zoneId: string, + nodes: readonly (FindingCategory | FindingNode)[], + prefix: string[], + ) => { + for (const node of nodes) { + const path = [...prefix, node.id] + if (node.children.length > 0) walk(zoneId, node.children, path) + else { + const vet = + 'requires_vet_referral' in node && node.requires_vet_referral + out.push({ zoneId, path, name: node.name, vet }) + } + } + } + for (const zone of doc.finding_zones) walk(zone.id, zone.categories, []) + return out +} + +export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 { + const byZone = new Map() + for (const leaf of leaves) { + let obs = byZone.get(leaf.zoneId) + if (!obs) { + obs = { + id: `obs-${leaf.zoneId}`, + zones: [], + findings: [], + freeTextFindings: [], + comment: '', + } + byZone.set(leaf.zoneId, obs) + } + obs.findings.push({ + zoneId: leaf.zoneId, + path: leaf.path, + labelFrSnapshot: leaf.name.fr, + labelEnSnapshot: leaf.name.en || leaf.name.fr, + ...(leaf.vet ? { requiresVetReferral: true } : {}), + }) + } + return ReportV2Schema.parse({ + version: 2, + id: 'all-leaves', + createdAt: '2026-10-10T00:00:00Z', + date: '2026-10-10', + practitioner: { name: 'Synthetic' }, + animal: { speciesId: 'equine', name: 'Synthetic' }, + owner: { name: 'Synthetic' }, + observations: [...byZone.values()], + conclusion: '', + recommendations: '', + }) +} diff --git a/apps/app/tests/unit/migration.leaves.test.ts b/apps/app/tests/unit/migration.leaves.test.ts new file mode 100644 index 00000000..c37446a7 --- /dev/null +++ b/apps/app/tests/unit/migration.leaves.test.ts @@ -0,0 +1,71 @@ +/** + * The 612 legacy leaves through the application itself: migrated with the + * bundled sheet's map, resolved by the sheet index the editor and the PDF + * use, exported to a v3 PDF and read back without loss. + */ +import { describe, it, expect, vi, beforeAll } from 'vitest' +import { + readReportDocument, + type Finding, + type Report, +} from '@faunosteo/domain' +import { exportReportToPdf } from '@/pdf/export' +import { importReportFromPdf } from '@/pdf/import' +import type { SheetIndex } from '@/services/sheetIndex' +import { loadTestSheet } from '../helpers/sheet' +import { + leavesAsV2Report, + legacyLeaves, + loadLegacyBaseline, +} from '../helpers/legacyLeaves' + +const ONE_PX_PNG = Uint8Array.from( + Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', + ), +) +vi.mock('@/pdf/render/svgToPng', () => ({ + rasterizeSvg: vi.fn(async () => ONE_PX_PNG), +})) + +let sheet: SheetIndex +let report: Report +let findings: Finding[] +let unresolvedFindings: number + +beforeAll(async () => { + sheet = await loadTestSheet() + const leaves = legacyLeaves(loadLegacyBaseline()) + const v2 = leavesAsV2Report(leaves) + const outcome = readReportDocument(v2, sheet.sheet.migrationMap) + report = outcome.report + findings = report.observations.flatMap((o) => o.findings) + unresolvedFindings = outcome.unresolvedFindings + vi.spyOn(console, 'warn').mockImplementation(() => undefined) +}) + +describe('the 612 legacy leaves in the application', () => { + it('resolves every migrated leaf to a leaf node of the bundled sheet', () => { + expect(findings).toHaveLength(612) + expect(unresolvedFindings).toBe(29) + for (const f of findings) { + const node = sheet.nodeAt(f.findingZoneId, f.path) + const where = `${f.findingZoneId}/${f.path.join('/')}` + if (f.unresolved) expect(node, where).toBeUndefined() + else { + expect(node, where).toBeDefined() + expect(node!.children, where).toHaveLength(0) + } + } + }) + + it('keeps every finding, resolved or not, through a v3 PDF export and import', async () => { + const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' }) + const back = await importReportFromPdf(bytes, sheet.sheet.migrationMap) + expect(back.migrated).toBe(false) + expect(back.report).toEqual(report) + const again = back.report.observations.flatMap((o) => o.findings) + expect(again.filter((f) => f.unresolved)).toHaveLength(29) + }, 30_000) +}) diff --git a/packages/anatomy/tests/curation.migration-leaves.test.ts b/packages/anatomy/tests/curation.migration-leaves.test.ts new file mode 100644 index 00000000..d628e32a --- /dev/null +++ b/packages/anatomy/tests/curation.migration-leaves.test.ts @@ -0,0 +1,271 @@ +/** + * Per-leaf adapter test over the committed seed: every leaf of the legacy + * catalog (612) and every legacy annotation (27) travels through the real + * Report v2 → v3 migration with the generated map, then is checked against + * the curated draft document itself, not against the map alone. + */ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { + AnatomicalSheetDocumentSchema, + ReportMigrationMapSchema, + ReportV2Schema, + findingPathKey, + migrateReportV2ToV3, + readReportDocument, + type AnatomicalSheetDocument, + type Annotation, + type Finding, + type FindingCategory, + type FindingNode, + type ObservationV2, + type ReportMigrationMap, + type ReportV2, +} from '@faunosteo/domain' +import { beforeAll, describe, expect, it } from 'vitest' +import { EQUINE_DRAFT_DIR, EQUINE_LEGACY_IMPORT_DIR } from '../src' +import { REPO_ROOT } from './helpers' + +interface LegacyLeaf { + zoneId: string + path: string[] + name: { fr: string; en: string } + vet: boolean +} + +/** Every leaf of a document's finding trees, in document order. */ +export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] { + const out: LegacyLeaf[] = [] + const walk = ( + zoneId: string, + nodes: readonly (FindingCategory | FindingNode)[], + prefix: string[], + ) => { + for (const node of nodes) { + const path = [...prefix, node.id] + if (node.children.length > 0) walk(zoneId, node.children, path) + else { + const vet = + 'requires_vet_referral' in node && node.requires_vet_referral + out.push({ zoneId, path, name: node.name, vet }) + } + } + } + for (const zone of doc.finding_zones) walk(zone.id, zone.categories, []) + return out +} + +/** One v2 observation per zone holding every leaf of that zone as a finding. */ +export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 { + const byZone = new Map() + for (const leaf of leaves) { + let obs = byZone.get(leaf.zoneId) + if (!obs) { + obs = { + id: `obs-${leaf.zoneId}`, + zones: [], + findings: [], + freeTextFindings: [], + comment: '', + } + byZone.set(leaf.zoneId, obs) + } + obs.findings.push({ + zoneId: leaf.zoneId, + path: leaf.path, + labelFrSnapshot: leaf.name.fr, + labelEnSnapshot: leaf.name.en || leaf.name.fr, + ...(leaf.vet ? { requiresVetReferral: true } : {}), + }) + } + return ReportV2Schema.parse({ + version: 2, + id: 'all-leaves', + createdAt: '2026-10-10T00:00:00Z', + date: '2026-10-10', + practitioner: { name: 'Synthetic' }, + animal: { speciesId: 'equine', name: 'Synthetic' }, + owner: { name: 'Synthetic' }, + observations: [...byZone.values()], + conclusion: '', + recommendations: '', + }) +} + +function nodeAt( + doc: AnatomicalSheetDocument, + zoneId: string, + path: readonly string[], +): FindingCategory | FindingNode | undefined { + const zone = doc.finding_zones.find((z) => z.id === zoneId) + let node: FindingCategory | FindingNode | undefined = zone?.categories.find( + (c) => c.id === path[0], + ) + for (const segment of path.slice(1)) { + node = node?.children.find((n) => n.id === segment) + } + return node +} + +async function readJson(relative: string): Promise { + return JSON.parse(await readFile(join(REPO_ROOT, relative), 'utf8')) +} + +let baseline: AnatomicalSheetDocument +let draft: AnatomicalSheetDocument +let map: ReportMigrationMap +let leaves: LegacyLeaf[] +let findings: Finding[] + +beforeAll(async () => { + baseline = AnatomicalSheetDocumentSchema.parse( + await readJson(`${EQUINE_LEGACY_IMPORT_DIR}/document.json`), + ) + draft = AnatomicalSheetDocumentSchema.parse( + await readJson(`${EQUINE_DRAFT_DIR}/document.json`), + ) + map = ReportMigrationMapSchema.parse( + await readJson(`${EQUINE_DRAFT_DIR}/report-migration-map.json`), + ) + leaves = legacyLeaves(baseline) + const { report } = migrateReportV2ToV3(leavesAsV2Report(leaves), map) + findings = report.observations.flatMap((o) => o.findings) +}) + +describe('every legacy leaf through the v2 → v3 migration', () => { + it('migrates the 612 leaves: 442 identical, 141 moved, 29 removed', () => { + expect(leaves).toHaveLength(612) + expect(findings).toHaveLength(612) + const fates = { identical: 0, moved: 0, removed: 0 } + leaves.forEach((leaf, i) => { + const out = findings[i]! + const same = + out.findingZoneId === leaf.zoneId && + out.path.join('/') === leaf.path.join('/') + if (out.unresolved) fates.removed += 1 + else if (same) fates.identical += 1 + else fates.moved += 1 + }) + expect(fates).toEqual({ identical: 442, moved: 141, removed: 29 }) + }) + + it('lands every resolved leaf on a leaf of the draft document', () => { + for (const out of findings) { + if (out.unresolved) continue + const node = nodeAt(draft, out.findingZoneId, out.path) + const where = `${out.findingZoneId}/${out.path.join('/')}` + expect(node, where).toBeDefined() + expect(node!.children, where).toHaveLength(0) + } + }) + + it('keeps the legacy snapshots and the vet flag verbatim on every finding', () => { + leaves.forEach((leaf, i) => { + const out = findings[i]! + expect(out.labelFrSnapshot).toBe(leaf.name.fr) + expect(out.labelEnSnapshot).toBe(leaf.name.en || leaf.name.fr) + expect(out.requiresVetReferral ?? false).toBe(leaf.vet) + }) + }) + + it('flags exactly the leaves the curation removed, with their legacy path kept', () => { + const removed = leaves.filter( + (leaf) => + map.finding_paths[findingPathKey(leaf.zoneId, leaf.path)] === null, + ) + expect(removed).toHaveLength(29) + const flagged = findings.filter((f) => f.unresolved) + expect( + flagged.map((f) => `${f.findingZoneId}/${f.path.join('/')}`), + ).toEqual(removed.map((leaf) => findingPathKey(leaf.zoneId, leaf.path))) + for (const f of flagged) { + expect(nodeAt(draft, f.findingZoneId, f.path)).toBeUndefined() + } + }) + + it('moves the 141 relocated leaves inside their zone: 134 under a renamed category, 7 renamed leaves', () => { + const fates = { category: 0, leaf: 0 } + leaves.forEach((leaf, i) => { + const out = findings[i]! + if (out.unresolved || out.path.join('/') === leaf.path.join('/')) return + expect(out.findingZoneId, leaf.path.join('/')).toBe(leaf.zoneId) + if (out.path.at(-1) === leaf.path.at(-1)) fates.category += 1 + else fates.leaf += 1 + }) + expect(fates).toEqual({ category: 134, leaf: 7 }) + }) + + it('reads the migrated report back unchanged (v3 is stable)', () => { + const { report } = migrateReportV2ToV3(leavesAsV2Report(leaves), map) + const again = readReportDocument(report, map) + expect(again.report).toEqual(report) + expect(again.unresolvedZones).toBe(0) + expect(again.unresolvedFindings).toBe(0) + }) +}) + +describe('every legacy annotation as a report zone', () => { + it('maps the 26 observable legacy ids to annotations of the right view, names snapshotted', () => { + const triggers = new Set( + draft.annotations + .filter((a) => a.kind === 'detail_trigger') + .map((a) => a.id), + ) + const legacyIds = Object.keys(map.annotations).filter( + (id) => !triggers.has(map.annotations[id]!.id), + ) + expect(legacyIds).toHaveLength(26) + const headIds = new Set( + draft.annotations.filter((a) => a.view_id === 'head').map((a) => a.id), + ) + const v2 = leavesAsV2Report([]) + v2.observations = [ + { + id: 'zones', + zones: legacyIds.map((boneId) => + headIds.has(map.annotations[boneId]!.id) + ? { boneId, detailSourceId: 'head' } + : { boneId }, + ), + findings: [], + freeTextFindings: [], + comment: '', + }, + ] + const out = migrateReportV2ToV3(v2, map) + expect(out.unresolvedZones).toBe(0) + out.report.observations[0]!.zones.forEach((zone, i) => { + const anno = draft.annotations.find((a) => a.id === zone.annotationId) + expect(anno, zone.annotationId).toBeDefined() + expect(anno!.view_id).toBe(zone.viewId) + expect(zone.labelFrSnapshot).toBe(map.annotations[legacyIds[i]!]!.name.fr) + }) + }) + + it('keeps vertebrae on the spine zones with region codes the draft defines', () => { + const codes = new Set(draft.vertebral_config.regions.map((r) => r.code)) + const spine = draft.annotations.filter( + (a): a is Extract => + a.kind !== 'detail_trigger' && a.vertebral_region_code !== null, + ) + expect(spine).toHaveLength(5) + for (const anno of spine) + expect(codes.has(anno.vertebral_region_code!)).toBe(true) + const legacyId = Object.keys(map.annotations).find( + (id) => map.annotations[id]!.id === 'cervical', + )! + const v2 = leavesAsV2Report([]) + v2.observations = [ + { + id: 'spine', + zones: [{ boneId: legacyId, vertebrae: [{ region: 'C', index: 7 }] }], + findings: [], + freeTextFindings: [], + comment: '', + }, + ] + const zone = migrateReportV2ToV3(v2, map).report.observations[0]!.zones[0]! + expect(zone.vertebrae).toEqual([{ region: 'C', index: 7 }]) + expect(codes.has(zone.vertebrae![0]!.region)).toBe(true) + }) +})