Files
faunosteo/packages/domain/tests/report.migrate.test.ts
T

258 lines
8.2 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import {
ReportMigrationMapSchema,
ReportSchema,
ReportV2Schema,
migrateReportV2ToV3,
readReportDocument,
UnsupportedReportVersionError,
type ReportMigrationMap,
} from '../src'
import full from './fixtures/report-v2.full.json'
import minimal from './fixtures/report-v2.minimal.json'
const SHA = 'a'.repeat(64)
/** Hand-written slice of the generated map, enough for the golden fixtures. */
const MAP: ReportMigrationMap = ReportMigrationMapSchema.parse({
schema_version: 1,
sheet: { sheetId: 'sheet-1', versionId: null, documentSha256: SHA },
main_view_id: 'main',
views: { head: 'head' },
annotations: {
'point-mpbwyyc9': {
id: 'c7-t1',
name: {
fr: 'Charnière C7-T1 (cervico-thoracique)',
en: 'C7-T1 (Cervicothoracic)',
},
},
'point-mpbwtst0': {
id: 'hip',
name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' },
},
'zone-mpbx5hx2': {
id: 'cervical',
name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' },
},
'point-mpbyo7zq': {
id: 'atm',
name: {
fr: 'Articulation Temporo-Mandibulaire (ATM)',
en: 'Temporomandibular Joint (TMJ)',
},
},
},
finding_paths: {
'c7-t1/c7-t1-dysfunctions/segmental/fixation':
'c7-t1/c7-t1-dysfunctions/segmental/fixation',
'hip/hip-dysfunctions/articular/restriction-flexion':
'hip/hip-dysfunctions/articular/restriction-flexion',
'cervical/cervical-observations/stumbling-proprioceptive':
'cervical/cervical-consultation-reasons/stumbling-proprioceptive',
'atm/atm-observations/headshaking': null,
},
})
describe('Report v3 schema', () => {
it('accepts a report with an empty reserved localAnnotations and defaults it', () => {
const parsed = ReportSchema.parse({
version: 3,
id: 'r',
createdAt: '2026-10-10T00:00:00Z',
date: '2026-10-10',
practitioner: { name: 'P' },
animal: { speciesId: 'equine', name: 'A' },
owner: { name: 'O' },
sheet: { sheetId: 's', versionId: null, documentSha256: SHA },
observations: [],
conclusion: '',
recommendations: '',
})
expect(parsed.localAnnotations).toEqual([])
})
it.each([
['version 2', { version: 2 }],
['a reserved localAnnotations entry', { localAnnotations: [{ x: 1 }] }],
[
'a French severity value',
{
observations: [
{
id: 'o',
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
severity: 'légère',
},
],
},
],
[
'a malformed document hash',
{ sheet: { sheetId: 's', versionId: null, documentSha256: 'xyz' } },
],
])('rejects %s', (_label, patch) => {
const base = migrateReportV2ToV3(ReportV2Schema.parse(minimal), MAP).report
expect(ReportSchema.safeParse({ ...base, ...patch }).success).toBe(false)
})
})
describe('migrateReportV2ToV3 on the golden fixtures', () => {
const v2 = ReportV2Schema.parse(full)
const outcome = migrateReportV2ToV3(v2, MAP)
const { report } = outcome
it('keeps identity, dates, conclusion and appointment verbatim', () => {
expect(report.version).toBe(3)
expect(report.id).toBe(v2.id)
expect(report.practitioner).toEqual(v2.practitioner)
expect(report.animal).toEqual(v2.animal)
expect(report.owner).toEqual(v2.owner)
expect(report.conclusion).toBe(v2.conclusion)
expect(report.nextAppointment).toEqual(v2.nextAppointment)
expect(report.sheet).toEqual(MAP.sheet)
expect(report.observations.map((o) => o.id)).toEqual(
v2.observations.map((o) => o.id),
)
})
it('maps legacy ids to annotation ids, views and snapshots the legacy names', () => {
const zones = report.observations.flatMap((o) => o.zones)
const hip = zones.filter((z) => z.annotationId === 'hip')
expect(hip.map((z) => z.side).sort()).toEqual(['left', 'right'])
expect(hip[0]!.viewId).toBe('main')
expect(hip[0]!.labelFrSnapshot).toBe('Hanche (coxo-fémorale)')
const atm = zones.find((z) => z.annotationId === 'atm')!
expect(atm.viewId).toBe('head')
const cervical = zones.find((z) => z.annotationId === 'cervical')!
expect(cervical.vertebrae).toEqual(
v2.observations
.flatMap((o) => o.zones)
.find((z) => z.boneId === 'zone-mpbx5hx2')!.vertebrae,
)
expect(zones.some((z) => z.unresolved)).toBe(false)
expect(outcome.unresolvedZones).toBe(0)
})
it('remaps moved finding paths, keeps removed ones flagged with their snapshots', () => {
const findings = report.observations.flatMap((o) => o.findings)
const moved = findings.find((f) =>
f.path.includes('stumbling-proprioceptive'),
)!
expect(moved.path).toEqual([
'cervical-consultation-reasons',
'stumbling-proprioceptive',
])
expect(moved.findingZoneId).toBe('cervical')
expect(moved.unresolved).toBeUndefined()
const removed = findings.find((f) => f.path.includes('headshaking'))!
expect(removed.unresolved).toBe(true)
expect(removed.path).toEqual(['atm-observations', 'headshaking'])
expect(removed.labelFrSnapshot).toBe('Headshaking (secouement de tête)')
expect(removed.requiresVetReferral).toBe(true)
expect(outcome.unresolvedFindings).toBe(1)
})
it('converts severities to stable codes', () => {
const codes = report.observations.map((o) => o.severity)
expect(codes).toContain('moderate')
expect(codes).toContain('severe')
expect(
codes.every(
(c) => c === undefined || ['mild', 'moderate', 'severe'].includes(c),
),
).toBe(true)
})
it('flags an unknown legacy zone id and an unknown finding path instead of dropping them', () => {
const odd = {
...v2,
observations: [
{
id: 'o',
zones: [{ boneId: 'point-unknown' }],
findings: [
{
zoneId: 'nowhere',
path: ['x'],
labelFrSnapshot: 'X',
labelEnSnapshot: 'X',
},
],
freeTextFindings: [],
comment: '',
},
],
}
const out = migrateReportV2ToV3(ReportV2Schema.parse(odd), MAP)
expect(out.report.observations[0]!.zones[0]).toMatchObject({
annotationId: 'point-unknown',
viewId: 'main',
unresolved: true,
})
expect(out.report.observations[0]!.findings[0]).toMatchObject({
findingZoneId: 'nowhere',
path: ['x'],
unresolved: true,
})
expect(out.unresolvedZones).toBe(1)
expect(out.unresolvedFindings).toBe(1)
})
})
describe('readReportDocument', () => {
it('returns a v3 document as is and migrates a v2 one', () => {
const v3 = migrateReportV2ToV3(ReportV2Schema.parse(minimal), MAP).report
expect(readReportDocument(v3, MAP).report).toEqual(v3)
expect(readReportDocument(minimal, MAP).report.version).toBe(3)
})
it('refuses unknown versions with the found version', () => {
expect(() => readReportDocument({ ...minimal, version: 1 }, MAP)).toThrow(
UnsupportedReportVersionError,
)
expect(() => readReportDocument({ hello: 'world' }, MAP)).toThrow(
UnsupportedReportVersionError,
)
try {
readReportDocument({ ...minimal, version: 7 }, MAP)
} catch (e) {
expect((e as UnsupportedReportVersionError).foundVersion).toBe(7)
}
})
})
describe('hostile identifiers', () => {
it('treats prototype keys as unknown ids instead of throwing', () => {
const odd = {
...ReportV2Schema.parse(minimal),
observations: [
{
id: 'o',
zones: [
{ boneId: '__proto__' },
{ boneId: 'constructor', detailSourceId: '__proto__' },
],
findings: [
{
zoneId: 'constructor',
path: ['__proto__'],
labelFrSnapshot: 'X',
labelEnSnapshot: 'X',
},
],
freeTextFindings: [],
comment: '',
},
],
}
const out = migrateReportV2ToV3(ReportV2Schema.parse(odd), MAP)
expect(out.unresolvedZones).toBe(2)
expect(out.unresolvedFindings).toBe(1)
expect(out.report.observations[0]!.zones[1]!.viewId).toBe('__proto__')
})
})