feat(app): administration screens and anatomical catalogue (V1-2.5 G, H, I)
Administration page (board 10), species, rights, official sheets list with filters, creation from the core's empty document, overview with the working-copy action; catalogue list (search by sheet name), sheet and version pages through PreviewSheet with zoom and pan. App 650, typecheck, lint, build green.
This commit is contained in:
1 parent
9f7824dc08
commit
0176b3184d
42 files changed
+6438
-39
No files matched your search
@@ -0,0 +1,46 @@
|
||||
import type { OfficialSheetAdminSummary } from '@faunosteo/supabase'
|
||||
|
||||
export interface SheetFilters {
|
||||
species: string
|
||||
sheetStatus: string
|
||||
versionStatus: string
|
||||
roundStatus: string
|
||||
}
|
||||
|
||||
export const NO_FILTER: SheetFilters = {
|
||||
species: '',
|
||||
sheetStatus: '',
|
||||
versionStatus: '',
|
||||
roundStatus: '',
|
||||
}
|
||||
export const SHEET_STATUSES = ['active', 'archived'] as const
|
||||
export const VERSION_STATUSES = ['draft', 'published', 'deprecated'] as const
|
||||
export const ROUND_STATUSES = [
|
||||
'verifying',
|
||||
'open',
|
||||
'approved',
|
||||
'changes_requested',
|
||||
'withdrawn',
|
||||
'verification_failed',
|
||||
] as const
|
||||
|
||||
/**
|
||||
* The filters of §11.1, over the loaded list: a version status matches a sheet
|
||||
* holding a version in it, a round status matches its latest round.
|
||||
*/
|
||||
export function filterSheets(
|
||||
sheets: readonly OfficialSheetAdminSummary[],
|
||||
filters: SheetFilters,
|
||||
): OfficialSheetAdminSummary[] {
|
||||
return sheets.filter(
|
||||
(sheet) =>
|
||||
(!filters.species || sheet.species_id === filters.species) &&
|
||||
(!filters.sheetStatus || sheet.status === filters.sheetStatus) &&
|
||||
(!filters.versionStatus ||
|
||||
sheet.version_statuses.some(
|
||||
(status) => status === filters.versionStatus,
|
||||
)) &&
|
||||
(!filters.roundStatus ||
|
||||
sheet.latest_round?.status === filters.roundStatus),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import type {
|
||||
CatalogSpecies,
|
||||
SheetAdminPerson,
|
||||
SheetAdminRound,
|
||||
SheetFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
type Translate = (key: string) => string
|
||||
|
||||
/**
|
||||
* The failure kinds the administration screens can meet (the RPCs they call,
|
||||
* their helpers and the shared session kinds), each with an
|
||||
* `admin.failure.<kind>` message. Any other kind cannot come from these
|
||||
* calls; it reads as the generic `unavailable`, never as a raw code.
|
||||
*/
|
||||
const ADMIN_FAILURE_KINDS: ReadonlySet<SheetFailureKind> =
|
||||
new Set<SheetFailureKind>([
|
||||
'authentication_required',
|
||||
'mfa_required',
|
||||
'forbidden',
|
||||
'rights.account',
|
||||
'rights.capability',
|
||||
'rights.mfa',
|
||||
'rights.owner',
|
||||
'not_found',
|
||||
'grant.active',
|
||||
'grant.ineligible',
|
||||
'grant.revoked',
|
||||
'grant.target_invalid',
|
||||
'document.shape',
|
||||
'document.schema_version',
|
||||
'document.species',
|
||||
'document.too_large',
|
||||
'sheet.species_invalid',
|
||||
'sheet.slug_taken',
|
||||
'species.exists',
|
||||
'species.not_active',
|
||||
'species.not_inactive',
|
||||
'working_copy.source_invalid',
|
||||
'working_copy.exists',
|
||||
'working_copy.assets_missing',
|
||||
'invalid_input',
|
||||
'rate_limited',
|
||||
'conflict_retry',
|
||||
'session_expired',
|
||||
'network',
|
||||
'unavailable',
|
||||
])
|
||||
|
||||
export function failureMessage(t: Translate, kind: SheetFailureKind): string {
|
||||
return t(
|
||||
`admin.failure.${ADMIN_FAILURE_KINDS.has(kind) ? kind : 'unavailable'}`,
|
||||
)
|
||||
}
|
||||
|
||||
/** A sheet or species name in the interface language. */
|
||||
export function localized(
|
||||
name: { fr: string; en: string },
|
||||
locale: Locale,
|
||||
): string {
|
||||
return name[locale]
|
||||
}
|
||||
|
||||
export function speciesName(species: CatalogSpecies, locale: Locale): string {
|
||||
return locale === 'fr' ? species.name_fr : species.name_en
|
||||
}
|
||||
|
||||
/** The species' name when the list knows it, else its id (never an empty cell). */
|
||||
export function speciesLabel(
|
||||
id: string,
|
||||
species: readonly CatalogSpecies[],
|
||||
locale: Locale,
|
||||
): string {
|
||||
const row = species.find((s) => s.id === id)
|
||||
return row ? speciesName(row, locale) : id
|
||||
}
|
||||
|
||||
export function personName(
|
||||
t: Translate,
|
||||
person: SheetAdminPerson | null,
|
||||
): string {
|
||||
return person?.display_name || t('admin.person.unnamed')
|
||||
}
|
||||
|
||||
/** A server timestamp as a date in the interface language. */
|
||||
export function formatDay(iso: string, locale: Locale): string {
|
||||
return new Date(iso).toLocaleDateString(locale, {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The round's state (§3). A failed verification names its cause only when
|
||||
* the server recorded one (`failure_outcome`, BDR-095): the title of that
|
||||
* outcome and its ratified sentence; otherwise the generic status label.
|
||||
*/
|
||||
export function roundLabel(
|
||||
t: Translate,
|
||||
round: Pick<SheetAdminRound, 'status'> & {
|
||||
failure_outcome?: SheetAdminRound['failure_outcome']
|
||||
},
|
||||
): { title: string; cause: string | null } {
|
||||
if (round.status === 'verification_failed' && round.failure_outcome) {
|
||||
return {
|
||||
title: t(`admin.outcome.${round.failure_outcome}.title`),
|
||||
cause: t(`admin.outcome.${round.failure_outcome}.body`),
|
||||
}
|
||||
}
|
||||
return { title: t(`admin.round_status.${round.status}`), cause: null }
|
||||
}
|
||||
|
||||
export const ROUND_TONE = {
|
||||
verifying: 'neutral',
|
||||
open: 'accent',
|
||||
approved: 'accent',
|
||||
changes_requested: 'warn',
|
||||
withdrawn: 'neutral',
|
||||
verification_failed: 'danger',
|
||||
} as const
|
||||
|
||||
export const VERSION_TONE = {
|
||||
draft: 'neutral',
|
||||
published: 'accent',
|
||||
deprecated: 'warn',
|
||||
} as const
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { OwnCatalogGrant } from '@faunosteo/supabase'
|
||||
import { isGrantActive } from '@/auth/navigationHint'
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
|
||||
export type Capability = 'sheet_editor' | 'sheet_reviewer' | 'sheet_publisher'
|
||||
|
||||
/** In the order the administration page names them (board 10). */
|
||||
export const CAPABILITIES: readonly Capability[] = [
|
||||
'sheet_editor',
|
||||
'sheet_reviewer',
|
||||
'sheet_publisher',
|
||||
]
|
||||
|
||||
export interface AdminPermissions {
|
||||
/** The caller's active capabilities, in CAPABILITIES order. */
|
||||
capabilities: Capability[]
|
||||
editor: boolean
|
||||
owner: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Which administration entries and actions to show (contract §11.1, §5.4),
|
||||
* from the caller's own grant rows and platform roles. A display rule only,
|
||||
* like the navigation hint: every page and action acts on the server's
|
||||
* answer (capability, `aal2`, owner checks), never on this.
|
||||
*/
|
||||
export function adminPermissions(
|
||||
grants: readonly OwnCatalogGrant[],
|
||||
owner: boolean,
|
||||
now: number = Date.now(),
|
||||
): AdminPermissions {
|
||||
const active = new Set(
|
||||
grants
|
||||
.filter((grant) => isGrantActive(grant, now))
|
||||
.map((grant) => grant.kind),
|
||||
)
|
||||
const capabilities = CAPABILITIES.filter((kind) => active.has(kind))
|
||||
return { capabilities, editor: active.has('sheet_editor'), owner }
|
||||
}
|
||||
|
||||
export function useAdminPermissions(): AdminPermissions {
|
||||
const grants = useAuthStore((s) => s.catalogGrants)
|
||||
const owner = useAuthStore((s) => s.roles.includes('owner'))
|
||||
return adminPermissions(grants, owner)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
classifySheetError,
|
||||
type FaunosteoClient,
|
||||
type SheetFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
|
||||
export type AdminQueryState<T> =
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; data: T }
|
||||
| { status: 'error'; failure: SheetFailureKind }
|
||||
|
||||
/**
|
||||
* One administration read (M7, species, grants), keyed: a new key shows the
|
||||
* loading state, a refresh of the same key keeps the data on screen until the
|
||||
* new answer. Every refusal arrives as its closed kind; the page decides what
|
||||
* a `rights.*` or `not_found` answer shows.
|
||||
*/
|
||||
export function useAdminQuery<T>(
|
||||
key: string,
|
||||
load: (client: FaunosteoClient) => Promise<T>,
|
||||
) {
|
||||
const [state, setState] = useState<AdminQueryState<T>>({ status: 'loading' })
|
||||
const [reload, setReload] = useState(0)
|
||||
const shownKey = useRef<string | null>(null)
|
||||
// The latest loader, so an inline arrow does not restart the request.
|
||||
const loader = useRef(load)
|
||||
loader.current = load
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
const client = getSupabaseClient()
|
||||
if (shownKey.current !== key) setState({ status: 'loading' })
|
||||
shownKey.current = key
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
loader
|
||||
.current(client)
|
||||
.then((data) => {
|
||||
if (live) setState({ status: 'ready', data })
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (live)
|
||||
setState({ status: 'error', failure: classifySheetError(error) })
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [key, reload])
|
||||
|
||||
const refresh = useCallback(() => setReload((n) => n + 1), [])
|
||||
return { state, refresh }
|
||||
}
|
||||
|
||||
/** A refusal of the caller's rights: the page answers « Accès non autorisé ». */
|
||||
export function isRightsRefusal(kind: SheetFailureKind): boolean {
|
||||
return kind.startsWith('rights.')
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import { z } from 'zod'
|
||||
import { codePointLength } from '@faunosteo/supabase'
|
||||
import { localDateIso } from '@/lib/dates'
|
||||
|
||||
/**
|
||||
* The administration forms (contract §5.2, §7.2, §7.4). Bounds and patterns
|
||||
* are the SQL CHECKs and RPC guards, so a form never sends what the server
|
||||
* refuses; the server still decides. Messages are i18n keys; `|n` carries
|
||||
* the {max} placeholder. Lengths count code points, like char_length.
|
||||
*/
|
||||
|
||||
/** `species_id_format`, and `other` is never a catalogue species (create_species). */
|
||||
export const SPECIES_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
|
||||
/** `anatomical_sheets_slug_format`. */
|
||||
export const SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{1,79}$/
|
||||
const SPECIES_NAME_MAX = 80
|
||||
/** `anatomical_sheets_name_length`. */
|
||||
const SHEET_NAME_MAX = 120
|
||||
/** reason, verification note and revocation reason (grant_catalog_right, revoke_catalog_right). */
|
||||
export const GRANT_TEXT_MAX = 1000
|
||||
|
||||
export type FieldErrors<K extends string> = Partial<Record<K, string>>
|
||||
|
||||
function requiredText(max: number) {
|
||||
return z
|
||||
.string()
|
||||
.trim()
|
||||
.superRefine((value, ctx) => {
|
||||
if (value === '')
|
||||
ctx.addIssue({ code: 'custom', message: 'clients.error.required' })
|
||||
else if (codePointLength(value) > max)
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
message: `clients.error.too_long|${max}`,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** The first message of each field. */
|
||||
function fieldErrors<K extends string>(error: z.ZodError): FieldErrors<K> {
|
||||
const errors: FieldErrors<K> = {}
|
||||
for (const issue of error.issues) {
|
||||
const key = issue.path[0] as K
|
||||
errors[key] ??= issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
export type Parsed<T, K extends string> =
|
||||
| { ok: true; value: T }
|
||||
| { ok: false; errors: FieldErrors<K> }
|
||||
|
||||
function parse<T, K extends string>(
|
||||
schema: z.ZodType<T, z.ZodTypeDef, unknown>,
|
||||
values: unknown,
|
||||
): Parsed<T, K> {
|
||||
const result = schema.safeParse(values)
|
||||
return result.success
|
||||
? { ok: true, value: result.data }
|
||||
: { ok: false, errors: fieldErrors<K>(result.error) }
|
||||
}
|
||||
|
||||
// --- Species ----------------------------------------------------------------
|
||||
export interface SpeciesFormValues {
|
||||
id: string
|
||||
name_fr: string
|
||||
name_en: string
|
||||
sort_order: string
|
||||
}
|
||||
|
||||
const speciesSchema = z.object({
|
||||
id: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
(id) => SPECIES_ID_PATTERN.test(id) && id !== 'other',
|
||||
'admin.species.error.id',
|
||||
),
|
||||
name_fr: requiredText(SPECIES_NAME_MAX),
|
||||
name_en: requiredText(SPECIES_NAME_MAX),
|
||||
sort_order: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine((order) => /^[0-9]{1,4}$/.test(order), 'admin.species.error.order')
|
||||
.transform(Number),
|
||||
})
|
||||
|
||||
export type SpeciesFields = z.infer<typeof speciesSchema>
|
||||
|
||||
export function parseSpecies(
|
||||
values: SpeciesFormValues,
|
||||
): Parsed<SpeciesFields, keyof SpeciesFormValues> {
|
||||
return parse(speciesSchema, values)
|
||||
}
|
||||
|
||||
// --- Official sheet ---------------------------------------------------------
|
||||
export interface SheetFormValues {
|
||||
species_id: string
|
||||
name_fr: string
|
||||
name_en: string
|
||||
slug: string
|
||||
}
|
||||
|
||||
const sheetSchema = z.object({
|
||||
species_id: z
|
||||
.string()
|
||||
.refine(
|
||||
(id) => id !== '' && id !== 'other',
|
||||
'admin.sheet_form.error.species',
|
||||
),
|
||||
name_fr: requiredText(SHEET_NAME_MAX),
|
||||
name_en: requiredText(SHEET_NAME_MAX),
|
||||
slug: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine((slug) => SLUG_PATTERN.test(slug), 'admin.sheet_form.error.slug'),
|
||||
})
|
||||
|
||||
export type SheetFields = z.infer<typeof sheetSchema>
|
||||
|
||||
export function parseSheet(
|
||||
values: SheetFormValues,
|
||||
): Parsed<SheetFields, keyof SheetFormValues> {
|
||||
return parse(sheetSchema, values)
|
||||
}
|
||||
|
||||
/**
|
||||
* A slug proposed from a name: accents dropped, lower case, every other run
|
||||
* of characters a single hyphen, cut to the 80 characters of the CHECK. The
|
||||
* editor may change it; the CHECK is checked again on submit.
|
||||
*/
|
||||
export function proposeSlug(name: string): string {
|
||||
return name
|
||||
.normalize('NFD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+/, '')
|
||||
.slice(0, 80)
|
||||
.replace(/-+$/, '')
|
||||
}
|
||||
|
||||
// --- Rights -----------------------------------------------------------------
|
||||
export type GrantKind =
|
||||
| 'catalog_reader'
|
||||
| 'sheet_editor'
|
||||
| 'sheet_reviewer'
|
||||
| 'sheet_publisher'
|
||||
|
||||
export const GRANT_KINDS: readonly GrantKind[] = [
|
||||
'catalog_reader',
|
||||
'sheet_editor',
|
||||
'sheet_reviewer',
|
||||
'sheet_publisher',
|
||||
]
|
||||
|
||||
/** The three capabilities: a verification note is required for them. */
|
||||
const CAPABILITY_KINDS: readonly GrantKind[] = [
|
||||
'sheet_editor',
|
||||
'sheet_reviewer',
|
||||
'sheet_publisher',
|
||||
]
|
||||
|
||||
export interface GrantFormValues {
|
||||
kind: GrantKind | ''
|
||||
reason: string
|
||||
verification_note: string
|
||||
/** YYYY-MM-DD or ''. */
|
||||
expires_on: string
|
||||
}
|
||||
|
||||
export interface GrantFields {
|
||||
kind: GrantKind
|
||||
reason: string
|
||||
verification_note?: string
|
||||
/** The end of the chosen day, device time zone. */
|
||||
expires_at?: string
|
||||
}
|
||||
|
||||
/** The expiry is a day after today (device date): the server refuses a past one. */
|
||||
function grantSchema(today: string) {
|
||||
return z
|
||||
.object({
|
||||
kind: z
|
||||
.enum([
|
||||
'',
|
||||
'catalog_reader',
|
||||
'sheet_editor',
|
||||
'sheet_reviewer',
|
||||
'sheet_publisher',
|
||||
])
|
||||
.refine((kind) => kind !== '', 'admin.access.error.kind'),
|
||||
reason: requiredText(GRANT_TEXT_MAX),
|
||||
verification_note: z.string().trim(),
|
||||
expires_on: z
|
||||
.string()
|
||||
.refine(
|
||||
(day) =>
|
||||
day === '' || (/^\d{4}-\d{2}-\d{2}$/.test(day) && day > today),
|
||||
'admin.access.error.expiry',
|
||||
),
|
||||
})
|
||||
.superRefine((values, ctx) => {
|
||||
const note = values.verification_note
|
||||
// Required for the three capabilities (§5.2), refused past 1 000 for every kind.
|
||||
if (
|
||||
note === '' &&
|
||||
(CAPABILITY_KINDS as readonly string[]).includes(values.kind)
|
||||
)
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['verification_note'],
|
||||
message: 'clients.error.required',
|
||||
})
|
||||
else if (codePointLength(note) > GRANT_TEXT_MAX)
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['verification_note'],
|
||||
message: `clients.error.too_long|${GRANT_TEXT_MAX}`,
|
||||
})
|
||||
})
|
||||
.transform(
|
||||
(values): GrantFields => ({
|
||||
kind: values.kind as GrantKind,
|
||||
reason: values.reason,
|
||||
...(values.verification_note
|
||||
? { verification_note: values.verification_note }
|
||||
: {}),
|
||||
...(values.expires_on
|
||||
? {
|
||||
expires_at: new Date(
|
||||
`${values.expires_on}T23:59:59`,
|
||||
).toISOString(),
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export function parseGrant(
|
||||
values: GrantFormValues,
|
||||
today: string = localDateIso(),
|
||||
): Parsed<GrantFields, keyof GrantFormValues> {
|
||||
return parse(grantSchema(today), values)
|
||||
}
|
||||
|
||||
export function parseRevocation(reason: string): Parsed<string, 'reason'> {
|
||||
return parse(
|
||||
z
|
||||
.object({ reason: requiredText(GRANT_TEXT_MAX) })
|
||||
.transform((v) => v.reason),
|
||||
{
|
||||
reason,
|
||||
},
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user