Files
co-lite/solvway-admin-portal/app/reference/page.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

425 lines
15 KiB
TypeScript

"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<string, string>;
}
function valueFor(row: ReferenceRow, field: string): string {
const v = (row as unknown as Record<string, unknown>)[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<string, string> {
const values: Record<string, string> = {};
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<string, string> {
const values: Record<string, string> = {};
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<string, string>;
onClose: () => void;
onSaved: () => void;
t: Translate;
}) {
const [values, setValues] = useState<Record<string, string>>(initial);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const isEdit = mode === "edit";
function setField(field: string, value: string) {
setValues((prev) => ({ ...prev, [field]: value }));
}
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
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 (
<Select
key={col.field}
value={values[col.field] || col.options[0].value}
onValueChange={(v) => setField(col.field, v)}
disabled={saving}
>
<SelectTrigger id={fieldId} className="w-full">
<SelectValue placeholder={t(col.label)} />
</SelectTrigger>
<SelectContent>
{col.options.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{t(opt.label)}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
const readOnly = col.field === "code" && isEdit;
return (
<Input
key={col.field}
id={fieldId}
required={col.required}
readOnly={readOnly}
disabled={saving}
value={values[col.field] ?? ""}
onChange={(e) => setField(col.field, e.target.value)}
className={readOnly ? "opacity-70" : undefined}
/>
);
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
{t(isEdit ? "RfrEditRowTitle" : "RfrAddRowTitle", { table: t(spec.label).toLowerCase() })}
</DialogTitle>
</DialogHeader>
{error && <ErrorState message={t(error)} />}
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
{spec.columns.filter((c) => c.editable).map((col) => (
<div key={col.field} className="space-y-1.5">
<Label htmlFor={`ref-${col.field}`}>{t(col.label)}</Label>
{renderField(col)}
{col.field === "code" && isEdit && (
<p className="text-xs text-muted-foreground">
{t("RfrCodeImmutableNote")}
</p>
)}
</div>
))}
<DialogFooter>
<Button type="submit" disabled={saving}>
{t("Save")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
// 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<ReferenceRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [dialog, setDialog] = useState<DialogState | null>(null);
const [bankAdding, setBankAdding] = useState(false);
const isBank = tableKey === BANK_KEY;
const [search, setSearch] = useState("");
const [page, setPage] = useState(1);
const [sorting, setSorting] = useState<SortingState>([]);
// 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 (
<Tabs
className="block"
value={tableKey}
onValueChange={(key) => {
setTableKey(key as typeof tableKey);
setSearch("");
setPage(1);
setSorting([]);
setDialog(null); // a dialog from another table is never kept open
setBankAdding(false);
}}
>
<PageHeader
title={t("BO_REFERENCE_DATA")}
actions={
<Button onClick={openAdd}>
<Plus aria-hidden="true" className="size-4" />
{t("CatAddRow")}
</Button>
}
/>
<TabsList aria-label={t("RfrTableAria")} className="mb-4 flex max-w-full justify-start overflow-x-auto">
{REFERENCE_TABLES.map((spec) => (
<TabsTrigger key={spec.key} value={spec.key}>{t(spec.label)}</TabsTrigger>
))}
<TabsTrigger value={BANK_KEY}>{t("Bank")}</TabsTrigger>
</TabsList>
<TabsContent value={tableKey}>
{isBank ? (
<BankPanel adding={bankAdding} onAddingChange={setBankAdding} />
) : (
<>
<FilterPanel className="mb-4" activeCount={search.trim() ? 1 : 0} onClear={() => { setSearch(""); setPage(1); }}>
<FilterField label={t("CatCodeOrName")}>
<FilterSearch aria-label={t("CatCodeOrName")} placeholder={t("CatCodeOrName")} value={search} onChange={(q) => { setSearch(q); setPage(1); }} />
</FilterField>
</FilterPanel>
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
{/* A failed fetch must not leave the previous table's rows on screen: the grid is gated
on !error, so switching tables with the new fetch failing shows only the error
banner — never stale rows under the new table's headers. */}
{loading ? (
<div ref={tableRef}><TableSkeleton columns={spec.columns.length + 1} /></div>
) : error ? null : rows.length === 0 ? (
<EmptyState title={t("RfrNoRowsYet", { table: t(spec.label).toLowerCase() })} />
) : shownRows.length === 0 ? (
<EmptyState title={t("CatNoRowsMatch")} />
) : (
<div ref={tableRef}>
<div className="overflow-hidden rounded-table border bg-card">
<Table>
<TableHeader>
<TableRow>
{spec.columns.map((col) => (
<SortableHead
key={col.field}
label={t(col.label)}
sortKey={col.field}
sorting={sorting}
onSortingChange={(s) => { setSorting(s); setPage(1); }}
/>
))}
<TableHead className="w-24 text-right">{t("CatActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{pagedRows.map((row) => (
<TableRow key={row.id ?? row.code}>
{spec.columns.map((col) => (
<TableCell key={col.field}>{cellText(col, valueFor(row, col.field), t)}</TableCell>
))}
<TableCell>
<div className="flex items-center justify-end">
<Button
variant="ghost"
size="sm"
aria-label={t("LocalesEditRow", { code: row.code })}
onClick={() => openEdit(row)}
className="h-8 px-2"
>
<Pencil aria-hidden="true" className="size-3.5" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<TablePager page={current} pageSize={size} total={shownRows.length} onPageChange={setPage} />
</div>
)}
{dialog && (
<ReferenceFormDialog
spec={spec}
mode={dialog.mode}
id={dialog.id}
initial={dialog.values}
onClose={() => setDialog(null)}
onSaved={refetch}
t={t}
/>
)}
</>
)}
</TabsContent>
</Tabs>
);
}
export default function ReferencePage() {
return (
<RequireModule pathname="/reference">
<ReferencePageContent />
</RequireModule>
);
}