fix(store): hold session texts whose set-aside fails, never overwrite them

This commit is contained in:
bchanot committed 2026-10-14 23:11:59 +02:00
1 parent 1312b366b1
commit e34b7f282e
19 files changed
+1093 -86

No files matched your search

+3 -1
View File
@@ -86,6 +86,7 @@ describe('drafts written through the core', () => {
nextAppointment: { kind: 'period', text: 'dans 3 semaines' },
},
sheet.sheet.ref,
sheet,
)
await expectN1ReadsTheDraft()
})
@@ -102,6 +103,7 @@ describe('drafts written through the core', () => {
recommendations: '',
},
sheet.sheet.ref,
sheet,
)
const apply = (obs: ReturnType<typeof current>) =>
useReportStore.getState().updateObservation(0, obs)
@@ -164,7 +166,7 @@ describe('drafts written through the core', () => {
)
useReportStore
.getState()
.hydrateImport({ report: rebase.report, archive: read.archive })
.hydrateImport({ report: rebase.report, archive: read.archive }, sheet)
await expectN1ReadsTheDraft()
const archive: unknown = JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!)
expect(ReportArchiveEnvelopeSchema.safeParse(archive).success).toBe(true)
@@ -45,7 +45,7 @@ beforeEach(() => {
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null })
.hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
exportMock.mockReset()
downloads.length = 0
URL.createObjectURL = vi.fn(() => 'blob:faunosteo-test')
@@ -56,7 +56,7 @@ beforeEach(() => {
],
}),
archive: null,
})
}, sheet)
})
afterEach(() => {
cleanup()
@@ -0,0 +1,212 @@
/**
* R2 maintenance B, interface (owner choice 2026-10-14): a session text that
* could not be set aside shows the resolution panel in the editor (copy to
* download, deletion or replacement only after a confirmation, retry); a new
* report started from /new is refused and sends the practitioner there; a
* refused draft write shows the storage-full banner.
*/
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 NewReportRoute from '@/app/routes/NewReportRoute'
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 { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
const UNREADABLE = JSON.stringify({ version: 7 })
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
saveFailed: false,
})
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())
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
function quarantineFull() {
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)
})
}
function mount(path: '/editor' | '/new') {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/" element={<p data-testid="home-route" />} />
<Route path="/new" element={<NewReportRoute />} />
<Route path="/editor" element={<EditorRoute />} />
</Routes>
</MemoryRouter>,
)
}
describe('the resolution panel', () => {
it('lists the held draft, deletes it only after the confirmation, then leaves', async () => {
const user = userEvent.setup()
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
mount('/editor')
await screen.findByText(fr['session.held.notice']!)
expect(screen.getByTestId('held-draft')).toHaveTextContent(
fr['session.held.draft_unreadable']!.replace('{size}', '1 Ko'),
)
await user.click(screen.getByRole('button', { name: fr['session.held.discard'] }))
const dialog = screen.getByRole('dialog')
expect(dialog).toHaveTextContent(fr['session.held.discard_body']!)
await user.click(screen.getByRole('button', { name: fr['common.cancel'] }))
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(UNREADABLE)
await user.click(screen.getByRole('button', { name: fr['session.held.discard'] }))
await user.click(
screen.getByRole('button', { name: fr['session.held.discard_confirm'] }),
)
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
await screen.findByTestId('home-route')
})
it('downloads the stored text verbatim', async () => {
const user = userEvent.setup()
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
const blobs: Blob[] = []
URL.createObjectURL = vi.fn((blob: Blob) => {
blobs.push(blob)
return 'blob:held'
})
URL.revokeObjectURL = vi.fn()
const clicks = vi
.spyOn(HTMLAnchorElement.prototype, 'click')
.mockImplementation(() => undefined)
mount('/editor')
await user.click(
await screen.findByRole('button', { name: fr['session.held.download'] }),
)
expect(clicks).toHaveBeenCalledOnce()
expect(await blobs[0]!.text()).toBe(UNREADABLE)
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(UNREADABLE)
})
it('opens the adapted draft only after the replacement is confirmed', async () => {
const user = userEvent.setup()
const stale = JSON.stringify(
minimalReport(sheet, {
conclusion: 'work in progress',
sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}),
)
sessionStorage.setItem(DRAFT_KEY, stale)
quarantineFull()
mount('/editor')
await user.click(
await screen.findByRole('button', { name: fr['session.held.open_adapted'] }),
)
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(stale)
await user.click(
screen.getByRole('button', { name: fr['session.held.open_confirm'] }),
)
await waitFor(() =>
expect(useReportStore.getState().report?.conclusion).toBe('work in progress'),
)
expect(screen.queryByText(fr['session.held.notice']!)).toBeNull()
})
it('retries the set-aside once the storage accepts it', async () => {
const user = userEvent.setup()
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
mount('/editor')
await screen.findByText(fr['session.held.notice']!)
vi.restoreAllMocks()
await user.click(screen.getByRole('button', { name: fr['session.held.retry'] }))
await screen.findByTestId('home-route')
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(UNREADABLE)
})
})
describe('a new report over a held draft', () => {
it('is refused and sends the practitioner to the resolution panel', async () => {
const user = userEvent.setup()
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
mount('/new')
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)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked']),
)
await screen.findByText(fr['session.held.notice']!)
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(UNREADABLE)
expect(useReportStore.getState().report).toBeNull()
})
})
describe('the storage-full banner', () => {
it('shows while the draft mirror is refused and goes once a write succeeds', async () => {
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
mount('/editor')
await screen.findByTestId('sheet-status')
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull()
const setItem = sessionStorage.setItem.bind(sessionStorage)
const spy = vi
.spyOn(sessionStorage, 'setItem')
.mockImplementation((key, value) => {
if (key === DRAFT_KEY) throw new DOMException('full', 'QuotaExceededError')
setItem(key, value)
})
useReportStore.getState().setConclusion('lost on reload')
await screen.findByText(fr['editor.save_failed']!)
spy.mockRestore()
useReportStore.getState().setConclusion('saved')
await waitFor(() =>
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull(),
)
})
})
@@ -88,14 +88,14 @@ describe('store actions on a failing core', () => {
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(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)).toEqual({ ok: true })
expect(s.initReport(draft(), sheet.sheet.ref, sheet)).toEqual({ ok: true })
expect(s.addObservation()).toEqual({ ok: true })
expect(useReportStore.getState().report!.observations).toHaveLength(2)
})
@@ -0,0 +1,309 @@
/**
* R2 maintenance B (owner rule 2026-10-14): no session text is removed or
* overwritten implicitly when a save or a quarantine fails. A text whose
* safety copy fails stays where it is (`held`), nothing is opened over it,
* and every later action that would replace it (new report, import, reset,
* an unrelated store change) leaves it alone until the practitioner decides.
* Covers the quota errors, the refused writes, an occupied quarantine slot,
* corrupted texts and the later overwriting actions.
*/
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 { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
saveFailed: false,
})
sessionStorage.clear()
})
afterEach(() => vi.restoreAllMocks())
const store = () => useReportStore.getState()
const UNREADABLE = JSON.stringify({ version: 7 })
const newDraft = () => ({
date: '2026-10-14',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
})
/** The storage refuses writes to the keys `refused` matches, as a full quota does. */
function refuseWrites(refused: (key: string) => boolean) {
const setItem = sessionStorage.setItem.bind(sessionStorage)
vi.spyOn(sessionStorage, 'setItem').mockImplementation((key, value) => {
if (refused(key)) throw new DOMException('full', 'QuotaExceededError')
setItem(key, value)
})
}
const quarantineFull = () =>
refuseWrites((key) => key.startsWith('osteo:quarantine:'))
/** Every session key and its value: what must not move. */
function snapshotStorage(): Record<string, string | null> {
const keys = [DRAFT_KEY, ARCHIVE_KEY, ...Object.values(QUARANTINE_KEYS)]
return Object.fromEntries(keys.map((k) => [k, sessionStorage.getItem(k)]))
}
/** The editor's sequence for a draft it cannot set aside, then the later actions. */
function expectEveryLaterActionRefused(before: Record<string, string | null>) {
expect(store().initReport(newDraft(), sheet.sheet.ref, sheet)).toEqual({
ok: false,
reason: 'held',
})
const report = minimalReport(sheet)
expect(
store().hydrateImport({ report, archive: archiveEnvelope(sheet, report) }, sheet),
).toEqual({ ok: false, reason: 'held' })
store().reset()
store().setActiveObservation(3)
store().setConclusion('x')
expect(store().report).toBeNull()
expect(snapshotStorage()).toEqual(before)
}
describe('an unreadable draft that cannot be set aside', () => {
it('is held verbatim when the quota refuses the quarantine write', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
const before = snapshotStorage()
expect(store().restoreDraft(sheet)).toEqual({
kind: 'held',
held: [{ text: 'draft', reason: 'unreadable', bytes: UNREADABLE.length }],
})
expectEveryLaterActionRefused(before)
})
it('never replaces an earlier text already in its quarantine slot', () => {
sessionStorage.setItem(QUARANTINE_KEYS.draft, '{"earlier":true}')
sessionStorage.setItem(DRAFT_KEY, '{not json')
const before = snapshotStorage()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'draft', reason: 'unreadable' }],
})
expectEveryLaterActionRefused(before)
})
it('is set aside when the slot already holds the same text (idempotent)', () => {
sessionStorage.setItem(QUARANTINE_KEYS.draft, UNREADABLE)
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
expect(store().restoreDraft(sheet)).toEqual({ kind: 'quarantined' })
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
})
it('keeps a lone surrogate (L1) text byte for byte', () => {
const raw = JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' }))
sessionStorage.setItem(DRAFT_KEY, raw)
quarantineFull()
expect(store().restoreDraft(sheet)).toMatchObject({ kind: 'held' })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(raw)
})
})
describe('an unreadable draft and the archive beside it', () => {
it('go to quarantine together, so no later session removes the archive', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
sessionStorage.setItem(ARCHIVE_KEY, '{"archive":1}')
expect(store().restoreDraft(sheet)).toEqual({ kind: 'quarantined' })
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(UNREADABLE)
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{"archive":1}')
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()
})
it('both stay in place, the draft copy undone, when the archive copy fails', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
sessionStorage.setItem(ARCHIVE_KEY, '{"archive":1}')
refuseWrites((key) => key === QUARANTINE_KEYS.archive)
const before = snapshotStorage()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [
{ text: 'draft', reason: 'unreadable' },
{ text: 'archive', reason: 'companion' },
],
})
expect(snapshotStorage()).toEqual(before)
expectEveryLaterActionRefused(before)
})
})
describe('an unreadable archive beside a readable draft', () => {
it('is held, and the draft is not opened over it', () => {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
quarantineFull()
const before = snapshotStorage()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'archive', reason: 'unreadable' }],
})
expectEveryLaterActionRefused(before)
})
it('once deleted on request, lets the draft open', () => {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
quarantineFull()
expect(store().restoreDraft(sheet)).toMatchObject({ kind: 'held' })
store().discardSessionText('archive')
expect(sessionStorage.getItem(DRAFT_KEY)).not.toBeNull()
expect(store().restoreDraft(sheet)).toMatchObject({ kind: 'restored' })
})
})
describe('an archive with no draft beside it', () => {
it('is set aside, or held when that fails', () => {
sessionStorage.setItem(ARCHIVE_KEY, '{"orphan":1}')
quarantineFull()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'archive', reason: 'companion' }],
})
vi.restoreAllMocks()
expect(store().restoreDraft(sheet)).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{"orphan":1}')
})
})
describe('a draft rebased with unresolved items whose original cannot be kept', () => {
const stale = () =>
JSON.stringify(
minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}),
)
it('is held unrebased: the mirror never overwrites the original', () => {
const raw = stale()
sessionStorage.setItem(DRAFT_KEY, raw)
quarantineFull()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'draft', reason: 'pre_rebase' }],
})
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(raw)
expect(store().report).toBeNull()
})
it('opens the adapted version only on the confirmed replacement', () => {
const raw = stale()
sessionStorage.setItem(DRAFT_KEY, raw)
quarantineFull()
expect(store().restoreDraft(sheet, { replaceOriginal: true })).toMatchObject({
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 1 },
})
expect(store().report).not.toBeNull()
expect(sessionStorage.getItem(DRAFT_KEY)).not.toBe(raw)
})
})
describe('a new session over texts this page never read (after a reload)', () => {
it('sets an unreadable draft and its archive aside before starting', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
sessionStorage.setItem(ARCHIVE_KEY, '{"archive":1}')
expect(store().initReport(newDraft(), sheet.sheet.ref, sheet)).toEqual({ ok: true })
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(UNREADABLE)
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{"archive":1}')
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3)
})
it('is refused, nothing touched, when that set-aside fails', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
const before = snapshotStorage()
expectEveryLaterActionRefused(before)
})
it('sets an unreadable archive beside a readable draft aside before an import', () => {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
const report = minimalReport(sheet, { conclusion: 'imported' })
expect(store().hydrateImport({ report, archive: null }, sheet)).toEqual({ ok: true })
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{not json')
})
it('replaces a readable draft as before (explicit new report)', () => {
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(minimalReport(sheet, { conclusion: 'previous' })),
)
expect(store().initReport(newDraft(), sheet.sheet.ref, sheet)).toEqual({ ok: true })
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).conclusion).toBe('')
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
it('is refused when the core cannot read the draft at all', () => {
const draft = JSON.stringify(minimalReport(sheet))
sessionStorage.setItem(DRAFT_KEY, draft)
const broken = {
...sheet,
ops: { restoreDraft: () => ({ ok: false, kind: 'core_unavailable' }) },
} as unknown as SheetIndex
expect(store().initReport(newDraft(), sheet.sheet.ref, broken)).toEqual({
ok: false,
reason: 'held',
})
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
})
})
describe('the draft mirror', () => {
it('reports a refused write and keeps the previous text in place', () => {
store().initReport(newDraft(), sheet.sheet.ref, sheet)
const saved = sessionStorage.getItem(DRAFT_KEY)
refuseWrites((key) => key === DRAFT_KEY)
store().setConclusion('not saved')
expect(store().saveFailed).toBe(true)
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(saved)
vi.restoreAllMocks()
store().setConclusion('saved again')
expect(store().saveFailed).toBe(false)
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).conclusion).toBe('saved again')
})
it('is never written or removed by a change that leaves the report alone', () => {
sessionStorage.setItem(DRAFT_KEY, '{"unread":true}')
store().setActiveObservation(2)
useReportStore.setState({ archive: null })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe('{"unread":true}')
})
it('a deletion request is ignored while a report is open', () => {
store().initReport(newDraft(), sheet.sheet.ref, sheet)
store().discardSessionText('draft')
expect(sessionStorage.getItem(DRAFT_KEY)).not.toBeNull()
})
})
+4 -1
View File
@@ -81,7 +81,10 @@ describe('an unreadable draft', () => {
setItem(key, value)
})
// Not announced as set aside: the editor stays put instead of leaving for Home.
expect(restore()).toEqual({ kind: 'unreadable_kept' })
expect(restore()).toEqual({
kind: 'held',
held: [{ text: 'draft', reason: 'unreadable', bytes: raw.length }],
})
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(raw)
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
+23 -21
View File
@@ -51,7 +51,7 @@ const draft = () => ({
describe('initReport', () => {
it('stamps version 3, id, createdAt, the sheet ref and one empty observation', () => {
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet)
const report = useReportStore.getState().report!
expect(report.version).toBe(3)
expect(report.id).toBeTruthy()
@@ -66,7 +66,7 @@ describe('initReport', () => {
describe('observation actions', () => {
it('adds, updates, moves and removes observations, keeping the active index sane', () => {
const s = useReportStore.getState()
s.initReport(draft(), sheet.sheet.ref)
s.initReport(draft(), sheet.sheet.ref, sheet)
s.addObservation()
expect(useReportStore.getState().report!.observations).toHaveLength(2)
expect(useReportStore.getState().activeObservationIndex).toBe(1)
@@ -91,7 +91,7 @@ describe('observation actions', () => {
it('setters replace identity, conclusion and appointment; nextAppointment can be cleared', () => {
const s = useReportStore.getState()
s.initReport(draft(), sheet.sheet.ref)
s.initReport(draft(), sheet.sheet.ref, sheet)
s.setPractitioner({ name: 'Dr. X' })
s.setAnimal({ speciesId: 'equine', name: 'Y' })
s.setOwner({ name: 'Z' })
@@ -124,7 +124,7 @@ describe('observation actions', () => {
describe('sessionStorage mirror and restore', () => {
it('mirrors every change under osteo:draft and removes it on reset', () => {
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet)
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3)
useReportStore.getState().reset()
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
@@ -154,15 +154,17 @@ describe('sessionStorage mirror and restore', () => {
kind: 'quarantined',
})
expect(useReportStore.getState().report).toBeNull()
// R2 maintenance B: the slot already holds the first text, which is never replaced.
sessionStorage.setItem(DRAFT_KEY, JSON.stringify({ version: 1 }))
expect(useReportStore.getState().restoreDraft(sheet)).toEqual({
kind: 'quarantined',
expect(useReportStore.getState().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'draft', reason: 'unreadable' }],
})
expect(useReportStore.getState().report).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(
JSON.stringify({ version: 1 }),
)
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe('{not json')
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(JSON.stringify({ version: 1 }))
useReportStore.getState().discardSessionText('draft')
useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet)
const before = useReportStore.getState().report
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
useReportStore.getState().restoreDraft(sheet)
@@ -172,10 +174,10 @@ describe('sessionStorage mirror and restore', () => {
it('createReportStore accepts another persistence adapter', () => {
const saved: unknown[] = []
const store = createReportStore(
{ loadText: () => null, save: (r) => saved.push(r) },
{ loadText: () => null, save: () => undefined },
{ loadText: () => null, save: (r) => saved.push(r) > 0 },
{ loadText: () => null, save: () => true },
)
store.getState().initReport(draft(), sheet.sheet.ref)
store.getState().initReport(draft(), sheet.sheet.ref, sheet)
expect(saved.at(-1)).toMatchObject({ version: 3 })
})
})
@@ -200,7 +202,7 @@ describe('archive of an imported Step 6 PDF', () => {
it('hydrateImport keeps the archive and mirrors it under osteo:archive', () => {
const report = minimalReport(sheet)
const archive = archiveEnvelope(sheet, report)
useReportStore.getState().hydrateImport({ report, archive })
useReportStore.getState().hydrateImport({ report, archive }, sheet)
expect(useReportStore.getState().archive).toEqual(archive)
expect(JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!).report.id).toBe(
report.id,
@@ -211,12 +213,12 @@ 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(
{ loadText: () => null, save: () => undefined },
{ loadText: () => null, save: (a) => archiveSaves.push(a) },
{ loadText: () => null, save: () => true },
{ loadText: () => null, save: (a) => archiveSaves.push(a) > 0 },
)
const report = minimalReport(sheet)
const archive = archiveEnvelope(sheet, report)
store.getState().hydrateImport({ report, archive })
store.getState().hydrateImport({ report, archive }, sheet)
expect(archiveSaves).toEqual([archive])
store.getState().setConclusion('edited')
store.getState().addObservation()
@@ -230,7 +232,7 @@ describe('archive of an imported Step 6 PDF', () => {
it('restoreDraft brings the archive back with the draft', () => {
const report = minimalReport(sheet, { conclusion: 'kept' })
const archive = archiveEnvelope(sheet, report)
useReportStore.getState().hydrateImport({ report, archive })
useReportStore.getState().hydrateImport({ report, archive }, sheet)
// Emptying the state clears the draft mirror, not the archive mirror.
useReportStore.setState({ report: null, archive: null })
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
@@ -248,21 +250,21 @@ describe('archive of an imported Step 6 PDF', () => {
it.each([
[
'initReport',
() => useReportStore.getState().initReport(draft(), sheet.sheet.ref),
() => useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet),
],
[
'hydrateImport without an archive',
() =>
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null }),
.hydrateImport({ report: minimalReport(sheet), archive: null }, sheet),
],
['reset', () => useReportStore.getState().reset()],
])('%s clears the archive and removes its mirror', (_name, act) => {
const report = minimalReport(sheet)
useReportStore
.getState()
.hydrateImport({ report, archive: archiveEnvelope(sheet, report) })
.hydrateImport({ report, archive: archiveEnvelope(sheet, report) }, sheet)
act()
expect(useReportStore.getState().archive).toBeNull()
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()