Files
faunosteo/packages/supabase/src/animals.ts
T
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

236 lines
7.0 KiB
TypeScript

import { z } from 'zod'
import type { FaunosteoClient } from './client'
import type { Database, Tables } from './database.types'
import {
RevisionSchema,
type AnimalRelationRole,
type NameCursor,
} from './clients'
import {
failRecord,
parseRecordAnswer,
UUID_PATTERN,
type RecordPage,
} from './records'
/**
* Browser side of the animals of a workspace (contract §5.2, §8.3, §9.3): one
* read by id under RLS with an explicit column list, the POST search, the
* three write RPCs. `create_animal` takes the optional initial relation in the
* same transaction, so an animal and its first client are never half made.
* The database rules decide; every failure is a RecordFailure of a closed kind.
*/
/** Columns the page reads; the derived keys and the request digest stay server-side. */
export const ANIMAL_COLUMNS =
'id, name, species_id, species_detail, sex, breed, birth_year, birth_date, revision, archived_at, created_at, updated_at'
export type AnimalRecord = Pick<
Tables<'animals'>,
| 'id'
| 'name'
| 'species_id'
| 'species_detail'
| 'sex'
| 'breed'
| 'birth_year'
| 'birth_date'
| 'revision'
| 'archived_at'
| 'created_at'
| 'updated_at'
>
/** The seven fields an animal is created or replaced with; an absent value is null, never ''. */
export type AnimalFields = Pick<
AnimalRecord,
| 'name'
| 'species_id'
| 'species_detail'
| 'sex'
| 'breed'
| 'birth_year'
| 'birth_date'
>
const AnimalListItemSchema = z.object({
id: z.string().uuid(),
name: z.string(),
species_id: z.string(),
species_detail: z.string().nullable(),
sex: z.enum(['male', 'female', 'unknown']),
breed: z.string().nullable(),
birth_year: z.number().int().nullable(),
archived_at: z.string().nullable(),
name_key: z.string(),
/** The first three current owners in name order, archived clients flagged. */
current_owners: z.array(
z.object({
client_id: z.string().uuid(),
display_name: z.string(),
archived: z.boolean(),
}),
),
current_owner_count: z.number().int(),
})
export type AnimalListItem = z.infer<typeof AnimalListItemSchema>
export interface AnimalSearch {
workspaceId: string
/** Trimmed by the server; 0 to 100 characters. */
query: string
/** A species id, or null for every species. */
speciesId: string | null
archived: boolean
/** 1 to 99; one more row is asked to know whether a next page exists. */
pageSize?: number
after?: NameCursor | null
}
/** One page of `search_animals` (POST: the term stays out of the URL). */
export async function searchAnimals(
client: FaunosteoClient,
search: AnimalSearch,
): Promise<RecordPage<AnimalListItem, NameCursor>> {
const size = search.pageSize ?? 25
const { data, error, status } = await client.rpc('search_animals', {
workspace_id: search.workspaceId,
query: search.query,
species_filter: search.speciesId ?? undefined,
archived: search.archived,
page_size: size + 1,
after_name_key: search.after?.nameKey,
after_id: search.after?.id,
})
if (error) failRecord(error, status)
const found = parseRecordAnswer(z.array(AnimalListItemSchema), data)
const rows = found.slice(0, size)
const last = rows.at(-1)
return {
rows,
next:
found.length > size && last
? { nameKey: last.name_key, id: last.id }
: null,
}
}
/** The animal, or null for an unknown id and for an id of another workspace alike. */
export async function fetchAnimalRecord(
client: FaunosteoClient,
animalId: string,
): Promise<AnimalRecord | null> {
if (!UUID_PATTERN.test(animalId)) return null
const { data, error, status } = await client
.from('animals')
.select(ANIMAL_COLUMNS)
.eq('id', animalId)
.maybeSingle()
if (error) failRecord(error, status)
return data
}
/** The client the animal is linked to at creation, with an explicit role. */
export interface InitialRelation {
clientId: string
relationRole: AnimalRelationRole
/** YYYY-MM-DD when known, else null (never filled by default). */
startedOn: string | null
}
export interface CreateAnimalInput {
workspaceId: string
/** One per creation intent, sent again on a retry: the server answers the first animal. */
requestId: string
fields: AnimalFields
relation: InitialRelation | null
}
const CreatedAnimalSchema = z.object({
id: z.string().uuid(),
revision: z.number().int(),
relation_id: z.string().uuid().nullable(),
})
/** Years and dates travel as text: the RPC parses them and answers invalid_input on a bad one. */
const yearText = (year: number | null) =>
year === null ? undefined : String(year)
export async function createAnimalRecord(
client: FaunosteoClient,
input: CreateAnimalInput,
): Promise<{ id: string; revision: number; relationId: string | null }> {
const f = input.fields
const r = input.relation
const { data, error, status } = await client.rpc('create_animal', {
workspace_id: input.workspaceId,
create_request_id: input.requestId,
name: f.name,
species_id: f.species_id,
sex: f.sex,
species_detail: f.species_detail ?? undefined,
breed: f.breed ?? undefined,
birth_year: yearText(f.birth_year),
birth_date: f.birth_date ?? undefined,
client_id: r?.clientId,
relation_role: r?.relationRole,
started_on: r?.startedOn ?? undefined,
})
if (error) failRecord(error, status)
const created = parseRecordAnswer(CreatedAnimalSchema, data)
return {
id: created.id,
revision: created.revision,
relationId: created.relation_id,
}
}
type UpdateAnimalArgs = Database['public']['Functions']['update_animal']['Args']
export interface UpdateAnimalInput {
animalId: string
expectedRevision: number
fields: AnimalFields
}
/** Replaces the seven fields at `expectedRevision`; a stale revision is `conflict`. */
export async function updateAnimalRecord(
client: FaunosteoClient,
input: UpdateAnimalInput,
): Promise<{ revision: number }> {
const f = input.fields
// The update RPC has no defaults: every field is sent, null included (see
// updateClientRecord for why the generated type is widened this way).
const args = {
animal_id: input.animalId,
expected_revision: input.expectedRevision,
name: f.name,
species_id: f.species_id,
sex: f.sex,
species_detail: f.species_detail,
breed: f.breed,
birth_year: f.birth_year === null ? null : String(f.birth_year),
birth_date: f.birth_date,
} satisfies { [K in keyof UpdateAnimalArgs]: UpdateAnimalArgs[K] | null }
const { data, error, status } = await client.rpc(
'update_animal',
args as UpdateAnimalArgs,
)
if (error) failRecord(error, status)
return parseRecordAnswer(RevisionSchema, data)
}
/** Archives or restores; the relations are kept either way (contract §7.1). */
export async function setAnimalArchived(
client: FaunosteoClient,
animalId: string,
archived: boolean,
): Promise<{ revision: number }> {
const { data, error, status } = await client.rpc('set_animal_archived', {
animal_id: animalId,
archived,
})
if (error) failRecord(error, status)
return parseRecordAnswer(RevisionSchema, data)
}