/** Lot E: the blocking recovery offer, the unreadable copy, the cap and quota notice. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, screen, waitFor, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { fr } from '@/i18n/fr' import { useLeaveGuardStore } from '@/state/leaveGuardStore' import { SHEET, USER, VERSION, baseText, commitMove, copyKeyOf, resetStore, sb, serverHas, storedCopy, store, } from '../helpers/editorHarness' import { grant, mountDraft, setWidth } from '../helpers/editorRoute' vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) vi.mock('@faunosteo/supabase', async (orig) => ({ ...(await orig()), getSheetVersion: vi.fn(), downloadSheetDrawing: vi.fn(), saveSheetDraft: vi.fn(), getOfficialSheetAdmin: vi.fn(), submitSheetReview: vi.fn(), })) beforeEach(() => serverHas(baseText(), 3)) afterEach(() => { cleanup() resetStore() setWidth(1024) }) const ready = () => screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' }) function movedText(x: number): string { return JSON.stringify( JSON.parse(baseText(), (key, value) => (key === 'cx' ? x : value)), ) } function seed( version: string, revision: number, text = movedText(10), over = {}, ) { sessionStorage.setItem( copyKeyOf(version, USER), JSON.stringify({ v: 1, user_id: USER, version_id: version, sheet_id: version === VERSION ? SHEET : `sheet-${version}`, sheet_name: 'Autre fiche', revision, written_at: '2026-11-03T10:00:00Z', document: JSON.parse(text), drawings: [], ...over, }), ) } describe('the blocking offer', () => { it('names the copy and its answers; consultation works, editing is refused', async () => { const user = userEvent.setup() seed(VERSION, 3) mountDraft() await ready() expect( screen.getByText( /Une copie locale temporaire de ce brouillon existe dans cet onglet \(révision 3, \d\d:\d\d\)/, ), ).toBeInTheDocument() expect( screen.getByText(/Choisissez avant de modifier le brouillon\./), ).toBeInTheDocument() expect( screen.getByRole('button', { name: 'Restaurer la copie' }), ).toBeEnabled() expect( screen.getByRole('button', { name: 'Ignorer la copie' }), ).toBeEnabled() expect(useLeaveGuardStore.getState().armed).toBe(true) // consultation: tabs still switch await user.click(screen.getByRole('tab', { name: 'Références' })) expect(screen.getByTestId('editor-tab-references')).toBeVisible() expect(screen.getByTestId('editor-tab-references')).toHaveAttribute( 'aria-labelledby', 'editor-references-title', ) // editing: refused by the store, no save offered expect(commitMove(40)).toMatchObject({ ok: false, kind: 'recovery.pending', }) expect(screen.getByRole('button', { name: 'Enregistrer' })).toBeDisabled() expect(sessionStorage.getItem(copyKeyOf())).not.toBeNull() }) it('an older base adds the server revision to the notice', async () => { seed(VERSION, 2) mountDraft() await ready() expect( screen.getByText( /Elle est basée sur la révision 2 ; le serveur est à la révision 3\./, ), ).toBeInTheDocument() }) it('restore applies the copy as unsaved work and lifts the block', async () => { const user = userEvent.setup() seed(VERSION, 3) mountDraft() await ready() await user.click(screen.getByRole('button', { name: 'Restaurer la copie' })) await waitFor(() => expect(screen.getByTestId('save-line')).toHaveTextContent( /^Modifications non enregistrées$/, ), ) expect( screen.queryByRole('button', { name: 'Restaurer la copie' }), ).toBeNull() expect(store.getState()).toMatchObject({ recovery: 'none', unsaved: true }) }) it('ignore asks first and keeps the copy until confirmed', async () => { const user = userEvent.setup() seed(VERSION, 3) mountDraft() await ready() await user.click(screen.getByRole('button', { name: 'Ignorer la copie' })) const dialog = within(await screen.findByRole('dialog')) expect( dialog.getByText( /Abandonner la copie locale temporaire de cet onglet, non enregistrée sur le serveur \(révision 3, \d\d:\d\d\) \? Elle sera supprimée de cet onglet\./, ), ).toBeInTheDocument() await user.click(dialog.getByRole('button', { name: 'Annuler' })) expect(sessionStorage.getItem(copyKeyOf())).not.toBeNull() await user.click(screen.getByRole('button', { name: 'Ignorer la copie' })) await user.click( within(await screen.findByRole('dialog')).getByRole('button', { name: 'Abandonner la copie', }), ) await waitFor(() => expect(sessionStorage.getItem(copyKeyOf())).toBeNull()) expect( screen.queryByRole('button', { name: 'Ignorer la copie' }), ).toBeNull() expect(useLeaveGuardStore.getState().armed).toBe(false) expect(store.getState().recovery).toBe('none') }) it('an unreadable copy: the loss named, « Ignorer » only, kept until ignored', async () => { const user = userEvent.setup() sessionStorage.setItem(copyKeyOf(), 'not json{') mountDraft() await ready() expect( screen.getByText(fr['editor.draft.recovery.unreadable']), ).toBeInTheDocument() expect( screen.queryByRole('button', { name: 'Restaurer la copie' }), ).toBeNull() expect(commitMove(40)).toMatchObject({ kind: 'recovery.pending' }) expect(sessionStorage.getItem(copyKeyOf())).toBe('not json{') await user.click(screen.getByRole('button', { name: 'Ignorer la copie' })) await user.click( within(await screen.findByRole('dialog')).getByRole('button', { name: 'Abandonner la copie', }), ) await waitFor(() => expect(sessionStorage.getItem(copyKeyOf())).toBeNull()) }) it('a copy the core refuses is kept: its kind shown, restore disabled', async () => { const broken = JSON.parse(baseText()) broken.views = 'broken' seed(VERSION, 3, JSON.stringify(broken)) const user = userEvent.setup() mountDraft() await ready() await user.click(screen.getByRole('button', { name: 'Restaurer la copie' })) expect( await screen.findByText( /Le contrôle du document refuse cette copie : .+\. Elle reste dans cet onglet\./, ), ).toBeInTheDocument() expect( screen.getByRole('button', { name: 'Restaurer la copie' }), ).toBeDisabled() expect(sessionStorage.getItem(copyKeyOf())).not.toBeNull() }) it('narrow screen: the offer shows; a mode that cannot save names the copy and leaves it', async () => { seed(VERSION, 3) mountDraft({ width: 800 }) await ready() expect( screen.getByRole('button', { name: 'Restaurer la copie' }), ).toBeInTheDocument() cleanup() resetStore() serverHas(baseText(), 3) seed(VERSION, 3) const raw = sessionStorage.getItem(copyKeyOf()) mountDraft({ grants: [grant('sheet_reviewer')] }) await ready() expect( screen.queryByRole('button', { name: 'Restaurer la copie' }), ).toBeNull() expect( screen.getByText(fr['editor.draft.mode.unusable_copy']), ).toBeInTheDocument() expect(sessionStorage.getItem(copyKeyOf())).toBe(raw) }) }) describe('cap and quota', () => { it('cap: the header says so, the other copies are listed with their sheet link; abandon retries the write', async () => { const user = userEvent.setup() seed('ver-2', 5) seed('ver-3', 6) mountDraft() await ready() act(() => void commitMove(40)) await waitFor(() => expect(screen.getByTestId('save-line')).toHaveTextContent( fr['editor.draft.status.copy_cap'], ), ) expect(storedCopy()).toBeNull() const items = screen .getAllByRole('listitem') .filter((item) => /Autre fiche/.test(item.textContent ?? '')) expect(items).toHaveLength(2) expect( within(items[0]).getByText(/Autre fiche · révision 5 · \d\d:\d\d/), ).toBeInTheDocument() expect( within(items[0]).getByRole('link', { name: 'Ouvrir ce brouillon' }), ).toHaveAttribute('href', '/app/admin/sheets/sheet-ver-2/draft') await user.click( within(items[0]).getByRole('button', { name: 'Abandonner cette copie' }), ) const dialog = within(await screen.findByRole('dialog')) expect(dialog.getByText(/révision 5/)).toBeInTheDocument() await user.click( dialog.getByRole('button', { name: 'Abandonner la copie' }), ) await waitFor(() => expect(storedCopy()).not.toBeNull()) expect(sessionStorage.getItem(copyKeyOf('ver-2'))).toBeNull() expect(sessionStorage.getItem(copyKeyOf('ver-3'))).not.toBeNull() expect(screen.getByTestId('save-line')).not.toHaveTextContent( fr['editor.draft.status.copy_cap'], ) }) it('quota: the full-storage status and notice, the other copies untouched', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}) vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => { throw new DOMException('full', 'QuotaExceededError') }) mountDraft() await ready() act(() => void commitMove(40)) await waitFor(() => expect(screen.getByTestId('save-line')).toHaveTextContent( fr['editor.draft.status.copy_quota'], ), ) expect( screen.getByText(fr['editor.draft.copy_issue.quota']), ).toBeInTheDocument() expect(store.getState().copyWritten).toBe(false) }) }) describe('the save stays disabled while the offer is pending', () => { it('no save call is made', async () => { seed(VERSION, 3) mountDraft() await ready() await store.getState().save() expect(sb.saveSheetDraft).not.toHaveBeenCalled() }) })