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.
This commit is contained in:
1 parent
e22357630f
commit
930499cd25
36 files changed
+5579
-113
No files matched your search
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* The age shown on an animal's page, for display only (contract §5.2): from
|
||||
* the full date when known, else « environ N ans » from the year. Nothing is
|
||||
* stored or sent.
|
||||
*/
|
||||
export interface AnimalAge {
|
||||
unit: 'year' | 'month'
|
||||
count: number
|
||||
/** From the year alone: the day is unknown. */
|
||||
about: boolean
|
||||
}
|
||||
|
||||
export function animalAge(
|
||||
birthYear: number | null,
|
||||
birthDate: string | null,
|
||||
today: string,
|
||||
): AnimalAge | null {
|
||||
const [ty, tm, td] = today.split('-').map(Number)
|
||||
if (birthDate) {
|
||||
const [by, bm, bd] = birthDate.split('-').map(Number)
|
||||
const months = (ty - by) * 12 + (tm - bm) - (td < bd ? 1 : 0)
|
||||
if (months < 0) return null
|
||||
return months >= 12
|
||||
? { unit: 'year', count: Math.floor(months / 12), about: false }
|
||||
: { unit: 'month', count: months, about: false }
|
||||
}
|
||||
if (birthYear === null || birthYear > ty) return null
|
||||
return { unit: 'year', count: ty - birthYear, about: true }
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
fetchSpeciesLabels,
|
||||
type RecordFailureKind,
|
||||
type SpeciesLabel,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
export type SpeciesState =
|
||||
| { status: 'idle' }
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; labels: SpeciesLabel[] }
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
interface SpeciesContextValue {
|
||||
state: SpeciesState
|
||||
/** Starts the read once; later calls change nothing. */
|
||||
request: () => void
|
||||
retry: () => void
|
||||
}
|
||||
|
||||
const SpeciesContext = createContext<SpeciesContextValue | null>(null)
|
||||
|
||||
/**
|
||||
* The active species (reference rows of contract §5.4), read once per
|
||||
* workspace and only when a page needs them: the list filter, the form and
|
||||
* the record pages share one answer. Mounted under RequireWorkspace, it
|
||||
* leaves with the workspace on a change of account.
|
||||
*/
|
||||
export function SpeciesProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<SpeciesState>({ status: 'idle' })
|
||||
// 0 until a page asks; each retry bumps it.
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (attempt === 0) return
|
||||
let live = true
|
||||
const client = getSupabaseClient()
|
||||
setState({ status: 'loading' })
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
fetchSpeciesLabels(client)
|
||||
.then((labels) => {
|
||||
if (live) setState({ status: 'ready', labels })
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (live)
|
||||
setState({ status: 'error', failure: classifyRecordError(error) })
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [attempt])
|
||||
|
||||
const request = useCallback(() => setAttempt((n) => (n === 0 ? 1 : n)), [])
|
||||
const retry = useCallback(() => setAttempt((n) => n + 1), [])
|
||||
const value = useMemo(
|
||||
() => ({ state, request, retry }),
|
||||
[state, request, retry],
|
||||
)
|
||||
return (
|
||||
<SpeciesContext.Provider value={value}>{children}</SpeciesContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/** The species labels of the workspace; the first page that asks starts the read. */
|
||||
export function useSpecies(): Omit<SpeciesContextValue, 'request'> {
|
||||
const context = useContext(SpeciesContext)
|
||||
if (!context) throw new Error('useSpecies needs a SpeciesProvider')
|
||||
const { request } = context
|
||||
useEffect(() => request(), [request])
|
||||
return { state: context.state, retry: context.retry }
|
||||
}
|
||||
|
||||
/** The species name in the locale, followed by the « Autre » detail when there is one. */
|
||||
export function speciesName(
|
||||
labels: readonly SpeciesLabel[],
|
||||
speciesId: string,
|
||||
detail: string | null,
|
||||
locale: Locale,
|
||||
): string {
|
||||
const label = labels.find((s) => s.id === speciesId)
|
||||
const name = label
|
||||
? pickLocaleLabel(label.name_fr, label.name_en, locale, speciesId)
|
||||
: speciesId
|
||||
return detail ? `${name} (${detail})` : name
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { useRef, useState, type FormEvent } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
createAnimalRecord,
|
||||
fetchAnimalRecord,
|
||||
updateAnimalRecord,
|
||||
type AnimalRecord,
|
||||
type AnimalRelationRole,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { generateUuid } from '@/lib/id'
|
||||
import { localDateIso } from '@/lib/dates'
|
||||
import {
|
||||
EMPTY_ANIMAL_VALUES,
|
||||
EMPTY_RELATION_VALUES,
|
||||
animalFieldErrors,
|
||||
animalFormValues,
|
||||
animalSchema,
|
||||
relationIssues,
|
||||
withBirthDate,
|
||||
type AnimalFieldErrors,
|
||||
type AnimalFormValues,
|
||||
type RelationFieldErrors,
|
||||
type RelationFormValues,
|
||||
} from './validation'
|
||||
|
||||
export interface PickedClient {
|
||||
id: string
|
||||
display_name: string
|
||||
}
|
||||
|
||||
export type AnimalFormTarget =
|
||||
| {
|
||||
mode: 'create'
|
||||
workspaceId: string
|
||||
/** The client the form opened from, pre-associated; the practitioner may remove it. */
|
||||
initialClient: PickedClient | null
|
||||
}
|
||||
| { mode: 'edit'; record: AnimalRecord }
|
||||
|
||||
export type AnimalFormPhase =
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'saving' }
|
||||
| { kind: 'failed'; failure: RecordFailureKind }
|
||||
|
||||
export interface AnimalSaved {
|
||||
animalId: string
|
||||
/** The client the new animal was linked to, if any. */
|
||||
linkedClientId: string | null
|
||||
}
|
||||
|
||||
const FIELDS = Object.keys(EMPTY_ANIMAL_VALUES) as (keyof AnimalFormValues)[]
|
||||
|
||||
function sameValues(a: AnimalFormValues, b: AnimalFormValues): boolean {
|
||||
return FIELDS.every((key) => a[key] === b[key])
|
||||
}
|
||||
|
||||
function sameRelation(a: RelationFormValues, b: RelationFormValues): boolean {
|
||||
return (
|
||||
a.client?.id === b.client?.id &&
|
||||
a.relation_role === b.relation_role &&
|
||||
a.started_on === b.started_on
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The animal form: typed values, the D-R7 schema, one save. A create keeps
|
||||
* one request id for the life of the form, and sends the animal with its
|
||||
* optional first client in one create_animal call, so a retry after a lost
|
||||
* answer returns the animal (and relation) already made. An update sends the
|
||||
* revision it was read at; on `conflict` the stored animal is shown beside
|
||||
* the typed values, which stay.
|
||||
*/
|
||||
export function useAnimalForm(
|
||||
target: AnimalFormTarget,
|
||||
activeSpeciesIds: readonly string[],
|
||||
onSaved: (saved: AnimalSaved) => void,
|
||||
) {
|
||||
const initial =
|
||||
target.mode === 'edit'
|
||||
? animalFormValues(target.record)
|
||||
: EMPTY_ANIMAL_VALUES
|
||||
const initialRelation: RelationFormValues =
|
||||
target.mode === 'create'
|
||||
? { ...EMPTY_RELATION_VALUES, client: target.initialClient }
|
||||
: EMPTY_RELATION_VALUES
|
||||
const [values, setValues] = useState<AnimalFormValues>(initial)
|
||||
const [baseline, setBaseline] = useState<AnimalFormValues>(initial)
|
||||
const [relation, setRelation] = useState(initialRelation)
|
||||
const [relationBaseline, setRelationBaseline] = useState(initialRelation)
|
||||
const [errors, setErrors] = useState<AnimalFieldErrors>({})
|
||||
const [relationErrors, setRelationErrors] = useState<RelationFieldErrors>({})
|
||||
const [errorRound, setErrorRound] = useState(0)
|
||||
const [phase, setPhase] = useState<AnimalFormPhase>({ kind: 'idle' })
|
||||
const [stored, setStored] = useState<AnimalRecord | null>(null)
|
||||
const [requestId] = useState(generateUuid)
|
||||
const revision = useRef(target.mode === 'edit' ? target.record.revision : 0)
|
||||
const inFlight = useRef(false)
|
||||
|
||||
const setField = (key: keyof AnimalFormValues) => (value: string) =>
|
||||
setValues((v) => ({ ...v, [key]: value }))
|
||||
const setBirthDate = (value: string) =>
|
||||
setValues((v) => withBirthDate(v, value))
|
||||
const chooseClient = (client: PickedClient | null) =>
|
||||
setRelation((r) => ({ ...r, client }))
|
||||
const setRelationRole = (role: AnimalRelationRole) =>
|
||||
setRelation((r) => ({ ...r, relation_role: role }))
|
||||
const setStartedOn = (value: string) =>
|
||||
setRelation((r) => ({ ...r, started_on: value }))
|
||||
|
||||
/** The species the form may send: on an edit, the stored one even if it left the active list. */
|
||||
const speciesIds =
|
||||
target.mode === 'edit' &&
|
||||
!activeSpeciesIds.includes(target.record.species_id)
|
||||
? [...activeSpeciesIds, target.record.species_id]
|
||||
: activeSpeciesIds
|
||||
|
||||
async function readStored(animalId: string) {
|
||||
const client = getSupabaseClient()
|
||||
const record = client
|
||||
? await fetchAnimalRecord(client, animalId).catch(() => null)
|
||||
: null
|
||||
if (record) {
|
||||
revision.current = record.revision
|
||||
setStored(record)
|
||||
}
|
||||
}
|
||||
|
||||
function validate() {
|
||||
const today = localDateIso()
|
||||
const parsed = animalSchema({ speciesIds, today }).safeParse(values)
|
||||
const linkIssues =
|
||||
target.mode === 'create' ? relationIssues(relation, today, false) : {}
|
||||
const fieldIssues = parsed.success ? {} : animalFieldErrors(parsed.error)
|
||||
setErrors(fieldIssues)
|
||||
setRelationErrors(linkIssues)
|
||||
if (!parsed.success || Object.keys(linkIssues).length > 0) {
|
||||
setErrorRound((n) => n + 1)
|
||||
return null
|
||||
}
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
async function save(fields: NonNullable<ReturnType<typeof validate>>) {
|
||||
const client = getSupabaseClient()
|
||||
if (!client) throw new TypeError('no backend')
|
||||
if (target.mode === 'edit') {
|
||||
revision.current = (
|
||||
await updateAnimalRecord(client, {
|
||||
animalId: target.record.id,
|
||||
expectedRevision: revision.current,
|
||||
fields,
|
||||
})
|
||||
).revision
|
||||
return { animalId: target.record.id, linkedClientId: null }
|
||||
}
|
||||
const linked = relation.client
|
||||
const created = await createAnimalRecord(client, {
|
||||
workspaceId: target.workspaceId,
|
||||
requestId,
|
||||
fields,
|
||||
relation: linked
|
||||
? {
|
||||
clientId: linked.id,
|
||||
relationRole: relation.relation_role as AnimalRelationRole,
|
||||
startedOn: relation.started_on || null,
|
||||
}
|
||||
: null,
|
||||
})
|
||||
return { animalId: created.id, linkedClientId: linked?.id ?? null }
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (inFlight.current) return
|
||||
const fields = validate()
|
||||
if (!fields) return
|
||||
inFlight.current = true
|
||||
setPhase({ kind: 'saving' })
|
||||
try {
|
||||
const saved = await save(fields)
|
||||
setBaseline(values)
|
||||
setRelationBaseline(relation)
|
||||
setPhase({ kind: 'idle' })
|
||||
onSaved(saved)
|
||||
} catch (error) {
|
||||
const failure = classifyRecordError(error)
|
||||
if (failure === 'conflict' && target.mode === 'edit')
|
||||
await readStored(target.record.id)
|
||||
setPhase({ kind: 'failed', failure })
|
||||
} finally {
|
||||
inFlight.current = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops the typed values for the stored ones after a conflict. */
|
||||
function takeStored() {
|
||||
if (!stored) return
|
||||
const next = animalFormValues(stored)
|
||||
setValues(next)
|
||||
setBaseline(next)
|
||||
setStored(null)
|
||||
setErrors({})
|
||||
setPhase({ kind: 'idle' })
|
||||
}
|
||||
|
||||
return {
|
||||
mode: target.mode,
|
||||
values,
|
||||
setField,
|
||||
setBirthDate,
|
||||
relation,
|
||||
chooseClient,
|
||||
setRelationRole,
|
||||
setStartedOn,
|
||||
errors,
|
||||
relationErrors,
|
||||
/** Changes after each refused submit, so the form can focus the first error. */
|
||||
errorRound,
|
||||
phase,
|
||||
/** The stored animal after a conflict, shown beside the typed values. */
|
||||
stored,
|
||||
takeStored,
|
||||
dirty:
|
||||
!sameValues(values, baseline) ||
|
||||
!sameRelation(relation, relationBaseline),
|
||||
submit,
|
||||
}
|
||||
}
|
||||
|
||||
export type AnimalForm = ReturnType<typeof useAnimalForm>
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
searchAnimals,
|
||||
type AnimalListItem,
|
||||
type NameCursor,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { SEARCH_DELAY_MS } from '@/clients/useClientList'
|
||||
|
||||
export type AnimalListState =
|
||||
| { status: 'loading' }
|
||||
| {
|
||||
status: 'ready'
|
||||
rows: AnimalListItem[]
|
||||
next: NameCursor | null
|
||||
moreFailure: RecordFailureKind | null
|
||||
}
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
/**
|
||||
* The animals of the workspace for a term, a species and the archived
|
||||
* toggle: the server searches (search_animals, POST), pages of 25 in name
|
||||
* order, « Afficher plus » appends the next page. An answer to an older
|
||||
* search is dropped.
|
||||
*/
|
||||
export function useAnimalList(workspaceId: string) {
|
||||
const [query, setQuery] = useState('')
|
||||
const [term, setTerm] = useState('')
|
||||
const [speciesId, setSpeciesId] = useState<string | null>(null)
|
||||
const [archived, setArchived] = useState(false)
|
||||
const [state, setState] = useState<AnimalListState>({ status: 'loading' })
|
||||
const [loadingMore, setLoadingMore] = useState(false)
|
||||
const [reload, setReload] = useState(0)
|
||||
const generation = useRef(0)
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setTerm(query.trim()), SEARCH_DELAY_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [query])
|
||||
|
||||
useEffect(() => {
|
||||
const current = ++generation.current
|
||||
const client = getSupabaseClient()
|
||||
setState({ status: 'loading' })
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
searchAnimals(client, { workspaceId, query: term, speciesId, archived })
|
||||
.then((page) => {
|
||||
if (current === generation.current)
|
||||
setState({
|
||||
status: 'ready',
|
||||
rows: page.rows,
|
||||
next: page.next,
|
||||
moreFailure: null,
|
||||
})
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (current === generation.current)
|
||||
setState({ status: 'error', failure: classifyRecordError(error) })
|
||||
})
|
||||
}, [workspaceId, term, speciesId, archived, reload])
|
||||
|
||||
const loadMore = useCallback(async () => {
|
||||
const client = getSupabaseClient()
|
||||
if (state.status !== 'ready' || !state.next || !client || loadingMore)
|
||||
return
|
||||
const current = generation.current
|
||||
setLoadingMore(true)
|
||||
try {
|
||||
const page = await searchAnimals(client, {
|
||||
workspaceId,
|
||||
query: term,
|
||||
speciesId,
|
||||
archived,
|
||||
after: state.next,
|
||||
})
|
||||
if (current === generation.current)
|
||||
setState({
|
||||
status: 'ready',
|
||||
rows: [...state.rows, ...page.rows],
|
||||
next: page.next,
|
||||
moreFailure: null,
|
||||
})
|
||||
} catch (error) {
|
||||
if (current === generation.current)
|
||||
setState({ ...state, moreFailure: classifyRecordError(error) })
|
||||
} finally {
|
||||
setLoadingMore(false)
|
||||
}
|
||||
}, [state, loadingMore, workspaceId, term, speciesId, archived])
|
||||
|
||||
return {
|
||||
query,
|
||||
setQuery,
|
||||
/** The term the shown rows answer (the typed one after the pause). */
|
||||
term,
|
||||
speciesId,
|
||||
setSpeciesId,
|
||||
archived,
|
||||
setArchived,
|
||||
state,
|
||||
loadingMore,
|
||||
loadMore,
|
||||
retry: () => setReload((n) => n + 1),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
fetchAnimalRecord,
|
||||
type AnimalRecord,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
|
||||
export type AnimalRecordState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; record: AnimalRecord }
|
||||
| { status: 'not_found' }
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
/** One animal by id; an unknown id and an id of another workspace are both not_found. */
|
||||
export function useAnimalRecord(animalId: string) {
|
||||
const [state, setState] = useState<AnimalRecordState>({ status: 'loading' })
|
||||
const [reload, setReload] = useState(0)
|
||||
const shownId = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
const client = getSupabaseClient()
|
||||
// A refresh of the same animal keeps it on screen until the new answer.
|
||||
if (shownId.current !== animalId) setState({ status: 'loading' })
|
||||
shownId.current = animalId
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
fetchAnimalRecord(client, animalId)
|
||||
.then((record) => {
|
||||
if (live)
|
||||
setState(
|
||||
record ? { status: 'ready', record } : { status: 'not_found' },
|
||||
)
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (live)
|
||||
setState({ status: 'error', failure: classifyRecordError(error) })
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [animalId, reload])
|
||||
|
||||
const refresh = useCallback(() => setReload((n) => n + 1), [])
|
||||
return { state, refresh }
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user