import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { ReactNode } from 'react' import { AlertTriangle, ArrowLeft, ChevronLeft, ChevronRight, ListChecks, Lock, Pencil, Plus, RotateCw, Search } from 'lucide-react' import clsx from 'clsx' import { ApiError, api } from '../../api/client' import type { CatalogBusinessDate, CatalogCardinality, CatalogDetail, CatalogItem, CatalogRelation, CatalogReviewAction, CatalogTableKind, CatalogTableRow, } from '../../types' import { DeleteButton, EmptyState, ErrorState, Notice, Skeleton, Spinner, confirmDialog, toast } from '../../components/ui' import { useLeaveGuard } from '../../lib/leave' import { formatDateTime, formatNumber } from '../../lib/format' import { CATALOG_CARDINALITY_LABEL, CATALOG_IMPACT_TEXT, CATALOG_KIND_HINT, CATALOG_KIND_LABEL, CATALOG_TABLE_FIELD_HINT, CATALOG_TABLE_FIELD_LABEL, CATALOG_TEXT as CT, CODES_TEXT as KT, } from '../../lib/terms' import { CatalogImpactList } from '../../components/CatalogImpact' import { CountBadges, ItemMark, StatusChip, StatusLegend, SystemNotesNotice } from './parts' import type { ReviewTarget } from './parts' import { ColumnTable, Value, pendingCodes } from './ColumnTable' import type { ColumnModel } from './ColumnTable' import { CodesDialog } from './CodesDialog' import { coverageText } from './profile' import { COLUMN_FIELDS, DATE_KEYS, TABLE_FIELDS, buildNotes, changeCount, columnPath, confirmProposed, countsOf, formFromNotes, relationDraft, relationPath, tablePath, unknownKeys, validateForm, } from './model' import type { ColumnField, EditForm, RelationDraft, TableField, TableKey } from './model' // =========================================================================== // 单表详情:表级各项、列表格、关联关系。每一项标出来源和状态,点状态标识做单项确认 / 驳回 / 恢复(审阅接口); // 「确认本表全部推断」「确认本列推断」和直接编辑都是整份提交(编辑即确认:改过的项服务端记为人工填写、已确认)。 // // 写操作都带读到的版本。409 说明别人刚改过:不静默覆盖,横幅写明并给「重新载入」;编辑中的修改留着,重新载入前 // 先问一句。编辑中换表、离开页面走全站的离开前确认。 // =========================================================================== const KINDS = Object.keys(CATALOG_KIND_LABEL) as CatalogTableKind[] const CARDINALITIES = Object.keys(CATALOG_CARDINALITY_LABEL) as CatalogCardinality[] const PROBLEM_TEXT = { tooLong: CT.tooLong, codesInvalid: CT.codesInvalid, codesDuplicate: CT.codesDuplicate, dateColumnRequired: CT.dateColumnRequired, relationIncomplete: CT.relationIncomplete, relationMismatch: CT.relationMismatch, relationDuplicate: CT.relationDuplicate, } type Editing = { initial: EditForm; form: EditForm } type Conflict = 'edit' | 'review' export function TableDetail({ sourceId, table, rows, drafted, fillCodes, prev, next, onOpen, onBack, onDetail }: { sourceId: string table: string /** 全部表:关联关系的目标表能点就跳过去,编辑时给目标表做候选 */ rows: CatalogTableRow[] /** 起草刚写进了这些表:正在看的表在里面、又没在编辑,就重新载入 */ drafted: { seq: number; tables: Set } /** 从剖析报告点「填写含义」过来:载入后打开这一列的码值弹窗(seq 让同一列连点两次也会再开) */ fillCodes?: { table: string; column: string; seq: number } | null prev: string | null next: string | null onOpen: (table: string) => void /** 窄屏:回到表清单 */ onBack: () => void /** 载入或写入之后的单表目录:清单据此更新这一行 */ onDetail: (d: CatalogDetail) => void }) { const [detail, setDetail] = useState(null) const [loadError, setLoadError] = useState(null) const [busy, setBusy] = useState('') const [conflict, setConflict] = useState(null) const [writeError, setWriteError] = useState(null) const [edit, setEdit] = useState(null) const [live, setLive] = useState('') const [colQuery, setColQuery] = useState('') const [onlyPending, setOnlyPending] = useState(false) /** 正在填写哪一列的码值含义 */ const [codesFor, setCodesFor] = useState(null) const loadSeq = useRef(0) const onDetailRef = useRef(onDetail) onDetailRef.current = onDetail const load = useCallback(async () => { const seq = ++loadSeq.current try { const d = await api.dataCatalog.get(sourceId, table) if (seq !== loadSeq.current) return setDetail(d) setLoadError(null) setConflict(null) onDetailRef.current(d) } catch (e) { if (seq !== loadSeq.current) return setLoadError(e) } }, [sourceId, table]) useEffect(() => { setDetail(null) setLoadError(null) setEdit(null) setConflict(null) setWriteError(null) setColQuery('') setOnlyPending(false) setLive('') setCodesFor(null) void load() }, [load]) // 起草写进了这张表:没在编辑就重新载入;在编辑就不动,保存时服务端按版本号拦下,横幅里再重新载入 const editingRef = useRef(false) editingRef.current = !!edit // 只认新的一次起草:换表时上面那个 effect 已经载入过,不再重复取 const draftSeen = useRef(drafted.seq) useEffect(() => { if (drafted.seq === draftSeen.current) return draftSeen.current = drafted.seq if (drafted.tables.has(table) && !editingRef.current) void load() }, [drafted, table, load]) // 剖析报告里点了「填写含义」:这张表载入后打开那一列的码值弹窗。编辑中不打开,免得同一项两处同时改 const fillSeen = useRef(0) useEffect(() => { if (!fillCodes || fillCodes.table !== table || fillCodes.seq === fillSeen.current) return if (!detail || detail.table_name !== table || editingRef.current) return fillSeen.current = fillCodes.seq if (detail.notes.columns?.[fillCodes.column]?.codes) setCodesFor(fillCodes.column) }, [fillCodes, table, detail]) const changes = edit ? changeCount(edit.initial, edit.form) : 0 const problems = useMemo(() => (edit ? validateForm(edit.form, PROBLEM_TEXT) : {}), [edit]) const problemCount = Object.keys(problems).length useLeaveGuard(changes > 0, () => confirmDialog({ title: CT.leaveTitle, consequences: CT.leaveConsequences, confirmLabel: CT.leaveConfirm, danger: true, })) /** 写操作:成功换上返回的目录;409 挂冲突横幅,422 显示服务端原话,其余弹提示。只用 ref 和 setState,自身不变 */ const write = useCallback(async (key: string, call: () => Promise): Promise => { setBusy(key) setWriteError(null) try { const d = await call() setDetail(d) setConflict(null) onDetailRef.current(d) return d } catch (e) { if (e instanceof ApiError && e.status === 409) setConflict(editingRef.current ? 'edit' : 'review') else if (e instanceof ApiError && e.kind === 'http' && (e.status === 422 || e.status === 404)) setWriteError(e.message) else toast.error(e) return null } finally { setBusy('') } }, []) const detailRef = useRef(detail) detailRef.current = detail const review = useCallback(async (t: ReviewTarget, action: CatalogReviewAction) => { const d = detailRef.current if (!d) return const done = await write(t.path, () => api.dataCatalog.review(sourceId, table, { path: t.path, action, if_version: d.version })) if (done) setLive(action === 'reset' && t.source === 'human' ? CT.removed(t.where) : CT.reviewed[action](t.where)) }, [sourceId, table, write]) const confirmColumn = useCallback(async (col: string) => { const d = detailRef.current if (!d) return const paths = new Set(COLUMN_FIELDS.map((f) => columnPath(col, f))) const { notes, n } = confirmProposed(d.notes, (p) => paths.has(p)) if (!n) return const done = await write(`column:${col}`, () => api.dataCatalog.put(sourceId, table, notes, d.version)) if (done) setLive(CT.confirmedN(n)) }, [sourceId, table, write]) const fillCodesOf = useCallback((col: string) => setCodesFor(col), []) /** * 填好的码值含义整份提交:只换这一列码值的值,服务端记为人工填写、已确认。别人刚改过(409)时收起弹窗、挂冲突横幅; * 其余失败弹窗留着,填的字不丢 */ const saveCodes = useCallback(async (col: string, value: Record) => { const d = detailRef.current const item = d?.notes.columns?.[col]?.codes if (!d || !item) return const notes = structuredClone(d.notes) notes.columns![col] = { ...notes.columns![col], codes: { ...item, value } } setBusy(`codes:${col}`) setWriteError(null) try { const next = await api.dataCatalog.put(sourceId, table, notes, d.version) setDetail(next) setConflict(null) onDetailRef.current(next) setCodesFor(null) const filled = Math.max(0, pendingCodes(item.value) - pendingCodes(value)) toast.ok(KT.saved(filled)) setLive(KT.saved(filled)) } catch (e) { if (e instanceof ApiError && e.status === 409) { setCodesFor(null) setConflict('review') } else { toast.error(e) } } finally { setBusy('') } }, [sourceId, table]) const setColumn = useCallback((col: string, f: ColumnField, v: string) => { setEdit((e) => e && ({ ...e, form: { ...e.form, columns: { ...e.form.columns, [col]: { ...e.form.columns[col], [f]: v } } } })) }, []) const setTable = (k: TableKey, v: string) => setEdit((e) => e && ({ ...e, form: { ...e.form, table: { ...e.form.table, [k]: v } } })) const setRelations = (fn: (rs: RelationDraft[]) => RelationDraft[]) => setEdit((e) => e && ({ ...e, form: { ...e.form, relations: fn(e.form.relations) } })) const columns: ColumnModel[] = useMemo(() => { if (!detail) return [] const st = detail.structure?.columns ?? [] const known = new Set(st.map((c) => c.name)) return [ ...st.map((c) => ({ name: c.name, structure: c, items: detail.notes.columns?.[c.name] })), ...Object.keys(detail.notes.columns ?? {}).filter((n) => !known.has(n)) .map((n) => ({ name: n, structure: null, items: detail.notes.columns?.[n] })), ] }, [detail]) const shownColumns = useMemo(() => { const q = colQuery.trim().toLowerCase() return columns.filter((c) => { if (onlyPending && !COLUMN_FIELDS.some((f) => c.items?.[f]?.status === 'proposed')) return false if (!q) return true const label = c.items?.label?.value ?? '' return c.name.toLowerCase().includes(q) || label.toLowerCase().includes(q) }) }, [columns, colQuery, onlyPending]) if (!detail) { return (
{loadError ? (loadError instanceof ApiError && loadError.status === 404 ? : void load()} />) : }
) } const notes = detail.notes const counts = countsOf(notes) const label = notes.label && notes.label.status !== 'rejected' ? notes.label.value : null const kind = notes.kind && notes.kind.status !== 'rejected' ? notes.kind.value : null const st = detail.structure const systemComment = detail.system_notes ? st?.comment?.trim() : '' const startEdit = () => { const f = formFromNotes(notes, st?.columns ?? []) setEdit({ initial: f, form: f }) setWriteError(null) } const cancelEdit = async () => { if (changes > 0 && !(await confirmDialog({ title: CT.cancelEditTitle, confirmLabel: CT.cancelEditAction, danger: true }))) return setEdit(null) setConflict(null) setWriteError(null) } const save = async () => { if (!edit || problemCount || !changes) return const body = buildNotes(notes, edit.initial, edit.form) const done = await write('save', () => api.dataCatalog.put(sourceId, table, body, detail.version)) if (done) { setEdit(null) toast.ok(CT.saved) } } const confirmAll = async () => { const { notes: body, n } = confirmProposed(notes) if (!n) return const ok = await confirmDialog({ title: CT.confirmAllTitle(n, label ?? table), consequences: CT.confirmAllConsequences, confirmLabel: CT.confirmAllAction(n), }) if (!ok) return const done = await write('confirm-all', () => api.dataCatalog.put(sourceId, table, body, detail.version)) if (done) toast.ok(CT.confirmedN(n)) } const reload = async () => { if (changes > 0 && !(await confirmDialog({ title: CT.reloadDiscardTitle, confirmLabel: CT.reloadDiscardAction, danger: true }))) return setEdit(null) setWriteError(null) await load() } const targetOf = (name: string) => { const lower = name.toLowerCase() return rows.find((r) => r.table_name === name || r.qualified === name) ?? rows.find((r) => r.table_name.toLowerCase() === lower || r.qualified.toLowerCase() === lower) } return (

{label ?? detail.table_name} {kind && {CATALOG_KIND_LABEL[kind]}} {st?.is_view && {CT.view}}

{label && {st?.qualified ?? detail.table_name}} {CT.usage(detail.usage)} {detail.updated_at ? (detail.updated_by ? CT.updatedBy(detail.updated_by, formatDateTime(detail.updated_at)) : CT.updatedAt(formatDateTime(detail.updated_at))) : CT.notStarted}
{!edit && (
{counts.proposed > 0 && ( )} {CT.editHint}
)}

{live}

{conflict && (

{CT.conflictTitle}

{conflict === 'edit' ? CT.conflictEditing : CT.conflictReview}

)} {writeError && {writeError}} {!detail.in_schema && ( {CT.missingBody} )} {detail.system_notes && } {edit && {CT.editHint}。{CT.clearHint}。}

{CT.sectionTable}

{!edit && }
{systemComment && (
{CT.systemTableNote} · {CT.systemTag}

{systemComment}

)}
{TABLE_FIELDS.map((f) => ( ))}

{CT.sectionColumns}

{CT.columnCount(shownColumns.length, columns.length)}
setColQuery(e.target.value)} data-column-filter="" />
{shownColumns.length ? ( ) :

{CT.noColumns}

}

