/** * The V1-1.5 access layer (src/workspaces.ts, src/clients.ts) against the * real GoTrue and PostgREST of `pnpm db:sandbox`, through supabase-js as the * browser uses it: the generated argument names, the explicit columns, the * keyset pages and every closed failure kind come from the real server, not * from a stub. One base URL is mapped onto the sandbox services, as Kong does. */ import { randomUUID } from 'node:crypto' import { createClient } from '@supabase/supabase-js' import { RecordFailure, createClientRecord, fetchClientArchivePreview, fetchClientRecord, fetchPersonalWorkspaceId, listClientAnimals, searchClients, setClientArchived, updateClientRecord, type ClientFields, type Database, type FaunosteoClient, } from '../../src' import { PASSWORD, confirmedAccount, sql, stack, type Account } from './stack' const BASE = 'http://sandbox.faunosteo.invalid' /** The browser client of the app, its requests replayed on the sandbox ports. */ function browserClient(fetchImpl: typeof fetch = fetch): FaunosteoClient { const mapped: typeof fetch = (input, init) => { const url = String(input instanceof Request ? input.url : input) .replace(`${BASE}/auth/v1`, stack.authUrl) .replace(`${BASE}/rest/v1`, stack.restUrl) return fetchImpl(url, init) } return createClient(BASE, stack.anonKey, { auth: { persistSession: false, autoRefreshToken: false }, global: { fetch: mapped }, }) } async function signedIn(account: Account): Promise { const client = browserClient() const { error } = await client.auth.signInWithPassword({ email: account.email, password: PASSWORD, }) if (error) throw error return client } async function kindOf(promise: Promise) { try { await promise return 'no failure' } catch (error) { return error instanceof RecordFailure ? error.kind : String(error) } } const person = ( displayName: string, patch: Partial = {}, ): ClientFields => ({ kind: 'person', display_name: displayName, email: null, phone: null, address_line1: null, address_line2: null, postal_code: null, city: null, country: null, ...patch, }) describe('workspaces and clients access layer on the sandbox', () => { let a: Account let b: Account let asA: FaunosteoClient let asB: FaunosteoClient let wA: string beforeAll(async () => { a = await confirmedAccount('acc-a') b = await confirmedAccount('acc-b') asA = await signedIn(a) asB = await signedIn(b) wA = (await fetchPersonalWorkspaceId(asA, a.id)) as string }) it('finds the personal workspace of the caller only', async () => { expect(wA).toBe( await sql( `select id from public.workspaces where personal_user_id = '${a.id}'`, ), ) expect(await fetchPersonalWorkspaceId(asB, a.id)).toBeNull() }) it('creates idempotently, refuses a divergent replay, reads the explicit columns', async () => { const requestId = randomUUID() const fields = person('Marie Dupont', { email: 'marie@exemple.test', phone: '+33612345678', city: 'Lyon', country: 'FR', }) const first = await createClientRecord(asA, { workspaceId: wA, requestId, fields, }) const replay = await createClientRecord(asA, { workspaceId: wA, requestId, fields, }) expect(replay).toEqual(first) expect( await kindOf( createClientRecord(asA, { workspaceId: wA, requestId, fields: person('Marie Durand'), }), ), ).toBe('request_conflict') const record = await fetchClientRecord(asA, first.id) expect(Object.keys(record ?? {}).sort()).toEqual( [ 'address_line1', 'address_line2', 'archived_at', 'city', 'country', 'created_at', 'display_name', 'email', 'id', 'kind', 'phone', 'postal_code', 'revision', 'updated_at', ].sort(), ) expect(record).toMatchObject({ ...fields, revision: 1, archived_at: null }) }) it('updates at the revision, clears a field with null, refuses a stale revision', async () => { const { id } = await createClientRecord(asA, { workspaceId: wA, requestId: randomUUID(), fields: person('Paul Martin', { city: 'Annecy' }), }) expect( await updateClientRecord(asA, { clientId: id, expectedRevision: 1, fields: person('Paul Martin', { city: null, phone: '+41791234567' }), }), ).toEqual({ revision: 2 }) expect(await fetchClientRecord(asA, id)).toMatchObject({ city: null, phone: '+41791234567', revision: 2, }) expect( await kindOf( updateClientRecord(asA, { clientId: id, expectedRevision: 1, fields: person('X'), }), ), ).toBe('conflict') expect( await kindOf( updateClientRecord(asA, { clientId: id, expectedRevision: 2, fields: person(''), }), ), ).toBe('invalid_input') }) it('archives, refuses edits while archived, restores', async () => { const { id } = await createClientRecord(asA, { workspaceId: wA, requestId: randomUUID(), fields: person('Zoé Bernard'), }) expect(await setClientArchived(asA, id, true)).toEqual({ revision: 2 }) expect( await kindOf( updateClientRecord(asA, { clientId: id, expectedRevision: 2, fields: person('Zoé'), }), ), ).toBe('archived') const archived = await searchClients(asA, { workspaceId: wA, query: 'zoe', archived: true, }) expect(archived.rows.map((r) => r.id)).toEqual([id]) expect(await setClientArchived(asA, id, false)).toEqual({ revision: 3 }) }) it('pages 25 by 25 in name order without gap or repeat', async () => { const c = await confirmedAccount('acc-page') const asC = await signedIn(c) const wC = (await fetchPersonalWorkspaceId(asC, c.id)) as string for (let i = 1; i <= 30; i++) { await createClientRecord(asC, { workspaceId: wC, requestId: randomUUID(), fields: person(`Client ${String(i).padStart(2, '0')}`), }) } const one = await searchClients(asC, { workspaceId: wC, query: '', archived: false, }) expect(one.rows).toHaveLength(25) expect(one.next).not.toBeNull() const two = await searchClients(asC, { workspaceId: wC, query: '', archived: false, after: one.next, }) expect(two.rows.map((r) => r.display_name)).toEqual([ 'Client 26', 'Client 27', 'Client 28', 'Client 29', 'Client 30', ]) expect(two.next).toBeNull() const ids = new Set([...one.rows, ...two.rows].map((r) => r.id)) expect(ids.size).toBe(30) }) it('lists the client animals and the archive preview from the real RPCs', async () => { const { id } = await createClientRecord(asA, { workspaceId: wA, requestId: randomUUID(), fields: person('Écurie du Lac', { kind: 'organization' }), }) const created = await asA.rpc('create_animal', { workspace_id: wA, create_request_id: randomUUID(), name: 'Éclair', species_id: 'equine', sex: 'male', client_id: id, relation_role: 'owner', }) expect(created.error).toBeNull() const page = await listClientAnimals(asA, id) expect(page.rows).toMatchObject([ { animal_name: 'Éclair', relation_role: 'owner', is_current: true }, ]) expect(page.next).toBeNull() expect(await fetchClientArchivePreview(asA, id)).toMatchObject({ count: 1, animals: [{ name: 'Éclair' }], }) const listed = await searchClients(asA, { workspaceId: wA, query: 'ecurie', archived: false, }) expect(listed.rows).toMatchObject([{ id, current_animal_count: 1 }]) }) it('gives B nothing of A, with the same not_found as an unknown id', async () => { const { id } = await createClientRecord(asA, { workspaceId: wA, requestId: randomUUID(), fields: person('Secret Client'), }) expect(await fetchClientRecord(asB, id)).toBeNull() expect( ( await searchClients(asB, { workspaceId: wA, query: '', archived: false, }) ).rows, ).toEqual([]) expect((await listClientAnimals(asB, id)).rows).toEqual([]) expect(await fetchClientArchivePreview(asB, id)).toEqual({ count: 0, animals: [], }) expect(await kindOf(setClientArchived(asB, id, true))).toBe('not_found') expect(await kindOf(setClientArchived(asB, randomUUID(), true))).toBe( 'not_found', ) expect( await kindOf( createClientRecord(asB, { workspaceId: wA, requestId: randomUUID(), fields: person('X'), }), ), ).toBe('not_found') }) it('reads no session as session_expired and an unreachable server as network', async () => { expect( await kindOf( searchClients(browserClient(), { workspaceId: wA, query: '', archived: false, }), ), ).toBe('session_expired') const offline = browserClient(async () => { throw new TypeError('fetch failed') }) expect( await kindOf( searchClients(offline, { workspaceId: wA, query: '', archived: false }), ), ).toBe('network') }) })