Files
co-lite/solvway-admin-portal/app/reference/BankPanel.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

412 lines
14 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import { Pencil } from "lucide-react";
import type { SortingState } from "@tanstack/react-table";
import { Button } from "@/app/components/ui/button";
import { SortableHead, sortRows } from "@/app/components/ui/sortable-head";
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 { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states";
import {
createBank,
listBankCountries,
listBanks,
updateBank,
type BankRowPayload,
} from "@/app/lib/services/adminBank";
import type { BankCountry, BankRow } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import type { Translate } from "@/app/lib/i18n/t";
// Bank tab of the /reference page (add-admin-bank-reference, spec "admin-portal-reference-ui").
// Banks are listed per active country; code is unique within a country and, like the other
// reference tables, immutable after create. Country is fixed per bank, so the dialog shows it
// read-only. The page's "Add row" button drives `adding`; the panel owns the dialog.
type OptionalField = "swiftCode" | "bnmCode" | "bankid" | "branchCode" | "messageTag";
const OPTIONAL_FIELDS: { field: OptionalField; label: string; maxLength: number }[] = [
{ field: "swiftCode", label: "RfrSwiftCode", maxLength: 255 },
{ field: "bnmCode", label: "RfrBnmCode", maxLength: 200 },
{ field: "bankid", label: "RfrBankId", maxLength: 255 },
{ field: "branchCode", label: "RfrBranchCode", maxLength: 20 },
{ field: "messageTag", label: "RfrMessageTag", maxLength: 255 },
];
const COLUMNS: { field: keyof BankRow; label: string }[] = [
{ field: "code", label: "Code" },
{ field: "name", label: "CatName" },
{ field: "swiftCode", label: "RfrSwift" },
{ field: "bnmCode", label: "RfrBnmCode" },
{ field: "bankid", label: "RfrBankId" },
{ field: "branchCode", label: "RfrBranchCode" },
{ field: "messageTag", label: "RfrMessageTag" },
];
function messageOf(err: unknown, fallback: string): string {
return err instanceof Error ? err.message : fallback;
}
function BankFormDialog({
country,
bank,
onClose,
onSaved,
t,
}: {
country: BankCountry;
bank: BankRow | null;
onClose: () => void;
onSaved: () => void;
t: Translate;
}) {
const isEdit = bank != null;
const codeRef = useRef<HTMLInputElement>(null);
const nameRef = useRef<HTMLInputElement>(null);
const [values, setValues] = useState<Record<string, string>>(() => {
const initial: Record<string, string> = { code: bank?.code ?? "", name: bank?.name ?? "" };
for (const { field } of OPTIONAL_FIELDS) initial[field] = bank?.[field] ?? "";
return initial;
});
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
function setField(field: string, value: string) {
setValues((prev) => ({ ...prev, [field]: value }));
}
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const code = values.code.trim();
const name = values.name.trim();
if (!code || !name) {
setError("RfrBankCodeNameRequired");
return;
}
// Every optional field is sent, "" included, so clearing a field on edit really clears it.
const payload: BankRowPayload = { code, name, countryCode: country.code };
for (const { field } of OPTIONAL_FIELDS) payload[field] = values[field].trim();
setSaving(true);
setError(null);
try {
if (isEdit && bank.id != null) {
await updateBank(bank.id, payload);
} else {
await createBank(payload);
}
onSaved();
onClose();
} catch (err) {
// A duplicate-code 409 / validation 422 is reported inline; the dialog stays open.
setError(messageOf(err, "RfrBankSaveFailed"));
} finally {
setSaving(false);
}
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent
className="max-h-[90vh] overflow-y-auto"
onOpenAutoFocus={(event) => {
event.preventDefault();
// Radix's default auto-focus lands on the first focusable field, which is the
// read-only Country input (Code too, on edit) — focus the first EDITABLE field instead.
(isEdit ? nameRef : codeRef).current?.focus();
}}
>
<DialogHeader>
<DialogTitle>{t(isEdit ? "RfrBankEditTitle" : "RfrBankAddTitle", isEdit ? { code: bank.code } : { country: country.name })}</DialogTitle>
</DialogHeader>
{error && <ErrorState message={t(error)} />}
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
<div className="space-y-1.5">
<Label htmlFor="bank-country-ro">{t("Country")}</Label>
<Input id="bank-country-ro" value={country.name} readOnly className="opacity-70" />
</div>
<div className="space-y-1.5">
<Label htmlFor="bank-code">{t("Code")}</Label>
<Input
id="bank-code"
ref={codeRef}
required
readOnly={isEdit}
disabled={saving}
value={values.code}
onChange={(e) => setField("code", e.target.value)}
className={isEdit ? "opacity-70" : undefined}
/>
{isEdit && (
<p className="text-xs text-muted-foreground">
{t("RfrBankCodeImmutableNote")}
</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="bank-name">{t("CatName")}</Label>
<Input
id="bank-name"
ref={nameRef}
required
disabled={saving}
maxLength={255}
value={values.name}
onChange={(e) => setField("name", e.target.value)}
/>
</div>
{OPTIONAL_FIELDS.map(({ field, label, maxLength }) => (
<div key={field} className="space-y-1.5">
<Label htmlFor={`bank-${field}`}>{t(label)}</Label>
<Input
id={`bank-${field}`}
disabled={saving}
maxLength={maxLength}
value={values[field]}
onChange={(e) => setField(field, e.target.value)}
/>
</div>
))}
<DialogFooter>
<Button type="submit" disabled={saving}>
{t("Save")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
export function BankPanel({
adding,
onAddingChange,
}: {
adding: boolean;
onAddingChange: (open: boolean) => void;
}) {
const t = useT();
const [countries, setCountries] = useState<BankCountry[] | null>(null);
const [countryCode, setCountryCode] = useState("");
const [rows, setRows] = useState<BankRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [query, setQuery] = useState("");
const [editing, setEditing] = useState<BankRow | null>(null);
const [sorting, setSorting] = useState<SortingState>([]);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
const country = countries?.find((c) => c.code === countryCode) ?? null;
// Add was requested (countries still loading, load failed, or none active) before a country was
// ready: treat the click as a no-op instead of leaving it pending for a delayed pop-up once a
// country becomes available.
useEffect(() => {
if (adding && !country) onAddingChange(false);
}, [adding, country, onAddingChange]);
// Countries load once; a retry after a failed load re-runs this (countries stays null).
useEffect(() => {
if (countries) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the fetch below; the fetch itself is the actual synchronization.
setLoading(true);
setError(null);
listBankCountries()
.then((list) => {
if (cancelled) return;
setCountries(list);
if (list.length > 0) setCountryCode(list[0].code);
else setLoading(false);
})
.catch((err: unknown) => {
if (cancelled) return;
setError(messageOf(err, "RfrBankLoadCountriesFailed"));
setLoading(false);
});
return () => {
cancelled = true;
};
}, [countries, reloadKey]);
useEffect(() => {
if (!countryCode) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the fetch below; the fetch itself is the actual synchronization.
setLoading(true);
setError(null);
listBanks(countryCode)
.then((result) => {
if (!cancelled) setRows(result);
})
.catch((err: unknown) => {
if (!cancelled) setError(messageOf(err, "RfrBankLoadFailed"));
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [countryCode, reloadKey]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
const matched = q
? rows.filter((r) => r.code.toLowerCase().includes(q) || r.name.toLowerCase().includes(q))
: rows;
const getters = Object.fromEntries(COLUMNS.map((c) => [c.field, (r: BankRow) => r[c.field]]));
return sortRows(matched, sorting, getters);
}, [rows, query, sorting]);
const total = rows.length;
const shown = filtered.length;
const countLabel = query.trim()
? t("RfrBankCountFiltered", { shown, total })
: t(total === 1 ? "RfrBankCountOne" : "RfrBankCountMany", { count: total });
function closeDialog() {
setEditing(null);
onAddingChange(false);
}
if (countries && countries.length === 0) {
return (
<EmptyState title={t("RfrBankNoCountries")} />
);
}
return (
<>
<div className="mb-4 flex flex-wrap items-end gap-3">
<div className="space-y-1.5">
<Label htmlFor="bank-country">{t("Country")}</Label>
<Select
value={countryCode}
onValueChange={(code) => {
setCountryCode(code);
setQuery("");
setRows([]);
setLoading(true);
setError(null);
}}
disabled={!countries}
>
<SelectTrigger id="bank-country" aria-label={t("Country")} className="w-48">
<SelectValue placeholder={t("Country")} />
</SelectTrigger>
<SelectContent>
{(countries ?? []).map((c) => (
<SelectItem key={c.code} value={c.code}>
{c.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="w-full max-w-xs space-y-1.5">
<Label htmlFor="bank-search">{t("KycSearch")}</Label>
<Input
id="bank-search"
type="search"
placeholder={t("CatCodeOrName")}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
</div>
<p className="ml-auto text-sm text-muted-foreground" aria-live="polite">
{loading || error ? "" : countLabel}
</p>
</div>
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
{/* Gated on !loading && !error so a failed or in-flight fetch never shows another
country's rows under this country's filter. */}
{loading ? (
<TableSkeleton columns={COLUMNS.length + 1} />
) : error ? null : rows.length === 0 ? (
<EmptyState title={t("RfrBankEmptyForCountry", { country: country?.name ?? t("RfrBankThisCountry") })} />
) : filtered.length === 0 ? (
<EmptyState title={t("RfrBankNoMatch", { query: query.trim() })} />
) : (
<div className="overflow-hidden rounded-table border bg-card">
<Table>
<TableHeader>
<TableRow>
{COLUMNS.map((col) => (
<SortableHead key={col.field} label={t(col.label)} sortKey={col.field} sorting={sorting} onSortingChange={setSorting} />
))}
<TableHead className="w-24 text-right">{t("CatActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filtered.map((row) => (
<TableRow key={row.id ?? row.code}>
{COLUMNS.map((col) => (
<TableCell key={col.field}>{row[col.field] || "—"}</TableCell>
))}
<TableCell>
<div className="flex items-center justify-end">
<Button
variant="ghost"
size="sm"
aria-label={t("LocalesEditRow", { code: row.code })}
onClick={() => setEditing(row)}
className="h-8 px-2"
>
<Pencil aria-hidden="true" className="size-3.5" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
{country && (adding || editing) && (
<BankFormDialog
key={editing?.id ?? "new"}
country={country}
bank={editing}
onClose={closeDialog}
onSaved={refetch}
t={t}
/>
)}
</>
);
}