feat(app): clients list, page, create, edit, archive and restore
Routes /app/clients, /new, /:clientId, /:clientId/edit behind a workspace gate that remounts per workspace; debounced POST search, archived toggle and « Afficher plus » pages; form on field-limits (D-R7) with the phone entry rule and ISO countries; request id per creation intent; conflict shows the saved values; archive confirmation with the sole-owner preview; animals read-only; leave guard on in-app links; Clients entry after the dashboard.
This commit is contained in:
1 parent
ff028ec071
commit
b38e62770e
25 files changed
+2744
-5
No files matched your search
@@ -0,0 +1,40 @@
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
/**
|
||||
* ISO 3166-1 alpha-2 codes officially assigned (249), committed so the form
|
||||
* never depends on a network list; the names come from the browser's
|
||||
* Intl.DisplayNames in the UI language (contract §5).
|
||||
*/
|
||||
export const COUNTRY_CODES: readonly string[] = (
|
||||
'AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ ' +
|
||||
'BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ ' +
|
||||
'CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ ' +
|
||||
'DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR ' +
|
||||
'GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ' +
|
||||
'ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ ' +
|
||||
'LA LB LC LI LK LR LS LT LU LV LY ' +
|
||||
'MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ ' +
|
||||
'NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA ' +
|
||||
'RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ ' +
|
||||
'TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ ' +
|
||||
'VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW'
|
||||
).split(' ')
|
||||
|
||||
export interface CountryOption {
|
||||
code: string
|
||||
label: string
|
||||
}
|
||||
|
||||
/** Every code with its name in `locale`, sorted by name in that language. */
|
||||
export function countryOptions(locale: Locale): CountryOption[] {
|
||||
const names = new Intl.DisplayNames([locale], { type: 'region' })
|
||||
return COUNTRY_CODES.map((code) => ({
|
||||
code,
|
||||
label: names.of(code) ?? code,
|
||||
})).sort((a, b) => a.label.localeCompare(b.label, locale))
|
||||
}
|
||||
|
||||
/** The country's name in `locale`, or the code when the browser has none. */
|
||||
export function countryName(code: string, locale: Locale): string {
|
||||
return new Intl.DisplayNames([locale], { type: 'region' }).of(code) ?? code
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { useRef, useState, type FormEvent } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
createClientRecord,
|
||||
fetchClientRecord,
|
||||
updateClientRecord,
|
||||
type ClientRecord,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { generateUuid } from '@/lib/id'
|
||||
import {
|
||||
EMPTY_CLIENT_VALUES,
|
||||
clientFieldErrors,
|
||||
clientFormValues,
|
||||
clientSchema,
|
||||
normalizePhoneEntry,
|
||||
type ClientFieldErrors,
|
||||
type ClientFormValues,
|
||||
} from './validation'
|
||||
|
||||
export type ClientFormTarget =
|
||||
| { mode: 'create'; workspaceId: string }
|
||||
| { mode: 'edit'; record: ClientRecord }
|
||||
|
||||
export type ClientFormPhase =
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'saving' }
|
||||
| { kind: 'failed'; failure: RecordFailureKind }
|
||||
|
||||
const FIELDS = Object.keys(EMPTY_CLIENT_VALUES) as (keyof ClientFormValues)[]
|
||||
|
||||
function sameValues(a: ClientFormValues, b: ClientFormValues): boolean {
|
||||
return FIELDS.every((key) => a[key] === b[key])
|
||||
}
|
||||
|
||||
/**
|
||||
* The client form: typed values, the D-R7 schema, one save. A create keeps
|
||||
* one request id for the life of the form, so a retry after a lost answer
|
||||
* returns the client already made instead of a second one. An update sends
|
||||
* the revision it was read at; on `conflict` the stored client is read again
|
||||
* and shown beside the typed values, which stay, and the next save applies
|
||||
* them over it knowingly.
|
||||
*/
|
||||
export function useClientForm(
|
||||
target: ClientFormTarget,
|
||||
onSaved: (clientId: string) => void,
|
||||
) {
|
||||
const initial =
|
||||
target.mode === 'edit'
|
||||
? clientFormValues(target.record)
|
||||
: EMPTY_CLIENT_VALUES
|
||||
const [values, setValues] = useState<ClientFormValues>(initial)
|
||||
const [baseline, setBaseline] = useState<ClientFormValues>(initial)
|
||||
const [errors, setErrors] = useState<ClientFieldErrors>({})
|
||||
const [errorRound, setErrorRound] = useState(0)
|
||||
const [phase, setPhase] = useState<ClientFormPhase>({ kind: 'idle' })
|
||||
const [stored, setStored] = useState<ClientRecord | null>(null)
|
||||
const [requestId] = useState(generateUuid)
|
||||
const revision = useRef(target.mode === 'edit' ? target.record.revision : 0)
|
||||
const inFlight = useRef(false)
|
||||
|
||||
const setField = (key: keyof ClientFormValues) => (value: string) =>
|
||||
setValues((v) => ({ ...v, [key]: value }))
|
||||
|
||||
/** Shows the converted phone as soon as the field is left (contract §11.3). */
|
||||
function convertPhone() {
|
||||
const phone = normalizePhoneEntry(values.phone, values.country)
|
||||
if (phone.ok && phone.value && phone.value !== values.phone)
|
||||
setValues((v) => ({ ...v, phone: phone.value as string }))
|
||||
}
|
||||
|
||||
async function readStored(clientId: string) {
|
||||
const client = getSupabaseClient()
|
||||
const record = client
|
||||
? await fetchClientRecord(client, clientId).catch(() => null)
|
||||
: null
|
||||
if (record) {
|
||||
revision.current = record.revision
|
||||
setStored(record)
|
||||
}
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (inFlight.current) return
|
||||
const parsed = clientSchema.safeParse(values)
|
||||
if (!parsed.success) {
|
||||
setErrors(clientFieldErrors(parsed.error))
|
||||
setErrorRound((n) => n + 1)
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
const sent = { ...values, phone: parsed.data.phone ?? '' }
|
||||
setValues(sent)
|
||||
const client = getSupabaseClient()
|
||||
if (!client) {
|
||||
setPhase({ kind: 'failed', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
inFlight.current = true
|
||||
setPhase({ kind: 'saving' })
|
||||
try {
|
||||
let clientId: string
|
||||
if (target.mode === 'create') {
|
||||
clientId = (
|
||||
await createClientRecord(client, {
|
||||
workspaceId: target.workspaceId,
|
||||
requestId,
|
||||
fields: parsed.data,
|
||||
})
|
||||
).id
|
||||
} else {
|
||||
clientId = target.record.id
|
||||
revision.current = (
|
||||
await updateClientRecord(client, {
|
||||
clientId,
|
||||
expectedRevision: revision.current,
|
||||
fields: parsed.data,
|
||||
})
|
||||
).revision
|
||||
}
|
||||
setBaseline(sent)
|
||||
setPhase({ kind: 'idle' })
|
||||
onSaved(clientId)
|
||||
} 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 = clientFormValues(stored)
|
||||
setValues(next)
|
||||
setBaseline(next)
|
||||
setStored(null)
|
||||
setErrors({})
|
||||
setPhase({ kind: 'idle' })
|
||||
}
|
||||
|
||||
return {
|
||||
values,
|
||||
setField,
|
||||
convertPhone,
|
||||
errors,
|
||||
/** Changes after each refused submit, so the form can focus the first error. */
|
||||
errorRound,
|
||||
phase,
|
||||
/** The stored client after a conflict, shown beside the typed values. */
|
||||
stored,
|
||||
takeStored,
|
||||
dirty: !sameValues(values, baseline),
|
||||
submit,
|
||||
}
|
||||
}
|
||||
|
||||
export type ClientForm = ReturnType<typeof useClientForm>
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
searchClients,
|
||||
type ClientListItem,
|
||||
type NameCursor,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
|
||||
/** Time without typing before the term is sent: one search per pause, not per key. */
|
||||
export const SEARCH_DELAY_MS = 300
|
||||
|
||||
export type ClientListState =
|
||||
| { status: 'loading' }
|
||||
| {
|
||||
status: 'ready'
|
||||
rows: ClientListItem[]
|
||||
next: NameCursor | null
|
||||
moreFailure: RecordFailureKind | null
|
||||
}
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
/**
|
||||
* The clients of the workspace for a term and the archived toggle: the
|
||||
* server searches (search_clients, POST), pages of 25 in name order, « Afficher
|
||||
* plus » appends the next page. An answer to an older term is dropped.
|
||||
*/
|
||||
export function useClientList(workspaceId: string) {
|
||||
const [query, setQuery] = useState('')
|
||||
const [term, setTerm] = useState('')
|
||||
const [archived, setArchived] = useState(false)
|
||||
const [state, setState] = useState<ClientListState>({ 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
|
||||
}
|
||||
searchClients(client, { workspaceId, query: term, 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, 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 searchClients(client, {
|
||||
workspaceId,
|
||||
query: term,
|
||||
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, archived])
|
||||
|
||||
return {
|
||||
query,
|
||||
setQuery,
|
||||
/** The term the shown rows answer (the typed one after the pause). */
|
||||
term,
|
||||
archived,
|
||||
setArchived,
|
||||
state,
|
||||
loadingMore,
|
||||
loadMore,
|
||||
retry: () => setReload((n) => n + 1),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
fetchClientRecord,
|
||||
type ClientRecord,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
|
||||
export type ClientRecordState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; record: ClientRecord }
|
||||
| { status: 'not_found' }
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
/** One client by id; an unknown id and an id of another workspace are both not_found. */
|
||||
export function useClientRecord(clientId: string) {
|
||||
const [state, setState] = useState<ClientRecordState>({ 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 client keeps it on screen until the new answer.
|
||||
if (shownId.current !== clientId) setState({ status: 'loading' })
|
||||
shownId.current = clientId
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
fetchClientRecord(client, clientId)
|
||||
.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
|
||||
}
|
||||
}, [clientId, reload])
|
||||
|
||||
const refresh = useCallback(() => setReload((n) => n + 1), [])
|
||||
return { state, refresh }
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
CLIENT_FIELD_LIMITS,
|
||||
CONTROL_CHARACTERS,
|
||||
EMAIL_PATTERN,
|
||||
PHONE_E164_PATTERN,
|
||||
codePointLength,
|
||||
type ClientFields,
|
||||
type ClientRecord,
|
||||
} from '@faunosteo/supabase'
|
||||
import { COUNTRY_CODES } from './countries'
|
||||
|
||||
/**
|
||||
* The client form (contract §5, §5.1, §11.3; D-R7): the bounds and patterns
|
||||
* come from field-limits, proven equal to the SQL CHECKs, so the form never
|
||||
* sends what the database refuses. Messages are i18n keys; `|n` carries the
|
||||
* {max} placeholder. Lengths count code points, like char_length.
|
||||
*/
|
||||
|
||||
export interface ClientFormValues {
|
||||
kind: 'person' | 'organization'
|
||||
display_name: string
|
||||
email: string
|
||||
phone: string
|
||||
address_line1: string
|
||||
address_line2: string
|
||||
postal_code: string
|
||||
city: string
|
||||
country: string
|
||||
}
|
||||
|
||||
export const EMPTY_CLIENT_VALUES: ClientFormValues = {
|
||||
kind: 'person',
|
||||
display_name: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
address_line1: '',
|
||||
address_line2: '',
|
||||
postal_code: '',
|
||||
city: '',
|
||||
country: '',
|
||||
}
|
||||
|
||||
/** The form's view of a stored client: null fields become empty inputs. */
|
||||
export function clientFormValues(record: ClientRecord): ClientFormValues {
|
||||
return {
|
||||
kind: record.kind,
|
||||
display_name: record.display_name,
|
||||
email: record.email ?? '',
|
||||
phone: record.phone ?? '',
|
||||
address_line1: record.address_line1 ?? '',
|
||||
address_line2: record.address_line2 ?? '',
|
||||
postal_code: record.postal_code ?? '',
|
||||
city: record.city ?? '',
|
||||
country: record.country ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
/** Without separators: spaces, dots, hyphens, parentheses. */
|
||||
function compactPhone(raw: string): string {
|
||||
return raw.replace(/[\s.\-()]/g, '')
|
||||
}
|
||||
|
||||
export type PhoneEntry =
|
||||
| { ok: true; value: string | null }
|
||||
| { ok: false; error: string }
|
||||
|
||||
/**
|
||||
* The phone entry rule of contract §11.3: an international number (+32…) is
|
||||
* kept as typed; a French national number (06 12 34 56 78) becomes +33… only
|
||||
* when the country is empty or France; with another country a national
|
||||
* number is refused and asks for the country code.
|
||||
*/
|
||||
export function normalizePhoneEntry(raw: string, country: string): PhoneEntry {
|
||||
const compact = compactPhone(raw)
|
||||
if (compact === '') return { ok: true, value: null }
|
||||
if (compact.startsWith('+')) {
|
||||
return PHONE_E164_PATTERN.test(compact)
|
||||
? { ok: true, value: compact }
|
||||
: { ok: false, error: 'clients.error.phone_format' }
|
||||
}
|
||||
const frenchContext = country === '' || country === 'FR'
|
||||
if (frenchContext && /^0[1-9][0-9]{8}$/.test(compact)) {
|
||||
return { ok: true, value: `+33${compact.slice(1)}` }
|
||||
}
|
||||
return frenchContext
|
||||
? { ok: false, error: 'clients.error.phone_format' }
|
||||
: { ok: false, error: 'clients.error.phone_country_code' }
|
||||
}
|
||||
|
||||
/** Trimmed text of at most `max` code points without control characters; '' → null. */
|
||||
function optionalText(max: number) {
|
||||
return z
|
||||
.string()
|
||||
.trim()
|
||||
.superRefine((value, ctx) => {
|
||||
if (codePointLength(value) > max)
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
message: `clients.error.too_long|${max}`,
|
||||
})
|
||||
else if (CONTROL_CHARACTERS.test(value))
|
||||
ctx.addIssue({ code: 'custom', message: 'clients.error.characters' })
|
||||
})
|
||||
.transform((value) => (value === '' ? null : value))
|
||||
}
|
||||
|
||||
const displayName = z
|
||||
.string()
|
||||
.trim()
|
||||
.superRefine((value, ctx) => {
|
||||
if (value === '')
|
||||
ctx.addIssue({ code: 'custom', message: 'clients.error.required' })
|
||||
else if (codePointLength(value) > CLIENT_FIELD_LIMITS.displayName)
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
message: `clients.error.too_long|${CLIENT_FIELD_LIMITS.displayName}`,
|
||||
})
|
||||
else if (CONTROL_CHARACTERS.test(value))
|
||||
ctx.addIssue({ code: 'custom', message: 'clients.error.characters' })
|
||||
})
|
||||
|
||||
const email = z
|
||||
.string()
|
||||
.trim()
|
||||
.transform((value) => value.toLowerCase())
|
||||
.superRefine((value, ctx) => {
|
||||
if (value === '') return
|
||||
if (codePointLength(value) > CLIENT_FIELD_LIMITS.email)
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
message: `clients.error.too_long|${CLIENT_FIELD_LIMITS.email}`,
|
||||
})
|
||||
else if (CONTROL_CHARACTERS.test(value) || !EMAIL_PATTERN.test(value))
|
||||
ctx.addIssue({ code: 'custom', message: 'clients.error.email_format' })
|
||||
})
|
||||
.transform((value) => (value === '' ? null : value))
|
||||
|
||||
/** Parses the typed values into the nine fields the RPCs take. */
|
||||
export const clientSchema = z
|
||||
.object({
|
||||
kind: z.enum(['person', 'organization']),
|
||||
display_name: displayName,
|
||||
email,
|
||||
phone: z.string(),
|
||||
address_line1: optionalText(CLIENT_FIELD_LIMITS.addressLine),
|
||||
address_line2: optionalText(CLIENT_FIELD_LIMITS.addressLine),
|
||||
postal_code: optionalText(CLIENT_FIELD_LIMITS.postalCode),
|
||||
city: optionalText(CLIENT_FIELD_LIMITS.city),
|
||||
country: z
|
||||
.string()
|
||||
.refine(
|
||||
(value) => value === '' || COUNTRY_CODES.includes(value),
|
||||
'clients.error.country',
|
||||
)
|
||||
.transform((value) => (value === '' ? null : value)),
|
||||
})
|
||||
// A refinement runs even when another field failed, so every error shows at once.
|
||||
.superRefine((values, ctx) => {
|
||||
const phone = normalizePhoneEntry(values.phone, values.country ?? '')
|
||||
if (!phone.ok)
|
||||
ctx.addIssue({ code: 'custom', path: ['phone'], message: phone.error })
|
||||
})
|
||||
.transform((values): ClientFields => {
|
||||
const phone = normalizePhoneEntry(values.phone, values.country ?? '')
|
||||
return { ...values, phone: phone.ok ? phone.value : null }
|
||||
})
|
||||
|
||||
export type ClientFieldErrors = Partial<Record<keyof ClientFormValues, string>>
|
||||
|
||||
/** The first message of each field, in form order. */
|
||||
export function clientFieldErrors(error: z.ZodError): ClientFieldErrors {
|
||||
const errors: ClientFieldErrors = {}
|
||||
for (const issue of error.issues) {
|
||||
const key = issue.path[0] as keyof ClientFormValues
|
||||
errors[key] ??= issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
Reference in new issue
Block a user