/**
* 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 (R4.3: after the import worker, which loads its own
* module, read the file).
*/
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
onTestFinished,
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 { 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 { FIXTURES_DIR } from '../helpers/goldens'
import { useInProcessImportWorker } from '../helpers/importWorker'
import {
emptyObservation,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
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, sheet)).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, sheet)).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(
} />
} />
,
)
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 () => {
const { workers, restore } = useInProcessImportWorker()
onTestFinished(restore)
setCoreRuntime(unavailableCoreRuntime())
setSheetProvider(bundledSheetProvider)
render(
} />
} />
,
)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
const bytes = readFileSync(resolve(FIXTURES_DIR, 'report-v3.bare.pdf'))
const file = new File([bytes], 'bilan.pdf', { type: 'application/pdf' })
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [file] },
})
await screen.findByText(fr['home.import.error_core_unavailable']!)
// The worker read the file; the page's core, needed to open it, did not load.
expect(workers[0]!.sequence()).toEqual(['ready', 'result'])
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
})