feat(app): R2 switch — the application runs its domain rules in the Rust core

Consumers now fed by the core (crates/core through @faunosteo/core-wasm):
- the sheet: the bundled payload is parsed and indexed by the core
  (SheetHandle, SheetIndexData); SheetIndex reads precomputed tables only;
- the store: new report, add / remove / move observation, draft restore
  (v2 migration + rebase) through the core, actions answering { ok };
- the editor click chain (zone.click), laterality and vertebra pickers
  (zone.add_sides, vertebra.initial / sync / select), the findings picker
  (finding.toggle by clicked leaf position), zone removal;
- the import: engine byte scan (TypeScript until R4), then the core's
  layered reading and rebase in one call; the export: the core builds the
  sheet snapshot, the frozen TypeScript engine writes the PDF (R4).
Lazy core: Home and the new-report form read the sheet availability from
the bundle and load the module on import / submit only; the auth shell
never references it. Degraded states (core_unavailable, invalid_sheet)
show the validated notice with a retry and never redirect or touch the
draft; an unreadable draft or archive is set aside under
osteo:quarantine:* (only content kinds; a failed write keeps it in place
and the editor stays), a rebase that flags items keeps the raw pre-rebase
draft. Four strings, wording validated by the owner.
Deleted: services/zoneInteraction.ts and its suite (13 cases ported to
cargo), the TypeScript Finding builder and vertebra selection rules of the
pickers, store rules, persistence parsing, hydrateReport. ESLint forbids
@faunosteo/domain in apps/app/src; the report:compare CLI keeps the frozen
domain until R4 (scripts/compare/sheet.ts). App suite 313/313 on the real
core (24 new tests: quarantine, degraded editor, core failures, N-1
reader); step6 goldens and the frozen envelopes unchanged.
This commit is contained in:
bchanot committed 2026-10-14 00:41:34 +02:00
1 parent 794dfd9d0b
commit 74fcb37564
65 files changed
+2227 -1678

No files matched your search

