fix(app): rescue copy importable, trapping draft held, replace confirmed
The JSON rescue copy could not be restored in the app, a draft that traps the engine left the tab on a reload screen and spent a recovery on every read, and an unsaved or in-progress report could be lost by a reload outside the editor or by New report / Import without warning. Home import reads the copy (content-sniffed, 16 MiB cap, strict UTF-8) through the core's draft.restore before any session change; a trapping (draft, archive) pair is held in the resolution panel and only re-read on Retry; ReplaceSessionDialog guards New report and Import; the beforeunload guard is app-wide while unsaved. Supersedes BDR-055's "never held" for `internal` only.
This commit is contained in:
1 parent
9464651140
commit
9bd9acaf58
22 files changed
+1090
-68
No files matched your search
@@ -16,6 +16,7 @@ import ResetPasswordRoute from './routes/auth/ResetPasswordRoute'
|
||||
import AuthCallbackRoute from './routes/auth/AuthCallbackRoute'
|
||||
import DashboardRoute from './routes/app/DashboardRoute'
|
||||
import AccountRoute from './routes/app/AccountRoute'
|
||||
import { useUnsavedGuard } from './useUnsavedGuard'
|
||||
|
||||
/** The local tool: unchanged routes, no account needed, shared footer. */
|
||||
function LocalToolShell() {
|
||||
@@ -58,6 +59,8 @@ export function AppRoutes() {
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
// The store is not a context: one call above the route tree guards every page.
|
||||
useUnsavedGuard()
|
||||
return (
|
||||
<ConfigProvider>
|
||||
<AuthProvider>
|
||||
|
||||
@@ -20,7 +20,6 @@ import HeldSessionPanel from '@/components/report/HeldSessionPanel'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import Button from '@/components/ui/Button'
|
||||
import {
|
||||
isUnsaved,
|
||||
useReportStore,
|
||||
type ActionResult,
|
||||
type HeldText,
|
||||
@@ -76,7 +75,6 @@ export default function EditorRoute() {
|
||||
// Without a report yet (draft restore), the default species' sheet carries the migration map.
|
||||
const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
|
||||
const stopped = useCoreStopped()
|
||||
const unsaved = isUnsaved(store)
|
||||
|
||||
const [detailViewId, setDetailViewId] = useState<string | null>(null)
|
||||
const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>(
|
||||
@@ -137,17 +135,6 @@ export default function EditorRoute() {
|
||||
navigate('/')
|
||||
}, [report, sheet, store, navigate, t, restoreAttempt])
|
||||
|
||||
// The report lives only in this tab's memory: the browser asks before a reload or a close.
|
||||
useEffect(() => {
|
||||
if (!unsaved) return
|
||||
const guard = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
window.addEventListener('beforeunload', guard)
|
||||
return () => window.removeEventListener('beforeunload', guard)
|
||||
}, [unsaved])
|
||||
|
||||
const retryRestore = useCallback(() => setRestoreAttempt((n) => n + 1), [])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -288,7 +275,11 @@ export default function EditorRoute() {
|
||||
restoreOptions.current = { replaceOriginal: true }
|
||||
retryRestore()
|
||||
}}
|
||||
onRetry={retryRestore}
|
||||
onRetry={() => {
|
||||
// The one explicit way to read a draft the engine trapped on again.
|
||||
restoreOptions.current = { retryTrapped: true }
|
||||
retryRestore()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -7,15 +7,23 @@ import type {
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
|
||||
import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
|
||||
import ReplaceSessionDialog from '@/components/report/ReplaceSessionDialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Card from '@/components/ui/Card'
|
||||
import {
|
||||
importAttachment,
|
||||
ImportError,
|
||||
MAX_ATTACHMENT_BYTES,
|
||||
MAX_PDF_BYTES,
|
||||
readAttachment,
|
||||
readRescueCopy,
|
||||
} from '@/pdf/import'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import {
|
||||
isSessionInProgress,
|
||||
useReportStore,
|
||||
type ImportedSession,
|
||||
} from '@/state/reportStore'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
|
||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||
import { useT } from '@/i18n/useT'
|
||||
@@ -107,11 +115,50 @@ function importErrorMessage(err: unknown, t: Translate): string {
|
||||
return t('home.import.error_no_attachment')
|
||||
case 'lone_surrogate':
|
||||
return t('home.import.error_lone_surrogate')
|
||||
case 'invalid_copy':
|
||||
return t('home.import.error_invalid_copy')
|
||||
case 'core_unavailable':
|
||||
return coreFailureMessage(t, 'home.import.error_core_unavailable')
|
||||
}
|
||||
}
|
||||
|
||||
/** What a picked file read into: the session to open and the alert lines to show after. */
|
||||
interface ImportRead {
|
||||
session: ImportedSession
|
||||
index: SheetIndex
|
||||
lines: string[]
|
||||
}
|
||||
|
||||
const SNIFF_BYTES = 1024
|
||||
const PDF_MAGIC = '%PDF-'
|
||||
|
||||
/** First non-blank byte of the head, after an optional UTF-8 byte order mark. */
|
||||
function firstContentByte(head: Uint8Array): number | undefined {
|
||||
const start = head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf ? 3 : 0
|
||||
return head.slice(start).find((b) => ![0x20, 0x09, 0x0a, 0x0d].includes(b))
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes by content, from the first KiB only: a PDF starts with its magic, a rescue copy
|
||||
* is JSON (an object) or is named as such; anything else goes the PDF path and its error.
|
||||
*/
|
||||
function isRescueCopy(file: File, head: Uint8Array): boolean {
|
||||
const start = new TextDecoder('latin1').decode(head.slice(0, PDF_MAGIC.length))
|
||||
if (start === PDF_MAGIC) return false
|
||||
if (firstContentByte(head) === 0x7b) return true
|
||||
return file.name.toLowerCase().endsWith('.json') || file.type === 'application/json'
|
||||
}
|
||||
|
||||
/** The copy's text, refused (never altered) when it is over the cap or not valid UTF-8. */
|
||||
async function readCopyText(file: File): Promise<string> {
|
||||
if (file.size > MAX_ATTACHMENT_BYTES) throw new ImportError('invalid_copy')
|
||||
try {
|
||||
return new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer())
|
||||
} catch {
|
||||
throw new ImportError('invalid_copy')
|
||||
}
|
||||
}
|
||||
|
||||
export default function HomeRoute() {
|
||||
const navigate = useNavigate()
|
||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
||||
@@ -120,10 +167,11 @@ export default function HomeRoute() {
|
||||
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [confirmingReplace, setConfirmingReplace] = useState(false)
|
||||
const t = useT()
|
||||
|
||||
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
|
||||
async function importFile(file: File) {
|
||||
/** A Faunosteo PDF: its attachment, read and rebased by the core on the loaded sheet. */
|
||||
async function readPdf(file: File): Promise<ImportRead> {
|
||||
// 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())
|
||||
@@ -131,20 +179,43 @@ export default function HomeRoute() {
|
||||
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
|
||||
if (!index) throw new ImportError('core_unavailable')
|
||||
const { read: outcome, rebase } = importAttachment(attachment, index)
|
||||
const opened = hydrateImport(
|
||||
{ report: rebase.report, archive: outcome.archive },
|
||||
return {
|
||||
session: { report: rebase.report, archive: outcome.archive },
|
||||
index,
|
||||
)
|
||||
lines: importMessages(outcome, rebase, t),
|
||||
}
|
||||
}
|
||||
|
||||
/** A rescue copy: read before any session change, so a refusal leaves the tab untouched. */
|
||||
async function readCopy(file: File): Promise<ImportRead> {
|
||||
const text = await readCopyText(file)
|
||||
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
|
||||
if (!index) throw new ImportError('core_unavailable')
|
||||
const rebase = readRescueCopy(text, index)
|
||||
const count = String(rebase.unresolvedZones + rebase.unresolvedFindings)
|
||||
return {
|
||||
session: { report: rebase.report, archive: null },
|
||||
index,
|
||||
lines: rebase.rebased ? [t('editor.draft_rebased').replace('{count}', count)] : [],
|
||||
}
|
||||
}
|
||||
|
||||
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
|
||||
async function importFile(file: File) {
|
||||
const head = new Uint8Array(await file.slice(0, SNIFF_BYTES).arrayBuffer())
|
||||
const read = isRescueCopy(file, head) ? await readCopy(file) : await readPdf(file)
|
||||
const opened = hydrateImport(read.session, read.index)
|
||||
// A tab text that could not be set aside would be overwritten: resolve it first.
|
||||
if (!opened.ok) {
|
||||
// A core failure reading the tab's draft is an engine error, not a held text.
|
||||
if (opened.reason !== 'held') throw new ImportError('core_unavailable')
|
||||
window.alert(t('session.held_blocked'))
|
||||
window.alert(
|
||||
t(opened.engine ? 'session.held_blocked_engine' : 'session.held_blocked'),
|
||||
)
|
||||
navigate('/editor')
|
||||
return
|
||||
}
|
||||
const lines = importMessages(outcome, rebase, t)
|
||||
if (lines.length > 0) window.alert(lines.join('\n\n'))
|
||||
if (read.lines.length > 0) window.alert(read.lines.join('\n\n'))
|
||||
navigate('/editor')
|
||||
}
|
||||
|
||||
@@ -208,14 +279,18 @@ export default function HomeRoute() {
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
accept="application/pdf,.pdf,application/json,.json"
|
||||
className="hidden"
|
||||
onChange={onPickFile}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="lg"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
onClick={() =>
|
||||
isSessionInProgress()
|
||||
? setConfirmingReplace(true)
|
||||
: fileRef.current?.click()
|
||||
}
|
||||
disabled={busy || sheet.status !== 'ready'}
|
||||
>
|
||||
{busy ? t('home.import.loading') : t('home.import.cta')}
|
||||
@@ -224,6 +299,16 @@ export default function HomeRoute() {
|
||||
</Card>
|
||||
</div>
|
||||
</section>
|
||||
<ReplaceSessionDialog
|
||||
open={confirmingReplace}
|
||||
onCancel={() => setConfirmingReplace(false)}
|
||||
onOpen={() => navigate('/editor')}
|
||||
onConfirm={() => {
|
||||
// The picker opens inside this click: a later call loses the user activation.
|
||||
fileRef.current?.click()
|
||||
setConfirmingReplace(false)
|
||||
}}
|
||||
/>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import PractitionerForm from '@/components/report/PractitionerForm'
|
||||
import AnimalForm from '@/components/report/AnimalForm'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
|
||||
import ReplaceSessionDialog from '@/components/report/ReplaceSessionDialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Label from '@/components/ui/Label'
|
||||
@@ -13,7 +14,7 @@ import {
|
||||
readCachedPractitioner,
|
||||
writeCachedPractitioner,
|
||||
} from '@/state/practitionerCache'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { isSessionInProgress, useReportStore } from '@/state/reportStore'
|
||||
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { coreFailureMessage } from '@/core/failure'
|
||||
@@ -35,6 +36,7 @@ export default function NewReportRoute() {
|
||||
})
|
||||
const [owner, setOwner] = useState<Owner>({ name: '' })
|
||||
const [date, setDate] = useState(todayIso())
|
||||
const [confirmingReplace, setConfirmingReplace] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const cached = readCachedPractitioner()
|
||||
@@ -47,8 +49,14 @@ export default function NewReportRoute() {
|
||||
owner.name.trim() &&
|
||||
sheet.status === 'ready'
|
||||
|
||||
async function submit() {
|
||||
function submit() {
|
||||
if (!canSubmit || sheet.status !== 'ready') return
|
||||
if (isSessionInProgress()) setConfirmingReplace(true)
|
||||
else void createReport()
|
||||
}
|
||||
|
||||
async function createReport() {
|
||||
if (sheet.status !== 'ready') return
|
||||
writeCachedPractitioner(practitioner)
|
||||
// The loaded sheet lets the store read a draft this page never opened before replacing it.
|
||||
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
|
||||
@@ -71,7 +79,9 @@ export default function NewReportRoute() {
|
||||
)
|
||||
if (created.ok) navigate('/editor')
|
||||
else if (created.reason === 'held') {
|
||||
window.alert(t('session.held_blocked'))
|
||||
window.alert(
|
||||
t(created.engine ? 'session.held_blocked_engine' : 'session.held_blocked'),
|
||||
)
|
||||
navigate('/editor')
|
||||
} else window.alert(coreFailureMessage(t))
|
||||
}
|
||||
@@ -129,6 +139,15 @@ export default function NewReportRoute() {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ReplaceSessionDialog
|
||||
open={confirmingReplace}
|
||||
onCancel={() => setConfirmingReplace(false)}
|
||||
onOpen={() => navigate('/editor')}
|
||||
onConfirm={() => {
|
||||
setConfirmingReplace(false)
|
||||
void createReport()
|
||||
}}
|
||||
/>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useEffect } from 'react'
|
||||
import { isUnsaved, useReportStore } from '@/state/reportStore'
|
||||
|
||||
/**
|
||||
* The report lives only in this tab's memory while the tab's storage refuses its writes:
|
||||
* on any page, the browser asks before a reload, a close or a full-page redirect.
|
||||
*/
|
||||
export function useUnsavedGuard(): void {
|
||||
const unsaved = useReportStore(isUnsaved)
|
||||
useEffect(() => {
|
||||
if (!unsaved) return
|
||||
const guard = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
window.addEventListener('beforeunload', guard)
|
||||
return () => window.removeEventListener('beforeunload', guard)
|
||||
}, [unsaved])
|
||||
}
|
||||
@@ -56,7 +56,13 @@ export default function HeldSessionPanel({
|
||||
|
||||
return (
|
||||
<main className="p-4 sm:p-6 space-y-4 max-w-2xl">
|
||||
<Notice tone="error">{t('session.held.notice')}</Notice>
|
||||
<Notice tone="error">
|
||||
{t(
|
||||
held.some((item) => item.reason === 'engine_failure')
|
||||
? 'session.held.notice_engine'
|
||||
: 'session.held.notice',
|
||||
)}
|
||||
</Notice>
|
||||
<ul className="space-y-3">
|
||||
{held.map((item) => (
|
||||
<li
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import Button from '@/components/ui/Button'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import { CopyReportButton } from '@/components/report/CoreStoppedNotice'
|
||||
import { isUnsaved, useReportStore } from '@/state/reportStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface ReplaceSessionDialogProps {
|
||||
open: boolean
|
||||
onCancel: () => void
|
||||
/** Leaves for the editor, where the bilan in progress is. */
|
||||
onOpen: () => void
|
||||
onConfirm: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Asked before a new report or an import replaces the bilan in progress in this tab,
|
||||
* saved or not: the practitioner cancels, goes back to it, or replaces it knowingly.
|
||||
* An unsaved report (tab storage full) comes with its rescue copy.
|
||||
*/
|
||||
export default function ReplaceSessionDialog({
|
||||
open,
|
||||
onCancel,
|
||||
onOpen,
|
||||
onConfirm,
|
||||
}: ReplaceSessionDialogProps) {
|
||||
const t = useT()
|
||||
const report = useReportStore((s) => s.report)
|
||||
const unsaved = useReportStore(isUnsaved)
|
||||
const body = report
|
||||
? t('session.replace.body').replace(/\{animal\}/, () => report.animal.name)
|
||||
: t('session.replace.body_unloaded')
|
||||
return (
|
||||
<Dialog open={open} onClose={onCancel} title={t('session.replace.title')} size="sm">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>
|
||||
{unsaved && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<p className="text-sm">{t('session.replace.unsaved')}</p>
|
||||
<CopyReportButton />
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={onCancel}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" onClick={onOpen}>
|
||||
{t('session.replace.open')}
|
||||
</Button>
|
||||
<Button type="button" variant="danger" onClick={onConfirm}>
|
||||
{t('session.replace.confirm')}
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
+19
-2
@@ -19,15 +19,17 @@ export const en: Dict = {
|
||||
'home.new_report.description':
|
||||
'Start a new osteopathic report for an animal.',
|
||||
'home.new_report.cta': 'Start',
|
||||
'home.import.title': 'Import a PDF',
|
||||
'home.import.title': 'Import a PDF or a rescue copy',
|
||||
'home.import.description':
|
||||
'Reopen a previous report generated by this app to follow up.',
|
||||
'home.import.cta': 'Choose a PDF',
|
||||
'home.import.cta': 'Choose a file',
|
||||
'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_invalid_copy':
|
||||
'This file is not a Faunosteo rescue copy this version can read. Import refused; the file was not changed.',
|
||||
'home.import.error_no_attachment':
|
||||
'This PDF was not generated by Faunosteo (no data detected).',
|
||||
'home.import.error_incompatible_version':
|
||||
@@ -122,6 +124,21 @@ export const en: Dict = {
|
||||
"Open",
|
||||
'session.held_blocked':
|
||||
"A draft in this tab must be recovered or deleted first: it could not be set aside and would be overwritten. The editor will open to resolve it.",
|
||||
'session.held.notice_engine':
|
||||
"Faunosteo's computation engine cannot open a draft of this tab. It is kept as is; nothing was deleted. Download a copy, try again, or delete it to start a new report.",
|
||||
'session.held.draft_engine_failure':
|
||||
"Draft the computation engine cannot open ({size})",
|
||||
'session.held_blocked_engine':
|
||||
"A draft of this tab makes the computation engine fail: recover or delete it first. The editor will open to resolve it.",
|
||||
'session.replace.title': 'Replace the report in progress?',
|
||||
'session.replace.body':
|
||||
"The report of {animal} will be replaced in this tab. Export it as a PDF to keep it.",
|
||||
'session.replace.body_unloaded':
|
||||
"The report in progress in this tab will be replaced. Open it and export it as a PDF to keep it.",
|
||||
'session.replace.unsaved':
|
||||
"Its latest changes are not saved in this tab.",
|
||||
'session.replace.open': 'Open the report in progress',
|
||||
'session.replace.confirm': 'Replace',
|
||||
'editor.edit_infos': 'Edit info',
|
||||
'editor.edit_dialog_title': 'Edit information',
|
||||
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
|
||||
|
||||
+19
-2
@@ -21,15 +21,17 @@ export const fr: Dict = {
|
||||
'home.new_report.description':
|
||||
"Démarrer un nouveau bilan d'ostéopathie sur un animal.",
|
||||
'home.new_report.cta': 'Commencer',
|
||||
'home.import.title': 'Importer un PDF',
|
||||
'home.import.title': 'Importer un PDF ou une copie de secours',
|
||||
'home.import.description':
|
||||
'Reprendre un bilan précédent généré par cette application pour effectuer un suivi.',
|
||||
'home.import.cta': 'Choisir un PDF',
|
||||
'home.import.cta': 'Choisir un fichier',
|
||||
'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_invalid_copy':
|
||||
"Ce fichier n'est pas une copie de secours Faunosteo lisible par cette version. Import refusé ; le fichier n'a pas été modifié.",
|
||||
'home.import.error_no_attachment':
|
||||
"Ce PDF n'a pas été généré par Faunosteo (pas de données détectées).",
|
||||
'home.import.error_incompatible_version':
|
||||
@@ -128,6 +130,21 @@ export const fr: Dict = {
|
||||
"Ouvrir",
|
||||
'session.held_blocked':
|
||||
"Un brouillon de cet onglet doit d'abord être récupéré ou supprimé : il n'a pas pu être mis de côté et serait écrasé. L'éditeur va s'ouvrir pour le résoudre.",
|
||||
'session.held.notice_engine':
|
||||
"Le moteur de calcul n'arrive pas à ouvrir un brouillon de cet onglet. Il est conservé tel quel ; rien n'a été supprimé. Téléchargez-en une copie, réessayez, ou supprimez-le pour commencer un nouveau bilan.",
|
||||
'session.held.draft_engine_failure':
|
||||
"Brouillon que le moteur de calcul n'arrive pas à ouvrir ({size})",
|
||||
'session.held_blocked_engine':
|
||||
"Un brouillon de cet onglet fait échouer le moteur de calcul : il doit d'abord être récupéré ou supprimé. L'éditeur va s'ouvrir pour le résoudre.",
|
||||
'session.replace.title': 'Remplacer le bilan en cours ?',
|
||||
'session.replace.body':
|
||||
"Le bilan de {animal} sera remplacé dans cet onglet. Exportez-le en PDF pour le garder.",
|
||||
'session.replace.body_unloaded':
|
||||
"Le bilan en cours dans cet onglet sera remplacé. Ouvrez-le et exportez-le en PDF pour le garder.",
|
||||
'session.replace.unsaved':
|
||||
"Ses dernières modifications ne sont pas enregistrées dans l'onglet.",
|
||||
'session.replace.open': 'Ouvrir le bilan en cours',
|
||||
'session.replace.confirm': 'Remplacer',
|
||||
'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",
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
import type { ArchiveImport } from '@faunosteo/core-wasm/types'
|
||||
import type { ArchiveImport, RebaseOutcome } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
ArchiveReadError,
|
||||
readAttachedDocument,
|
||||
type ArchiveReadErrorKind,
|
||||
} from '@faunosteo/pdf'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { UNREADABLE_DRAFT_KINDS } from '@/state/reportStore'
|
||||
|
||||
export { MAX_PDF_BYTES } from '@faunosteo/pdf'
|
||||
export { MAX_ATTACHMENT_BYTES, MAX_PDF_BYTES } from '@faunosteo/pdf'
|
||||
|
||||
/**
|
||||
* `lone_surrogate`: the attachment escapes a lone UTF-16 surrogate, which the
|
||||
* core cannot read without altering it (L1): refused, the file untouched.
|
||||
* `invalid_copy`: a file offered as a rescue copy that this build cannot read.
|
||||
*/
|
||||
export type ImportErrorKind =
|
||||
| ArchiveReadErrorKind
|
||||
| 'core_unavailable'
|
||||
| 'lone_surrogate'
|
||||
| 'invalid_copy'
|
||||
|
||||
/**
|
||||
* Localization-agnostic import error. Carries a kind discriminant + an
|
||||
@@ -84,3 +87,17 @@ export async function importReportFromPdf(
|
||||
): Promise<ArchiveImport> {
|
||||
return importAttachment(await readAttachment(pdfBytes), index)
|
||||
}
|
||||
|
||||
/**
|
||||
* A rescue copy (`JSON.stringify(report)`, the byte format of the tab's draft)
|
||||
* read by the core's draft restore, no archive beside it. Content the core
|
||||
* refuses is `invalid_copy`; any other failure is the engine's or the sheet's.
|
||||
*/
|
||||
export function readRescueCopy(text: string, index: SheetIndex): RebaseOutcome {
|
||||
const outcome = index.ops.restoreDraft(text, null)
|
||||
if (outcome.ok) return outcome.value.rebase
|
||||
if (UNREADABLE_DRAFT_KINDS.has(outcome.kind)) {
|
||||
throw new ImportError('invalid_copy')
|
||||
}
|
||||
throw new ImportError('core_unavailable')
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
ARCHIVE_KEY,
|
||||
quarantine,
|
||||
quarantineSession,
|
||||
readSessionText,
|
||||
removeSessionText,
|
||||
sessionStorageArchivePersistence,
|
||||
sessionStoragePersistence,
|
||||
@@ -57,17 +58,20 @@ export interface ActionResult {
|
||||
ok: boolean
|
||||
/** Refused because a session text is held (it could not be set aside and would be lost). */
|
||||
reason?: 'held'
|
||||
/** With `held`: the engine itself fails on the tab's draft (a trap), not a storage problem. */
|
||||
engine?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* A session text kept in place because its safety copy failed (storage full, or the
|
||||
* quarantine slot already holds an earlier text): `unreadable` by this build, the
|
||||
* archive `companion` of an unreadable draft, or a draft whose `pre_rebase` original
|
||||
* could not be kept before the rebase replaces it.
|
||||
* could not be kept before the rebase replaces it, or a draft the engine trapped on
|
||||
* (`engine_failure`, kept as is).
|
||||
*/
|
||||
export interface HeldText {
|
||||
text: SessionText
|
||||
reason: 'unreadable' | 'companion' | 'pre_rebase'
|
||||
reason: 'unreadable' | 'companion' | 'pre_rebase' | 'engine_failure'
|
||||
/** UTF-8 size of the stored text, for the resolution panel. */
|
||||
bytes: number
|
||||
}
|
||||
@@ -75,6 +79,8 @@ export interface HeldText {
|
||||
export interface RestoreOptions {
|
||||
/** The practitioner confirmed that the rebased draft may replace its original. */
|
||||
replaceOriginal?: boolean
|
||||
/** The practitioner asked to read a draft the engine trapped on again. */
|
||||
retryTrapped?: boolean
|
||||
}
|
||||
|
||||
/** What a draft restore did; `null` from the action when there was nothing to restore. */
|
||||
@@ -116,6 +122,8 @@ export interface ReportStore {
|
||||
) => RestoreResult | null
|
||||
/** Removes a held session text, on the practitioner's confirmed request; no-op once a report is open. */
|
||||
discardSessionText: (text: SessionText) => void
|
||||
/** Forgets the draft the engine trapped on (test seam; every discard does it too). */
|
||||
clearTrapped: () => void
|
||||
addObservation: () => ActionResult
|
||||
removeObservation: (index: number) => ActionResult
|
||||
moveObservationUp: (index: number) => ActionResult
|
||||
@@ -140,6 +148,7 @@ type Getter = () => ReportStore
|
||||
const OK: ActionResult = { ok: true }
|
||||
const FAILED: ActionResult = { ok: false }
|
||||
const HELD: ActionResult = { ok: false, reason: 'held' }
|
||||
const HELD_ENGINE: ActionResult = { ok: false, reason: 'held', engine: true }
|
||||
|
||||
/** The tab's storage refused the last write: the in-memory report is the only copy. */
|
||||
export const isUnsaved = (s: Pick<ReportStore, 'saveFailed' | 'report'>): boolean =>
|
||||
@@ -172,7 +181,7 @@ function applyCore(
|
||||
* (`lone_surrogate`: reading it would alter a string, L1). Any other failure is the core's
|
||||
* or the sheet's and leaves the draft in place.
|
||||
*/
|
||||
const UNREADABLE_DRAFT_KINDS: ReadonlySet<string> = new Set([
|
||||
export const UNREADABLE_DRAFT_KINDS: ReadonlySet<string> = new Set([
|
||||
'invalid',
|
||||
'unsupported_version',
|
||||
'lone_surrogate',
|
||||
@@ -186,6 +195,37 @@ function held(text: SessionText, reason: HeldText['reason'], raw: string): HeldT
|
||||
return { text, reason, bytes: utf8Bytes(raw) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The (draft, archive) pair a `draft.restore` call trapped on. The same pair is never read
|
||||
* again until the practitioner retries: each read of it would spend an engine recovery.
|
||||
*/
|
||||
interface TrapMemory {
|
||||
matches: (draft: string, archiveText: string | null) => boolean
|
||||
remember: (draft: string, archiveText: string | null) => void
|
||||
clear: () => void
|
||||
}
|
||||
|
||||
function createTrapMemory(): TrapMemory {
|
||||
let trapped: { draft: string; archive: string | null } | null = null
|
||||
return {
|
||||
matches: (draft, archiveText) =>
|
||||
trapped !== null && trapped.draft === draft && trapped.archive === archiveText,
|
||||
remember: (draft, archiveText) => {
|
||||
trapped = { draft, archive: archiveText }
|
||||
},
|
||||
clear: () => {
|
||||
trapped = null
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** The held rows of a trapped draft: the draft, and its archive when one is beside it. */
|
||||
function engineFailureRows(draft: string, archiveText: string | null): HeldText[] {
|
||||
const rows = [held('draft', 'engine_failure', draft)]
|
||||
if (archiveText !== null) rows.push(held('archive', 'companion', archiveText))
|
||||
return rows
|
||||
}
|
||||
|
||||
type Restored = { result: RestoreResult; patch?: Patch } | null
|
||||
|
||||
/** An archive with no draft beside it can never be restored: set it aside, or hold it. */
|
||||
@@ -212,12 +252,21 @@ function restore(
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
options: RestoreOptions,
|
||||
trap: TrapMemory,
|
||||
): Restored {
|
||||
const draft = persistence.loadText()
|
||||
const archiveText = archives.loadText()
|
||||
if (draft === null) return restoreOrphanArchive(archiveText)
|
||||
if (options.retryTrapped) trap.clear()
|
||||
if (trap.matches(draft, archiveText)) {
|
||||
return { result: { kind: 'held', held: engineFailureRows(draft, archiveText) } }
|
||||
}
|
||||
const outcome = index.ops.restoreDraft(draft, archiveText)
|
||||
if (!outcome.ok) {
|
||||
if (outcome.kind === 'internal') {
|
||||
trap.remember(draft, archiveText)
|
||||
return { result: { kind: 'held', held: engineFailureRows(draft, archiveText) } }
|
||||
}
|
||||
// Only an unreadable draft is set aside; a core or sheet failure leaves it in place.
|
||||
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) {
|
||||
return { result: { kind: 'core_unavailable' } }
|
||||
@@ -247,19 +296,26 @@ function restore(
|
||||
/**
|
||||
* Before a new session replaces texts this page never read: an unreadable draft (and its
|
||||
* archive) or an unreadable archive is set aside first; a readable draft is replaced as
|
||||
* before. HELD when something could not be set aside; FAILED when the core could not even
|
||||
* read the draft (not a held text: nothing is set aside, nothing is written).
|
||||
* before. HELD when something could not be set aside, or when the engine traps on the draft
|
||||
* (`engine`: kept as is); FAILED when the core could not even read the draft (not a held
|
||||
* text: nothing is set aside, nothing is written).
|
||||
*/
|
||||
function releaseUnreadSession(
|
||||
index: SheetIndex,
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
trap: TrapMemory,
|
||||
): ActionResult {
|
||||
const draft = persistence.loadText()
|
||||
const archiveText = archives.loadText()
|
||||
if (draft === null) return restoreOrphanArchive(archiveText) === null ? OK : HELD
|
||||
if (trap.matches(draft, archiveText)) return HELD_ENGINE
|
||||
const outcome = index.ops.restoreDraft(draft, archiveText)
|
||||
if (!outcome.ok) {
|
||||
if (outcome.kind === 'internal') {
|
||||
trap.remember(draft, archiveText)
|
||||
return HELD_ENGINE
|
||||
}
|
||||
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return FAILED
|
||||
return quarantineSession(draft, archiveText) ? OK : HELD
|
||||
}
|
||||
@@ -271,6 +327,7 @@ export function createReportStore(
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
) {
|
||||
const trap = createTrapMemory()
|
||||
/** The archive mirror is explicit: these actions are the session's edges. */
|
||||
// The archive of this session could not be written: the tab's copy lacks it (banner).
|
||||
let archiveRefused = false
|
||||
@@ -286,7 +343,7 @@ export function createReportStore(
|
||||
const mayStartSession = (index: SheetIndex): ActionResult =>
|
||||
store.getState().report !== null
|
||||
? OK
|
||||
: releaseUnreadSession(index, persistence, archives)
|
||||
: releaseUnreadSession(index, persistence, archives, trap)
|
||||
|
||||
const store = create<ReportStore>((set, get) => ({
|
||||
report: null,
|
||||
@@ -318,7 +375,7 @@ export function createReportStore(
|
||||
|
||||
restoreDraft: (index, options = {}) => {
|
||||
if (get().report) return null
|
||||
const restored = restore(index, persistence, archives, options)
|
||||
const restored = restore(index, persistence, archives, options, trap)
|
||||
if (!restored) return null
|
||||
if (restored.patch) set(restored.patch)
|
||||
return restored.result
|
||||
@@ -326,9 +383,12 @@ export function createReportStore(
|
||||
|
||||
discardSessionText: (text) => {
|
||||
if (get().report) return
|
||||
trap.clear()
|
||||
removeSessionText(text)
|
||||
},
|
||||
|
||||
clearTrapped: () => trap.clear(),
|
||||
|
||||
addObservation: () =>
|
||||
applyCore(
|
||||
set,
|
||||
@@ -409,3 +469,8 @@ export const useReportStore = createReportStore(
|
||||
sessionStoragePersistence,
|
||||
sessionStorageArchivePersistence,
|
||||
)
|
||||
|
||||
/** A bilan is in progress in this tab: in memory, or as a draft this page never opened. */
|
||||
export function isSessionInProgress(): boolean {
|
||||
return useReportStore.getState().report !== null || readSessionText('draft') !== null
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { CoreRuntime } from '@faunosteo/core-wasm'
|
||||
import { nodeCoreRuntime } from '@faunosteo/core-wasm/node'
|
||||
import { CoreRuntime, type CoreSource } from '@faunosteo/core-wasm'
|
||||
import { nodeCoreRuntime, nodeCoreSource } from '@faunosteo/core-wasm/node'
|
||||
|
||||
/** A loaded runtime on the shipped build (the package's Node source). */
|
||||
export function testCoreRuntime(): Promise<CoreRuntime> {
|
||||
@@ -26,3 +26,39 @@ export function unavailableCoreRuntime(): CoreRuntime {
|
||||
importGlue: () => Promise.reject(new TypeError('blocked')),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* A real runtime on the shipped module whose `SheetHandle.call` throws a
|
||||
* `WebAssembly.RuntimeError` (as an out-of-memory trap does) for `draft.restore`
|
||||
* calls whose input contains `marker`; `traps.count` counts them. The runtime
|
||||
* poisons and recovers exactly as in production (three recoveries).
|
||||
*/
|
||||
export async function trappingCoreRuntime(marker: string) {
|
||||
const source = nodeCoreSource('pkg')
|
||||
const traps = { count: 0 }
|
||||
const wrapped: CoreSource = {
|
||||
compile: () => source.compile(),
|
||||
importGlue: async (instance) => {
|
||||
const glue = await source.importGlue(instance)
|
||||
const Real = glue.SheetHandle
|
||||
class Trapping extends Real {
|
||||
call(op: string, input: string): string {
|
||||
if (op === 'draft.restore' && input.includes(marker)) {
|
||||
traps.count += 1
|
||||
throw new WebAssembly.RuntimeError('unreachable')
|
||||
}
|
||||
return super.call(op, input)
|
||||
}
|
||||
}
|
||||
return {
|
||||
default: glue.default,
|
||||
core_version: glue.core_version,
|
||||
call: glue.call,
|
||||
SheetHandle: Trapping,
|
||||
}
|
||||
},
|
||||
}
|
||||
const runtime = new CoreRuntime(wrapped)
|
||||
if (!(await runtime.ready())) throw new Error('trapping runtime failed to load')
|
||||
return { runtime, traps }
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* The beforeunload guard is app-wide (R3 final checks): prevented exactly while the report
|
||||
* is unsaved, on any page; App mounts it, the editor no longer registers its own.
|
||||
*/
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react'
|
||||
import App from '@/app/App'
|
||||
import { useUnsavedGuard } from '@/app/useUnsavedGuard'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
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, saveFailed: false })
|
||||
useReportStore.getState().hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
useReportStore.setState({ report: null, saveFailed: false })
|
||||
})
|
||||
|
||||
const leave = () => {
|
||||
const event = new Event('beforeunload', { cancelable: true })
|
||||
window.dispatchEvent(event)
|
||||
return event.defaultPrevented
|
||||
}
|
||||
|
||||
function fillStorage() {
|
||||
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
|
||||
throw new DOMException('full', 'QuotaExceededError')
|
||||
})
|
||||
act(() => useReportStore.getState().setConclusion('edited after the quota'))
|
||||
expect(useReportStore.getState().saveFailed).toBe(true)
|
||||
}
|
||||
|
||||
describe('useUnsavedGuard', () => {
|
||||
it('prevents the unload exactly while the report is unsaved', async () => {
|
||||
renderHook(() => useUnsavedGuard())
|
||||
expect(leave()).toBe(false)
|
||||
fillStorage()
|
||||
await waitFor(() => expect(leave()).toBe(true))
|
||||
vi.restoreAllMocks()
|
||||
act(() => useReportStore.getState().setConclusion('saved again'))
|
||||
await waitFor(() => expect(leave()).toBe(false))
|
||||
})
|
||||
|
||||
it('leaves the listener off once the hook unmounts', async () => {
|
||||
const { unmount } = renderHook(() => useUnsavedGuard())
|
||||
fillStorage()
|
||||
await waitFor(() => expect(leave()).toBe(true))
|
||||
unmount()
|
||||
expect(leave()).toBe(false)
|
||||
})
|
||||
|
||||
it('is mounted by App, on a page that is not the editor', async () => {
|
||||
window.history.pushState({}, '', '/')
|
||||
render(<App />)
|
||||
expect(leave()).toBe(false)
|
||||
fillStorage()
|
||||
await waitFor(() => expect(leave()).toBe(true))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* The rescue copy (`JSON.stringify(report)`, the downloaded format) imported from Home:
|
||||
* routed by content from the first KiB, read by the core's draft restore, opened as the
|
||||
* original report; every refusal leaves the store and the tab's slots untouched.
|
||||
*/
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import HomeRoute from '@/app/routes/HomeRoute'
|
||||
import { MAX_ATTACHMENT_BYTES } from '@/pdf/import'
|
||||
import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { fr } from '@/i18n/fr'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { buildGoldenReports, GOLDEN_REPORTS } from '../helpers/goldenReports'
|
||||
import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
||||
|
||||
let sheet: SheetIndex
|
||||
|
||||
beforeAll(async () => {
|
||||
sheet = await loadTestSheet()
|
||||
})
|
||||
beforeEach(() => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
sessionStorage.clear()
|
||||
useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0 })
|
||||
useReportStore.getState().clearTrapped()
|
||||
vi.stubGlobal('alert', vi.fn())
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function pick(file: File) {
|
||||
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())
|
||||
fireEvent.change(document.querySelector('input[type="file"]')!, {
|
||||
target: { files: [file] },
|
||||
})
|
||||
}
|
||||
|
||||
const copyFile = (text: string, name = 'faunosteo-brouillon.json') =>
|
||||
new File([text], name, { type: 'application/json' })
|
||||
|
||||
describe('opening a rescue copy', () => {
|
||||
it.each(GOLDEN_REPORTS)('reopens the %s report equal to the original', async (name) => {
|
||||
const { reports } = buildGoldenReports(sheet)
|
||||
await pick(copyFile(JSON.stringify(reports[name])))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(useReportStore.getState().report).toEqual(reports[name])
|
||||
expect(useReportStore.getState().archive).toBeNull()
|
||||
})
|
||||
|
||||
it('routes by content: no .json name, no type, leading blanks and a BOM', async () => {
|
||||
const report = minimalReport(sheet, { conclusion: 'sniffed' })
|
||||
const text = ` \n${JSON.stringify(report)}`
|
||||
await pick(new File([text], 'secours'))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(useReportStore.getState().report).toEqual(report)
|
||||
})
|
||||
|
||||
it('announces a copy rebased on another sheet revision', async () => {
|
||||
const stale = minimalReport(sheet, {
|
||||
sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) },
|
||||
observations: [
|
||||
{
|
||||
id: 'o',
|
||||
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
},
|
||||
],
|
||||
})
|
||||
await pick(copyFile(JSON.stringify(stale)))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(window.alert).toHaveBeenCalledWith(
|
||||
fr['editor.draft_rebased']!.replace('{count}', '1'),
|
||||
)
|
||||
})
|
||||
|
||||
it('still sends a PDF down the PDF path', async () => {
|
||||
await pick(new File(['%PDF-1.7 not really'], 'bilan.pdf', { type: 'application/pdf' }))
|
||||
await screen.findByText(fr['home.import.error_no_attachment']!)
|
||||
expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('refusing a file', () => {
|
||||
const unreadable = JSON.stringify({ version: 7 })
|
||||
const refused: [string, () => File][] = [
|
||||
['invalid JSON', () => copyFile('{not json')],
|
||||
['an unsupported version', () => copyFile(JSON.stringify({ version: 1 }))],
|
||||
[
|
||||
'a lone surrogate',
|
||||
() => copyFile(JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' }))),
|
||||
],
|
||||
[
|
||||
'invalid UTF-8',
|
||||
() => new File([new Uint8Array([0x7b, 0xff, 0xfe, 0x7d])], 'copie.json'),
|
||||
],
|
||||
]
|
||||
|
||||
async function expectUntouched() {
|
||||
await screen.findByText(fr['home.import.error_invalid_copy']!)
|
||||
expect(useReportStore.getState().report).toBeNull()
|
||||
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(unreadable)
|
||||
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
|
||||
expect(window.alert).not.toHaveBeenCalled()
|
||||
expect(screen.queryByTestId('editor-route')).toBeNull()
|
||||
}
|
||||
|
||||
it.each(refused)('%s: error line, nothing changed, nothing held', async (_label, make) => {
|
||||
sessionStorage.setItem(DRAFT_KEY, unreadable)
|
||||
await pick(make())
|
||||
await expectUntouched()
|
||||
})
|
||||
|
||||
it('an over-cap file is refused before any full read', async () => {
|
||||
sessionStorage.setItem(DRAFT_KEY, unreadable)
|
||||
const file = copyFile('{"version":3}')
|
||||
Object.defineProperty(file, 'size', { value: MAX_ATTACHMENT_BYTES + 1 })
|
||||
const read = vi.spyOn(file, 'arrayBuffer')
|
||||
await pick(file)
|
||||
await expectUntouched()
|
||||
expect(read).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['internal', 'rebase_failed'])(
|
||||
'the core kind %s takes the engine message path, not the copy message',
|
||||
async (kind) => {
|
||||
vi.spyOn(sheet.ops, 'restoreDraft').mockReturnValue({ ok: false, kind } as never)
|
||||
await pick(copyFile(JSON.stringify(minimalReport(sheet))))
|
||||
await screen.findByText(fr['home.import.error_core_unavailable']!)
|
||||
expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull()
|
||||
expect(useReportStore.getState().report).toBeNull()
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -2,7 +2,7 @@
|
||||
* The engine stopped for good (three recoveries spent, owner decision 2026-10-15): the
|
||||
* stopped notice on every core page, its two variants (tab copy saved: reload; tab storage
|
||||
* full: download a copy), no retry anywhere, the editor's save banner with its copy button,
|
||||
* the beforeunload guard while the report is unsaved, and the stopped alerts.
|
||||
* and the stopped alerts (the beforeunload guard has its own hook test).
|
||||
*/
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
@@ -167,24 +167,6 @@ describe('EditorRoute', () => {
|
||||
expect(await blobs[0]!.text()).toBe(JSON.stringify(useReportStore.getState().report))
|
||||
})
|
||||
|
||||
it('guards the page with beforeunload exactly while the report is unsaved', async () => {
|
||||
setStopped(false)
|
||||
mountEditor()
|
||||
await screen.findByTestId('sheet-status')
|
||||
const leave = () => {
|
||||
const event = new Event('beforeunload', { cancelable: true })
|
||||
window.dispatchEvent(event)
|
||||
return event.defaultPrevented
|
||||
}
|
||||
expect(leave()).toBe(false)
|
||||
fillStorage()
|
||||
await waitFor(() => expect(leave()).toBe(true))
|
||||
vi.restoreAllMocks()
|
||||
act(() => useReportStore.getState().setConclusion('saved again'))
|
||||
expect(useReportStore.getState().saveFailed).toBe(false)
|
||||
await waitFor(() => expect(leave()).toBe(false))
|
||||
})
|
||||
|
||||
it('says the stopped text when the export fails once the engine stopped', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('core_unavailable'))
|
||||
@@ -244,6 +226,8 @@ describe('the stopped text on the Home import line and the New report alert', ()
|
||||
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
|
||||
await waitFor(() => expect(submit).toBeEnabled())
|
||||
await user.click(submit)
|
||||
// A report is in progress (beforeEach): replacing it is confirmed first.
|
||||
await user.click(await screen.findByRole('button', { name: fr['session.replace.confirm']! }))
|
||||
}
|
||||
|
||||
it('Home import: the engine error line says the stopped text', async () => {
|
||||
|
||||
@@ -177,6 +177,10 @@ describe('a new report over a held draft', () => {
|
||||
const submit = screen.getByRole('button', { name: fr['new_report.submit'] })
|
||||
await waitFor(() => expect(submit).toBeEnabled())
|
||||
await user.click(submit)
|
||||
// A draft sits in the slot: replacing it is confirmed first.
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked']),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Replacing the bilan in progress (R3 final checks): New report and the Home file pick ask
|
||||
* first when a report is in memory or a draft sits in the slot (named, unloaded and
|
||||
* unsaved variants); Annuler changes nothing, Ouvrir goes back to the editor, Remplacer
|
||||
* proceeds; nothing in progress, no dialog.
|
||||
*/
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } 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 { DRAFT_KEY } from '@/state/persistence'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { fr } from '@/i18n/fr'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
||||
|
||||
let sheet: SheetIndex
|
||||
|
||||
beforeAll(async () => {
|
||||
sheet = await loadTestSheet()
|
||||
})
|
||||
beforeEach(() => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
sessionStorage.clear()
|
||||
localStorage.clear()
|
||||
useReportStore.setState({
|
||||
report: null,
|
||||
archive: null,
|
||||
activeObservationIndex: 0,
|
||||
saveFailed: false,
|
||||
})
|
||||
useReportStore.getState().clearTrapped()
|
||||
vi.stubGlobal('alert', vi.fn())
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
useReportStore.setState({ report: null, saveFailed: false })
|
||||
})
|
||||
|
||||
const mount = (path: '/' | '/new') =>
|
||||
render(
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomeRoute />} />
|
||||
<Route path="/new" element={<NewReportRoute />} />
|
||||
<Route path="/editor" element={<p data-testid="editor-route" />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
const openReport = (animalName = 'Mistral') =>
|
||||
useReportStore.getState().hydrateImport(
|
||||
{ report: minimalReport(sheet, { animal: { speciesId: 'equine', name: animalName } }), archive: null },
|
||||
sheet,
|
||||
)
|
||||
|
||||
async function submitForm(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr X')
|
||||
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Rex')
|
||||
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
|
||||
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
|
||||
await waitFor(() => expect(submit).toBeEnabled())
|
||||
await user.click(submit)
|
||||
}
|
||||
|
||||
const button = (key: string) => screen.getByRole('button', { name: fr[key]! })
|
||||
/** A button of the open dialog (the page behind has its own Annuler). */
|
||||
const dialogButton = (key: string) =>
|
||||
within(screen.getByRole('dialog')).getByRole('button', { name: fr[key]! })
|
||||
|
||||
describe('New report over a bilan in progress', () => {
|
||||
it('names the animal of the report in memory and replaces it on Remplacer', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
expect(dialog).toHaveTextContent(fr['session.replace.body']!.replace('{animal}', 'Mistral'))
|
||||
expect(dialog).not.toHaveTextContent(fr['session.replace.unsaved']!)
|
||||
await user.click(button('session.replace.confirm'))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(useReportStore.getState().report?.animal.name).toBe('Rex')
|
||||
})
|
||||
|
||||
it('renders an animal name with a replacement pattern literally', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport('Rex$&$1')
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
expect(await screen.findByRole('dialog')).toHaveTextContent('Le bilan de Rex$&$1 sera')
|
||||
})
|
||||
|
||||
it('uses the unloaded text for a draft this page never opened', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
expect(await screen.findByRole('dialog')).toHaveTextContent(fr['session.replace.body_unloaded']!)
|
||||
})
|
||||
|
||||
it('adds the unsaved line and the copy button when the tab storage is full', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
|
||||
throw new DOMException('full', 'QuotaExceededError')
|
||||
})
|
||||
act(() => useReportStore.getState().setConclusion('edited'))
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
expect(dialog).toHaveTextContent(fr['session.replace.unsaved']!)
|
||||
expect(dialog).toHaveTextContent(fr['session.held.download']!)
|
||||
})
|
||||
|
||||
it('Annuler changes nothing and Ouvrir goes to the editor', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
const before = useReportStore.getState().report
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
await screen.findByRole('dialog')
|
||||
await user.click(dialogButton('common.cancel'))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
expect(useReportStore.getState().report).toBe(before)
|
||||
await user.click(button('new_report.submit'))
|
||||
await screen.findByRole('dialog')
|
||||
await user.click(button('session.replace.open'))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(useReportStore.getState().report).toBe(before)
|
||||
})
|
||||
|
||||
it('asks nothing when no bilan is in progress', async () => {
|
||||
const user = userEvent.setup()
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
expect(useReportStore.getState().report?.animal.name).toBe('Rex')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the Home file pick over a bilan in progress', () => {
|
||||
const pickButton = () => button('home.import.cta')
|
||||
const enabled = () => waitFor(() => expect(pickButton()).toBeEnabled())
|
||||
|
||||
it('asks first; Remplacer opens the picker inside the same click', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
mount('/')
|
||||
await enabled()
|
||||
await user.click(pickButton())
|
||||
expect(await screen.findByRole('dialog')).toHaveTextContent('Mistral')
|
||||
expect(click).not.toHaveBeenCalled()
|
||||
fireEvent.click(button('session.replace.confirm'))
|
||||
expect(click).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('Annuler never opens the picker; Ouvrir goes to the editor; the report stays', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
const before = useReportStore.getState().report
|
||||
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
mount('/')
|
||||
await enabled()
|
||||
await user.click(pickButton())
|
||||
await user.click(dialogButton('common.cancel'))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
await user.click(pickButton())
|
||||
await user.click(button('session.replace.open'))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(click).not.toHaveBeenCalled()
|
||||
expect(useReportStore.getState().report).toBe(before)
|
||||
})
|
||||
|
||||
it('also asks for a draft only in the slot (unloaded text), nothing otherwise', async () => {
|
||||
const user = userEvent.setup()
|
||||
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
mount('/')
|
||||
await enabled()
|
||||
await user.click(pickButton())
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
expect(click).toHaveBeenCalledOnce()
|
||||
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
|
||||
await user.click(pickButton())
|
||||
expect(await screen.findByRole('dialog')).toHaveTextContent(fr['session.replace.body_unloaded']!)
|
||||
expect(click).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* A draft the engine traps on (R3 final checks): on a real poisoning runtime the editor
|
||||
* shows the resolution panel (engine_failure row, engine notice), never the reload screen
|
||||
* while the engine is not stopped; New report and Import answer the engine message then
|
||||
* open the panel; the trapping (draft, archive) pair is read once (one trap across mount,
|
||||
* New report, Import and remount); only the panel's Retry reads it again; a confirmed
|
||||
* discard removes the draft and clears the memory.
|
||||
*/
|
||||
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 EditorRoute from '@/app/routes/EditorRoute'
|
||||
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 { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { fr } from '@/i18n/fr'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { testCoreRuntime, trappingCoreRuntime } from '../helpers/core'
|
||||
import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
||||
|
||||
const MARKER = 'trap-me'
|
||||
let sheet: SheetIndex
|
||||
let draft: string
|
||||
let traps: { count: number }
|
||||
let engineStopped: () => boolean
|
||||
let engineReady: () => Promise<boolean>
|
||||
|
||||
beforeAll(async () => {
|
||||
sheet = await loadTestSheet()
|
||||
draft = JSON.stringify(minimalReport(sheet, { conclusion: MARKER }))
|
||||
})
|
||||
beforeEach(async () => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
sessionStorage.clear()
|
||||
localStorage.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 })
|
||||
useReportStore.getState().clearTrapped()
|
||||
const trapping = await trappingCoreRuntime(MARKER)
|
||||
traps = trapping.traps
|
||||
engineStopped = () => trapping.runtime.stopped
|
||||
engineReady = () => trapping.runtime.ready()
|
||||
setCoreRuntime(trapping.runtime)
|
||||
setSheetProvider(bundledSheetProvider)
|
||||
// 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()
|
||||
vi.restoreAllMocks()
|
||||
useReportStore.getState().clearTrapped()
|
||||
setCoreRuntime(await testCoreRuntime())
|
||||
setSheetProvider(bundledSheetProvider)
|
||||
})
|
||||
|
||||
const routes = (initial: string) =>
|
||||
render(
|
||||
<MemoryRouter initialEntries={[initial]}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomeRoute />} />
|
||||
<Route path="/new" element={<NewReportRoute />} />
|
||||
<Route path="/editor" element={<EditorRoute />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
async function expectEnginePanel() {
|
||||
await screen.findByText(fr['session.held.notice_engine']!)
|
||||
expect(screen.getByTestId('held-draft')).toHaveTextContent(
|
||||
fr['session.held.draft_engine_failure']!.replace('{size}', /\d+ Ko/.exec(
|
||||
screen.getByTestId('held-draft').textContent ?? '',
|
||||
)![0]),
|
||||
)
|
||||
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
|
||||
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
|
||||
}
|
||||
|
||||
async function submitNewReport(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr X')
|
||||
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Rex')
|
||||
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
|
||||
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
|
||||
await waitFor(() => expect(submit).toBeEnabled())
|
||||
await user.click(submit)
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
|
||||
)
|
||||
}
|
||||
|
||||
async function pickCopy(user: ReturnType<typeof userEvent.setup>) {
|
||||
const pick = screen.getByRole('button', { name: fr['home.import.cta']! })
|
||||
await waitFor(() => expect(pick).toBeEnabled())
|
||||
await user.click(pick)
|
||||
vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
|
||||
)
|
||||
const copy = JSON.stringify(minimalReport(sheet, { id: 'other' }))
|
||||
fireEvent.change(document.querySelector('input[type="file"]')!, {
|
||||
target: { files: [new File([copy], 'copie.json', { type: 'application/json' })] },
|
||||
})
|
||||
}
|
||||
|
||||
describe('a draft the engine traps on', () => {
|
||||
it('opens the engine_failure panel, never the reload screen', async () => {
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
expect(traps.count).toBe(1)
|
||||
expect(engineStopped()).toBe(false)
|
||||
expect(useReportStore.getState().report).toBeNull()
|
||||
})
|
||||
|
||||
it('is read once across mount, New report, Import and remount', async () => {
|
||||
const user = userEvent.setup()
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
cleanup()
|
||||
|
||||
routes('/new')
|
||||
await submitNewReport(user)
|
||||
await waitFor(() =>
|
||||
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']),
|
||||
)
|
||||
await expectEnginePanel()
|
||||
cleanup()
|
||||
|
||||
routes('/')
|
||||
await pickCopy(user)
|
||||
await waitFor(() =>
|
||||
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']),
|
||||
)
|
||||
await expectEnginePanel()
|
||||
cleanup()
|
||||
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
expect(traps.count).toBe(1)
|
||||
expect(useReportStore.getState().report).toBeNull()
|
||||
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
|
||||
})
|
||||
|
||||
it('reads the pair again only on the panel Retry', async () => {
|
||||
const user = userEvent.setup()
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
// The instance that trapped is replaced in the background: retry on the fresh one.
|
||||
await engineReady()
|
||||
await user.click(screen.getByRole('button', { name: fr['session.held.retry'] }))
|
||||
await waitFor(() => expect(traps.count).toBe(2))
|
||||
await expectEnginePanel()
|
||||
})
|
||||
|
||||
it('removes only the draft after the confirmation and forgets the trap', async () => {
|
||||
const user = userEvent.setup()
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
await user.click(screen.getByRole('button', { name: fr['session.held.discard'] }))
|
||||
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: fr['session.held.discard_confirm'] }),
|
||||
)
|
||||
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
|
||||
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
|
||||
cleanup()
|
||||
await engineReady()
|
||||
// The memory is gone: the same text, stored again, is read (and traps) anew.
|
||||
sessionStorage.setItem(DRAFT_KEY, draft)
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
expect(traps.count).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -32,6 +32,7 @@ beforeEach(() => {
|
||||
archive: null,
|
||||
activeObservationIndex: 0,
|
||||
})
|
||||
useReportStore.getState().clearTrapped()
|
||||
})
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
@@ -91,7 +92,7 @@ describe('an unreadable draft', () => {
|
||||
})
|
||||
|
||||
describe('a core failure while reading the draft', () => {
|
||||
it.each(['core_unavailable', 'internal', 'rebase_failed'])(
|
||||
it.each(['core_unavailable', 'rebase_failed'])(
|
||||
'%s leaves the draft and the archive untouched',
|
||||
(kind) => {
|
||||
const draft = JSON.stringify(minimalReport(sheet))
|
||||
@@ -109,6 +110,91 @@ describe('a core failure while reading the draft', () => {
|
||||
)
|
||||
})
|
||||
|
||||
describe('a core trap while reading the draft (internal)', () => {
|
||||
/** A sheet whose draft restore traps (`internal`), counting the reads. */
|
||||
function trappingSheet() {
|
||||
const calls = { n: 0 }
|
||||
const index = {
|
||||
...sheet,
|
||||
ops: {
|
||||
restoreDraft: () => {
|
||||
calls.n += 1
|
||||
return { ok: false, kind: 'internal' }
|
||||
},
|
||||
},
|
||||
} as unknown as SheetIndex
|
||||
return { index, calls }
|
||||
}
|
||||
const draftText = () => JSON.stringify(minimalReport(sheet))
|
||||
|
||||
function seed() {
|
||||
const draft = draftText()
|
||||
sessionStorage.setItem(DRAFT_KEY, draft)
|
||||
sessionStorage.setItem(ARCHIVE_KEY, '{"kept":true}')
|
||||
return draft
|
||||
}
|
||||
|
||||
it('holds the draft (engine_failure) and its archive, both untouched', () => {
|
||||
const draft = seed()
|
||||
const { index } = trappingSheet()
|
||||
const result = useReportStore.getState().restoreDraft(index)
|
||||
expect(result).toMatchObject({
|
||||
kind: 'held',
|
||||
held: [
|
||||
{ text: 'draft', reason: 'engine_failure' },
|
||||
{ text: 'archive', reason: 'companion' },
|
||||
],
|
||||
})
|
||||
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()
|
||||
})
|
||||
|
||||
it('never reads the same pair again, except on the explicit retry', () => {
|
||||
seed()
|
||||
const { index, calls } = trappingSheet()
|
||||
const store = useReportStore.getState()
|
||||
store.restoreDraft(index)
|
||||
expect(store.restoreDraft(index)).toMatchObject({ kind: 'held' })
|
||||
expect(calls.n).toBe(1)
|
||||
store.restoreDraft(index, { retryTrapped: true })
|
||||
expect(calls.n).toBe(2)
|
||||
})
|
||||
|
||||
it('answers a new session HELD with the engine cause, without a second read', () => {
|
||||
seed()
|
||||
const { index, calls } = trappingSheet()
|
||||
const store = useReportStore.getState()
|
||||
store.restoreDraft(index)
|
||||
const draft = { practitioner: { name: 'p' } } as never
|
||||
expect(store.initReport(draft, sheet.sheet.ref, index)).toEqual({
|
||||
ok: false,
|
||||
reason: 'held',
|
||||
engine: true,
|
||||
})
|
||||
expect(store.hydrateImport({ report: minimalReport(sheet), archive: null }, index)).toEqual({
|
||||
ok: false,
|
||||
reason: 'held',
|
||||
engine: true,
|
||||
})
|
||||
expect(calls.n).toBe(1)
|
||||
})
|
||||
|
||||
it('reads again once the stored pair changed, or after a discard', () => {
|
||||
seed()
|
||||
const { index, calls } = trappingSheet()
|
||||
const store = useReportStore.getState()
|
||||
store.restoreDraft(index)
|
||||
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet, { conclusion: 'x' })))
|
||||
store.restoreDraft(index)
|
||||
expect(calls.n).toBe(2)
|
||||
store.discardSessionText('archive')
|
||||
store.restoreDraft(index)
|
||||
expect(calls.n).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('an unreadable archive beside a readable draft', () => {
|
||||
it('goes to its quarantine key while the draft restores', () => {
|
||||
sessionStorage.setItem(
|
||||
|
||||
Reference in new issue
Block a user