feat(admin-ui): record CRUD with json-schema-driven form

POST/PUT/DELETE формы для записей справочников. Schema-driven рендер полей
из definition.schemaJson — i18n-aware (x-localized → input на каждый supportedLocale),
enum → select, type → text/number/checkbox/array. Валидация через ajv (Draft-07,
match backend networknt validator).

- new: api/mutations.ts с Idempotency-Key (crypto.randomUUID) и query invalidation
- new: SchemaDrivenForm — react-hook-form + ajv compile per-schema, errors через
  setError по ajv instancePath
- new: Modal (Esc + backdrop click) и confirm dialog для close-операции
- nginx: regex location ^/api/v1/dictionaries/[^/]+$ → writer (admin schema fetch)
- queries: dictionaryDetailQuery возвращает full def с schemaJson
- i18n: RU/EN ключи для CRUD (create/edit/close, validFrom/validTo, confirm)
This commit is contained in:
Zimin A.N.
2026-05-04 01:49:08 +03:00
parent d5a747616a
commit b1b1f05e3c
11 changed files with 3137 additions and 36 deletions
@@ -0,0 +1,389 @@
import { useMemo } from 'react'
import { useForm, Controller, type SubmitHandler } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import Ajv, { type ErrorObject } from 'ajv'
import addFormats from 'ajv-formats'
import type { CreateRecordRequest, JsonSchema } from '@/api/client'
type FormValues = {
businessKey: string
validFrom: string
validTo: string
data: Record<string, unknown>
}
type Props = {
schema: JsonSchema
supportedLocales: string[]
defaultLocale: string
defaultValues?: Partial<FormValues>
mode: 'create' | 'edit'
isPending: boolean
serverError?: string | null
onSubmit: (req: CreateRecordRequest) => void
onCancel: () => void
}
const ajv = new Ajv({ allErrors: true, strict: false })
addFormats(ajv)
const isLocalized = (s: JsonSchema): boolean => Boolean(s['x-localized'])
const fieldLabel = (key: string, schema: JsonSchema): string =>
schema.title ?? key
export const SchemaDrivenForm = ({
schema,
supportedLocales,
defaultLocale,
defaultValues,
mode,
isPending,
serverError,
onSubmit,
onCancel,
}: Props) => {
const { t } = useTranslation()
const validator = useMemo(() => {
try {
return ajv.compile(schema)
} catch {
return null
}
}, [schema])
const properties = schema.properties ?? {}
const required = new Set(schema.required ?? [])
const { register, handleSubmit, control, setError, formState } = useForm<FormValues>({
defaultValues: {
businessKey: defaultValues?.businessKey ?? '',
validFrom: defaultValues?.validFrom ?? '',
validTo: defaultValues?.validTo ?? '',
data: defaultValues?.data ?? {},
},
})
const submit: SubmitHandler<FormValues> = (values) => {
if (validator) {
const ok = validator(values.data)
if (!ok && validator.errors) {
applyAjvErrors(validator.errors, setError)
return
}
}
const req: CreateRecordRequest = {
businessKey: values.businessKey.trim(),
data: values.data,
validFrom: values.validFrom || undefined,
validTo: values.validTo || undefined,
}
onSubmit(req)
}
return (
<form onSubmit={handleSubmit(submit)} className="space-y-4">
<div>
<label className="block text-sm font-medium text-zinc-700 mb-1">
{t('form.businessKey')} <span className="text-red-500">*</span>
</label>
<input
type="text"
disabled={mode === 'edit'}
{...register('businessKey', { required: true, minLength: 1 })}
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 disabled:bg-zinc-100 disabled:text-zinc-500 font-mono"
placeholder="MY_RECORD_KEY"
/>
{formState.errors.businessKey && (
<p className="text-xs text-red-600 mt-1">{t('form.error.required')}</p>
)}
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-medium text-zinc-700 mb-1">
{t('form.validFrom')}
</label>
<input
type="datetime-local"
{...register('validFrom')}
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 mb-1">
{t('form.validTo')}
</label>
<input
type="datetime-local"
{...register('validTo')}
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
</div>
</div>
<div className="border-t border-zinc-200 pt-4">
<h3 className="text-sm font-semibold text-zinc-700 mb-3">{t('form.dataFields')}</h3>
<div className="space-y-3">
{Object.entries(properties).map(([key, propSchema]) => (
<FieldRenderer
key={key}
fieldKey={key}
schema={propSchema}
required={required.has(key)}
control={control}
supportedLocales={supportedLocales}
defaultLocale={defaultLocale}
fieldError={formState.errors.data?.[key as keyof FormValues['data']]}
/>
))}
</div>
</div>
{serverError && (
<div className="px-3 py-2 bg-red-50 border border-red-200 rounded text-sm text-red-700">
{serverError}
</div>
)}
<div className="flex justify-end gap-2 pt-2 border-t border-zinc-200">
<button
type="button"
onClick={onCancel}
disabled={isPending}
className="px-4 py-2 text-sm border border-zinc-300 rounded hover:bg-zinc-50 disabled:opacity-50"
>
{t('form.cancel')}
</button>
<button
type="submit"
disabled={isPending}
className="px-4 py-2 text-sm bg-brand-600 text-white rounded hover:bg-brand-700 disabled:opacity-50"
>
{isPending ? t('form.saving') : t('form.save')}
</button>
</div>
</form>
)
}
type FieldRendererProps = {
fieldKey: string
schema: JsonSchema
required: boolean
control: ReturnType<typeof useForm<FormValues>>['control']
supportedLocales: string[]
defaultLocale: string
fieldError?: unknown
}
const FieldRenderer = ({
fieldKey,
schema,
required,
control,
supportedLocales,
defaultLocale,
fieldError,
}: FieldRendererProps) => {
const label = fieldLabel(fieldKey, schema)
const errorMsg = (fieldError as { message?: string } | undefined)?.message
if (isLocalized(schema)) {
return (
<div>
<label className="block text-sm font-medium text-zinc-700 mb-1">
{label}
{required && <span className="text-red-500"> *</span>}
<span className="text-xs text-zinc-400 ml-1">(i18n)</span>
</label>
<div className="space-y-2 pl-3 border-l-2 border-zinc-200">
{supportedLocales.map((loc) => (
<Controller
key={loc}
control={control}
name={`data.${fieldKey}.${loc}` as `data.${string}`}
render={({ field }) => (
<div className="flex items-center gap-2">
<span className="text-xs font-mono text-zinc-500 w-12">
{loc === defaultLocale ? <strong>{loc}</strong> : loc}
</span>
<input
type="text"
{...field}
value={(field.value as string | undefined) ?? ''}
className="flex-1 px-3 py-1.5 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
</div>
)}
/>
))}
</div>
{schema.description && (
<p className="text-xs text-zinc-500 mt-1">{schema.description}</p>
)}
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
</div>
)
}
if (schema.enum) {
return (
<Controller
control={control}
name={`data.${fieldKey}` as `data.${string}`}
render={({ field }) => (
<div>
<label className="block text-sm font-medium text-zinc-700 mb-1">
{label}
{required && <span className="text-red-500"> *</span>}
</label>
<select
{...field}
value={(field.value as string | undefined) ?? ''}
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 bg-white"
>
<option value=""></option>
{schema.enum?.map((v) => (
<option key={String(v)} value={String(v)}>
{String(v)}
</option>
))}
</select>
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
</div>
)}
/>
)
}
if (schema.type === 'boolean') {
return (
<Controller
control={control}
name={`data.${fieldKey}` as `data.${string}`}
render={({ field }) => (
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={Boolean(field.value)}
onChange={(e) => field.onChange(e.target.checked)}
className="rounded"
/>
<span>{label}</span>
</label>
)}
/>
)
}
if (schema.type === 'integer' || schema.type === 'number') {
return (
<Controller
control={control}
name={`data.${fieldKey}` as `data.${string}`}
render={({ field }) => (
<div>
<label className="block text-sm font-medium text-zinc-700 mb-1">
{label}
{required && <span className="text-red-500"> *</span>}
</label>
<input
type="number"
step={schema.type === 'integer' ? 1 : 'any'}
value={(field.value as number | undefined) ?? ''}
onChange={(e) =>
field.onChange(e.target.value === '' ? undefined : Number(e.target.value))
}
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
</div>
)}
/>
)
}
if (schema.type === 'array' && schema.items?.type === 'string') {
return (
<Controller
control={control}
name={`data.${fieldKey}` as `data.${string}`}
render={({ field }) => (
<div>
<label className="block text-sm font-medium text-zinc-700 mb-1">
{label}
{required && <span className="text-red-500"> *</span>}
<span className="text-xs text-zinc-400 ml-1">(comma-separated)</span>
</label>
<input
type="text"
value={Array.isArray(field.value) ? (field.value as string[]).join(', ') : ''}
onChange={(e) =>
field.onChange(
e.target.value
.split(',')
.map((s) => s.trim())
.filter(Boolean),
)
}
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
</div>
)}
/>
)
}
return (
<Controller
control={control}
name={`data.${fieldKey}` as `data.${string}`}
render={({ field }) => {
const isLong = (schema.maxLength ?? 0) > 200
return (
<div>
<label className="block text-sm font-medium text-zinc-700 mb-1">
{label}
{required && <span className="text-red-500"> *</span>}
</label>
{isLong ? (
<textarea
{...field}
value={(field.value as string | undefined) ?? ''}
rows={3}
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
) : (
<input
type={schema.format === 'date-time' ? 'datetime-local' : 'text'}
{...field}
value={(field.value as string | undefined) ?? ''}
pattern={schema.pattern}
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
)}
{schema.description && (
<p className="text-xs text-zinc-500 mt-1">{schema.description}</p>
)}
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
</div>
)
}}
/>
)
}
const applyAjvErrors = (
errors: ErrorObject[],
setError: ReturnType<typeof useForm<FormValues>>['setError'],
) => {
for (const err of errors) {
const path = err.instancePath.replace(/^\//, '').replace(/\//g, '.')
const fieldPath = path ? (`data.${path}` as `data.${string}`) : 'data'
setError(fieldPath as 'data', { type: 'ajv', message: err.message ?? 'invalid' })
}
}
@@ -0,0 +1,50 @@
import { useEffect, type ReactNode } from 'react'
type Props = {
open: boolean
title: string
onClose: () => void
children: ReactNode
widthClass?: string
}
export const Modal = ({ open, title, onClose, children, widthClass = 'max-w-2xl' }: Props) => {
useEffect(() => {
if (!open) return
const handleKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', handleKey)
return () => window.removeEventListener('keydown', handleKey)
}, [open, onClose])
if (!open) return null
return (
<div
className="fixed inset-0 z-50 flex items-start justify-center bg-zinc-900/50 backdrop-blur-sm pt-16 px-4"
role="dialog"
aria-modal="true"
aria-label={title}
onClick={onClose}
>
<div
className={`bg-white rounded-lg shadow-xl w-full ${widthClass} max-h-[85vh] flex flex-col`}
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between px-5 py-3 border-b border-zinc-200">
<h2 className="text-lg font-semibold">{title}</h2>
<button
type="button"
onClick={onClose}
className="text-zinc-400 hover:text-zinc-700 text-xl leading-none w-8 h-8 rounded hover:bg-zinc-100"
aria-label="Close"
>
×
</button>
</div>
<div className="overflow-y-auto p-5">{children}</div>
</div>
</div>
)
}