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

731 lines
25 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
import {
ChevronDown,
ChevronRight,
Pencil,
Plus,
Trash2,
type LucideIcon,
} from "lucide-react";
import { Badge } from "@/app/components/ui/badge";
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,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/app/components/ui/dialog";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/app/components/ui/table";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states";
import { iconFor, ICON_NAMES } from "@/app/components/app/icon-map";
import { RequireModule } from "@/app/lib/RequireModule";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import type { Translate } from "@/app/lib/i18n/t";
import { isProtectedModuleName } from "@/app/lib/protectedModules";
import {
createModule,
deleteModule,
listModules,
updateModule,
type ModuleNodePayload,
} from "@/app/lib/services/adminModules";
import { filterModuleNodes } from "./filterModuleNodes";
import { FilterPanel, FilterField, FilterSearch } from "@/app/components/ui/filter-panel";
import type { ModuleNode } from "@/app/lib/types";
// `/modules` module-tree management (spec "admin-portal-module-ui"): shows the
// Area-'BO' module tree (nested by parentId) and supports create / edit
// (including reparent) / delete. The sidebar, route-gate and ACL grant matrix
// all derive from these rows, so the page is super-admin-gated server-side for
// every write; this client page only renders. Wrapped in RequireModule against
// the seeded BO_MODULES module (id 41700000, operator SQL — the page manages
// the tree it lives in, so its own node cannot be created from here).
//
// Post-create honesty (spec "A New Node's Presentation Gaps Are Disclosed"):
// a live-created node whose name has no defaultMessages/catalog entry renders
// its raw name, and an iconName outside the icon-map.ts allowlist renders the
// fallback icon — closing those gaps is a code change in defaultMessages.ts /
// icon-map.ts, stated in the create dialog.
interface TreeNode {
node: ModuleNode;
children: TreeNode[];
}
/** Nest the flat tree by parentId; children sort by id (id-driven sidebar order). */
function buildTree(nodes: ModuleNode[]): TreeNode[] {
const ids = new Set(nodes.map((n) => n.id));
const byParent = new Map<number | null, ModuleNode[]>();
for (const n of nodes) {
// A node is a root when its parent is null OR absent from the response. The module
// API never returns BO_ROOT, so every real top-level node is parented to an id that
// is not in the list; keying those under null roots them — mirroring the sidebar,
// which shows the same top-level modules with no visible root, and the server's
// dangling-parent-is-null (@NotFound IGNORE) convention. Keying only on parentId==null
// collapsed the whole tree against real data.
const key = n.parentId != null && ids.has(n.parentId) ? n.parentId : null;
const list = byParent.get(key) ?? [];
list.push(n);
byParent.set(key, list);
}
for (const list of byParent.values()) list.sort((a, b) => a.id - b.id);
return (byParent.get(null) ?? []).map((n) => toTreeNode(n, byParent));
}
function toTreeNode(node: ModuleNode, byParent: Map<number | null, ModuleNode[]>): TreeNode {
return {
node,
children: (byParent.get(node.id) ?? []).map((c) => toTreeNode(c, byParent)),
};
}
/** A category is a module whose id is a multiple of 100000; other modules are slots. */
const isCategory = (n: ModuleNode) => n.type === "M" && n.id % 100000 === 0;
/** Candidate parents: every non-Action node except the node itself and its descendants. */
function parentOptions(nodes: ModuleNode[], excludeId?: number): ModuleNode[] {
if (excludeId == null) {
return nodes.filter((n) => n.type !== "A");
}
const byParent = new Map<number | null, ModuleNode[]>();
for (const n of nodes) {
const list = byParent.get(n.parentId) ?? [];
list.push(n);
byParent.set(n.parentId, list);
}
const excluded = new Set<number>();
const stack = [excludeId];
while (stack.length > 0) {
const id = stack.pop() as number;
excluded.add(id);
for (const child of byParent.get(id) ?? []) stack.push(child.id);
}
return nodes.filter((n) => n.type !== "A" && !excluded.has(n.id));
}
// Radix SelectItem forbids "", so null parent is TOP_LEVEL in create (edit keeps "").
const TOP_LEVEL = "top";
function typeLabel(type: ModuleNode["type"], t: Translate): string {
if (type === "R") return t("ModulesTypeRoot");
if (type === "A") return t("ModulesTypeAction");
return t("ModulesTypeModule");
}
interface FormState {
id?: number;
name: string;
desc: string;
type: "R" | "M" | "A";
url: string;
iconName: string;
parentId: number | null;
}
const EMPTY_FORM: FormState = {
name: "",
desc: "",
type: "M",
url: "",
iconName: "Settings",
parentId: null,
};
function NameHintAdd({ t }: { t: Translate }) {
const parts = t("ModulesNameHintAdd").split(/\{(defaults|pathDefaults|pathIconMap)\}/);
return (
<p className="text-xs text-muted-foreground">
{parts.map((part, i) => {
if (part === "defaults") return <code key={i}>{"DEFAULT_MESSAGES"}</code>;
if (part === "pathDefaults") return <code key={i}>{"app/lib/i18n/defaultMessages.ts"}</code>;
if (part === "pathIconMap") return <code key={i}>{"app/components/app/icon-map.ts"}</code>;
return <span key={i}>{part}</span>;
})}
</p>
);
}
function IconHint({ t }: { t: Translate }) {
const [pre, post] = t("ModulesIconHint").split("{iconMap}");
return (
<p className="text-xs text-muted-foreground">
{pre}<code>{"icon-map.ts"}</code>{post}
</p>
);
}
function ModuleFormDialog({
mode,
initial,
nodes,
onClose,
onSaved,
}: {
mode: "add" | "edit";
initial: FormState;
nodes: ModuleNode[];
onClose: () => void;
onSaved: () => void;
}) {
const t = useT();
const [form, setForm] = useState<FormState>(initial);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const isEdit = mode === "edit";
// Protected nodes keep ONLY desc/icon editable — reparent/type/url would
// break their hardcoded consumers (server also refuses them, 422).
const structuralLocked = isEdit && isProtectedModuleName(form.name);
// Create only: an Action belongs to a module (id source), never a leaf/action; others may be top level.
const belongsTo = !isEdit && form.type === "A";
const parents = useMemo(() => {
const opts = parentOptions(nodes, isEdit ? form.id : undefined);
if (belongsTo) return opts.filter((n) => n.type === "M");
if (isEdit) return opts;
// A Module hangs under a category (or top level), never under a slot.
return opts.filter((n) => (form.type === "M" ? isCategory(n) : n.type !== "R"));
}, [nodes, isEdit, form.id, form.type, belongsTo]);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
if (belongsTo && form.parentId == null) {
setError("ModulesActionNeedsModule");
return;
}
setSaving(true);
try {
const payload: ModuleNodePayload = {
name: form.name.trim(),
desc: form.desc.trim(),
type: form.type,
url: form.url.trim(),
iconName: form.iconName,
parentId: form.parentId,
};
if (form.id != null) {
await updateModule(form.id, payload);
} else {
await createModule(payload);
}
onSaved();
onClose();
} catch (err) {
// A duplicate name (409) / invalid parent / protected node (422) surfaces
// here as the downstream message — reported inline, never a silent no-op.
setError(err instanceof Error ? err.message : "ModulesSaveFailed");
} finally {
setSaving(false);
}
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{isEdit ? t("ModulesEdit") : t("ModulesAdd")}</DialogTitle>
<DialogDescription>
{isEdit
? t("ModulesEditHint")
: t("ModulesAddHint")}
</DialogDescription>
</DialogHeader>
{error && <ErrorState message={t(error)} />}
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
<div className="space-y-1.5">
<Label htmlFor="module-name">{t("ModulesName")}</Label>
<Input
id="module-name"
required
readOnly={isEdit}
disabled={saving}
placeholder={t("ModulesNamePlaceholder")}
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
className={isEdit ? "opacity-70" : undefined}
/>
{isEdit ? (
<p className="text-xs text-muted-foreground">
{t("ModulesNameHintEdit")}
</p>
) : (
<NameHintAdd t={t} />
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="module-desc">{t("Description")}</Label>
<Input
id="module-desc"
placeholder={t("ModulesDescriptionPlaceholder")}
value={form.desc}
onChange={(e) => setForm((f) => ({ ...f, desc: e.target.value }))}
disabled={saving}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="module-type">{t("Type")}</Label>
<Select
value={form.type}
onValueChange={(v) =>
setForm((f) => {
const parent = nodes.find((n) => n.id === f.parentId);
const keep =
isEdit || (v === "A" ? parent?.type === "M" : v !== "M" || !parent || isCategory(parent));
return { ...f, type: v as "R" | "M" | "A", parentId: keep ? f.parentId : null };
})
}
disabled={saving || structuralLocked}
>
<SelectTrigger id="module-type" className="w-full" data-testid="module-type-select">
<SelectValue placeholder={t("Type")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="M">{t("ModulesTypeModule")}</SelectItem>
<SelectItem value="A">{t("ModulesTypeAction")}</SelectItem>
{/* Root is not a user-choosable type — the tree has exactly one seeded root
and the server refuses to create another (only M/A). Render it solely so an
existing Root node (structurally locked) can display its current value. */}
{form.type === "R" && <SelectItem value="R">{t("ModulesTypeRoot")}</SelectItem>}
</SelectContent>
</Select>
{structuralLocked && (
<p className="text-xs text-muted-foreground">
{t("ModulesProtectedHint")}
</p>
)}
{isEdit && !structuralLocked && form.type !== initial.type && (
<p className="text-xs text-warning">
{form.type === "A"
? t("ModulesChangeToAction")
: t("ModulesChangeToModule")}
</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="module-url">{t("ModulesUrl")}</Label>
<Input
id="module-url"
placeholder={t("ModulesUrlPlaceholder")}
value={form.url}
onChange={(e) => setForm((f) => ({ ...f, url: e.target.value }))}
disabled={saving || structuralLocked}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="module-icon">{t("ModulesIcon")}</Label>
<Select
value={form.iconName}
onValueChange={(v) => setForm((f) => ({ ...f, iconName: v }))}
disabled={saving}
>
<SelectTrigger id="module-icon" className="w-full" data-testid="module-icon-select">
<SelectValue placeholder={t("ModulesIcon")} />
</SelectTrigger>
<SelectContent>
{ICON_NAMES.map((name) => (
<SelectItem key={name} value={name}>
{name}
</SelectItem>
))}
</SelectContent>
</Select>
<IconHint t={t} />
</div>
<div className="space-y-1.5">
<Label htmlFor="module-parent">{belongsTo ? t("ModulesBelongsTo") : t("ModulesParent")}</Label>
<Select
value={form.parentId == null ? (isEdit ? "" : TOP_LEVEL) : String(form.parentId)}
onValueChange={(v) => setForm((f) => ({ ...f, parentId: v === "" || v === TOP_LEVEL ? null : Number(v) }))}
disabled={saving || structuralLocked}
>
<SelectTrigger id="module-parent" className="w-full" data-testid="module-parent-select">
<SelectValue placeholder={t("ModulesParentGroup")} />
</SelectTrigger>
<SelectContent>
{!isEdit && !belongsTo && <SelectItem value={TOP_LEVEL}>{t("ModulesTopLevel")}</SelectItem>}
{parents.map((p) => (
<SelectItem key={p.id} value={String(p.id)}>
{t(p.name)} ({p.name})
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
{belongsTo ? t("ModulesBelongsToHint") : t("ModulesParentHint")}
</p>
</div>
<DialogFooter>
<Button type="submit" disabled={saving}>
{t("Save")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
function DeleteModuleDialog({
target,
onClose,
onDeleted,
}: {
target: ModuleNode;
onClose: () => void;
onDeleted: () => void;
}) {
const t = useT();
const [deleting, setDeleting] = useState(false);
const [error, setError] = useState<string | null>(null);
const label = t(target.name);
async function confirmDelete() {
setDeleting(true);
setError(null);
try {
await deleteModule(target.id);
onDeleted();
onClose();
} catch (err) {
// The has-children (422) and protected-name (422) refusals land here as
// the downstream message — shown inline, the dialog stays open.
setError(err instanceof Error ? err.message : "ModulesDeleteFailed");
} finally {
setDeleting(false);
}
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("ModulesDeleteTitle", { label })}</DialogTitle>
<DialogDescription>
{t(target.grantCount === 1 ? "ModulesDeleteBodyOne" : "ModulesDeleteBodyMany", { count: target.grantCount })}
</DialogDescription>
</DialogHeader>
{error && <ErrorState message={t(error)} />}
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={deleting}>
{t("Cancel")}
</Button>
<Button variant="destructive" onClick={confirmDelete} disabled={deleting}>
{t("Delete")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
function ModuleTreeRow({
item,
depth,
expanded,
onToggle,
onEdit,
onDelete,
onAddChild,
}: {
item: TreeNode;
depth: number;
expanded: Set<number>;
onToggle: (id: number) => void;
onEdit: (node: ModuleNode) => void;
onDelete: (node: ModuleNode) => void;
onAddChild: (node: ModuleNode) => void;
}) {
const t = useT();
const { node, children } = item;
const hasChildren = children.length > 0;
const isExpanded = expanded.has(node.id);
const Icon: LucideIcon = iconFor(node.iconName);
const label = t(node.name);
const protectedNode = isProtectedModuleName(node.name);
return (
<>
<TableRow>
<TableCell>
<div
className="flex items-center gap-2"
style={{ paddingLeft: `${depth * 20}px` }}
>
{hasChildren ? (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0"
aria-label={isExpanded ? t("ModulesCollapseRow", { label }) : t("ModulesExpandRow", { label })}
onClick={() => onToggle(node.id)}
>
{isExpanded ? (
<ChevronDown aria-hidden="true" className="size-3.5" />
) : (
<ChevronRight aria-hidden="true" className="size-3.5" />
)}
</Button>
) : (
<span className="inline-block w-6" />
)}
{/* eslint-disable-next-line react-hooks/static-components -- iconFor returns a component from a module-level map, so its identity is stable across renders. */}
<Icon aria-hidden="true" className="size-4 shrink-0" />
<div>
<span className="font-medium">{label}</span>
{label !== node.name && <code className="block text-xs text-muted-foreground">{node.name}</code>}
</div>
{protectedNode && <Badge variant="outline">{t("ModulesProtected")}</Badge>}
</div>
</TableCell>
<TableCell>{typeLabel(node.type, t)}</TableCell>
<TableCell>{node.url || "—"}</TableCell>
<TableCell className="text-right tabular">{node.grantCount}</TableCell>
<TableCell>
<div className="flex items-center justify-end gap-1">
{node.type === "M" && (
<Button
variant="ghost"
size="sm"
className="h-8 px-2"
aria-label={t("ModulesAddChildRow", { label })}
onClick={() => onAddChild(node)}
>
<Plus aria-hidden="true" className="size-3.5" />
</Button>
)}
<Button
variant="ghost"
size="sm"
className="h-8 px-2"
aria-label={t("ModulesEditRow", { label })}
onClick={() => onEdit(node)}
>
<Pencil aria-hidden="true" className="size-3.5" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 px-2 text-destructive hover:text-destructive"
aria-label={t("ModulesDeleteRow", { label })}
onClick={() => onDelete(node)}
>
<Trash2 aria-hidden="true" className="size-3.5" />
</Button>
</div>
</TableCell>
</TableRow>
{hasChildren &&
isExpanded &&
children.map((child) => (
<ModuleTreeRow
key={child.node.id}
item={child}
depth={depth + 1}
expanded={expanded}
onToggle={onToggle}
onEdit={onEdit}
onDelete={onDelete}
onAddChild={onAddChild}
/>
))}
</>
);
}
function ModulesPageContent() {
const t = useT();
const [nodes, setNodes] = useState<ModuleNode[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [expanded, setExpanded] = useState<Set<number>>(new Set());
const [formDialog, setFormDialog] = useState<{ mode: "add" | "edit"; initial: FormState } | null>(null);
const [deleteTarget, setDeleteTarget] = useState<ModuleNode | null>(null);
const [search, setSearch] = useState("");
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error ahead of the reload-triggered fetch below, which is the actual synchronization.
setLoading(true);
setError(null);
listModules()
.then((result) => {
if (cancelled) return;
setNodes(result);
// Groups (nodes with children) start expanded so the tree is visible.
const ids = new Set<number>();
for (const n of result) {
if (result.some((m) => m.parentId === n.id)) ids.add(n.id);
}
setExpanded((prev) => new Set([...prev, ...ids]));
})
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : "ModulesLoadFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [reloadKey]);
const searching = search.trim() !== "";
const tree = useMemo(() => buildTree(filterModuleNodes(nodes, search, t)), [nodes, search, t]);
// While searching every remaining group is open, so each match is visible in place.
const shownExpanded = useMemo(() => (searching ? new Set(nodes.map((n) => n.id)) : expanded), [searching, nodes, expanded]);
function toggle(id: number) {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
function openAdd(parentNode?: ModuleNode) {
setFormDialog({
mode: "add",
initial: {
...EMPTY_FORM,
type: parentNode && !isCategory(parentNode) ? "A" : EMPTY_FORM.type,
parentId: parentNode?.id ?? null,
},
});
}
function openEdit(node: ModuleNode) {
setFormDialog({
mode: "edit",
initial: {
id: node.id,
name: node.name,
desc: node.desc ?? "",
type: node.type ?? "M",
url: node.url ?? "",
iconName: node.iconName ?? "Settings",
parentId: node.parentId,
},
});
}
return (
<>
<PageHeader
title={t("BO_MODULES")}
actions={
<Button onClick={() => openAdd()}>
<Plus aria-hidden="true" className="size-4" />
{t("ModulesAdd")}
</Button>
}
/>
<FilterPanel className="mb-4" activeCount={searching ? 1 : 0} onClear={() => setSearch("")}>
<FilterField label={t("ModulesSearchLabel")}>
<FilterSearch aria-label={t("ModulesSearchLabel")} placeholder={t("ModulesSearchLabel")} value={search} onChange={setSearch} />
</FilterField>
</FilterPanel>
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
{/* The empty state must never masquerade as truth next to an error banner: a failed
listModules leaves nodes == [] but the tree may be fine. */}
{loading ? (
<TableSkeleton columns={5} />
) : !error && tree.length === 0 ? (
<EmptyState title={searching ? t("ModulesNoMatch") : t("ModulesEmpty")} />
) : (
<div className="overflow-hidden rounded-table border bg-card">
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("ModulesNode")}</TableHead>
<TableHead>{t("Type")}</TableHead>
<TableHead>{t("ModulesUrl")}</TableHead>
<TableHead className="text-right tabular">{t("ModulesGrants")}</TableHead>
<TableHead className="w-36 text-right">{t("ModulesActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{tree.map((item) => (
<ModuleTreeRow
key={item.node.id}
item={item}
depth={0}
expanded={shownExpanded}
// Searching shows every group open; collapsing then would silently change the hidden state.
onToggle={searching ? () => {} : toggle}
onEdit={openEdit}
onDelete={setDeleteTarget}
onAddChild={(node) => openAdd(node)}
/>
))}
</TableBody>
</Table>
</div>
)}
{formDialog && (
<ModuleFormDialog
mode={formDialog.mode}
initial={formDialog.initial}
nodes={nodes}
onClose={() => setFormDialog(null)}
onSaved={refetch}
/>
)}
{deleteTarget && (
<DeleteModuleDialog
target={deleteTarget}
onClose={() => setDeleteTarget(null)}
onDeleted={refetch}
/>
)}
</>
);
}
export default function ModulesPage() {
return (
<RequireModule pathname="/modules">
<ModulesPageContent />
</RequireModule>
);
}