/** * 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) }) })