Files
faunosteo/packages/supabase/src/clients.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

284 lines
8.6 KiB
TypeScript

import { z } from 'zod'
import type { FaunosteoClient } from './client'
import type { Database, Enums, Tables } from './database.types'
import {
failRecord,
parseRecordAnswer,
RecordFailure,
UUID_PATTERN,
type RecordPage,
} from './records'
/**
* Browser side of the clients of a workspace (contract §5.1, §8.2, §9.3):
* one read by id under RLS with an explicit column list, the POST searches,
* the three write RPCs. Validation of what the user types lives in the app's
* form schemas (D-R7); the database rules decide. Every failure is a
* RecordFailure of a closed kind.
*/
export type ClientKind = Enums<'client_kind'>
export type AnimalRelationRole = Enums<'animal_relation_role'>
export type AnimalSex = Enums<'animal_sex'>
/** Columns the page reads; the derived keys and the request digest stay server-side. */
export const CLIENT_COLUMNS =
'id, kind, display_name, email, phone, address_line1, address_line2, postal_code, city, country, revision, archived_at, created_at, updated_at'
export type ClientRecord = Pick<
Tables<'clients'>,
| 'id'
| 'kind'
| 'display_name'
| 'email'
| 'phone'
| 'address_line1'
| 'address_line2'
| 'postal_code'
| 'city'
| 'country'
| 'revision'
| 'archived_at'
| 'created_at'
| 'updated_at'
>
/** The nine fields a client is created or replaced with; an absent value is null, never ''. */
export type ClientFields = Pick<
ClientRecord,
| 'kind'
| 'display_name'
| 'email'
| 'phone'
| 'address_line1'
| 'address_line2'
| 'postal_code'
| 'city'
| 'country'
>
/** Keyset position in name order: the last row's name_key and id. */
export interface NameCursor {
nameKey: string
id: string
}
const ClientListItemSchema = z.object({
id: z.string().uuid(),
kind: z.enum(['person', 'organization']),
display_name: z.string(),
city: z.string().nullable(),
phone: z.string().nullable(),
email: z.string().nullable(),
archived_at: z.string().nullable(),
name_key: z.string(),
current_animal_count: z.number().int(),
})
export type ClientListItem = z.infer<typeof ClientListItemSchema>
export interface ClientSearch {
workspaceId: string
/** Trimmed by the server; 0 to 100 characters. */
query: string
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_clients` (POST: the term stays out of the URL). */
export async function searchClients(
client: FaunosteoClient,
search: ClientSearch,
): Promise<RecordPage<ClientListItem, NameCursor>> {
const size = search.pageSize ?? 25
const { data, error, status } = await client.rpc('search_clients', {
workspace_id: search.workspaceId,
query: search.query,
archived: search.archived,
page_size: size + 1,
after_name_key: search.after?.nameKey,
after_id: search.after?.id,
})
if (error) failRecord(error, status)
const parsed = z.array(ClientListItemSchema).safeParse(data)
if (!parsed.success) throw new RecordFailure('unavailable', parsed.error)
const rows = parsed.data.slice(0, size)
const last = rows.at(-1)
return {
rows,
next:
parsed.data.length > size && last
? { nameKey: last.name_key, id: last.id }
: null,
}
}
/** The client, or null for an unknown id and for an id of another workspace alike. */
export async function fetchClientRecord(
client: FaunosteoClient,
clientId: string,
): Promise<ClientRecord | null> {
if (!UUID_PATTERN.test(clientId)) return null
const { data, error, status } = await client
.from('clients')
.select(CLIENT_COLUMNS)
.eq('id', clientId)
.maybeSingle()
if (error) failRecord(error, status)
return data
}
const CreatedSchema = z.object({
id: z.string().uuid(),
revision: z.number().int(),
})
/** The answer of every update, archive and relation write RPC. */
export const RevisionSchema = z.object({ revision: z.number().int() })
export interface CreateClientInput {
workspaceId: string
/** One per creation intent, sent again on a retry: the server answers the first client. */
requestId: string
fields: ClientFields
}
export async function createClientRecord(
client: FaunosteoClient,
input: CreateClientInput,
): Promise<{ id: string; revision: number }> {
const f = input.fields
const { data, error, status } = await client.rpc('create_client', {
workspace_id: input.workspaceId,
create_request_id: input.requestId,
kind: f.kind,
display_name: f.display_name,
email: f.email ?? undefined,
phone: f.phone ?? undefined,
address_line1: f.address_line1 ?? undefined,
address_line2: f.address_line2 ?? undefined,
postal_code: f.postal_code ?? undefined,
city: f.city ?? undefined,
country: f.country ?? undefined,
})
if (error) failRecord(error, status)
return parseRecordAnswer(CreatedSchema, data)
}
type UpdateClientArgs = Database['public']['Functions']['update_client']['Args']
export interface UpdateClientInput {
clientId: string
expectedRevision: number
fields: ClientFields
}
/** Replaces the nine fields at `expectedRevision`; a stale revision is `conflict`. */
export async function updateClientRecord(
client: FaunosteoClient,
input: UpdateClientInput,
): Promise<{ revision: number }> {
const f = input.fields
// The update RPC has no defaults: every field is sent, null included. The
// generator types SQL parameters as non-null, so the keys and value types
// are checked against it with null allowed, then handed over.
const args = {
client_id: input.clientId,
expected_revision: input.expectedRevision,
kind: f.kind,
display_name: f.display_name,
email: f.email,
phone: f.phone,
address_line1: f.address_line1,
address_line2: f.address_line2,
postal_code: f.postal_code,
city: f.city,
country: f.country,
} satisfies { [K in keyof UpdateClientArgs]: UpdateClientArgs[K] | null }
const { data, error, status } = await client.rpc(
'update_client',
args as UpdateClientArgs,
)
if (error) failRecord(error, status)
return parseRecordAnswer(RevisionSchema, data)
}
export async function setClientArchived(
client: FaunosteoClient,
clientId: string,
archived: boolean,
): Promise<{ revision: number }> {
const { data, error, status } = await client.rpc('set_client_archived', {
client_id: clientId,
archived,
})
if (error) failRecord(error, status)
return parseRecordAnswer(RevisionSchema, data)
}
const ArchivePreviewSchema = z.object({
count: z.number().int(),
animals: z.array(z.object({ id: z.string().uuid(), name: z.string() })),
})
export type ClientArchivePreview = z.infer<typeof ArchivePreviewSchema>
/** Active animals for which the client is the only current owner (first 10 by name). */
export async function fetchClientArchivePreview(
client: FaunosteoClient,
clientId: string,
): Promise<ClientArchivePreview> {
const { data, error, status } = await client.rpc('client_archive_preview', {
client_id: clientId,
})
if (error) failRecord(error, status)
return parseRecordAnswer(ArchivePreviewSchema, data)
}
const ClientAnimalSchema = z.object({
relation_id: z.string().uuid(),
relation_role: z.enum(['owner', 'keeper', 'contact']),
started_on: z.string().nullable(),
ended_on: z.string().nullable(),
is_current: z.boolean(),
animal_id: z.string().uuid(),
animal_name: z.string(),
species_id: z.string(),
species_detail: z.string().nullable(),
animal_archived_at: z.string().nullable(),
sort_key: z.string(),
})
/** A relation of the client with its animal: read-only view of V1-1.5. */
export type ClientAnimalItem = z.infer<typeof ClientAnimalSchema>
/** Keyset position of `list_client_animals`: the last row's sort_key and relation id. */
export interface RelationCursor {
sortKey: string
relationId: string
}
/** The client's relations, current first then former, each in animal name order. */
export async function listClientAnimals(
client: FaunosteoClient,
clientId: string,
options: { pageSize?: number; after?: RelationCursor | null } = {},
): Promise<RecordPage<ClientAnimalItem, RelationCursor>> {
const size = options.pageSize ?? 50
const { data, error, status } = await client.rpc('list_client_animals', {
client_id: clientId,
page_size: size + 1,
after_sort: options.after?.sortKey,
after_id: options.after?.relationId,
})
if (error) failRecord(error, status)
const rows = parseRecordAnswer(z.array(ClientAnimalSchema), data)
const page = rows.slice(0, size)
const last = page.at(-1)
return {
rows: page,
next:
rows.length > size && last
? { sortKey: last.sort_key, relationId: last.relation_id }
: null,
}
}