import { z } from 'zod' import type { FaunosteoClient } from './client' import type { Database } from './database.types' import { RevisionSchema } from './clients' import { failRecord, parseRecordAnswer, UUID_PATTERN } from './records' /** * Browser side of the relations between an animal and its clients (contract * §5.3, §8.3, §9.3). The animal page reads them with one select by animal id * (at most 200 by the cap), the client embedded through the composite foreign * key; voided relations are left out, as every V1-1 screen leaves them out. * Writes go through the four relation RPCs only. */ const RELATION_ROLES = ['owner', 'keeper', 'contact'] as const /** * `ended_at` tells a current relation from a former one; it is a technical * time, never shown as the end date (`ended_on` is). */ export const ANIMAL_RELATION_COLUMNS = 'id, relation_role, started_on, ended_on, ended_at, revision, client:clients!animal_client_relations_client_fk(id, kind, display_name, phone, email, archived_at)' const AnimalRelationSchema = z.object({ id: z.string().uuid(), relation_role: z.enum(RELATION_ROLES), started_on: z.string().nullable(), ended_on: z.string().nullable(), ended_at: z.string().nullable(), revision: z.number().int(), client: z.object({ id: z.string().uuid(), kind: z.enum(['person', 'organization']), display_name: z.string(), phone: z.string().nullable(), email: z.string().nullable(), archived_at: z.string().nullable(), }), }) export type AnimalRelationItem = z.infer /** The cap of relations per animal (contract §10), ended and voided included. */ const RELATIONS_PER_ANIMAL = 200 /** The animal's relations that existed (voided ones left out), in creation order. */ export async function fetchAnimalRelations( client: FaunosteoClient, animalId: string, ): Promise { if (!UUID_PATTERN.test(animalId)) return [] const { data, error, status } = await client .from('animal_client_relations') .select(ANIMAL_RELATION_COLUMNS) .eq('animal_id', animalId) .is('voided_at', null) .order('created_at') .order('id') .limit(RELATIONS_PER_ANIMAL) if (error) failRecord(error, status) return parseRecordAnswer(z.array(AnimalRelationSchema), data) } export interface CreateRelationInput { animalId: string clientId: string /** One per creation intent, sent again on a retry: the server answers the first relation. */ requestId: string relationRole: (typeof RELATION_ROLES)[number] /** YYYY-MM-DD when known, else null (never filled by default). */ startedOn: string | null } const CreatedSchema = z.object({ id: z.string().uuid(), revision: z.number().int(), }) /** A current relation between an active animal and an active client of one workspace. */ export async function createAnimalClientRelation( client: FaunosteoClient, input: CreateRelationInput, ): Promise<{ id: string; revision: number }> { const { data, error, status } = await client.rpc( 'create_animal_client_relation', { animal_id: input.animalId, client_id: input.clientId, create_request_id: input.requestId, relation_role: input.relationRole, started_on: input.startedOn ?? undefined, }, ) if (error) failRecord(error, status) return parseRecordAnswer(CreatedSchema, data) } export interface EndRelationInput { relationId: string expectedRevision: number /** The real end date when known; null records the end without one. */ endedOn: string | null } /** Ends a current relation: it stays as a former one, with its dates. */ export async function endAnimalClientRelation( client: FaunosteoClient, input: EndRelationInput, ): Promise<{ revision: number }> { const { data, error, status } = await client.rpc( 'end_animal_client_relation', { relation_id: input.relationId, expected_revision: input.expectedRevision, ended_on: input.endedOn ?? undefined, }, ) if (error) failRecord(error, status) return parseRecordAnswer(RevisionSchema, data) } type UpdateRelationArgs = Database['public']['Functions']['update_animal_client_relation']['Args'] export interface UpdateRelationDatesInput { relationId: string expectedRevision: number startedOn: string | null /** Only on an ended relation; the server refuses one on a current relation. */ endedOn: string | null } /** Corrects the dates; both are sent, an empty one is null (the RPC has no defaults). */ export async function updateAnimalClientRelation( client: FaunosteoClient, input: UpdateRelationDatesInput, ): Promise<{ revision: number }> { const args = { relation_id: input.relationId, expected_revision: input.expectedRevision, started_on: input.startedOn, ended_on: input.endedOn, } satisfies { [K in keyof UpdateRelationArgs]: UpdateRelationArgs[K] | null } const { data, error, status } = await client.rpc( 'update_animal_client_relation', args as UpdateRelationArgs, ) if (error) failRecord(error, status) return parseRecordAnswer(RevisionSchema, data) } /** Voids a relation entered by mistake (N4): kept, frozen and shown nowhere; never a deletion. */ export async function voidAnimalClientRelation( client: FaunosteoClient, input: { relationId: string; expectedRevision: number }, ): Promise<{ revision: number }> { const { data, error, status } = await client.rpc( 'void_animal_client_relation', { relation_id: input.relationId, expected_revision: input.expectedRevision, }, ) if (error) failRecord(error, status) return parseRecordAnswer(RevisionSchema, data) }