Files
faunosteo/apps/app/tests/unit/routes.HomeRoute.archive.test.tsx
T
bchanot 6d1cce6e06 feat(app): R4.3b/c import worker, client, controller; HomeRoute on the disposable worker
Protocol v1 (task → ready → result | failed with phase and kind), the worker entry with
the glue bundled statically and the page's compiled Module posted, the file streamed into
the module's memory; client with start and task timers (paused while hidden), settle-once,
terminate always, error events never masked; module-level controller (one import at a
time, cancel on leaving Home, worker chunk prefetched once the engine is loaded); the
settlement mapped to the B.1.8 messages (OD-5: a trap, a timeout or an unreadable file is
« Erreur de lecture du PDF. », never a corrupt PDF). HomeRoute keeps its routing and size
pre-checks, loads its own index after acceptance, drops a result when the session changed.
Tests: handler and client in-process, the corpus message test (O8 51, O7 stored inputs,
O2/O3/Step 5), the six existing suites migrated to the real worker logic.
2026-10-18 18:10:42 +02:00

252 lines
8.8 KiB
TypeScript

/**
* T15 (STEP6 §7, §16): the home route on Step 6 archives, each envelope
* written into a minimal Faunosteo PDF (`helpers/pdfBytes`) and read by the
* import worker (R4.3: the real worker logic in-process on the shipped
* module): the byte scan, the layered read and the rebase all run in the
* core. 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
* ref updated) and the alert says degraded with the count; a rebase that
* resolved everything stays complete. Snapshot rejected: degraded with the
* reason label. Attachment stripped: its error message.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
beforeEach,
afterEach,
} from 'vitest'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type {
Annotation,
Report,
ReportArchiveEnvelope,
} from '@faunosteo/core-wasm/types'
import HomeRoute from '@/app/routes/HomeRoute'
import { useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY } from '@/state/persistence'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { useInProcessImportWorker } from '../helpers/importWorker'
import { archivePdf, pdfFile, strippedPdf } from '../helpers/pdfBytes'
import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
let restoreSpawn: () => void
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
vi.stubGlobal('alert', vi.fn())
restoreSpawn = useInProcessImportWorker().restore
})
afterEach(() => {
restoreSpawn()
cleanup()
vi.unstubAllGlobals()
})
const OTHER_SHA = 'b'.repeat(64)
function reportWithHip(): Report {
return minimalReport(sheet, {
observations: [
{
id: 'o1',
zones: [{ annotationId: 'hip', viewId: 'main', side: 'left' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
})
}
/**
* A report written on another revision of the sheet: a zone and a finding
* path the loaded sheet does not hold, next to a zone it does. Its archived
* snapshot names the lost zone so the rebase can fill the label.
*/
function staleReportAndArchive(): {
report: Report
archive: ReportArchiveEnvelope
} {
const report = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
observations: [
{
id: 'o-stale',
zones: [
{ annotationId: 'point-gone', viewId: 'main' },
{ annotationId: 'hip', viewId: 'main', side: 'left' },
],
findings: [
{
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'gone'],
labelFrSnapshot: 'Constat disparu',
labelEnSnapshot: 'Gone finding',
},
],
freeTextFindings: [],
comment: '',
},
],
})
const archive = archiveEnvelope(sheet, report)
archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA
const gone: Annotation = {
...sheet.annotation('hip')!,
id: 'point-gone',
name: { fr: 'Point disparu', en: 'Gone point' },
} as Annotation
archive.sheetSnapshot.document.annotations.push(gone)
return { report, archive }
}
/** Home mounted, then `pdf` picked: a Faunosteo PDF the worker reads in full. */
async function mountAndPickPdf(pdf: Uint8Array<ArrayBuffer>): Promise<void> {
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 input = document.querySelector('input[type="file"]')!
fireEvent.change(input, { target: { files: [pdfFile(pdf)] } })
}
/** The PDF the app exports for `archive`: the envelope as its attachment. */
const pdfOf = (archive: ReportArchiveEnvelope) =>
archivePdf(JSON.stringify(archive))
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 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)
await mountAndPickPdf(pdfOf(archive))
await screen.findByTestId('editor-route')
const state = useReportStore.getState()
expect(state.report).toEqual(report)
expect(state.archive).toEqual(archive)
expect(JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!).report.id).toBe(
report.id,
)
expect(alertMock()).toHaveBeenCalledTimes(1)
expect(alertLines()).toEqual([
fr['home.import.complete'],
fr['home.import.archive_ok'],
])
})
it('other sheet: rebases onto the loaded sheet, labels from the archived snapshot, alert with the count', async () => {
const { report, archive } = staleReportAndArchive()
// The attachment is the envelope of the stale report (read by the core).
expect(archive.report).toBe(report)
await mountAndPickPdf(pdfOf(archive))
await screen.findByTestId('editor-route')
const opened = useReportStore.getState().report!
expect(opened.sheet).toEqual(sheet.sheet.ref)
const [gone, hip] = opened.observations[0]!.zones
expect(gone).toMatchObject({
unresolved: true,
labelFrSnapshot: 'Point disparu',
labelEnSnapshot: 'Gone point',
})
expect(hip!.unresolved).toBeUndefined()
expect(opened.observations[0]!.findings[0]).toMatchObject({
unresolved: true,
labelFrSnapshot: 'Constat disparu',
})
// The archive stays as exported, never rebased.
expect(useReportStore.getState().archive).toEqual(archive)
expect(alertMock()).toHaveBeenCalledTimes(1)
expect(alertLines()).toEqual([
fr['home.import.degraded'],
fr['home.import.archive_ok'],
fr['home.import.rebased']!.replace('{count}', '2'),
])
})
it('other sheet, everything resolved: complete headline, the rebased line says 0', async () => {
const report = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
observations: reportWithHip().observations,
})
const archive = archiveEnvelope(sheet, report)
archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA
await mountAndPickPdf(pdfOf(archive))
await screen.findByTestId('editor-route')
const opened = useReportStore.getState().report!
expect(opened.sheet).toEqual(sheet.sheet.ref)
expect(opened.observations[0]!.zones[0]!.unresolved).toBeUndefined()
expect(alertMock()).toHaveBeenCalledTimes(1)
expect(alertLines()).toEqual([
fr['home.import.complete'],
fr['home.import.archive_ok'],
fr['home.import.rebased']!.replace('{count}', '0'),
])
})
it('snapshot rejected: the report opens, the alert names the reason, no archive kept', async () => {
const report = reportWithHip()
// 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)
await mountAndPickPdf(pdfOf(archive))
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(report)
expect(useReportStore.getState().archive).toBeNull()
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()
expect(alertMock()).toHaveBeenCalledTimes(1)
expect(alertLines()).toEqual([
fr['home.import.degraded'],
fr['home.import.snapshot_rejected']!.replace(
'{reason}',
fr['home.import.snapshot_reason.caps']!,
),
])
})
it('attachment_stripped → its error message, nothing opened', async () => {
// The stamp says Faunosteo, the embedded file is gone (a tool rewrote the PDF).
await mountAndPickPdf(strippedPdf())
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(
fr['home.import.error_attachment_stripped'],
)
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
expect(alertMock()).not.toHaveBeenCalled()
})
})