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:
bchanot committed 2026-10-10 11:11:25 +02:00
1 parent cce0bdcd9c
commit 70bf992017
13 files changed
+767 -2

No files matched your search

@@ -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
View File
@@ -1 +1,2 @@
export * from './anatomical-sheet'
export * from './report'
+37
View File
@@ -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>
+27
View File
@@ -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'
+159
View File
@@ -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('/')}`
}
+72
View File
@@ -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>
+97
View File
@@ -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'