diff --git a/src/domain/schema/observation.ts b/src/domain/schema/observation.ts index b5386514..e7d15854 100644 --- a/src/domain/schema/observation.ts +++ b/src/domain/schema/observation.ts @@ -26,11 +26,28 @@ export const ObservationZoneSchema = z.object({ export type ObservationZone = z.infer +/** + * A selected leaf from the species findings tree. The path is anchored at the + * zone root (categories array), e.g. ['sphenoid-dysfunctions', 'physiological', + * 'flexion']. Labels are snapshotted at selection time so previously exported + * reports remain readable if the catalog is later edited. + */ +export const FindingSchema = z.object({ + zoneId: z.string().min(1), + path: z.array(z.string().min(1)).min(1), + labelFrSnapshot: z.string().min(1), + labelEnSnapshot: z.string().min(1), + requiresVetReferral: z.boolean().optional(), +}) + +export type Finding = z.infer + export const ObservationSchema = z.object({ id: z.string().min(1), zones: z.array(ObservationZoneSchema), - pathologyIds: z.array(z.string()), - freeTextPathologies: z.array(z.string()), + findings: z.array(FindingSchema), + /** Free-text additions when the tree does not cover a finding */ + freeTextFindings: z.array(z.string()), severity: SeveritySchema.optional(), comment: z.string(), }) diff --git a/src/domain/schema/pathology.ts b/src/domain/schema/pathology.ts deleted file mode 100644 index a3e37eb6..00000000 --- a/src/domain/schema/pathology.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { z } from 'zod' - -export const PathologyCategorySchema = z.enum([ - 'osseux', - 'articulaire', - 'musculaire', - 'tendino-ligamentaire', - 'fascial', - 'visceral', - 'cranio-sacre', - 'nerveux', - 'autre', -]) - -export type PathologyCategory = z.infer - -export const PathologyRefTypeSchema = z.enum([ - 'manual', - 'journal', - 'database', - 'web', -]) - -export const PathologyRefSchema = z.object({ - type: PathologyRefTypeSchema, - /** Human-readable citation — no raw URLs in PDF output */ - citation: z.string().min(1), - url: z.string().url().optional(), -}) - -export type PathologyRef = z.infer - -export const PathologySchema = z.object({ - /** Stable kebab-case identifier */ - id: z.string().min(1), - labelFr: z.string().min(1), - description: z.string().min(1), - category: PathologyCategorySchema, - /** Empty array = applicable to all species */ - speciesIds: z.array(z.string()), - /** Empty array = applicable to all zones */ - boneIds: z.array(z.string()), - /** At least one source required */ - sources: z.array(PathologyRefSchema).min(1), -}) - -export type Pathology = z.infer diff --git a/src/domain/schema/report.ts b/src/domain/schema/report.ts index 40c39444..457390f4 100644 --- a/src/domain/schema/report.ts +++ b/src/domain/schema/report.ts @@ -11,8 +11,11 @@ const NextAppointmentSchema = z.discriminatedUnion('kind', [ export type NextAppointment = z.infer export const ReportSchema = z.object({ - /** Schema version — always 1 for MVP. Bump on breaking changes. */ - version: z.literal(1), + /** + * Schema version. v2 introduced the hierarchical findings tree + * (replacing the flat pathology list). Bump on breaking changes. + */ + version: z.literal(2), id: z.string().min(1), /** ISO timestamp of report creation */ createdAt: z.string(), diff --git a/src/pdf/attachment.ts b/src/pdf/attachment.ts index f2d43f77..0cac7aa4 100644 --- a/src/pdf/attachment.ts +++ b/src/pdf/attachment.ts @@ -3,11 +3,21 @@ import { ReportSchema, type Report } from '@/domain/schema/report' const FILENAME = 'osteo-report.json' +export class IncompatibleReportVersionError extends Error { + constructor(public readonly foundVersion: number) { + super( + `Ce PDF est au format v${foundVersion}, incompatible avec la version actuelle (v2). ` + + `Réexportez le bilan depuis une version récente de l'application.`, + ) + this.name = 'IncompatibleReportVersionError' + } +} + export async function attachReportJson(pdfDoc: PDFDocument, report: Report): Promise { const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2)) await pdfDoc.attach(bytes, FILENAME, { mimeType: 'application/json', - description: 'Osteo Report state v1', + description: 'Osteo Report state v2', creationDate: new Date(), modificationDate: new Date(), afRelationship: AFRelationship.Data, @@ -30,7 +40,16 @@ export async function extractReportJson(pdfDoc: PDFDocument): Promise { function parseAttachment(bytes: Uint8Array): Report { const text = new TextDecoder().decode(bytes) - const data = JSON.parse(text) + const data: unknown = JSON.parse(text) + if ( + data !== null && + typeof data === 'object' && + 'version' in data && + typeof (data as { version: unknown }).version === 'number' && + (data as { version: number }).version !== 2 + ) { + throw new IncompatibleReportVersionError((data as { version: number }).version) + } return ReportSchema.parse(data) } diff --git a/src/pdf/import.ts b/src/pdf/import.ts index ccd78389..ec15e916 100644 --- a/src/pdf/import.ts +++ b/src/pdf/import.ts @@ -1,10 +1,13 @@ import { PDFDocument } from 'pdf-lib' -import { extractReportJson } from './attachment' +import { extractReportJson, IncompatibleReportVersionError } from './attachment' import type { Report } from '@/domain/schema/report' export class ImportError extends Error { - constructor() { - super("Ce PDF n'a pas été généré par Osteo Report (pas de données détectées).") + constructor(message?: string) { + super( + message ?? + "Ce PDF n'a pas été généré par Osteo Report (pas de données détectées).", + ) this.name = 'ImportError' } } @@ -18,7 +21,12 @@ export async function importReportFromPdf(pdfBytes: Uint8Array): Promise } try { return await extractReportJson(pdfDoc) - } catch { + } catch (err) { + // Version mismatch is a distinct failure mode — surface its message + // to the user instead of the generic "not an osteo PDF" line. + if (err instanceof IncompatibleReportVersionError) { + throw new ImportError(err.message) + } throw new ImportError() } } diff --git a/src/state/reportStore.ts b/src/state/reportStore.ts index ea197ea5..43763424 100644 --- a/src/state/reportStore.ts +++ b/src/state/reportStore.ts @@ -30,8 +30,8 @@ function emptyObservation(): Observation { return { id: generateId(), zones: [], - pathologyIds: [], - freeTextPathologies: [], + findings: [], + freeTextFindings: [], comment: '', } } @@ -44,7 +44,7 @@ export const useReportStore = create((set) => ({ set({ report: { ...draft, - version: 1, + version: 2, id: generateId(), createdAt: nowIso(), observations: diff --git a/tests/unit/pdf.attachment.test.ts b/tests/unit/pdf.attachment.test.ts index 7a024f29..3995f165 100644 --- a/tests/unit/pdf.attachment.test.ts +++ b/tests/unit/pdf.attachment.test.ts @@ -4,7 +4,7 @@ import { attachReportJson, extractReportJson } from '@/pdf/attachment' import type { Report } from '@/domain/schema/report' const report: Report = { - version: 1, + version: 2, id: 'r1', createdAt: '2026-05-18T10:00:00Z', date: '2026-05-18', @@ -27,7 +27,7 @@ describe('PDF attachment roundtrip', () => { const out = await extractReportJson(reopened) expect(out.conclusion).toBe('tout va bien') expect(out.animal.name).toBe('Mistral') - expect(out.version).toBe(1) + expect(out.version).toBe(2) }) it('throws on PDFs without the attachment', async () => { diff --git a/tests/unit/pdf.roundtrip.test.ts b/tests/unit/pdf.roundtrip.test.ts index 2f1cb658..86f3341d 100644 --- a/tests/unit/pdf.roundtrip.test.ts +++ b/tests/unit/pdf.roundtrip.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi } from 'vitest' +import { AFRelationship, PDFDocument } from 'pdf-lib' import { exportReportToPdf } from '@/pdf/export' import { importReportFromPdf, ImportError } from '@/pdf/import' import type { Report } from '@/domain/schema/report' @@ -6,7 +7,7 @@ import type { Report } from '@/domain/schema/report' vi.mock('@/pdf/render/svgToPng', () => ({ rasterizeSvg: async () => new Uint8Array([137, 80, 78, 71]) })) const report: Report = { - version: 1, + version: 2, id: 'r1', createdAt: '2026-05-18T10:00:00Z', date: '2026-05-18', @@ -28,5 +29,31 @@ describe('PDF roundtrip', () => { const bytes = await exportReportToPdf(report) const imported = await importReportFromPdf(bytes) expect(imported.animal.name).toBe('Mistral') + expect(imported.version).toBe(2) + }) + + it('rejects a legacy v1 PDF with a version-specific message', async () => { + const doc = await PDFDocument.create() + doc.addPage() + const legacyPayload = { + version: 1, + id: 'legacy', + createdAt: '2025-12-01T00:00:00Z', + date: '2025-12-01', + practitioner: { name: 'Dr. Dupont' }, + animal: { speciesId: 'equine', name: 'Mistral' }, + owner: { name: 'Jean Martin' }, + observations: [], + conclusion: '', + recommendations: '', + } + const bytes = new TextEncoder().encode(JSON.stringify(legacyPayload)) + await doc.attach(bytes, 'osteo-report.json', { + mimeType: 'application/json', + description: 'Osteo Report state v1', + afRelationship: AFRelationship.Data, + }) + const pdfBytes = await doc.save() + await expect(importReportFromPdf(pdfBytes)).rejects.toThrow(/v1/) }) }) diff --git a/tests/unit/schema.observation.test.ts b/tests/unit/schema.observation.test.ts index 5a361fb9..318fd993 100644 --- a/tests/unit/schema.observation.test.ts +++ b/tests/unit/schema.observation.test.ts @@ -3,6 +3,7 @@ import { ObservationSchema, VertebraSchema, SeveritySchema, + FindingSchema, } from '@/domain/schema/observation' describe('SeveritySchema', () => { @@ -34,12 +35,39 @@ describe('VertebraSchema', () => { }) }) +describe('FindingSchema', () => { + const base = { + zoneId: 'sphenoid', + path: ['sphenoid-dysfunctions', 'physiological', 'flexion'], + labelFrSnapshot: 'Flexion', + labelEnSnapshot: 'Flexion', + } + + it('accepts a minimal finding', () => { + expect(() => FindingSchema.parse(base)).not.toThrow() + }) + + it('accepts the optional vet-referral flag', () => { + expect(() => + FindingSchema.parse({ ...base, requiresVetReferral: true }), + ).not.toThrow() + }) + + it('rejects an empty path', () => { + expect(() => FindingSchema.parse({ ...base, path: [] })).toThrow() + }) + + it('rejects an empty zoneId', () => { + expect(() => FindingSchema.parse({ ...base, zoneId: '' })).toThrow() + }) +}) + describe('ObservationSchema', () => { const baseObs = { id: 'obs-1', zones: [{ boneId: 'epaule' }], - pathologyIds: [], - freeTextPathologies: [], + findings: [], + freeTextFindings: [], comment: '', } @@ -63,6 +91,22 @@ describe('ObservationSchema', () => { expect(() => ObservationSchema.parse(obs)).not.toThrow() }) + it('accepts an observation with findings and free-text additions', () => { + const obs = { + ...baseObs, + findings: [ + { + zoneId: 'sphenoid', + path: ['sphenoid-dysfunctions', 'physiological', 'flexion'], + labelFrSnapshot: 'Flexion', + labelEnSnapshot: 'Flexion', + }, + ], + freeTextFindings: ['note libre'], + } + expect(() => ObservationSchema.parse(obs)).not.toThrow() + }) + it('rejects empty id', () => { expect(() => ObservationSchema.parse({ ...baseObs, id: '' })).toThrow() }) diff --git a/tests/unit/schema.pathology.test.ts b/tests/unit/schema.pathology.test.ts deleted file mode 100644 index b928a221..00000000 --- a/tests/unit/schema.pathology.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { PathologySchema } from '@/domain/schema/pathology' - -describe('PathologySchema', () => { - const base = { - id: 'desmite-suspenseur', - labelFr: 'Desmite du ligament suspenseur', - description: 'Inflammation du ligament suspenseur du boulet.', - category: 'tendino-ligamentaire' as const, - speciesIds: ['equine'], - boneIds: ['boulet-ant', 'boulet-post'], - sources: [ - { type: 'manual' as const, citation: 'Merck Vet Manual (2024).' }, - ], - } - - it('accepts a valid entry', () => { - expect(() => PathologySchema.parse(base)).not.toThrow() - }) - - it('rejects zero sources', () => { - expect(() => PathologySchema.parse({ ...base, sources: [] })).toThrow() - }) - - it('rejects empty id', () => { - expect(() => PathologySchema.parse({ ...base, id: '' })).toThrow() - }) - - it('rejects non-URL urls', () => { - expect(() => - PathologySchema.parse({ - ...base, - sources: [{ type: 'web', citation: 'X', url: 'not-a-url' }], - }), - ).toThrow() - }) -}) diff --git a/tests/unit/schema.report.test.ts b/tests/unit/schema.report.test.ts index 97493d14..2bc2dc1c 100644 --- a/tests/unit/schema.report.test.ts +++ b/tests/unit/schema.report.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest' import { ReportSchema } from '@/domain/schema/report' const minimal = { - version: 1 as const, + version: 2 as const, id: 'r1', createdAt: '2026-05-18T10:00:00Z', date: '2026-05-18', @@ -37,8 +37,12 @@ describe('ReportSchema', () => { ).not.toThrow() }) - it('rejects version !== 1', () => { - expect(() => ReportSchema.parse({ ...minimal, version: 2 })).toThrow() + it('rejects legacy v1 reports', () => { + expect(() => ReportSchema.parse({ ...minimal, version: 1 })).toThrow() + }) + + it('rejects unknown future versions', () => { + expect(() => ReportSchema.parse({ ...minimal, version: 3 })).toThrow() }) it('rejects empty practitioner.name', () => { diff --git a/tests/unit/smoke.test.ts b/tests/unit/smoke.test.ts index ac5f93db..c9bf195c 100644 --- a/tests/unit/smoke.test.ts +++ b/tests/unit/smoke.test.ts @@ -23,7 +23,7 @@ describe('skeleton smoke test', () => { it('ReportSchema parses a valid minimal report', () => { const validReport = { - version: 1 as const, + version: 2 as const, id: generateId(), createdAt: nowIso(), date: todayIso(), diff --git a/tests/unit/state.reportStore.test.ts b/tests/unit/state.reportStore.test.ts index 1ecd2543..602130a4 100644 --- a/tests/unit/state.reportStore.test.ts +++ b/tests/unit/state.reportStore.test.ts @@ -16,10 +16,10 @@ beforeEach(() => { }) describe('reportStore.initReport', () => { - it('sets a report with version=1, id, and createdAt', () => { + it('sets a report with version=2, id, and createdAt', () => { useReportStore.getState().initReport(draft) const r = useReportStore.getState().report! - expect(r.version).toBe(1) + expect(r.version).toBe(2) expect(r.id.length).toBeGreaterThan(0) expect(r.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/) expect(r.practitioner.name).toBe('Dr. Dupont')