diff --git a/apps/app/e2e/shell/animals.spec.ts b/apps/app/e2e/shell/animals.spec.ts new file mode 100644 index 00000000..89a9c3fa --- /dev/null +++ b/apps/app/e2e/shell/animals.spec.ts @@ -0,0 +1,1028 @@ +import { randomUUID } from 'node:crypto' +import { en } from '@/i18n/en' +import { fr } from '@/i18n/fr' +import type { Dict } from '@/i18n/types' +import { formatDate } from '@/lib/dates' +import type { Locator, Page, TestInfo } from '@playwright/test' +import { sql } from '../../../../packages/supabase/tests/sandbox/stack' +import { + expect, + expectAccessible, + expectNoHorizontalOverflow, + test, +} from '../support/browser' +import { createAccount, routeToSandbox, sandboxUrl } from '../support/sandbox' +import { + literal, + seedAnimal, + seedClient, + seedRelation, +} from '../support/records' +import { signIn } from '../support/shell' + +// V1-1.6 animals and relations on the isolated stack: contract §11.2 journeys +// 1 to 7 and the owner brief's list (empty list, creation with and without a +// client, search, species filter, edit, concurrent edit, archive and restore, +// first animal from a client page, linking an existing animal, co-owners, the +// end and the voiding of a relation, a refused duplicate, two accounts, a +// change of session, keyboard only, a retry after a lost answer, network +// failures, a change of language), in FR and EN, desktop and 375 px, axe on +// every state. Every fixture is fictitious and made per test. + +const LANGUAGES = [ + ['fr', fr], + ['en', en], +] as const + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' +const tagOf = () => randomUUID().slice(0, 8) + +/** Follows an entry of the shell's navigation: the sidebar, or the drawer on a phone. */ +async function navigate(page: Page, dict: Dict, info: TestInfo, key: string) { + if (isPhone(info)) { + await page.getByRole('button', { name: dict['shell.open_menu'] }).click() + await page + .getByRole('dialog', { name: dict['shell.nav_label'] }) + .getByRole('navigation') + .getByRole('link', { name: dict[key] }) + .click() + } else { + await page + .getByRole('navigation', { name: dict['shell.nav_label'] }) + .getByRole('link', { name: dict[key] }) + .click() + } +} + +async function openAnimals(page: Page, dict: Dict, info: TestInfo) { + await navigate(page, dict, info, 'shell.nav.animals') + await expect(page).toHaveURL(/\/app\/animals$/) + await expect(heading(page, dict['animals.list.title'])).toBeFocused() +} + +async function signOut(page: Page, dict: Dict, info: TestInfo) { + if (isPhone(info)) { + await page.getByRole('button', { name: dict['shell.open_menu'] }).click() + await page + .getByRole('dialog', { name: dict['shell.nav_label'] }) + .getByRole('button', { name: dict['shell.sign_out'] }) + .click() + } else { + await page.getByRole('button', { name: dict['shell.sign_out'] }).click() + } + await expect(page).toHaveURL(/\/$/) +} + +const heading = (page: Page, name: string) => + page.getByRole('main').getByRole('heading', { level: 1, name }) + +const listRows = (page: Page, dict: Dict) => + page + .getByRole('list', { name: dict['animals.list.results_label'] }) + .getByRole('listitem') + +const relationsCard = (page: Page) => + page.locator('section[aria-labelledby="animal-relations-title"]') + +/** The accessible name of a relation action: « Terminer : Marie Dupont, propriétaire ». */ +const actionName = ( + dict: Dict, + action: string, + client: string, + roleKey: string, +) => + dict['relations.action_named'] + .replace('{action}', dict[action]) + .replace('{name}', client) + .replace('{role}', dict[roleKey].toLowerCase()) + +/** Picks a record in the in-page search of a relation panel or of the form. */ +async function pick(scope: Page | Locator, label: string, term: string) { + await scope.getByRole('searchbox', { name: label }).fill(term) + await scope.getByRole('button', { name: new RegExp(`^${term}`) }).click() +} + +const count = (query: string) => sql(`select count(*) from ${query}`) + +/** + * axe from the top of the page: a state reached at the bottom of a phone page + * leaves the first controls under the sticky top bar, which axe's target-size + * rule measures as cut; at rest on the page nothing sits under the bar. + */ +async function expectAccessibleFromTop(page: Page, state: string) { + await page.evaluate(() => window.scrollTo(0, 0)) + await expectAccessible(page, state) +} + +for (const [locale, dict] of LANGUAGES) { + test.describe(`animals (${locale})`, () => { + test.use({ locale: locale === 'fr' ? 'fr-FR' : 'en-GB' }) + test.beforeEach(async ({ context }) => { + await routeToSandbox(context) + }) + // A page may still be reading (a list, the relations) when its last check + // passed: the replay of that answer is dropped with the context, not failed. + test.afterEach(async ({ context }) => { + await context.unrouteAll({ behavior: 'ignoreErrors' }) + }) + + test('empty list, an « Autre » with no owner, search, species filter, edit, archive, archived filter, restore', async ({ + page, + requests, + }, info) => { + const tag = tagOf() + const name = `Furet Fictif ${tag}` + const horse = `Cheval Témoin ${tag}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + name, + horse, + tag, + 'Furet', + 'Albinos', + ) + await signIn(page, account, dict) + await openAnimals(page, dict, info) + await expect(page.getByText(dict['animals.list.empty'])).toBeVisible() + await expectAccessible(page, 'the empty animal list') + await expectNoHorizontalOverflow(page, 'the empty animal list') + + await page.getByRole('link', { name: dict['animals.list.new'] }).click() + await expect(page).toHaveURL(/\/app\/animals\/new$/) + await expect( + heading(page, dict['animals.form.create_title']), + ).toBeFocused() + for (const sex of ['male', 'female', 'unknown']) + await expect( + page.getByRole('radio', { + name: dict[`animals.sex.${sex}`], + exact: true, + }), + ).not.toBeChecked() + const species = page.getByRole('combobox', { + name: dict['animals.form.species'], + }) + await expect(species).toHaveValue('') + await expectAccessible(page, 'the new animal form') + await expectNoHorizontalOverflow(page, 'the new animal form') + + await page.getByLabel(dict['animals.form.name']).fill(name) + await species.selectOption('other') + await page.getByLabel(dict['animals.form.species_detail']).fill('Furet') + await page + .getByRole('radio', { name: dict['animals.sex.unknown'], exact: true }) + .check() + const year = page.getByLabel(dict['animals.form.birth_year']) + const date = page.getByLabel(dict['animals.form.birth_date']) + await year.fill('2020') + await date.fill('2021-06-15') + await expect(year).toHaveValue('2021') + await expect(year).toHaveAttribute('readonly', '') + await date.fill('') + await expect(year).toHaveValue('2021') + await expect(year).not.toHaveAttribute('readonly', '') + await date.fill('2021-06-15') + await expectAccessible(page, 'the filled animal form') + await page + .getByRole('button', { name: dict['animals.form.submit_create'] }) + .click() + + await expect(page).toHaveURL(/\/app\/animals\/[0-9a-f-]{36}$/) + await expect(heading(page, name)).toBeFocused() + await expect(page.getByText(dict['animals.detail.created'])).toBeVisible() + const main = page.getByRole('main') + await expect(main).toContainText( + `${locale === 'fr' ? 'Autre' : 'Other'} (Furet)`, + ) + await expect(main).toContainText( + dict['animals.detail.birth_on'].replace( + '{date}', + formatDate('2021-06-15', locale), + ), + ) + await expect(page.getByText(dict['animals.no_owner'])).toBeVisible() + await expect(page.getByText(dict['relations.none'])).toBeVisible() + await expectAccessible(page, 'the animal page') + await expectNoHorizontalOverflow(page, 'the animal page') + + await page + .getByRole('link', { name: dict['animals.detail.edit'] }) + .click() + await expect(page.getByLabel(dict['animals.form.name'])).toHaveValue(name) + await expect( + page.getByRole('radio', { + name: dict['animals.sex.unknown'], + exact: true, + }), + ).toBeChecked() + await page.getByLabel(dict['animals.form.breed']).fill('Albinos') + await page + .getByRole('button', { + name: dict['animals.form.submit_update'], + exact: true, + }) + .click() + await expect(page.getByText(dict['animals.detail.updated'])).toBeVisible() + await expect(main).toContainText('Albinos') + + await seedAnimal(account, horse) + await page + .getByRole('link', { name: dict['animals.detail.back'] }) + .click() + await expect(listRows(page, dict)).toHaveCount(2) + const search = page.getByRole('searchbox', { + name: dict['animals.list.search_label'], + }) + await search.fill(`furet fictif ${tag}`) + await expect(listRows(page, dict)).toHaveCount(1) + await expect(listRows(page, dict).first()).toContainText(name) + await expect(listRows(page, dict).first()).toContainText( + dict['animals.no_owner'], + ) + await search.fill('albinos') + await expect(listRows(page, dict)).toHaveCount(1) + await search.fill('') + const filter = page.getByRole('combobox', { + name: dict['animals.list.species_filter'], + }) + await filter.selectOption('equine') + await expect(listRows(page, dict)).toHaveCount(1) + await expect(listRows(page, dict).first()).toContainText(horse) + await filter.selectOption('other') + await expect(listRows(page, dict)).toHaveCount(1) + await expect(listRows(page, dict).first()).toContainText(name) + await filter.selectOption('canine') + await expect( + page.getByText(dict['animals.list.no_results']), + ).toBeVisible() + await expectAccessible(page, 'a filtered animal list') + await filter.selectOption('') + await expect(listRows(page, dict)).toHaveCount(2) + await listRows(page, dict) + .filter({ hasText: name }) + .getByRole('link') + .click() + + const archive = page.getByRole('button', { + name: dict['animals.detail.archive'], + }) + await archive.click() + const dialog = page.getByRole('dialog', { + name: dict['animals.archive.title'], + }) + await expect(dialog).toHaveAccessibleDescription( + dict['animals.archive.body'], + ) + await expectAccessible(page, 'the animal archive confirmation') + await page.keyboard.press('Escape') + await expect(dialog).toBeHidden() + await expect(archive).toBeFocused() + await archive.click() + await dialog + .getByRole('button', { + name: dict['animals.archive.confirm'], + exact: true, + }) + .click() + await expect(dialog).toBeHidden() + await expect( + page.getByText(dict['animals.detail.archived'], { exact: true }), + ).toBeVisible() + await expect( + page.getByText(dict['animals.detail.archived_notice']), + ).toBeVisible() + await expect( + page.getByRole('link', { name: dict['animals.detail.edit'] }), + ).toHaveCount(0) + await expect( + page.getByRole('button', { name: dict['relations.add_client'] }), + ).toHaveCount(0) + expect( + await sql( + `select archived_at is not null from public.animals where name = ${literal(name)}`, + ), + ).toBe('t') + + await page + .getByRole('link', { name: dict['animals.detail.back'] }) + .click() + await expect(listRows(page, dict)).toHaveCount(1) + await page + .getByRole('switch', { name: dict['animals.list.archived_toggle'] }) + .check() + await expect(listRows(page, dict)).toHaveCount(1) + await expect(listRows(page, dict).first()).toContainText( + dict['animals.archived_badge'], + ) + await expectAccessible(page, 'the archived animals') + await listRows(page, dict).first().getByRole('link').click() + await page + .getByRole('button', { name: dict['animals.detail.restore'] }) + .click() + await expect( + page.getByText(dict['animals.detail.restored']), + ).toBeVisible() + await expect( + page.getByRole('link', { name: dict['animals.detail.edit'] }), + ).toBeVisible() + // The relations are read again for the restored animal: editable again. + await expect( + relationsCard(page).getByRole('button', { + name: dict['relations.add_client'], + }), + ).toBeVisible() + await expect(page.getByText(dict['relations.none'])).toBeVisible() + }) + + test('pages of 25 with « Afficher plus », in name order', async ({ + page, + requests, + }, info) => { + const account = await createAccount(locale, false) + requests.forbid(account.email, account.password, account.displayName) + const ws = await sql( + `select id from public.workspaces where personal_user_id = ${literal(account.id)}`, + ) + await sql(`insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest) + select ${literal(ws)}, 'Animal Paginé ' || lpad(i::text, 2, '0'), 'canine', 'male', gen_random_uuid(), '\\x00' + from generate_series(1, 30) i`) + await signIn(page, account, dict) + await openAnimals(page, dict, info) + await expect(listRows(page, dict)).toHaveCount(25) + await expect(listRows(page, dict).first()).toContainText( + 'Animal Paginé 01', + ) + await expect(listRows(page, dict).nth(24)).toContainText( + 'Animal Paginé 25', + ) + await page + .getByRole('button', { name: dict['animals.list.more'] }) + .click() + await expect(listRows(page, dict)).toHaveCount(30) + await expect(listRows(page, dict).nth(29)).toContainText( + 'Animal Paginé 30', + ) + await expect( + page.getByRole('button', { name: dict['animals.list.more'] }), + ).toHaveCount(0) + await expectNoHorizontalOverflow(page, 'a long animal list') + }) + + test('from a client page: a first animal pre-associated as owner, then an existing animal linked', async ({ + page, + requests, + }) => { + const tag = tagOf() + const client = `Marie Fictive ${tag}` + const filly = `Pouliche Fictive ${tag}` + const existing = `Cheval Existant ${tag}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + client, + filly, + existing, + tag, + '612345678', + ) + const clientId = await seedClient(account, client, { + phone: '+33612345678', + }) + await seedAnimal(account, existing) + await signIn(page, account, dict) + await page.goto(`/app/clients/${clientId}`) + await expect(heading(page, client)).toBeFocused() + await expect(page.getByText(dict['clients.animals.none'])).toBeVisible() + + await page + .getByRole('link', { name: dict['clients.animals.add_first'] }) + .click() + await expect(page).toHaveURL(/\/app\/animals\/new$/) + await expect( + heading(page, dict['animals.form.create_title']), + ).toBeFocused() + await expect(page.getByRole('main')).toContainText(client) + for (const role of ['owner', 'keeper', 'contact']) + await expect( + page.getByRole('radio', { + name: dict[`clients.role.${role}`], + exact: true, + }), + ).not.toBeChecked() + await expectAccessible(page, 'the animal form with its client') + await page.getByLabel(dict['animals.form.name']).fill(filly) + await page + .getByRole('combobox', { name: dict['animals.form.species'] }) + .selectOption('equine') + await page + .getByRole('radio', { name: dict['animals.sex.female'], exact: true }) + .check() + const submit = page.getByRole('button', { + name: dict['animals.form.submit_create'], + }) + await submit.click() + await expect(page.getByText(dict['animals.error.role'])).toBeVisible() + await expect( + page.getByRole('radio', { + name: dict['clients.role.owner'], + exact: true, + }), + ).toBeFocused() + await page + .getByRole('radio', { name: dict['clients.role.owner'], exact: true }) + .check() + await submit.click() + + await expect(page).toHaveURL(new RegExp(`/app/clients/${clientId}$`)) + await expect( + page.getByText(dict['clients.detail.animal_added']), + ).toBeVisible() + await expect(page.getByRole('link', { name: filly })).toBeVisible() + await expect(page.getByRole('main')).toContainText( + dict['clients.role.owner'], + ) + expect( + await count( + `public.animal_client_relations r join public.animals a on a.id = r.animal_id + where a.name = ${literal(filly)} and r.client_id = ${literal(clientId)} + and r.relation_role = 'owner' and r.ended_at is null and r.voided_at is null`, + ), + ).toBe('1') + + const link = page.getByRole('button', { + name: dict['clients.animals.link_existing'], + }) + await link.click() + const panel = page.getByRole('form', { + name: dict['relations.panel.title_animal'], + }) + await expect( + panel.getByRole('heading', { + name: dict['relations.panel.title_animal'], + }), + ).toBeFocused() + await pick(panel, dict['relations.picker.animal_label'], existing) + await panel + .getByRole('radio', { name: dict['clients.role.keeper'], exact: true }) + .check() + await panel + .getByLabel(dict['relations.panel.started_on']) + .fill('2024-03-01') + await expectAccessible(page, 'the link-an-animal panel') + await expectNoHorizontalOverflow(page, 'the link-an-animal panel') + await panel + .getByRole('button', { name: dict['relations.panel.save_animal'] }) + .click() + await expect(page.getByText(dict['relations.added_animal'])).toBeVisible() + await expect(link).toBeFocused() + await expect(page.getByRole('link', { name: existing })).toBeVisible() + await expect(page.getByRole('main')).toContainText( + dict['clients.animals.since'].replace( + '{date}', + formatDate('2024-03-01', locale), + ), + ) + await expectAccessibleFromTop(page, 'the client page with its animals') + + await page.getByRole('link', { name: filly }).click() + await expect(heading(page, filly)).toBeFocused() + const card = relationsCard(page) + await expect(card.getByRole('link', { name: client })).toBeVisible() + await expect( + card.getByRole('link', { name: '+33612345678' }), + ).toHaveAttribute('href', 'tel:+33612345678') + await expect(page.getByText(dict['animals.no_owner'])).toHaveCount(0) + }) + + test('animal page: co-owners, a keeper structure, a duplicate refused, a mistake voided, the sale ended with its date', async ({ + page, + requests, + }) => { + const tag = tagOf() + const mare = `Jument Vendue ${tag}` + const former = `Ancien Propriétaire ${tag}` + const buyer = `Nouvelle Propriétaire ${tag}` + const stable = `Écurie du Lac ${tag}` + const wrong = `Client Erroné ${tag}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + mare, + former, + buyer, + stable, + wrong, + tag, + ) + const animalId = await seedAnimal(account, mare) + const formerId = await seedClient(account, former) + await seedClient(account, buyer) + await seedClient(account, stable, { kind: 'organization' }) + await seedClient(account, wrong) + await seedRelation(account, animalId, formerId, 'owner', '2018-04-01') + await signIn(page, account, dict) + await page.goto(`/app/animals/${animalId}`) + await expect(heading(page, mare)).toBeFocused() + const card = relationsCard(page) + const add = card.getByRole('button', { + name: dict['relations.add_client'], + }) + + async function link(clientName: string, roleKey: string) { + await add.click() + const panel = page.getByRole('form', { + name: dict['relations.panel.title_client'], + }) + await pick(panel, dict['relations.picker.client_label'], clientName) + await panel + .getByRole('radio', { name: dict[roleKey], exact: true }) + .check() + await panel + .getByRole('button', { name: dict['relations.panel.save_client'] }) + .click() + return panel + } + + await link(buyer, 'clients.role.owner') + await expect(page.getByText(dict['relations.added_client'])).toBeVisible() + await expect(add).toBeFocused() + const current = card.locator( + 'section[aria-labelledby="animal-relations-current"]', + ) + await expect(current.getByRole('link', { name: former })).toBeVisible() + await expect(current.getByRole('link', { name: buyer })).toBeVisible() + + const duplicate = await link(buyer, 'clients.role.owner') + await expect( + duplicate.getByText(dict['relations.failure.duplicate_relation']), + ).toBeVisible() + await expectAccessibleFromTop(page, 'a refused duplicate') + await duplicate + .getByRole('button', { name: dict['common.cancel'] }) + .click() + await expect(add).toBeFocused() + + await link(stable, 'clients.role.keeper') + await expect(current.getByRole('link', { name: stable })).toBeVisible() + await link(wrong, 'clients.role.contact') + await expect(current.getByRole('link', { name: wrong })).toBeVisible() + + await card + .getByRole('button', { + name: actionName( + dict, + 'relations.void.action', + wrong, + 'clients.role.contact', + ), + }) + .click() + const voiding = page.getByRole('dialog', { + name: dict['relations.void.title'], + }) + await expect(voiding).toContainText(dict['relations.void.body']) + await expectAccessible(page, 'the void confirmation') + await voiding + .getByRole('button', { name: dict['relations.void.confirm'] }) + .click() + await expect(voiding).toBeHidden() + await expect(page.getByText(dict['relations.void.done'])).toBeVisible() + await expect(card.getByRole('link', { name: wrong })).toHaveCount(0) + await expect(card.locator(':focus')).toHaveCount(1) + expect( + await count( + `public.animal_client_relations r join public.clients c on c.id = r.client_id + where c.display_name = ${literal(wrong)} and r.voided_at is not null`, + ), + ).toBe('1') + + await card + .getByRole('button', { + name: actionName( + dict, + 'relations.end.action', + former, + 'clients.role.owner', + ), + }) + .click() + const ending = page.getByRole('dialog', { + name: dict['relations.end.title'], + }) + await expect(ending).toContainText(dict['relations.end.body']) + await ending.getByLabel(dict['relations.end.ended_on']).fill('2017-01-01') + await ending + .getByRole('button', { name: dict['relations.end.confirm'] }) + .click() + await expect( + ending.getByText(dict['relations.error.end_before_start']), + ).toBeVisible() + await expect( + ending.getByLabel(dict['relations.end.ended_on']), + ).toBeFocused() + await ending.getByLabel(dict['relations.end.ended_on']).fill('2025-09-30') + await expectAccessible(page, 'the end confirmation') + await ending + .getByRole('button', { name: dict['relations.end.confirm'] }) + .click() + await expect(ending).toBeHidden() + await expect(page.getByText(dict['relations.end.done'])).toBeVisible() + await expect(card.locator(':focus')).toHaveCount(1) + const history = card.locator( + 'section[aria-labelledby="animal-relations-former"]', + ) + await expect(history).toContainText(dict['clients.role.former_owner']) + await expect(history).toContainText( + dict['relations.until'].replace( + '{date}', + formatDate('2025-09-30', locale), + ), + ) + await expect(current.getByRole('link', { name: former })).toHaveCount(0) + await expectAccessible(page, 'an animal with its history') + await expectNoHorizontalOverflow(page, 'an animal with its history') + + await history.getByRole('link', { name: former }).click() + await expect(heading(page, former)).toBeFocused() + const formerGroup = page.locator( + 'section[aria-labelledby="client-animals-former"]', + ) + await expect(formerGroup.getByRole('link', { name: mare })).toBeVisible() + await expect(formerGroup).toContainText(dict['clients.role.former_owner']) + }) + + test('two accounts and a change of session: nothing of A reaches B', async ({ + page, + requests, + }, info) => { + const secret = `Animal Secret ${tagOf()}` + const a = await createAccount(locale, false) + const b = await createAccount(locale, false) + requests.forbid( + a.email, + a.password, + b.email, + b.password, + b.displayName, + secret, + ) + const id = await seedAnimal(a, secret) + await signIn(page, b, dict) + await openAnimals(page, dict, info) + await expect(page.getByText(dict['animals.list.empty'])).toBeVisible() + await page + .getByRole('searchbox', { name: dict['animals.list.search_label'] }) + .fill(secret) + await expect( + page.getByText(dict['animals.list.no_results']), + ).toBeVisible() + for (const path of [ + `/app/animals/${id}`, + `/app/animals/${id}/edit`, + `/app/animals/${randomUUID()}`, + '/app/animals/not-an-id', + ]) { + await page.goto(path) + await expect( + heading(page, dict['animals.not_found.title']), + ).toBeFocused() + await expect(page.getByText(secret)).toHaveCount(0) + } + await expectAccessible(page, 'the animal not found screen') + + await signOut(page, dict, info) + await signIn(page, a, dict) + await openAnimals(page, dict, info) + await expect(listRows(page, dict)).toHaveCount(1) + await expect(listRows(page, dict).first()).toContainText(secret) + await signOut(page, dict, info) + await page.goto(`/app/animals/${id}`) + await expect(page).toHaveURL(/\/login/) + await expect(page.getByText(secret)).toHaveCount(0) + await signIn(page, b, dict) + await openAnimals(page, dict, info) + await expect(page.getByText(dict['animals.list.empty'])).toBeVisible() + await expect(page.getByText(secret)).toHaveCount(0) + }) + + test('keyboard only: create an animal, a refused submit focuses its field', async ({ + page, + requests, + }, info) => { + const name = `Clavier Fictif ${tagOf()}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + name, + ) + await signIn(page, account, dict) + await openAnimals(page, dict, info) + await page.keyboard.press('Tab') + await expect( + page.getByRole('link', { name: dict['animals.list.new'] }), + ).toBeFocused() + await page.keyboard.press('Enter') + await expect( + heading(page, dict['animals.form.create_title']), + ).toBeFocused() + await page.keyboard.press('Tab') + const field = page.getByLabel(dict['animals.form.name']) + await expect(field).toBeFocused() + await page.keyboard.press('Enter') + await expect(page.getByText(dict['animals.error.required'])).toBeVisible() + await expect(field).toBeFocused() + await expect(field).toHaveAttribute('aria-invalid', 'true') + await expectAccessible(page, 'the animal form with errors') + await page.keyboard.type(name) + await page.keyboard.press('Tab') + const species = page.getByRole('combobox', { + name: dict['animals.form.species'], + }) + await expect(species).toBeFocused() + // The select's type-ahead: the first letters of the localized name. + await page.keyboard.type(locale === 'fr' ? 'Chien' : 'Dog') + await expect(species).toHaveValue('canine') + await page.keyboard.press('Tab') + const male = page.getByRole('radio', { + name: dict['animals.sex.male'], + exact: true, + }) + await expect(male).toBeFocused() + await page.keyboard.press('Space') + await expect(male).toBeChecked() + await page.keyboard.press('Shift+Tab') + await page.keyboard.press('Shift+Tab') + await expect(field).toBeFocused() + await page.keyboard.press('Enter') + await expect(heading(page, name)).toBeFocused() + }) + + test('a concurrent edit: the saved values beside the typed ones, then a knowing save', async ({ + page, + requests, + }) => { + const name = `Révision Fictive ${tagOf()}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + name, + ) + const id = await seedAnimal(account, name) + await signIn(page, account, dict) + await page.goto(`/app/animals/${id}/edit`) + const breed = page.getByLabel(dict['animals.form.breed']) + await expect(page.getByLabel(dict['animals.form.name'])).toHaveValue(name) + await breed.fill('Selle Français') + await sql( + `update public.animals set breed = 'Pur-sang', revision = revision + 1 where id = ${literal(id)}`, + ) + const save = page.getByRole('button', { + name: dict['animals.form.submit_update'], + exact: true, + }) + await save.click() + await expect( + page.getByText(dict['animals.form.conflict_title']), + ).toBeVisible() + await expect(breed).toHaveValue('Selle Français') + await expect( + page.getByText( + dict['animals.form.stored_value'].replace('{value}', 'Pur-sang'), + ), + ).toBeVisible() + await expectAccessible(page, 'the animal conflict') + await save.click() + await expect(page.getByText(dict['animals.detail.updated'])).toBeVisible() + expect( + await sql( + `select breed || '/' || revision from public.animals where id = ${literal(id)}`, + ), + ).toBe('Selle Français/3') + }) + + test('a lost answer: the retry sends the same request id, one animal and one relation exist', async ({ + page, + requests, + }) => { + const tag = tagOf() + const client = `Reprise Cliente ${tag}` + const name = `Reprise Animal ${tag}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + client, + name, + ) + const clientId = await seedClient(account, client) + await signIn(page, account, dict) + const sent: string[] = [] + await page.route('**/rest/v1/rpc/create_animal', async (route) => { + sent.push( + JSON.parse(route.request().postData() ?? '{}').create_request_id, + ) + if (sent.length > 1) return route.fallback() + // The server creates the animal and its relation; the answer never reaches the page. + await route.fetch({ url: sandboxUrl(route.request().url()) ?? '' }) + await route.abort('failed') + }) + await page.goto(`/app/clients/${clientId}`) + await page + .getByRole('link', { name: dict['clients.animals.add_first'] }) + .click() + await page.getByLabel(dict['animals.form.name']).fill(name) + await page + .getByRole('combobox', { name: dict['animals.form.species'] }) + .selectOption('feline') + await page + .getByRole('radio', { name: dict['animals.sex.male'], exact: true }) + .check() + await page + .getByRole('radio', { name: dict['clients.role.owner'], exact: true }) + .check() + const submit = page.getByRole('button', { + name: dict['animals.form.submit_create'], + }) + await submit.click() + await expect( + page.getByText(dict['animals.failure.network']), + ).toBeVisible() + const made = `public.animals a join public.animal_client_relations r on r.animal_id = a.id + where a.name = ${literal(name)} and r.client_id = ${literal(clientId)}` + expect(await count(made)).toBe('1') + await submit.click() + await expect(heading(page, client)).toBeVisible() + expect(sent).toHaveLength(2) + expect(sent[0]).toBe(sent[1]) + expect(await count(made)).toBe('1') + expect(await count(`public.animals where name = ${literal(name)}`)).toBe( + '1', + ) + }) + + test('failures: a list retries, a failed relation write stays in its dialog, an archived client is refused', async ({ + page, + requests, + }, info) => { + const tag = tagOf() + const name = `Réseau Animal ${tag}` + const owner = `Réseau Client ${tag}` + const other = `Archivée Ensuite ${tag}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + name, + owner, + other, + tag, + ) + const animalId = await seedAnimal(account, name) + const ownerId = await seedClient(account, owner) + const otherId = await seedClient(account, other) + await seedRelation(account, animalId, ownerId, 'owner') + await signIn(page, account, dict) + let failing = true + await page.route('**/rest/v1/rpc/search_animals', (route) => + failing ? route.abort('failed') : route.fallback(), + ) + await openAnimals(page, dict, info) + await expect( + page.getByText(dict['animals.failure.network']), + ).toBeVisible() + failing = false + await page.getByRole('button', { name: dict['common.retry'] }).click() + await expect(listRows(page, dict)).toHaveCount(1) + await listRows(page, dict).first().getByRole('link').click() + await expect(heading(page, name)).toBeFocused() + + let endFailing = true + await page.route('**/rest/v1/rpc/end_animal_client_relation', (route) => + endFailing ? route.abort('failed') : route.fallback(), + ) + const card = relationsCard(page) + await card + .getByRole('button', { + name: actionName( + dict, + 'relations.end.action', + owner, + 'clients.role.owner', + ), + }) + .click() + const ending = page.getByRole('dialog', { + name: dict['relations.end.title'], + }) + await ending.getByLabel(dict['relations.end.ended_on']).fill('2025-01-15') + await ending + .getByRole('button', { name: dict['relations.end.confirm'] }) + .click() + await expect( + ending.getByText(dict['relations.failure.network']), + ).toBeVisible() + await expect( + ending.getByLabel(dict['relations.end.ended_on']), + ).toHaveValue('2025-01-15') + endFailing = false + await ending + .getByRole('button', { name: dict['relations.end.confirm'] }) + .click() + await expect(ending).toBeHidden() + await expect(page.getByText(dict['relations.end.done'])).toBeVisible() + + await card + .getByRole('button', { name: dict['relations.add_client'] }) + .click() + const panel = page.getByRole('form', { + name: dict['relations.panel.title_client'], + }) + await pick(panel, dict['relations.picker.client_label'], other) + await panel + .getByRole('radio', { name: dict['clients.role.contact'], exact: true }) + .check() + await sql( + `update public.clients set archived_at = now() where id = ${literal(otherId)}`, + ) + await panel + .getByRole('button', { name: dict['relations.panel.save_client'] }) + .click() + await expect( + panel.getByText(dict['relations.failure.archived']), + ).toBeVisible() + await expect( + panel.getByRole('radio', { + name: dict['clients.role.contact'], + exact: true, + }), + ).toBeChecked() + }) + + test('the animal pages follow a change of language', async ({ + page, + requests, + }, info) => { + const tag = tagOf() + const name = `Animal Bilingue ${tag}` + const owner = `Client Bilingue ${tag}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + name, + owner, + ) + const animalId = await seedAnimal(account, name, 'canine', 'male') + await seedRelation( + account, + animalId, + await seedClient(account, owner), + 'owner', + ) + await signIn(page, account, dict) + await openAnimals(page, dict, info) + const other = locale === 'fr' ? en : fr + await page + .getByRole('button', { + name: dict[ + locale === 'fr' ? 'lang.switch_to_en' : 'lang.switch_to_fr' + ], + }) + .click() + await expect( + page.getByRole('link', { name: other['animals.list.new'] }), + ).toBeVisible() + await expect( + page.getByRole('combobox', { + name: other['animals.list.species_filter'], + }), + ).toBeVisible() + await expect(listRows(page, other).first()).toContainText( + other['animals.sex.male'], + ) + await expect(listRows(page, other).first()).toContainText( + other['animals.list.owner'].replace('{names}', owner), + ) + await expectAccessible(page, 'the animal list after a change of language') + await listRows(page, other).first().getByRole('link').click() + await expect(relationsCard(page)).toContainText(other['relations.title']) + await expect(relationsCard(page)).toContainText( + other['clients.role.owner'], + ) + }) + }) +} diff --git a/apps/app/e2e/support/records.ts b/apps/app/e2e/support/records.ts new file mode 100644 index 00000000..f078ccd5 --- /dev/null +++ b/apps/app/e2e/support/records.ts @@ -0,0 +1,54 @@ +/** + * Setup rows of the shell suites, written as postgres in an account's + * workspace of the isolated stack: the subject of a test goes through the + * page, its surroundings through here. Values are fictitious literals; each + * one is quoted as an SQL literal, never pasted raw. + */ +import { sql } from '../../../../packages/supabase/tests/sandbox/stack' +import { workspaceOf, type SandboxAccount } from './sandbox' + +/** A text as an SQL literal ('' doubles a quote), or null. */ +export const literal = (value: string | null) => + value === null ? 'null' : `'${value.replaceAll("'", "''")}'` + +export interface ClientSeed { + kind?: 'person' | 'organization' + city?: string | null + phone?: string | null +} + +export async function seedClient( + account: SandboxAccount, + displayName: string, + seed: ClientSeed = {}, +): Promise { + const ws = await workspaceOf(account) + return sql(`insert into public.clients (workspace_id, kind, display_name, city, phone, create_request_id, create_request_digest) + values (${literal(ws)}, ${literal(seed.kind ?? 'person')}, ${literal(displayName)}, ${literal(seed.city ?? null)}, + ${literal(seed.phone ?? null)}, gen_random_uuid(), '\\x00') returning id`) +} + +export async function seedAnimal( + account: SandboxAccount, + name: string, + speciesId = 'equine', + sex: 'male' | 'female' | 'unknown' = 'female', +): Promise { + const ws = await workspaceOf(account) + return sql(`insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest) + values (${literal(ws)}, ${literal(name)}, ${literal(speciesId)}, ${literal(sex)}, gen_random_uuid(), '\\x00') returning id`) +} + +export async function seedRelation( + account: SandboxAccount, + animalId: string, + clientId: string, + role: 'owner' | 'keeper' | 'contact', + startedOn: string | null = null, +): Promise { + const ws = await workspaceOf(account) + return sql(`insert into public.animal_client_relations + (workspace_id, animal_id, client_id, relation_role, started_on, create_request_id, create_request_digest) + values (${literal(ws)}, ${literal(animalId)}, ${literal(clientId)}, ${literal(role)}, ${literal(startedOn)}, + gen_random_uuid(), '\\x00') returning id`) +} diff --git a/scripts/db-sandbox.sh b/scripts/db-sandbox.sh index 7aa43789..fede3b49 100755 --- a/scripts/db-sandbox.sh +++ b/scripts/db-sandbox.sh @@ -13,7 +13,7 @@ # pnpm db:sandbox test-db the pgTAP files (`supabase test db`) # pnpm db:sandbox types [--check] generated types (write, or diff with the committed file) # pnpm db:sandbox test packages/supabase/tests/sandbox (HTTP, concurrency) -# pnpm db:sandbox e2e-shell = pnpm e2e:shell: the /app shell in Chromium (apps/app/e2e) +# pnpm db:sandbox e2e-shell [args] = pnpm e2e:shell: the /app shell in Chromium (apps/app/e2e); args go to Playwright (a spec file, --grep) # pnpm db:sandbox sql psql as postgres on stdin # pnpm db:sandbox down # @@ -247,7 +247,7 @@ case "${1:-}" in printf '%s\n' "$out" > packages/supabase/src/database.types.ts; echo "== types written" fi ;; test) load_secrets; with_sandbox_env node_modules/.bin/pnpm --filter @faunosteo/supabase test:sandbox ;; - e2e-shell) load_secrets; with_sandbox_env node_modules/.bin/pnpm --filter @faunosteo/app e2e:shell ;; + e2e-shell) shift; load_secrets; with_sandbox_env node_modules/.bin/pnpm --filter @faunosteo/app e2e:shell "$@" ;; sql) load_secrets; sb_psql ;; *) sed -n '2,23p' "$0"; exit 1 ;; esac