feat(app): administration screens and anatomical catalogue (V1-2.5 G, H, I)

Administration page (board 10), species, rights, official sheets list with filters, creation from the core's empty document, overview with the working-copy action; catalogue list (search by sheet name), sheet and version pages through PreviewSheet with zoom and pan. App 650, typecheck, lint, build green.
This commit is contained in:
bchanot committed 2026-11-02 17:18:27 +01:00
1 parent 9f7824dc08
commit 0176b3184d
42 files changed
+6438 -39

No files matched your search

+916
View File
@@ -0,0 +1,916 @@
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 { parseGrant, 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<string, unknown> = {}) {
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',
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<string, unknown>)
function Where() {
return <span data-testid="where">{useLocation().pathname}</span>
}
function mount(
path: string,
grants: OwnCatalogGrant[],
roles: PlatformRole[] = [],
) {
useAuthStore.setState({ catalogGrants: grants, roles })
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/app/admin">
<Route index element={<AdminHomeRoute />} />
<Route path="sheets" element={<AdminSheetsRoute />} />
<Route path="sheets/new" element={<AdminSheetCreateRoute />} />
<Route path="sheets/:sheetId" element={<AdminSheetRoute />} />
<Route path="species" element={<AdminSpeciesRoute />} />
<Route path="access" element={<AdminAccessRoute />} />
</Route>
<Route path="/app/anatomy/:sheetId" element={<p>catalogue page</p>} />
</Routes>
<Where />
</MemoryRouter>,
)
}
beforeAll(async () => {
setCoreRuntime(await testCoreRuntime())
})
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())
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()
})
})
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, 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()
})
it('parseGrant: the reader needs no note; the expiry is the end of the chosen day', () => {
const parsed = parseGrant(
{
kind: 'catalog_reader',
reason: ' Lecture ',
verification_note: '',
expires_on: '2026-12-31',
},
'2026-11-02',
)
expect(parsed).toEqual({
ok: true,
value: {
kind: 'catalog_reader',
reason: 'Lecture',
expires_at: new Date('2026-12-31T23:59:59').toISOString(),
},
})
const today = parseGrant(
{
kind: 'catalog_reader',
reason: 'x',
verification_note: '',
expires_on: '2026-11-02',
},
'2026-11-02',
)
expect(today).toMatchObject({
ok: false,
errors: { expires_on: 'admin.access.error.expiry' },
})
})
})
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()
})
})
describe('Sheet creation (A1)', () => {
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,
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}`,
),
)
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<string, unknown> = {}) {
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 },
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('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,
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,
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}`,
),
)
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,
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()
})
})
@@ -0,0 +1,335 @@
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { 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 type { PreviewState } from '@faunosteo/core-wasm/types'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
import { bundledSheet } from '../helpers/sheet'
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 CatalogRoute from '@/app/routes/app/anatomy/CatalogRoute'
import SheetRoute from '@/app/routes/app/anatomy/SheetRoute'
import { coreRuntime } from '@/core/runtime'
import { CataloguePreview } from '@/catalogue/preview'
import { coreFailure, serverFailure } from '@/catalogue/failure'
import { SheetFailure } from '@faunosteo/supabase'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
/**
* The catalogue screens (V1-2.5 slice I, boards 01 to 03) on a fake client and
* the real core: the equine draft stands for a published version, its
* drawing served as Storage would, so the core checks the hash, the
* fingerprint and the caps exactly as in the browser.
*/
const SHEET = '503dc301-0000-4000-8000-000000000001'
const OTHER = '503dc301-0000-4000-8000-000000000002'
const V1 = 'aaaaaaaa-0000-4000-8000-000000000001'
const V2 = 'aaaaaaaa-0000-4000-8000-000000000002'
const V3 = 'aaaaaaaa-0000-4000-8000-000000000003'
const DOG = 'bbbbbbbb-0000-4000-8000-000000000001'
let fake: FakeSupabase
let document: unknown
let assetId: string
let sha256: string
let bytes: Uint8Array<ArrayBuffer>
let fingerprint: string
beforeAll(async () => {
const bundle = await bundledSheet()
document = bundle.document
;[assetId] = Object.keys(bundle.assets)
sha256 = bundle.assetHashes[assetId]
bytes = new TextEncoder().encode(bundle.assets[assetId])
// The fingerprint a publication stores: the core's, read from a draft preview.
const draft = new CataloguePreview(
coreRuntime(),
{ status: 'draft', document: JSON.stringify(document) },
[{ assetId, sha256, bytes }],
)
const state = draft.state()
if (!state.ok || !state.value.fingerprint) throw new Error('draft preview refused')
fingerprint = state.value.fingerprint
draft.free()
})
function versionAnswer(id: string, status: 'published' | 'deprecated', patch: Record<string, unknown> = {}) {
return {
sheet_id: SHEET,
version_id: id,
version_number: Number(id.slice(-1)),
status,
species_id: 'equine',
document,
revision: 1,
// PreviewSheet requires the stored fingerprint for deprecated versions too, while
// `get_sheet_version` returns it for published ones only (gap reported at V1-2.5).
fingerprint,
drawings: [{ asset_id: assetId, sha256, byte_size: bytes.length }],
...patch,
}
}
/** `get_sheet_version` answers per id, as the server would; unknown ids are `not_found`. */
function serveVersions(answers: Record<string, unknown>) {
fake.rpcResults.get_sheet_version = () => {
const [, args] = fake.rpcCalls.filter(([n]) => n === 'get_sheet_version').at(-1)!
const answer = answers[(args as { version_id: string }).version_id]
return answer ? { data: answer } : { error: { message: 'not_found', code: '42501' } }
}
}
function mount(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/app/anatomy" element={<CatalogRoute />} />
<Route path="/app/anatomy/:sheetId" element={<SheetRoute />} />
<Route path="/app/anatomy/:sheetId/versions/:number" element={<SheetRoute />} />
</Routes>
</MemoryRouter>,
)
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useAuthStore.setState({ status: 'signed_in', user: fakeUser(), profile: fakeProfile(), catalogGrants: [] })
fake = createFakeSupabase()
fake.tables.species = [
{ id: 'equine', name_fr: 'Cheval', name_en: 'Horse', sort_order: 1 },
{ id: 'canine', name_fr: 'Chien', name_en: 'Dog', sort_order: 2 },
]
fake.tables.anatomical_sheet_versions = [
{ sheet_id: SHEET, id: V3, version_number: 3, status: 'published', published_at: '2026-10-28T10:00:00Z', deprecated_at: null },
{ sheet_id: SHEET, id: V2, version_number: 2, status: 'deprecated', published_at: '2026-10-20T10:00:00Z', deprecated_at: '2026-10-28T10:00:00Z' },
{ sheet_id: SHEET, id: V1, version_number: 1, status: 'published', published_at: '2026-10-10T10:00:00Z', deprecated_at: null },
]
fake.rpcResults.list_official_catalog = {
data: [
{ sheet_id: SHEET, species_id: 'equine', slug: 'cheval', name: { fr: 'Cheval', en: 'Horse' }, description: {}, version_number: 3, version_id: V3 },
{ sheet_id: OTHER, species_id: 'canine', slug: 'chien', name: { fr: 'Chien, rachis', en: 'Dog spine' }, description: {}, version_number: 1, version_id: DOG },
],
}
serveVersions({ [V3]: versionAnswer(V3, 'published'), [V2]: versionAnswer(V2, 'deprecated'), [V1]: versionAnswer(V1, 'published') })
fake.storage.download.mockImplementation(async () => ({ data: new Blob([bytes]), error: null }))
mocks.fake = fake
})
afterEach(() => cleanup())
describe('/app/anatomy', () => {
it('shows each published sheet with its species, status, version line and link', async () => {
mount('/app/anatomy')
expect(await screen.findByRole('heading', { level: 1, name: fr['shell.nav.anatomy'] })).toBeInTheDocument()
const card = (await screen.findByRole('heading', { level: 2, name: 'Cheval' })).closest('article')!
expect(within(card).getByText(fr['catalogue.status.published'])).toBeInTheDocument()
expect(within(card).getByText('Cheval', { selector: 'span' })).toBeInTheDocument()
expect(
await within(card).findByText('Version 3 · publiée le 28/10/2026 · 2 vues, 27 zones de constats'),
).toBeInTheDocument()
// The thumbnail is the core's composed main view, as an image (never inserted as markup).
expect(card.querySelector('img')?.getAttribute('src')).toMatch(/^blob:/)
expect(within(card).getByRole('link', { name: 'Consulter Cheval' })).toHaveAttribute('href', `/app/anatomy/${SHEET}`)
// The card whose version cannot be read keeps its name, version and link.
const dog = screen.getByRole('heading', { level: 2, name: 'Chien, rachis' }).closest('article')!
expect(within(dog).getByText('Version 1')).toBeInTheDocument()
})
it('searches by sheet name in either language and filters by species', async () => {
mount('/app/anatomy')
await screen.findByRole('heading', { level: 2, name: 'Cheval' })
const search = screen.getByRole('searchbox', { name: fr['catalogue.search'] })
await userEvent.type(search, 'dog')
expect(screen.queryByRole('heading', { level: 2, name: 'Cheval' })).toBeNull()
expect(screen.getByRole('heading', { level: 2, name: 'Chien, rachis' })).toBeInTheDocument()
await userEvent.clear(search)
await userEvent.type(search, 'thoracique')
expect(screen.getByText(fr['catalogue.no_results'])).toBeInTheDocument()
await userEvent.clear(search)
const chips = screen.getByRole('group', { name: fr['catalogue.species_filter'] })
expect(within(chips).getAllByRole('button').map((b) => b.textContent)).toEqual([
fr['catalogue.all_species'],
'Cheval',
'Chien',
])
await userEvent.click(within(chips).getByRole('button', { name: 'Cheval' }))
expect(screen.getByRole('heading', { level: 2, name: 'Cheval' })).toBeInTheDocument()
expect(screen.queryByRole('heading', { level: 2, name: 'Chien, rachis' })).toBeNull()
})
it('says when no sheet is published', async () => {
fake.rpcResults.list_official_catalog = { data: [] }
mount('/app/anatomy')
expect(await screen.findByText(fr['catalogue.empty'])).toBeInTheDocument()
})
it('shows « Accès non autorisé » on the server refusal', async () => {
fake.rpcResults.list_official_catalog = { error: { message: 'rights.catalog', code: '42501' } }
mount('/app/anatomy')
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
it('names an unavailable server and reads again on retry', async () => {
fake.rpcResults.list_official_catalog = { error: { message: 'boom' } }
mount('/app/anatomy')
expect(await screen.findByText(fr['catalogue.failure.unavailable'])).toBeInTheDocument()
fake.rpcResults.list_official_catalog = { data: [] }
await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] }))
expect(await screen.findByText(fr['catalogue.empty'])).toBeInTheDocument()
})
})
describe('/app/anatomy/:sheetId', () => {
it('shows the current version: views, zone panel, references and disclaimer', async () => {
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByRole('heading', { level: 1, name: 'Cheval' })).toBeInTheDocument()
expect(screen.getByText('Version 3 · publiée le 28/10/2026')).toBeInTheDocument()
const tabs = screen.getAllByRole('tab')
expect(tabs.map((tab) => tab.textContent)).toEqual(['Vue latérale gauche', 'Tête (vue latérale gauche)'])
expect(tabs[0]).toHaveAttribute('aria-selected', 'true')
const canvas = screen.getByTestId('catalogue-canvas-drawing')
await waitFor(() => expect(canvas.querySelector('svg')).not.toBeNull())
fireEvent.click(canvas.querySelector('[data-anno-id="thoracic"]')!)
expect(screen.getByRole('heading', { name: 'Zone : Vertèbres thoraciques' })).toBeInTheDocument()
expect(screen.getByText('Catégorie : Segments vertébraux · vertèbres T1 à T18')).toBeInTheDocument()
expect(screen.getByRole('heading', { level: 3, name: 'Dysfonctions ostéopathiques' })).toBeInTheDocument()
expect(canvas.querySelector('[data-anno-id="thoracic"]')).toHaveAttribute('data-state', 'current')
expect(screen.getByRole('heading', { name: fr['catalogue.references.title'] })).toBeInTheDocument()
expect(screen.getByText(/Code rural et de la pêche maritime, art\. L\. 243-3/)).toBeInTheDocument()
expect(screen.getByText(/Aucun diagnostic médical n'est posé/)).toBeInTheDocument()
// No capability: no link to the administration.
expect(screen.queryByRole('link', { name: fr['catalogue.open_admin'] })).toBeNull()
})
it('opens the detail view from its link on the drawing', async () => {
mount(`/app/anatomy/${SHEET}`)
const canvas = await screen.findByTestId('catalogue-canvas-drawing')
await waitFor(() => expect(canvas.querySelector('[data-anno-id="head-trigger"]')).not.toBeNull())
fireEvent.click(canvas.querySelector('[data-anno-id="head-trigger"]')!)
expect(screen.getByRole('tab', { name: 'Tête (vue latérale gauche)' })).toHaveAttribute('aria-selected', 'true')
})
it('lists the versions with the « Retirée » mark, each linking to its page', async () => {
mount(`/app/anatomy/${SHEET}`)
await userEvent.click(await screen.findByRole('button', { name: '2 versions antérieures' }))
const list = screen.getByRole('list', { name: fr['catalogue.versions.title'] })
const links = within(list).getAllByRole('link')
expect(links.map((l) => l.getAttribute('href'))).toEqual([3, 2, 1].map((n) => `/app/anatomy/${SHEET}/versions/${n}`))
expect(links[0]).toHaveAttribute('aria-current', 'page')
expect(within(links[1]).getByText(fr['catalogue.status.deprecated'])).toBeInTheDocument()
})
it('opens a retired version by number with its mark', async () => {
mount(`/app/anatomy/${SHEET}/versions/2`)
expect(await screen.findByText('Version 2 · publiée le 20/10/2026')).toBeInTheDocument()
expect(screen.getByText(fr['catalogue.status.deprecated'])).toBeInTheDocument()
expect(fake.rpcCalls.filter(([n]) => n === 'get_sheet_version').map(([, a]) => a)).toEqual([{ version_id: V2 }])
})
it('links an editor to the administration', async () => {
useAuthStore.setState({ catalogGrants: [{ kind: 'sheet_editor', expires_at: null, revoked_at: null }] })
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByRole('link', { name: fr['catalogue.open_admin'] })).toHaveAttribute(
'href',
`/app/admin/sheets/${SHEET}`,
)
})
it.each([
['an unknown sheet', `/app/anatomy/${OTHER}`],
['a malformed id', '/app/anatomy/not-a-uuid'],
['an unknown number', `/app/anatomy/${SHEET}/versions/9`],
['a malformed number', `/app/anatomy/${SHEET}/versions/0`],
])('shows « Accès non autorisé » for %s', async (_case, path) => {
mount(path)
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
it('shows « Accès non autorisé » when the version read is refused', async () => {
serveVersions({})
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
it('zooms with the buttons and « Ajuster » brings the whole drawing back', async () => {
mount(`/app/anatomy/${SHEET}`)
const drawing = await screen.findByTestId('catalogue-canvas-drawing')
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.in'] }))
expect(drawing.style.transform).toContain('scale(1.5)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.in'] }))
expect(drawing.style.transform).toContain('scale(2.25)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.out'] }))
expect(drawing.style.transform).toContain('scale(1.5)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.fit'] }))
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
// The keyboard on the focused box: + zooms, 0 fits.
fireEvent.keyDown(screen.getByTestId('catalogue-canvas'), { key: '+' })
expect(drawing.style.transform).toContain('scale(1.5)')
fireEvent.keyDown(screen.getByTestId('catalogue-canvas'), { key: '0' })
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
})
})
describe('failures', () => {
it.each([
[
'a drawing whose bytes do not hash to its row',
() => {
const altered = bytes.slice()
altered[200] ^= 1
fake.storage.download.mockImplementation(async () => ({ data: new Blob([altered]), error: null }))
},
'catalogue.failure.drawing_hash_mismatch',
],
[
'a stored fingerprint the core does not recompute',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) }),
'catalogue.failure.fingerprint_mismatch',
],
[
'a drawing Storage does not give',
() =>
fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 400, name: 'StorageApiError' } })),
'catalogue.failure.drawing_missing',
],
[
'an unreadable document',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { document: { schema_version: 2 } }) }),
'catalogue.failure.invalid_document',
],
])('names %s', async (_case, arrange, key) => {
arrange()
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByText(fr[key])).toBeInTheDocument()
expect(screen.getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument()
})
it('folds server and core kinds into the closed page kinds', () => {
expect(serverFailure(new SheetFailure('rights.catalog'))).toBe('denied')
expect(serverFailure(new SheetFailure('not_found'))).toBe('denied')
expect(serverFailure(new SheetFailure('network'))).toBe('network')
expect(serverFailure(new SheetFailure('draft_conflict'))).toBe('unavailable')
expect(coreFailure('caps')).toBe('caps')
expect(coreFailure('internal')).toBe('core_unavailable')
expect(coreFailure('invalid_json')).toBe('invalid_document')
})
it('a freed preview never rebuilds its handle', () => {
const preview = new CataloguePreview(
coreRuntime(),
{ status: 'published', document: JSON.stringify(document), fingerprint },
[{ assetId, sha256, bytes }],
)
const state = preview.state()
expect(state.ok && (state.value as PreviewState).status).toBe('published')
preview.free()
expect(preview.canvas('main')).toEqual({ ok: false, kind: 'core_unavailable' })
})
})