import { afterEach, beforeAll, beforeEach, describe, expect, it, vi, } from 'vitest' import { cleanup, render, screen, waitFor, within, } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom' import type { OwnCatalogGrant, PlatformRole } from '@faunosteo/supabase' import { createFakeSupabase, type FakeSupabase } from '../helpers/fakeSupabase' import { testCoreRuntime } from '../helpers/core' const mocks = vi.hoisted(() => ({ fake: null as unknown })) vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null, isSupabaseConfigured: () => mocks.fake !== null, })) import AdminHomeRoute from '@/app/routes/app/admin/AdminHomeRoute' import AdminSheetsRoute from '@/app/routes/app/admin/AdminSheetsRoute' import AdminSheetCreateRoute from '@/app/routes/app/admin/AdminSheetCreateRoute' import AdminSheetRoute from '@/app/routes/app/admin/AdminSheetRoute' import AdminSpeciesRoute from '@/app/routes/app/admin/AdminSpeciesRoute' import AdminAccessRoute from '@/app/routes/app/admin/AdminAccessRoute' import { NO_FILTER, filterSheets } from '@/admin/filters' import { proposeSlug } from '@/admin/validation' import { setCoreRuntime } from '@/core/runtime' import { useAuthStore } from '@/state/authStore' import { useLocaleStore } from '@/state/localeStore' import { fr } from '@/i18n/fr' /** * The administration screens (V1-2.5 G, H) on a fake client: what each * account sees (a display rule: the server decides), the calls the actions * make and how refusals read. RPC shapes are proven in packages/supabase; * the journeys run in Chromium in the e2e shell suite. */ const SHEET = '33333333-3333-4333-8333-333333333333' const HISTORICAL = '503dc301-0000-4000-8000-000000000001' const NEW_ID = '44444444-4444-4444-8444-444444444444' let fake: FakeSupabase function grant(kind: OwnCatalogGrant['kind']): OwnCatalogGrant { return { kind, expires_at: null, revoked_at: null } } function summary(patch: Record = {}) { return { sheet_id: SHEET, species_id: 'equine', slug: 'cheval-squelette', status: 'active', archived_at: null, created_at: '2026-11-01T10:00:00Z', updated_at: '2026-11-01T10:00:00Z', last_modified_at: '2026-11-01T10:00:00.000000+00:00', name: { fr: 'Cheval, squelette et rachis', en: 'Horse, skeleton and spine', }, historical: false, working_copy: true, working_copy_active: null, latest_version: { version_id: 'v-1', version_number: 1, status: 'draft', revision: 3, }, current_version: null, draft_version: { version_id: 'v-1', version_number: 1, revision: 3 }, version_statuses: ['draft'], open_rounds: 1, latest_round: { review_id: 'r-1', version_number: 1, round: 1, status: 'open', submitted_at: null, }, ...patch, } } const historical = () => summary({ sheet_id: HISTORICAL, slug: 'equine', name: { fr: 'Cheval', en: 'Horse' }, historical: true, working_copy: false, working_copy_active: true, open_rounds: 0, latest_round: null, latest_version: { version_id: 'v-h', version_number: 1, status: 'draft', revision: 0, }, }) const SPECIES = [ { id: 'equine', name_fr: 'Cheval', name_en: 'Horse', sort_order: 10, active: true, }, { id: 'camelid', name_fr: 'Chameau', name_en: 'Camel', sort_order: 120, active: false, }, { id: 'other', name_fr: 'Autre', name_en: 'Other', sort_order: 999, active: true, }, ] const refusal = (message: string) => ({ error: { code: '42501', message } }) const rpcArgs = (name: string) => fake.rpcCalls .filter(([n]) => n === name) .map(([, a]) => a as Record) function Where() { return {useLocation().pathname} } function mount( path: string, grants: OwnCatalogGrant[], roles: PlatformRole[] = [], status: 'loading' | 'ready' | 'failed' = 'ready', ) { useAuthStore.setState({ catalogGrants: grants, catalogGrantsStatus: status, roles }) return render( } /> } /> } /> } /> draft page

} /> } /> } /> catalogue page

} />
, ) } beforeAll(async () => { setCoreRuntime(await testCoreRuntime()) }) const realReloadAccess = useAuthStore.getState().reloadAccess beforeEach(() => { useLocaleStore.setState({ locale: 'fr' }) fake = createFakeSupabase() fake.rpcResults.list_official_sheets_admin = { data: [summary(), historical()], } fake.rpcResults.list_catalog_species = { data: SPECIES } mocks.fake = fake }) afterEach(() => { cleanup() useAuthStore.setState({ reloadAccess: realReloadAccess }) }) describe('Administration page: own grants states', () => { it('loading: the waiting status, not « aucune »', () => { mount('/app/admin', [], [], 'loading') expect(screen.getByText(fr['shell.loading_session'])).toHaveAttribute('role', 'status') expect(screen.queryByText(/aucune/)).toBeNull() }) it('failed: the unavailable notice as a section, Retry, focus kept on the wrapper', async () => { const user = userEvent.setup() const reloadAccess = vi.fn(async () => useAuthStore.setState({ catalogGrants: [grant('sheet_editor')], catalogGrantsStatus: 'ready' }), ) mount('/app/admin', [], [], 'failed') useAuthStore.setState({ reloadAccess }) expect(screen.getAllByRole('heading', { level: 1 })).toHaveLength(1) expect( screen.getByRole('heading', { level: 2, name: fr['permissions_unavailable.title'] }), ).toBeInTheDocument() expect(screen.queryByText(/aucune/)).toBeNull() await user.click(screen.getByRole('button', { name: 'Réessayer' })) expect(reloadAccess).toHaveBeenCalledTimes(1) await waitFor(() => expect(screen.getByText(/Vos habilitations : éditeur de fiches/)).toBeInTheDocument(), ) const wrapper = screen.getByText(/Vos habilitations/).parentElement expect(wrapper).toHaveFocus() }) }) describe('Administration page (board 10)', () => { it('editor and publisher: permissions line, sheets with badges, the working copy action disabled with its reason', async () => { mount('/app/admin', [ grant('sheet_editor'), grant('sheet_publisher'), grant('catalog_reader'), ]) expect( screen.getByText( 'Vos habilitations : éditeur de fiches, responsable de publication · session renforcée (double authentification) active.', ), ).toBeInTheDocument() expect( await screen.findByRole('link', { name: 'Cheval, squelette et rachis' }), ).toBeInTheDocument() expect(screen.getByText('Copie de travail')).toBeInTheDocument() expect(screen.getByText('1 à relire')).toBeInTheDocument() expect(screen.getByText('Fiche historique')).toBeInTheDocument() const action = screen.getByRole('button', { name: 'Créer une copie de travail', }) expect(action).toBeDisabled() expect(action).toHaveAccessibleDescription(fr['admin.working_copy.active']) expect(screen.getByRole('heading', { name: 'Espèces' })).toBeInTheDocument() expect( screen.queryByRole('heading', { name: 'Accès et habilitations' }), ).toBeNull() }) it('reviewer only: the sheets card without the working copy action, no rights card', async () => { mount('/app/admin', [grant('sheet_reviewer')]) expect( screen.getByText( /^Vos habilitations : relecteur ou relectrice · session/, ), ).toBeInTheDocument() expect( await screen.findByRole('link', { name: 'Cheval' }), ).toBeInTheDocument() expect( screen.queryByRole('button', { name: 'Créer une copie de travail' }), ).toBeNull() expect( screen.queryByRole('heading', { name: 'Accès et habilitations' }), ).toBeNull() expect(screen.getByRole('heading', { name: 'Espèces' })).toBeInTheDocument() }) it('publisher only: no working copy action', async () => { mount('/app/admin', [grant('sheet_publisher')]) expect( await screen.findByRole('link', { name: 'Cheval' }), ).toBeInTheDocument() expect( screen.queryByRole('button', { name: 'Créer une copie de travail' }), ).toBeNull() }) it('owner without capability: the server refuses the list, so only species and rights show', async () => { fake.rpcResults.list_official_sheets_admin = refusal('rights.capability') mount('/app/admin', [], ['owner']) expect( screen.getByText( 'Vos habilitations : aucune · rôle propriétaire · session renforcée (double authentification) active.', ), ).toBeInTheDocument() expect( await screen.findByRole('heading', { name: 'Accès et habilitations' }), ).toBeInTheDocument() await waitFor(() => expect( screen.queryByRole('heading', { name: 'Fiches officielles' }), ).toBeNull(), ) expect(screen.getByRole('heading', { name: 'Espèces' })).toBeInTheDocument() expect(screen.queryByRole('alert')).toBeNull() }) it('an expired grant is no permission', () => { mount('/app/admin', [ { kind: 'sheet_editor', expires_at: '2020-01-01T00:00:00Z', revoked_at: null, }, ]) expect( screen.getByText(/^Vos habilitations : aucune · session/), ).toBeInTheDocument() }) }) /** Seven sheets named « Fiche n », modified on n Nov 2026 (Paris 11:00), unsorted. */ function sevenSheets() { return [3, 7, 1, 5, 2, 6, 4].map((n) => summary({ sheet_id: `00000000-0000-4000-8000-00000000000${n}`, slug: `fiche-${n}`, name: { fr: `Fiche ${n}`, en: `Sheet ${n}` }, last_modified_at: `2026-11-0${n}T10:00:00.000000+00:00`, }), ) } describe('Administration home card: latest modified sheets (board 29 B)', () => { const cardItems = async () => within(await screen.findByRole('list')).getAllByRole('listitem') const historicalAt = (day: string) => ({ ...historical(), last_modified_at: `2026-${day}T10:00:00.000000+00:00`, }) const COPY = { name: 'Créer une copie de travail' } it('seven sheets: five items, newest first, then « Voir les 7 fiches »', async () => { fake.rpcResults.list_official_sheets_admin = { data: sevenSheets() } mount('/app/admin', [grant('sheet_editor')]) const items = await cardItems() expect(items).toHaveLength(5) expect( items.map((li) => within(li).getAllByRole('link')[0].textContent), ).toEqual(['Fiche 7', 'Fiche 6', 'Fiche 5', 'Fiche 4', 'Fiche 3']) expect( screen.getByRole('heading', { name: 'Dernières modifications' }), ).toBeInTheDocument() expect( screen.getByRole('link', { name: 'Voir les 7 fiches' }), ).toHaveAttribute('href', '/app/admin/sheets') expect(screen.queryByText('Toutes les fiches officielles')).toBeNull() }) it('one sheet: the sub-heading, the item and « Toutes les fiches officielles »', async () => { fake.rpcResults.list_official_sheets_admin = { data: [summary()] } mount('/app/admin', [grant('sheet_editor')]) expect(await cardItems()).toHaveLength(1) expect( screen.getByRole('heading', { name: 'Dernières modifications' }), ).toBeInTheDocument() expect( screen.getByRole('link', { name: 'Toutes les fiches officielles' }), ).toHaveAttribute('href', '/app/admin/sheets') }) it('no sheet: the empty sentence, no sub-heading, the same link', async () => { fake.rpcResults.list_official_sheets_admin = { data: [] } mount('/app/admin', [grant('sheet_editor')]) expect(await screen.findByText(fr['admin.sheets.empty'])).toBeInTheDocument() expect( screen.queryByRole('heading', { name: 'Dernières modifications' }), ).toBeNull() expect(screen.queryByRole('list')).toBeNull() expect( screen.getByRole('link', { name: 'Toutes les fiches officielles' }), ).toBeInTheDocument() }) it('the historical sheet keeps its action inside the five, for an editor only', async () => { // Newest of all: inside the five. fake.rpcResults.list_official_sheets_admin = { data: [historicalAt('11-09'), ...sevenSheets()], } mount('/app/admin', [grant('sheet_editor')]) await cardItems() expect(screen.getByRole('button', COPY)).toBeInTheDocument() cleanup() // Inside the five, but the account is a reviewer. mount('/app/admin', [grant('sheet_reviewer')]) await cardItems() expect(screen.queryByRole('button', COPY)).toBeNull() cleanup() // Oldest of all: outside the five. fake.rpcResults.list_official_sheets_admin = { data: [historicalAt('10-01'), ...sevenSheets()], } mount('/app/admin', [grant('sheet_editor')]) await cardItems() expect(screen.queryByRole('link', { name: 'Cheval' })).toBeNull() expect(screen.queryByRole('button', COPY)).toBeNull() }) it('the detail line and the date are those of the list', async () => { mount('/app/admin', [grant('sheet_editor')]) const [item] = await cardItems() const detail = within(item).getByText(/^Cheval · /).textContent ?? '' const date = within(item).getByText(/^Modifiée le /).textContent ?? '' expect(date).toBe('Modifiée le 1 nov. 2026, 11:00') cleanup() mount('/app/admin/sheets', [grant('sheet_editor')]) const row = (await screen.findAllByRole('listitem'))[0] expect(within(row).getByText(detail)).toBeInTheDocument() expect(within(row).getByText(date)).toBeInTheDocument() }) it('a refused species read: the card still shows, the id in the detail line', async () => { fake.rpcResults.list_catalog_species = refusal('rights.capability') mount('/app/admin', [grant('sheet_editor')]) const [item] = await cardItems() expect(within(item).getByText(/^equine · /)).toBeInTheDocument() expect(screen.queryByRole('alert')).toBeNull() }) it('English texts', async () => { useLocaleStore.setState({ locale: 'en' }) fake.rpcResults.list_official_sheets_admin = { data: sevenSheets() } mount('/app/admin', [grant('sheet_editor')]) await cardItems() expect( screen.getByRole('heading', { name: 'Latest changes' }), ).toBeInTheDocument() expect( screen.getByRole('link', { name: 'See the 7 sheets' }), ).toBeInTheDocument() expect( screen.getByText('Modified on 7 Nov 2026, 11:00'), ).toBeInTheDocument() }) }) describe('Species (S1, matrix §5.4)', () => { const rows = () => within(screen.getByRole('list', { name: 'Espèces' })) it('editor: creates and edits inactive species, never activates or renames', async () => { mount('/app/admin/species', [grant('sheet_editor')]) await screen.findByRole('list', { name: 'Espèces' }) expect( screen.getByRole('button', { name: 'Nouvelle espèce' }), ).toBeInTheDocument() expect( rows().getByRole('button', { name: 'Modifier Chameau' }), ).toBeInTheDocument() expect( rows().queryByRole('button', { name: /Activer|Renommer|Modifier Cheval/, }), ).toBeNull() }) it('owner: activates inactive species and renames active ones, creates nothing', async () => { mount('/app/admin/species', [], ['owner']) await screen.findByRole('list', { name: 'Espèces' }) expect(screen.queryByRole('button', { name: 'Nouvelle espèce' })).toBeNull() expect( rows().getByRole('button', { name: 'Activer Chameau' }), ).toBeInTheDocument() expect( rows().getByRole('button', { name: 'Renommer Cheval' }), ).toBeInTheDocument() expect(rows().queryByRole('button', { name: /Modifier/ })).toBeNull() }) it('reviewer: reads the list, no action', async () => { mount('/app/admin/species', [grant('sheet_reviewer')]) await screen.findByRole('list', { name: 'Espèces' }) expect(screen.queryByRole('button')).toBeNull() expect(screen.getAllByText('Inactive')).toHaveLength(1) }) it('activation is confirmed, says the animal forms will show it, then calls activate_species', async () => { const user = userEvent.setup() fake.rpcResults.activate_species = { data: 'camelid' } mount('/app/admin/species', [], ['owner']) await screen.findByRole('list', { name: 'Espèces' }) await user.click(rows().getByRole('button', { name: 'Activer Chameau' })) const dialog = screen.getByRole('dialog', { name: 'Activer « Chameau » ?' }) expect(dialog).toHaveAccessibleDescription( fr['admin.species.activate.body'], ) expect(rpcArgs('activate_species')).toEqual([]) await user.click(within(dialog).getByRole('button', { name: 'Activer' })) await waitFor(() => expect(rpcArgs('activate_species')).toEqual([{ id: 'camelid' }]), ) expect(await screen.findByText('Espèce activée.')).toBeInTheDocument() }) it('creation checks the id, then shows the server refusal in words', async () => { const user = userEvent.setup() fake.rpcResults.create_species = { error: { code: 'P0001', message: 'species.exists' }, } mount('/app/admin/species', [grant('sheet_editor')]) await user.click( await screen.findByRole('button', { name: 'Nouvelle espèce' }), ) const dialog = within( screen.getByRole('dialog', { name: 'Nouvelle espèce' }), ) await user.type(dialog.getByLabelText('Identifiant'), 'other') await user.type(dialog.getByLabelText('Nom (français)'), 'Lama') await user.type(dialog.getByLabelText('Nom (anglais)'), 'Llama') await user.click(dialog.getByRole('button', { name: 'Enregistrer' })) expect(dialog.getByText(fr['admin.species.error.id'])).toBeInTheDocument() expect(rpcArgs('create_species')).toEqual([]) await user.clear(dialog.getByLabelText('Identifiant')) await user.type(dialog.getByLabelText('Identifiant'), 'llama') await user.click(dialog.getByRole('button', { name: 'Enregistrer' })) expect( await dialog.findByText(fr['admin.failure.species.exists']), ).toBeInTheDocument() expect(rpcArgs('create_species')).toEqual([ { id: 'llama', name_fr: 'Lama', name_en: 'Llama', sort_order: 100 }, ]) }) }) describe('Rights (A0, §5.2)', () => { const GRANTS = [ { id: 'g-1', user_id: 'user-2', display_name: 'Dr Marie Lefèvre', email: 'marie@example.test', kind: 'sheet_reviewer', reason: 'Relecture équine', verification_note: 'Diplôme vérifié', granted_by: 'user-1', granted_by_name: 'Alice Local', granted_at: '2026-11-01T10:00:00Z', expires_at: null, revoked_at: null, revoked_by: null, revocation_reason: null, state: 'active', effective: true, }, { id: 'g-2', user_id: 'user-3', display_name: 'Paul', email: 'paul@example.test', kind: 'catalog_reader', reason: 'Essai', verification_note: null, granted_by: 'user-1', granted_by_name: 'Alice Local', granted_at: '2026-10-01T10:00:00Z', expires_at: null, revoked_at: '2026-10-20T10:00:00Z', revoked_by: 'user-1', revocation_reason: 'Fin de l’essai', state: 'revoked', effective: false, }, ] const ACCOUNT = { user_id: 'user-4', display_name: 'Jean Martin', active: true, email_confirmed: true, verified_totp: false, platform_roles: [], } beforeEach(() => { fake.rpcResults.list_catalog_grants = { data: GRANTS } fake.rpcResults.lookup_catalog_account = { data: ACCOUNT } }) it('answers « Accès non autorisé » on the server refusal', async () => { fake.rpcResults.list_catalog_grants = refusal('rights.owner') mount('/app/admin/access', [grant('sheet_editor')]) expect( await screen.findByRole('heading', { name: 'Accès non autorisé' }), ).toBeInTheDocument() expect(screen.queryByLabelText('Adresse e-mail du compte')).toBeNull() }) it('lists grants with reason and note, filtered by state', async () => { const user = userEvent.setup() mount('/app/admin/access', [], ['owner']) const list = within( await screen.findByRole('list', { name: 'Droits attribués' }), ) expect(list.getByText('Relecture équine')).toBeInTheDocument() expect(list.getByText('Diplôme vérifié')).toBeInTheDocument() expect(list.getByText('Fin de l’essai')).toBeInTheDocument() await user.selectOptions(screen.getByLabelText('État'), 'revoked') expect(list.queryByText('Relecture équine')).toBeNull() expect(list.getByText('Paul (paul@example.test)')).toBeInTheDocument() expect(list.queryByRole('button', { name: 'Révoquer' })).toBeNull() }) it('grant form: a capability needs a note, an expiry in the future; then grant_catalog_right', async () => { const user = userEvent.setup() fake.rpcResults.grant_catalog_right = { data: 'g-9' } mount('/app/admin/access', [], ['owner']) await user.type( await screen.findByLabelText('Adresse e-mail du compte'), 'jean@example.test', ) await user.click(screen.getByRole('button', { name: 'Rechercher' })) expect(await screen.findByText('Jean Martin')).toBeInTheDocument() expect(screen.getByText('Aucun facteur vérifié')).toBeInTheDocument() expect(rpcArgs('lookup_catalog_account')).toEqual([ { email: 'jean@example.test' }, ]) await user.click(screen.getByRole('button', { name: 'Attribuer' })) expect(screen.getByText(fr['admin.access.error.kind'])).toBeInTheDocument() await user.click(screen.getByLabelText('Relecteur ou relectrice')) await user.type(screen.getByLabelText('Motif'), 'Relecture') await user.type(screen.getByLabelText(/Échéance/), '2020-01-01') await user.click(screen.getByRole('button', { name: 'Attribuer' })) expect(screen.getByText(fr['clients.error.required'])).toBeInTheDocument() expect( screen.getByText(fr['admin.access.error.expiry']), ).toBeInTheDocument() expect(rpcArgs('grant_catalog_right')).toEqual([]) await user.type( screen.getByLabelText('Note de vérification'), 'DMV vérifié', ) await user.clear(screen.getByLabelText(/Échéance/)) await user.click(screen.getByRole('button', { name: 'Attribuer' })) await waitFor(() => expect(rpcArgs('grant_catalog_right')).toEqual([ { user_id: 'user-4', kind: 'sheet_reviewer', reason: 'Relecture', verification_note: 'DMV vérifié', }, ]), ) expect(await screen.findByText('Droit attribué.')).toBeInTheDocument() }) it('explains an ineligible account', async () => { const user = userEvent.setup() fake.rpcResults.grant_catalog_right = { error: { code: 'P0001', message: 'grant.ineligible' }, } mount('/app/admin/access', [], ['owner']) await user.type( await screen.findByLabelText('Adresse e-mail du compte'), 'jean@example.test', ) await user.click(screen.getByRole('button', { name: 'Rechercher' })) await user.click(await screen.findByLabelText('Accès au catalogue')) await user.type(screen.getByLabelText('Motif'), 'Lecture') await user.click(screen.getByRole('button', { name: 'Attribuer' })) expect( await screen.findByText(fr['admin.access.ineligible_detail']), ).toBeInTheDocument() expect(rpcArgs('grant_catalog_right')[0]).toEqual({ user_id: 'user-4', kind: 'catalog_reader', reason: 'Lecture', }) }) it('an unknown address reads as such', async () => { const user = userEvent.setup() fake.rpcResults.lookup_catalog_account = refusal('not_found') mount('/app/admin/access', [], ['owner']) await user.type( await screen.findByLabelText('Adresse e-mail du compte'), 'nobody@example.test', ) await user.click(screen.getByRole('button', { name: 'Rechercher' })) expect( await screen.findByText('Aucun compte avec cette adresse.'), ).toBeInTheDocument() }) it('revocation asks a reason in a dialog, then calls revoke_catalog_right', async () => { const user = userEvent.setup() fake.rpcResults.revoke_catalog_right = { data: 'g-1' } mount('/app/admin/access', [], ['owner']) const list = within( await screen.findByRole('list', { name: 'Droits attribués' }), ) await user.click(list.getByRole('button', { name: 'Révoquer' })) const dialog = within( screen.getByRole('dialog', { name: 'Révoquer ce droit ?' }), ) await user.click(dialog.getByRole('button', { name: 'Révoquer' })) expect(dialog.getByText(fr['clients.error.required'])).toBeInTheDocument() expect(rpcArgs('revoke_catalog_right')).toEqual([]) await user.type( dialog.getByLabelText('Motif de la révocation'), 'Fin de mission', ) await user.click(dialog.getByRole('button', { name: 'Révoquer' })) await waitFor(() => expect(rpcArgs('revoke_catalog_right')).toEqual([ { grant_id: 'g-1', reason: 'Fin de mission' }, ]), ) expect(await screen.findByText('Droit révoqué.')).toBeInTheDocument() }) }) describe('Official sheets list (H1)', () => { it('filters over the loaded list', () => { const sheets = [summary(), historical()] as Parameters< typeof filterSheets >[0] expect(filterSheets(sheets, NO_FILTER)).toHaveLength(2) expect( filterSheets(sheets, { ...NO_FILTER, roundStatus: 'open' }).map( (s) => s.sheet_id, ), ).toEqual([SHEET]) expect( filterSheets(sheets, { ...NO_FILTER, versionStatus: 'published' }), ).toEqual([]) expect( filterSheets(sheets, { ...NO_FILTER, sheetStatus: 'active', species: 'equine', }), ).toHaveLength(2) }) it('shows every sheet with badges and details; the filters narrow it; « Nouvelle fiche » for editors only', async () => { const user = userEvent.setup() const view = mount('/app/admin/sheets', [grant('sheet_editor')]) const list = within( await screen.findByRole('list', { name: 'Liste des fiches officielles' }), ) expect(list.getAllByRole('link')).toHaveLength(2) expect( list.getByText( /Cheval · Active · aucune version publiée · brouillon version 1 · revue n° 1 : À relire/, ), ).toBeInTheDocument() expect( screen.getByRole('link', { name: 'Nouvelle fiche' }), ).toHaveAttribute('href', '/app/admin/sheets/new') await user.selectOptions( screen.getByLabelText('État de la dernière revue'), 'open', ) expect(list.getAllByRole('link')).toHaveLength(1) await user.selectOptions( screen.getByLabelText('Statut de version'), 'published', ) expect( screen.getByText('Aucune fiche ne correspond à ces filtres.'), ).toBeInTheDocument() view.unmount() mount('/app/admin/sheets', [grant('sheet_reviewer')]) await screen.findByRole('list', { name: 'Liste des fiches officielles' }) expect(screen.queryByRole('link', { name: 'Nouvelle fiche' })).toBeNull() }) // R3 (boards 28, 29 A): search, sort, count line and date over three sheets. const HORSE = 'Cheval, squelette et rachis' const DOG = 'Chien, squelette et rachis' const DONKEY = 'Âne, squelette et rachis' const threeSheets = () => [ summary({ last_modified_at: '2026-11-09T11:06:00.123456+00:00' }), summary({ sheet_id: '55555555-5555-4555-8555-555555555555', slug: 'chien-squelette', name: { fr: DOG, en: 'Dog, skeleton and spine' }, last_modified_at: '2026-11-08T16:41:00+00:00', }), summary({ sheet_id: '66666666-6666-4666-8666-666666666666', slug: 'ane-squelette', name: { fr: DONKEY, en: 'Donkey, skeleton and spine' }, last_modified_at: '2026-11-03T10:02:00+00:00', }), ] const ALL_NAMES = [HORSE, DOG, DONKEY] async function mountThree() { fake.rpcResults.list_official_sheets_admin = { data: threeSheets() } mount('/app/admin/sheets', [grant('sheet_editor')]) return within( await screen.findByRole('list', { name: 'Liste des fiches officielles' }), ) } const rowNames = (list: ReturnType) => list .getAllByRole('link') .map((row: HTMLElement) => ALL_NAMES.find((n) => row.textContent?.startsWith(n))) const searchField = () => screen.getByRole('searchbox', { name: 'Rechercher une fiche par son nom' }) it('orders by last modification, newest first, and dates each row', async () => { const list = await mountThree() expect(rowNames(list)).toEqual([HORSE, DOG, DONKEY]) const date = list.getByText('Modifiée le 9 nov. 2026, 12:06') expect(date.tagName).toBe('TIME') expect(date).toHaveAttribute('datetime', '2026-11-09T11:06:00.123Z') expect(screen.getByText('3 fiches')).toHaveAttribute('aria-live', 'polite') expect(screen.getByLabelText('Trier par')).toHaveValue('modified') }) it('narrows the list by name as the user types and counts « 1 fiche sur 3 »', async () => { const user = userEvent.setup() const list = await mountThree() expect(searchField()).toHaveAttribute('maxlength', '100') expect(searchField()).toHaveAttribute('autocomplete', 'off') await user.type(searchField(), 'chev') expect(rowNames(list)).toEqual([HORSE]) expect(screen.getByText('1 fiche sur 3')).toBeInTheDocument() }) it('clears the search by « × » or Escape and gives the focus back to the field', async () => { const user = userEvent.setup() await mountThree() expect( screen.queryByRole('button', { name: 'Effacer la recherche' }), ).toBeNull() await user.type(searchField(), 'chev') await user.click(screen.getByRole('button', { name: 'Effacer la recherche' })) expect(searchField()).toHaveValue('') expect(screen.getByText('3 fiches')).toBeInTheDocument() expect(searchField()).toHaveFocus() expect( screen.queryByRole('button', { name: 'Effacer la recherche' }), ).toBeNull() const reached: string[] = [] const listen = (event: KeyboardEvent) => reached.push(event.key) window.addEventListener('keydown', listen) try { await user.type(searchField(), 'chien') expect(screen.getByText('1 fiche sur 3')).toBeInTheDocument() reached.length = 0 await user.keyboard('{Escape}') expect(searchField()).toHaveValue('') expect(screen.getByText('3 fiches')).toBeInTheDocument() expect(searchField()).toHaveFocus() expect(reached).toEqual([]) await user.keyboard('{Escape}') expect(searchField()).toHaveValue('') expect(screen.getByText('3 fiches')).toBeInTheDocument() expect(reached).toEqual(['Escape']) } finally { window.removeEventListener('keydown', listen) } }) it('reorders the rows by name with « Nom »', async () => { const user = userEvent.setup() const list = await mountThree() await user.selectOptions(screen.getByLabelText('Trier par'), 'name') expect(rowNames(list)).toEqual([DONKEY, HORSE, DOG]) }) it('tells the three empty states apart; the search text is shown as typed', async () => { const user = userEvent.setup() fake.rpcResults.list_official_sheets_admin = { data: [] } const view = mount('/app/admin/sheets', [grant('sheet_editor')]) expect( await screen.findByText('Aucune fiche officielle pour le moment.'), ).toBeInTheDocument() expect(screen.queryByText(/^0 fiche/)).toBeNull() view.unmount() await mountThree() await user.type(searchField(), ' mulet ') expect(screen.getByText('0 fiche sur 3')).toBeInTheDocument() expect( screen.getByText('Aucune fiche ne contient « mulet » dans son nom.'), ).toBeInTheDocument() const clears = screen.getAllByRole('button', { name: 'Effacer la recherche', }) expect(clears).toHaveLength(2) await user.click(clears[1]) expect(searchField()).toHaveValue('') expect(searchField()).toHaveFocus() expect(screen.getByText('3 fiches')).toBeInTheDocument() await user.type(searchField(), '$&') expect( screen.getByText('Aucune fiche ne contient « $& » dans son nom.'), ).toBeInTheDocument() await user.selectOptions( screen.getByLabelText('Statut de version'), 'published', ) expect( screen.getByText('Aucune fiche ne correspond à ces filtres.'), ).toBeInTheDocument() expect(screen.queryByText(/Aucune fiche ne contient/)).toBeNull() }) it('reads in English: count, date and sort label', async () => { useLocaleStore.setState({ locale: 'en' }) const user = userEvent.setup() fake.rpcResults.list_official_sheets_admin = { data: threeSheets() } mount('/app/admin/sheets', [grant('sheet_editor')]) const list = within( await screen.findByRole('list', { name: 'Official sheet list' }), ) expect(list.getByText('Modified on 9 Nov 2026, 12:06')).toBeInTheDocument() expect(screen.getByLabelText('Sort by')).toBeInTheDocument() await user.type( screen.getByRole('searchbox', { name: 'Search a sheet by name' }), 'horse', ) expect(screen.getByText('1 sheet of 3')).toBeInTheDocument() }) it('announces an empty filtered result once: the count line, not a status', async () => { const user = userEvent.setup() await mountThree() await user.selectOptions( screen.getByLabelText('Statut de version'), 'published', ) const note = screen.getByText('Aucune fiche ne correspond à ces filtres.') expect(note.closest('[role="status"]')).toBeNull() expect(screen.getByText('0 fiche sur 3')).toHaveAttribute( 'aria-live', 'polite', ) }) describe('collapsible filters on a phone', () => { const toggle = (name: RegExp | string = /^Filtres/) => screen.getByRole('button', { name }) const panel = () => document.getElementById('admin-sheets-filters')! const reset = () => screen.queryByRole('button', { name: 'Réinitialiser les filtres' }) it('is closed by default: aria-expanded false, controls the panel, hidden on a phone only', async () => { await mountThree() expect(toggle()).toHaveTextContent('Filtres') expect(toggle()).toHaveAttribute('aria-expanded', 'false') expect(toggle()).toHaveAttribute('aria-controls', 'admin-sheets-filters') expect(toggle()).toHaveClass('sm:hidden') expect(panel()).toHaveAttribute('data-open', 'false') expect(panel().className).toContain('max-sm:invisible') expect(panel().className).toContain('motion-reduce:transition-none') expect(panel().className).not.toMatch(/(^|\s)invisible/) }) it('opens and closes on the button, with the four filters inside', async () => { const user = userEvent.setup() await mountThree() await user.click(toggle()) expect(toggle()).toHaveAttribute('aria-expanded', 'true') expect(panel()).toHaveAttribute('data-open', 'true') expect(panel().className).not.toContain('max-sm:invisible') for (const label of [ 'Espèce', 'État de la fiche', 'Statut de version', 'État de la dernière revue', ]) expect(within(panel()).getByLabelText(label)).toBeInTheDocument() await user.click(toggle()) expect(toggle()).toHaveAttribute('aria-expanded', 'false') expect(panel().className).toContain('max-sm:invisible') }) it('counts the active filters on the button; closing keeps them', async () => { const user = userEvent.setup() const list = await mountThree() await user.click(toggle()) await user.selectOptions(screen.getByLabelText('Espèce'), 'equine') await user.selectOptions( screen.getByLabelText('État de la fiche'), 'active', ) expect(toggle()).toHaveTextContent('Filtres (2)') await user.click(toggle(/^Filtres \(2\)/)) expect(toggle()).toHaveTextContent('Filtres (2)') await user.click(toggle()) expect(screen.getByLabelText('Espèce')).toHaveValue('equine') expect(screen.getByLabelText('État de la fiche')).toHaveValue('active') expect(list.getAllByRole('link').length).toBeGreaterThan(0) }) it('resets every filter, keeps the search, and hands the focus to the button', async () => { const user = userEvent.setup() await mountThree() expect(reset()).toBeNull() await user.click(toggle()) await user.type(searchField(), 'chev') await user.selectOptions( screen.getByLabelText('Statut de version'), 'published', ) expect(toggle()).toHaveTextContent('Filtres (1)') await user.click(reset()!) expect(screen.getByLabelText('Statut de version')).toHaveValue('') expect(toggle()).toHaveTextContent(/^Filtres$/) expect(searchField()).toHaveValue('chev') expect(reset()).toBeNull() expect(toggle()).toHaveFocus() }) it('reads in English', async () => { useLocaleStore.setState({ locale: 'en' }) const user = userEvent.setup() fake.rpcResults.list_official_sheets_admin = { data: threeSheets() } mount('/app/admin/sheets', [grant('sheet_editor')]) await screen.findByRole('list', { name: 'Official sheet list' }) await user.click(screen.getByRole('button', { name: 'Filters' })) await user.selectOptions(screen.getByLabelText('Version status'), 'draft') expect( screen.getByRole('button', { name: 'Filters (1)' }), ).toBeInTheDocument() expect( screen.getByRole('button', { name: 'Reset filters' }), ).toBeInTheDocument() }) }) }) describe('Sheet creation (A1)', () => { it.each([ ['a reviewer', [grant('sheet_reviewer')], []], ['a publisher', [grant('sheet_publisher')], []], ['an owner without the editor capability', [], ['owner']], ] as const)('offers no form to %s reaching the address', async (_, grants, roles) => { mount('/app/admin/sheets/new', [...grants], [...roles]) expect( await screen.findByRole('heading', { name: fr['access_denied.title'] }), ).toBeInTheDocument() expect(screen.queryByLabelText('Espèce')).toBeNull() expect(rpcArgs('create_official_sheet')).toEqual([]) }) describe.each([ ['a reviewer-only account', [grant('sheet_reviewer')], false], ['an editor account', [grant('sheet_editor')], true], ] as const)('permission states for %s', (_, grants, canCreate) => { const denied = () => screen.queryByRole('heading', { name: fr['access_denied.title'] }) const unavailable = () => screen.queryByRole('heading', { name: fr['permissions_unavailable.title'], }) it('ready: the form for the editor, « Accès non autorisé » otherwise', async () => { mount('/app/admin/sheets/new', [...grants]) if (canCreate) { expect(await screen.findByLabelText('Espèce')).toBeInTheDocument() expect(denied()).toBeNull() } else { expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument() expect(screen.queryByLabelText('Espèce')).toBeNull() } expect(unavailable()).toBeNull() }) it('failed: the unavailable state, no form, no refusal deduced', async () => { mount('/app/admin/sheets/new', [...grants], [], 'failed') expect(await screen.findByRole('heading', { name: fr['permissions_unavailable.title'] })).toBeInTheDocument() expect(screen.getByText(fr['permissions_unavailable.body'])).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Réessayer' })).toBeInTheDocument() expect(document.querySelector('input, select')).toBeNull() expect(denied()).toBeNull() }) it('loading: waits, decides nothing', async () => { mount('/app/admin/sheets/new', [...grants], [], 'loading') expect(await screen.findByRole('status')).toHaveTextContent(fr['shell.loading_session']) expect(denied()).toBeNull() expect(unavailable()).toBeNull() expect(document.querySelector('input, select')).toBeNull() }) it('Retry lands on what the new answer gives', async () => { const user = userEvent.setup() const reloadAccess = vi.fn(async () => useAuthStore.setState({ catalogGrants: [...grants], catalogGrantsStatus: 'ready' }), ) mount('/app/admin/sheets/new', [], [], 'failed') useAuthStore.setState({ reloadAccess }) await user.click(await screen.findByRole('button', { name: 'Réessayer' })) expect(reloadAccess).toHaveBeenCalledTimes(1) if (canCreate) expect(await screen.findByLabelText('Espèce')).toBeInTheDocument() else expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument() }) }) it('Retry also reads a failed species list again', async () => { const user = userEvent.setup() let calls = 0 fake.rpcResults.list_catalog_species = () => ++calls === 1 ? { error: new TypeError('fetch failed') } : { data: SPECIES } mount('/app/admin/sheets/new', [], [], 'failed') useAuthStore.setState({ reloadAccess: vi.fn(async () => useAuthStore.setState({ catalogGrants: [grant('sheet_editor')], catalogGrantsStatus: 'ready' }), ), }) await user.click(await screen.findByRole('button', { name: 'Réessayer' })) const species = await screen.findByLabelText('Espèce') await waitFor(() => expect(within(species).getAllByRole('option')).toHaveLength(3)) expect(calls).toBe(2) }) it('a server rights refusal wins over a failed grants read', async () => { fake.rpcResults.list_catalog_species = refusal('rights.capability') mount('/app/admin/sheets/new', [], [], 'failed') expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument() expect(screen.queryByRole('heading', { name: fr['permissions_unavailable.title'] })).toBeNull() }) it('proposes a slug from the French name', () => { expect(proposeSlug('Chien : squelette et rachis ')).toBe( 'chien-squelette-et-rachis', ) expect(proposeSlug('Équidé')).toBe('equide') }) it('builds the core empty document, calls create_official_sheet, opens the overview', async () => { const user = userEvent.setup() fake.rpcResults.create_official_sheet = { data: NEW_ID } fake.rpcResults.get_official_sheet_admin = { data: { ...summary({ sheet_id: NEW_ID }), working_copy_source: null, draft_last_save: null, versions: [], rounds: [], }, } mount('/app/admin/sheets/new', [grant('sheet_editor')]) const species = await screen.findByLabelText('Espèce') await waitFor(() => expect(within(species).getAllByRole('option')).toHaveLength(3), ) expect( within(species).getByRole('option', { name: 'Chameau (inactive)' }), ).toBeInTheDocument() expect(within(species).queryByRole('option', { name: 'Autre' })).toBeNull() await user.click(screen.getByRole('button', { name: 'Créer la fiche' })) expect( screen.getByText(fr['admin.sheet_form.error.species']), ).toBeInTheDocument() expect(rpcArgs('create_official_sheet')).toEqual([]) await user.selectOptions(species, 'camelid') await user.type( screen.getByLabelText('Nom (français)'), 'Chameau, squelette', ) await user.type(screen.getByLabelText('Nom (anglais)'), 'Camel, skeleton') expect(screen.getByLabelText('Identifiant (slug)')).toHaveValue( 'chameau-squelette', ) await user.click(screen.getByRole('button', { name: 'Créer la fiche' })) await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent( `/app/admin/sheets/${NEW_ID}/draft`, ), ) const [args] = rpcArgs('create_official_sheet') expect(args.slug).toBe('chameau-squelette') expect(args.document).toMatchObject({ species_id: 'camelid', name: { fr: 'Chameau, squelette', en: 'Camel, skeleton' }, }) }) it('shows a slug taken by another sheet in words', async () => { const user = userEvent.setup() fake.rpcResults.create_official_sheet = { error: { code: 'P0001', message: 'sheet.slug_taken' }, } mount('/app/admin/sheets/new', [grant('sheet_editor')]) const species = await screen.findByLabelText('Espèce') await waitFor(() => expect(within(species).getAllByRole('option')).toHaveLength(3), ) await user.selectOptions(species, 'equine') await user.type(screen.getByLabelText('Nom (français)'), 'Cheval bis') await user.type(screen.getByLabelText('Nom (anglais)'), 'Horse bis') await user.click(screen.getByRole('button', { name: 'Créer la fiche' })) expect( await screen.findByText(fr['admin.failure.sheet.slug_taken']), ).toBeInTheDocument() expect(screen.getByTestId('where')).toHaveTextContent( '/app/admin/sheets/new', ) }) }) describe('Sheet overview (H3)', () => { function overview(patch: Record = {}) { return { ...summary({ current_version: { version_id: 'v-0', version_number: 1, published_at: '2026-10-01T10:00:00Z', }, }), working_copy_source: { version_id: 'v-h', version_number: 1 }, draft_last_save: null, versions: [ { version_id: 'v-1', version_number: 2, status: 'draft', revision: 3, change_note: 'Rachis repris', created_at: '2026-11-01T10:00:00Z', published_at: null, deprecated_at: null, source_version_number: 1, authors: [{ user_id: 'user-1', display_name: 'Bastien Chanot' }], }, ], rounds: [ { review_id: 'r-2', version_id: 'v-1', version_number: 2, round: 2, revision: 3, status: 'verification_failed', submitted_by: { user_id: 'user-1', display_name: 'Bastien Chanot' }, submitted_at: '2026-11-01T11:00:00Z', verified_at: null, failure_outcome: 'unavailable', failure_code: null, decided_by: null, decided_at: null, withdrawn_at: null, }, { review_id: 'r-1', version_id: 'v-1', version_number: 2, round: 1, revision: 2, status: 'verification_failed', submitted_by: null, submitted_at: null, verified_at: null, failure_outcome: null, failure_code: null, decided_by: null, decided_at: null, withdrawn_at: null, }, ], ...patch, } } it('shows versions and rounds; a failure outcome only when the server recorded it', async () => { fake.rpcResults.get_official_sheet_admin = { data: overview() } mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_reviewer')]) expect( await screen.findByRole('heading', { level: 1, name: 'Cheval, squelette et rachis', }), ).toBeInTheDocument() expect(rpcArgs('get_official_sheet_admin')).toEqual([{ sheet_id: SHEET }]) const versions = within(screen.getByRole('region', { name: 'Versions' })) expect(versions.getByText('Rachis repris')).toBeInTheDocument() expect( versions.getByText(/issue de la version 1 · auteurs : Bastien Chanot/), ).toBeInTheDocument() const rounds = within(screen.getByRole('region', { name: 'Revues' })) const [second, first] = rounds.getAllByRole('listitem') expect( within(second).getByText('Vérification indisponible'), ).toBeInTheDocument() expect( within(second).getByText("La vérification n'a pas pu aboutir."), ).toBeInTheDocument() expect( within(second).getByText(/soumise le .* par Bastien Chanot/), ).toBeInTheDocument() expect(within(first).getByText('Vérification échouée')).toBeInTheDocument() expect(within(first).queryByText(/ne passe pas|pas pu aboutir/)).toBeNull() expect( screen.getByRole('link', { name: 'Voir dans le catalogue' }), ).toHaveAttribute('href', `/app/anatomy/${SHEET}`) expect( screen.queryByRole('button', { name: 'Créer une copie de travail' }), ).toBeNull() }) it('links to the draft: « Ouvrir » for an editor with the admin role, « Consulter » otherwise', async () => { fake.rpcResults.get_official_sheet_admin = { data: overview() } mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_editor')], ['admin']) const open = await screen.findByRole('link', { name: 'Ouvrir le brouillon' }) expect(open).toHaveAttribute('href', `/app/admin/sheets/${SHEET}/draft`) cleanup() mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_reviewer')]) const view = await screen.findByRole('link', { name: 'Consulter le brouillon' }) expect(view).toHaveAttribute('href', `/app/admin/sheets/${SHEET}/draft`) }) it('links nothing without a draft', async () => { fake.rpcResults.get_official_sheet_admin = { data: overview({ draft_version: null }), } mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_editor')], ['admin']) await screen.findByRole('heading', { level: 1 }) expect(screen.queryByRole('link', { name: /brouillon/ })).toBeNull() }) it('historical sheet: the working copy action disabled while a copy is active', async () => { fake.rpcResults.get_official_sheet_admin = { data: { ...historical(), working_copy_source: null, draft_last_save: null, versions: [], rounds: [], }, } mount(`/app/admin/sheets/${HISTORICAL}`, [grant('sheet_editor')]) const action = await screen.findByRole('button', { name: 'Créer une copie de travail', }) expect(action).toBeDisabled() expect( screen.getByText(fr['admin.working_copy.active']), ).toBeInTheDocument() expect( screen.queryByRole('link', { name: 'Voir dans le catalogue' }), ).toBeNull() }) it('historical sheet: creates the copy from the latest version and opens its overview', async () => { const user = userEvent.setup() fake.rpcResults.get_official_sheet_admin = () => ({ data: { ...historical(), working_copy_active: false, working_copy_source: null, draft_last_save: null, versions: [], rounds: [], }, }) fake.rpcResults.create_sheet_working_copy = { data: NEW_ID } mount(`/app/admin/sheets/${HISTORICAL}`, [grant('sheet_editor')]) await user.click( await screen.findByRole('button', { name: 'Créer une copie de travail' }), ) const dialog = within( screen.getByRole('dialog', { name: 'Créer une copie de travail' }), ) expect(dialog.getByLabelText('Identifiant (slug)')).toHaveValue( 'equine-copie-de-travail', ) await user.click(dialog.getByRole('button', { name: 'Créer la copie' })) await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent( `/app/admin/sheets/${NEW_ID}/draft`, ), ) expect(rpcArgs('create_sheet_working_copy')).toEqual([ { source_version_id: 'v-h', slug: 'equine-copie-de-travail' }, ]) }) it('names missing drawings when the copy cannot be made', async () => { const user = userEvent.setup() fake.rpcResults.get_official_sheet_admin = { data: { ...historical(), working_copy_active: false, working_copy_source: null, draft_last_save: null, versions: [], rounds: [], }, } fake.rpcResults.create_sheet_working_copy = { error: { code: 'P0001', message: 'working_copy.assets_missing' }, } mount(`/app/admin/sheets/${HISTORICAL}`, [grant('sheet_editor')]) await user.click( await screen.findByRole('button', { name: 'Créer une copie de travail' }), ) await user.click(screen.getByRole('button', { name: 'Créer la copie' })) expect( await screen.findByText(fr['admin.failure.working_copy.assets_missing']), ).toBeInTheDocument() }) it('one answer for an unknown or hidden id', async () => { fake.rpcResults.get_official_sheet_admin = refusal('not_found') mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_editor')]) expect( await screen.findByRole('heading', { name: 'Fiche introuvable' }), ).toBeInTheDocument() cleanup() mount('/app/admin/sheets/not-a-uuid', [grant('sheet_editor')]) expect( await screen.findByRole('heading', { name: 'Fiche introuvable' }), ).toBeInTheDocument() }) })