Files
bchanot e22357630f feat(supabase): animals and relations access layer
animals.ts: POST search with species filter and a probe row, read by id with
explicit columns, create with the optional first client in one call, update,
archive. relations.ts: an animal's relations in one select (voided left out),
create, end, dates, void. Kinds duplicate_relation and already_ended added.
2026-10-26 17:11:23 +01:00

571 lines
16 KiB
TypeScript

/**
* The V1-1.6 access layer (src/animals.ts, src/relations.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
* embedded client of a relation, the keyset pages and every closed failure
* kind come from the real server, not from a stub. Fictitious data only.
*/
import { randomUUID } from 'node:crypto'
import { createClient } from '@supabase/supabase-js'
import {
RecordFailure,
createAnimalClientRelation,
createAnimalRecord,
createClientRecord,
endAnimalClientRelation,
fetchAnimalRecord,
fetchAnimalRelations,
fetchPersonalWorkspaceId,
listClientAnimals,
searchAnimals,
setAnimalArchived,
updateAnimalClientRelation,
updateAnimalRecord,
voidAnimalClientRelation,
type AnimalFields,
type Database,
type FaunosteoClient,
} from '../../src'
import { PASSWORD, confirmedAccount, stack, type Account } from './stack'
const BASE = 'http://sandbox.faunosteo.invalid'
function browserClient(): 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 fetch(url, init)
}
return createClient<Database>(BASE, stack.anonKey, {
auth: { persistSession: false, autoRefreshToken: false },
global: { fetch: mapped },
})
}
async function signedIn(account: Account): Promise<FaunosteoClient> {
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<unknown>) {
try {
await promise
return 'no failure'
} catch (error) {
return error instanceof RecordFailure ? error.kind : String(error)
}
}
const animal = (
name: string,
patch: Partial<AnimalFields> = {},
): AnimalFields => ({
name,
species_id: 'equine',
species_detail: null,
sex: 'unknown',
breed: null,
birth_year: null,
birth_date: null,
...patch,
})
describe('animals and relations access layer on the sandbox', () => {
let a: Account
let b: Account
let asA: FaunosteoClient
let asB: FaunosteoClient
let wA: string
let wB: string
async function clientOfA(name: string): Promise<string> {
const { id } = await createClientRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: {
kind: 'person',
display_name: name,
email: null,
phone: '+33612345678',
address_line1: null,
address_line2: null,
postal_code: null,
city: null,
country: null,
},
})
return id
}
async function animalOfA(name: string): Promise<string> {
return (
await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal(name),
relation: null,
})
).id
}
beforeAll(async () => {
a = await confirmedAccount('animals-a')
b = await confirmedAccount('animals-b')
asA = await signedIn(a)
asB = await signedIn(b)
wA = (await fetchPersonalWorkspaceId(asA, a.id)) as string
wB = (await fetchPersonalWorkspaceId(asB, b.id)) as string
})
it('creates without a relation and reads the explicit columns', async () => {
const fields = animal('Tornado Fictif', {
sex: 'male',
breed: 'Selle français',
birth_year: 2015,
birth_date: '2015-04-12',
})
const created = await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields,
relation: null,
})
expect(created).toMatchObject({ revision: 1, relationId: null })
const record = await fetchAnimalRecord(asA, created.id)
expect(Object.keys(record ?? {}).sort()).toEqual(
[
'archived_at',
'birth_date',
'birth_year',
'breed',
'created_at',
'id',
'name',
'revision',
'sex',
'species_detail',
'species_id',
'updated_at',
].sort(),
)
expect(record).toMatchObject({ ...fields, revision: 1, archived_at: null })
expect(await fetchAnimalRelations(asA, created.id)).toEqual([])
})
it('creates with an initial relation, replays idempotently, refuses a divergent replay', async () => {
const clientId = await clientOfA('Marie Initiale')
const requestId = randomUUID()
const input = {
workspaceId: wA,
requestId,
fields: animal('Furet Fictif', {
species_id: 'other',
species_detail: 'Furet',
}),
relation: {
clientId,
relationRole: 'owner' as const,
startedOn: '2020-01-02',
},
}
const first = await createAnimalRecord(asA, input)
expect(first.relationId).not.toBeNull()
expect(await createAnimalRecord(asA, input)).toEqual(first)
expect(
await kindOf(
createAnimalRecord(asA, {
...input,
fields: animal('Autre Nom', {
species_id: 'other',
species_detail: 'Furet',
}),
}),
),
).toBe('request_conflict')
const relations = await fetchAnimalRelations(asA, first.id)
expect(relations).toEqual([
{
id: first.relationId,
relation_role: 'owner',
started_on: '2020-01-02',
ended_on: null,
ended_at: null,
revision: 1,
client: {
id: clientId,
kind: 'person',
display_name: 'Marie Initiale',
phone: '+33612345678',
email: null,
archived_at: null,
},
},
])
const found = await searchAnimals(asA, {
workspaceId: wA,
query: 'furet fictif',
speciesId: null,
archived: false,
})
expect(found.rows).toHaveLength(1)
expect(found.rows[0]).toMatchObject({
id: first.id,
current_owner_count: 1,
current_owners: [
{
client_id: clientId,
display_name: 'Marie Initiale',
archived: false,
},
],
})
})
it('searches by term, species filter and archived toggle, in pages', async () => {
const c = await confirmedAccount('animals-page')
const asC = await signedIn(c)
const wC = (await fetchPersonalWorkspaceId(asC, c.id)) as string
for (let i = 1; i <= 12; i++) {
await createAnimalRecord(asC, {
workspaceId: wC,
requestId: randomUUID(),
fields: animal(`Cheval ${String(i).padStart(2, '0')}`),
relation: null,
})
}
const dog = await createAnimalRecord(asC, {
workspaceId: wC,
requestId: randomUUID(),
fields: animal('Chien Unique', { species_id: 'canine' }),
relation: null,
})
const one = await searchAnimals(asC, {
workspaceId: wC,
query: 'cheval',
speciesId: 'equine',
archived: false,
pageSize: 10,
})
expect(one.rows).toHaveLength(10)
expect(one.next).not.toBeNull()
const two = await searchAnimals(asC, {
workspaceId: wC,
query: 'cheval',
speciesId: 'equine',
archived: false,
pageSize: 10,
after: one.next,
})
expect(two.rows.map((r) => r.name)).toEqual(['Cheval 11', 'Cheval 12'])
expect(two.next).toBeNull()
const equines = await searchAnimals(asC, {
workspaceId: wC,
query: '',
speciesId: 'equine',
archived: false,
pageSize: 50,
})
expect(equines.rows.map((r) => r.id)).not.toContain(dog.id)
const canines = await searchAnimals(asC, {
workspaceId: wC,
query: '',
speciesId: 'canine',
archived: false,
})
expect(canines.rows.map((r) => r.id)).toEqual([dog.id])
expect(await setAnimalArchived(asC, dog.id, true)).toEqual({ revision: 2 })
const active = await searchAnimals(asC, {
workspaceId: wC,
query: 'chien',
speciesId: null,
archived: false,
})
expect(active.rows).toEqual([])
const archived = await searchAnimals(asC, {
workspaceId: wC,
query: 'chien',
speciesId: null,
archived: true,
})
expect(archived.rows.map((r) => r.id)).toEqual([dog.id])
})
it('nothing of A reaches B: reads empty, writes not_found', async () => {
const clientId = await clientOfA('Client Secret')
const created = await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal('Animal Secret'),
relation: { clientId, relationRole: 'owner', startedOn: null },
})
const relationId = created.relationId as string
expect(await fetchAnimalRecord(asB, created.id)).toBeNull()
expect(await fetchAnimalRecord(asA, randomUUID())).toBeNull()
expect(await fetchAnimalRelations(asB, created.id)).toEqual([])
const search = await searchAnimals(asB, {
workspaceId: wB,
query: 'secret',
speciesId: null,
archived: false,
})
expect(search.rows).toEqual([])
const bAnimal = await createAnimalRecord(asB, {
workspaceId: wB,
requestId: randomUUID(),
fields: animal('Animal de B'),
relation: null,
})
for (const write of [
() =>
updateAnimalRecord(asB, {
animalId: created.id,
expectedRevision: 1,
fields: animal('X'),
}),
() => setAnimalArchived(asB, created.id, true),
() =>
createAnimalClientRelation(asB, {
animalId: bAnimal.id,
clientId,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: null,
}),
() =>
endAnimalClientRelation(asB, {
relationId,
expectedRevision: 1,
endedOn: null,
}),
() =>
updateAnimalClientRelation(asB, {
relationId,
expectedRevision: 1,
startedOn: null,
endedOn: null,
}),
() => voidAnimalClientRelation(asB, { relationId, expectedRevision: 1 }),
() =>
createAnimalRecord(asB, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal('Intrus'),
relation: null,
}),
])
expect(await kindOf(write())).toBe('not_found')
expect(await fetchAnimalRelations(asA, created.id)).toHaveLength(1)
})
it('a relation: duplicate refused, end with and without date, already_ended, dates, conflict', async () => {
const animalId = await animalOfA('Relation Fictive')
const owner = await clientOfA('Propriétaire Fictif')
const keeper = await clientOfA('Détenteur Fictif')
const rel = await createAnimalClientRelation(asA, {
animalId,
clientId: owner,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: '2019-03-01',
})
expect(rel.revision).toBe(1)
expect(
await kindOf(
createAnimalClientRelation(asA, {
animalId,
clientId: owner,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: null,
}),
),
).toBe('duplicate_relation')
const keep = await createAnimalClientRelation(asA, {
animalId,
clientId: keeper,
requestId: randomUUID(),
relationRole: 'keeper',
startedOn: null,
})
expect(
await endAnimalClientRelation(asA, {
relationId: rel.id,
expectedRevision: 1,
endedOn: '2024-05-01',
}),
).toEqual({ revision: 2 })
expect(
await endAnimalClientRelation(asA, {
relationId: keep.id,
expectedRevision: 1,
endedOn: null,
}),
).toEqual({ revision: 2 })
expect(
await kindOf(
endAnimalClientRelation(asA, {
relationId: rel.id,
expectedRevision: 2,
endedOn: null,
}),
),
).toBe('already_ended')
const relations = await fetchAnimalRelations(asA, animalId)
const byId = new Map(relations.map((r) => [r.id, r]))
expect(byId.get(rel.id)).toMatchObject({
ended_on: '2024-05-01',
started_on: '2019-03-01',
})
expect(byId.get(rel.id)?.ended_at).not.toBeNull()
expect(byId.get(keep.id)).toMatchObject({ ended_on: null })
expect(byId.get(keep.id)?.ended_at).not.toBeNull()
expect(
await updateAnimalClientRelation(asA, {
relationId: rel.id,
expectedRevision: 2,
startedOn: null,
endedOn: '2024-06-01',
}),
).toEqual({ revision: 3 })
expect(
(await fetchAnimalRelations(asA, animalId)).find((r) => r.id === rel.id),
).toMatchObject({ started_on: null, ended_on: '2024-06-01', revision: 3 })
expect(
await kindOf(
updateAnimalClientRelation(asA, {
relationId: rel.id,
expectedRevision: 2,
startedOn: null,
endedOn: null,
}),
),
).toBe('conflict')
// A successive relation of the same triple once the first has ended.
expect(
(
await createAnimalClientRelation(asA, {
animalId,
clientId: owner,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: null,
})
).revision,
).toBe(1)
})
it('a voided relation leaves the relations, the current owners and the client animals', async () => {
const owner = await clientOfA('Erreur de Saisie')
const created = await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal('Annulation Fictive'),
relation: { clientId: owner, relationRole: 'owner', startedOn: null },
})
const relationId = created.relationId as string
expect((await listClientAnimals(asA, owner)).rows).toHaveLength(1)
expect(
await voidAnimalClientRelation(asA, { relationId, expectedRevision: 1 }),
).toEqual({ revision: 2 })
expect(await fetchAnimalRelations(asA, created.id)).toEqual([])
const search = await searchAnimals(asA, {
workspaceId: wA,
query: 'annulation fictive',
speciesId: null,
archived: false,
})
expect(search.rows[0]).toMatchObject({
current_owners: [],
current_owner_count: 0,
})
expect((await listClientAnimals(asA, owner)).rows).toEqual([])
// Voided is frozen: no end, no date change, no second void.
expect(
await kindOf(
endAnimalClientRelation(asA, {
relationId,
expectedRevision: 2,
endedOn: null,
}),
),
).toBe('invalid_input')
expect(
await kindOf(
voidAnimalClientRelation(asA, { relationId, expectedRevision: 2 }),
),
).toBe('invalid_input')
})
it('an archived animal refuses its edits and relation writes, then restores', async () => {
const clientId = await clientOfA('Client Archive')
const created = await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal('Archive Fictive'),
relation: { clientId, relationRole: 'keeper', startedOn: null },
})
const relationId = created.relationId as string
expect(await setAnimalArchived(asA, created.id, true)).toEqual({
revision: 2,
})
const other = await clientOfA('Autre Client')
for (const write of [
() =>
updateAnimalRecord(asA, {
animalId: created.id,
expectedRevision: 2,
fields: animal('Renommé'),
}),
() =>
createAnimalClientRelation(asA, {
animalId: created.id,
clientId: other,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: null,
}),
() =>
endAnimalClientRelation(asA, {
relationId,
expectedRevision: 1,
endedOn: null,
}),
() =>
updateAnimalClientRelation(asA, {
relationId,
expectedRevision: 1,
startedOn: '2020-01-01',
endedOn: null,
}),
() => voidAnimalClientRelation(asA, { relationId, expectedRevision: 1 }),
])
expect(await kindOf(write())).toBe('archived')
expect(await fetchAnimalRelations(asA, created.id)).toHaveLength(1)
expect(await setAnimalArchived(asA, created.id, false)).toEqual({
revision: 3,
})
expect(
await updateAnimalRecord(asA, {
animalId: created.id,
expectedRevision: 3,
fields: animal('Restaurée Fictive', { sex: 'female' }),
}),
).toEqual({ revision: 4 })
expect(
await kindOf(
updateAnimalRecord(asA, {
animalId: created.id,
expectedRevision: 3,
fields: animal('Périmée'),
}),
),
).toBe('conflict')
})
})