"use client"; import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react"; import { Pencil, Plus } from "lucide-react"; import type { SortingState } from "@tanstack/react-table"; import { Button } from "@/app/components/ui/button"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/app/components/ui/select"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, } from "@/app/components/ui/dialog"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/app/components/ui/table"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/app/components/ui/tabs"; import { SortableHead, sortRows } from "@/app/components/ui/sortable-head"; import { PageHeader } from "@/app/components/ui/page-header"; import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states"; import { FilterPanel, FilterField, FilterSearch } from "@/app/components/ui/filter-panel"; import { TablePager } from "@/app/components/ui/table-pager"; import { RequireModule } from "@/app/lib/RequireModule"; import { matchesCodeOrName } from "@/app/lib/codeOrNameSearch"; import { REFERENCE_TABLES, type ReferenceColumn, type ReferenceTableSpec, } from "@/app/lib/referenceTables"; import { createReferenceRow, listReferenceRows, updateReferenceRow, type ReferenceRowPayload, } from "@/app/lib/services/adminReference"; import type { ReferenceRow } from "@/app/lib/types"; import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import type { Translate } from "@/app/lib/i18n/t"; import { BankPanel } from "./BankPanel"; // `/reference` reference-data management (spec "admin-portal-reference-ui"): one generic // surface over the five uniform lookup tables (nationality, marital status, race, preferred // language, salutation). A table picker switches the registry-driven grid; add/edit go through // the portal's own app/api/reference/** route handlers, which forward the admin JWT. Code is // the stable key — editable only on CREATE, read-only with a rename caveat on EDIT. A // duplicate-code 409 and a validation 422 surface inline and keep the dialog open; the grid // never shows a phantom success. Wrapped in RequireModule against the seeded BO_REFERENCE_DATA // module (id 41800000). GETs are pure reads — no side effects on prefetch. interface DialogState { mode: "add" | "edit"; id?: number; values: Record; } function valueFor(row: ReferenceRow, field: string): string { const v = (row as unknown as Record)[field]; return v == null ? "" : String(v); } /** Option columns (e.g. spouseRequired Y/N) show the option's label, never the stored code. */ function cellText(col: ReferenceColumn, value: string, t: Translate): string { return shownText(col, value, t) || "—"; } /** What the cell shows, "" when blank (sort getters treat blank as last, not as the "—" placeholder). */ function shownText(col: ReferenceColumn, value: string, t: Translate): string { const opt = col.options?.find((o) => o.value === value); return opt ? t(opt.label) : value; } function emptyValues(spec: ReferenceTableSpec): Record { const values: Record = {}; for (const col of spec.columns) { // An option column (e.g. marital spouse_required) must seed its DEFAULT option value so // the value the select displays on an untouched add form is exactly what gets submitted — // never a "" that the submit handler skips (which would let the server default persist). values[col.field] = col.options ? col.options[0].value : ""; } return values; } function valuesForRow(spec: ReferenceTableSpec, row: ReferenceRow): Record { const values: Record = {}; for (const col of spec.columns) values[col.field] = valueFor(row, col.field); return values; } function ReferenceFormDialog({ spec, mode, id, initial, onClose, onSaved, t, }: { spec: ReferenceTableSpec; mode: "add" | "edit"; id?: number; initial: Record; onClose: () => void; onSaved: () => void; t: Translate; }) { const [values, setValues] = useState>(initial); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const isEdit = mode === "edit"; function setField(field: string, value: string) { setValues((prev) => ({ ...prev, [field]: value })); } async function handleSubmit(event: FormEvent) { event.preventDefault(); setSaving(true); setError(null); try { // code/name always; optional fields only when non-empty (an empty optional is not sent, // so an update keeps the persisted value server-side). const payload: ReferenceRowPayload = { code: (values.code ?? "").trim(), name: (values.name ?? "").trim(), }; if (values.messageTag?.trim()) payload.messageTag = values.messageTag.trim(); if (values.isoCode?.trim()) payload.isoCode = values.isoCode.trim(); if (values.spouseRequired) payload.spouseRequired = values.spouseRequired; if (isEdit && id != null) { await updateReferenceRow(spec.key, id, payload); } else { await createReferenceRow(spec.key, payload); } onSaved(); onClose(); } catch (err) { // A duplicate-code 409 / validation 422 surfaces here as the downstream message — // reported inline, never a silent no-op and never a phantom success in the grid. setError(err instanceof Error ? err.message : "CatSaveRowFailed"); } finally { setSaving(false); } } function renderField(col: ReferenceColumn) { const fieldId = `ref-${col.field}`; if (col.options) { return ( ); } const readOnly = col.field === "code" && isEdit; return ( setField(col.field, e.target.value)} className={readOnly ? "opacity-70" : undefined} /> ); } return ( !open && onClose()}> {t(isEdit ? "RfrEditRowTitle" : "RfrAddRowTitle", { table: t(spec.label).toLowerCase() })} {error && }
{spec.columns.filter((c) => c.editable).map((col) => (
{renderField(col)} {col.field === "code" && isEdit && (

{t("RfrCodeImmutableNote")}

)}
))}
); } // The Bank tab (add-admin-bank-reference) is not a registry table: it has its own panel, // dialog and API. It sits in the same picker so it looks and gates like the other tables. const BANK_KEY = "bank"; function ReferencePageContent() { const t = useT(); const { tableRef, pageSize } = useFitPageSize(); const size = pageSize ?? MIN_PAGE_SIZE; const [tableKey, setTableKey] = useState(REFERENCE_TABLES[0].key); const spec = useMemo( () => REFERENCE_TABLES.find((rt) => rt.key === tableKey) ?? REFERENCE_TABLES[0], [tableKey], ); const [rows, setRows] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [reloadKey, setReloadKey] = useState(0); const [dialog, setDialog] = useState(null); const [bankAdding, setBankAdding] = useState(false); const isBank = tableKey === BANK_KEY; const [search, setSearch] = useState(""); const [page, setPage] = useState(1); const [sorting, setSorting] = useState([]); // Sort the whole filtered list before paging; each column sorts by what it shows. const shownRows = useMemo(() => { const getters = Object.fromEntries( spec.columns.map((col) => [col.field, (row: ReferenceRow) => shownText(col, valueFor(row, col.field), t) || null]), ); return sortRows(rows.filter((row) => matchesCodeOrName(row, search)), sorting, getters); }, [rows, search, sorting, spec, t]); const lastPage = Math.max(1, Math.ceil(shownRows.length / size)); const current = Math.min(page, lastPage); const pagedRows = useMemo(() => shownRows.slice((current - 1) * size, current * size), [shownRows, size, current]); const refetch = useCallback(() => setReloadKey((k) => k + 1), []); useEffect(() => { if (tableKey === BANK_KEY) return; // BankPanel loads its own rows let cancelled = false; // eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the filter/reloadKey-triggered fetch below. setLoading(true); setError(null); listReferenceRows(tableKey) .then((result) => { if (!cancelled) setRows(result); }) .catch((err: unknown) => { if (!cancelled) setError(err instanceof Error ? err.message : "CatLoadRowsFailed"); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; }, [tableKey, reloadKey]); function openAdd() { if (isBank) { setBankAdding(true); return; } setDialog({ mode: "add", values: emptyValues(spec) }); } function openEdit(row: ReferenceRow) { setDialog({ mode: "edit", id: row.id, values: valuesForRow(spec, row) }); } return ( { setTableKey(key as typeof tableKey); setSearch(""); setPage(1); setSorting([]); setDialog(null); // a dialog from another table is never kept open setBankAdding(false); }} > ); } export default function ReferencePage() { return ( ); }