Files
faunosteo/apps/app/src/animals/validation.ts
T
bchanot 930499cd25 feat(app): animal screens, relation panels, animals on the client page
Routes /app/animals, new, :animalId, edit under one workspace gate; list with
species filter; form (D-R7, U3 birth, no default sex or role, optional first
client); page with current and former relations, end, dates, void; client page
links its animals, adds one pre-associated, links an existing one. Card now
passes aria-labelledby, which it silently dropped.
2026-10-26 17:11:28 +01:00

254 lines
8.1 KiB
TypeScript

import { z } from 'zod'
import {
ANIMAL_FIELD_LIMITS,
BIRTH_YEAR_MIN,
CONTROL_CHARACTERS,
RECORD_DATE_MIN,
codePointLength,
type AnimalFields,
type AnimalRecord,
type AnimalRelationRole,
type AnimalSex,
} from '@faunosteo/supabase'
/**
* The animal form (contract §5.2, §11.3; D-R7): bounds from field-limits,
* proven equal to the SQL CHECKs, so the form never sends what the database
* refuses. The birth keeps the precision given (D6b): a year alone stays a
* year, a full date carries its year again. « Not in the future » is the
* device's local date (`today`); the RPCs allow up to tomorrow UTC. Messages
* are i18n keys; `|n` carries the {max} placeholder.
*/
export const ANIMAL_SEXES: readonly AnimalSex[] = ['male', 'female', 'unknown']
export const RELATION_ROLES: readonly AnimalRelationRole[] = [
'owner',
'keeper',
'contact',
]
/** The species that asks for a detail (« Autre »). */
export const OTHER_SPECIES = 'other'
export interface AnimalFormValues {
name: string
species_id: string
species_detail: string
/** '' until the practitioner picks one: no default (N8). */
sex: AnimalSex | ''
breed: string
birth_year: string
birth_date: string
}
export const EMPTY_ANIMAL_VALUES: AnimalFormValues = {
name: '',
species_id: '',
species_detail: '',
sex: '',
breed: '',
birth_year: '',
birth_date: '',
}
/** The form's view of a stored animal: null fields become empty inputs. */
export function animalFormValues(record: AnimalRecord): AnimalFormValues {
return {
name: record.name,
species_id: record.species_id,
species_detail: record.species_detail ?? '',
sex: record.sex,
breed: record.breed ?? '',
birth_year: record.birth_year === null ? '' : String(record.birth_year),
birth_date: record.birth_date ?? '',
}
}
/**
* U3: a complete date fills the year (which the form then locks); clearing
* the date leaves the year as it was, editable again.
*/
export function withBirthDate(
values: AnimalFormValues,
birthDate: string,
): AnimalFormValues {
const year = /^\d{4}-\d{2}-\d{2}$/.test(birthDate)
? birthDate.slice(0, 4)
: values.birth_year
return { ...values, birth_date: birthDate, birth_year: year }
}
function isCalendarDate(value: string): boolean {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
if (!match) return false
const [y, m, d] = match.slice(1).map(Number)
const date = new Date(Date.UTC(y, m - 1, d))
return (
date.getUTCFullYear() === y &&
date.getUTCMonth() === m - 1 &&
date.getUTCDate() === d
)
}
/**
* The issue of an optional record date (birth, relation start or end), or
* null when it is fine: a real calendar date from 1900 to `today` (ISO text
* compares in date order).
*/
export function recordDateIssue(value: string, today: string): string | null {
if (value === '') return null
if (!isCalendarDate(value)) return 'animals.error.date_format'
if (value < RECORD_DATE_MIN || value > today)
return 'animals.error.date_range'
return null
}
/** Trimmed text of at most `max` code points without control characters. */
function textIssue(value: string, max: number): string | null {
if (codePointLength(value) > max) return `animals.error.too_long|${max}`
if (CONTROL_CHARACTERS.test(value)) return 'animals.error.characters'
return null
}
export interface AnimalSchemaContext {
/** The species the form may send: the active ones, plus the stored one on an edit. */
speciesIds: readonly string[]
/** The device's local date, YYYY-MM-DD. */
today: string
}
type Issue = { path: keyof AnimalFormValues; message: string }
function identityIssues(v: AnimalFormValues, ctx: AnimalSchemaContext) {
const issues: Issue[] = []
const name = v.name.trim()
const nameIssue =
name === ''
? 'animals.error.required'
: textIssue(name, ANIMAL_FIELD_LIMITS.name)
if (nameIssue) issues.push({ path: 'name', message: nameIssue })
if (!ctx.speciesIds.includes(v.species_id))
issues.push({ path: 'species_id', message: 'animals.error.species' })
if (v.species_id === OTHER_SPECIES) {
const detail = v.species_detail.trim()
const detailIssue =
detail === ''
? 'animals.error.species_detail'
: textIssue(detail, ANIMAL_FIELD_LIMITS.speciesDetail)
if (detailIssue)
issues.push({ path: 'species_detail', message: detailIssue })
}
if (!ANIMAL_SEXES.includes(v.sex as AnimalSex))
issues.push({ path: 'sex', message: 'animals.error.sex' })
const breedIssue = textIssue(v.breed.trim(), ANIMAL_FIELD_LIMITS.breed)
if (breedIssue) issues.push({ path: 'breed', message: breedIssue })
return issues
}
function birthIssues(v: AnimalFormValues, today: string) {
const issues: Issue[] = []
if (v.birth_year !== '') {
if (!/^\d{4}$/.test(v.birth_year))
issues.push({ path: 'birth_year', message: 'animals.error.year_format' })
else if (
Number(v.birth_year) < BIRTH_YEAR_MIN ||
Number(v.birth_year) > Number(today.slice(0, 4))
)
issues.push({ path: 'birth_year', message: 'animals.error.year_range' })
}
const dateIssue = recordDateIssue(v.birth_date, today)
if (dateIssue) issues.push({ path: 'birth_date', message: dateIssue })
else if (v.birth_date !== '' && v.birth_date.slice(0, 4) !== v.birth_year)
issues.push({ path: 'birth_year', message: 'animals.error.date_year' })
return issues
}
const nullIfEmpty = (value: string) => (value === '' ? null : value)
/** Parses the typed values into the seven fields the RPCs take. */
export function animalSchema(ctx: AnimalSchemaContext) {
return z
.object({
name: z.string(),
species_id: z.string(),
species_detail: z.string(),
sex: z.string(),
breed: z.string(),
birth_year: z.string(),
birth_date: z.string(),
})
.superRefine((raw, zctx) => {
const v = raw as AnimalFormValues
for (const issue of [
...identityIssues(v, ctx),
...birthIssues(v, ctx.today),
])
zctx.addIssue({
code: 'custom',
path: [issue.path],
message: issue.message,
})
})
.transform(
(v): AnimalFields => ({
name: v.name.trim(),
species_id: v.species_id,
// Any other species refuses a detail: a hidden leftover is dropped, never sent.
species_detail:
v.species_id === OTHER_SPECIES ? v.species_detail.trim() : null,
sex: v.sex as AnimalSex,
breed: nullIfEmpty(v.breed.trim()),
birth_year: v.birth_year === '' ? null : Number(v.birth_year),
birth_date: nullIfEmpty(v.birth_date),
}),
)
}
/** The optional client of a new animal, or of a relation added from a page. */
export interface RelationFormValues {
client: { id: string; display_name: string } | null
/** '' until chosen: no role is preselected (owner decision 2026-10-26). */
relation_role: AnimalRelationRole | ''
started_on: string
}
export const EMPTY_RELATION_VALUES: RelationFormValues = {
client: null,
relation_role: '',
started_on: '',
}
export type RelationFieldErrors = Partial<
Record<'client' | 'relation_role' | 'started_on', string>
>
/** Errors of a relation choice; `requireClient` when the client is the point of the form. */
export function relationIssues(
values: RelationFormValues,
today: string,
requireClient: boolean,
): RelationFieldErrors {
const errors: RelationFieldErrors = {}
if (!values.client) {
if (requireClient) errors.client = 'animals.error.client'
return errors
}
if (!RELATION_ROLES.includes(values.relation_role as AnimalRelationRole))
errors.relation_role = 'animals.error.role'
const dateIssue = recordDateIssue(values.started_on, today)
if (dateIssue) errors.started_on = dateIssue
return errors
}
export type AnimalFieldErrors = Partial<Record<keyof AnimalFormValues, string>>
/** The first message of each field, in form order. */
export function animalFieldErrors(error: z.ZodError): AnimalFieldErrors {
const errors: AnimalFieldErrors = {}
for (const issue of error.issues) {
const key = issue.path[0] as keyof AnimalFormValues
errors[key] ??= issue.message
}
return errors
}