feat(domain): report document v3 (annotation ids, sheet ref, severity codes, unresolved findings), v2 schema as input, v2→v3 migration with map; annotation colour override
This commit is contained in:
1 parent
cce0bdcd9c
commit
70bf992017
13 files changed
+767
-2
No files matched your search
@@ -2,14 +2,15 @@
|
||||
"name": "@faunosteo/domain",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Faunosteo pure domain model: canonical anatomical sheet document, Zod schemas and integrity rules",
|
||||
"description": "Faunosteo pure domain model: canonical anatomical sheet document, report document (v3 + v2 migration), Zod schemas and integrity rules",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./anatomical-sheet": "./src/anatomical-sheet/index.ts"
|
||||
"./anatomical-sheet": "./src/anatomical-sheet/index.ts",
|
||||
"./report": "./src/report/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
|
||||
@@ -149,6 +149,8 @@ const annotationCommon = {
|
||||
laterality: LateralitySchema,
|
||||
geometry: GeometrySchema.nullable(),
|
||||
review_status: ReviewStatusSchema.default('inherited'),
|
||||
/** Marker colour of this annotation; null = the category colour. */
|
||||
color: HexColorSchema.nullable().default(null),
|
||||
}
|
||||
|
||||
/** Observable annotations link to findings through one explicit field. */
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export * from './anatomical-sheet'
|
||||
export * from './report'
|
||||
@@ -0,0 +1,37 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* Identity snapshots carried by every report version: who wrote it, on
|
||||
* which animal, for which owner. Copied into the report at creation so a
|
||||
* report stays readable when the underlying records change (BDR-010).
|
||||
*/
|
||||
|
||||
export const PractitionerSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
cabinet: z.string().optional(),
|
||||
contact: z.string().optional(),
|
||||
/** SIRET, 14-digit French business identifier (not validated). */
|
||||
siret: z.string().optional(),
|
||||
})
|
||||
export type Practitioner = z.infer<typeof PractitionerSchema>
|
||||
|
||||
export const AnimalSchema = z.object({
|
||||
/** Species of the animal; the sheet the report references matches it. */
|
||||
speciesId: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
breed: z.string().optional(),
|
||||
age: z.string().optional(),
|
||||
})
|
||||
export type Animal = z.infer<typeof AnimalSchema>
|
||||
|
||||
export const OwnerSchema = z.object({ name: z.string().min(1) })
|
||||
export type Owner = z.infer<typeof OwnerSchema>
|
||||
|
||||
export const NextAppointmentSchema = z.discriminatedUnion('kind', [
|
||||
z.object({ kind: z.literal('date'), date: z.string() }),
|
||||
z.object({ kind: z.literal('period'), text: z.string() }),
|
||||
])
|
||||
export type NextAppointment = z.infer<typeof NextAppointmentSchema>
|
||||
|
||||
export const LateralSideSchema = z.enum(['left', 'right'])
|
||||
export type LateralSide = z.infer<typeof LateralSideSchema>
|
||||
@@ -0,0 +1,27 @@
|
||||
export * from './identity'
|
||||
export * from './v3'
|
||||
export {
|
||||
FindingV2Schema,
|
||||
ObservationV2Schema,
|
||||
ObservationZoneV2Schema,
|
||||
ReportV2Schema,
|
||||
SeverityV2Schema,
|
||||
VertebraV2Schema,
|
||||
VertebralRegionV2Schema,
|
||||
type FindingV2,
|
||||
type ObservationV2,
|
||||
type ObservationZoneV2,
|
||||
type ReportV2,
|
||||
type SeverityV2,
|
||||
} from './v2'
|
||||
export {
|
||||
ReportMigrationMapSchema,
|
||||
findingPathKey,
|
||||
type ReportMigrationMap,
|
||||
} from './migration-map'
|
||||
export {
|
||||
migrateReportV2ToV3,
|
||||
readReportDocument,
|
||||
UnsupportedReportVersionError,
|
||||
type MigrationOutcome,
|
||||
} from './migrate'
|
||||
@@ -0,0 +1,159 @@
|
||||
import { findingPathKey, type ReportMigrationMap } from './migration-map'
|
||||
import {
|
||||
ReportV2Schema,
|
||||
type FindingV2,
|
||||
type ObservationV2,
|
||||
type ObservationZoneV2,
|
||||
type ReportV2,
|
||||
type SeverityV2,
|
||||
} from './v2'
|
||||
import {
|
||||
REPORT_VERSION,
|
||||
ReportSchema,
|
||||
type Finding,
|
||||
type Observation,
|
||||
type Report,
|
||||
type ReportZone,
|
||||
type Severity,
|
||||
} from './v3'
|
||||
|
||||
/**
|
||||
* Lifts a Report v2 (PDF attachment or sessionStorage draft of the deployed
|
||||
* application) to v3 against the migration map of the reference sheet.
|
||||
* Never throws on content: a zone or finding the map cannot place is kept
|
||||
* verbatim with its snapshots and flagged `unresolved`, so the practitioner's
|
||||
* data survives any catalog change and stays identifiable.
|
||||
*/
|
||||
|
||||
const SEVERITY: Record<SeverityV2, Severity> = {
|
||||
légère: 'mild',
|
||||
modérée: 'moderate',
|
||||
sévère: 'severe',
|
||||
}
|
||||
|
||||
export interface MigrationOutcome {
|
||||
report: Report
|
||||
/** Zones whose legacy id has no annotation in the map. */
|
||||
unresolvedZones: number
|
||||
/** Findings whose legacy path no longer exists in the sheet. */
|
||||
unresolvedFindings: number
|
||||
}
|
||||
|
||||
function migrateZone(
|
||||
zone: ObservationZoneV2,
|
||||
map: ReportMigrationMap,
|
||||
): ReportZone {
|
||||
const entry = map.annotations[zone.boneId]
|
||||
const viewId = zone.detailSourceId
|
||||
? (map.views[zone.detailSourceId] ?? zone.detailSourceId)
|
||||
: map.main_view_id
|
||||
const out: ReportZone = { annotationId: entry?.id ?? zone.boneId, viewId }
|
||||
if (zone.side) out.side = zone.side
|
||||
if (zone.vertebrae) out.vertebrae = zone.vertebrae.map((v) => ({ ...v }))
|
||||
if (entry) {
|
||||
out.labelFrSnapshot = entry.name.fr
|
||||
out.labelEnSnapshot = entry.name.en
|
||||
} else {
|
||||
out.unresolved = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function migrateFinding(finding: FindingV2, map: ReportMigrationMap): Finding {
|
||||
const mapped = map.finding_paths[findingPathKey(finding.zoneId, finding.path)]
|
||||
const out: Finding = {
|
||||
findingZoneId: finding.zoneId,
|
||||
path: [...finding.path],
|
||||
labelFrSnapshot: finding.labelFrSnapshot,
|
||||
labelEnSnapshot: finding.labelEnSnapshot,
|
||||
}
|
||||
if (finding.requiresVetReferral) out.requiresVetReferral = true
|
||||
if (finding.side) out.side = finding.side
|
||||
if (typeof mapped === 'string') {
|
||||
const [zoneId, ...path] = mapped.split('/')
|
||||
out.findingZoneId = zoneId!
|
||||
out.path = path
|
||||
} else {
|
||||
// null = removed by curation; undefined = never part of the legacy catalog.
|
||||
out.unresolved = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function migrateObservation(
|
||||
obs: ObservationV2,
|
||||
map: ReportMigrationMap,
|
||||
): Observation {
|
||||
const out: Observation = {
|
||||
id: obs.id,
|
||||
zones: obs.zones.map((z) => migrateZone(z, map)),
|
||||
findings: obs.findings.map((f) => migrateFinding(f, map)),
|
||||
freeTextFindings: [...obs.freeTextFindings],
|
||||
comment: obs.comment,
|
||||
}
|
||||
if (obs.severity) out.severity = SEVERITY[obs.severity]
|
||||
return out
|
||||
}
|
||||
|
||||
export function migrateReportV2ToV3(
|
||||
report: ReportV2,
|
||||
map: ReportMigrationMap,
|
||||
): MigrationOutcome {
|
||||
const observations = report.observations.map((o) =>
|
||||
migrateObservation(o, map),
|
||||
)
|
||||
const migrated: Report = {
|
||||
version: REPORT_VERSION,
|
||||
id: report.id,
|
||||
createdAt: report.createdAt,
|
||||
date: report.date,
|
||||
practitioner: report.practitioner,
|
||||
animal: report.animal,
|
||||
owner: report.owner,
|
||||
sheet: { ...map.sheet },
|
||||
observations,
|
||||
conclusion: report.conclusion,
|
||||
recommendations: report.recommendations,
|
||||
localAnnotations: [],
|
||||
}
|
||||
if (report.nextAppointment) migrated.nextAppointment = report.nextAppointment
|
||||
const zones = observations.flatMap((o) => o.zones)
|
||||
const findings = observations.flatMap((o) => o.findings)
|
||||
return {
|
||||
report: ReportSchema.parse(migrated),
|
||||
unresolvedZones: zones.filter((z) => z.unresolved).length,
|
||||
unresolvedFindings: findings.filter((f) => f.unresolved).length,
|
||||
}
|
||||
}
|
||||
|
||||
/** Thrown for a report whose version this code cannot read. */
|
||||
export class UnsupportedReportVersionError extends Error {
|
||||
constructor(public readonly foundVersion: number | null) {
|
||||
super(`unsupported report version: ${foundVersion ?? 'unknown'}`)
|
||||
this.name = 'UnsupportedReportVersionError'
|
||||
}
|
||||
}
|
||||
|
||||
function versionOf(data: unknown): number | null {
|
||||
if (data === null || typeof data !== 'object') return null
|
||||
const v = (data as { version?: unknown }).version
|
||||
return typeof v === 'number' ? v : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a report document of any supported version (2 or 3) and returns it
|
||||
* as v3. Zod errors propagate: a document of a known version that does not
|
||||
* parse is corrupt, not old.
|
||||
*/
|
||||
export function readReportDocument(
|
||||
data: unknown,
|
||||
map: ReportMigrationMap,
|
||||
): MigrationOutcome {
|
||||
const version = versionOf(data)
|
||||
if (version === REPORT_VERSION) {
|
||||
const report = ReportSchema.parse(data)
|
||||
return { report, unresolvedZones: 0, unresolvedFindings: 0 }
|
||||
}
|
||||
if (version === 2) return migrateReportV2ToV3(ReportV2Schema.parse(data), map)
|
||||
throw new UnsupportedReportVersionError(version)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { z } from 'zod'
|
||||
import { SheetRefSchema } from './v3'
|
||||
|
||||
/**
|
||||
* Correspondence between the legacy identifiers a Report v2 carries and the
|
||||
* canonical sheet a Report v3 references. Generated by the curation pipeline
|
||||
* (`draft/report-migration-map.json`), never written by hand: annotations
|
||||
* come from the legacy id map, finding paths from the applier's rename and
|
||||
* removal records. A `null` finding path means "removed from the sheet":
|
||||
* the migration keeps the finding with its snapshots and flags it.
|
||||
*/
|
||||
|
||||
const LocalizedNameSchema = z.object({ fr: z.string(), en: z.string() })
|
||||
|
||||
export const ReportMigrationMapSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
sheet: SheetRefSchema,
|
||||
/** Id of the view a v2 zone without `detailSourceId` belongs to. */
|
||||
main_view_id: z.string().min(1),
|
||||
/** Legacy detail popup key → view id. */
|
||||
views: z.record(z.string(), z.string().min(1)),
|
||||
/** Legacy `data-anno-id` → annotation id and the legacy labels. */
|
||||
annotations: z.record(
|
||||
z.string(),
|
||||
z.object({ id: z.string().min(1), name: LocalizedNameSchema }),
|
||||
),
|
||||
/**
|
||||
* `<zoneId>/<path segments joined by '/'>` of every legacy finding node →
|
||||
* the same key in the sheet, or null when the node was removed.
|
||||
*/
|
||||
finding_paths: z.record(z.string(), z.string().nullable()),
|
||||
})
|
||||
export type ReportMigrationMap = z.infer<typeof ReportMigrationMapSchema>
|
||||
|
||||
export function findingPathKey(
|
||||
zoneId: string,
|
||||
path: readonly string[],
|
||||
): string {
|
||||
return `${zoneId}/${path.join('/')}`
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
AnimalSchema,
|
||||
LateralSideSchema,
|
||||
NextAppointmentSchema,
|
||||
OwnerSchema,
|
||||
PractitionerSchema,
|
||||
} from './identity'
|
||||
|
||||
/**
|
||||
* Report document version 2, exactly as the deployed application wrote it
|
||||
* (PDF attachments of the practitioner's archive, sessionStorage drafts).
|
||||
* Kept as an INPUT format only: nothing writes v2 any more, `migrate.ts`
|
||||
* lifts it to v3. Field comments describe the legacy meaning.
|
||||
*/
|
||||
|
||||
export const SeverityV2Schema = z.enum(['légère', 'modérée', 'sévère'])
|
||||
export type SeverityV2 = z.infer<typeof SeverityV2Schema>
|
||||
|
||||
export const VertebralRegionV2Schema = z.enum(['C', 'T', 'L', 'S', 'Cd'])
|
||||
|
||||
export const VertebraV2Schema = z.object({
|
||||
region: VertebralRegionV2Schema,
|
||||
index: z.number().int().positive(),
|
||||
})
|
||||
|
||||
export const ObservationZoneV2Schema = z.object({
|
||||
/** The legacy SVG `data-anno-id` (e.g. `point-mpbwtst0`). */
|
||||
boneId: z.string().min(1),
|
||||
/** Legacy detail popup key (`head`) when the zone came from that view. */
|
||||
detailSourceId: z.string().optional(),
|
||||
vertebrae: z.array(VertebraV2Schema).optional(),
|
||||
side: LateralSideSchema.optional(),
|
||||
})
|
||||
export type ObservationZoneV2 = z.infer<typeof ObservationZoneV2Schema>
|
||||
|
||||
export const FindingV2Schema = z.object({
|
||||
/** Legacy catalog zone key (equal to the canonical finding zone id). */
|
||||
zoneId: z.string().min(1),
|
||||
/** Node ids from the zone's categories down to the leaf. */
|
||||
path: z.array(z.string().min(1)).min(1),
|
||||
labelFrSnapshot: z.string().min(1),
|
||||
labelEnSnapshot: z.string().min(1),
|
||||
requiresVetReferral: z.boolean().optional(),
|
||||
side: LateralSideSchema.optional(),
|
||||
})
|
||||
export type FindingV2 = z.infer<typeof FindingV2Schema>
|
||||
|
||||
export const ObservationV2Schema = z.object({
|
||||
id: z.string().min(1),
|
||||
zones: z.array(ObservationZoneV2Schema),
|
||||
findings: z.array(FindingV2Schema),
|
||||
freeTextFindings: z.array(z.string()),
|
||||
severity: SeverityV2Schema.optional(),
|
||||
comment: z.string(),
|
||||
})
|
||||
export type ObservationV2 = z.infer<typeof ObservationV2Schema>
|
||||
|
||||
export const ReportV2Schema = z.object({
|
||||
version: z.literal(2),
|
||||
id: z.string().min(1),
|
||||
createdAt: z.string(),
|
||||
date: z.string(),
|
||||
practitioner: PractitionerSchema,
|
||||
animal: AnimalSchema,
|
||||
owner: OwnerSchema,
|
||||
observations: z.array(ObservationV2Schema),
|
||||
conclusion: z.string(),
|
||||
recommendations: z.string(),
|
||||
nextAppointment: NextAppointmentSchema.optional(),
|
||||
})
|
||||
export type ReportV2 = z.infer<typeof ReportV2Schema>
|
||||
@@ -0,0 +1,97 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
AnimalSchema,
|
||||
LateralSideSchema,
|
||||
NextAppointmentSchema,
|
||||
OwnerSchema,
|
||||
PractitionerSchema,
|
||||
} from './identity'
|
||||
|
||||
/**
|
||||
* Report document version 3: a report written on the canonical anatomical
|
||||
* sheet. Zones name an annotation of a view of an exact sheet, findings a
|
||||
* node path of a finding zone, both by stable ids; every label the report
|
||||
* needs to stay readable without the sheet is snapshotted. Breaking change
|
||||
* → version 4; additive optional fields keep the version.
|
||||
*/
|
||||
|
||||
export const REPORT_VERSION = 3
|
||||
|
||||
export const SeveritySchema = z.enum(['mild', 'moderate', 'severe'])
|
||||
export type Severity = z.infer<typeof SeveritySchema>
|
||||
|
||||
/** Region codes are the sheet's `vertebral_config` codes, checked at runtime. */
|
||||
export const VertebraSchema = z.object({
|
||||
region: z.string().min(1),
|
||||
index: z.number().int().positive(),
|
||||
})
|
||||
export type Vertebra = z.infer<typeof VertebraSchema>
|
||||
|
||||
/** The sheet document a report was built on, by content. */
|
||||
export const SheetRefSchema = z.object({
|
||||
sheetId: z.string().min(1),
|
||||
/** Database version id once the sheet lives in the database; null for a bundled draft. */
|
||||
versionId: z.string().min(1).nullable(),
|
||||
/** sha256 of the document file the report was written against. */
|
||||
documentSha256: z.string().regex(/^[0-9a-f]{64}$/),
|
||||
})
|
||||
export type SheetRef = z.infer<typeof SheetRefSchema>
|
||||
|
||||
export const ReportZoneSchema = z.object({
|
||||
annotationId: z.string().min(1),
|
||||
viewId: z.string().min(1),
|
||||
side: LateralSideSchema.optional(),
|
||||
vertebrae: z.array(VertebraSchema).optional(),
|
||||
/** Annotation name at selection time (or legacy name at migration). */
|
||||
labelFrSnapshot: z.string().optional(),
|
||||
labelEnSnapshot: z.string().optional(),
|
||||
/** Set by the migration when the legacy id has no canonical annotation. */
|
||||
unresolved: z.literal(true).optional(),
|
||||
})
|
||||
export type ReportZone = z.infer<typeof ReportZoneSchema>
|
||||
|
||||
export const FindingSchema = z.object({
|
||||
findingZoneId: z.string().min(1),
|
||||
/** Node ids from the zone's categories down to the leaf. */
|
||||
path: z.array(z.string().min(1)).min(1),
|
||||
labelFrSnapshot: z.string().min(1),
|
||||
labelEnSnapshot: z.string().min(1),
|
||||
requiresVetReferral: z.boolean().optional(),
|
||||
side: LateralSideSchema.optional(),
|
||||
/** Set by the migration when the path no longer exists in the sheet; data kept. */
|
||||
unresolved: z.literal(true).optional(),
|
||||
})
|
||||
export type Finding = z.infer<typeof FindingSchema>
|
||||
|
||||
export const ObservationSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
zones: z.array(ReportZoneSchema),
|
||||
findings: z.array(FindingSchema),
|
||||
freeTextFindings: z.array(z.string()),
|
||||
severity: SeveritySchema.optional(),
|
||||
comment: z.string(),
|
||||
})
|
||||
export type Observation = z.infer<typeof ObservationSchema>
|
||||
|
||||
export const ReportSchema = z.object({
|
||||
version: z.literal(REPORT_VERSION),
|
||||
id: z.string().min(1),
|
||||
/** ISO timestamp of report creation. */
|
||||
createdAt: z.string(),
|
||||
/** ISO date of the clinical encounter. */
|
||||
date: z.string(),
|
||||
practitioner: PractitionerSchema,
|
||||
animal: AnimalSchema,
|
||||
owner: OwnerSchema,
|
||||
sheet: SheetRefSchema,
|
||||
observations: z.array(ObservationSchema),
|
||||
conclusion: z.string(),
|
||||
recommendations: z.string(),
|
||||
nextAppointment: NextAppointmentSchema.optional(),
|
||||
/** Reserved for report-only points (OPEN_QUESTIONS Q6); empty until defined. */
|
||||
localAnnotations: z.array(z.unknown()).max(0).default([]),
|
||||
})
|
||||
export type Report = z.infer<typeof ReportSchema>
|
||||
export type ReportInput = z.input<typeof ReportSchema>
|
||||
|
||||
export type { LateralSide, NextAppointment } from './identity'
|
||||
@@ -33,6 +33,7 @@ function point(id: string, fields: Partial<Annotation> = {}): Annotation {
|
||||
laterality: 'bilateral',
|
||||
geometry: null,
|
||||
review_status: 'inherited',
|
||||
color: null,
|
||||
name: { fr: id, en: id },
|
||||
finding_zone_id: 'hip',
|
||||
vertebral_region_code: null,
|
||||
@@ -49,6 +50,7 @@ function trigger(id: string, viewId: string, opensViewId: string) {
|
||||
laterality: 'unpaired',
|
||||
geometry: null,
|
||||
review_status: 'inherited',
|
||||
color: null,
|
||||
name: null,
|
||||
opens_view_id: opensViewId,
|
||||
} satisfies Annotation
|
||||
|
||||
@@ -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" }
|
||||
}
|
||||
@@ -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,226 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user