feat(supabase): workspaces and clients access layer with closed failures

fetchPersonalWorkspaceId, client search (keyset, one probe row), read by id
with explicit columns, create (request id), update (every field), archive,
client animals and archive preview, species labels; RecordFailure kinds of
contract §9.4 plus session_expired and network; RPC answers checked by Zod.
Unit tests and the same functions against real PostgREST on the sandbox.
This commit is contained in:
bchanot committed 2026-10-26 01:34:45 +01:00
1 parent 6251051618
commit a0e069959b
7 files changed
+1136

No files matched your search

+287
View File
@@ -0,0 +1,287 @@
import { z } from 'zod'
import type { FaunosteoClient } from './client'
import type { Database, Enums, Tables } from './database.types'
import {
failRecord,
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(),
})
const RevisionSchema = z.object({ revision: z.number().int() })
function parsed<T>(schema: z.ZodType<T>, data: unknown): T {
const result = schema.safeParse(data)
if (!result.success) throw new RecordFailure('unavailable', result.error)
return result.data
}
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 parsed(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 parsed(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 parsed(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 parsed(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 = parsed(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,
}
}
+44
View File
@@ -89,3 +89,47 @@ export type SheetVisibility = Enums<'sheet_visibility'>
export type SheetStatus = Enums<'sheet_status'>
/** draft | published | deprecated. */
export type SheetVersionStatus = Enums<'sheet_version_status'>
export {
RECORD_FAILURE_KINDS,
RecordFailure,
classifyRecordError,
type RecordFailureKind,
type RecordPage,
} from './records'
export { fetchPersonalWorkspaceId } from './workspaces'
export { fetchSpeciesLabels, type SpeciesLabel } from './species'
export {
CLIENT_COLUMNS,
createClientRecord,
fetchClientArchivePreview,
fetchClientRecord,
listClientAnimals,
searchClients,
setClientArchived,
updateClientRecord,
type AnimalRelationRole,
type AnimalSex,
type ClientAnimalItem,
type ClientArchivePreview,
type ClientFields,
type ClientKind,
type ClientListItem,
type ClientRecord,
type ClientSearch,
type CreateClientInput,
type NameCursor,
type RelationCursor,
type UpdateClientInput,
} from './clients'
export {
ANIMAL_FIELD_LIMITS,
BIRTH_YEAR_MIN,
CLIENT_FIELD_LIMITS,
CONTROL_CHARACTERS,
COUNTRY_CODE_PATTERN,
EMAIL_PATTERN,
PHONE_E164_PATTERN,
RECORD_DATE_MIN,
codePointLength,
isCleanText,
} from './field-limits'
+81
View File
@@ -0,0 +1,81 @@
/**
* Closed failure kinds of the V1-1 record reads and RPCs (clients, animals,
* relations): contract docs/development/V1-1_OWNERS_ANIMALS.md §9.4. The
* server answers closed codes, never values; this module folds them, the
* session and the network into one kind the UI phrases. A foreign id and an
* unknown one are the same `not_found`, as the server makes them.
*/
export const RECORD_FAILURE_KINDS = [
'not_found',
'archived',
'conflict',
'request_conflict',
'limit_reached',
'rate_limited',
'invalid_input',
'session_expired',
'network',
'unavailable',
] as const
export type RecordFailureKind = (typeof RECORD_FAILURE_KINDS)[number]
export class RecordFailure extends Error {
readonly kind: RecordFailureKind
constructor(kind: RecordFailureKind, cause?: unknown) {
super(`record: ${kind}`, { cause })
this.name = 'RecordFailure'
this.kind = kind
}
}
/** Messages the record RPCs raise with SQLSTATE P0001 (contract §9.4). */
const RPC_MESSAGE_KINDS: ReadonlySet<string> = new Set([
'archived',
'conflict',
'request_conflict',
'limit_reached',
'rate_limited',
'invalid_input',
])
interface PostgrestLikeError {
code?: string | null
message?: string
}
/**
* Folds a PostgREST answer into a closed kind. `status` is the HTTP status
* postgrest-js returns beside the error: 0 when the request never got an
* answer, 401 when the JWT is missing or expired (PGRST30x).
*/
export function classifyRecordError(
error: unknown,
status?: number,
): RecordFailureKind {
if (error instanceof RecordFailure) return error.kind
if (error instanceof TypeError) return 'network'
const e = (error ?? {}) as PostgrestLikeError
if (e.code === '42501' && e.message === 'not_found') return 'not_found'
if (e.code === 'P0001' && e.message && RPC_MESSAGE_KINDS.has(e.message)) {
return e.message as RecordFailureKind
}
if (status === 401 || e.code?.startsWith('PGRST30')) return 'session_expired'
if (status === 0) return 'network'
return 'unavailable'
}
/** Throws the closed failure of a PostgREST answer. */
export function failRecord(error: unknown, status?: number): never {
throw new RecordFailure(classifyRecordError(error, status), error)
}
/** Ids are uuids: anything else is answered as unknown without a request. */
export const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
/** One page of a keyset list; `next` is null on the last page. */
export interface RecordPage<Row, Cursor> {
rows: Row[]
next: Cursor | null
}
+17
View File
@@ -0,0 +1,17 @@
import type { FaunosteoClient } from './client'
import type { Tables } from './database.types'
import { failRecord } from './records'
export type SpeciesLabel = Pick<Tables<'species'>, 'id' | 'name_fr' | 'name_en'>
/** The active species with their names, in the reference order (RLS: active rows only). */
export async function fetchSpeciesLabels(
client: FaunosteoClient,
): Promise<SpeciesLabel[]> {
const { data, error, status } = await client
.from('species')
.select('id, name_fr, name_en')
.order('sort_order')
if (error) failRecord(error, status)
return data ?? []
}
+22
View File
@@ -0,0 +1,22 @@
import type { FaunosteoClient } from './client'
import { failRecord } from './records'
/**
* The signed-in account's personal workspace (contract §4, M1). It is
* created by the server in the sign-up transaction, never by the browser;
* RLS returns it only to its member with an active profile and a confirmed
* email, so null means "not readable now", not "create one". Its id is a
* context for the RPCs, which check the caller's rights again themselves.
*/
export async function fetchPersonalWorkspaceId(
client: FaunosteoClient,
userId: string,
): Promise<string | null> {
const { data, error, status } = await client
.from('workspaces')
.select('id')
.eq('personal_user_id', userId)
.maybeSingle()
if (error) failRecord(error, status)
return data?.id ?? null
}