/** * Replaces state.reportStore / state.reportStore.restore / .setters / * state.draftMirror: the v3 store, its actions, the sessionStorage mirror, * the migration of a v2 draft on restore, and (Step 6) the archive kept * beside the report and the rebase of a stale draft. */ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi, } from 'vitest' import type { Annotation } from '@faunosteo/core-wasm/types' import { createReportStore, useReportStore } from '@/state/reportStore' import { ARCHIVE_KEY, DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence' import type { SheetIndex } from '@/services/sheetIndex' import { archiveEnvelope, emptyObservation, loadTestSheet, minimalReport, } from '../helpers/sheet' import fullV2 from '../fixtures/report-v2.full.json' let sheet: SheetIndex beforeAll(async () => { sheet = await loadTestSheet() }) beforeEach(() => { sessionStorage.clear() useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0, }) }) afterEach(() => vi.restoreAllMocks()) const draft = () => ({ date: '2026-10-10', practitioner: { name: 'Dr. Dupont' }, animal: { speciesId: 'equine', name: 'Mistral' }, owner: { name: 'Jean Martin' }, observations: [], conclusion: '', recommendations: '', }) describe('initReport', () => { it('stamps version 3, id, createdAt, the sheet ref and one empty observation', () => { useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet) const report = useReportStore.getState().report! expect(report.version).toBe(3) expect(report.id).toBeTruthy() expect(report.createdAt).toMatch(/^\d{4}-/) expect(report.sheet).toEqual(sheet.sheet.ref) expect(report.observations).toHaveLength(1) expect(report.localAnnotations).toEqual([]) expect(useReportStore.getState().activeObservationIndex).toBe(0) }) }) describe('observation actions', () => { it('adds, updates, moves and removes observations, keeping the active index sane', () => { const s = useReportStore.getState() s.initReport(draft(), sheet.sheet.ref, sheet) s.addObservation() expect(useReportStore.getState().report!.observations).toHaveLength(2) expect(useReportStore.getState().activeObservationIndex).toBe(1) const [first, second] = useReportStore.getState().report!.observations s.updateObservation(1, { ...second!, comment: 'note' }) s.moveObservationUp(1) expect( useReportStore.getState().report!.observations.map((o) => o.id), ).toEqual([second!.id, first!.id]) s.moveObservationDown(0) expect( useReportStore.getState().report!.observations.map((o) => o.id), ).toEqual([first!.id, second!.id]) s.moveObservationUp(0) s.moveObservationDown(1) s.removeObservation(1) expect(useReportStore.getState().report!.observations).toHaveLength(1) expect(useReportStore.getState().activeObservationIndex).toBe(0) s.setActiveObservation(-1) expect(useReportStore.getState().activeObservationIndex).toBe(-1) }) it('setters replace identity, conclusion and appointment; nextAppointment can be cleared', () => { const s = useReportStore.getState() s.initReport(draft(), sheet.sheet.ref, sheet) s.setPractitioner({ name: 'Dr. X' }) s.setAnimal({ speciesId: 'equine', name: 'Y' }) s.setOwner({ name: 'Z' }) s.setConclusion('c') s.setRecommendations('r') s.setNextAppointment({ kind: 'date', date: '2026-11-01' }) const r = useReportStore.getState().report! expect([ r.practitioner.name, r.animal.name, r.owner.name, r.conclusion, r.recommendations, ]).toEqual(['Dr. X', 'Y', 'Z', 'c', 'r']) expect(r.nextAppointment).toEqual({ kind: 'date', date: '2026-11-01' }) s.setNextAppointment(undefined) expect('nextAppointment' in useReportStore.getState().report!).toBe(false) s.reset() expect(useReportStore.getState().report).toBeNull() }) it('every action is a no-op without a report', () => { const s = useReportStore.getState() s.addObservation() s.updateObservation(0, emptyObservation()) s.setConclusion('x') expect(useReportStore.getState().report).toBeNull() }) }) describe('sessionStorage mirror and restore', () => { it('mirrors every change under osteo:draft and removes it on reset', () => { useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet) expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3) useReportStore.getState().reset() expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull() }) it('restores a v3 draft, and migrates a v2 draft left by the previous version', () => { const v3 = minimalReport(sheet, { conclusion: 'kept' }) sessionStorage.setItem(DRAFT_KEY, JSON.stringify(v3)) useReportStore.getState().restoreDraft(sheet) expect(useReportStore.getState().report?.conclusion).toBe('kept') useReportStore.setState({ report: null }) sessionStorage.setItem(DRAFT_KEY, JSON.stringify(fullV2)) useReportStore.getState().restoreDraft(sheet) const restored = useReportStore.getState().report! expect(restored.version).toBe(3) expect( restored.observations.flatMap((o) => o.zones).map((z) => z.annotationId), ).toContain('hip') expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3) }) it('sets an unreadable draft aside instead of restoring it, and does not replace an open report', () => { // R2: an unreadable draft is quarantined (P12), no longer dropped. sessionStorage.setItem(DRAFT_KEY, '{not json') expect(useReportStore.getState().restoreDraft(sheet)).toEqual({ kind: 'quarantined', }) expect(useReportStore.getState().report).toBeNull() // R2 maintenance B: the slot already holds the first text, which is never replaced. sessionStorage.setItem(DRAFT_KEY, JSON.stringify({ version: 1 })) expect(useReportStore.getState().restoreDraft(sheet)).toMatchObject({ kind: 'held', held: [{ text: 'draft', reason: 'unreadable' }], }) expect(useReportStore.getState().report).toBeNull() expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe('{not json') expect(sessionStorage.getItem(DRAFT_KEY)).toBe(JSON.stringify({ version: 1 })) useReportStore.getState().discardSessionText('draft') useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet) const before = useReportStore.getState().report sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet))) useReportStore.getState().restoreDraft(sheet) expect(useReportStore.getState().report).toBe(before) }) it('createReportStore accepts another persistence adapter', () => { const saved: unknown[] = [] const store = createReportStore( { loadText: () => null, save: (r) => saved.push(r) > 0 }, { loadText: () => null, save: () => true }, ) store.getState().initReport(draft(), sheet.sheet.ref, sheet) expect(saved.at(-1)).toMatchObject({ version: 3 }) }) }) describe('store edge cases', () => { it('identity setters are no-ops without a report', () => { const s = useReportStore.getState() s.setPractitioner({ name: 'X' }) s.setAnimal({ speciesId: 'equine', name: 'X' }) s.setOwner({ name: 'X' }) expect(useReportStore.getState().report).toBeNull() }) it('restoreDraft with no draft leaves the store empty', () => { useReportStore.getState().restoreDraft(sheet) expect(useReportStore.getState().report).toBeNull() }) }) describe('archive of an imported Step 6 PDF', () => { const OTHER_SHA = 'b'.repeat(64) it('hydrateImport keeps the archive and mirrors it under osteo:archive', () => { const report = minimalReport(sheet) const archive = archiveEnvelope(sheet, report) useReportStore.getState().hydrateImport({ report, archive }, sheet) expect(useReportStore.getState().archive).toEqual(archive) expect(JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!).report.id).toBe( report.id, ) expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).id).toBe(report.id) }) it('the archive is written at the session edges only, never on an edit', () => { const archiveSaves: unknown[] = [] const store = createReportStore( { loadText: () => null, save: () => true }, { loadText: () => null, save: (a) => archiveSaves.push(a) > 0 }, ) const report = minimalReport(sheet) const archive = archiveEnvelope(sheet, report) store.getState().hydrateImport({ report, archive }, sheet) expect(archiveSaves).toEqual([archive]) store.getState().setConclusion('edited') store.getState().addObservation() store.getState().setRecommendations('again') expect(archiveSaves).toHaveLength(1) expect(store.getState().report?.conclusion).toBe('edited') store.getState().reset() expect(archiveSaves).toEqual([archive, null]) }) it('restoreDraft brings the archive back with the draft', () => { const report = minimalReport(sheet, { conclusion: 'kept' }) const archive = archiveEnvelope(sheet, report) useReportStore.getState().hydrateImport({ report, archive }, sheet) // Emptying the state clears the draft mirror, not the archive mirror. useReportStore.setState({ report: null, archive: null }) expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull() expect(sessionStorage.getItem(ARCHIVE_KEY)).not.toBeNull() sessionStorage.setItem(DRAFT_KEY, JSON.stringify(report)) const outcome = useReportStore.getState().restoreDraft(sheet) expect(outcome).toMatchObject({ kind: 'restored', rebase: { rebased: false }, }) expect(useReportStore.getState().report?.conclusion).toBe('kept') expect(useReportStore.getState().archive).toEqual(archive) }) it.each([ [ 'initReport', () => useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet), ], [ 'hydrateImport without an archive', () => useReportStore .getState() .hydrateImport({ report: minimalReport(sheet), archive: null }, sheet), ], ['reset', () => useReportStore.getState().reset()], ])('%s clears the archive and removes its mirror', (_name, act) => { const report = minimalReport(sheet) useReportStore .getState() .hydrateImport({ report, archive: archiveEnvelope(sheet, report) }, sheet) act() expect(useReportStore.getState().archive).toBeNull() expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull() }) it('restoreDraft rebases a draft written on another revision of the sheet, labels from the archived snapshot', () => { const stale = minimalReport(sheet, { sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA }, observations: [ { id: 'o-stale', zones: [ { annotationId: 'point-gone', viewId: 'main' }, { annotationId: 'hip', viewId: 'main', side: 'left' }, ], findings: [], freeTextFindings: [], comment: '', }, ], }) const archive = archiveEnvelope(sheet, stale) archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA archive.sheetSnapshot.document.annotations.push({ ...sheet.annotation('hip')!, id: 'point-gone', name: { fr: 'Point disparu', en: 'Gone point' }, } as Annotation) sessionStorage.setItem(DRAFT_KEY, JSON.stringify(stale)) sessionStorage.setItem(ARCHIVE_KEY, JSON.stringify(archive)) const outcome = useReportStore.getState().restoreDraft(sheet) expect(outcome).toMatchObject({ kind: 'restored', rebase: { rebased: true, unresolvedZones: 1, unresolvedFindings: 0 }, }) const restored = useReportStore.getState().report! expect(restored.sheet).toEqual(sheet.sheet.ref) expect(restored.observations[0]!.zones[0]).toMatchObject({ unresolved: true, labelFrSnapshot: 'Point disparu', }) expect(restored.observations[0]!.zones[1]!.unresolved).toBeUndefined() expect(useReportStore.getState().archive).toEqual(archive) // The mirror now holds the rebased draft. expect( JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).sheet.documentSha256, ).toBe(sheet.sheet.ref.documentSha256) }) it('ignores a corrupt or foreign osteo:archive', () => { sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet))) sessionStorage.setItem(ARCHIVE_KEY, '{not json') useReportStore.getState().restoreDraft(sheet) expect(useReportStore.getState().report).not.toBeNull() expect(useReportStore.getState().archive).toBeNull() useReportStore.setState({ report: null }) sessionStorage.setItem(ARCHIVE_KEY, JSON.stringify({ hello: 'world' })) useReportStore.getState().restoreDraft(sheet) expect(useReportStore.getState().archive).toBeNull() }) })