feat(admin-ui): D-pack — history, breaking-change detection, x-unique, x-id-source, datetime

History:
- Drawer на детальной странице записи (timeline всех версий через GET /records/{key}/history)
- Иконка ClockCounterClockwise в actions колонке таблицы записей
- Каждая версия показывает v(version), validFrom/To, updatedBy + expand JSON

Schema diff (breaking detection):
- Util diffSchemas() сравнивает старую/новую схему и классифицирует изменения:
  breaking (removed/typeChanged/becameRequired/enumRemoved/maxLengthTightened/
  patternChanged/newRequiredField), compatible (added optional/enumAdded/
  becameOptional), metadata (description)
- В DictionaryEditorDialog при breaking → Alert с детальным списком + Save заблокирован
- При compatible → Alert info со списком
- suggestVersionBump: major для breaking, minor для compatible field changes,
  patch для metadata-only

x-unique:
- Чекбокс «Уникальное» на PropertyEditor → emit x-unique: true в schema
- Backend enforcement позже — отдельный PR с partial unique index

x-id-source:
- SingleSelect в Метаданных «Использовать как ID» → emit x-id-source на schema root
- В SchemaDrivenForm если установлен — businessKey input скрывается, на submit
  derived из data[idSource]
- Подсказка с именем поля

DateTime для validFrom/validTo:
- Заменил DatePicker (date-only) на DateTimeField компонент: DatePicker + TextInput
  type=time рядом
- Default time: validFrom=00:00, validTo=23:59 (запись действует до конца дня
  иначе зануляется в полночь)
- Поддерживает 2-часовые интервалы (запуск КА в 14:30 → сход в 02:15 etc.)

Bug fix:
- parseSchemaJson изменил сигнатуру с PropertyDef[] на {properties, idSource},
  старый код в DictionaryEditorDialog падал "{} is not iterable". Поправлено
  через destructuring const parsed = parseSchemaJson(...).

i18n: 25+ новых ключей (RU/EN) — schema.unique, schema.idSource, schema.diff.*,
history.*, form.idSourceNote.
This commit is contained in:
Zimin A.N.
2026-05-04 03:38:21 +03:00
parent 0289cf5ff2
commit baf76ac6e0
5 changed files with 221 additions and 35 deletions
@@ -17,7 +17,15 @@ import {
import { useCreateDictionary, useUpdateDictionary } from '@/api/mutations'
import type { CreateDictionaryRequest, DataScope, DictionaryDetail } from '@/api/client'
import { SchemaBuilder } from './SchemaBuilder'
import { buildSchemaJson, parseSchemaJson, type PropertyDef } from './types'
import {
buildSchemaJson,
diffSchemas,
hasBreakingChanges,
parseSchemaJson,
suggestVersionBump,
type PropertyDef,
type SchemaChange,
} from './types'
type Mode =
| { kind: 'create' }
@@ -48,6 +56,8 @@ export const DictionaryEditorDialog = ({ open, mode, onClose, onSuccess }: Props
const isEdit = mode.kind === 'edit'
const initial = mode.kind === 'edit' ? mode.existing : null
const parsed = useMemo(() => parseSchemaJson(initial?.schemaJson), [initial])
const [activeTab, setActiveTab] = useState<EditorTab>('metadata')
const [name, setName] = useState(initial?.name ?? '')
const [displayName, setDisplayName] = useState(initial?.displayName ?? '')
@@ -59,12 +69,24 @@ export const DictionaryEditorDialog = ({ open, mode, onClose, onSuccess }: Props
initial?.supportedLocales ?? ['ru-RU'],
)
const [defaultLocale, setDefaultLocale] = useState(initial?.defaultLocale ?? 'ru-RU')
const [properties, setProperties] = useState<PropertyDef[]>(
() => parseSchemaJson(initial?.schemaJson),
)
const [properties, setProperties] = useState<PropertyDef[]>(parsed.properties)
const [idSource, setIdSource] = useState<string>(parsed.idSource ?? '')
const [nameError, setNameError] = useState<string | null>(null)
const schemaJson = useMemo(() => buildSchemaJson(properties), [properties])
const schemaJson = useMemo(
() => buildSchemaJson(properties, idSource || undefined),
[properties, idSource],
)
const changes: SchemaChange[] = useMemo(
() => (isEdit ? diffSchemas(initial?.schemaJson, schemaJson) : []),
[isEdit, initial, schemaJson],
)
const breaking = hasBreakingChanges(changes)
const suggestedVersion = useMemo(
() => (isEdit ? suggestVersionBump(initial?.schemaVersion, changes) : schemaVersion),
[isEdit, initial, changes, schemaVersion],
)
const activeMutation = isEdit ? updateMut : createMut
const serverError = serverErrorMessage(activeMutation.error)
@@ -79,6 +101,10 @@ export const DictionaryEditorDialog = ({ open, mode, onClose, onSuccess }: Props
return
}
setNameError(null)
if (isEdit && breaking) {
setActiveTab('metadata')
return
}
const payload: CreateDictionaryRequest = {
name,
@@ -161,9 +187,26 @@ export const DictionaryEditorDialog = ({ open, mode, onClose, onSuccess }: Props
<TextInput
label={t('schema.version')}
placeholder="1.0.0"
hint={
isEdit && suggestedVersion !== schemaVersion
? t('schema.versionSuggest', { v: suggestedVersion })
: undefined
}
value={schemaVersion}
onChange={(e) => setSchemaVersion(e.target.value)}
/>
<SingleSelect
label={t('schema.idSource')}
hint={t('schema.idSourceHint')}
options={[
{ id: '', label: '— ' + t('schema.idSourceManual') + ' —' },
...properties
.filter((p) => p.name && (p.kind === 'string' || p.kind === 'integer' || p.kind === 'number'))
.map((p) => ({ id: p.name, label: p.name })),
]}
value={idSource}
onChange={setIdSource}
/>
<MultiSelect
label={t('schema.supportedLocales')}
options={localeOptions}
@@ -194,6 +237,35 @@ export const DictionaryEditorDialog = ({ open, mode, onClose, onSuccess }: Props
</pre>
</div>
{isEdit && breaking && (
<Alert variant="error" title={t('schema.diff.blockedTitle')}>
<div className="space-y-2">
<p className="text-sm">{t('schema.diff.blockedBody')}</p>
<ul className="list-disc pl-5 text-sm space-y-0.5">
{changes
.filter((c) => c.severity === 'breaking')
.map((c, i) => (
<li key={i}>
<span className="font-mono">{c.field}</span> {c.reason}
</li>
))}
</ul>
</div>
</Alert>
)}
{isEdit && !breaking && changes.length > 0 && (
<Alert variant="info" title={t('schema.diff.compatibleTitle')}>
<ul className="list-disc pl-5 text-sm space-y-0.5">
{changes.map((c, i) => (
<li key={i}>
<span className="font-mono">{c.field}</span> {c.reason}
</li>
))}
</ul>
</Alert>
)}
{serverError && <Alert variant="error">{serverError}</Alert>}
<FormActions align="end">
@@ -204,6 +276,7 @@ export const DictionaryEditorDialog = ({ open, mode, onClose, onSuccess }: Props
type="button"
variant="primary"
loading={activeMutation.isPending}
disabled={isEdit && breaking}
onClick={handleSubmit}
>
{activeMutation.isPending ? t('form.saving') : t('form.save')}