@@ -7,7 +7,9 @@
* must parse with the frozen N-1 reader and be deep-equal to the frozen
* envelope; only the key order may differ (D-R11). `MAKE_R2_FREEZE=1`
* writes the files: never once the switch has landed without an owner
* decision.
* decision. Since R2 the golden reports are read and the snapshot built by
* the Rust core: the attachment differs from the frozen one by key order at
* most (the deep-equality below ignores it).
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
@@ -19,7 +21,7 @@ import {
} from '@faunosteo/core-wasm/n-1'
import { exportReportToPdf } from '@/pdf/export'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import { bundledMigrationMap, loadTestSheet } from '../helpers/sheet'
import { FIXTURES_DIR, ONE_PX_PNG } from '../helpers/goldens'
import {
buildGoldenReports,
@@ -75,7 +77,7 @@ describe.each(GOLDEN_REPORTS)('archive envelope of %s', (name) => {
const data: unknown = JSON.parse(text)
expect(data).toEqual(JSON.parse(readFileSync(file, 'utf8')))
expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true)
const outcome = readArchiveDocument(data, sheet.sheet.migrationMap)
const outcome = readArchiveDocument(data, await bundledMigrationMap())
expect(outcome.origin).toBe('envelope_v1')
expect(outcome.archive).not.toBeNull()
expect(outcome.snapshotRejected).toBeUndefined()
@@ -9,7 +9,7 @@ import {
} from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Finding } from '@faunosteo/domain'
import type { Finding, LateralSide } from '@faunosteo/core-wasm/types'
import FindingsTreePicker from '@/components/observation/FindingsTreePicker'
import { useLocaleStore } from '@/state/localeStore'
import type { SheetIndex } from '@/services/sheetIndex'
@@ -22,18 +22,51 @@ beforeAll(async () => {
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
/**
* The picker reports the clicked leaf; the core builds or removes the finding
* (R2), as ObservationCard wires it. `onChange` receives the observation's
* findings after the toggle, which is what the picker handed out before R2.
*/
function CorePicker({
side,
selected,
onChange,
}: {
side?: LateralSide
selected: Finding[]
onChange: (next: Finding[]) => void
}) {
return (
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
side={side}
selected={selected}
onToggle={(path, leafPosition) => {
const out = sheet.ops.toggleFinding({
observation: {
id: 'obs',
zones: [],
findings: selected,
freeTextFindings: [],
comment: '',
},
findingZoneId: 'hip',
path,
leafPosition,
...(side ? { side } : {}),
})
if (!out.ok) throw new Error(out.kind)
onChange(out.value.findings)
}}
/>
)
}
describe('FindingsTreePicker on a sheet finding zone', () => {
it('drills down the hip zone and selects a leaf as a v3 finding with snapshots and side', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
side="left"
selected={[]}
onChange={onChange}
/>,
)
render(<CorePicker side="left" selected={[]} onChange={onChange} />)
expect(screen.getByText('Hanche (coxo-fémorale)')).toBeInTheDocument()
await user.click(
screen.getByRole('button', {
@@ -72,13 +105,7 @@ describe('FindingsTreePicker on a sheet finding zone', () => {
},
]
const onChange = vi.fn()
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
selected={selected}
onChange={onChange}
/>,
)
render(<CorePicker selected={selected} onChange={onChange} />)
expect(screen.getByLabelText('1 finding selected')).toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: 'Open Osteopathic dysfunctions' }),
@@ -113,13 +140,7 @@ describe('FindingsTreePicker on a sheet finding zone', () => {
it('flags a vet-referral leaf and omits the key on other leaves', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
selected={[]}
onChange={onChange}
/>,
)
render(<CorePicker selected={[]} onChange={onChange} />)
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Dysfonctions ostéopathiques',
@@ -162,14 +183,7 @@ describe('FindingsTreePicker on a sheet finding zone', () => {
]
function renderPicker(selected: Finding[]) {
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
side="left"
selected={selected}
onChange={vi.fn()}
/>,
)
render(<CorePicker side="left" selected={selected} onChange={vi.fn()} />)
}
it('counts selected findings per level, none on a clean sibling', async () => {
@@ -223,13 +237,7 @@ describe('FindingsTreePicker on a sheet finding zone', () => {
})
it('the findings list carries no permanent compositing hint (text stays crisp)', () => {
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
selected={[]}
onChange={() => {}}
/>,
)
render(<CorePicker selected={[]} onChange={() => {}} />)
const ul = document.querySelector('ul') as HTMLElement
expect(ul.getAttribute('style') ?? '').not.toContain('will-change')
expect(ul.style.willChange).toBe('')
+8 -10
View File
@@ -4,15 +4,11 @@
* use, exported to a v3 PDF and read back without loss.
*/
import { describe, it, expect, vi, beforeAll } from 'vitest'
import {
readReportDocument,
type Finding,
type Report,
} from '@faunosteo/domain'
import type { Finding, Report } from '@faunosteo/core-wasm/types'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf } from '@/pdf/import'
import { importAttachment, importReportFromPdf } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import { findingNodeAt, loadTestSheet } from '../helpers/sheet'
import {
leavesAsV2Report,
legacyLeaves,
@@ -34,7 +30,8 @@ beforeAll(async () => {
sheet = await loadTestSheet()
const leaves = legacyLeaves(loadLegacyBaseline())
const v2 = leavesAsV2Report(leaves)
const outcome = readReportDocument(v2, sheet.sheet.migrationMap)
// Read as the application reads an attachment: the core migrates the v2 report.
const outcome = importAttachment(v2, sheet).read
report = outcome.report
findings = report.observations.flatMap((o) => o.findings)
unresolvedFindings = outcome.unresolvedFindings
@@ -46,8 +43,9 @@ describe('the 612 legacy leaves in the application', () => {
expect(findings).toHaveLength(612)
expect(unresolvedFindings).toBe(29)
for (const f of findings) {
const node = sheet.nodeAt(f.findingZoneId, f.path)
const node = findingNodeAt(sheet, f.findingZoneId, f.path)
const where = `${f.findingZoneId}/${f.path.join('/')}`
expect(sheet.hasNode(f.findingZoneId, f.path), where).toBe(!f.unresolved)
if (f.unresolved) expect(node, where).toBeUndefined()
else {
expect(node, where).toBeDefined()
@@ -60,7 +58,7 @@ describe('the 612 legacy leaves in the application', () => {
const { pdf: bytes } = await exportReportToPdf(report, sheet, {
locale: 'fr',
})
const back = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
const { read: back } = await importReportFromPdf(bytes, sheet)
expect(back.migrated).toBe(false)
expect(back.origin).toBe('envelope_v1')
expect(back.archive).not.toBeNull()
+192
View File
@@ -0,0 +1,192 @@
/**
* The N-1 reader test (RUST_ARCHITECTURE_REVIEW III.3 rule 7, VI.3 R2 row):
* every draft and archive the application writes through the Rust core must
* stay readable by the build before R2, whose Zod schemas and readers are
* frozen in `@faunosteo/core-wasm/n-1`. A rollback to that build then finds
* every session the R2 build left behind (key order may differ: D-R11).
*/
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
readArchiveDocument,
readReportDocument,
ReportArchiveEnvelopeSchema,
ReportSchema,
} from '@faunosteo/core-wasm/n-1'
import { readAttachmentBytes } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importAttachment } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY, DRAFT_KEY } from '@/state/persistence'
import type { SheetIndex } from '@/services/sheetIndex'
import { FIXTURES_DIR, ONE_PX_PNG } from '../helpers/goldens'
import {
archiveEnvelope,
bundledMigrationMap,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
vi.mock('@/pdf/browserRasterizer', () => ({
browserRasterizer: vi.fn(async () => ONE_PX_PNG),
}))
vi.mock('@/pdf/branding', async () => {
const { brandingOf } = await import('../helpers/goldens')
return { loadBranding: vi.fn(() => brandingOf('nologos')) }
})
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => vi.restoreAllMocks())
beforeEach(() => {
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
})
const fixture = (name: string): unknown =>
JSON.parse(readFileSync(resolve(FIXTURES_DIR, name), 'utf8'))
/** The draft mirror as the previous build reads it on a rollback. */
async function expectN1ReadsTheDraft(): Promise<void> {
const text = sessionStorage.getItem(DRAFT_KEY)
expect(text).not.toBeNull()
const data: unknown = JSON.parse(text!)
expect(ReportSchema.safeParse(data).success).toBe(true)
const read = readReportDocument(data, await bundledMigrationMap())
expect(read.report).toEqual(useReportStore.getState().report)
}
describe('drafts written through the core', () => {
it('a new report', async () => {
useReportStore.getState().initReport(
{
date: '2026-10-14',
practitioner: { name: 'Dr. Dupont', cabinet: 'Équi' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
nextAppointment: { kind: 'period', text: 'dans 3 semaines' },
},
sheet.sheet.ref,
)
await expectN1ReadsTheDraft()
})
it('after the editor reducers (zones, sides, vertebrae, findings)', async () => {
useReportStore.getState().initReport(
{
date: '2026-10-14',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
},
sheet.sheet.ref,
)
const apply = (obs: ReturnType<typeof current>) =>
useReportStore.getState().updateObservation(0, obs)
const current = () => useReportStore.getState().report!.observations[0]!
const click = sheet.ops.zoneClick(current(), 'c7-t1')
if (!click.ok || !click.value.observation) throw new Error('zone click')
apply(click.value.observation)
const sides = sheet.ops.addSides(current(), 'hip', ['left', 'right'])
if (!sides.ok) throw new Error('add sides')
apply(sides.value)
const spine = sheet.ops.zoneClick(current(), 'cervical')
if (!spine.ok || !spine.value.observation) throw new Error('spine click')
apply(spine.value.observation)
const synced = sheet.ops.syncVertebrae(
current(),
[
{ region: 'C', index: 3 },
{ region: 'L', index: 2 },
],
'main',
)
if (!synced.ok) throw new Error('vertebrae')
apply(synced.value)
const articular = sheet
.findingZone('hip')!
.categories.find((c) => c.id === 'hip-dysfunctions')!
.children.find((n) => n.id === 'articular')!
const finding = sheet.ops.toggleFinding({
observation: current(),
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'hypermobility'],
leafPosition: articular.children.findIndex(
(n) => n.id === 'hypermobility',
),
side: 'left',
})
if (!finding.ok) throw new Error(finding.kind)
apply(finding.value)
expect(current().zones.length).toBeGreaterThanOrEqual(4)
expect(current().findings).toHaveLength(1)
await expectN1ReadsTheDraft()
})
it('after the restore of a v2 draft left by the previous version', async () => {
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(fixture('report-v2.full.json')),
)
expect(useReportStore.getState().restoreDraft(sheet)).toMatchObject({
kind: 'restored',
})
await expectN1ReadsTheDraft()
})
it('after the import of an archive (draft and archive mirror)', async () => {
const report = minimalReport(sheet, { conclusion: 'imported' })
const { read, rebase } = importAttachment(
archiveEnvelope(sheet, report),
sheet,
)
useReportStore
.getState()
.hydrateImport({ report: rebase.report, archive: read.archive })
await expectN1ReadsTheDraft()
const archive: unknown = JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!)
expect(ReportArchiveEnvelopeSchema.safeParse(archive).success).toBe(true)
})
})
describe('archives exported from core-built reports', () => {
it.each([['report-v3.demo.json'], ['report-v2.full.json']])(
'the attachment of %s reads back through the N-1 reader',
async (name) => {
const { report } = importAttachment(fixture(name), sheet).read
const { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' })
const data: unknown = JSON.parse(
new TextDecoder().decode(await readAttachmentBytes(pdf)),
)
expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true)
const outcome = readArchiveDocument(data, await bundledMigrationMap())
expect(outcome.origin).toBe('envelope_v1')
expect(outcome.archive).not.toBeNull()
expect(outcome.snapshotRejected).toBeUndefined()
expect(outcome.report).toEqual(report)
},
30_000,
)
})
+49 -28
View File
@@ -15,23 +15,24 @@ import {
} from 'vitest'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
buildSheetIndex,
buildSheetSnapshot,
ReportSchema,
type Branding,
type FindingCategory,
type FindingNode,
type Report,
type ReportArchiveEnvelope,
} from '@faunosteo/domain'
import { exportFromEnvelope, readReportArchive } from '@faunosteo/pdf'
import type {
Branding,
LocalizedText,
Report,
} from '@faunosteo/core-wasm/types'
import { exportFromEnvelope } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importAttachment, importReportFromPdf } from '@/pdf/import'
import { browserRasterizer } from '@/pdf/browserRasterizer'
import { loadBranding } from '@/pdf/branding'
import type { LoadedSheet } from '@/sheets/provider'
import type { BundledSheetData } from '@/sheets/provider'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import {
bundledSheet,
loadTestSheet,
sheetFromBundle,
sheetSnapshot,
} from '../helpers/sheet'
import {
FIXTURES_DIR,
ONE_PX_PNG,
@@ -63,11 +64,12 @@ let demo: Report
beforeAll(async () => {
sheet = await loadTestSheet()
demo = ReportSchema.parse(
demo = importAttachment(
JSON.parse(
readFileSync(resolve(FIXTURES_DIR, 'report-v3.demo.json'), 'utf8'),
),
)
sheet,
).read.report
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterEach(() => {
@@ -107,10 +109,13 @@ function appExport(index: SheetIndex): Promise<Facts & { pdf: Uint8Array }> {
return recorded(() => exportReportToPdf(demo, index, { locale: 'fr' }))
}
async function archiveOf(pdf: Uint8Array): Promise<ReportArchiveEnvelope> {
const outcome = await readReportArchive(pdf, sheet.sheet.migrationMap)
/** The envelope the app reads back from its own export, as the engine takes it. */
type EngineEnvelope = Parameters<typeof exportFromEnvelope>[0]
async function archiveOf(pdf: Uint8Array): Promise<EngineEnvelope> {
const { read: outcome } = await importReportFromPdf(pdf, sheet)
expect(outcome.origin).toBe('envelope_v1')
return outcome.archive!
return outcome.archive! as EngineEnvelope
}
const REEXPORT = {
@@ -119,26 +124,42 @@ const REEXPORT = {
exportedAt: new Date('2027-01-01T00:00:00.000Z'),
}
function renameNodes(nodes: (FindingCategory | FindingNode)[]): void {
/** A category or node of the bundled payload (authoring form: leaves have no children). */
interface PayloadNode {
name: LocalizedText
children?: PayloadNode[]
}
interface PayloadDocument {
annotations: {
id: string
name: LocalizedText | null
geometry: { type: string; cx?: number } | null
}[]
finding_zones: { name: LocalizedText; categories: PayloadNode[] }[]
}
function renameNodes(nodes: PayloadNode[]): void {
for (const node of nodes) {
node.name = {
fr: `${node.name.fr} (révisé)`,
en: `${node.name.en} (revised)`,
}
renameNodes(node.children)
renameNodes(node.children ?? [])
}
}
/** The catalog after a revision: every label changed, the hip marker moved. */
function revisedSheet(source: LoadedSheet): LoadedSheet {
function revisedSheet(source: BundledSheetData): BundledSheetData {
const next = structuredClone(source)
for (const a of next.document.annotations) {
const document = next.document as PayloadDocument
for (const a of document.annotations) {
if (a.name) {
a.name = { fr: `${a.name.fr} (révisé)`, en: `${a.name.en} (revised)` }
}
if (a.id === 'hip' && a.geometry?.type === 'circle') a.geometry.cx += 100
if (a.id === 'hip' && a.geometry?.type === 'circle') a.geometry.cx! += 100
}
for (const zone of next.document.finding_zones) {
for (const zone of document.finding_zones) {
zone.name = {
fr: `${zone.name.fr} (révisé)`,
en: `${zone.name.en} (revised)`,
@@ -154,14 +175,14 @@ describe('the archive survives its resources', () => {
const archive = await archiveOf(first.pdf)
// The revision is visible through the app path (labels and geometry)...
const revised = buildSheetIndex(revisedSheet(sheet.sheet))
const revised = sheetFromBundle(revisedSheet(await bundledSheet()))
const onRevised = await appExport(revised)
expect(onRevised.texts).not.toEqual(first.texts)
const revisedViews = snapshotViews(
buildSheetSnapshot(revised.sheet, demo),
const revisedViews = snapshotViews(sheetSnapshot(revised, demo), demo)
const archivedViews = snapshotViews(
archive.sheetSnapshot as Parameters<typeof snapshotViews>[0],
demo,
)
const archivedViews = snapshotViews(archive.sheetSnapshot, demo)
expect(revisedViews).not.toEqual(archivedViews)
// ...and absent from a re-export of the envelope alone.
+4 -4
View File
@@ -12,12 +12,12 @@ import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
import type { Report } from '@faunosteo/core-wasm/types'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import type { Locale } from '@/i18n/types'
import { loadTestSheet } from '../helpers/sheet'
import { loadTestSheet, sheetSnapshot } from '../helpers/sheet'
import {
buildGoldenReports,
GOLDEN_REPORTS,
@@ -154,7 +154,7 @@ describe.each(REPORTS)('goldens of %s', (name) => {
// shrinks to the highlighted markers plus the asset's own, and
// `dataAttributes` drops from 2 to 0. Everything else must match.
it('highlighted views: same facts but titles and data attributes', () => {
const snapshot = buildSheetSnapshot(sheet.sheet, reports[name])
const snapshot = sheetSnapshot(sheet, reports[name])
const actual = snapshotViews(snapshot, reports[name])
const expected = readGolden<ViewSnapshot[]>(`views.${name}.json`)
const comparable = (v: ViewSnapshot) => ({
@@ -177,7 +177,7 @@ describe.each(REPORTS)('goldens of %s', (name) => {
describe('report-v3.bare.pdf', () => {
it('is the demo report exported bare by Step 5 and imports with no archive', async () => {
const bytes = new Uint8Array(readFileSync(BARE_PDF))
const outcome = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
const { read: outcome } = await importReportFromPdf(bytes, sheet)
expect(outcome.origin).toBe('bare_v3')
expect(outcome.migrated).toBe(false)
expect(outcome.archive).toBeNull()
+1 -1
View File
@@ -25,7 +25,7 @@ async function pdfWithoutAttachment(keywords?: string[]): Promise<Uint8Array> {
}
async function rejectsWith(bytes: Uint8Array, kind: string): Promise<void> {
const promise = importReportFromPdf(bytes, sheet.sheet.migrationMap)
const promise = importReportFromPdf(bytes, sheet)
await expect(promise).rejects.toBeInstanceOf(ImportError)
await expect(promise).rejects.toMatchObject({ kind })
}
+26 -39
View File
@@ -17,18 +17,14 @@ import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import {
buildSheetSnapshot,
type Observation,
type Report,
} from '@faunosteo/domain'
import type { Observation, Report } from '@faunosteo/core-wasm/types'
import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { formatDate } from '@/lib/dates'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
import { loadTestSheet, minimalReport, sheetSnapshot } from '../helpers/sheet'
// The factory runs when the engine first loads the adapter: fixed 1×1 PNG.
vi.mock('@/pdf/browserRasterizer', async () => {
@@ -36,6 +32,14 @@ vi.mock('@/pdf/browserRasterizer', async () => {
return { browserRasterizer: vi.fn(async () => ONE_PX_PNG) }
})
/** The engine's own (Zod-inferred) types of the same JSON contracts. */
type EngineView = Parameters<typeof composeHighlightedViewSvg>
/** The layered reading the application does on import (the core's read part). */
async function readBack(bytes: Uint8Array) {
return (await importReportFromPdf(bytes, sheet)).read
}
/** The static PDF strings now belong to the engine's label set. */
const { fr, en } = defaultPdfLabels
@@ -147,7 +151,7 @@ describe('export on a full v3 report (FR)', () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
for (const locale of ['fr', 'en'] as const) {
const bytes = await exportPdf(report, locale)
const out = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
const out = await readBack(bytes)
expect(out.migrated).toBe(false)
expect(out.origin).toBe('envelope_v1')
expect(out.report).toEqual(report)
@@ -163,7 +167,7 @@ describe('export on a full v3 report (FR)', () => {
// pdf.goldens.test.ts "highlighted views".
it('highlights the observation zones of a view and omits the other markers', () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
const snapshot = buildSheetSnapshot(sheet.sheet, report)
const snapshot = sheetSnapshot(sheet, report) as EngineView[0]
const svg = composeHighlightedViewSvg(snapshot, 'main', fullObservation())
expect(svg).toContain('viewBox="0 0 2073.4 1629.4"')
expect(svg).toContain('fill="#b85a3f"')
@@ -278,7 +282,7 @@ describe('PDF content on a two-observation report', () => {
})
expect(fetchSpy).not.toHaveBeenCalled()
expect(warnings).toEqual([])
const out = await importReportFromPdf(pdf, sheet.sheet.migrationMap)
const out = await readBack(pdf)
const branding = out.archive!.branding
expect(branding.headerLogo?.kind).toBe('png')
expect(branding.footerLogo?.kind).toBe('png')
@@ -321,27 +325,24 @@ describe('attachment rejection', () => {
it('reports no_attachment for a foreign JSON attachment (no version)', async () => {
const bytes = await pdfWith('other.json', { hello: 'world' })
await expect(
importReportFromPdf(bytes, sheet.sheet.migrationMap),
).rejects.toMatchObject({ kind: 'no_attachment' })
await expect(importReportFromPdf(bytes, sheet)).rejects.toMatchObject({
kind: 'no_attachment',
})
})
it('reports no_attachment for a v3 report failing validation', async () => {
const broken: Record<string, unknown> = { ...minimalReport(sheet) }
delete broken.sheet
const bytes = await pdfWith('osteo-report.json', broken)
await expect(
importReportFromPdf(bytes, sheet.sheet.migrationMap),
).rejects.toMatchObject({ kind: 'no_attachment' })
await expect(importReportFromPdf(bytes, sheet)).rejects.toMatchObject({
kind: 'no_attachment',
})
})
})
describe('import of the frozen v2 archive PDFs', () => {
it('migrates the full v2 report: ids, views, paths, severities, unresolved findings', async () => {
const out = await importReportFromPdf(
fixture('report-v2.full.pdf'),
sheet.sheet.migrationMap,
)
const out = await readBack(fixture('report-v2.full.pdf'))
expect(out.migrated).toBe(true)
const { report } = out
expect(report.version).toBe(3)
@@ -379,10 +380,7 @@ describe('import of the frozen v2 archive PDFs', () => {
expect.arrayContaining(['moderate', 'severe']),
)
// Re-export and re-import: stable.
const again = await importReportFromPdf(
await exportPdf(report, 'fr'),
sheet.sheet.migrationMap,
)
const again = await readBack(await exportPdf(report, 'fr'))
expect(again.report).toEqual(report)
expect(again.migrated).toBe(false)
expect(again.origin).toBe('envelope_v1')
@@ -424,10 +422,7 @@ describe('import of the frozen v2 archive PDFs', () => {
'osteo-report.json',
{ mimeType: 'application/json' },
)
const out = await importReportFromPdf(
await doc.save(),
sheet.sheet.migrationMap,
)
const out = await readBack(await doc.save())
const [obs] = out.report.observations
expect(obs!.zones).toEqual([
expect.objectContaining({
@@ -451,18 +446,12 @@ describe('import of the frozen v2 archive PDFs', () => {
expect(out.unresolvedFindings).toBe(1)
expect(out.unresolvedZones).toBe(1)
// The migrated document is a valid v3 document: exporting it again keeps the flags.
const again = await importReportFromPdf(
await exportPdf(out.report, 'en'),
sheet.sheet.migrationMap,
)
const again = await readBack(await exportPdf(out.report, 'en'))
expect(again.report.observations[0]!.findings[0]!.unresolved).toBe(true)
})
it('migrates the minimal v2 report', async () => {
const out = await importReportFromPdf(
fixture('report-v2.minimal.pdf'),
sheet.sheet.migrationMap,
)
const out = await readBack(fixture('report-v2.minimal.pdf'))
expect(out.report.version).toBe(3)
expect(out.report.observations).toEqual([])
expect(out.unresolvedFindings + out.unresolvedZones).toBe(0)
@@ -477,11 +466,9 @@ describe('import of the frozen v2 archive PDFs', () => {
{ mimeType: 'application/json' },
)
await expect(
importReportFromPdf(await doc.save(), sheet.sheet.migrationMap),
importReportFromPdf(await doc.save(), sheet),
).rejects.toMatchObject({ kind: 'incompatible_version', foundVersion: 7 })
const fake = new Uint8Array([37, 80, 68, 70, 45, 49, 46, 52, 10])
await expect(
importReportFromPdf(fake, sheet.sheet.migrationMap),
).rejects.toThrow(ImportError)
await expect(importReportFromPdf(fake, sheet)).rejects.toThrow(ImportError)
})
})
@@ -1,714 +0,0 @@
/**
* R2 freeze of the editor rules (RUST_ARCHITECTURE_REVIEW VI.1, R2 plan §5 oracles b):
* every reducer and click decision of `services/zoneInteraction.ts`, the findings picker's
* `toggleLeaf`, the vertebra picker's toggle / all / none and the store's report rules,
* computed by the TypeScript code on the bundled draft sheet and written once to
* `crates/core/tests/oracles/editor.json`. The Rust port (`crates/core/src/domain/editor`)
* is checked case by case against that file (`crates/core/tests/editor_rules.rs`).
* `MAKE_R2_ORACLES=1` writes the file; otherwise the TypeScript output is asserted equal to
* it. The picker and store closures live inside a component or a store factory: they are
* copied below verbatim from VertebraPicker.tsx, FindingsTreePicker.tsx and reportStore.ts.
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { beforeAll, describe, expect, it } from 'vitest'
import {
REPORT_VERSION,
type Annotation,
type Finding,
type FindingCategory,
type FindingNode,
type LateralSide,
type Observation,
type Report,
type SheetRef,
type Vertebra,
} from '@faunosteo/domain'
import type { SheetIndex } from '@/services/sheetIndex'
import {
addSides,
collectVertebrae,
decideZoneClick,
ensureZone,
refOf,
removeAllSides,
removeZoneAt,
sidesPresent,
syncVertebrae,
toggleZone,
} from '@/services/zoneInteraction'
import {
emptyObservation,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../../..')
const ORACLE = resolve(ROOT, 'crates/core/tests/oracles/editor.json')
const MAKE = process.env.MAKE_R2_ORACLES === '1'
interface Case {
name: string
fn: string
input: unknown
output: unknown
}
let sheet: SheetIndex
const a = (id: string): Annotation => {
const annotation = sheet.annotation(id)
if (!annotation) throw new Error(`no annotation ${id}`)
return annotation
}
/** EditorRoute.onZoneClick, with the follow-up data the pickers read. */
function zoneClick(obs: Observation | null, annotationId: string): unknown {
const annotation = sheet.annotation(annotationId)
const decision = decideZoneClick(annotation, obs ?? undefined)
if (!annotation) return { kind: decision.kind }
switch (decision.kind) {
case 'open_view':
return { kind: decision.kind, viewId: decision.viewId }
case 'ignore':
case 'activate_fallback':
return { kind: decision.kind }
case 'open_vertebra_picker': {
const { observation, index } = ensureZone(obs!, annotation)
const out: Record<string, unknown> = { kind: decision.kind }
if (observation !== obs) out.observation = observation
out.zoneIndex = index
out.vertebrae = collectVertebrae(observation, sheet, index)
return out
}
case 'open_laterality_picker':
return {
kind: decision.kind,
sidesPresent: sidesPresent(obs!, refOf(annotation)),
}
case 'remove_both_sides':
return {
kind: decision.kind,
observation: removeAllSides(obs!, refOf(annotation)),
}
case 'toggle':
return { kind: decision.kind, observation: toggleZone(obs!, annotation) }
}
}
// --- FindingsTreePicker.tsx (verbatim) ---------------------------------------
type TreeNode = FindingCategory | FindingNode
function samePath(x: readonly string[], y: readonly string[]): boolean {
return x.length === y.length && x.every((seg, i) => seg === y[i])
}
function findNode(
categories: readonly FindingCategory[],
path: readonly string[],
): TreeNode | undefined {
let nodes: readonly TreeNode[] = categories
let node: TreeNode | undefined
for (const segment of path) {
node = nodes.find((n) => n.id === segment)
if (!node) return undefined
nodes = node.children
}
return node
}
/** The picker on `findingZoneId`, its `toggleLeaf` on the leaf at `leafPosition`, then the card's onChange. */
function toggleFinding(
obs: Observation,
findingZoneId: string,
path: string[],
leafPosition: number,
side: LateralSide | undefined,
): Observation {
const zone = sheet.findingZone(findingZoneId)!
const parentPath = path.slice(0, -1)
const currentNodes =
parentPath.length === 0
? zone.categories
: (findNode(zone.categories, parentPath)?.children ?? [])
const leaf: TreeNode = currentNodes[leafPosition]!
const selected = obs.findings
let result = obs
const onChange = (next: Finding[]) => {
result = { ...obs, findings: next }
}
const matches = (f: Finding) => f.findingZoneId === zone.id && f.side === side
const isLeafSelected = (leafPath: string[]) =>
selected.some((f) => matches(f) && samePath(f.path, leafPath))
function toggleLeaf(leafPath: string[], leaf: TreeNode) {
if (isLeafSelected(leafPath)) {
onChange(
selected.filter((f) => !(matches(f) && samePath(f.path, leafPath))),
)
return
}
const next: Finding = {
findingZoneId: zone.id,
path: leafPath,
labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name.en,
}
if ('requires_vet_referral' in leaf && leaf.requires_vet_referral)
next.requiresVetReferral = true
if (side) next.side = side
onChange([...selected, next])
}
toggleLeaf(path, leaf)
return result
}
// --- VertebraPicker.tsx (verbatim closures, `selected` = `cur`) ---------------
type VertebraAction =
| { kind: 'toggle'; region: string; index: number }
| { kind: 'all'; region: string; count: number }
| { kind: 'none'; region: string }
const sameVertebra = (v: Vertebra, r: string, i: number) =>
v.region === r && v.index === i
function selectVertebrae(cur: Vertebra[], action: VertebraAction): Vertebra[] {
const has = (r: string, i: number) => cur.some((v) => sameVertebra(v, r, i))
switch (action.kind) {
case 'toggle': {
const { region: r, index: i } = action
return has(r, i)
? cur.filter((v) => !sameVertebra(v, r, i))
: [...cur, { region: r, index: i }]
}
case 'all':
return [
...cur.filter((v) => v.region !== action.region),
...Array.from({ length: action.count }, (_, k) => ({
region: action.region,
index: k + 1,
})),
]
case 'none':
return cur.filter((v) => v.region !== action.region)
}
}
// --- reportStore.ts (verbatim expressions, ids and time injected) -------------
type NewReportDraft = Omit<
Report,
'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'
>
function newReport(
draft: NewReportDraft,
sheetRef: SheetRef,
id: string,
createdAt: string,
observationId: string,
): Report {
return {
...draft,
version: REPORT_VERSION,
id,
createdAt,
sheet: sheetRef,
observations:
draft.observations.length === 0
? [emptyObservation(observationId)]
: draft.observations,
localAnnotations: [],
}
}
function swapped(list: Observation[], i: number, j: number): Observation[] {
const next = [...list]
;[next[i], next[j]] = [next[j]!, next[i]!]
return next
}
function moveObservation(r: Report, index: number, direction: 'up' | 'down') {
if (direction === 'up') {
return index <= 0
? r
: { ...r, observations: swapped(r.observations, index - 1, index) }
}
return index >= r.observations.length - 1
? r
: { ...r, observations: swapped(r.observations, index, index + 1) }
}
// --- fixtures -----------------------------------------------------------------
const C7T1 = ['c7-t1-dysfunctions', 'segmental', 'restriction-flexion']
const HIP = ['hip-dysfunctions', 'articular', 'restriction-flexion']
const VET = ['frontal-consultation-reasons', 'head-rubbing']
function obsWith(
zones: Observation['zones'],
findings: Finding[] = [],
): Observation {
return { ...emptyObservation(), zones, findings }
}
function zoneCases(): Case[] {
const empty = emptyObservation()
const withC7 = toggleZone(empty, a('c7-t1'))
const left = addSides(empty, a('hip'), ['left'])
const both = addSides(left, a('hip'), ['right'])
const spines = obsWith([
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'T', index: 2 }],
},
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
],
},
{ annotationId: 'c7-t1', viewId: 'main' },
])
const click = (
name: string,
observation: Observation | null,
annotationId: string,
): Case => ({
name,
fn: 'zone_click',
input: { observation, annotationId },
output: zoneClick(observation, annotationId),
})
return [
click('click plain zone adds it', empty, 'c7-t1'),
click('click plain zone removes it', withC7, 'c7-t1'),
click(
'click bilateral zone without side opens the side picker',
empty,
'hip',
),
click(
'click bilateral zone with one side opens the side picker',
left,
'hip',
),
click('click bilateral zone with both sides removes them', both, 'hip'),
click(
'click spine zone absent adds it and opens the picker',
empty,
'cervical',
),
click(
'click spine zone present opens the picker on it',
spines,
'cervical',
),
click(
'click detail trigger with an observation opens the view',
empty,
'head-trigger',
),
click(
'click detail trigger without an observation opens the view',
null,
'head-trigger',
),
click('click unknown annotation is ignored', empty, 'no-such-annotation'),
click('click without an active observation activates one', null, 'c7-t1'),
click('click head view zone toggles it', empty, 'atm'),
]
}
function sideAndIndexCases(): Case[] {
const empty = emptyObservation()
const left = addSides(empty, a('hip'), ['left'])
const withFinding = {
...toggleZone(empty, a('c7-t1')),
findings: [
{
findingZoneId: 'c7-t1',
path: C7T1,
labelFrSnapshot: 'F',
labelEnSnapshot: 'F',
},
],
}
const sides = (
name: string,
observation: Observation,
id: string,
s: LateralSide[],
): Case => ({
name,
fn: 'add_sides',
input: { observation, annotationId: id, sides: s },
output: addSides(observation, a(id), s),
})
const removeAt = (
name: string,
observation: Observation,
index: number,
): Case => ({
name,
fn: 'remove_zone_at',
input: { observation, index },
output: removeZoneAt(observation, index),
})
return [
sides('add left side', empty, 'hip', ['left']),
sides('add both sides to left', left, 'hip', ['left', 'right']),
sides('add an existing side changes nothing', left, 'hip', ['left']),
sides(
'add a side to a detail trigger records no label',
empty,
'head-trigger',
['left'],
),
removeAt('remove zone keeps findings', withFinding, 0),
removeAt('remove zone outside the list changes nothing', withFinding, 5),
]
}
function vertebraCases(): Case[] {
const initial = (
name: string,
observation: Observation,
zoneIndex: number,
): Case => ({
name,
fn: 'vertebra_initial',
input: { observation, zoneIndex },
output: collectVertebrae(observation, sheet, zoneIndex),
})
const sync = (
name: string,
observation: Observation,
selection: Vertebra[],
viewId: string,
): Case => ({
name,
fn: 'sync_vertebrae',
input: { observation, selection, viewId },
output: syncVertebrae(observation, selection, sheet, viewId),
})
const spines = obsWith([
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'T', index: 2 }],
},
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
],
},
{
annotationId: 'c7-t1',
viewId: 'main',
vertebrae: [{ region: 'C', index: 9 }],
},
])
const collision = obsWith([
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [{ region: 'C1', index: 1 }],
},
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'C', index: 11 }],
},
])
const cervical = ensureZone(emptyObservation(), a('cervical')).observation
const twoCervical = obsWith([
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [{ region: 'C', index: 1 }],
},
{
annotationId: 'cervical',
viewId: 'head',
vertebrae: [{ region: 'C', index: 5 }],
},
])
const cervicalThoracic = obsWith([
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [{ region: 'C', index: 1 }],
},
{ annotationId: 'c7-t1', viewId: 'main' },
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'T', index: 1 }],
},
])
return [
initial(
'initial selection, priority zone first, non-spine zone ignored',
spines,
1,
),
initial('initial selection keys on region + index text', collision, 0),
initial('initial selection with an index outside the list', spines, 9),
sync(
'sync spawns zones for new regions and prunes the emptied one',
cervical,
[
{ region: 'L', index: 3 },
{ region: 'L', index: 4 },
{ region: 'Cd', index: 20 },
],
'main',
),
sync(
'sync with an empty selection prunes every spine zone',
spines,
[],
'main',
),
sync(
'sync ignores unknown regions and keeps non-spine zones',
toggleZone(emptyObservation(), a('c7-t1')),
[{ region: 'XX', index: 1 }],
'main',
),
sync(
'sync prunes a second zone of a served region',
twoCervical,
[{ region: 'C', index: 2 }],
'main',
),
sync(
'sync replaces per region and prunes a region left empty',
cervicalThoracic,
[{ region: 'T', index: 3 }],
'main',
),
sync(
'sync falls back to the main view spine annotation',
emptyObservation(),
[{ region: 'C', index: 5 }],
'head',
),
sync(
'sync spawns zones in first-seen region order',
emptyObservation(),
[
{ region: 'Cd', index: 1 },
{ region: 'C', index: 2 },
{ region: 'Cd', index: 3 },
],
'main',
),
]
}
function findingCases(): Case[] {
const empty = emptyObservation()
const toggle = (
name: string,
observation: Observation,
findingZoneId: string,
path: string[],
leafPosition: number,
side?: LateralSide,
): Case => {
const input: Record<string, unknown> = {
observation,
findingZoneId,
path,
leafPosition,
}
if (side) input.side = side
return {
name,
fn: 'toggle_finding',
input,
output: toggleFinding(
observation,
findingZoneId,
path,
leafPosition,
side,
),
}
}
const added = toggleFinding(empty, 'c7-t1', C7T1, 0, undefined)
const hipLeft = toggleFinding(empty, 'hip', HIP, 0, 'left')
const twice = { ...empty, findings: [...added.findings, ...added.findings] }
return [
toggle('toggle adds a leaf', empty, 'c7-t1', C7T1, 0),
toggle('toggle removes a selected leaf', added, 'c7-t1', C7T1, 0),
toggle('toggle adds a leaf with a side', empty, 'hip', HIP, 0, 'left'),
toggle('toggle adds the other side', hipLeft, 'hip', HIP, 0, 'right'),
toggle(
'toggle without side ignores a sided finding',
hipLeft,
'hip',
HIP,
0,
),
toggle('toggle a vet-referral leaf flags it', empty, 'frontal', VET, 1),
toggle('toggle removes every duplicate', twice, 'c7-t1', C7T1, 0),
]
}
function selectCases(): Case[] {
const select = (
name: string,
selection: Vertebra[],
action: VertebraAction,
): Case => ({
name,
fn: 'vertebra_select',
input: { selection, action },
output: selectVertebrae(selection, action),
})
const c1 = { region: 'C', index: 1 }
const t2 = { region: 'T', index: 2 }
const c3 = { region: 'C', index: 3 }
return [
select('select toggles a vertebra on', [], {
kind: 'toggle',
region: 'C',
index: 1,
}),
select('select toggles a vertebra off', [c1, t2], {
kind: 'toggle',
region: 'C',
index: 1,
}),
select('select toggles off every duplicate', [c1, c1], {
kind: 'toggle',
region: 'C',
index: 1,
}),
select('select all replaces the region at the end', [t2, c3], {
kind: 'all',
region: 'C',
count: 7,
}),
select('select none removes the region', [c1, t2, c3], {
kind: 'none',
region: 'C',
}),
]
}
function reportCases(): Case[] {
const ref = sheet.sheet.ref
const draft = (
observations: Observation[],
next = false,
): NewReportDraft => ({
date: '2026-10-14',
practitioner: { name: 'Dr. Dupont', cabinet: 'Cabinet' },
animal: { speciesId: 'equine', name: 'Mistral', age: '9 ans' },
owner: { name: 'Jean Martin' },
observations,
conclusion: '',
recommendations: 'Repos',
...(next
? { nextAppointment: { kind: 'period' as const, text: '3 semaines' } }
: {}),
})
const make = (name: string, d: NewReportDraft): Case => ({
name,
fn: 'new_report',
input: {
draft: d,
sheet: ref,
id: 'report-1',
createdAt: '2026-10-14T08:00:00.000Z',
observationId: 'obs-new',
},
output: newReport(
d,
ref,
'report-1',
'2026-10-14T08:00:00.000Z',
'obs-new',
),
})
const three = minimalReport(sheet, {
observations: [
emptyObservation('o1'),
emptyObservation('o2'),
emptyObservation('o3'),
],
})
const add: Case = {
name: 'add observation appends an empty one',
fn: 'add_observation',
input: { report: three, id: 'o4' },
output: {
...three,
observations: [...three.observations, emptyObservation('o4')],
},
}
const remove = (name: string, index: number): Case => ({
name,
fn: 'remove_observation',
input: { report: three, index },
output: {
...three,
observations: three.observations.filter((_, i) => i !== index),
},
})
const move = (
name: string,
index: number,
direction: 'up' | 'down',
): Case => ({
name,
fn: 'move_observation',
input: { report: three, index, direction },
output: moveObservation(three, index, direction),
})
return [
make('new report starts with one empty observation', draft([])),
make(
'new report keeps the draft observations',
draft([emptyObservation('o9')], true),
),
add,
remove('remove observation by index', 1),
remove('remove observation outside the list', 5),
move('move observation up', 1, 'up'),
move('move the first observation up changes nothing', 0, 'up'),
move('move observation down', 1, 'down'),
move('move the last observation down changes nothing', 2, 'down'),
]
}
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('editor rules characterisation (TypeScript side of the R2 switch)', () => {
it('matches the frozen oracle file', () => {
const cases = [
...zoneCases(),
...sideAndIndexCases(),
...vertebraCases(),
...findingCases(),
...selectCases(),
...reportCases(),
]
const text = `${JSON.stringify({ cases }, null, 2)}\n`
if (MAKE) {
mkdirSync(dirname(ORACLE), { recursive: true })
writeFileSync(ORACLE, text)
}
expect(new Set(cases.map((c) => c.name)).size).toBe(cases.length)
expect(text).toBe(readFileSync(ORACLE, 'utf8'))
})
})
@@ -0,0 +1,118 @@
/**
* R2 plan rev 2 (robustness BLOCKER 1): when the core cannot run, a reload of
* the editor shows the degraded notice with a retry, never redirects to the
* home page, and never reads, rewrites or removes the tab's draft. A sheet
* payload the core refuses (`invalid_sheet`) shows the same notice. Once the
* module loads, the retry restores the draft.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import EditorRoute from '@/app/routes/EditorRoute'
import { setCoreRuntime } from '@/core/runtime'
import { bundledSheetProvider } from '@/sheets/provider'
import { setSheetProvider } from '@/sheets/useSheet'
import { useReportStore } from '@/state/reportStore'
import { DRAFT_KEY } from '@/state/persistence'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { testCoreRuntime, unavailableCoreRuntime } from '../helpers/core'
import { bundledSheet, loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
let draft: string
beforeAll(async () => {
sheet = await loadTestSheet()
draft = JSON.stringify(minimalReport(sheet, { conclusion: 'unsaved work' }))
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
sessionStorage.setItem('osteo:disclaimer-shown', '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
// After the reset (an empty store mirrors no draft): the tab as a reload finds it.
sessionStorage.setItem(DRAFT_KEY, draft)
})
afterEach(async () => {
cleanup()
vi.unstubAllGlobals()
setCoreRuntime(await testCoreRuntime())
setSheetProvider(bundledSheetProvider)
})
function mount() {
return render(
<MemoryRouter initialEntries={['/editor']}>
<Routes>
<Route path="/" element={<p data-testid="home-route" />} />
<Route path="/editor" element={<EditorRoute />} />
</Routes>
</MemoryRouter>,
)
}
async function expectDegraded() {
await screen.findByText(fr['sheet.core_unavailable']!)
expect(
screen.getByRole('button', { name: fr['sheet.core_retry'] }),
).toBeInTheDocument()
expect(screen.queryByTestId('home-route')).toBeNull()
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(useReportStore.getState().report).toBeNull()
}
describe('EditorRoute while the core cannot run', () => {
it('shows the degraded notice, stays on the editor and leaves the draft byte-identical', async () => {
setCoreRuntime(unavailableCoreRuntime())
setSheetProvider(bundledSheetProvider)
mount()
await expectDegraded()
expect(window.alert).not.toHaveBeenCalled()
})
it('restores the draft once a retry finds the module', async () => {
const user = userEvent.setup()
setCoreRuntime(unavailableCoreRuntime())
setSheetProvider(bundledSheetProvider)
mount()
await expectDegraded()
// The module is reachable again (network back, CSP fixed).
setCoreRuntime(await testCoreRuntime())
await user.click(
screen.getByRole('button', { name: fr['sheet.core_retry'] }),
)
await waitFor(() =>
expect(useReportStore.getState().report?.conclusion).toBe('unsaved work'),
)
expect(screen.queryByTestId('home-route')).toBeNull()
})
it('shows the same notice for a sheet payload the core refuses (invalid_sheet)', async () => {
const bundle = await bundledSheet()
setSheetProvider({
getReferenceSheet: async () => ({
...bundle,
document: { schema_version: 2, broken: true },
}),
})
mount()
await expectDegraded()
})
})
@@ -43,7 +43,9 @@ beforeEach(() => {
sessionStorage.setItem('osteo:disclaimer-shown', '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.getState().hydrateReport(minimalReport(sheet))
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null })
exportMock.mockReset()
downloads.length = 0
URL.createObjectURL = vi.fn(() => 'blob:faunosteo-test')
@@ -43,8 +43,8 @@ beforeEach(() => {
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.getState().hydrateReport(
minimalReport(sheet, {
useReportStore.getState().hydrateImport({
report: minimalReport(sheet, {
observations: [
{
id: 'o1',
@@ -55,7 +55,8 @@ beforeEach(() => {
},
],
}),
)
archive: null,
})
})
afterEach(() => {
cleanup()
@@ -1,6 +1,7 @@
/**
* T15 (STEP6 §7, §16): the home route on Step 6 archives, with
* `importReportFromPdf` mocked. Every alert opens with a headline: complete
* T15 (STEP6 §7, §16): the home route on Step 6 archives, with the byte
* scan (`readAttachment`) mocked to hand over the attachment; the layered
* read and the rebase run in the core (R2). Every alert opens with a headline: complete
* restoration or partial recovery. Same sheet: archive kept in the store and
* mirrored, complete + archive_ok. Other sheet: the report is rebased on the
* loaded sheet (unresolved flags, labels from the archived snapshot, sheet
@@ -27,12 +28,11 @@ import {
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type {
Annotation,
ArchiveReadOutcome,
Report,
ReportArchiveEnvelope,
} from '@faunosteo/domain'
} from '@faunosteo/core-wasm/types'
import HomeRoute from '@/app/routes/HomeRoute'
import { ImportError, importReportFromPdf } from '@/pdf/import'
import { ImportError, readAttachment } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY } from '@/state/persistence'
import { useLocaleStore } from '@/state/localeStore'
@@ -42,9 +42,9 @@ import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
importReportFromPdf: vi.fn(),
readAttachment: vi.fn(),
}))
const importMock = vi.mocked(importReportFromPdf)
const readMock = vi.mocked(readAttachment)
let sheet: SheetIndex
@@ -60,7 +60,7 @@ beforeEach(() => {
activeObservationIndex: 0,
})
vi.stubGlobal('alert', vi.fn())
importMock.mockReset()
readMock.mockReset()
})
afterEach(() => {
cleanup()
@@ -69,23 +69,6 @@ afterEach(() => {
const OTHER_SHA = 'b'.repeat(64)
/** An outcome carrying a kept envelope (v3, nothing migrated). */
function archived(
report: Report,
archive: ReportArchiveEnvelope | null,
patch: Partial<ArchiveReadOutcome> = {},
): ArchiveReadOutcome {
return {
report,
origin: 'envelope_v1',
migrated: false,
unresolvedZones: 0,
unresolvedFindings: 0,
archive,
...patch,
}
}
function reportWithHip(): Report {
return minimalReport(sheet, {
observations: [
@@ -162,15 +145,14 @@ async function mountAndPickPdf(): Promise<void> {
const alertMock = () => vi.mocked(window.alert)
/** The alert split on its blank lines: headline first, then the detail lines. */
const alertLines = () =>
(alertMock().mock.calls[0]![0] as string).split('\n\n')
const alertLines = () => (alertMock().mock.calls[0]![0] as string).split('\n\n')
const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' })
describe('HomeRoute import of a Step 6 archive', () => {
it('same sheet: keeps the archive in the store and its mirror, alerts archive_ok, no rebase', async () => {
const report = reportWithHip()
const archive = archiveEnvelope(sheet, report)
importMock.mockResolvedValue(archived(report, archive))
readMock.mockResolvedValue(archive)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
const state = useReportStore.getState()
@@ -188,7 +170,9 @@ describe('HomeRoute import of a Step 6 archive', () => {
it('other sheet: rebases onto the loaded sheet, labels from the archived snapshot, alert with the count', async () => {
const { report, archive } = staleReportAndArchive()
importMock.mockResolvedValue(archived(report, archive))
// The attachment is the envelope of the stale report (read by the core).
expect(archive.report).toBe(report)
readMock.mockResolvedValue(archive)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
const opened = useReportStore.getState().report!
@@ -221,7 +205,7 @@ describe('HomeRoute import of a Step 6 archive', () => {
})
const archive = archiveEnvelope(sheet, report)
archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA
importMock.mockResolvedValue(archived(report, archive))
readMock.mockResolvedValue(archive)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
const opened = useReportStore.getState().report!
@@ -237,9 +221,10 @@ describe('HomeRoute import of a Step 6 archive', () => {
it('snapshot rejected: the report opens, the alert names the reason, no archive kept', async () => {
const report = reportWithHip()
importMock.mockResolvedValue(
archived(report, null, { snapshotRejected: 'caps' }),
)
// A label over the 512-character cap: the core drops the snapshot ('caps').
const archive = archiveEnvelope(sheet, report)
archive.sheetSnapshot.document.name.fr = 'x'.repeat(513)
readMock.mockResolvedValue(archive)
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(report)
@@ -256,7 +241,7 @@ describe('HomeRoute import of a Step 6 archive', () => {
})
it('attachment_stripped → its error message, nothing opened', async () => {
importMock.mockRejectedValue(new ImportError('attachment_stripped'))
readMock.mockRejectedValue(new ImportError('attachment_stripped'))
await mountAndPickPdf()
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(
@@ -1,8 +1,10 @@
/**
* Step 6 Phase 0 characterisation of the import flow on the home route, with
* `importReportFromPdf` mocked: the migration alert (degraded headline, then
* the count), the three ImportError kinds plus the generic error mapped to
* the FR messages, and the navigation to /editor on success.
* the two import steps mocked (R2: `readAttachment`, the engine's byte scan,
* then `importAttachment`, the core's layered read and rebase on the loaded
* sheet): the migration alert (degraded headline, then the count), the three
* ImportError kinds plus the generic error mapped to the FR messages, and the
* navigation to /editor on success.
*/
import {
describe,
@@ -21,9 +23,14 @@ import {
waitFor,
} from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { ArchiveReadOutcome } from '@faunosteo/domain'
import type { ArchiveImport } from '@faunosteo/core-wasm/types'
import HomeRoute from '@/app/routes/HomeRoute'
import { ImportError, importReportFromPdf, MAX_PDF_BYTES } from '@/pdf/import'
import {
ImportError,
importAttachment,
MAX_PDF_BYTES,
readAttachment,
} from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
@@ -32,9 +39,12 @@ import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
importReportFromPdf: vi.fn(),
readAttachment: vi.fn(),
importAttachment: vi.fn(),
}))
const importMock = vi.mocked(importReportFromPdf)
const readMock = vi.mocked(readAttachment)
const importMock = vi.mocked(importAttachment)
const ATTACHMENT = { version: 3 }
let sheet: SheetIndex
@@ -49,6 +59,8 @@ beforeEach(() => {
activeObservationIndex: 0,
})
vi.stubGlobal('alert', vi.fn())
readMock.mockReset()
readMock.mockResolvedValue(ATTACHMENT)
importMock.mockReset()
})
afterEach(() => {
@@ -56,19 +68,28 @@ afterEach(() => {
vi.unstubAllGlobals()
})
/** The outcome shape importReportFromPdf resolves with (bare report, no archive). */
/** What the import resolves with: the read (bare report, no archive) and no rebase. */
function outcome(patch: {
migrated: boolean
unresolvedZones?: number
unresolvedFindings?: number
}): ArchiveReadOutcome {
}): ArchiveImport {
const report = minimalReport(sheet)
return {
report: minimalReport(sheet),
origin: patch.migrated ? 'v2' : 'bare_v3',
archive: null,
unresolvedZones: 0,
unresolvedFindings: 0,
...patch,
read: {
report,
origin: patch.migrated ? 'v2' : 'bare_v3',
archive: null,
unresolvedZones: 0,
unresolvedFindings: 0,
...patch,
},
rebase: {
report,
unresolvedZones: 0,
unresolvedFindings: 0,
rebased: false,
},
}
}
@@ -98,20 +119,22 @@ const alertMock = () => vi.mocked(window.alert)
const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' })
describe('HomeRoute import: success paths', () => {
it('passes the file bytes and the sheet migration map, hydrates, navigates to /editor', async () => {
importMock.mockResolvedValue(outcome({ migrated: false }))
it('passes the file bytes to the scan and the attachment to the loaded sheet, hydrates, navigates to /editor', async () => {
importMock.mockReturnValue(outcome({ migrated: false }))
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(readMock).toHaveBeenCalledTimes(1)
expect(readMock.mock.calls[0]![0]).toBeInstanceOf(Uint8Array)
expect(importMock).toHaveBeenCalledTimes(1)
const [bytes, map] = importMock.mock.calls[0]!
expect(bytes).toBeInstanceOf(Uint8Array)
expect(map).toBe(sheet.sheet.migrationMap)
const [attachment, index] = importMock.mock.calls[0]!
expect(attachment).toBe(ATTACHMENT)
expect(index).toBe(sheet)
expect(useReportStore.getState().report?.id).toBe('r1')
expect(alertMock()).not.toHaveBeenCalled()
})
it('alerts "degraded" then the unresolved count (zones + findings) after a lossy migration', async () => {
importMock.mockResolvedValue(
importMock.mockReturnValue(
outcome({ migrated: true, unresolvedZones: 1, unresolvedFindings: 1 }),
)
await mountAndPickPdf()
@@ -120,13 +143,11 @@ describe('HomeRoute import: success paths', () => {
const message = alertMock().mock.calls[0]![0] as string
const [headline, ...lines] = message.split('\n\n')
expect(headline).toBe(fr['home.import.degraded'])
expect(lines).toEqual([
fr['home.import.migrated']!.replace('{count}', '2'),
])
expect(lines).toEqual([fr['home.import.migrated']!.replace('{count}', '2')])
})
it('stays silent on a migration that lost nothing', async () => {
importMock.mockResolvedValue(outcome({ migrated: true }))
importMock.mockReturnValue(outcome({ migrated: true }))
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(alertMock()).not.toHaveBeenCalled()
@@ -158,7 +179,9 @@ describe('HomeRoute import: error paths', () => {
]
it.each(cases)('%s', async (_label, error, expected) => {
importMock.mockRejectedValue(error)
importMock.mockImplementation(() => {
throw error
})
await mountAndPickPdf()
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(expected)
@@ -177,6 +200,7 @@ describe('HomeRoute import: size gate', () => {
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(fr['home.import.error_invalid_pdf'])
expect(read).not.toHaveBeenCalled()
expect(readMock).not.toHaveBeenCalled()
expect(importMock).not.toHaveBeenCalled()
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
+20 -6
View File
@@ -1,7 +1,9 @@
/**
* The archive check tool (scripts/compare-reports.ts) on the frozen v2 PDF,
* on a synthetic v2 report with removed and unknown items, on a v3 report
* and on a Step 6 envelope (archive header line).
* and on a Step 6 envelope (archive header line). The tool keeps its own
* reading on the frozen TypeScript domain until R4 (`compareSheetIndex`);
* the fixtures it compares are built through the application (the core).
*/
import { describe, it, expect, beforeAll } from 'vitest'
import { readFileSync } from 'node:fs'
@@ -14,6 +16,10 @@ import {
} from '@faunosteo/domain'
import { readAttachedDocument } from '@faunosteo/pdf'
import type { SheetIndex } from '@/services/sheetIndex'
import {
compareSheetIndex,
type CompareSheetIndex,
} from '../../scripts/compare/sheet'
import {
compareReport,
diffLines,
@@ -22,12 +28,19 @@ import {
renderSummary,
UNRESOLVED,
} from '../../scripts/compare/report'
import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
import {
archiveEnvelope,
bundledSheet,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
const OPTS = { locale: 'fr' as const, full: false }
/** The application's sheet (fixture building) and the tool's own reading of it. */
let sheet: SheetIndex
let cli: CompareSheetIndex
function minimalV2(): ReportV2 {
return JSON.parse(
@@ -36,12 +49,13 @@ function minimalV2(): ReportV2 {
}
function compareRaw(raw: unknown, full = false) {
const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, sheet, { ...OPTS, full })
const outcome = readArchiveDocument(raw, cli.sheet.migrationMap)
return compareReport(raw, outcome, cli, { ...OPTS, full })
}
beforeAll(async () => {
sheet = await loadTestSheet()
cli = compareSheetIndex(await bundledSheet())
})
describe('compareReport on the frozen v2 archive PDF', () => {
@@ -210,7 +224,7 @@ describe('compareReport on unresolved items', () => {
describe('diff and arguments', () => {
it('diffs the v3 content of a migrated v2 report and its v3 re-reading', () => {
const v2 = minimalV2()
const migrated = readReportDocument(v2, sheet.sheet.migrationMap).report
const migrated = readReportDocument(v2, cli.sheet.migrationMap).report
const a = compareRaw(v2)
const b = compareRaw(migrated)
expect(diffLines(a.normalized, b.normalized)).toEqual([])
@@ -221,7 +235,7 @@ describe('diff and arguments', () => {
})
it('compares placeholders by default and real texts with --full', () => {
const base = readReportDocument(minimalV2(), sheet.sheet.migrationMap)
const base = readReportDocument(minimalV2(), cli.sheet.migrationMap)
const original = { ...base.report, conclusion: 'original' }
const edited = { ...base.report, conclusion: 'changed' }
expect(
@@ -1,214 +0,0 @@
/**
* Replaces char.clickChain (Step 1) one-to-one: every branch of the legacy
* zone-click chain, now decided by the pure service on the bundled sheet's
* annotations, with outcomes in Report v3 shape.
*/
import { beforeAll, describe, expect, it } from 'vitest'
import type { Annotation } from '@faunosteo/domain'
import type { SheetIndex } from '@/services/sheetIndex'
import {
addSides,
collectVertebrae,
decideZoneClick,
ensureZone,
refOf,
removeAllSides,
removeZoneAt,
sidesPresent,
syncVertebrae,
toggleZone,
} from '@/services/zoneInteraction'
import { emptyObservation, loadTestSheet } from '../helpers/sheet'
let sheet: SheetIndex
const a = (id: string): Annotation => {
const annotation = sheet.annotation(id)
if (!annotation) throw new Error(`no annotation ${id}`)
return annotation
}
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('decideZoneClick', () => {
it('opens the detail view for the trigger, even without an active observation', () => {
expect(decideZoneClick(a('head-trigger'), undefined)).toEqual({
kind: 'open_view',
viewId: 'head',
})
expect(decideZoneClick(a('head-trigger'), emptyObservation())).toEqual({
kind: 'open_view',
viewId: 'head',
})
})
it('only activates a fallback observation when none is active', () => {
expect(decideZoneClick(a('c7-t1'), undefined)).toEqual({
kind: 'activate_fallback',
})
expect(decideZoneClick(undefined, emptyObservation())).toEqual({
kind: 'ignore',
})
})
it('always opens the vertebra picker on a spine zone', () => {
const obs = toggleZone(emptyObservation(), a('cervical'))
expect(decideZoneClick(a('cervical'), emptyObservation())).toEqual({
kind: 'open_vertebra_picker',
})
expect(decideZoneClick(a('cervical'), obs)).toEqual({
kind: 'open_vertebra_picker',
})
})
it('routes bilateral zones through the side picker, or clears both sides', () => {
const hip = a('hip')
expect(decideZoneClick(hip, emptyObservation())).toEqual({
kind: 'open_laterality_picker',
})
const left = addSides(emptyObservation(), hip, ['left'])
expect(decideZoneClick(hip, left)).toEqual({
kind: 'open_laterality_picker',
})
const both = addSides(left, hip, ['right'])
expect(decideZoneClick(hip, both)).toEqual({ kind: 'remove_both_sides' })
})
it('toggles plain zones; the ten bilateral annotations and the 18 others split as the sheet says', () => {
expect(decideZoneClick(a('c7-t1'), emptyObservation())).toEqual({
kind: 'toggle',
})
const observable = sheet.sheet.document.annotations.filter(
(x) => x.kind !== 'detail_trigger',
)
const decisions = observable.map(
(x) => decideZoneClick(x, emptyObservation()).kind,
)
expect(
decisions.filter((k) => k === 'open_laterality_picker'),
).toHaveLength(10)
expect(decisions.filter((k) => k === 'open_vertebra_picker')).toHaveLength(
5,
)
expect(decisions.filter((k) => k === 'toggle')).toHaveLength(12)
})
})
describe('reducers', () => {
it('toggleZone adds a zone with snapshots then removes it', () => {
const added = toggleZone(emptyObservation(), a('c7-t1'))
expect(added.zones).toEqual([
{
annotationId: 'c7-t1',
viewId: 'main',
labelFrSnapshot: 'Charnière C7-T1 (cervico-thoracique)',
labelEnSnapshot: 'C7-T1 junction (cervicothoracic)',
},
])
expect(toggleZone(added, a('c7-t1')).zones).toEqual([])
})
it('ensureZone keeps an existing zone and reports its index', () => {
const base = toggleZone(
toggleZone(emptyObservation(), a('c7-t1')),
a('cervical'),
)
expect(ensureZone(base, a('cervical')).index).toBe(1)
const { observation, index } = ensureZone(emptyObservation(), a('cervical'))
expect(index).toBe(0)
expect(observation.zones[0]!.annotationId).toBe('cervical')
})
it('addSides appends only the missing sides and never removes one', () => {
const hip = a('hip')
const left = addSides(emptyObservation(), hip, ['left'])
expect(sidesPresent(left, refOf(hip))).toEqual(['left'])
const same = addSides(left, hip, ['left'])
expect(same).toBe(left)
const both = addSides(left, hip, ['left', 'right'])
expect(both.zones.map((z) => z.side)).toEqual(['left', 'right'])
expect(removeAllSides(both, refOf(hip)).zones).toEqual([])
})
it('removeZoneAt removes one zone by index and keeps findings (BDR-019 wart kept, D5)', () => {
const obs = {
...toggleZone(emptyObservation(), a('c7-t1')),
findings: [
{
findingZoneId: 'c7-t1',
path: ['c7-t1-dysfunctions', 'segmental', 'fixation'],
labelFrSnapshot: 'F',
labelEnSnapshot: 'F',
},
],
}
const out = removeZoneAt(obs, 0)
expect(out.zones).toEqual([])
expect(out.findings).toHaveLength(1)
})
it('detail-view zones are distinct from main-view zones with the same id', () => {
const atm = a('atm')
const obs = toggleZone(emptyObservation(), atm)
expect(obs.zones[0]).toMatchObject({ annotationId: 'atm', viewId: 'head' })
expect(decideZoneClick(atm, obs)).toEqual({ kind: 'toggle' })
})
})
describe('vertebrae (BDR-019 sync, region codes from the sheet)', () => {
it('collects vertebrae across spine zones, the priority zone first', () => {
const obs = {
...emptyObservation(),
zones: [
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'T', index: 2 }],
},
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
],
},
{ annotationId: 'c7-t1', viewId: 'main' },
],
}
expect(collectVertebrae(obs, sheet, 1)).toEqual([
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
{ region: 'T', index: 2 },
])
})
it('replaces per region, prunes emptied zones and spawns zones for new regions', () => {
const base = ensureZone(emptyObservation(), a('cervical')).observation
const out = syncVertebrae(
base,
[
{ region: 'L', index: 3 },
{ region: 'L', index: 4 },
{ region: 'Cd', index: 20 },
],
sheet,
'main',
)
expect(out.zones.map((z) => z.annotationId)).toEqual(['lumbar', 'caudal'])
expect(out.zones[0]!.vertebrae).toEqual([
{ region: 'L', index: 3 },
{ region: 'L', index: 4 },
])
expect(out.zones[0]!.labelFrSnapshot).toBe('Vertèbres lombaires')
const cleared = syncVertebrae(out, [], sheet, 'main')
expect(cleared.zones).toEqual([])
})
it('keeps non-spine zones untouched and ignores unknown regions', () => {
const base = toggleZone(emptyObservation(), a('c7-t1'))
const out = syncVertebrae(base, [{ region: 'XX', index: 1 }], sheet, 'main')
expect(out.zones).toEqual(base.zones)
})
})
+75 -36
View File
@@ -1,17 +1,23 @@
/**
* Replaces anatomy.horse / char.svgCatalogLink: the bundled reference sheet
* loads, validates, and indexes as the canonical document says.
* loads, validates, and indexes as the canonical document says. Since R2 the
* provider hands the raw payload over and the core parses and indexes it;
* the facts the TypeScript index no longer exposes (annotations per view,
* region by code, spine annotation of a region) are read from the document
* the core parsed.
*/
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { beforeAll, describe, expect, it } from 'vitest'
import type {
Annotation,
FindingCategory,
FindingNode,
} from '@faunosteo/core-wasm/types'
import { bundledSheetProvider } from '@/sheets/provider'
import {
buildSheetIndex,
isObservable,
pickLabel,
type SheetIndex,
} from '@/services/sheetIndex'
import { isObservable, type SheetIndex } from '@/services/sheetIndex'
import { setSheetProvider } from '@/sheets/useSheet'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { loadTestSheet } from '../helpers/sheet'
/** The seed manifest the bundle reads its asset hashes from. */
@@ -25,19 +31,49 @@ beforeAll(async () => {
sheet = await loadTestSheet()
})
/** Annotations drawn on a view, in document order. */
function annotationsOfView(viewId: string): Annotation[] {
return sheet.sheet.document.annotations.filter((a) => a.view_id === viewId)
}
/** The first spine annotation of a region on a view (what the core's rules use). */
function spineAnnotation(code: string, viewId: string) {
return sheet.sheet.document.annotations
.filter(isObservable)
.find((a) => a.view_id === viewId && a.vertebral_region_code === code)
}
/** The name of the category or node at a path, read from the zone's tree. */
function nodeName(zoneId: string, path: string[]): string | undefined {
let nodes: readonly (FindingCategory | FindingNode)[] =
sheet.findingZone(zoneId)?.categories ?? []
let node: FindingCategory | FindingNode | undefined
for (const segment of path) {
node = nodes.find((n) => n.id === segment)
if (!node) return undefined
nodes = node.children
}
return node?.name.fr
}
describe('bundled sheet provider', () => {
it('returns the equine draft with its reference, assets and migration map', async () => {
const loaded = await bundledSheetProvider.getReferenceSheet('equine')
expect(loaded).not.toBeNull()
expect(loaded!.status).toBe('draft')
expect(loaded!.speciesId).toBe('equine')
expect(loaded!.ref.documentSha256).toMatch(/^[0-9a-f]{64}$/)
expect(loaded!.ref.versionId).toBeNull()
expect(loaded!.migrationMap.sheet).toEqual(loaded!.ref)
expect(loaded!.ref.species_id).toBe('equine')
expect(loaded!.ref.document_sha256).toMatch(/^[0-9a-f]{64}$/)
expect(loaded!.ref.version_id).toBeNull()
expect((loaded!.migrationMap as { sheet: unknown }).sheet).toEqual({
sheetId: loaded!.ref.sheet_id,
versionId: loaded!.ref.version_id,
documentSha256: loaded!.ref.document_sha256,
})
expect(Object.keys(loaded!.assets)).toHaveLength(1)
expect(loaded!.assets[loaded!.document.views[0]!.svg_asset_id!]).toContain(
'<svg',
)
const document = loaded!.document as {
views: { svg_asset_id: string | null }[]
}
expect(loaded!.assets[document.views[0]!.svg_asset_id!]).toContain('<svg')
expect(await bundledSheetProvider.getReferenceSheet('canine')).toBeNull()
})
@@ -48,7 +84,8 @@ describe('bundled sheet provider', () => {
svg_asset_id: string
}[]
const horse = manifest[0]!
expect(loaded!.schemaVersion).toBe(2)
expect(loaded!.ref.schema_version).toBe(2)
expect(sheet.sheet.schemaVersion).toBe(2)
expect(Object.keys(loaded!.assetHashes)).toEqual([horse.svg_asset_id])
expect(loaded!.assetHashes[horse.svg_asset_id]).toBe(horse.sha256)
expect(horse.sha256).toMatch(/^[0-9a-f]{64}$/)
@@ -58,7 +95,7 @@ describe('bundled sheet provider', () => {
describe('sheet index', () => {
it('exposes the views, 28 annotations (27 observable), 27 finding zones and 5 regions', () => {
const { document } = sheet.sheet
expect(sheet.mainView.id).toBe('main')
expect(sheet.mainViewId).toBe('main')
expect(sheet.view('head')).toMatchObject({
kind: 'detail',
parent_view_id: 'main',
@@ -66,8 +103,8 @@ describe('sheet index', () => {
})
expect(document.annotations).toHaveLength(28)
expect(document.annotations.filter(isObservable)).toHaveLength(27)
expect(sheet.annotationsOfView('head')).toHaveLength(9)
expect(sheet.annotationsOfView('main')).toHaveLength(19)
expect(annotationsOfView('head')).toHaveLength(9)
expect(annotationsOfView('main')).toHaveLength(19)
expect(document.finding_zones).toHaveLength(27)
expect(sheet.regions().map((r) => r.code)).toEqual([
'C',
@@ -76,7 +113,7 @@ describe('sheet index', () => {
'S',
'Cd',
])
expect(sheet.region('Cd')).toMatchObject({
expect(sheet.regions().find((r) => r.code === 'Cd')).toMatchObject({
count: 18,
count_range: { min: 15, max: 21 },
})
@@ -91,8 +128,8 @@ describe('sheet index', () => {
expect(a.finding_zone_id, a.id).not.toBeNull()
expect(sheet.findingZone(a.finding_zone_id!), a.id).toBeDefined()
}
expect(sheet.spineAnnotation('C', 'main')?.id).toBe('cervical')
expect(sheet.spineAnnotation('C', 'head')).toBeUndefined()
expect(spineAnnotation('C', 'main')?.id).toBe('cervical')
expect(spineAnnotation('C', 'head')).toBeUndefined()
expect(sheet.isSpine('cervical')).toBe(true)
expect(sheet.isSpine('hip')).toBe(false)
expect(sheet.isSpine('head-trigger')).toBe(false)
@@ -101,7 +138,7 @@ describe('sheet index', () => {
it('maps spine annotations to their region codes on the main view', () => {
const codes = ['C', 'T', 'L', 'S', 'Cd']
for (const code of codes) {
const a = sheet.spineAnnotation(code, 'main')
const a = spineAnnotation(code, 'main')
expect(a, code).toBeDefined()
expect(a!.vertebral_region_code).toBe(code)
expect(sheet.isSpine(a!.id)).toBe(true)
@@ -123,27 +160,24 @@ describe('sheet index', () => {
})
it('resolves finding paths and reports absent ones', () => {
expect(
sheet.nodeAt('hip', [
'hip-dysfunctions',
'articular',
'restriction-flexion',
])?.name.fr,
).toBe('Restriction en flexion')
expect(sheet.nodeAt('hip', ['hip-dysfunctions'])?.name.fr).toBe(
const leaf = ['hip-dysfunctions', 'articular', 'restriction-flexion']
expect(sheet.hasNode('hip', leaf)).toBe(true)
expect(nodeName('hip', leaf)).toBe('Restriction en flexion')
expect(sheet.hasNode('hip', ['hip-dysfunctions'])).toBe(true)
expect(nodeName('hip', ['hip-dysfunctions'])).toBe(
'Dysfonctions ostéopathiques',
)
expect(
sheet.nodeAt('cervical', [
sheet.hasNode('cervical', [
'cervical-observations',
'stumbling-proprioceptive',
]),
).toBeUndefined()
expect(sheet.nodeAt('nowhere', ['x'])).toBeUndefined()
expect(sheet.nodeAt('hip', [])).toBeUndefined()
).toBe(false)
expect(sheet.hasNode('nowhere', ['x'])).toBe(false)
expect(sheet.hasNode('hip', [])).toBe(false)
})
it('names annotations and triggers in both locales', () => {
it('names annotations and triggers in both locales', async () => {
expect(pickLabel(sheet.name(sheet.annotation('hip')!), 'fr')).toBe(
'Hanche (coxo-fémorale)',
)
@@ -153,6 +187,11 @@ describe('sheet index', () => {
expect(pickLabel(sheet.name(sheet.annotation('head-trigger')!), 'en')).toBe(
'Head (left lateral view)',
)
expect(buildSheetIndex(sheet.sheet).mainView).toEqual(sheet.mainView)
// A second load of the same payload indexes it the same way.
setSheetProvider(bundledSheetProvider)
const again = await loadTestSheet()
expect(again).not.toBe(sheet)
expect(again.mainViewId).toBe(sheet.mainViewId)
expect(again.sheet.document).toEqual(sheet.sheet.document)
})
})
@@ -0,0 +1,178 @@
/**
* R2 plan rev 2 (robustness 7): a store action whose core call fails changes
* nothing and answers `{ ok: false }`, and the callers stop: the new-report
* page does not open the editor, the home page shows the import error instead
* of opening a report.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import HomeRoute from '@/app/routes/HomeRoute'
import NewReportRoute from '@/app/routes/NewReportRoute'
import { setCoreRuntime } from '@/core/runtime'
import { readAttachment } from '@/pdf/import'
import { bundledSheetProvider } from '@/sheets/provider'
import { setSheetProvider } from '@/sheets/useSheet'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { testCoreRuntime, unavailableCoreRuntime } from '../helpers/core'
import {
emptyObservation,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
readAttachment: vi.fn(),
}))
const readMock = vi.mocked(readAttachment)
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
localStorage.clear()
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
})
afterEach(async () => {
cleanup()
vi.unstubAllGlobals()
setCoreRuntime(await testCoreRuntime())
setSheetProvider(bundledSheetProvider)
})
const draft = () => ({
date: '2026-10-10',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
})
describe('store actions on a failing core', () => {
it('change nothing and answer { ok: false }', () => {
const report = minimalReport(sheet, {
observations: [emptyObservation('a'), emptyObservation('b')],
})
useReportStore.setState({ report, activeObservationIndex: 1 })
setCoreRuntime(unavailableCoreRuntime())
const s = useReportStore.getState()
expect(s.addObservation()).toEqual({ ok: false })
expect(s.moveObservationUp(1)).toEqual({ ok: false })
expect(s.removeObservation(0)).toEqual({ ok: false })
expect(s.initReport(draft(), sheet.sheet.ref)).toEqual({ ok: false })
expect(useReportStore.getState().report).toBe(report)
expect(useReportStore.getState().activeObservationIndex).toBe(1)
})
it('answer { ok: true } on the live core', () => {
const s = useReportStore.getState()
expect(s.initReport(draft(), sheet.sheet.ref)).toEqual({ ok: true })
expect(s.addObservation()).toEqual({ ok: true })
expect(useReportStore.getState().report!.observations).toHaveLength(2)
})
})
describe('callers stop on a failed core call', () => {
async function fillNewReport() {
const user = userEvent.setup()
render(
<MemoryRouter initialEntries={['/new']}>
<Routes>
<Route path="/new" element={<NewReportRoute />} />
<Route path="/editor" element={<p data-testid="editor-route" />} />
</Routes>
</MemoryRouter>,
)
await user.type(
screen.getByLabelText(fr['form.practitioner.name']!),
'Dr. Dupont',
)
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Mistral')
await user.type(
screen.getByLabelText(fr['form.owner.name']!),
'Jean Martin',
)
const submit = screen.getByRole('button', { name: fr['new_report.submit'] })
await waitFor(() => expect(submit).toBeEnabled())
await user.click(submit)
}
it('the new-report page stays put when the core cannot load', async () => {
setCoreRuntime(unavailableCoreRuntime())
await fillNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['sheet.core_unavailable']),
)
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
it('the new-report page stays put when the creation fails', async () => {
useReportStore.setState({ initReport: () => ({ ok: false }) })
try {
await fillNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.action_failed']),
)
expect(screen.queryByTestId('editor-route')).toBeNull()
} finally {
useReportStore.setState({
initReport: useReportStore.getInitialState().initReport,
})
}
})
it('the home page shows the import error when the core cannot load', async () => {
readMock.mockResolvedValue({ version: 3 })
setCoreRuntime(unavailableCoreRuntime())
setSheetProvider(bundledSheetProvider)
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route path="/" element={<HomeRoute />} />
<Route path="/editor" element={<p data-testid="editor-route" />} />
</Routes>
</MemoryRouter>,
)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', {
type: 'application/pdf',
})
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [file] },
})
await screen.findByText(fr['home.import.error_core_unavailable']!)
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
})
@@ -0,0 +1,151 @@
/**
* R2 plan P12 (rev 2): a draft or an archive the running build cannot read is
* set aside under a quarantine key, never dropped; only the content failures
* of the core (`invalid`, `unsupported_version`) quarantine, any other failure
* leaves both keys where they were; the source key is removed only once the
* quarantine write succeeded; a draft rebased with unresolved items keeps its
* raw pre-rebase text.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import { useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY, DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
})
afterEach(() => vi.restoreAllMocks())
const restore = () => useReportStore.getState().restoreDraft(sheet)
/** A sheet whose core answers `kind` to every draft restore. */
function sheetFailingWith(kind: string): SheetIndex {
return {
...sheet,
ops: { restoreDraft: () => ({ ok: false, kind }) },
} as unknown as SheetIndex
}
describe('an unreadable draft', () => {
it.each([
['a known version that does not parse', JSON.stringify({ version: 3 })],
['an unknown version', JSON.stringify({ version: 7 })],
['text that is not JSON', '{not json'],
])('%s is moved to its quarantine key', (_label, raw) => {
sessionStorage.setItem(DRAFT_KEY, raw)
expect(restore()).toEqual({ kind: 'quarantined' })
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(raw)
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
it('stays where it is when the quarantine write fails (storage full)', () => {
const raw = JSON.stringify({ version: 7 })
sessionStorage.setItem(DRAFT_KEY, raw)
const setItem = sessionStorage.setItem.bind(sessionStorage)
vi.spyOn(sessionStorage, 'setItem').mockImplementation((key, value) => {
if (key.startsWith('osteo:quarantine:')) {
throw new DOMException('full', 'QuotaExceededError')
}
setItem(key, value)
})
// Not announced as set aside: the editor stays put instead of leaving for Home.
expect(restore()).toEqual({ kind: 'unreadable_kept' })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(raw)
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
})
describe('a core failure while reading the draft', () => {
it.each(['core_unavailable', 'internal', 'rebase_failed'])(
'%s leaves the draft and the archive untouched',
(kind) => {
const draft = JSON.stringify(minimalReport(sheet))
sessionStorage.setItem(DRAFT_KEY, draft)
sessionStorage.setItem(ARCHIVE_KEY, '{"kept":true}')
const result = useReportStore
.getState()
.restoreDraft(sheetFailingWith(kind))
expect(result).toEqual({ kind: 'core_unavailable' })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBe('{"kept":true}')
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
},
)
})
describe('an unreadable archive beside a readable draft', () => {
it('goes to its quarantine key while the draft restores', () => {
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(minimalReport(sheet, { conclusion: 'kept' })),
)
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
expect(restore()).toMatchObject({ kind: 'restored' })
expect(useReportStore.getState().report?.conclusion).toBe('kept')
expect(useReportStore.getState().archive).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{not json')
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()
})
})
describe('a draft rebased onto the loaded sheet', () => {
const OTHER_SHA = 'c'.repeat(64)
it('keeps its raw text when the rebase flagged items', () => {
const stale = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
})
const raw = JSON.stringify(stale)
sessionStorage.setItem(DRAFT_KEY, raw)
expect(restore()).toMatchObject({
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 1 },
})
expect(sessionStorage.getItem(QUARANTINE_KEYS.draftPreRebase)).toBe(raw)
// The mirror now holds the rebased draft.
expect(
JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).sheet.documentSha256,
).toBe(sheet.sheet.ref.documentSha256)
})
it('keeps nothing aside when the rebase resolved everything', () => {
const moved = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
})
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(moved))
expect(restore()).toMatchObject({
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 0, unresolvedFindings: 0 },
})
expect(sessionStorage.getItem(QUARANTINE_KEYS.draftPreRebase)).toBeNull()
})
})
+37 -34
View File
@@ -13,19 +13,16 @@ import {
it,
vi,
} from 'vitest'
import type { Annotation } from '@faunosteo/domain'
import {
createReportStore,
useReportStore,
emptyObservation,
} from '@/state/reportStore'
import {
ARCHIVE_KEY,
DRAFT_KEY,
sessionStoragePersistence,
} from '@/state/persistence'
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, loadTestSheet, minimalReport } from '../helpers/sheet'
import {
archiveEnvelope,
emptyObservation,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
import fullV2 from '../fixtures/report-v2.full.json'
let sheet: SheetIndex
@@ -150,11 +147,21 @@ describe('sessionStorage mirror and restore', () => {
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3)
})
it('ignores an unreadable draft and does not replace an open report', () => {
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(sessionStoragePersistence.load(sheet.sheet.migrationMap)).toBeNull()
expect(useReportStore.getState().restoreDraft(sheet)).toEqual({
kind: 'quarantined',
})
expect(useReportStore.getState().report).toBeNull()
sessionStorage.setItem(DRAFT_KEY, JSON.stringify({ version: 1 }))
expect(sessionStoragePersistence.load(sheet.sheet.migrationMap)).toBeNull()
expect(useReportStore.getState().restoreDraft(sheet)).toEqual({
kind: 'quarantined',
})
expect(useReportStore.getState().report).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(
JSON.stringify({ version: 1 }),
)
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
const before = useReportStore.getState().report
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
@@ -165,8 +172,8 @@ describe('sessionStorage mirror and restore', () => {
it('createReportStore accepts another persistence adapter', () => {
const saved: unknown[] = []
const store = createReportStore(
{ load: () => null, save: (r) => saved.push(r) },
{ load: () => null, save: () => undefined },
{ loadText: () => null, save: (r) => saved.push(r) },
{ loadText: () => null, save: () => undefined },
)
store.getState().initReport(draft(), sheet.sheet.ref)
expect(saved.at(-1)).toMatchObject({ version: 3 })
@@ -174,15 +181,6 @@ describe('sessionStorage mirror and restore', () => {
})
describe('store edge cases', () => {
it('hydrateReport stores the given object as is, without revalidating', () => {
const odd = { ...minimalReport(sheet), extra: 1 }
useReportStore.getState().hydrateReport(odd)
expect(useReportStore.getState().report).toBe(odd)
expect(
(useReportStore.getState().report as unknown as { extra: number }).extra,
).toBe(1)
})
it('identity setters are no-ops without a report', () => {
const s = useReportStore.getState()
s.setPractitioner({ name: 'X' })
@@ -213,8 +211,8 @@ describe('archive of an imported Step 6 PDF', () => {
it('the archive is written at the session edges only, never on an edit', () => {
const archiveSaves: unknown[] = []
const store = createReportStore(
{ load: () => null, save: () => undefined },
{ load: () => null, save: (a) => archiveSaves.push(a) },
{ loadText: () => null, save: () => undefined },
{ loadText: () => null, save: (a) => archiveSaves.push(a) },
)
const report = minimalReport(sheet)
const archive = archiveEnvelope(sheet, report)
@@ -239,7 +237,10 @@ describe('archive of an imported Step 6 PDF', () => {
expect(sessionStorage.getItem(ARCHIVE_KEY)).not.toBeNull()
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(report))
const outcome = useReportStore.getState().restoreDraft(sheet)
expect(outcome).toMatchObject({ rebased: false })
expect(outcome).toMatchObject({
kind: 'restored',
rebase: { rebased: false },
})
expect(useReportStore.getState().report?.conclusion).toBe('kept')
expect(useReportStore.getState().archive).toEqual(archive)
})
@@ -250,8 +251,11 @@ describe('archive of an imported Step 6 PDF', () => {
() => useReportStore.getState().initReport(draft(), sheet.sheet.ref),
],
[
'hydrateReport',
() => useReportStore.getState().hydrateReport(minimalReport(sheet)),
'hydrateImport without an archive',
() =>
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null }),
],
['reset', () => useReportStore.getState().reset()],
])('%s clears the archive and removes its mirror', (_name, act) => {
@@ -292,9 +296,8 @@ describe('archive of an imported Step 6 PDF', () => {
const outcome = useReportStore.getState().restoreDraft(sheet)
expect(outcome).toMatchObject({
rebased: true,
unresolvedZones: 1,
unresolvedFindings: 0,
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 1, unresolvedFindings: 0 },
})
const restored = useReportStore.getState().report!
expect(restored.sheet).toEqual(sheet.sheet.ref)