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:
@@ -1,36 +1,103 @@
|
||||
import { useState } from 'react'
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useRecords } from '@/api/queries'
|
||||
import axios from 'axios'
|
||||
import { useDictionaryDetail, useRecords } from '@/api/queries'
|
||||
import { useCreateRecord, useUpdateRecord, useCloseRecord } from '@/api/mutations'
|
||||
import type { CreateRecordRequest, FlattenedRecord } from '@/api/client'
|
||||
import { Modal } from '@/components/ui/Modal'
|
||||
import { SchemaDrivenForm } from '@/components/form/SchemaDrivenForm'
|
||||
|
||||
export const Route = createFileRoute('/dictionaries/$name')({
|
||||
component: DictionaryDetail,
|
||||
})
|
||||
|
||||
type EditState =
|
||||
| { kind: 'closed' }
|
||||
| { kind: 'create' }
|
||||
| { kind: 'edit'; record: FlattenedRecord }
|
||||
| { kind: 'close-confirm'; record: FlattenedRecord }
|
||||
|
||||
function DictionaryDetail() {
|
||||
const { name } = Route.useParams()
|
||||
const { t } = useTranslation()
|
||||
const { data, isLoading, error } = useRecords(name, 'PUBLIC,INTERNAL,RESTRICTED')
|
||||
const detailQuery = useDictionaryDetail(name)
|
||||
const recordsResult = useRecords(name, 'PUBLIC,INTERNAL,RESTRICTED')
|
||||
const createMut = useCreateRecord(name)
|
||||
const updateMut = useUpdateRecord(name)
|
||||
const closeMut = useCloseRecord(name)
|
||||
|
||||
const [edit, setEdit] = useState<EditState>({ kind: 'closed' })
|
||||
const [closeReason, setCloseReason] = useState('')
|
||||
|
||||
const handleSubmit = (req: CreateRecordRequest) => {
|
||||
if (edit.kind === 'create') {
|
||||
createMut.mutate(req, { onSuccess: () => setEdit({ kind: 'closed' }) })
|
||||
return
|
||||
}
|
||||
if (edit.kind === 'edit') {
|
||||
updateMut.mutate(
|
||||
{ businessKey: edit.record.businessKey, payload: req },
|
||||
{ onSuccess: () => setEdit({ kind: 'closed' }) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
if (edit.kind !== 'close-confirm') return
|
||||
closeMut.mutate(
|
||||
{ businessKey: edit.record.businessKey, reason: closeReason || undefined },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setEdit({ kind: 'closed' })
|
||||
setCloseReason('')
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const activeMutation =
|
||||
edit.kind === 'create' ? createMut : edit.kind === 'edit' ? updateMut : null
|
||||
const serverError = serverErrorMessage(activeMutation?.error)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-6">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Link to="/dictionaries" className="text-sm text-zinc-500 hover:text-brand-700">
|
||||
← {t('nav.dictionaries')}
|
||||
</Link>
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold mb-1">{name}</h1>
|
||||
<p className="text-sm text-zinc-500 mb-4">
|
||||
{data?.length ?? 0} {t('dict.list.records')}
|
||||
</p>
|
||||
|
||||
{isLoading && <p className="text-zinc-500">{t('loading')}</p>}
|
||||
{error && <p className="text-red-600">{t('error.failed')}</p>}
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold mb-1">
|
||||
{detailQuery.data?.displayName ?? name}
|
||||
</h1>
|
||||
{detailQuery.data?.description && (
|
||||
<p className="text-sm text-zinc-500">{detailQuery.data.description}</p>
|
||||
)}
|
||||
<p className="text-sm text-zinc-500 mt-1">
|
||||
{recordsResult.data?.length ?? 0} {t('dict.list.records')}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEdit({ kind: 'create' })}
|
||||
disabled={!detailQuery.data}
|
||||
className="px-4 py-2 text-sm bg-brand-600 text-white rounded hover:bg-brand-700 disabled:opacity-50"
|
||||
>
|
||||
+ {t('dict.action.create')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{data && data.length === 0 && (
|
||||
{recordsResult.isLoading && <p className="text-zinc-500">{t('loading')}</p>}
|
||||
{recordsResult.error && <p className="text-red-600">{t('error.failed')}</p>}
|
||||
|
||||
{recordsResult.data && recordsResult.data.length === 0 && (
|
||||
<p className="text-zinc-500 italic">{t('dict.empty')}</p>
|
||||
)}
|
||||
|
||||
{data && data.length > 0 && (
|
||||
{recordsResult.data && recordsResult.data.length > 0 && (
|
||||
<div className="overflow-x-auto bg-white border border-zinc-200 rounded-lg">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-zinc-50 text-zinc-600">
|
||||
@@ -40,14 +107,15 @@ function DictionaryDetail() {
|
||||
<th className="text-left px-4 py-2 font-medium">{t('dict.col.scope')}</th>
|
||||
<th className="text-left px-4 py-2 font-medium">{t('dict.col.locale')}</th>
|
||||
<th className="text-left px-4 py-2 font-medium">{t('dict.col.validFrom')}</th>
|
||||
<th className="text-right px-4 py-2 font-medium">{t('dict.col.actions')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.map((r) => (
|
||||
{recordsResult.data.map((r) => (
|
||||
<tr key={r.id} className="border-t border-zinc-100 hover:bg-zinc-50">
|
||||
<td className="px-4 py-2 font-mono text-xs">{r.businessKey}</td>
|
||||
<td className="px-4 py-2">
|
||||
{String((r.data as Record<string, unknown>).name ?? (r.data as Record<string, unknown>).code ?? '—')}
|
||||
{String(r.data.name ?? r.data.code ?? '—')}
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<span className="text-xs px-2 py-0.5 rounded bg-zinc-100">{r.dataScope}</span>
|
||||
@@ -56,12 +124,132 @@ function DictionaryDetail() {
|
||||
<td className="px-4 py-2 text-zinc-500 text-xs">
|
||||
{new Date(r.validFrom).toLocaleDateString()}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-right whitespace-nowrap">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEdit({ kind: 'edit', record: r })}
|
||||
className="text-xs text-brand-700 hover:underline mr-3"
|
||||
>
|
||||
{t('dict.action.edit')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEdit({ kind: 'close-confirm', record: r })}
|
||||
className="text-xs text-red-600 hover:underline"
|
||||
>
|
||||
{t('dict.action.close')}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
open={edit.kind === 'create' || edit.kind === 'edit'}
|
||||
onClose={() => setEdit({ kind: 'closed' })}
|
||||
title={
|
||||
edit.kind === 'create'
|
||||
? t('dict.action.create')
|
||||
: edit.kind === 'edit'
|
||||
? `${t('dict.action.edit')}: ${edit.record.businessKey}`
|
||||
: ''
|
||||
}
|
||||
>
|
||||
{detailQuery.data && (edit.kind === 'create' || edit.kind === 'edit') && (
|
||||
<SchemaDrivenForm
|
||||
schema={detailQuery.data.schemaJson}
|
||||
supportedLocales={detailQuery.data.supportedLocales}
|
||||
defaultLocale={detailQuery.data.defaultLocale}
|
||||
mode={edit.kind}
|
||||
isPending={Boolean(activeMutation?.isPending)}
|
||||
serverError={serverError}
|
||||
defaultValues={
|
||||
edit.kind === 'edit'
|
||||
? {
|
||||
businessKey: edit.record.businessKey,
|
||||
data: edit.record.data,
|
||||
validFrom: toDatetimeLocal(edit.record.validFrom),
|
||||
validTo: toDatetimeLocal(edit.record.validTo),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => setEdit({ kind: 'closed' })}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
open={edit.kind === 'close-confirm'}
|
||||
onClose={() => setEdit({ kind: 'closed' })}
|
||||
title={t('dict.confirmClose.title')}
|
||||
widthClass="max-w-md"
|
||||
>
|
||||
{edit.kind === 'close-confirm' && (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-zinc-600">
|
||||
{t('dict.confirmClose.body', { key: edit.record.businessKey })}
|
||||
</p>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{t('dict.confirmClose.reason')}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={closeReason}
|
||||
onChange={(e) => setCloseReason(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"
|
||||
placeholder={t('dict.confirmClose.reasonPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
{serverErrorMessage(closeMut.error) && (
|
||||
<div className="px-3 py-2 bg-red-50 border border-red-200 rounded text-sm text-red-700">
|
||||
{serverErrorMessage(closeMut.error)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEdit({ kind: 'closed' })}
|
||||
disabled={closeMut.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="button"
|
||||
onClick={handleClose}
|
||||
disabled={closeMut.isPending}
|
||||
className="px-4 py-2 text-sm bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50"
|
||||
>
|
||||
{closeMut.isPending ? t('form.saving') : t('dict.action.close')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const toDatetimeLocal = (iso: string | undefined): string => {
|
||||
if (!iso) return ''
|
||||
const d = new Date(iso)
|
||||
if (isNaN(d.getTime())) return ''
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
|
||||
const serverErrorMessage = (err: unknown): string | null => {
|
||||
if (!err) return null
|
||||
if (axios.isAxiosError(err)) {
|
||||
const data = err.response?.data as { message?: string; error?: string } | undefined
|
||||
if (err.response?.status === 422) return data?.message ?? 'Validation failed'
|
||||
if (err.response?.status === 409) return data?.message ?? 'Conflict — request already in progress'
|
||||
return data?.message ?? data?.error ?? err.message
|
||||
}
|
||||
return err instanceof Error ? err.message : 'Unknown error'
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user