import { ANIMAL_COLUMNS, ANIMAL_RELATION_COLUMNS, RECORD_FAILURE_KINDS, RecordFailure, classifyRecordError, createAnimalClientRelation, createAnimalRecord, endAnimalClientRelation, fetchAnimalRecord, fetchAnimalRelations, parseRecordAnswer, searchAnimals, setAnimalArchived, updateAnimalClientRelation, updateAnimalRecord, voidAnimalClientRelation, type AnimalFields, type FaunosteoClient, } from '../src' import { z } from 'zod' /** * Call shapes and closed failure kinds of the animals and relations access * layer. The argument names are checked by the compiler against the generated * types; the RPC bodies by supabase/tests/014_animals_relations.sql; the same * functions run against real PostgREST in tests/sandbox/animals-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 orders: string[] = [] 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), is: (col: string, value: unknown) => ((query[`is:${col}`] = value), chain), order: (col: string) => (orders.push(col), chain), limit: (n: number) => ((query.limit = n), chain), maybeSingle: async () => settle(answers.select), then: (resolve: (v: unknown) => void) => resolve(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, orders } } const WS = '11111111-1111-4111-8111-111111111111' const ID = '22222222-2222-4222-8222-222222222222' const REQUEST = '33333333-3333-4333-8333-333333333333' const CLIENT = '44444444-4444-4444-8444-444444444444' const RELATION = '55555555-5555-4555-8555-555555555555' const fields: AnimalFields = { name: 'Éclair', species_id: 'equine', species_detail: null, sex: 'female', breed: null, birth_year: 2015, birth_date: null, } function listRow(i: number) { return { id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`, name: `Animal ${i}`, species_id: 'equine', species_detail: null, sex: 'unknown', breed: null, birth_year: null, archived_at: null, name_key: `animal ${String(i).padStart(3, '0')}`, current_owners: [], current_owner_count: 0, } } function relationRow(patch: Record = {}) { return { id: RELATION, relation_role: 'owner', started_on: null, ended_on: null, ended_at: null, revision: 1, client: { id: CLIENT, kind: 'person', display_name: 'Marie Dupont', phone: null, email: null, archived_at: null, }, ...patch, } } async function kindOf(promise: Promise) { try { await promise return 'no failure' } catch (error) { return error instanceof RecordFailure ? error.kind : 'not a RecordFailure' } } describe('relation failure kinds', () => { it('are closed kinds of the record failures', () => { expect(RECORD_FAILURE_KINDS).toContain('duplicate_relation') expect(RECORD_FAILURE_KINDS).toContain('already_ended') }) it.each(['duplicate_relation', 'already_ended'])( 'P0001 %s is that kind', (message) => { expect(classifyRecordError({ code: 'P0001', message }, 400)).toBe(message) }, ) it('parseRecordAnswer returns the parsed value or throws unavailable', async () => { const schema = z.object({ revision: z.number().int() }) expect(parseRecordAnswer(schema, { revision: 2 })).toEqual({ revision: 2 }) expect( await kindOf(Promise.resolve().then(() => parseRecordAnswer(schema, {}))), ).toBe('unavailable') }) }) describe('searchAnimals', () => { it('posts the term, every species when null, one row more than the page', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: [listRow(1)] } }) const page = await searchAnimals(client, { workspaceId: WS, query: 'ecl', speciesId: null, archived: false, }) expect(rpcCalls).toEqual([ [ 'search_animals', { workspace_id: WS, query: 'ecl', species_filter: undefined, archived: false, page_size: 26, after_name_key: undefined, after_id: undefined, }, ], ]) expect(page).toEqual({ rows: [listRow(1)], next: null }) }) it('sends the species filter and the cursor; the probe row becomes next', async () => { const rows = Array.from({ length: 11 }, (_, i) => listRow(i + 1)) const { client, rpcCalls } = stubClient({ rpc: { data: rows } }) const page = await searchAnimals(client, { workspaceId: WS, query: '', speciesId: 'canine', archived: true, pageSize: 10, after: { nameKey: 'animal 000', id: ID }, }) expect(rpcCalls[0][1]).toMatchObject({ species_filter: 'canine', archived: true, page_size: 11, after_name_key: 'animal 000', after_id: ID, }) expect(page.rows).toHaveLength(10) expect(page.next).toEqual({ nameKey: rows[9].name_key, id: rows[9].id }) }) it('refuses an answer of another shape as unavailable', async () => { const { client } = stubClient({ rpc: { data: [{ id: ID }] } }) expect( await kindOf( searchAnimals(client, { workspaceId: WS, query: '', speciesId: null, archived: false, }), ), ).toBe('unavailable') }) }) describe('fetchAnimalRecord', () => { it('reads one animal by id with the explicit column list', async () => { const { client, query } = stubClient({ select: { data: { id: ID } } }) expect(await fetchAnimalRecord(client, ID)).toEqual({ id: ID }) expect(query).toEqual({ table: 'animals', select: ANIMAL_COLUMNS, 'eq:id': ID, }) expect(ANIMAL_COLUMNS).not.toContain('*') expect(ANIMAL_COLUMNS).not.toContain('create_request') expect(ANIMAL_COLUMNS).not.toContain('workspace_id') }) it('answers null for an id that is not a uuid, without a request', async () => { const { client, query } = stubClient() expect(await fetchAnimalRecord(client, 'not-a-uuid')).toBeNull() expect(query.table).toBeUndefined() }) it('maps a lost answer to network and an expired session to session_expired', async () => { const lost = stubClient({ select: { error: { code: '', message: 'FetchError' }, status: 0 }, }) expect(await kindOf(fetchAnimalRecord(lost.client, ID))).toBe('network') const expired = stubClient({ select: { error: { code: 'PGRST301', message: 'JWT expired' }, status: 401, }, }) expect(await kindOf(fetchAnimalRecord(expired.client, ID))).toBe( 'session_expired', ) }) }) describe('animal writes', () => { it('creates without relation: optionals left to their defaults, year as text', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { id: ID, revision: 1, relation_id: null } }, }) expect( await createAnimalRecord(client, { workspaceId: WS, requestId: REQUEST, fields, relation: null, }), ).toEqual({ id: ID, revision: 1, relationId: null }) expect(rpcCalls[0]).toEqual([ 'create_animal', { workspace_id: WS, create_request_id: REQUEST, name: 'Éclair', species_id: 'equine', sex: 'female', species_detail: undefined, breed: undefined, birth_year: '2015', birth_date: undefined, client_id: undefined, relation_role: undefined, started_on: undefined, }, ]) }) it('creates with an initial relation in the same call', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { id: ID, revision: 1, relation_id: RELATION } }, }) const created = await createAnimalRecord(client, { workspaceId: WS, requestId: REQUEST, fields: { ...fields, species_id: 'other', species_detail: 'Furet', birth_year: 2015, birth_date: '2015-04-12', }, relation: { clientId: CLIENT, relationRole: 'keeper', startedOn: '2020-01-02', }, }) expect(created.relationId).toBe(RELATION) expect(rpcCalls[0][1]).toMatchObject({ species_id: 'other', species_detail: 'Furet', birth_year: '2015', birth_date: '2015-04-12', client_id: CLIENT, relation_role: 'keeper', started_on: '2020-01-02', }) const noDate = stubClient({ rpc: { data: { id: ID, revision: 1, relation_id: RELATION } }, }) await createAnimalRecord(noDate.client, { workspaceId: WS, requestId: REQUEST, fields: { ...fields, birth_year: null }, relation: { clientId: CLIENT, relationRole: 'owner', startedOn: null }, }) expect(noDate.rpcCalls[0][1]).toMatchObject({ birth_year: undefined, started_on: undefined, client_id: CLIENT, }) }) it('updates with every field, null included, at the expected revision', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } }) expect( await updateAnimalRecord(client, { animalId: ID, expectedRevision: 2, fields: { ...fields, birth_year: null }, }), ).toEqual({ revision: 3 }) expect(rpcCalls[0]).toEqual([ 'update_animal', { animal_id: ID, expected_revision: 2, name: 'Éclair', species_id: 'equine', sex: 'female', species_detail: null, breed: null, birth_year: null, birth_date: null, }, ]) const withYear = stubClient({ rpc: { data: { revision: 3 } } }) await updateAnimalRecord(withYear.client, { animalId: ID, expectedRevision: 2, fields, }) expect(withYear.rpcCalls[0][1].birth_year).toBe('2015') }) it('archives and restores through set_animal_archived', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } }) expect(await setAnimalArchived(client, ID, false)).toEqual({ revision: 2 }) expect(rpcCalls[0]).toEqual([ 'set_animal_archived', { animal_id: ID, archived: false }, ]) }) 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( updateAnimalRecord(client, { animalId: ID, expectedRevision: 1, fields, }), ), ).toBe(message) }) it('an unknown or foreign id is not_found; a created answer of another shape is unavailable', async () => { const { client } = stubClient({ rpc: { error: { code: '42501', message: 'not_found' }, status: 403 }, }) expect(await kindOf(setAnimalArchived(client, ID, true))).toBe('not_found') const odd = stubClient({ rpc: { data: { id: ID, revision: 1 } } }) expect( await kindOf( createAnimalRecord(odd.client, { workspaceId: WS, requestId: REQUEST, fields, relation: null, }), ), ).toBe('unavailable') }) }) describe('fetchAnimalRelations', () => { it('reads by animal id, voided left out, explicit columns, bounded and ordered', async () => { const { client, query, orders } = stubClient({ select: { data: [relationRow()] }, }) expect(await fetchAnimalRelations(client, ID)).toEqual([relationRow()]) expect(query).toEqual({ table: 'animal_client_relations', select: ANIMAL_RELATION_COLUMNS, 'eq:animal_id': ID, 'is:voided_at': null, limit: 200, }) expect(orders).toEqual(['created_at', 'id']) expect(ANIMAL_RELATION_COLUMNS).not.toContain('*') expect(ANIMAL_RELATION_COLUMNS).not.toContain('create_request') }) it('answers [] for an id that is not a uuid, without a request', async () => { const { client, query } = stubClient() expect(await fetchAnimalRelations(client, 'nope')).toEqual([]) expect(query.table).toBeUndefined() }) it('refuses a row without its client as unavailable, maps failures', async () => { const { client } = stubClient({ select: { data: [relationRow({ client: null })] }, }) expect(await kindOf(fetchAnimalRelations(client, ID))).toBe('unavailable') const lost = stubClient({ select: { error: { message: 'TypeError: Failed to fetch' }, status: 0 }, }) expect(await kindOf(fetchAnimalRelations(lost.client, ID))).toBe('network') }) }) describe('relation writes', () => { it('creates with the request id; a missing start date is left to its default', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { id: RELATION, revision: 1 } }, }) expect( await createAnimalClientRelation(client, { animalId: ID, clientId: CLIENT, requestId: REQUEST, relationRole: 'contact', startedOn: null, }), ).toEqual({ id: RELATION, revision: 1 }) expect(rpcCalls[0]).toEqual([ 'create_animal_client_relation', { animal_id: ID, client_id: CLIENT, create_request_id: REQUEST, relation_role: 'contact', started_on: undefined, }, ]) }) it('ends with or without a date', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } }) await endAnimalClientRelation(client, { relationId: RELATION, expectedRevision: 1, endedOn: null, }) await endAnimalClientRelation(client, { relationId: RELATION, expectedRevision: 1, endedOn: '2024-05-01', }) expect(rpcCalls).toEqual([ [ 'end_animal_client_relation', { relation_id: RELATION, expected_revision: 1, ended_on: undefined }, ], [ 'end_animal_client_relation', { relation_id: RELATION, expected_revision: 1, ended_on: '2024-05-01' }, ], ]) }) it('corrects the dates sending both, null included', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } }) expect( await updateAnimalClientRelation(client, { relationId: RELATION, expectedRevision: 2, startedOn: '2020-01-01', endedOn: null, }), ).toEqual({ revision: 3 }) expect(rpcCalls[0]).toEqual([ 'update_animal_client_relation', { relation_id: RELATION, expected_revision: 2, started_on: '2020-01-01', ended_on: null, }, ]) }) it('voids at the expected revision', async () => { const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } }) expect( await voidAnimalClientRelation(client, { relationId: RELATION, expectedRevision: 1, }), ).toEqual({ revision: 2 }) expect(rpcCalls[0]).toEqual([ 'void_animal_client_relation', { relation_id: RELATION, expected_revision: 1 }, ]) }) it.each([ ['duplicate_relation', 'P0001', 400], ['already_ended', 'P0001', 400], ['conflict', 'P0001', 400], ['archived', 'P0001', 400], ['limit_reached', 'P0001', 400], ['not_found', '42501', 403], ])( 'a %s refusal reaches the caller as that kind', async (message, code, status) => { const { client } = stubClient({ rpc: { error: { code, message }, status }, }) expect( await kindOf( createAnimalClientRelation(client, { animalId: ID, clientId: CLIENT, requestId: REQUEST, relationRole: 'owner', startedOn: null, }), ), ).toBe(message) expect( await kindOf( endAnimalClientRelation(client, { relationId: RELATION, expectedRevision: 1, endedOn: null, }), ), ).toBe(message) }, ) it('an expired session, a lost answer and an odd answer are closed kinds', async () => { const expired = stubClient({ rpc: { error: { code: 'PGRST301', message: 'JWT expired' }, status: 401 }, }) expect( await kindOf( voidAnimalClientRelation(expired.client, { relationId: RELATION, expectedRevision: 1, }), ), ).toBe('session_expired') const lost = stubClient({ rpc: { error: { message: 'TypeError: Failed to fetch' }, status: 0 }, }) expect( await kindOf( voidAnimalClientRelation(lost.client, { relationId: RELATION, expectedRevision: 1, }), ), ).toBe('network') const odd = stubClient({ rpc: { data: { revision: 'x' } } }) expect( await kindOf( voidAnimalClientRelation(odd.client, { relationId: RELATION, expectedRevision: 1, }), ), ).toBe('unavailable') }) })