{CT.sectionRelations}

{formatNumber((edit ? edit.form.relations : notes.relations ?? []).length)}
{edit ? : }

{CATALOG_IMPACT_TEXT.title}

{CATALOG_IMPACT_TEXT.hint}
{codesFor && notes.columns?.[codesFor]?.codes && ( void saveCodes(codesFor, v)} onClose={() => setCodesFor(null)} /> )} {edit && (
{changes ? CT.changes(changes) : CT.noChanges} {problemCount > 0 && ( {CT.invalidCount(problemCount)} )}
)}
) } // --------------------------------------------------------------------------- // 表级各项 // --------------------------------------------------------------------------- function TableFieldRow({ field, item, edit, busy, problems, columns, onChange, onReview }: { field: TableField item: CatalogItem | undefined edit: Editing | null busy: boolean problems: Record /** 表结构里的列:业务日期的候选、业务主键的核对 */ columns: { name: string }[] onChange: (k: TableKey, v: string) => void onReview: (t: ReviewTarget, a: CatalogReviewAction) => void }) { const where = CT.whereTable(CATALOG_TABLE_FIELD_LABEL[field]) const keys: TableKey[] = field === 'business_date' ? [...DATE_KEYS] : [field as TableKey] const changed = !!edit && keys.some((k) => (edit.form.table[k] ?? '') !== (edit.initial.table[k] ?? '')) const problem = keys.map((k) => problems[`t:${k}`]).find(Boolean) const inputId = `catalog-field-${field}` const rejected = item?.status === 'rejected' const placeholder = rejected ? CT.rejectedPlaceholder(plainValue(field, item?.value)) : CATALOG_TABLE_FIELD_HINT[field] let input: ReactNode = null if (edit) { const v = (k: TableKey) => edit.form.table[k] ?? '' if (field === 'kind') { input = ( ) } else if (field === 'business_date') { input = (
onChange('business_date.column', e.target.value)} data-input="business_date.column" />
onChange('business_date.rule', e.target.value)} data-input="business_date.rule" />
onChange('business_date.timezone', e.target.value)} data-input="business_date.timezone" />
{columns.map((c) =>
) } else if (field === 'description') { input = (