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:
1 parent
794dfd9d0b
commit
74fcb37564
65 files changed
+2227
-1678
No files matched your search
@@ -38,4 +38,24 @@ export default tseslint.config(
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// R2: the application's rules run in the Rust core; its contracts come from
|
||||
// @faunosteo/core-wasm. The TypeScript domain stays frozen for the PDF engine, the
|
||||
// pipeline and scripts/ until R4/R5 (RUST_ARCHITECTURE_REVIEW VI.4).
|
||||
files: ['src/**/*.{ts,tsx}'],
|
||||
rules: {
|
||||
'no-restricted-imports': [
|
||||
'error',
|
||||
{
|
||||
paths: [
|
||||
{
|
||||
name: '@faunosteo/domain',
|
||||
message: 'Use @faunosteo/core-wasm (types) and the core operations.',
|
||||
},
|
||||
],
|
||||
patterns: ['@faunosteo/domain/*'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -27,8 +27,7 @@ import {
|
||||
MAX_PDF_BYTES,
|
||||
readAttachedDocument,
|
||||
} from '@faunosteo/pdf'
|
||||
import { parseBundledSheet } from '../src/sheets/provider'
|
||||
import { buildSheetIndex, type SheetIndex } from '../src/services/sheetIndex'
|
||||
import { compareSheetIndex, type CompareSheetIndex } from './compare/sheet'
|
||||
import {
|
||||
compareReport,
|
||||
diffLines,
|
||||
@@ -47,20 +46,15 @@ const SEED_DIR = resolve(
|
||||
/** pnpm runs the script from apps/app; paths are typed from the caller's folder. */
|
||||
const CWD = process.env.INIT_CWD ?? process.cwd()
|
||||
|
||||
function loadSheet(): SheetIndex {
|
||||
function loadSheet(): CompareSheetIndex {
|
||||
const json = (name: string) =>
|
||||
JSON.parse(readFileSync(join(SEED_DIR, name), 'utf8')) as never
|
||||
// The comparison needs the document and the map, not the drawings.
|
||||
return buildSheetIndex(
|
||||
parseBundledSheet({
|
||||
status: 'draft',
|
||||
ref: json('sheet-ref.json'),
|
||||
document: json('document.json'),
|
||||
migrationMap: json('report-migration-map.json'),
|
||||
assets: {},
|
||||
assetHashes: {},
|
||||
}),
|
||||
)
|
||||
return compareSheetIndex({
|
||||
ref: json('sheet-ref.json'),
|
||||
document: json('document.json'),
|
||||
migrationMap: json('report-migration-map.json'),
|
||||
})
|
||||
}
|
||||
|
||||
/** A folder stands for its PDFs; any other argument stays one entry. */
|
||||
@@ -79,7 +73,7 @@ function expandArg(arg: string): string[] {
|
||||
|
||||
async function compareFile(
|
||||
path: string,
|
||||
sheet: SheetIndex,
|
||||
sheet: CompareSheetIndex,
|
||||
args: CliArgs,
|
||||
): Promise<Comparison> {
|
||||
const st = statSync(path)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
pickLabel,
|
||||
ReportV2Schema,
|
||||
findingPathKey,
|
||||
type ArchiveReadOutcome,
|
||||
@@ -9,7 +10,7 @@ import {
|
||||
type ReportZone,
|
||||
} from '@faunosteo/domain'
|
||||
import type { Locale } from '../../src/i18n/types'
|
||||
import { pickLabel, type SheetIndex } from '../../src/services/sheetIndex'
|
||||
import type { CompareSheetIndex as SheetIndex } from './sheet'
|
||||
|
||||
/**
|
||||
* Pure comparison of a report document found in a PDF with its v3 reading:
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
buildSheetIndex,
|
||||
ReportMigrationMapSchema,
|
||||
type AnatomicalSheetDocument,
|
||||
type ReportMigrationMap,
|
||||
type SheetIndex,
|
||||
type SheetRef,
|
||||
} from '@faunosteo/domain'
|
||||
|
||||
/**
|
||||
* The reference sheet as the archive check tool reads it: the frozen TypeScript domain
|
||||
* (Zod schemas and index), as the application did before R2. The tool moves to the Rust
|
||||
* core with the PDF reader at R4 (RUST_ARCHITECTURE_REVIEW VI.4); until then it keeps its
|
||||
* own reading, independent of the application's core runtime.
|
||||
*/
|
||||
|
||||
export interface CompareSheet {
|
||||
status: 'draft' | 'published'
|
||||
ref: SheetRef
|
||||
document: AnatomicalSheetDocument
|
||||
assets: Readonly<Record<string, string>>
|
||||
migrationMap: ReportMigrationMap
|
||||
}
|
||||
|
||||
export type CompareSheetIndex = SheetIndex<CompareSheet>
|
||||
|
||||
/** The seed files of the reference sheet, parsed and indexed. */
|
||||
export function compareSheetIndex(seed: {
|
||||
ref: { sheet_id: string; version_id: string | null; document_sha256: string }
|
||||
document: unknown
|
||||
migrationMap: unknown
|
||||
}): CompareSheetIndex {
|
||||
return buildSheetIndex({
|
||||
status: 'draft',
|
||||
ref: {
|
||||
sheetId: seed.ref.sheet_id,
|
||||
versionId: seed.ref.version_id,
|
||||
documentSha256: seed.ref.document_sha256,
|
||||
},
|
||||
document: AnatomicalSheetDocumentSchema.parse(seed.document),
|
||||
assets: {},
|
||||
migrationMap: ReportMigrationMapSchema.parse(seed.migrationMap),
|
||||
})
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
renderAnnotationLayer,
|
||||
viewBoxOf,
|
||||
} from '@faunosteo/anatomy/render'
|
||||
import type { SheetView } from '@faunosteo/domain'
|
||||
import type { SheetView } from '@faunosteo/core-wasm/types'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,7 +3,10 @@ import { useNavigate } from 'react-router-dom'
|
||||
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
|
||||
import DetailModal from '@/components/canvas/DetailModal'
|
||||
import ObservationList from '@/components/observation/ObservationList'
|
||||
import ObservationPickers from '@/components/observation/ObservationPickers'
|
||||
import ObservationPickers, {
|
||||
type LateralTarget,
|
||||
type VertebraTarget,
|
||||
} from '@/components/observation/ObservationPickers'
|
||||
import ConclusionPanel from '@/components/report/ConclusionPanel'
|
||||
import ReportHeader from '@/components/report/ReportHeader'
|
||||
import EditInfosDialog, {
|
||||
@@ -11,25 +14,22 @@ import EditInfosDialog, {
|
||||
type Identity,
|
||||
} from '@/components/report/EditInfosDialog'
|
||||
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
|
||||
import CoreUnavailable from '@/components/report/CoreUnavailable'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import {
|
||||
useReportStore,
|
||||
type ActionResult,
|
||||
type RestoreResult,
|
||||
} from '@/state/reportStore'
|
||||
import { writeCachedPractitioner } from '@/state/practitionerCache'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { useSheet } from '@/sheets/useSheet'
|
||||
import { pickLabel, type SheetIndex } from '@/services/sheetIndex'
|
||||
import {
|
||||
decideZoneClick,
|
||||
ensureZone,
|
||||
refOf,
|
||||
removeAllSides,
|
||||
removeZoneAt,
|
||||
toggleZone,
|
||||
type ZoneRef,
|
||||
} from '@/services/zoneInteraction'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import type { ViewStates } from '@/anatomy/drawing'
|
||||
import { exportReportToPdf } from '@/pdf/export'
|
||||
import type { ExportWarning } from '@faunosteo/pdf'
|
||||
import type { RebaseOutcome } from '@faunosteo/domain'
|
||||
import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||
|
||||
@@ -45,6 +45,19 @@ function unresolvedCountOf(outcome: RebaseOutcome): number {
|
||||
return outcome.unresolvedZones + outcome.unresolvedFindings
|
||||
}
|
||||
|
||||
/** The alert of a restore, if any: a rebase on another sheet or a draft set aside. */
|
||||
function restoreAlert(
|
||||
result: RestoreResult,
|
||||
t: ReturnType<typeof useT>,
|
||||
): string | null {
|
||||
if (result.kind === 'quarantined') return t('editor.draft_quarantined')
|
||||
if (result.kind === 'restored' && result.rebase.rebased) {
|
||||
const count = String(unresolvedCountOf(result.rebase))
|
||||
return t('editor.draft_rebased').replace('{count}', count)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Editor on the reference sheet: wires the canvas, the pickers and the store. */
|
||||
export default function EditorRoute() {
|
||||
const navigate = useNavigate()
|
||||
@@ -56,8 +69,14 @@ export default function EditorRoute() {
|
||||
const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
|
||||
|
||||
const [detailViewId, setDetailViewId] = useState<string | null>(null)
|
||||
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
|
||||
const [lateralTarget, setLateralTarget] = useState<ZoneRef | null>(null)
|
||||
const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>(
|
||||
null,
|
||||
)
|
||||
const [lateralTarget, setLateralTarget] = useState<LateralTarget | null>(
|
||||
null,
|
||||
)
|
||||
// The core failed while reading the draft: stay here, keep the draft, offer a retry.
|
||||
const [restoreFailed, setRestoreFailed] = useState(false)
|
||||
const [disclaimer, setDisclaimer] = useState<string | null>(null)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [editDraft, setEditDraft] = useState<Identity | null>(null)
|
||||
@@ -69,15 +88,24 @@ export default function EditorRoute() {
|
||||
}, [])
|
||||
|
||||
// No report in memory: restore the per-tab draft once the sheet is known.
|
||||
// A draft rebased on another sheet is announced with its unresolved count.
|
||||
// A draft rebased on another sheet is announced with its unresolved count,
|
||||
// an unreadable one is set aside. While the core cannot run, nothing is
|
||||
// read or written and the page stays on the degraded notice (no redirect).
|
||||
useEffect(() => {
|
||||
if (report) return
|
||||
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet')
|
||||
return
|
||||
if (sheet.status === 'ready') {
|
||||
const outcome = store.restoreDraft(sheet.index)
|
||||
if (outcome?.rebased && !rebaseAlerted.current) {
|
||||
const result = store.restoreDraft(sheet.index)
|
||||
// Nothing could be read or set aside: stay, keep the draft where it is.
|
||||
if (result?.kind === 'core_unavailable' || result?.kind === 'unreadable_kept') {
|
||||
setRestoreFailed(true)
|
||||
return
|
||||
}
|
||||
const alert = result ? restoreAlert(result, t) : null
|
||||
if (alert && !rebaseAlerted.current) {
|
||||
rebaseAlerted.current = true
|
||||
const count = String(unresolvedCountOf(outcome))
|
||||
window.alert(t('editor.draft_rebased').replace('{count}', count))
|
||||
window.alert(alert)
|
||||
}
|
||||
}
|
||||
if (sheet.status !== 'loading' && !useReportStore.getState().report)
|
||||
@@ -111,42 +139,56 @@ export default function EditorRoute() {
|
||||
if (sheet.status !== 'ready' || !report) return
|
||||
const activeObs =
|
||||
activeIndex >= 0 ? report.observations[activeIndex] : undefined
|
||||
const index = sheet.index
|
||||
const annotation = index.annotation(annotationId)
|
||||
const decision = decideZoneClick(annotation, activeObs)
|
||||
if (!annotation) return
|
||||
switch (decision.kind) {
|
||||
case 'ignore':
|
||||
return
|
||||
const outcome = sheet.index.ops.zoneClick(activeObs ?? null, annotationId)
|
||||
if (!outcome.ok) return window.alert(t('core.action_failed'))
|
||||
const click = outcome.value
|
||||
if (click.observation) store.updateObservation(activeIndex, click.observation)
|
||||
switch (click.kind) {
|
||||
case 'open_view':
|
||||
return setDetailViewId(decision.viewId)
|
||||
return setDetailViewId(click.viewId ?? null)
|
||||
case 'activate_fallback':
|
||||
return store.setActiveObservation(report.observations.length - 1)
|
||||
case 'open_vertebra_picker': {
|
||||
const { observation, index: zoneIndex } = ensureZone(
|
||||
activeObs!,
|
||||
annotation,
|
||||
)
|
||||
store.updateObservation(activeIndex, observation)
|
||||
return setVertebraTarget(zoneIndex)
|
||||
}
|
||||
case 'open_vertebra_picker':
|
||||
return setVertebraTarget({
|
||||
zoneIndex: click.zoneIndex ?? 0,
|
||||
initial: click.vertebrae ?? [],
|
||||
})
|
||||
case 'open_laterality_picker':
|
||||
return setLateralTarget(refOf(annotation))
|
||||
case 'remove_both_sides':
|
||||
return store.updateObservation(
|
||||
activeIndex,
|
||||
removeAllSides(activeObs!, refOf(annotation)),
|
||||
)
|
||||
case 'toggle':
|
||||
return store.updateObservation(
|
||||
activeIndex,
|
||||
toggleZone(activeObs!, annotation),
|
||||
)
|
||||
return setLateralTarget({
|
||||
annotationId,
|
||||
sidesPresent: click.sidesPresent ?? [],
|
||||
})
|
||||
default:
|
||||
return
|
||||
}
|
||||
},
|
||||
[sheet, store],
|
||||
[sheet, store, t],
|
||||
)
|
||||
|
||||
/** A store action the core ran: the practitioner hears about a failure. */
|
||||
const guarded = useCallback(
|
||||
(result: ActionResult) => {
|
||||
if (!result.ok) window.alert(t('core.action_failed'))
|
||||
},
|
||||
[t],
|
||||
)
|
||||
|
||||
/** The vertebra picker opened from a zone chip: the core computes its selection. */
|
||||
function openVertebraPicker(index: SheetIndex, zoneIndex: number) {
|
||||
if (!activeObs) return
|
||||
const outcome = index.ops.vertebraInitial(activeObs, zoneIndex)
|
||||
if (!outcome.ok) return window.alert(t('core.action_failed'))
|
||||
setVertebraTarget({ zoneIndex, initial: outcome.value })
|
||||
}
|
||||
|
||||
function removeZone(index: SheetIndex, i: number, zoneIndex: number) {
|
||||
const obs = report?.observations[i]
|
||||
if (!obs) return
|
||||
const outcome = index.ops.removeZoneAt(obs, zoneIndex)
|
||||
if (outcome.ok) store.updateObservation(i, outcome.value)
|
||||
else window.alert(t('core.action_failed'))
|
||||
}
|
||||
|
||||
function acknowledgeDisclaimer() {
|
||||
sessionStorage?.setItem(DISCLAIMER_FLAG, '1')
|
||||
setDisclaimer(null)
|
||||
@@ -190,6 +232,12 @@ export default function EditorRoute() {
|
||||
}
|
||||
}
|
||||
|
||||
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet') {
|
||||
return <CoreUnavailable onRetry={sheet.retry} />
|
||||
}
|
||||
if (restoreFailed) {
|
||||
return <CoreUnavailable onRetry={() => window.location.reload()} />
|
||||
}
|
||||
if (!report) return null
|
||||
if (sheet.status === 'loading') {
|
||||
return (
|
||||
@@ -218,7 +266,7 @@ export default function EditorRoute() {
|
||||
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col">
|
||||
<AnatomyCanvas
|
||||
index={index}
|
||||
viewId={index.mainView.id}
|
||||
viewId={index.mainViewId}
|
||||
states={states}
|
||||
onZoneClick={onZoneClick}
|
||||
className="flex-1"
|
||||
@@ -241,19 +289,16 @@ export default function EditorRoute() {
|
||||
onToggle={(i) =>
|
||||
store.setActiveObservation(activeIndex === i ? -1 : i)
|
||||
}
|
||||
onAdd={store.addObservation}
|
||||
onDelete={store.removeObservation}
|
||||
onMoveUp={store.moveObservationUp}
|
||||
onMoveDown={store.moveObservationDown}
|
||||
onAdd={() => guarded(store.addObservation())}
|
||||
onDelete={(i) => guarded(store.removeObservation(i))}
|
||||
onMoveUp={(i) => guarded(store.moveObservationUp(i))}
|
||||
onMoveDown={(i) => guarded(store.moveObservationDown(i))}
|
||||
sheet={index}
|
||||
onChange={store.updateObservation}
|
||||
onOpenVertebraPicker={(_i, zoneIndex) =>
|
||||
setVertebraTarget(zoneIndex)
|
||||
openVertebraPicker(index, zoneIndex)
|
||||
}
|
||||
onRemoveZone={(i, zoneIndex) => {
|
||||
const obs = report.observations[i]
|
||||
if (obs) store.updateObservation(i, removeZoneAt(obs, zoneIndex))
|
||||
}}
|
||||
onRemoveZone={(i, zoneIndex) => removeZone(index, i, zoneIndex)}
|
||||
/>
|
||||
<ConclusionPanel
|
||||
conclusion={report.conclusion}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useRef, useState } from 'react'
|
||||
import {
|
||||
rebaseReportOnSheet,
|
||||
type ArchiveReadOutcome,
|
||||
type RebaseOutcome,
|
||||
} from '@faunosteo/domain'
|
||||
import type {
|
||||
ArchiveReadOutcome,
|
||||
RebaseOutcome,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Card from '@/components/ui/Card'
|
||||
import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import'
|
||||
import {
|
||||
importAttachment,
|
||||
ImportError,
|
||||
MAX_PDF_BYTES,
|
||||
readAttachment,
|
||||
} from '@/pdf/import'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useSheet } from '@/sheets/useSheet'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
|
||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
@@ -100,6 +103,8 @@ function importErrorMessage(err: unknown, t: Translate): string {
|
||||
return t('home.import.error_attachment_stripped')
|
||||
case 'no_attachment':
|
||||
return t('home.import.error_no_attachment')
|
||||
case 'core_unavailable':
|
||||
return t('home.import.error_core_unavailable')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,22 +112,21 @@ export default function HomeRoute() {
|
||||
const navigate = useNavigate()
|
||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
||||
const hydrateImport = useReportStore((s) => s.hydrateImport)
|
||||
const sheet = useSheet(DEFAULT_SPECIES_ID)
|
||||
// The page only needs to know a sheet exists; the core loads when a file is picked.
|
||||
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const t = useT()
|
||||
|
||||
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
|
||||
async function importFile(file: File, index: SheetIndex) {
|
||||
async function importFile(file: File) {
|
||||
// The engine refuses the same size; checking first keeps a huge file out of memory.
|
||||
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
|
||||
const bytes = new Uint8Array(await file.arrayBuffer())
|
||||
const outcome = await importReportFromPdf(bytes, index.sheet.migrationMap)
|
||||
const rebase = rebaseReportOnSheet(
|
||||
outcome.report,
|
||||
index,
|
||||
outcome.archive?.sheetSnapshot ?? null,
|
||||
)
|
||||
const attachment = await readAttachment(bytes)
|
||||
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
|
||||
if (!index) throw new ImportError('core_unavailable')
|
||||
const { read: outcome, rebase } = importAttachment(attachment, index)
|
||||
hydrateImport({ report: rebase.report, archive: outcome.archive })
|
||||
const lines = importMessages(outcome, rebase, t)
|
||||
if (lines.length > 0) window.alert(lines.join('\n\n'))
|
||||
@@ -135,7 +139,7 @@ export default function HomeRoute() {
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await importFile(file, sheet.index)
|
||||
await importFile(file)
|
||||
} catch (err) {
|
||||
setError(importErrorMessage(err, t))
|
||||
} finally {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
|
||||
import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
|
||||
import PractitionerForm from '@/components/report/PractitionerForm'
|
||||
import AnimalForm from '@/components/report/AnimalForm'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
@@ -13,7 +13,8 @@ import {
|
||||
writeCachedPractitioner,
|
||||
} from '@/state/practitionerCache'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useSheet } from '@/sheets/useSheet'
|
||||
import { useSheetAvailability } from '@/sheets/useSheet'
|
||||
import { coreRuntime } from '@/core/runtime'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** The one species this build ships a sheet for. */
|
||||
@@ -23,7 +24,8 @@ export default function NewReportRoute() {
|
||||
const navigate = useNavigate()
|
||||
const initReport = useReportStore((s) => s.initReport)
|
||||
const t = useT()
|
||||
const sheet = useSheet(DEFAULT_SPECIES_ID)
|
||||
// The form needs the sheet's reference and name only; the core loads on submit.
|
||||
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
|
||||
|
||||
const [practitioner, setPractitioner] = useState<Practitioner>({ name: '' })
|
||||
const [animal, setAnimal] = useState<Animal>({
|
||||
@@ -44,10 +46,14 @@ export default function NewReportRoute() {
|
||||
owner.name.trim() &&
|
||||
sheet.status === 'ready'
|
||||
|
||||
function submit() {
|
||||
async function submit() {
|
||||
if (!canSubmit || sheet.status !== 'ready') return
|
||||
writeCachedPractitioner(practitioner)
|
||||
initReport(
|
||||
if (!(await coreRuntime().ready())) {
|
||||
window.alert(t('sheet.core_unavailable'))
|
||||
return
|
||||
}
|
||||
const created = initReport(
|
||||
{
|
||||
date,
|
||||
practitioner,
|
||||
@@ -57,9 +63,10 @@ export default function NewReportRoute() {
|
||||
conclusion: '',
|
||||
recommendations: '',
|
||||
},
|
||||
sheet.index.sheet.ref,
|
||||
sheet.sheet.ref,
|
||||
)
|
||||
navigate('/editor')
|
||||
if (created.ok) navigate('/editor')
|
||||
else window.alert(t('core.action_failed'))
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -91,8 +98,8 @@ export default function NewReportRoute() {
|
||||
sheet.status === 'ready'
|
||||
? [
|
||||
{
|
||||
id: sheet.index.sheet.speciesId,
|
||||
name: sheet.index.sheet.document.name,
|
||||
id: sheet.sheet.speciesId,
|
||||
name: sheet.sheet.name,
|
||||
},
|
||||
]
|
||||
: [
|
||||
|
||||
@@ -7,9 +7,9 @@ import type {
|
||||
FindingZone,
|
||||
LateralSide,
|
||||
LocalizedOptionalText,
|
||||
} from '@faunosteo/domain'
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { pickLabel } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
@@ -25,7 +25,11 @@ export interface FindingsTreePickerProps {
|
||||
zone: FindingZone
|
||||
side?: LateralSide
|
||||
selected: Finding[]
|
||||
onChange: (next: Finding[]) => void
|
||||
/**
|
||||
* A leaf was ticked or unticked: its path and its position among the siblings shown.
|
||||
* The parent has the core build or remove the finding (R2).
|
||||
*/
|
||||
onToggle: (leafPath: string[], leafPosition: number) => void
|
||||
}
|
||||
|
||||
function isLeaf(node: TreeNode): boolean {
|
||||
@@ -69,13 +73,14 @@ function descriptionOf(node: TreeNode, locale: Locale): string | undefined {
|
||||
|
||||
/**
|
||||
* Drill-down picker over one finding zone of the sheet. A finding is keyed
|
||||
* by `(findingZoneId, path, side)`; labels are snapshotted at selection.
|
||||
* by `(findingZoneId, path, side)`; the core snapshots its labels when it
|
||||
* builds it. The selection predicates below only decide what is shown.
|
||||
*/
|
||||
export default function FindingsTreePicker({
|
||||
zone,
|
||||
side,
|
||||
selected,
|
||||
onChange,
|
||||
onToggle,
|
||||
}: FindingsTreePickerProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
@@ -125,25 +130,6 @@ export default function FindingsTreePicker({
|
||||
selected.filter((f) => matches(f) && pathStartsWith(f.path, nodePath))
|
||||
.length
|
||||
|
||||
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])
|
||||
}
|
||||
|
||||
const focusedDescription = focusedNode && descriptionOf(focusedNode, locale)
|
||||
|
||||
return (
|
||||
@@ -202,7 +188,7 @@ export default function FindingsTreePicker({
|
||||
{t('findings.no_options')}
|
||||
</li>
|
||||
) : (
|
||||
currentNodes.map((node) => {
|
||||
currentNodes.map((node, position) => {
|
||||
const nodePath = [...path, node.id]
|
||||
const nodeLabel = pickLabel(node.name, locale)
|
||||
const nodeDesc = descriptionOf(node, locale)
|
||||
@@ -215,7 +201,7 @@ export default function FindingsTreePicker({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isLeafSelected(nodePath)}
|
||||
onChange={() => toggleLeaf(nodePath, node)}
|
||||
onChange={() => onToggle(nodePath, position)}
|
||||
className="mt-1 accent-[var(--color-accent)]"
|
||||
aria-label={nodeLabel}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import type { LateralSide } from '@faunosteo/domain'
|
||||
import type { LateralSide } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface LateralityPickerProps {
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
LateralSide,
|
||||
Observation,
|
||||
ReportZone,
|
||||
} from '@faunosteo/domain'
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import { AnimatePresence, motion } from 'motion/react'
|
||||
import Card from '@/components/ui/Card'
|
||||
import Badge from '@/components/ui/Badge'
|
||||
@@ -15,7 +15,8 @@ import Textarea from '@/components/ui/Textarea'
|
||||
import FindingsTreePicker from './FindingsTreePicker'
|
||||
import FreeTextFindingInput from './FreeTextFindingInput'
|
||||
import SeveritySelector from './SeveritySelector'
|
||||
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
|
||||
import { isObservable, type SheetIndex } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
@@ -96,7 +97,7 @@ function unresolvedFindings(
|
||||
sheet: SheetIndex,
|
||||
): Finding[] {
|
||||
return observation.findings.filter(
|
||||
(f) => !sheet.nodeAt(f.findingZoneId, f.path),
|
||||
(f) => !sheet.hasNode(f.findingZoneId, f.path),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -152,6 +153,23 @@ export default function ObservationCard({
|
||||
event.stopPropagation()
|
||||
fn()
|
||||
}
|
||||
/** The core builds or removes the finding of the clicked leaf (R2). */
|
||||
function toggleFinding(
|
||||
findingZoneId: string,
|
||||
side: LateralSide | undefined,
|
||||
path: string[],
|
||||
leafPosition: number,
|
||||
) {
|
||||
const outcome = sheet.ops.toggleFinding({
|
||||
observation,
|
||||
findingZoneId,
|
||||
path,
|
||||
leafPosition,
|
||||
...(side ? { side } : {}),
|
||||
})
|
||||
if (outcome.ok) onChange(outcome.value)
|
||||
else window.alert(t('core.action_failed'))
|
||||
}
|
||||
const removeFinding = (target: Finding) =>
|
||||
onChange({
|
||||
...observation,
|
||||
@@ -379,11 +397,8 @@ export default function ObservationCard({
|
||||
zone={zone}
|
||||
side={side}
|
||||
selected={observation.findings}
|
||||
onChange={(next) =>
|
||||
onChange({
|
||||
...observation,
|
||||
findings: next,
|
||||
})
|
||||
onToggle={(path, leafPosition) =>
|
||||
toggleFinding(zone.id, side, path, leafPosition)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Observation } from '@faunosteo/domain'
|
||||
import type { Observation } from '@faunosteo/core-wasm/types'
|
||||
import ObservationCard from './ObservationCard'
|
||||
import Button from '@/components/ui/Button'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
|
||||
@@ -1,29 +1,39 @@
|
||||
import type { LateralSide, Observation } from '@faunosteo/domain'
|
||||
import type {
|
||||
LateralSide,
|
||||
Observation,
|
||||
Vertebra,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import VertebraPicker from '@/components/observation/VertebraPicker'
|
||||
import LateralityPicker from '@/components/observation/LateralityPicker'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
|
||||
import {
|
||||
addSides,
|
||||
collectVertebrae,
|
||||
sidesPresent,
|
||||
syncVertebrae,
|
||||
type ZoneRef,
|
||||
} from '@/services/zoneInteraction'
|
||||
import { isObservable, type SheetIndex } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** The zone the vertebra picker edits, with its initial selection (computed on open). */
|
||||
export interface VertebraTarget {
|
||||
zoneIndex: number
|
||||
initial: Vertebra[]
|
||||
}
|
||||
|
||||
/** The bilateral annotation the laterality picker records sides for. */
|
||||
export interface LateralTarget {
|
||||
annotationId: string
|
||||
sidesPresent: LateralSide[]
|
||||
}
|
||||
|
||||
export interface ObservationPickersProps {
|
||||
sheet: SheetIndex
|
||||
activeIndex: number
|
||||
activeObs: Observation | undefined
|
||||
vertebraTarget: number | null
|
||||
lateralTarget: ZoneRef | null
|
||||
vertebraTarget: VertebraTarget | null
|
||||
lateralTarget: LateralTarget | null
|
||||
onCloseVertebra: () => void
|
||||
onCloseLateral: () => void
|
||||
}
|
||||
|
||||
/** Vertebra and laterality pickers of the active observation. */
|
||||
/** Vertebra and laterality pickers of the active observation; the core applies the result. */
|
||||
export default function ObservationPickers({
|
||||
sheet,
|
||||
activeIndex,
|
||||
@@ -37,12 +47,25 @@ export default function ObservationPickers({
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const updateObservation = useReportStore((s) => s.updateObservation)
|
||||
const vertebraZone =
|
||||
vertebraTarget !== null ? activeObs?.zones[vertebraTarget] : undefined
|
||||
vertebraTarget !== null
|
||||
? activeObs?.zones[vertebraTarget.zoneIndex]
|
||||
: undefined
|
||||
const vertebraAnnotation =
|
||||
vertebraZone && sheet.annotation(vertebraZone.annotationId)
|
||||
const lateralAnnotation =
|
||||
lateralTarget && sheet.annotation(lateralTarget.annotationId)
|
||||
|
||||
/** Applies a core-built observation to the fresh active one; alerts on failure. */
|
||||
function apply(
|
||||
run: (fresh: Observation) => ReturnType<SheetIndex['ops']['addSides']>,
|
||||
) {
|
||||
const fresh = useReportStore.getState().report?.observations[activeIndex]
|
||||
if (!fresh) return
|
||||
const outcome = run(fresh)
|
||||
if (outcome.ok) updateObservation(activeIndex, outcome.value)
|
||||
else window.alert(t('core.action_failed'))
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{vertebraTarget !== null &&
|
||||
@@ -53,17 +76,12 @@ export default function ObservationPickers({
|
||||
open
|
||||
onClose={onCloseVertebra}
|
||||
onConfirm={(vertebrae) => {
|
||||
const fresh =
|
||||
useReportStore.getState().report?.observations[activeIndex]
|
||||
if (fresh) {
|
||||
updateObservation(
|
||||
activeIndex,
|
||||
syncVertebrae(fresh, vertebrae, sheet, vertebraZone.viewId),
|
||||
)
|
||||
}
|
||||
apply((fresh) =>
|
||||
sheet.ops.syncVertebrae(fresh, vertebrae, vertebraZone.viewId),
|
||||
)
|
||||
onCloseVertebra()
|
||||
}}
|
||||
initial={collectVertebrae(activeObs, sheet, vertebraTarget)}
|
||||
initial={vertebraTarget.initial}
|
||||
regions={sheet.regions()}
|
||||
title={`${t('vertebra.title_prefix')}${pickLabel(vertebraAnnotation.name, locale)}`}
|
||||
initialRegion={
|
||||
@@ -77,15 +95,11 @@ export default function ObservationPickers({
|
||||
open
|
||||
onClose={onCloseLateral}
|
||||
title={pickLabel(sheet.name(lateralAnnotation), locale)}
|
||||
existingSides={sidesPresent(activeObs, lateralTarget)}
|
||||
existingSides={lateralTarget.sidesPresent}
|
||||
onSelect={(sides: LateralSide[]) => {
|
||||
const fresh =
|
||||
useReportStore.getState().report?.observations[activeIndex]
|
||||
if (fresh)
|
||||
updateObservation(
|
||||
activeIndex,
|
||||
addSides(fresh, lateralAnnotation, sides),
|
||||
)
|
||||
apply((fresh) =>
|
||||
sheet.ops.addSides(fresh, lateralTarget.annotationId, sides),
|
||||
)
|
||||
onCloseLateral()
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Severity } from '@faunosteo/domain'
|
||||
import type { Severity } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface SeveritySelectorProps {
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { useState } from 'react'
|
||||
import type { Vertebra, VertebralRegion } from '@faunosteo/domain'
|
||||
import type {
|
||||
Vertebra,
|
||||
VertebraAction,
|
||||
VertebralRegion,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Chip from '@/components/ui/Chip'
|
||||
import { pickLabel } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { reportOps } from '@/core/reportOps'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
@@ -26,6 +31,8 @@ const sameVertebra = (a: Vertebra, r: string, i: number) =>
|
||||
* Picks vertebrae across every region of the sheet. A region shows its
|
||||
* usual count; when the sheet documents a wider range (D6), one control
|
||||
* extends the grid to the documented maximum. Nothing horse-specific here.
|
||||
* The selection rules (tap, check all, uncheck all) run in the core; the
|
||||
* grid extent and the chip state are display.
|
||||
*/
|
||||
export default function VertebraPicker({
|
||||
open,
|
||||
@@ -57,19 +64,17 @@ export default function VertebraPicker({
|
||||
|
||||
const has = (r: string, i: number) =>
|
||||
selected.some((v) => sameVertebra(v, r, i))
|
||||
const toggle = (r: string, i: number) =>
|
||||
setSelected((cur) =>
|
||||
has(r, i)
|
||||
? cur.filter((v) => !sameVertebra(v, r, i))
|
||||
: [...cur, { region: r, index: i }],
|
||||
)
|
||||
const all = (r: string, n: number) =>
|
||||
setSelected((cur) => [
|
||||
...cur.filter((v) => v.region !== r),
|
||||
...Array.from({ length: n }, (_, k) => ({ region: r, index: k + 1 })),
|
||||
])
|
||||
const none = (r: string) =>
|
||||
setSelected((cur) => cur.filter((v) => v.region !== r))
|
||||
/** One tap, applied by the core to the selection the picker shows (R2). */
|
||||
const apply = (action: VertebraAction) => {
|
||||
const outcome = reportOps.selectVertebrae(selected, action)
|
||||
if (outcome.ok) setSelected(outcome.value)
|
||||
else window.alert(t('core.action_failed'))
|
||||
}
|
||||
const toggle = (region: string, index: number) =>
|
||||
apply({ kind: 'toggle', region, index })
|
||||
const all = (region: string, count: number) =>
|
||||
apply({ kind: 'all', region, count })
|
||||
const none = (region: string) => apply({ kind: 'none', region })
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={title} size="lg">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Animal, LocalizedText, Owner } from '@faunosteo/domain'
|
||||
import type { Animal, LocalizedText, Owner } from '@faunosteo/core-wasm/types'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Select from '@/components/ui/Select'
|
||||
import { pickLabel } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import type { Report } from '@faunosteo/core-wasm/types'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Textarea from '@/components/ui/Textarea'
|
||||
import NextAppointmentPicker from './NextAppointmentPicker'
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface CoreUnavailableProps {
|
||||
onRetry: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Degraded state of the sheet pages when the core module cannot run (CSP, network, an old
|
||||
* browser, a refused sheet): the session data stays where it is, the practitioner retries.
|
||||
*/
|
||||
export default function CoreUnavailable({ onRetry }: CoreUnavailableProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
<main className="p-6 space-y-3 max-w-xl">
|
||||
<Notice tone="error">{t('sheet.core_unavailable')}</Notice>
|
||||
<Button onClick={onRetry}>{t('sheet.core_retry')}</Button>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
|
||||
import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import PractitionerForm from '@/components/report/PractitionerForm'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import type { Report } from '@faunosteo/core-wasm/types'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Label from '@/components/ui/Label'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Practitioner } from '@faunosteo/domain'
|
||||
import type { Practitioner } from '@faunosteo/core-wasm/types'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Input from '@/components/ui/Input'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import type { Report } from '@faunosteo/core-wasm/types'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { CoreOutcome } from '@faunosteo/core-wasm'
|
||||
import type {
|
||||
MoveDirection,
|
||||
NewReportDraft,
|
||||
Report,
|
||||
SheetRef,
|
||||
Vertebra,
|
||||
VertebraAction,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import { coreRuntime } from './runtime'
|
||||
|
||||
/**
|
||||
* The report rules that need no sheet (R2): creation and the observation list operations
|
||||
* of the store, the vertebra picker's selection. Ids and time come from the caller.
|
||||
*/
|
||||
|
||||
function run<T>(op: string, input: unknown): CoreOutcome<T> {
|
||||
return coreRuntime().call<T>(op, JSON.stringify(input))
|
||||
}
|
||||
|
||||
export interface NewReportInput {
|
||||
draft: NewReportDraft
|
||||
sheet: SheetRef
|
||||
id: string
|
||||
createdAt: string
|
||||
/** Id of the empty observation a draft without any starts with. */
|
||||
observationId: string
|
||||
}
|
||||
|
||||
export const reportOps = {
|
||||
newReport: (input: NewReportInput): CoreOutcome<Report> =>
|
||||
run('report.new', input),
|
||||
addObservation: (report: Report, id: string): CoreOutcome<Report> =>
|
||||
run('report.add_observation', { report, id }),
|
||||
removeObservation: (report: Report, index: number): CoreOutcome<Report> =>
|
||||
run('report.remove_observation', { report, index }),
|
||||
moveObservation: (
|
||||
report: Report,
|
||||
index: number,
|
||||
direction: MoveDirection,
|
||||
): CoreOutcome<Report> =>
|
||||
run('report.move_observation', { report, index, direction }),
|
||||
selectVertebrae: (
|
||||
selection: readonly Vertebra[],
|
||||
action: VertebraAction,
|
||||
): CoreOutcome<Vertebra[]> => run('vertebra.select', { selection, action }),
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import glueUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js?url'
|
||||
import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url'
|
||||
import {
|
||||
CoreRuntime,
|
||||
type CoreSource,
|
||||
type GlueModule,
|
||||
} from '@faunosteo/core-wasm'
|
||||
|
||||
/**
|
||||
* The application's core runtime (Rust compiled to WebAssembly, R2). Vite emits the glue
|
||||
* and the `.wasm` as hashed assets that no route chunk imports: nothing is fetched until a
|
||||
* sheet path or an import asks `ready()` (review III.3 rule 6). The production CSP must
|
||||
* carry `'wasm-unsafe-eval'` (DEPLOY.md); without it the load fails and the editor shows
|
||||
* the degraded state.
|
||||
*/
|
||||
|
||||
async function compileModule(): Promise<WebAssembly.Module> {
|
||||
const response = await fetch(wasmUrl)
|
||||
if (!response.ok) throw new Error(`core module HTTP ${response.status}`)
|
||||
try {
|
||||
// Needs `Content-Type: application/wasm`; any other type falls back to bytes.
|
||||
return await WebAssembly.compileStreaming(response.clone())
|
||||
} catch {
|
||||
return WebAssembly.compile(await response.arrayBuffer())
|
||||
}
|
||||
}
|
||||
|
||||
const browserSource: CoreSource = {
|
||||
compile: compileModule,
|
||||
// A distinct query per instance gives a new glue module record (R0 finding).
|
||||
importGlue: (instance) =>
|
||||
import(/* @vite-ignore */ `${glueUrl}?instance=${instance}`) as Promise<GlueModule>,
|
||||
}
|
||||
|
||||
let runtime: CoreRuntime | null = null
|
||||
|
||||
/** The page's runtime, created on first use. */
|
||||
export function coreRuntime(): CoreRuntime {
|
||||
runtime ??= new CoreRuntime(browserSource)
|
||||
return runtime
|
||||
}
|
||||
|
||||
/** Test seam: run the application on another runtime (the Node source in vitest). */
|
||||
export function setCoreRuntime(next: CoreRuntime): void {
|
||||
runtime = next
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { CoreOutcome, SheetSession } from '@faunosteo/core-wasm'
|
||||
import type {
|
||||
ArchiveImport,
|
||||
DraftRestore,
|
||||
LateralSide,
|
||||
Observation,
|
||||
Report,
|
||||
SheetSnapshot,
|
||||
Vertebra,
|
||||
ZoneClick,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* The sheet-bound rules of the editor, run by the core on the session's sheet (R2): one
|
||||
* call per user action or load, never in a render. Each returns the core's outcome; the
|
||||
* caller stops on `ok: false` (nothing is written, the action shows `core.action_failed`).
|
||||
*/
|
||||
|
||||
export interface FindingToggle {
|
||||
observation: Observation
|
||||
findingZoneId: string
|
||||
path: readonly string[]
|
||||
/** Position of the clicked leaf among the siblings the picker rendered. */
|
||||
leafPosition: number
|
||||
side?: LateralSide
|
||||
}
|
||||
|
||||
export class SheetOps {
|
||||
constructor(private readonly session: SheetSession) {}
|
||||
|
||||
private run<T>(op: string, input: unknown): CoreOutcome<T> {
|
||||
return this.session.call<T>(op, JSON.stringify(input))
|
||||
}
|
||||
|
||||
/** What a click on an annotation does to the active observation (the whole click chain). */
|
||||
zoneClick(
|
||||
observation: Observation | null,
|
||||
annotationId: string,
|
||||
): CoreOutcome<ZoneClick> {
|
||||
return this.run('zone.click', { observation, annotationId })
|
||||
}
|
||||
|
||||
addSides(
|
||||
observation: Observation,
|
||||
annotationId: string,
|
||||
sides: readonly LateralSide[],
|
||||
): CoreOutcome<Observation> {
|
||||
return this.run('zone.add_sides', { observation, annotationId, sides })
|
||||
}
|
||||
|
||||
removeZoneAt(observation: Observation, index: number): CoreOutcome<Observation> {
|
||||
return this.run('zone.remove_at', { observation, index })
|
||||
}
|
||||
|
||||
/** The vertebra picker's initial selection, the zone at `index` first. */
|
||||
vertebraInitial(
|
||||
observation: Observation,
|
||||
index: number,
|
||||
): CoreOutcome<Vertebra[]> {
|
||||
return this.run('vertebra.initial', { observation, index })
|
||||
}
|
||||
|
||||
syncVertebrae(
|
||||
observation: Observation,
|
||||
selection: readonly Vertebra[],
|
||||
viewId: string,
|
||||
): CoreOutcome<Observation> {
|
||||
return this.run('vertebra.sync', { observation, selection, viewId })
|
||||
}
|
||||
|
||||
toggleFinding(toggle: FindingToggle): CoreOutcome<Observation> {
|
||||
return this.run('finding.toggle', toggle)
|
||||
}
|
||||
|
||||
/** Reads the tab's draft (and the archive kept beside it) and rebases it on this sheet. */
|
||||
restoreDraft(
|
||||
draft: string,
|
||||
archive: string | null,
|
||||
): CoreOutcome<DraftRestore> {
|
||||
return this.run('draft.restore', { draft, archive })
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a PDF attachment (any supported shape, as the byte scan parsed it) and rebases
|
||||
* it on this sheet. Failures: `incompatible_version` (with `found`), `no_attachment`.
|
||||
*/
|
||||
importArchive(attachment: unknown): CoreOutcome<ArchiveImport> {
|
||||
return this.run('archive.import', attachment)
|
||||
}
|
||||
|
||||
/** The snapshot of this sheet an archive of `report` carries. */
|
||||
snapshot(report: Report): CoreOutcome<SheetSnapshot> {
|
||||
return this.run('archive.snapshot', { report })
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ export const en: Dict = {
|
||||
'Reopen a previous report generated by this app to follow up.',
|
||||
'home.import.cta': 'Choose a PDF',
|
||||
'home.import.loading': 'Reading…',
|
||||
'home.import.error_core_unavailable':
|
||||
'The reading engine could not be loaded. Try the import again.',
|
||||
'home.import.error_generic': 'Failed to read the PDF.',
|
||||
'home.import.error_invalid_pdf': 'This file is not a readable PDF.',
|
||||
'home.import.error_no_attachment':
|
||||
@@ -76,6 +78,8 @@ export const en: Dict = {
|
||||
'PDF exported with missing elements: {items}. Check the browser console.',
|
||||
'editor.draft_rebased':
|
||||
'Draft restored on an anatomical sheet different from the one it was created on. Items not found: {count} (kept with their labels).',
|
||||
'editor.draft_quarantined':
|
||||
"This tab's draft could not be read by this version of Faunosteo. It was set aside, not deleted.",
|
||||
'editor.edit_infos': 'Edit info',
|
||||
'editor.edit_dialog_title': 'Edit information',
|
||||
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
|
||||
@@ -152,6 +156,11 @@ export const en: Dict = {
|
||||
'Anatomical sheet: reference draft, not medically validated',
|
||||
'sheet.status.published': 'Official anatomical sheet',
|
||||
'sheet.loading': 'Loading the anatomical sheet…',
|
||||
'sheet.core_unavailable':
|
||||
"Faunosteo's computation engine could not be loaded. Your session data is kept.",
|
||||
'sheet.core_retry': 'Retry',
|
||||
'core.action_failed':
|
||||
'This action could not be applied. Try again; your report was not changed.',
|
||||
|
||||
// unresolved (migrated) data
|
||||
'observation.unresolved_short': 'inherited',
|
||||
|
||||
@@ -26,6 +26,8 @@ export const fr: Dict = {
|
||||
'Reprendre un bilan précédent généré par cette application pour effectuer un suivi.',
|
||||
'home.import.cta': 'Choisir un PDF',
|
||||
'home.import.loading': 'Lecture…',
|
||||
'home.import.error_core_unavailable':
|
||||
"Le moteur de lecture n'a pas pu être chargé. Réessayez l'import.",
|
||||
'home.import.error_generic': 'Erreur de lecture du PDF.',
|
||||
'home.import.error_invalid_pdf': "Ce fichier n'est pas un PDF lisible.",
|
||||
'home.import.error_no_attachment':
|
||||
@@ -82,6 +84,8 @@ export const fr: Dict = {
|
||||
'PDF exporté avec des éléments manquants : {items}. Vérifiez la console du navigateur.',
|
||||
'editor.draft_rebased':
|
||||
'Brouillon restauré sur une fiche anatomique différente de celle où il a été créé. Éléments non retrouvés : {count} (conservés avec leurs libellés).',
|
||||
'editor.draft_quarantined':
|
||||
"Le brouillon de cet onglet n'a pas pu être relu par cette version de Faunosteo. Il a été mis de côté, pas supprimé.",
|
||||
'editor.edit_infos': 'Modifier les infos',
|
||||
'editor.edit_dialog_title': 'Modifier les informations',
|
||||
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
|
||||
@@ -166,6 +170,11 @@ export const fr: Dict = {
|
||||
'Fiche anatomique : brouillon de référence, non validé médicalement',
|
||||
'sheet.status.published': 'Fiche anatomique officielle',
|
||||
'sheet.loading': 'Chargement de la fiche anatomique…',
|
||||
'sheet.core_unavailable':
|
||||
"Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées.",
|
||||
'sheet.core_retry': 'Réessayer',
|
||||
'core.action_failed':
|
||||
"Cette action n'a pas pu être appliquée. Réessayez ; votre bilan n'a pas été modifié.",
|
||||
|
||||
// unresolved (migrated) data
|
||||
'observation.unresolved_short': 'hérité',
|
||||
|
||||
@@ -14,3 +14,11 @@ export function pickLocaleLabel(
|
||||
if (locale === 'en') return en || fr || fallback
|
||||
return fr || en || fallback
|
||||
}
|
||||
|
||||
/** The same rule for a `{ fr, en }` label of the sheet or a snapshot ('' when absent). */
|
||||
export function pickLabel(
|
||||
text: { fr?: string; en?: string } | null | undefined,
|
||||
locale: Locale,
|
||||
): string {
|
||||
return pickLocaleLabel(text?.fr, text?.en, locale)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Branding, ImageAsset } from '@faunosteo/domain'
|
||||
import type { Branding, ImageAsset } from '@faunosteo/core-wasm/types'
|
||||
import headerLogoDataUrl from '@/assets/brand/faunosteo-logo-horizontal-512.png?inline'
|
||||
import footerLogoDataUrl from '@/assets/brand/faunosteo-horizontal-com-512.png?inline'
|
||||
import poweredByLogoDataUrl from '@/assets/brand/zenquality-logo-fr.png?inline'
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
|
||||
import type { Report } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
defaultPdfLabels,
|
||||
exportReportArchive,
|
||||
type ExportInput,
|
||||
type ExportWarning,
|
||||
} from '@faunosteo/pdf'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
@@ -20,19 +21,24 @@ export interface PdfExportResult {
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports the report as an archive PDF through the engine: the loaded sheet
|
||||
* becomes the snapshot the pages are drawn from and the attachment carries,
|
||||
* the branding comes from the bundled logos, the browser rasterises the
|
||||
* views. Warnings are logged and returned for the caller to surface.
|
||||
* Exports the report as an archive PDF through the engine: the core builds
|
||||
* the snapshot of the loaded sheet the pages are drawn from and the
|
||||
* attachment carries (R2), the branding comes from the bundled logos, the
|
||||
* browser rasterises the views, the TypeScript engine writes the file (the
|
||||
* writer moves to the core at R4). The core's report and snapshot are the
|
||||
* same JSON contracts the engine's Zod types describe. Warnings are logged
|
||||
* and returned for the caller to surface.
|
||||
*/
|
||||
export async function exportReportToPdf(
|
||||
report: Report,
|
||||
index: SheetIndex,
|
||||
opts: PdfExportOptions,
|
||||
): Promise<PdfExportResult> {
|
||||
const snapshot = index.ops.snapshot(report)
|
||||
if (!snapshot.ok) throw new Error(`snapshot failed: ${snapshot.kind}`)
|
||||
const result = await exportReportArchive({
|
||||
report,
|
||||
sheet: buildSheetSnapshot(index.sheet, report),
|
||||
report: report as ExportInput['report'],
|
||||
sheet: snapshot.value as ExportInput['sheet'],
|
||||
branding: await loadBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
locale: opts.locale,
|
||||
|
||||
+42
-11
@@ -1,13 +1,14 @@
|
||||
import type { ArchiveReadOutcome, ReportMigrationMap } from '@faunosteo/domain'
|
||||
import type { ArchiveImport } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
ArchiveReadError,
|
||||
readReportArchive,
|
||||
readAttachedDocument,
|
||||
type ArchiveReadErrorKind,
|
||||
} from '@faunosteo/pdf'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
|
||||
export { MAX_PDF_BYTES } from '@faunosteo/pdf'
|
||||
|
||||
export type ImportErrorKind = ArchiveReadErrorKind
|
||||
export type ImportErrorKind = ArchiveReadErrorKind | 'core_unavailable'
|
||||
|
||||
/**
|
||||
* Localization-agnostic import error. Carries a kind discriminant + an
|
||||
@@ -25,17 +26,13 @@ export class ImportError extends Error {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a Faunosteo PDF back through the engine: the report (v3 as is, v2
|
||||
* migrated through the sheet's map) and, when the file is a Step 6 archive,
|
||||
* the validated envelope or the reason its snapshot was dropped. Engine
|
||||
* Step 1, no core needed: the JSON a Faunosteo PDF carries, located by the
|
||||
* engine's byte scan (BLK-009; the scanner moves to the core at R4). Engine
|
||||
* failures become ImportError kinds, one to one.
|
||||
*/
|
||||
export async function importReportFromPdf(
|
||||
pdfBytes: Uint8Array,
|
||||
map: ReportMigrationMap,
|
||||
): Promise<ArchiveReadOutcome> {
|
||||
export async function readAttachment(pdfBytes: Uint8Array): Promise<unknown> {
|
||||
try {
|
||||
return await readReportArchive(pdfBytes, map)
|
||||
return await readAttachedDocument(pdfBytes)
|
||||
} catch (err) {
|
||||
if (err instanceof ArchiveReadError) {
|
||||
throw new ImportError(err.kind, err.foundVersion)
|
||||
@@ -43,3 +40,37 @@ export async function importReportFromPdf(
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 2, in the core on the loaded sheet: the layered reading of the
|
||||
* attachment (report first, v2 migrated through the sheet's map, then the
|
||||
* envelope kept or its snapshot dropped with a reason) and the rebase onto
|
||||
* that sheet. An unknown numeric report version is `incompatible_version`,
|
||||
* any other unreadable content `no_attachment`, as the engine reported them.
|
||||
*/
|
||||
export function importAttachment(
|
||||
attachment: unknown,
|
||||
index: SheetIndex,
|
||||
): ArchiveImport {
|
||||
const outcome = index.ops.importArchive(attachment)
|
||||
if (outcome.ok) return outcome.value
|
||||
switch (outcome.kind) {
|
||||
case 'incompatible_version':
|
||||
throw new ImportError('incompatible_version', outcome.found ?? null)
|
||||
case 'no_attachment':
|
||||
throw new ImportError('no_attachment')
|
||||
case 'core_unavailable':
|
||||
case 'internal':
|
||||
throw new ImportError('core_unavailable')
|
||||
default:
|
||||
throw new Error(`import failed: ${outcome.kind}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Both steps on a sheet already loaded in the core. */
|
||||
export async function importReportFromPdf(
|
||||
pdfBytes: Uint8Array,
|
||||
index: SheetIndex,
|
||||
): Promise<ArchiveImport> {
|
||||
return importAttachment(await readAttachment(pdfBytes), index)
|
||||
}
|
||||
@@ -1,11 +1,109 @@
|
||||
import type { SheetIndex as DomainSheetIndex } from '@faunosteo/domain'
|
||||
import type { LoadedSheet } from '@/sheets/provider'
|
||||
import type {
|
||||
Annotation,
|
||||
AnatomicalSheetDocument,
|
||||
FindingZone,
|
||||
LocalizedText,
|
||||
ObservableAnnotation,
|
||||
SheetIndexData,
|
||||
SheetRef,
|
||||
SheetStatus,
|
||||
SheetView,
|
||||
VertebralRegion,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import type { SheetOps } from '@/core/sheetOps'
|
||||
|
||||
/**
|
||||
* The sheet index lives in @faunosteo/domain since Step 6 (shared with the
|
||||
* PDF engine). This shim keeps the app's import path and binds the index to
|
||||
* the sheet the app loads, so `index.sheet` still carries the migration map.
|
||||
* The loaded sheet as React reads it (R2). Every lookup table is computed once by the
|
||||
* core (`SheetIndexData`): positions by id with the TypeScript `Map` semantics (last
|
||||
* duplicate wins), names, spine ids and the finding paths that exist. This class only reads
|
||||
* them, so no render calls the core; the sheet-bound rules go through `ops`.
|
||||
*/
|
||||
export { buildSheetIndex, isObservable, pickLabel } from '@faunosteo/domain'
|
||||
export type { ObservableAnnotation } from '@faunosteo/domain'
|
||||
export type SheetIndex = DomainSheetIndex<LoadedSheet>
|
||||
|
||||
export type { ObservableAnnotation }
|
||||
|
||||
/** What the screens read about the loaded sheet. */
|
||||
export interface LoadedSheetView {
|
||||
status: SheetStatus
|
||||
ref: SheetRef
|
||||
speciesId: string
|
||||
schemaVersion: number
|
||||
/** The document as the core parsed it (defaults filled in). */
|
||||
document: AnatomicalSheetDocument
|
||||
/** SVG text by `svg_asset_id` (the canvas draws them until R3). */
|
||||
assets: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
function at<T>(
|
||||
list: readonly T[],
|
||||
positions: Readonly<Record<string, number>>,
|
||||
id: string,
|
||||
): T | undefined {
|
||||
return Object.hasOwn(positions, id) ? list[positions[id]!] : undefined
|
||||
}
|
||||
|
||||
export function isObservable(
|
||||
a: Annotation | undefined,
|
||||
): a is ObservableAnnotation {
|
||||
return a !== undefined && a.kind !== 'detail_trigger'
|
||||
}
|
||||
|
||||
export class SheetIndex {
|
||||
readonly sheet: LoadedSheetView
|
||||
/** The first `main` view of the document. */
|
||||
readonly mainViewId: string
|
||||
private readonly spine: ReadonlySet<string>
|
||||
private readonly nodes: ReadonlySet<string>
|
||||
|
||||
constructor(
|
||||
private readonly data: SheetIndexData,
|
||||
assets: Readonly<Record<string, string>>,
|
||||
readonly ops: SheetOps,
|
||||
) {
|
||||
const { document } = data
|
||||
this.sheet = {
|
||||
status: data.status,
|
||||
ref: data.ref,
|
||||
speciesId: data.speciesId,
|
||||
schemaVersion: data.schemaVersion,
|
||||
document,
|
||||
assets,
|
||||
}
|
||||
this.mainViewId = data.mainViewId
|
||||
this.spine = new Set(data.spineIds)
|
||||
this.nodes = new Set(data.nodeKeys)
|
||||
}
|
||||
|
||||
view(id: string): SheetView | undefined {
|
||||
return at(this.data.document.views, this.data.viewById, id)
|
||||
}
|
||||
|
||||
annotation(id: string): Annotation | undefined {
|
||||
return at(this.data.document.annotations, this.data.annotationById, id)
|
||||
}
|
||||
|
||||
findingZone(id: string): FindingZone | undefined {
|
||||
return at(this.data.document.finding_zones, this.data.findingZoneById, id)
|
||||
}
|
||||
|
||||
regions(): VertebralRegion[] {
|
||||
return this.data.document.vertebral_config.regions
|
||||
}
|
||||
|
||||
/** Whether an annotation opens the vertebra picker. */
|
||||
isSpine(annotationId: string): boolean {
|
||||
return this.spine.has(annotationId)
|
||||
}
|
||||
|
||||
/** The name the sheet gives an annotation (a trigger: its own or its view's). */
|
||||
name(annotation: Annotation): LocalizedText {
|
||||
const names = this.data.names
|
||||
return Object.hasOwn(names, annotation.id)
|
||||
? names[annotation.id]!
|
||||
: { fr: '', en: '' }
|
||||
}
|
||||
|
||||
/** Whether the finding zone holds this category or node path. */
|
||||
hasNode(zoneId: string, path: readonly string[]): boolean {
|
||||
return this.nodes.has(JSON.stringify([zoneId, ...path]))
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,17 @@
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
ReportMigrationMapSchema,
|
||||
type AnatomicalSheetDocument,
|
||||
type ReportMigrationMap,
|
||||
type SheetRef,
|
||||
} from '@faunosteo/domain'
|
||||
import type { LocalizedText, SheetRef } from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* Where the application gets the anatomical sheet it works on. Step 5 ships
|
||||
* one implementation, the sheet bundled at build time (virtual module, see
|
||||
* vite/sheet-bundle.ts); the Supabase implementation of Step 13 sits behind
|
||||
* the same interface. A loaded sheet is immutable for the session.
|
||||
* the same interface. The payload is handed to the core as it is: the core
|
||||
* parses the document and the migration map (R2). A loaded sheet is
|
||||
* immutable for the session.
|
||||
*/
|
||||
|
||||
export type SheetStatus = 'draft' | 'published'
|
||||
|
||||
/** Raw payload of the virtual module, validated here before use. */
|
||||
/** Raw payload of the virtual module, parsed by the core (`SheetHandle`). */
|
||||
export interface BundledSheetData {
|
||||
status: SheetStatus
|
||||
ref: {
|
||||
@@ -32,56 +28,53 @@ export interface BundledSheetData {
|
||||
assetHashes: Record<string, string>
|
||||
}
|
||||
|
||||
export interface LoadedSheet {
|
||||
status: SheetStatus
|
||||
export interface SheetProvider {
|
||||
/** The reference sheet payload of a species, or null when none is available. */
|
||||
getReferenceSheet(speciesId: string): Promise<BundledSheetData | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* What the pages that only offer to start or import a report show, read from the payload
|
||||
* without the core: the reference a new report is stamped with and the species name.
|
||||
*/
|
||||
export interface SheetAvailability {
|
||||
ref: SheetRef
|
||||
speciesId: string
|
||||
/** Document schema version of the sheet (`ref.schema_version`). */
|
||||
schemaVersion: number
|
||||
document: AnatomicalSheetDocument
|
||||
/** SVG text by `svg_asset_id`. */
|
||||
assets: Readonly<Record<string, string>>
|
||||
/** sha256 by `svg_asset_id`; carried into a report archive as provenance. */
|
||||
assetHashes: Readonly<Record<string, string>>
|
||||
migrationMap: ReportMigrationMap
|
||||
name: LocalizedText
|
||||
}
|
||||
|
||||
export interface SheetProvider {
|
||||
/** The reference sheet of a species, or null when none is available. */
|
||||
getReferenceSheet(speciesId: string): Promise<LoadedSheet | null>
|
||||
}
|
||||
|
||||
export function parseBundledSheet(data: BundledSheetData): LoadedSheet {
|
||||
const document = AnatomicalSheetDocumentSchema.parse(data.document)
|
||||
const migrationMap = ReportMigrationMapSchema.parse(data.migrationMap)
|
||||
export function availabilityOf(data: BundledSheetData): SheetAvailability {
|
||||
const document = data.document as { name: LocalizedText }
|
||||
return {
|
||||
status: data.status,
|
||||
ref: {
|
||||
sheetId: data.ref.sheet_id,
|
||||
versionId: data.ref.version_id,
|
||||
documentSha256: data.ref.document_sha256,
|
||||
},
|
||||
speciesId: data.ref.species_id,
|
||||
schemaVersion: data.ref.schema_version,
|
||||
document,
|
||||
assets: data.assets,
|
||||
assetHashes: data.assetHashes,
|
||||
migrationMap,
|
||||
name: document.name,
|
||||
}
|
||||
}
|
||||
|
||||
let cached: Promise<LoadedSheet | null> | null = null
|
||||
let cached: Promise<BundledSheetData | null> | null = null
|
||||
|
||||
async function loadBundled(): Promise<LoadedSheet | null> {
|
||||
async function loadBundled(): Promise<BundledSheetData | null> {
|
||||
const mod = await import('virtual:faunosteo-sheet')
|
||||
return mod.bundledSheet ? parseBundledSheet(mod.bundledSheet) : null
|
||||
return mod.bundledSheet
|
||||
}
|
||||
|
||||
export const bundledSheetProvider: SheetProvider = {
|
||||
async getReferenceSheet(speciesId) {
|
||||
cached ??= loadBundled()
|
||||
const sheet = await cached
|
||||
return sheet && sheet.speciesId === speciesId ? sheet : null
|
||||
let sheet: BundledSheetData | null
|
||||
try {
|
||||
sheet = await cached
|
||||
} catch (error) {
|
||||
// A failed chunk load is not remembered: the next attempt fetches again.
|
||||
cached = null
|
||||
throw error
|
||||
}
|
||||
return sheet && sheet.ref.species_id === speciesId ? sheet : null
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+105
-12
@@ -1,20 +1,40 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { buildSheetIndex, type SheetIndex } from '@/services/sheetIndex'
|
||||
import { bundledSheetProvider, type SheetProvider } from './provider'
|
||||
import type { SheetIndexData } from '@faunosteo/core-wasm/types'
|
||||
import { coreRuntime } from '@/core/runtime'
|
||||
import { SheetOps } from '@/core/sheetOps'
|
||||
import { SheetIndex } from '@/services/sheetIndex'
|
||||
import {
|
||||
availabilityOf,
|
||||
bundledSheetProvider,
|
||||
type SheetAvailability,
|
||||
type SheetProvider,
|
||||
} from './provider'
|
||||
|
||||
/**
|
||||
* The reference sheet of a species for the current session, loaded once
|
||||
* through the provider and indexed. `none` means the build carries no sheet
|
||||
* (production bundle without SHEET_BUNDLE=draft) or no sheet for the species.
|
||||
* The reference sheet of a species for the current session. `useSheet` loads it into the
|
||||
* core (the editor, the import): `none` means the build carries no sheet (production
|
||||
* bundle without SHEET_BUNDLE=draft) or none for the species; `core_unavailable` means the
|
||||
* module could not be loaded (CSP, network, old browser) and `invalid_sheet` that the
|
||||
* bundled payload was refused, both with a `retry`. `useSheetAvailability` reads the
|
||||
* payload alone, without the core, for the pages that only offer to start a report.
|
||||
*/
|
||||
|
||||
export type SheetLoad =
|
||||
| { status: 'none' }
|
||||
| { status: 'ready'; index: SheetIndex }
|
||||
| { status: 'core_unavailable' }
|
||||
| { status: 'invalid_sheet' }
|
||||
|
||||
export type SheetState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'none' }
|
||||
| { status: 'ready'; index: SheetIndex }
|
||||
| { status: 'core_unavailable'; retry: () => void }
|
||||
| { status: 'invalid_sheet'; retry: () => void }
|
||||
|
||||
let provider: SheetProvider = bundledSheetProvider
|
||||
const cache = new Map<string, Promise<SheetIndex | null>>()
|
||||
/** Settled loads only (`ready`, `none`): a failure is never remembered. */
|
||||
const cache = new Map<string, Promise<SheetLoad>>()
|
||||
|
||||
/** Test seam: swap the provider and forget loaded sheets. */
|
||||
export function setSheetProvider(next: SheetProvider): void {
|
||||
@@ -22,19 +42,48 @@ export function setSheetProvider(next: SheetProvider): void {
|
||||
cache.clear()
|
||||
}
|
||||
|
||||
export function loadSheetIndex(speciesId: string): Promise<SheetIndex | null> {
|
||||
async function loadIntoCore(speciesId: string): Promise<SheetLoad> {
|
||||
const bundle = await provider.getReferenceSheet(speciesId)
|
||||
if (!bundle) return { status: 'none' }
|
||||
if (!(await coreRuntime().ready())) return { status: 'core_unavailable' }
|
||||
const session = coreRuntime().sheet(JSON.stringify(bundle))
|
||||
const data = session.call<SheetIndexData>('index_data', '')
|
||||
if (data.ok) {
|
||||
const index = new SheetIndex(data.value, bundle.assets, new SheetOps(session))
|
||||
return { status: 'ready', index }
|
||||
}
|
||||
return {
|
||||
status: data.kind === 'invalid_sheet' ? 'invalid_sheet' : 'core_unavailable',
|
||||
}
|
||||
}
|
||||
|
||||
/** The species' sheet in the core; failures are retried on the next call. */
|
||||
export function loadSheet(speciesId: string): Promise<SheetLoad> {
|
||||
let pending = cache.get(speciesId)
|
||||
if (!pending) {
|
||||
pending = provider
|
||||
.getReferenceSheet(speciesId)
|
||||
.then((sheet) => (sheet ? buildSheetIndex(sheet) : null))
|
||||
pending = loadIntoCore(speciesId).catch(
|
||||
(): SheetLoad => ({ status: 'core_unavailable' }),
|
||||
)
|
||||
cache.set(speciesId, pending)
|
||||
void pending.then((load) => {
|
||||
const settled = load.status === 'ready' || load.status === 'none'
|
||||
if (!settled) cache.delete(speciesId)
|
||||
})
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
/** The ready index, or null (tests and callers that need the sheet or nothing). */
|
||||
export async function loadSheetIndex(
|
||||
speciesId: string,
|
||||
): Promise<SheetIndex | null> {
|
||||
const load = await loadSheet(speciesId)
|
||||
return load.status === 'ready' ? load.index : null
|
||||
}
|
||||
|
||||
export function useSheet(speciesId: string | undefined): SheetState {
|
||||
const [state, setState] = useState<SheetState>({ status: 'loading' })
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
if (!speciesId) {
|
||||
@@ -42,13 +91,57 @@ export function useSheet(speciesId: string | undefined): SheetState {
|
||||
return
|
||||
}
|
||||
setState({ status: 'loading' })
|
||||
loadSheetIndex(speciesId).then((index) => {
|
||||
const retry = () => {
|
||||
void coreRuntime()
|
||||
.retry()
|
||||
.finally(() => setAttempt((n) => n + 1))
|
||||
}
|
||||
void loadSheet(speciesId).then((load) => {
|
||||
if (cancelled) return
|
||||
setState(index ? { status: 'ready', index } : { status: 'none' })
|
||||
if (load.status === 'ready' || load.status === 'none') setState(load)
|
||||
else if (load.status === 'invalid_sheet') setState({ status: load.status, retry })
|
||||
else setState({ status: 'core_unavailable', retry })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [speciesId, attempt])
|
||||
return state
|
||||
}
|
||||
|
||||
export type SheetAvailabilityState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'none' }
|
||||
| { status: 'ready'; sheet: SheetAvailability }
|
||||
|
||||
/** Whether the build carries a sheet for the species, without loading the core. */
|
||||
export function useSheetAvailability(
|
||||
speciesId: string | undefined,
|
||||
): SheetAvailabilityState {
|
||||
const [state, setState] = useState<SheetAvailabilityState>({
|
||||
status: 'loading',
|
||||
})
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
if (!speciesId) {
|
||||
setState({ status: 'none' })
|
||||
return
|
||||
}
|
||||
void provider
|
||||
.getReferenceSheet(speciesId)
|
||||
.then((bundle) => {
|
||||
if (cancelled) return
|
||||
setState(
|
||||
bundle
|
||||
? { status: 'ready', sheet: availabilityOf(bundle) }
|
||||
: { status: 'none' },
|
||||
)
|
||||
})
|
||||
// A failed chunk load leaves the page loading, as before R2; a reload fetches again.
|
||||
.catch(() => undefined)
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [speciesId])
|
||||
return state
|
||||
}
|
||||
@@ -1,33 +1,39 @@
|
||||
import {
|
||||
readReportDocument,
|
||||
ReportArchiveEnvelopeSchema,
|
||||
type Report,
|
||||
type ReportArchiveEnvelope,
|
||||
type ReportMigrationMap,
|
||||
} from '@faunosteo/domain'
|
||||
import type { Report, ReportArchiveEnvelope } from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* Where the session lives between renders. The report draft is mirrored on
|
||||
* every change; the archive an import brought along (the envelope of a
|
||||
* Step 6 PDF) is written only when the session starts or ends, so a stale
|
||||
* draft can still be rebased with the labels of its original sheet. One
|
||||
* implementation today (per-tab sessionStorage); the Supabase and outbox
|
||||
* adapters of later steps implement the same interfaces.
|
||||
* draft can still be rebased with the labels of its original sheet. The
|
||||
* texts are read raw: the core parses them (R2), and a text the running
|
||||
* build cannot read is set aside under a quarantine key instead of being
|
||||
* dropped. One implementation today (per-tab sessionStorage); the Supabase
|
||||
* and outbox adapters of later steps implement the same interfaces.
|
||||
*/
|
||||
|
||||
export interface ReportPersistence {
|
||||
load(map: ReportMigrationMap): Report | null
|
||||
/** The raw draft text, null when there is none. */
|
||||
loadText(): string | null
|
||||
save(report: Report | null): void
|
||||
}
|
||||
|
||||
export interface ArchivePersistence {
|
||||
load(): ReportArchiveEnvelope | null
|
||||
loadText(): string | null
|
||||
save(archive: ReportArchiveEnvelope | null): void
|
||||
}
|
||||
|
||||
export const DRAFT_KEY = 'osteo:draft'
|
||||
export const ARCHIVE_KEY = 'osteo:archive'
|
||||
|
||||
/** Unreadable texts and the pre-rebase draft, newest only (R2 plan rev 2). */
|
||||
export const QUARANTINE_KEYS = {
|
||||
draft: 'osteo:quarantine:draft',
|
||||
archive: 'osteo:quarantine:archive',
|
||||
draftPreRebase: 'osteo:quarantine:draft-pre-rebase',
|
||||
} as const
|
||||
|
||||
export type QuarantineSlot = keyof typeof QUARANTINE_KEYS
|
||||
|
||||
function storage(): Storage | null {
|
||||
return typeof sessionStorage === 'undefined' ? null : sessionStorage
|
||||
}
|
||||
@@ -47,33 +53,37 @@ function writeOrRemove(key: string, value: unknown): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies `raw` into its quarantine slot, then removes `source` (when given)
|
||||
* only if that copy succeeded: a full storage keeps the text where it was.
|
||||
* Returns whether the text is now in quarantine.
|
||||
*/
|
||||
export function quarantine(
|
||||
slot: QuarantineSlot,
|
||||
raw: string,
|
||||
source?: string,
|
||||
): boolean {
|
||||
const store = storage()
|
||||
if (!store) return false
|
||||
try {
|
||||
store.setItem(QUARANTINE_KEYS[slot], raw)
|
||||
} catch (err) {
|
||||
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
|
||||
return false
|
||||
}
|
||||
if (source) store.removeItem(source)
|
||||
return true
|
||||
}
|
||||
|
||||
export const sessionStoragePersistence: ReportPersistence = {
|
||||
load(map) {
|
||||
const raw = storage()?.getItem(DRAFT_KEY)
|
||||
if (!raw) return null
|
||||
try {
|
||||
return readReportDocument(JSON.parse(raw), map).report
|
||||
} catch (err) {
|
||||
if (import.meta.env.DEV) console.warn('osteo:draft ignored', err)
|
||||
return null
|
||||
}
|
||||
},
|
||||
loadText: () => storage()?.getItem(DRAFT_KEY) ?? null,
|
||||
save(report) {
|
||||
writeOrRemove(DRAFT_KEY, report)
|
||||
},
|
||||
}
|
||||
|
||||
export const sessionStorageArchivePersistence: ArchivePersistence = {
|
||||
load() {
|
||||
const raw = storage()?.getItem(ARCHIVE_KEY)
|
||||
if (!raw) return null
|
||||
try {
|
||||
const parsed = ReportArchiveEnvelopeSchema.safeParse(JSON.parse(raw))
|
||||
return parsed.success ? parsed.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
loadText: () => storage()?.getItem(ARCHIVE_KEY) ?? null,
|
||||
save(archive) {
|
||||
writeOrRemove(ARCHIVE_KEY, archive)
|
||||
},
|
||||
|
||||
@@ -1,4 +1,17 @@
|
||||
import { PractitionerSchema, type Practitioner } from '@faunosteo/domain'
|
||||
import { z } from 'zod'
|
||||
import type { Practitioner } from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* Prefill of the practitioner form (D-R7: form validation stays TypeScript, the core is
|
||||
* not loaded on the new-report page): the cached value is used only when it still has the
|
||||
* shape of the report's practitioner (name required, the rest optional text).
|
||||
*/
|
||||
const CachedPractitionerSchema: z.ZodType<Practitioner> = z.object({
|
||||
name: z.string().min(1),
|
||||
cabinet: z.string().optional(),
|
||||
contact: z.string().optional(),
|
||||
siret: z.string().optional(),
|
||||
})
|
||||
|
||||
const STORAGE_KEY = 'osteo:lastPractitioner'
|
||||
|
||||
@@ -8,7 +21,7 @@ export function readCachedPractitioner(): Practitioner | undefined {
|
||||
if (!raw) return undefined
|
||||
try {
|
||||
const data = JSON.parse(raw)
|
||||
const parsed = PractitionerSchema.safeParse(data)
|
||||
const parsed = CachedPractitionerSchema.safeParse(data)
|
||||
return parsed.success ? parsed.data : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
|
||||
+149
-123
@@ -1,21 +1,25 @@
|
||||
import { create } from 'zustand'
|
||||
import {
|
||||
rebaseReportOnSheet,
|
||||
REPORT_VERSION,
|
||||
type Animal,
|
||||
type NextAppointment,
|
||||
type Observation,
|
||||
type Owner,
|
||||
type Practitioner,
|
||||
type RebaseOutcome,
|
||||
type Report,
|
||||
type ReportArchiveEnvelope,
|
||||
type SheetRef,
|
||||
} from '@faunosteo/domain'
|
||||
import type {
|
||||
Animal,
|
||||
NewReportDraft,
|
||||
NextAppointment,
|
||||
Observation,
|
||||
Owner,
|
||||
Practitioner,
|
||||
RebaseOutcome,
|
||||
Report,
|
||||
ReportArchiveEnvelope,
|
||||
SheetRef,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import type { CoreOutcome } from '@faunosteo/core-wasm'
|
||||
import { reportOps } from '@/core/reportOps'
|
||||
import { generateId } from '@/lib/id'
|
||||
import { nowIso } from '@/lib/dates'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import {
|
||||
ARCHIVE_KEY,
|
||||
DRAFT_KEY,
|
||||
quarantine,
|
||||
sessionStorageArchivePersistence,
|
||||
sessionStoragePersistence,
|
||||
type ArchivePersistence,
|
||||
@@ -23,45 +27,60 @@ import {
|
||||
} from './persistence'
|
||||
|
||||
/**
|
||||
* In-memory report document (v3) and its editing actions. Observation-level
|
||||
* zone rules live in services/zoneInteraction; the store only replaces
|
||||
* documents. The per-tab draft is mirrored through the persistence adapter
|
||||
* and restored once the sheet is known; a draft written on another revision
|
||||
* of the sheet is rebased on restore. The archive an import brought along
|
||||
* (STEP6 §14 "App session") is kept beside the report for later operations
|
||||
* and written only when the session starts or ends.
|
||||
* In-memory report document (v3) and its editing actions. Every report that
|
||||
* enters the store comes from the core (R2): a new report, a restored draft,
|
||||
* an import; the observation list rules (add, remove, move) run in the core
|
||||
* too, and the editor's reducers hand back core-built observations. Form
|
||||
* values (identity, texts, an observation's comment, severity or free
|
||||
* findings) are plain assignments. An action whose core call fails changes
|
||||
* nothing and answers `{ ok: false }`; the caller tells the practitioner.
|
||||
* The per-tab draft is mirrored through the persistence adapter and restored
|
||||
* once the sheet is known; the archive an import brought along is kept
|
||||
* beside the report and written only when the session starts or ends.
|
||||
*/
|
||||
|
||||
/** What a new report needs before the store stamps version, id and dates. */
|
||||
export type NewReportDraft = Omit<
|
||||
Report,
|
||||
'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'
|
||||
>
|
||||
export type { NewReportDraft }
|
||||
|
||||
export interface ImportedSession {
|
||||
report: Report
|
||||
archive: ReportArchiveEnvelope | null
|
||||
}
|
||||
|
||||
export interface ActionResult {
|
||||
ok: boolean
|
||||
}
|
||||
|
||||
/** What a draft restore did; `null` from the action when there was nothing to restore. */
|
||||
export type RestoreResult =
|
||||
| { kind: 'restored'; rebase: RebaseOutcome }
|
||||
/** The draft is unreadable by this build: set aside under a quarantine key. */
|
||||
| { kind: 'quarantined' }
|
||||
/**
|
||||
* The draft is unreadable but could not be set aside (storage full): it stays in
|
||||
* `osteo:draft`, and the caller must not start anything that would overwrite it.
|
||||
*/
|
||||
| { kind: 'unreadable_kept' }
|
||||
/** The core failed: nothing read, nothing written, the draft is where it was. */
|
||||
| { kind: 'core_unavailable' }
|
||||
|
||||
export interface ReportStore {
|
||||
report: Report | null
|
||||
/** The envelope of the imported archive, as exported; null otherwise. */
|
||||
archive: ReportArchiveEnvelope | null
|
||||
activeObservationIndex: number
|
||||
initReport: (draft: NewReportDraft, sheet: SheetRef) => void
|
||||
hydrateReport: (report: Report) => void
|
||||
/** Opens an imported report (already rebased) with its archive. */
|
||||
initReport: (draft: NewReportDraft, sheet: SheetRef) => ActionResult
|
||||
/** Opens an imported report (read and rebased by the core) with its archive. */
|
||||
hydrateImport: (session: ImportedSession) => void
|
||||
/**
|
||||
* Restores the per-tab draft on the loaded sheet, rebasing it when it was
|
||||
* written on another revision; a no-op when a report is already open.
|
||||
* Returns the rebase outcome, null when nothing was restored.
|
||||
* written on another revision; a no-op (null) when a report is already open
|
||||
* or there is no draft.
|
||||
*/
|
||||
restoreDraft: (index: SheetIndex) => RebaseOutcome | null
|
||||
addObservation: () => void
|
||||
removeObservation: (index: number) => void
|
||||
moveObservationUp: (index: number) => void
|
||||
moveObservationDown: (index: number) => void
|
||||
restoreDraft: (index: SheetIndex) => RestoreResult | null
|
||||
addObservation: () => ActionResult
|
||||
removeObservation: (index: number) => ActionResult
|
||||
moveObservationUp: (index: number) => ActionResult
|
||||
moveObservationDown: (index: number) => ActionResult
|
||||
updateObservation: (index: number, obs: Observation) => void
|
||||
setActiveObservation: (index: number) => void
|
||||
setPractitioner: (next: Practitioner) => void
|
||||
@@ -73,47 +92,68 @@ export interface ReportStore {
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
export function emptyObservation(): Observation {
|
||||
return {
|
||||
id: generateId(),
|
||||
zones: [],
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
}
|
||||
}
|
||||
|
||||
/** A fresh v3 document: the store stamps version, id, dates and the sheet. */
|
||||
function newReport(draft: NewReportDraft, sheet: SheetRef): Report {
|
||||
return {
|
||||
...draft,
|
||||
version: REPORT_VERSION,
|
||||
id: generateId(),
|
||||
createdAt: nowIso(),
|
||||
sheet,
|
||||
observations:
|
||||
draft.observations.length === 0
|
||||
? [emptyObservation()]
|
||||
: 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
|
||||
}
|
||||
|
||||
type Patch = Partial<
|
||||
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'>
|
||||
>
|
||||
type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
|
||||
type Getter = () => ReportStore
|
||||
|
||||
const OK: ActionResult = { ok: true }
|
||||
const FAILED: ActionResult = { ok: false }
|
||||
|
||||
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
|
||||
set((s) => (s.report ? update(s.report, s) : s))
|
||||
}
|
||||
|
||||
/** Applies a core-built report with its active index; nothing changes on failure. */
|
||||
function applyCore(
|
||||
set: Setter,
|
||||
get: Getter,
|
||||
run: (report: Report) => CoreOutcome<Report>,
|
||||
active: (next: Report, s: ReportStore) => number,
|
||||
): ActionResult {
|
||||
const state = get()
|
||||
if (!state.report) return OK
|
||||
const outcome = run(state.report)
|
||||
if (!outcome.ok) return FAILED
|
||||
set(() => ({
|
||||
report: outcome.value,
|
||||
activeObservationIndex: active(outcome.value, state),
|
||||
}))
|
||||
return OK
|
||||
}
|
||||
|
||||
/** Reads the draft through the core; unreadable content goes to quarantine, never away. */
|
||||
function restore(
|
||||
index: SheetIndex,
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
): { result: RestoreResult; patch?: Patch } | null {
|
||||
const draft = persistence.loadText()
|
||||
if (draft === null) return null
|
||||
const archiveText = archives.loadText()
|
||||
const outcome = index.ops.restoreDraft(draft, archiveText)
|
||||
if (!outcome.ok) {
|
||||
// Only an unreadable draft is set aside; a core or sheet failure leaves it in place.
|
||||
if (outcome.kind !== 'invalid' && outcome.kind !== 'unsupported_version') {
|
||||
return { result: { kind: 'core_unavailable' } }
|
||||
}
|
||||
const setAside = quarantine('draft', draft, DRAFT_KEY)
|
||||
return { result: { kind: setAside ? 'quarantined' : 'unreadable_kept' } }
|
||||
}
|
||||
const { rebase, archive, archiveRejected } = outcome.value
|
||||
if (archiveRejected && archiveText !== null) {
|
||||
quarantine('archive', archiveText, ARCHIVE_KEY)
|
||||
}
|
||||
if (rebase.rebased && rebase.unresolvedZones + rebase.unresolvedFindings > 0) {
|
||||
quarantine('draftPreRebase', draft)
|
||||
}
|
||||
return {
|
||||
result: { kind: 'restored', rebase },
|
||||
patch: { report: rebase.report, archive, activeObservationIndex: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
export function createReportStore(
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
@@ -129,78 +169,64 @@ export function createReportStore(
|
||||
archive: null,
|
||||
activeObservationIndex: 0,
|
||||
|
||||
initReport: (draft, sheet) =>
|
||||
set(
|
||||
withArchive(
|
||||
{ report: newReport(draft, sheet), activeObservationIndex: 0 },
|
||||
null,
|
||||
),
|
||||
),
|
||||
|
||||
hydrateReport: (report) =>
|
||||
set(withArchive({ report, activeObservationIndex: 0 }, null)),
|
||||
initReport: (draft, sheet) => {
|
||||
const outcome = reportOps.newReport({
|
||||
draft,
|
||||
sheet,
|
||||
id: generateId(),
|
||||
createdAt: nowIso(),
|
||||
observationId: generateId(),
|
||||
})
|
||||
if (!outcome.ok) return FAILED
|
||||
set(withArchive({ report: outcome.value, activeObservationIndex: 0 }, null))
|
||||
return OK
|
||||
},
|
||||
|
||||
hydrateImport: ({ report, archive }) =>
|
||||
set(withArchive({ report, activeObservationIndex: 0 }, archive)),
|
||||
|
||||
restoreDraft: (index) => {
|
||||
if (get().report) return null
|
||||
const draft = persistence.load(index.sheet.migrationMap)
|
||||
if (!draft) return null
|
||||
const archive = archives.load()
|
||||
const rebase = rebaseReportOnSheet(
|
||||
draft,
|
||||
index,
|
||||
archive?.sheetSnapshot ?? null,
|
||||
)
|
||||
set({ report: rebase.report, archive, activeObservationIndex: 0 })
|
||||
return rebase
|
||||
const restored = restore(index, persistence, archives)
|
||||
if (!restored) return null
|
||||
if (restored.patch) set(restored.patch)
|
||||
return restored.result
|
||||
},
|
||||
|
||||
addObservation: () =>
|
||||
onReport(set, (r) => {
|
||||
const observations = [...r.observations, emptyObservation()]
|
||||
return {
|
||||
report: { ...r, observations },
|
||||
activeObservationIndex: observations.length - 1,
|
||||
}
|
||||
}),
|
||||
applyCore(
|
||||
set,
|
||||
get,
|
||||
(r) => reportOps.addObservation(r, generateId()),
|
||||
(next) => next.observations.length - 1,
|
||||
),
|
||||
|
||||
removeObservation: (index) =>
|
||||
onReport(set, (r, s) => {
|
||||
const observations = r.observations.filter((_, i) => i !== index)
|
||||
const active = Math.min(
|
||||
s.activeObservationIndex,
|
||||
Math.max(0, observations.length - 1),
|
||||
)
|
||||
return {
|
||||
report: { ...r, observations },
|
||||
activeObservationIndex: active,
|
||||
}
|
||||
}),
|
||||
applyCore(
|
||||
set,
|
||||
get,
|
||||
(r) => reportOps.removeObservation(r, index),
|
||||
(next, s) =>
|
||||
Math.min(
|
||||
s.activeObservationIndex,
|
||||
Math.max(0, next.observations.length - 1),
|
||||
),
|
||||
),
|
||||
|
||||
moveObservationUp: (index) =>
|
||||
onReport(set, (r) =>
|
||||
index <= 0
|
||||
? {}
|
||||
: {
|
||||
report: {
|
||||
...r,
|
||||
observations: swapped(r.observations, index - 1, index),
|
||||
},
|
||||
},
|
||||
applyCore(
|
||||
set,
|
||||
get,
|
||||
(r) => reportOps.moveObservation(r, index, 'up'),
|
||||
(_, s) => s.activeObservationIndex,
|
||||
),
|
||||
|
||||
moveObservationDown: (index) =>
|
||||
onReport(set, (r) =>
|
||||
index >= r.observations.length - 1
|
||||
? {}
|
||||
: {
|
||||
report: {
|
||||
...r,
|
||||
observations: swapped(r.observations, index, index + 1),
|
||||
},
|
||||
},
|
||||
applyCore(
|
||||
set,
|
||||
get,
|
||||
(r) => reportOps.moveObservation(r, index, 'down'),
|
||||
(_, s) => s.activeObservationIndex,
|
||||
),
|
||||
|
||||
updateObservation: (index, obs) =>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { CoreRuntime } from '@faunosteo/core-wasm'
|
||||
import { nodeCoreRuntime } from '@faunosteo/core-wasm/node'
|
||||
|
||||
/** A loaded runtime on the shipped build (the package's Node source). */
|
||||
export function testCoreRuntime(): Promise<CoreRuntime> {
|
||||
return nodeCoreRuntime('pkg')
|
||||
}
|
||||
|
||||
/** A runtime whose module never loads (CSP refusal, network failure). */
|
||||
export function unavailableCoreRuntime(): CoreRuntime {
|
||||
return new CoreRuntime({
|
||||
compile: () => Promise.reject(new WebAssembly.CompileError('blocked')),
|
||||
importGlue: () => Promise.reject(new TypeError('blocked')),
|
||||
})
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import {
|
||||
readReportDocument,
|
||||
ReportSchema,
|
||||
type Report,
|
||||
} from '@faunosteo/domain'
|
||||
import type { Report } from '@faunosteo/core-wasm/types'
|
||||
import { importAttachment } from '@/pdf/import'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { FIXTURES_DIR } from './goldens'
|
||||
import {
|
||||
@@ -16,7 +13,9 @@ import {
|
||||
/**
|
||||
* The three reports the Step 6 goldens and the R2 envelope freeze are drawn
|
||||
* from: the Step 5 v2 archive fixture migrated, the v3 demo report, and a v2
|
||||
* report whose sphenoid and ssb findings the migration cannot place.
|
||||
* report whose sphenoid and ssb findings the migration cannot place. Since
|
||||
* R2 they are read the way the application reads an attachment: the core's
|
||||
* layered reading (v3 parsed, v2 migrated through the sheet's map).
|
||||
*/
|
||||
|
||||
export const GOLDEN_REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
|
||||
@@ -38,21 +37,20 @@ function buildV2Unresolved(sheet: SheetIndex) {
|
||||
(l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb',
|
||||
)
|
||||
const resolved = leaves.find((l) => l.zoneId === 'frontal')!
|
||||
return readReportDocument(
|
||||
return importAttachment(
|
||||
leavesAsV2Report([...unresolvedFamilies, resolved]),
|
||||
sheet.sheet.migrationMap,
|
||||
)
|
||||
sheet,
|
||||
).read
|
||||
}
|
||||
|
||||
export function buildGoldenReports(sheet: SheetIndex): GoldenReports {
|
||||
const v2unresolved = buildV2Unresolved(sheet)
|
||||
return {
|
||||
reports: {
|
||||
v2full: readReportDocument(
|
||||
readJson('report-v2.full.json'),
|
||||
sheet.sheet.migrationMap,
|
||||
).report,
|
||||
demo: ReportSchema.parse(readJson('report-v3.demo.json')),
|
||||
v2full: importAttachment(readJson('report-v2.full.json'), sheet).read
|
||||
.report,
|
||||
demo: importAttachment(readJson('report-v3.demo.json'), sheet).read
|
||||
.report,
|
||||
v2unresolved: v2unresolved.report,
|
||||
},
|
||||
unresolvedOfV2Unresolved: v2unresolved.unresolvedFindings,
|
||||
|
||||
@@ -17,8 +17,11 @@ import type {
|
||||
Observation,
|
||||
Report,
|
||||
SheetSnapshot,
|
||||
} from '@faunosteo/domain'
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
|
||||
|
||||
/** The engine's own (Zod-inferred) types of the same JSON contracts. */
|
||||
type EngineView = Parameters<typeof composeHighlightedViewSvg>
|
||||
import { nologosBranding } from './sheet'
|
||||
|
||||
/**
|
||||
@@ -241,7 +244,11 @@ export function snapshotView(
|
||||
observation: Observation,
|
||||
viewId: string,
|
||||
): ViewSnapshot {
|
||||
const svg = composeHighlightedViewSvg(sheet, viewId, observation)
|
||||
const svg = composeHighlightedViewSvg(
|
||||
sheet as EngineView[0],
|
||||
viewId,
|
||||
observation as EngineView[2],
|
||||
)
|
||||
const root = new DOMParser().parseFromString(
|
||||
svg,
|
||||
'image/svg+xml',
|
||||
|
||||
@@ -1,21 +1,15 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolve } from 'node:path'
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
ReportV2Schema,
|
||||
type AnatomicalSheetDocument,
|
||||
type FindingCategory,
|
||||
type FindingNode,
|
||||
type ObservationV2,
|
||||
type ReportV2,
|
||||
} from '@faunosteo/domain'
|
||||
import type { LocalizedText } from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* The legacy catalog as the application's archive knew it: every leaf of the
|
||||
* generated baseline (`legacy-import/document.json`) becomes a Report v2
|
||||
* finding, grouped in one observation per zone. Mirrors the anatomy package
|
||||
* helper of the same name; both read the committed seed, never a copy.
|
||||
* helper of the same name; both read the committed seed, never a copy. The
|
||||
* baseline is read as its authoring form (leaves carry no `children` key);
|
||||
* the core reads the v2 report built from it.
|
||||
*/
|
||||
|
||||
const BASELINE = resolve(
|
||||
@@ -23,6 +17,18 @@ const BASELINE = resolve(
|
||||
'../../../../../supabase/seed/anatomical-sheets/equine/legacy-import/document.json',
|
||||
)
|
||||
|
||||
/** A category or node of the baseline in its authoring form. */
|
||||
interface BaselineNode {
|
||||
id: string
|
||||
name: LocalizedText
|
||||
requires_vet_referral?: boolean
|
||||
children?: BaselineNode[]
|
||||
}
|
||||
|
||||
export interface LegacyBaseline {
|
||||
finding_zones: { id: string; categories: BaselineNode[] }[]
|
||||
}
|
||||
|
||||
export interface LegacyLeaf {
|
||||
zoneId: string
|
||||
path: string[]
|
||||
@@ -30,25 +36,49 @@ export interface LegacyLeaf {
|
||||
vet: boolean
|
||||
}
|
||||
|
||||
export function loadLegacyBaseline(): AnatomicalSheetDocument {
|
||||
return AnatomicalSheetDocumentSchema.parse(
|
||||
JSON.parse(readFileSync(BASELINE, 'utf8')),
|
||||
)
|
||||
/** A Report v2 document as the deployed application wrote it (input of the migration). */
|
||||
export interface ReportV2Fixture {
|
||||
version: 2
|
||||
id: string
|
||||
createdAt: string
|
||||
date: string
|
||||
practitioner: { name: string }
|
||||
animal: { speciesId: string; name: string }
|
||||
owner: { name: string }
|
||||
observations: {
|
||||
id: string
|
||||
zones: unknown[]
|
||||
findings: {
|
||||
zoneId: string
|
||||
path: string[]
|
||||
labelFrSnapshot: string
|
||||
labelEnSnapshot: string
|
||||
requiresVetReferral?: true
|
||||
}[]
|
||||
freeTextFindings: string[]
|
||||
comment: string
|
||||
}[]
|
||||
conclusion: string
|
||||
recommendations: string
|
||||
}
|
||||
|
||||
export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
|
||||
export function loadLegacyBaseline(): LegacyBaseline {
|
||||
return JSON.parse(readFileSync(BASELINE, 'utf8')) as LegacyBaseline
|
||||
}
|
||||
|
||||
export function legacyLeaves(doc: LegacyBaseline): LegacyLeaf[] {
|
||||
const out: LegacyLeaf[] = []
|
||||
const walk = (
|
||||
zoneId: string,
|
||||
nodes: readonly (FindingCategory | FindingNode)[],
|
||||
nodes: readonly BaselineNode[],
|
||||
prefix: string[],
|
||||
) => {
|
||||
for (const node of nodes) {
|
||||
const path = [...prefix, node.id]
|
||||
if (node.children.length > 0) walk(zoneId, node.children, path)
|
||||
const children = node.children ?? []
|
||||
if (children.length > 0) walk(zoneId, children, path)
|
||||
else {
|
||||
const vet =
|
||||
'requires_vet_referral' in node && node.requires_vet_referral
|
||||
const vet = node.requires_vet_referral === true
|
||||
out.push({ zoneId, path, name: node.name, vet })
|
||||
}
|
||||
}
|
||||
@@ -57,8 +87,8 @@ export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
|
||||
return out
|
||||
}
|
||||
|
||||
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
|
||||
const byZone = new Map<string, ObservationV2>()
|
||||
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2Fixture {
|
||||
const byZone = new Map<string, ReportV2Fixture['observations'][number]>()
|
||||
for (const leaf of leaves) {
|
||||
let obs = byZone.get(leaf.zoneId)
|
||||
if (!obs) {
|
||||
@@ -76,10 +106,10 @@ export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
|
||||
path: leaf.path,
|
||||
labelFrSnapshot: leaf.name.fr,
|
||||
labelEnSnapshot: leaf.name.en || leaf.name.fr,
|
||||
...(leaf.vet ? { requiresVetReferral: true } : {}),
|
||||
...(leaf.vet ? { requiresVetReferral: true as const } : {}),
|
||||
})
|
||||
}
|
||||
return ReportV2Schema.parse({
|
||||
return {
|
||||
version: 2,
|
||||
id: 'all-leaves',
|
||||
createdAt: '2026-10-10T00:00:00Z',
|
||||
@@ -90,5 +120,5 @@ export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
|
||||
observations: [...byZone.values()],
|
||||
conclusion: '',
|
||||
recommendations: '',
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
import {
|
||||
buildSheetSnapshot,
|
||||
ENVELOPE_FORMAT,
|
||||
ENVELOPE_VERSION,
|
||||
REPORT_VERSION,
|
||||
type Branding,
|
||||
type Observation,
|
||||
type Report,
|
||||
type ReportArchiveEnvelope,
|
||||
} from '@faunosteo/domain'
|
||||
import type {
|
||||
Branding,
|
||||
FindingCategory,
|
||||
FindingNode,
|
||||
Observation,
|
||||
Report,
|
||||
ReportArchiveEnvelope,
|
||||
SheetSnapshot,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import { defaultPdfLabels } from '@faunosteo/pdf'
|
||||
import type { SheetIndexData } from '@faunosteo/core-wasm/types'
|
||||
import type { ReportMigrationMap } from '@faunosteo/core-wasm/n-1'
|
||||
import { coreRuntime } from '@/core/runtime'
|
||||
import { SheetOps } from '@/core/sheetOps'
|
||||
import { bundledSheetProvider, type BundledSheetData } from '@/sheets/provider'
|
||||
import { loadSheetIndex } from '@/sheets/useSheet'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { SheetIndex } from '@/services/sheetIndex'
|
||||
|
||||
/** The bundled reference draft (vitest runs the sheet-bundle plugin in draft mode). */
|
||||
export async function loadTestSheet(): Promise<SheetIndex> {
|
||||
@@ -28,7 +32,7 @@ export function minimalReport(
|
||||
patch: Partial<Report> = {},
|
||||
): Report {
|
||||
return {
|
||||
version: REPORT_VERSION,
|
||||
version: 3,
|
||||
id: 'r1',
|
||||
createdAt: '2026-10-10T10:00:00Z',
|
||||
date: '2026-10-10',
|
||||
@@ -63,19 +67,70 @@ export function nologosBranding(): Branding {
|
||||
}
|
||||
}
|
||||
|
||||
/** The snapshot of `sheet` an archive of `report` carries, built by the core. */
|
||||
export function sheetSnapshot(
|
||||
sheet: SheetIndex,
|
||||
report: Report,
|
||||
): SheetSnapshot {
|
||||
const outcome = sheet.ops.snapshot(report)
|
||||
if (!outcome.ok) throw new Error(`snapshot failed: ${outcome.kind}`)
|
||||
return outcome.value
|
||||
}
|
||||
|
||||
/** A valid Step 6 envelope for `report`, snapshotted on `sheet` (no logos). */
|
||||
export function archiveEnvelope(
|
||||
sheet: SheetIndex,
|
||||
report: Report,
|
||||
): ReportArchiveEnvelope {
|
||||
return {
|
||||
format: ENVELOPE_FORMAT,
|
||||
envelopeVersion: ENVELOPE_VERSION,
|
||||
format: 'faunosteo-report-archive',
|
||||
envelopeVersion: 1,
|
||||
exportedAt: '2026-10-11T12:00:00.000Z',
|
||||
locale: 'fr',
|
||||
report,
|
||||
sheetSnapshot: buildSheetSnapshot(sheet.sheet, report),
|
||||
sheetSnapshot: sheetSnapshot(sheet, report),
|
||||
branding: nologosBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
}
|
||||
}
|
||||
|
||||
/** The bundled migration map, for the frozen N-1 readers (the core keeps its own copy). */
|
||||
export async function bundledMigrationMap(): Promise<ReportMigrationMap> {
|
||||
return (await bundledSheet()).migrationMap as ReportMigrationMap
|
||||
}
|
||||
|
||||
/**
|
||||
* The category or node at a path of a finding zone (first match at each level, as the
|
||||
* core's walk), read from the parsed document: the tests' view of what `hasNode` answers.
|
||||
*/
|
||||
export function findingNodeAt(
|
||||
sheet: SheetIndex,
|
||||
zoneId: string,
|
||||
path: readonly string[],
|
||||
): FindingCategory | FindingNode | undefined {
|
||||
if (path.length === 0) return 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
|
||||
}
|
||||
|
||||
/** The bundled payload as the provider hands it to the core. */
|
||||
export async function bundledSheet(): Promise<BundledSheetData> {
|
||||
const bundle = await bundledSheetProvider.getReferenceSheet('equine')
|
||||
if (!bundle) throw new Error('bundled sheet missing: run pnpm import:equine')
|
||||
return bundle
|
||||
}
|
||||
|
||||
/** Another sheet loaded in the core (a revised catalog), outside the provider's cache. */
|
||||
export function sheetFromBundle(bundle: BundledSheetData): SheetIndex {
|
||||
const session = coreRuntime().sheet(JSON.stringify(bundle))
|
||||
const data = session.call<SheetIndexData>('index_data', '')
|
||||
if (!data.ok) throw new Error(`sheet refused by the core: ${data.kind}`)
|
||||
return new SheetIndex(data.value, bundle.assets, new SheetOps(session))
|
||||
}
|
||||
@@ -1 +1,6 @@
|
||||
import '@testing-library/jest-dom'
|
||||
import { setCoreRuntime } from '@/core/runtime'
|
||||
import { testCoreRuntime } from './helpers/core'
|
||||
|
||||
// The application runs on the real core (R2): the shipped wasm build, loaded from disk.
|
||||
setCoreRuntime(await testCoreRuntime())
|
||||
@@ -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('')
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
})
|
||||
@@ -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.
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
|
||||
@@ -14,6 +14,8 @@ export default defineConfig({
|
||||
environment: 'happy-dom',
|
||||
globals: true,
|
||||
setupFiles: ['tests/setup.ts'],
|
||||
// Refuses to run on a missing or stale core module (pnpm wasm:build).
|
||||
globalSetup: ['../../packages/core-wasm/tests/global-setup.ts'],
|
||||
include: ['tests/**/*.test.ts', 'tests/**/*.test.tsx'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
|
||||
@@ -5,20 +5,22 @@
|
||||
*/
|
||||
import { existsSync } from 'node:fs'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
import { CoreRuntime, type CoreSource, type GlueModule } from './runtime'
|
||||
|
||||
export type CoreBuild = 'pkg' | 'pkg-proofs'
|
||||
|
||||
const glueUrl = (build: CoreBuild) =>
|
||||
new URL(`../${build}/faunosteo_wasm.js`, import.meta.url)
|
||||
const wasmUrl = (build: CoreBuild) =>
|
||||
new URL(`../${build}/faunosteo_wasm_bg.wasm`, import.meta.url)
|
||||
// Paths from this file's own location: Vite (happy-dom suites) rewrites the
|
||||
// `new URL(relative, import.meta.url)` form into a dev-server URL, which Node cannot read.
|
||||
const PACKAGE_DIR = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const gluePath = (build: CoreBuild) =>
|
||||
join(PACKAGE_DIR, build, 'faunosteo_wasm.js')
|
||||
|
||||
/** Path of a built module on disk (size measurements). */
|
||||
export function coreWasmPath(build: CoreBuild = 'pkg'): string {
|
||||
return fileURLToPath(wasmUrl(build))
|
||||
return join(PACKAGE_DIR, build, 'faunosteo_wasm_bg.wasm')
|
||||
}
|
||||
|
||||
/** True when `pnpm wasm:build` has produced the module. */
|
||||
@@ -35,9 +37,8 @@ export function nodeCoreSource(build: CoreBuild = 'pkg'): CoreSource {
|
||||
WebAssembly.compile(await readFile(coreWasmPath(build))),
|
||||
importGlue: async () => {
|
||||
imports += 1
|
||||
return (await import(
|
||||
`${glueUrl(build).href}?instance=${imports}`
|
||||
)) as GlueModule
|
||||
const url = `${pathToFileURL(gluePath(build)).href}?instance=${imports}`
|
||||
return (await import(/* @vite-ignore */ url)) as GlueModule
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user