import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor, within, } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { MemoryRouter, Route, Routes, useLocation, type InitialEntry, } from 'react-router-dom' import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase, } from '../helpers/fakeSupabase' 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 AppLayout from '@/components/shell/AppLayout' import RequireWorkspace from '@/app/guards/RequireWorkspace' import ClientDetailRoute from '@/app/routes/app/clients/ClientDetailRoute' import AnimalsListRoute from '@/app/routes/app/animals/AnimalsListRoute' import AnimalCreateRoute from '@/app/routes/app/animals/AnimalCreateRoute' import AnimalDetailRoute from '@/app/routes/app/animals/AnimalDetailRoute' import AnimalEditRoute from '@/app/routes/app/animals/AnimalEditRoute' import { SEARCH_DELAY_MS } from '@/clients/useClientList' import { useAuthStore } from '@/state/authStore' import { useLocaleStore } from '@/state/localeStore' import { fr } from '@/i18n/fr' /** * The animal screens and the client page's animals on a fake client: states, * the calls they make and what they keep. The RPC shapes are proven in * packages/supabase (unit and real PostgREST); the journeys run in Chromium. */ const WS = '11111111-1111-4111-8111-111111111111' const AID = '22222222-2222-4222-8222-222222222222' const CID = '33333333-3333-4333-8333-333333333333' const R1 = '44444444-4444-4444-8444-444444444441' const R2 = '44444444-4444-4444-8444-444444444442' const R3 = '44444444-4444-4444-8444-444444444443' const R4 = '44444444-4444-4444-8444-444444444444' let fake: FakeSupabase const SPECIES = [ { id: 'equine', name_fr: 'Cheval', name_en: 'Horse', sort_order: 10, active: true, }, { id: 'canine', name_fr: 'Chien', name_en: 'Dog', sort_order: 30, active: true, }, { id: 'other', name_fr: 'Autre', name_en: 'Other', sort_order: 1000, active: true, }, ] function listRow(i: number, patch: Record = {}) { return { id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`, name: `Animal ${String(i).padStart(2, '0')}`, species_id: 'equine', species_detail: null, sex: 'female', breed: null, birth_year: null, archived_at: null, name_key: `animal ${String(i).padStart(2, '0')}`, current_owners: [], current_owner_count: 0, ...patch, } } function animalRow(patch: Record = {}) { return { id: AID, name: 'Tornado', species_id: 'equine', species_detail: null, sex: 'female', breed: 'Pur-sang', birth_year: 2015, birth_date: '2015-04-12', revision: 1, archived_at: null, created_at: '2026-10-26T10:00:00Z', updated_at: '2026-10-26T10:00:00Z', ...patch, } } function clientRow(patch: Record = {}) { return { id: CID, kind: 'person', display_name: 'Marie Dupont', email: null, phone: null, address_line1: null, address_line2: null, postal_code: null, city: 'Lyon', country: null, revision: 1, archived_at: null, created_at: '2026-10-26T10:00:00Z', updated_at: '2026-10-26T10:00:00Z', ...patch, } } function relationRow( id: string, name: string, patch: Record = {}, ) { return { id, animal_id: AID, relation_role: 'owner', started_on: null, ended_on: null, ended_at: null, voided_at: null, revision: 1, created_at: '2026-10-26T10:00:00Z', client: { id: `55555555-5555-4555-8555-55555555555${id.slice(-1)}`, kind: 'person', display_name: name, phone: null, email: null, archived_at: null, }, ...patch, } } const page = () => within(screen.getByRole('main')) const rpcArgs = (name: string) => fake.rpcCalls .filter(([n]) => n === name) .map(([, a]) => a as Record) function Where() { return {useLocation().pathname} } function mount(entry: InitialEntry) { useAuthStore.setState({ status: 'signed_in', user: fakeUser(), profile: fakeProfile(), workspace: { status: 'ready', id: WS }, }) return render( }> dashboard

} /> }> clients

} /> } /> } /> } /> } /> } />
, ) } /** Holds the next call of `name` until released (the fake answers `result`). */ function holdRpc(name: string, result: { data?: unknown; error?: unknown }) { let release: () => void = () => undefined const pending = new Promise((resolve) => (release = resolve)) const client = fake.client as unknown as { rpc: (n: string, a: unknown) => Promise } const rpc = client.rpc.bind(client) client.rpc = async (n, args) => { if (n !== name) return rpc(n, args) fake.rpcCalls.push([n, args]) await pending return { data: result.data ?? null, error: result.error ?? null } } return () => act(async () => release()) } const label = (key: string) => new RegExp(fr[key].replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) async function fillIdentity(name = 'Tornado') { await userEvent.type(screen.getByLabelText(label('animals.form.name')), name) await userEvent.selectOptions( screen.getByRole('combobox', { name: label('animals.form.species') }), 'equine', ) await userEvent.click( screen.getByRole('radio', { name: fr['animals.sex.female'] }), ) } beforeEach(() => { useLocaleStore.setState({ locale: 'fr' }) fake = createFakeSupabase() fake.tables.species = SPECIES.map((s) => ({ ...s })) fake.tables.animals = [] fake.tables.clients = [] fake.tables.animal_client_relations = [] fake.rpcResults.search_animals = { data: [] } fake.rpcResults.search_clients = { data: [] } fake.rpcResults.list_client_animals = { data: [] } mocks.fake = fake }) afterEach(() => { cleanup() vi.useRealTimers() }) describe('animal list', () => { it('lists the first page with owners or « Propriétaire non renseigné », then « Afficher plus »', async () => { fake.rpcResults.search_animals = { data: [ listRow(1, { current_owners: [ { client_id: CID, display_name: 'Marie Dupont', archived: false }, ], current_owner_count: 1, }), ...Array.from({ length: 25 }, (_, i) => listRow(i + 2)), ], } mount('/app/animals') expect(page().getByRole('status')).toHaveTextContent( fr['animals.list.loading'], ) expect(await screen.findByText('Animal 01')).toBeInTheDocument() expect( page().getByRole('heading', { level: 1, name: fr['animals.list.title'] }), ).toHaveFocus() expect(screen.getByText('Propriétaire : Marie Dupont')).toBeInTheDocument() expect(screen.getAllByText(fr['animals.no_owner']).length).toBeGreaterThan( 0, ) const results = screen.getByRole('list', { name: fr['animals.list.results_label'], }) expect(within(results).getAllByRole('listitem')).toHaveLength(25) expect(rpcArgs('search_animals')[0]).toMatchObject({ workspace_id: WS, query: '', archived: false, page_size: 26, species_filter: undefined, }) fake.rpcResults.search_animals = { data: [listRow(26), listRow(27)] } await userEvent.click( screen.getByRole('button', { name: fr['animals.list.more'] }), ) expect(await screen.findByText('Animal 27')).toBeInTheDocument() expect(rpcArgs('search_animals').at(-1)).toMatchObject({ after_name_key: 'animal 25', after_id: listRow(25).id, }) expect( screen.queryByRole('button', { name: fr['animals.list.more'] }), ).toBeNull() }) it('says it is empty', async () => { mount('/app/animals') expect( await screen.findByText(fr['animals.list.empty']), ).toBeInTheDocument() expect(screen.getByText(fr['animals.list.empty_hint'])).toBeInTheDocument() }) it('filters by species and by archive, in the RPC body', async () => { mount('/app/animals') await screen.findByText(fr['animals.list.empty']) const filter = screen.getByRole('combobox', { name: fr['animals.list.species_filter'], }) await waitFor(() => expect( within(filter).getByRole('option', { name: 'Chien' }), ).toBeInTheDocument(), ) await userEvent.selectOptions(filter, 'canine') await waitFor(() => expect(rpcArgs('search_animals').at(-1)?.species_filter).toBe('canine'), ) expect( await screen.findByText(fr['animals.list.no_results']), ).toBeInTheDocument() fake.rpcResults.search_animals = { data: [listRow(1, { archived_at: '2026-10-26T10:00:00Z' })], } await userEvent.click( screen.getByRole('switch', { name: fr['animals.list.archived_toggle'] }), ) expect( await screen.findByText(fr['animals.archived_badge']), ).toBeInTheDocument() expect(rpcArgs('search_animals').at(-1)).toMatchObject({ archived: true, species_filter: 'canine', }) }) it('waits for a pause in typing, then sends the term in the body once', async () => { vi.useFakeTimers({ shouldAdvanceTime: true }) mount('/app/animals') await screen.findByText(fr['animals.list.empty']) const before = rpcArgs('search_animals').length const box = screen.getByRole('searchbox', { name: label('animals.list.search_label'), }) for (const value of ['t', 'to', 'tor']) fireEvent.change(box, { target: { value } }) await act(() => vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS + 10)) await waitFor(() => expect(rpcArgs('search_animals').length).toBe(before + 1), ) expect(rpcArgs('search_animals').at(-1)?.query).toBe('tor') }) it('names a failure and retries', async () => { fake.rpcResults.search_animals = { error: { code: 'P0001', message: 'rate_limited' }, } mount('/app/animals') expect( await screen.findByText(fr['animals.failure.rate_limited']), ).toBeInTheDocument() fake.rpcResults.search_animals = { data: [listRow(1)] } await userEvent.click( screen.getByRole('button', { name: fr['common.retry'] }), ) expect(await screen.findByText('Animal 01')).toBeInTheDocument() }) }) describe('animal creation', () => { it('refuses an empty form, focuses the name; no sex is preselected', async () => { mount('/app/animals/new') for (const sex of ['male', 'female', 'unknown']) expect( screen.getByRole('radio', { name: fr[`animals.sex.${sex}`] }), ).not.toBeChecked() await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_create'] }), ) expect(screen.getByLabelText(label('animals.form.name'))).toHaveFocus() expect(screen.getByText(fr['animals.error.required'])).toBeInTheDocument() expect(screen.getByText(fr['animals.error.species'])).toBeInTheDocument() expect(screen.getByText(fr['animals.error.sex'])).toBeInTheDocument() expect(rpcArgs('create_animal')).toEqual([]) }) it('« Autre » asks for its detail', async () => { mount('/app/animals/new') expect( screen.queryByLabelText(label('animals.form.species_detail')), ).toBeNull() const species = screen.getByRole('combobox', { name: label('animals.form.species'), }) await waitFor(() => expect( within(species).getByRole('option', { name: 'Autre' }), ).toBeInTheDocument(), ) await userEvent.selectOptions(species, 'other') expect( screen.getByLabelText(label('animals.form.species_detail')), ).toBeInTheDocument() }) it('a full birth date fills and locks the year; clearing it unlocks', async () => { mount('/app/animals/new') const year = screen.getByLabelText(label('animals.form.birth_year')) const date = screen.getByLabelText(label('animals.form.birth_date')) fireEvent.change(date, { target: { value: '2015-04-12' } }) expect(year).toHaveValue('2015') expect(year).toHaveAttribute('readonly') fireEvent.change(date, { target: { value: '' } }) expect(year).toHaveValue('2015') expect(year).not.toHaveAttribute('readonly') }) it('sends the same request id after a lost answer, then opens the animal', async () => { fake.rpcResults.create_animal = { error: { code: '', message: 'TypeError: fetch failed' }, } mount('/app/animals/new') await screen.findByRole('option', { name: 'Cheval' }) await fillIdentity() await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_create'] }), ) expect( await screen.findByText(fr['animals.failure.unavailable']), ).toBeInTheDocument() fake.rpcResults.create_animal = { data: { id: AID, revision: 1, relation_id: null }, } fake.tables.animals = [animalRow()] await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_create'] }), ) await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent( `/app/animals/${AID}`, ), ) const [first, second] = rpcArgs('create_animal') expect(first.create_request_id).toBe(second.create_request_id) expect(first).toMatchObject({ workspace_id: WS, name: 'Tornado', species_id: 'equine', sex: 'female', }) expect(first.client_id).toBeUndefined() expect( await screen.findByText(fr['animals.detail.created']), ).toBeInTheDocument() }) it('a new form is a new intent: another request id', async () => { fake.rpcResults.create_animal = { error: { code: 'P0001', message: 'rate_limited' }, } const first = mount('/app/animals/new') await screen.findByRole('option', { name: 'Cheval' }) await fillIdentity() await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_create'] }), ) await screen.findByText(fr['animals.failure.rate_limited']) first.unmount() mount('/app/animals/new') await screen.findByRole('option', { name: 'Cheval' }) await fillIdentity() await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_create'] }), ) await screen.findByText(fr['animals.failure.rate_limited']) const ids = rpcArgs('create_animal').map((a) => a.create_request_id) expect(ids[0]).not.toBe(ids[1]) }) }) describe('animal creation from a client page', () => { const fromClient = (clientId: unknown = CID) => ({ pathname: '/app/animals/new', state: { clientId }, }) it('pre-associates the client with no role; refuses a save without a role; one create_animal with the relation', async () => { fake.tables.clients = [clientRow()] mount(fromClient()) expect(await screen.findByText('Marie Dupont')).toBeInTheDocument() expect( screen.getByText(fr['relations.panel.client_chosen'], { exact: false }), ).toBeInTheDocument() for (const role of ['owner', 'keeper', 'contact']) expect( screen.getByRole('radio', { name: fr[`clients.role.${role}`] }), ).not.toBeChecked() await screen.findByRole('option', { name: 'Cheval' }) await fillIdentity() await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_create'] }), ) expect(screen.getByText(fr['animals.error.role'])).toBeInTheDocument() expect(rpcArgs('create_animal')).toEqual([]) await userEvent.click( screen.getByRole('radio', { name: fr['clients.role.owner'] }), ) fake.rpcResults.create_animal = { data: { id: AID, revision: 1, relation_id: R1 }, } await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_create'] }), ) await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent( `/app/clients/${CID}`, ), ) expect(rpcArgs('create_animal')).toHaveLength(1) expect(rpcArgs('create_animal')[0]).toMatchObject({ client_id: CID, relation_role: 'owner', }) expect(rpcArgs('create_animal')[0].started_on).toBeUndefined() expect(rpcArgs('create_animal_client_relation')).toEqual([]) expect( await screen.findByText(fr['clients.detail.animal_added']), ).toBeInTheDocument() }) it('removing the client sends none and opens the animal', async () => { fake.tables.clients = [clientRow()] mount(fromClient()) await userEvent.click( await screen.findByRole('button', { name: fr['animals.form.client_remove'], }), ) expect( screen.getByRole('searchbox', { name: label('relations.picker.client_label'), }), ).toHaveFocus() await screen.findByRole('option', { name: 'Cheval' }) await fillIdentity() fake.rpcResults.create_animal = { data: { id: AID, revision: 1, relation_id: null }, } fake.tables.animals = [animalRow()] await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_create'] }), ) await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent( `/app/animals/${AID}`, ), ) expect(rpcArgs('create_animal')[0].client_id).toBeUndefined() expect(rpcArgs('create_animal')[0].relation_role).toBeUndefined() }) it.each([ ['archived', [clientRow({ archived_at: '2026-10-26T11:00:00Z' })]], ['unknown', []], ])( 'an %s origin client is not pre-associated, and the page says so', async (_, rows) => { fake.tables.clients = rows mount(fromClient()) expect( await screen.findByText(fr['animals.form.origin_unavailable']), ).toBeInTheDocument() expect( screen.queryByText(fr['relations.panel.client_chosen'], { exact: false, }), ).toBeNull() }, ) it('a malformed state value reads nothing', async () => { const from = vi.spyOn( fake.client as unknown as { from: (t: string) => unknown }, 'from', ) mount(fromClient('not-an-id')) await screen.findByRole('option', { name: 'Cheval' }) expect(from.mock.calls.map(([t]) => t)).not.toContain('clients') expect(screen.queryByText(fr['animals.form.origin_unavailable'])).toBeNull() }) }) describe('animal edit', () => { it('on conflict shows the stored value beside the typed one and keeps it', async () => { fake.tables.animals = [animalRow()] mount(`/app/animals/${AID}/edit`) const name = await screen.findByLabelText(label('animals.form.name')) expect(name).toHaveValue('Tornado') await userEvent.clear(name) await userEvent.type(name, 'Typhon') fake.tables.animals = [animalRow({ name: 'Ouragan', revision: 2 })] fake.rpcResults.update_animal = { error: { code: 'P0001', message: 'conflict' }, } await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_update'] }), ) expect( await screen.findByText(fr['animals.form.conflict_title']), ).toBeInTheDocument() expect(name).toHaveValue('Typhon') expect( screen.getByText( fr['animals.form.stored_value'].replace('{value}', 'Ouragan'), ), ).toBeInTheDocument() fake.rpcResults.update_animal = { data: { revision: 3 } } await userEvent.click( screen.getByRole('button', { name: fr['animals.form.submit_update'] }), ) await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent( `/app/animals/${AID}`, ), ) expect(rpcArgs('update_animal').map((a) => a.expected_revision)).toEqual([ 1, 2, ]) expect(rpcArgs('update_animal')[1]).toMatchObject({ name: 'Typhon', birth_year: '2015', birth_date: '2015-04-12', species_detail: null, }) }) it('an archived animal has no form', async () => { fake.tables.animals = [animalRow({ archived_at: '2026-10-26T11:00:00Z' })] mount(`/app/animals/${AID}/edit`) expect( await screen.findByText(fr['animals.detail.archived_notice']), ).toBeInTheDocument() expect( screen.queryByRole('button', { name: fr['animals.form.submit_update'] }), ).toBeNull() }) }) describe('animal page', () => { it('shows the identity with the birth precision', async () => { fake.tables.animals = [animalRow()] mount(`/app/animals/${AID}`) expect( await page().findByRole('heading', { level: 1, name: 'Tornado' }), ).toHaveFocus() expect(await screen.findByText('Cheval')).toBeInTheDocument() expect(screen.getByText('Femelle')).toBeInTheDocument() expect(screen.getByText('Pur-sang')).toBeInTheDocument() expect( screen.getByText(/^Le 12 avril 2015 \(\d+ ans\)$/), ).toBeInTheDocument() expect( screen.getByText(fr['animals.detail.status_active']), ).toBeInTheDocument() }) it.each([ [{ birth_date: null, birth_year: 2015 }, /^En 2015 \(environ \d+ ans\)$/], [ { birth_date: null, birth_year: null }, new RegExp(`^${fr['animals.detail.birth_unknown']}$`), ], ])('birth %o', async (patch, text) => { fake.tables.animals = [animalRow(patch)] mount(`/app/animals/${AID}`) expect(await screen.findByText(text)).toBeInTheDocument() }) it('shows the same « introuvable » for an unknown id and a malformed one', async () => { mount(`/app/animals/${AID}`) expect( await screen.findByRole('heading', { name: fr['animals.not_found.title'], }), ).toHaveFocus() cleanup() mount('/app/animals/not-an-id') expect( await screen.findByRole('heading', { name: fr['animals.not_found.title'], }), ).toHaveFocus() }) it('archives after a confirmation that refuses to close while the request runs', async () => { fake.tables.animals = [animalRow()] const release = holdRpc('set_animal_archived', { data: { revision: 2 } }) mount(`/app/animals/${AID}`) await userEvent.click( await screen.findByRole('button', { name: fr['animals.detail.archive'] }), ) const dialog = await screen.findByRole('dialog', { name: fr['animals.archive.title'], }) await userEvent.click( within(dialog).getByRole('button', { name: fr['animals.archive.confirm'], }), ) await userEvent.click( within(dialog).getByRole('button', { name: fr['common.cancel'] }), ) expect(dialog).toBeInTheDocument() fake.tables.animals = [ animalRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 }), ] await release() expect( await screen.findByText(fr['animals.detail.archived']), ).toBeInTheDocument() await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) expect(rpcArgs('set_animal_archived')).toEqual([ { animal_id: AID, archived: true }, ]) }) it('an archived animal is read-only, relations included, and can be restored', async () => { fake.tables.animals = [ animalRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 }), ] fake.tables.animal_client_relations = [relationRow(R1, 'Marie Dupont')] mount(`/app/animals/${AID}`) expect( await screen.findByText(fr['animals.detail.archived_notice']), ).toBeInTheDocument() expect( await screen.findByRole('link', { name: 'Marie Dupont' }), ).toBeInTheDocument() expect(screen.queryByRole('button', { name: /Terminer/ })).toBeNull() expect( screen.queryByRole('button', { name: fr['relations.add_client'] }), ).toBeNull() expect( screen.queryByRole('link', { name: fr['animals.detail.edit'] }), ).toBeNull() fake.rpcResults.set_animal_archived = { data: { revision: 3 } } fake.tables.animals = [animalRow({ revision: 3 })] await userEvent.click( screen.getByRole('button', { name: fr['animals.detail.restore'] }), ) expect( await screen.findByText(fr['animals.detail.restored']), ).toBeInTheDocument() expect(rpcArgs('set_animal_archived')).toEqual([ { animal_id: AID, archived: false }, ]) expect( await screen.findByRole('button', { name: fr['relations.add_client'] }), ).toBeInTheDocument() }) }) describe('animal relations', () => { function seed() { fake.tables.animals = [animalRow()] fake.tables.animal_client_relations = [ relationRow(R1, 'Marie Dupont', { started_on: '2020-03-01' }), relationRow(R2, 'Écurie du Lac', { relation_role: 'keeper' }), relationRow(R3, 'Jean Martin', { ended_at: '2024-01-01T00:00:00Z', ended_on: '2023-12-31', }), relationRow(R4, 'Fantôme Erroné', { voided_at: '2026-01-01T00:00:00Z' }), ] } it('groups current and former relations; a voided one is never shown', async () => { seed() mount(`/app/animals/${AID}`) expect( await screen.findByRole('link', { name: 'Marie Dupont' }), ).toHaveAttribute( 'href', `/app/clients/55555555-5555-4555-8555-555555555551`, ) expect( screen.getByRole('heading', { name: fr['relations.current'] }), ).toBeInTheDocument() expect( screen.getByRole('heading', { name: fr['relations.former'] }), ).toBeInTheDocument() expect( screen.getByText(/Ancien propriétaire · jusqu'au 31 décembre 2023/), ).toBeInTheDocument() expect(screen.queryByText('Fantôme Erroné')).toBeNull() expect(screen.queryByText(fr['animals.no_owner'])).toBeNull() }) it('says « Propriétaire non renseigné » without a current owner', async () => { fake.tables.animals = [animalRow()] fake.tables.animal_client_relations = [ relationRow(R2, 'Écurie du Lac', { relation_role: 'keeper' }), ] mount(`/app/animals/${AID}`) expect(await screen.findByText(fr['animals.no_owner'])).toBeInTheDocument() }) it('ends a relation without a date, then with one', async () => { seed() fake.rpcResults.end_animal_client_relation = { data: { revision: 2 } } mount(`/app/animals/${AID}`) await userEvent.click( await screen.findByRole('button', { name: 'Terminer : Marie Dupont, propriétaire', }), ) let dialog = await screen.findByRole('dialog', { name: fr['relations.end.title'], }) await userEvent.click( within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }), ) expect( await screen.findByText(fr['relations.end.done']), ).toBeInTheDocument() await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) expect(rpcArgs('end_animal_client_relation')[0]).toEqual({ relation_id: R1, expected_revision: 1, }) await userEvent.click( screen.getByRole('button', { name: 'Terminer : Écurie du Lac, détenteur', }), ) dialog = await screen.findByRole('dialog', { name: fr['relations.end.title'], }) fireEvent.change( within(dialog).getByLabelText(label('relations.end.ended_on')), { target: { value: '2026-01-15' }, }, ) await userEvent.click( within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }), ) await waitFor(() => expect(rpcArgs('end_animal_client_relation')).toHaveLength(2), ) expect(rpcArgs('end_animal_client_relation')[1]).toMatchObject({ relation_id: R2, ended_on: '2026-01-15', }) }) it('refuses an end before the start, in the dialog', async () => { seed() mount(`/app/animals/${AID}`) await userEvent.click( await screen.findByRole('button', { name: 'Terminer : Marie Dupont, propriétaire', }), ) const dialog = await screen.findByRole('dialog', { name: fr['relations.end.title'], }) const field = within(dialog).getByLabelText(label('relations.end.ended_on')) fireEvent.change(field, { target: { value: '2019-01-01' } }) await userEvent.click( within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }), ) expect( within(dialog).getByText(fr['relations.error.end_before_start']), ).toBeInTheDocument() expect(field).toHaveFocus() expect(rpcArgs('end_animal_client_relation')).toEqual([]) }) it('a conflict reloads and says the relation changed; a network failure stays in the dialog', async () => { seed() fake.rpcResults.end_animal_client_relation = { error: { code: '', message: 'TypeError: fetch failed' }, } mount(`/app/animals/${AID}`) await userEvent.click( await screen.findByRole('button', { name: 'Terminer : Marie Dupont, propriétaire', }), ) const dialog = await screen.findByRole('dialog', { name: fr['relations.end.title'], }) await userEvent.click( within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }), ) expect( await within(dialog).findByText(fr['relations.failure.unavailable']), ).toBeInTheDocument() expect(dialog).toBeInTheDocument() fake.rpcResults.end_animal_client_relation = { error: { code: 'P0001', message: 'conflict' }, } fake.tables.animal_client_relations = [ relationRow(R1, 'Marie Dupont', { revision: 2, ended_at: '2026-10-26T12:00:00Z', }), ] await userEvent.click( within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }), ) expect( await screen.findByText(fr['relations.failure.conflict']), ).toBeInTheDocument() await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) expect(screen.queryByRole('link', { name: 'Écurie du Lac' })).toBeNull() }) it('corrects the dates of a former relation', async () => { seed() fake.rpcResults.update_animal_client_relation = { data: { revision: 2 } } mount(`/app/animals/${AID}`) await userEvent.click( await screen.findByRole('button', { name: 'Corriger les dates : Jean Martin, ancien propriétaire', }), ) const dialog = await screen.findByRole('dialog', { name: fr['relations.dates.title'], }) fireEvent.change( within(dialog).getByLabelText(label('relations.dates.started_on')), { target: { value: '2018-05-01' }, }, ) await userEvent.click( within(dialog).getByRole('button', { name: fr['relations.dates.confirm'], }), ) expect( await screen.findByText(fr['relations.dates.done']), ).toBeInTheDocument() expect(rpcArgs('update_animal_client_relation')).toEqual([ { relation_id: R3, expected_revision: 1, started_on: '2018-05-01', ended_on: '2023-12-31', }, ]) }) it('voids a relation entered by mistake after a danger confirmation', async () => { seed() fake.rpcResults.void_animal_client_relation = { data: { revision: 2 } } mount(`/app/animals/${AID}`) await userEvent.click( await screen.findByRole('button', { name: 'Erreur de saisie : Écurie du Lac, détenteur', }), ) const dialog = await screen.findByRole('dialog', { name: fr['relations.void.title'], }) expect(dialog).toHaveAccessibleDescription( expect.stringContaining(fr['relations.void.body']), ) fake.tables.animal_client_relations = fake.tables.animal_client_relations.filter((r) => r.id !== R2) await userEvent.click( within(dialog).getByRole('button', { name: fr['relations.void.confirm'], }), ) expect( await screen.findByText(fr['relations.void.done']), ).toBeInTheDocument() expect(rpcArgs('void_animal_client_relation')).toEqual([ { relation_id: R2, expected_revision: 1 }, ]) await waitFor(() => expect(screen.queryByRole('link', { name: 'Écurie du Lac' })).toBeNull(), ) }) it('the add-client panel needs a choice and a role, phrases a duplicate, reuses its request id', async () => { fake.tables.animals = [animalRow()] fake.rpcResults.search_clients = { data: [ { id: CID, kind: 'person', display_name: 'Marie Dupont', city: 'Lyon', phone: null, email: null, archived_at: null, name_key: 'marie dupont', current_animal_count: 0, }, ], } mount(`/app/animals/${AID}`) await userEvent.click( await screen.findByRole('button', { name: fr['relations.add_client'] }), ) expect( screen.getByRole('heading', { name: fr['relations.panel.title_client'] }), ).toHaveFocus() await userEvent.click( screen.getByRole('button', { name: fr['relations.panel.save_client'] }), ) expect(screen.getByText(fr['animals.error.client'])).toBeInTheDocument() await userEvent.click( await screen.findByRole('button', { name: /Marie Dupont/ }), ) await userEvent.click( screen.getByRole('button', { name: fr['relations.panel.save_client'] }), ) expect(screen.getByText(fr['animals.error.role'])).toBeInTheDocument() expect(rpcArgs('create_animal_client_relation')).toEqual([]) await userEvent.click( screen.getByRole('radio', { name: fr['clients.role.keeper'] }), ) fake.rpcResults.create_animal_client_relation = { error: { code: 'P0001', message: 'duplicate_relation' }, } await userEvent.click( screen.getByRole('button', { name: fr['relations.panel.save_client'] }), ) expect( await screen.findByText(fr['relations.failure.duplicate_relation']), ).toBeInTheDocument() fake.rpcResults.create_animal_client_relation = { data: { id: R1, revision: 1 }, } fake.tables.animal_client_relations = [ relationRow(R1, 'Marie Dupont', { relation_role: 'keeper' }), ] await userEvent.click( screen.getByRole('button', { name: fr['relations.panel.save_client'] }), ) expect( await screen.findByText(fr['relations.added_client']), ).toBeInTheDocument() const calls = rpcArgs('create_animal_client_relation') expect(calls[0]).toMatchObject({ animal_id: AID, client_id: CID, relation_role: 'keeper', }) expect(calls[0].create_request_id).toBe(calls[1].create_request_id) await waitFor(() => expect( screen.getByRole('button', { name: fr['relations.add_client'] }), ).toHaveFocus(), ) }) }) describe('client page animals', () => { const ANIMAL2 = '66666666-6666-4666-8666-666666666666' function item(relationId: string, patch: Record = {}) { return { relation_id: relationId, relation_role: 'owner', started_on: null, ended_on: null, is_current: true, relation_revision: 1, animal_id: AID, animal_name: 'Tornado', species_id: 'equine', species_detail: null, sex: 'female', breed: null, birth_year: null, animal_archived_at: null, sort_key: '0tornado', ...patch, } } it('shows each animal once with all its roles, linked to its page', async () => { fake.tables.clients = [clientRow()] fake.rpcResults.list_client_animals = { data: [ item(R1), item(R2, { relation_role: 'keeper' }), item(R3, { animal_id: ANIMAL2, animal_name: 'Éclair', is_current: false, sort_key: '1eclair', }), ], } mount(`/app/clients/${CID}`) const links = await screen.findAllByRole('link', { name: 'Tornado' }) expect(links).toHaveLength(1) expect(links[0]).toHaveAttribute('href', `/app/animals/${AID}`) expect(screen.getByText(fr['clients.role.owner'])).toBeInTheDocument() expect(screen.getByText(fr['clients.role.keeper'])).toBeInTheDocument() expect( screen.getByText(fr['clients.role.former_owner']), ).toBeInTheDocument() expect( screen.getByRole('link', { name: fr['clients.animals.add'] }), ).toBeInTheDocument() }) it('offers « Ajouter un premier animal » when there is none, with the client in the navigation state', async () => { fake.tables.clients = [clientRow()] mount(`/app/clients/${CID}`) await userEvent.click( await screen.findByRole('link', { name: fr['clients.animals.add_first'], }), ) await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/app/animals/new'), ) expect( await screen.findByText(fr['relations.panel.client_chosen'], { exact: false, }), ).toBeInTheDocument() expect(screen.getByText('Marie Dupont')).toBeInTheDocument() }) it('links an existing animal with the client id', async () => { fake.tables.clients = [clientRow()] fake.rpcResults.search_animals = { data: [listRow(1, { id: AID, name: 'Tornado' })], } mount(`/app/clients/${CID}`) await userEvent.click( await screen.findByRole('button', { name: fr['clients.animals.link_existing'], }), ) await userEvent.click( await screen.findByRole('button', { name: /Tornado/ }), ) await userEvent.click( screen.getByRole('radio', { name: fr['clients.role.contact'] }), ) fake.rpcResults.create_animal_client_relation = { data: { id: R1, revision: 1 }, } fake.rpcResults.list_client_animals = { data: [item(R1, { relation_role: 'contact' })], } await userEvent.click( screen.getByRole('button', { name: fr['relations.panel.save_animal'] }), ) expect( await screen.findByText(fr['relations.added_animal']), ).toBeInTheDocument() expect(rpcArgs('create_animal_client_relation')[0]).toMatchObject({ animal_id: AID, client_id: CID, relation_role: 'contact', }) expect(rpcArgs('search_animals')[0]).toMatchObject({ archived: false, workspace_id: WS, }) }) it('an archived client offers no add and no link', async () => { fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z' })] fake.rpcResults.list_client_animals = { data: [item(R1)] } mount(`/app/clients/${CID}`) expect( await screen.findByRole('link', { name: 'Tornado' }), ).toBeInTheDocument() expect( screen.queryByRole('link', { name: fr['clients.animals.add'] }), ).toBeNull() expect( screen.queryByRole('button', { name: fr['clients.animals.link_existing'], }), ).toBeNull() }) })