"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(); 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): 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(); for (const n of nodes) { const list = byParent.get(n.parentId) ?? []; list.push(n); byParent.set(n.parentId, list); } const excluded = new Set(); 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 (

{parts.map((part, i) => { if (part === "defaults") return {"DEFAULT_MESSAGES"}; if (part === "pathDefaults") return {"app/lib/i18n/defaultMessages.ts"}; if (part === "pathIconMap") return {"app/components/app/icon-map.ts"}; return {part}; })}

); } function IconHint({ t }: { t: Translate }) { const [pre, post] = t("ModulesIconHint").split("{iconMap}"); return (

{pre}{"icon-map.ts"}{post}

); } 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(initial); const [saving, setSaving] = useState(false); const [error, setError] = useState(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) { 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 ( !open && onClose()}> {isEdit ? t("ModulesEdit") : t("ModulesAdd")} {isEdit ? t("ModulesEditHint") : t("ModulesAddHint")} {error && }
setForm((f) => ({ ...f, name: e.target.value }))} className={isEdit ? "opacity-70" : undefined} /> {isEdit ? (

{t("ModulesNameHintEdit")}

) : ( )}
setForm((f) => ({ ...f, desc: e.target.value }))} disabled={saving} />
{structuralLocked && (

{t("ModulesProtectedHint")}

)} {isEdit && !structuralLocked && form.type !== initial.type && (

{form.type === "A" ? t("ModulesChangeToAction") : t("ModulesChangeToModule")}

)}
setForm((f) => ({ ...f, url: e.target.value }))} disabled={saving || structuralLocked} />

{belongsTo ? t("ModulesBelongsToHint") : t("ModulesParentHint")}

); } function DeleteModuleDialog({ target, onClose, onDeleted, }: { target: ModuleNode; onClose: () => void; onDeleted: () => void; }) { const t = useT(); const [deleting, setDeleting] = useState(false); const [error, setError] = useState(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 ( !open && onClose()}> {t("ModulesDeleteTitle", { label })} {t(target.grantCount === 1 ? "ModulesDeleteBodyOne" : "ModulesDeleteBodyMany", { count: target.grantCount })} {error && } ); } function ModuleTreeRow({ item, depth, expanded, onToggle, onEdit, onDelete, onAddChild, }: { item: TreeNode; depth: number; expanded: Set; 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 ( <>
{hasChildren ? ( ) : ( )} {/* eslint-disable-next-line react-hooks/static-components -- iconFor returns a component from a module-level map, so its identity is stable across renders. */}
{typeLabel(node.type, t)} {node.url || "—"} {node.grantCount}
{node.type === "M" && ( )}
{hasChildren && isExpanded && children.map((child) => ( ))} ); } function ModulesPageContent() { const t = useT(); const [nodes, setNodes] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [reloadKey, setReloadKey] = useState(0); const [expanded, setExpanded] = useState>(new Set()); const [formDialog, setFormDialog] = useState<{ mode: "add" | "edit"; initial: FormState } | null>(null); const [deleteTarget, setDeleteTarget] = useState(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(); 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 ( <> openAdd()}>