Files
faunosteo/apps/app/tests/unit/routes.HomeRoute.archive.test.tsx
T

270 lines
8.8 KiB
TypeScript

/**
* T15 (STEP6 §7, §16): the home route on Step 6 archives, with
* `importReportFromPdf` mocked. 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,
ArchiveReadOutcome,
Report,
ReportArchiveEnvelope,
} from '@faunosteo/domain'
import HomeRoute from '@/app/routes/HomeRoute'
import { ImportError, importReportFromPdf } from '@/pdf/import'
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 { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
importReportFromPdf: vi.fn(),
}))
const importMock = vi.mocked(importReportFromPdf)
let sheet: SheetIndex
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())
importMock.mockReset()
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
})
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: [
{
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 }
}
async function mountAndPickPdf(): 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"]')!
const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', {
type: 'application/pdf',
})
fireEvent.change(input, { target: { files: [file] } })
}
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)
importMock.mockResolvedValue(archived(report, archive))
await mountAndPickPdf()
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()
importMock.mockResolvedValue(archived(report, archive))
await mountAndPickPdf()
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
importMock.mockResolvedValue(archived(report, archive))
await mountAndPickPdf()
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()
importMock.mockResolvedValue(
archived(report, null, { snapshotRejected: 'caps' }),
)
await mountAndPickPdf()
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 () => {
importMock.mockRejectedValue(new ImportError('attachment_stripped'))
await mountAndPickPdf()
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()
})
})