import { RecordFailure, classifyRecordError, createClientRecord, fetchClientArchivePreview, fetchClientRecord, fetchPersonalWorkspaceId, listClientAnimals, searchClients, setClientArchived, updateClientRecord, type ClientFields, type FaunosteoClient, } from '../src' /** * Call shapes and closed failure kinds of the workspaces and clients access * layer. The argument names are checked by the compiler against the generated * types; the RPC bodies by supabase/tests/013_clients.sql and 014; the same * functions run against real PostgREST in tests/sandbox/clients-access.sandbox.ts. */ type Answer = { data?: unknown; error?: unknown; status?: number } function stubClient(answers: { rpc?: Answer; select?: Answer } = {}) { const rpcCalls: Array<[string, Record]> = [] const query: Record = {} const settle = (a: Answer = {}) => ({ data: a.data ?? null, error: a.error ?? null, status: a.status ?? (a.error ? 400 : 200), }) const chain = { select: (cols: string) => ((query.select = cols), chain), eq: (col: string, value: unknown) => ((query[`eq:${col}`] = value), chain), maybeSingle: async () => settle(answers.select), } const client = { from: (table: string) => ((query.table = table), chain), rpc: async (name: string, args: Record) => { rpcCalls.push([name, args]) return settle(answers.rpc) }, } as unknown as FaunosteoClient return { client, rpcCalls, query } } const WS = '11111111-1111-4111-8111-111111111111' const ID = '22222222-2222-4222-8222-222222222222' const REQUEST = '33333333-3333-4333-8333-333333333333' const fields: ClientFields = { kind: 'person', display_name: 'Marie Dupont', email: null, phone: '+33612345678', address_line1: null, address_line2: null, postal_code: null, city: 'Lyon', country: null, } function listRow(i: number) { return { id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`, kind: 'person', display_name: `Client ${i}`, city: null, phone: null, email: null, archived_at: null, name_key: `client ${String(i).padStart(3, '0')}`, current_animal_count: 0, } } async function kindOf(promise: Promise) { try { await promise return 'no failure' } catch (error) { return error instanceof RecordFailure ? error.kind : 'not a RecordFailure' } } describe('classifyRecordError', () => { it.each([ [{ code: '42501', message: 'not_found' }, 403, 'not_found'], [{ code: 'P0001', message: 'archived' }, 400, 'archived'], [{ code: 'P0001', message: 'conflict' }, 400, 'conflict'], [{ code: 'P0001', message: 'request_conflict' }, 400, 'request_conflict'], [{ code: 'P0001', message: 'limit_reached' }, 400, 'limit_reached'], [{ code: 'P0001', message: 'rate_limited' }, 400, 'rate_limited'], [{ code: 'P0001', message: 'invalid_input' }, 400, 'invalid_input'], [{ code: 'P0001', message: 'something else' }, 400, 'unavailable'], [ { code: '42501', message: 'permission denied for table clients' }, 403, 'unavailable', ], [{ code: 'PGRST301', message: 'JWT expired' }, 401, 'session_expired'], [{ code: '', message: 'anything' }, 401, 'session_expired'], [{ code: '', message: 'TypeError: Failed to fetch' }, 0, 'network'], [ { code: '57014', message: 'canceling statement due to statement timeout', }, 500, 'unavailable', ], ])('%o with HTTP %i is %s', (error, status, kind) => { expect(classifyRecordError(error, status)).toBe(kind) }) it('reads a thrown TypeError as the network', () => { expect(classifyRecordError(new TypeError('Failed to fetch'))).toBe( 'network', ) }) }) describe('fetchPersonalWorkspaceId', () => { it('reads the id of the workspace whose personal user is the caller', async () => { const { client, query } = stubClient({ select: { data: { id: WS } } }) expect(await fetchPersonalWorkspaceId(client, 'user-1')).toBe(WS) expect(query).toEqual({ table: 'workspaces', select: 'id', 'eq:personal_user_id': 'user-1', }) }) it('answers null when RLS returns no row, and a closed kind on failure', async () => { expect( await fetchPersonalWorkspaceId(stubClient().client, 'user-1'), ).toBeNull() const failing = stubClient({ select: { error: { code: '', message: 'FetchError' }, status: 0 }, }) expect( await kindOf(fetchPersonalWorkspaceId(failing.client, 'user-1')), ).toBe('network') }) }) describe('searchClients', () => { it('posts the term, asks one row more than the page and leaves the cursor out on page one', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: [listRow(1)] } }) const page = await searchClients(client, { workspaceId: WS, query: 'marie', archived: false, }) expect(rpcCalls).toEqual([ [ 'search_clients', { workspace_id: WS, query: 'marie', archived: false, page_size: 26, after_name_key: undefined, after_id: undefined, }, ], ]) expect(page).toEqual({ rows: [listRow(1)], next: null }) }) it('keeps 25 rows and turns the 26th into a next cursor at the 25th', async () => { const rows = Array.from({ length: 26 }, (_, i) => listRow(i + 1)) const { client, rpcCalls } = stubClient({ rpc: { data: rows } }) const page = await searchClients(client, { workspaceId: WS, query: '', archived: true, after: { nameKey: 'client 000', id: ID }, }) expect(page.rows).toHaveLength(25) expect(page.next).toEqual({ nameKey: rows[24].name_key, id: rows[24].id }) expect(rpcCalls[0][1]).toMatchObject({ after_name_key: 'client 000', after_id: ID, archived: true, }) }) it('refuses an answer of another shape as unavailable', async () => { const { client } = stubClient({ rpc: { data: [{ id: 'x' }] } }) expect( await kindOf( searchClients(client, { workspaceId: WS, query: '', archived: false }), ), ).toBe('unavailable') }) }) describe('fetchClientRecord', () => { it('reads one client by id with the explicit column list', async () => { const { client, query } = stubClient({ select: { data: { id: ID } } }) expect(await fetchClientRecord(client, ID)).toEqual({ id: ID }) expect(query.table).toBe('clients') expect(query['eq:id']).toBe(ID) expect(String(query.select)).not.toContain('*') expect(String(query.select)).not.toContain('create_request_digest') }) it('answers null for an id that is not a uuid, without a request', async () => { const { client, query } = stubClient() expect(await fetchClientRecord(client, 'not-a-uuid')).toBeNull() expect(query.table).toBeUndefined() }) }) describe('client writes', () => { it('creates with the request id and leaves absent optionals to their defaults', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { id: ID, revision: 1 } }, }) expect( await createClientRecord(client, { workspaceId: WS, requestId: REQUEST, fields, }), ).toEqual({ id: ID, revision: 1, }) expect(rpcCalls[0]).toEqual([ 'create_client', { workspace_id: WS, create_request_id: REQUEST, kind: 'person', display_name: 'Marie Dupont', email: undefined, phone: '+33612345678', address_line1: undefined, address_line2: undefined, postal_code: undefined, city: 'Lyon', country: undefined, }, ]) }) it('updates with every field, null included, at the expected revision', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } }) expect( await updateClientRecord(client, { clientId: ID, expectedRevision: 2, fields, }), ).toEqual({ revision: 3 }) expect(rpcCalls[0]).toEqual([ 'update_client', { client_id: ID, expected_revision: 2, ...fields }, ]) }) it('archives and restores through set_client_archived', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } }) expect(await setClientArchived(client, ID, true)).toEqual({ revision: 2 }) expect(rpcCalls[0]).toEqual([ 'set_client_archived', { client_id: ID, archived: true }, ]) }) it.each([ 'conflict', 'request_conflict', 'archived', 'rate_limited', 'limit_reached', 'invalid_input', ])('a %s refusal reaches the caller as that kind', async (message) => { const { client } = stubClient({ rpc: { error: { code: 'P0001', message } }, }) expect( await kindOf( updateClientRecord(client, { clientId: ID, expectedRevision: 1, fields, }), ), ).toBe(message) }) it('an unknown or foreign id is not_found', async () => { const { client } = stubClient({ rpc: { error: { code: '42501', message: 'not_found' }, status: 403 }, }) expect(await kindOf(setClientArchived(client, ID, true))).toBe('not_found') }) }) describe('client animals and archive preview', () => { it('lists 50 relations per page by default with a cursor on sort_key and relation id', async () => { const row = (i: number) => ({ relation_id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`, relation_role: 'owner', started_on: null, ended_on: null, is_current: true, relation_revision: 1, animal_id: ID, animal_name: `Animal ${i}`, species_id: 'equine', species_detail: null, sex: 'female', breed: null, birth_year: null, animal_archived_at: null, sort_key: `0animal ${String(i).padStart(3, '0')}`, }) const rows = Array.from({ length: 51 }, (_, i) => row(i + 1)) const { client, rpcCalls } = stubClient({ rpc: { data: rows } }) const page = await listClientAnimals(client, ID) expect(rpcCalls[0]).toEqual([ 'list_client_animals', { client_id: ID, page_size: 51, after_sort: undefined, after_id: undefined, }, ]) expect(page.rows).toHaveLength(50) expect(page.next).toEqual({ sortKey: rows[49].sort_key, relationId: rows[49].relation_id, }) }) it('reads the archive preview', async () => { const preview = { count: 1, animals: [{ id: ID, name: 'Éclair' }] } const { client, rpcCalls } = stubClient({ rpc: { data: preview } }) expect(await fetchClientArchivePreview(client, ID)).toEqual(preview) expect(rpcCalls[0]).toEqual(['client_archive_preview', { client_id: ID }]) }) })