Files
Epicnabbo-Catalogus-Updated…/src/app/admin/housekeeping/client.tsx
T
openhands 70f5e37373 refactor(housekeeping): split client, add loading states, URL persistence, fix dead code
- Split ManageClient into ManageSection, PresetsSection, TestSection,
  ImportSection, ExportSection - each tab only renders what it needs
- Add loading/disabled states to preset, import, export, clear buttons
- Persist search and group filter via URL searchParams (survives refresh)
- Remove dead getAuditHistory export from actions
- Fix testRankPermission - remove unnecessary revalidatePath with JSON result
- Clean up unused errors/count variables in bulkImportPermissions
- Add 'loading' translation key to housekeeping section (en/nl)
2026-07-17 19:28:19 +02:00

617 lines
16 KiB
TypeScript

"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { useCallback, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import {
applyPreset,
bulkImportPermissions,
clearAllPermissions,
deletePermission,
exportPermissions,
testRankPermission,
upsertPermission,
} from "@/actions/admin-housekeeping";
const PAGE_SIZE = 25;
interface HKPerm {
id: bigint;
permission: string;
minRank: number;
description: string | null;
groupName: string | null;
dependsOn: string | null;
}
interface SharedProps {
permissions: HKPerm[];
groups: string[];
groupCounts: Record<string, number>;
permSet: Set<string>;
}
export function ManageSection(props: SharedProps) {
const t = useTranslations("pages.admin.housekeeping");
const router = useRouter();
const sp = useSearchParams();
const [search, setSearch] = useState(sp.get("search") ?? "");
const [groupFilter, setGroupFilter] = useState(sp.get("group") ?? "");
const [page, setPage] = useState(1);
const [pendingDel, setPendingDel] = useState<string | null>(null);
const filtered = useMemo(() => {
return props.permissions.filter((p) => {
if (search && !p.permission.toLowerCase().includes(search.toLowerCase()))
return false;
if (groupFilter && (p.groupName ?? "") !== groupFilter) return false;
return true;
});
}, [props.permissions, search, groupFilter]);
const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
const safePage = Math.min(page, totalPages);
const paginated = filtered.slice(
(safePage - 1) * PAGE_SIZE,
safePage * PAGE_SIZE,
);
const syncUrl = useCallback(
(s: string, g: string) => {
const params = new URLSearchParams();
if (s) params.set("search", s);
if (g) params.set("group", g);
const qs = params.toString();
router.replace(
"/admin/housekeeping?tab=manage" + (qs ? "&" + qs : ""),
{ scroll: false },
);
},
[router],
);
const handleUpsert = useCallback(
async (formData: FormData) => {
try {
await upsertPermission(formData);
toast.success(t("saved"));
router.refresh();
} catch {
toast.error(t("errorOccurred"));
}
},
[router, t],
);
const handleDelete = useCallback(
async (id: string) => {
if (!confirm(t("confirmDelete"))) return;
setPendingDel(id);
try {
const fd = new FormData();
fd.set("id", id);
await deletePermission(fd);
toast.success(t("deleted"));
router.refresh();
} catch {
toast.error(t("errorOccurred"));
}
setPendingDel(null);
},
[router, t],
);
return (
<div>
<div className="admin-filter-bar">
<div className="flex gap-2 flex-1 flex-wrap">
<input
value={search}
onChange={(e) => {
const v = e.target.value;
setSearch(v);
setPage(1);
syncUrl(v, groupFilter);
}}
placeholder={t("searchPermission")}
className="flex-1 min-w-[200px]"
/>
<select
value={groupFilter}
onChange={(e) => {
const v = e.target.value;
setGroupFilter(v);
setPage(1);
syncUrl(search, v);
}}
className="w-[180px]"
>
<option value="">{t("allGroups")}</option>
{props.groups.map((g) => (
<option key={g} value={g}>
{g} ({props.groupCounts[g] ?? 0})
</option>
))}
</select>
</div>
</div>
<section>
<h2 className="admin-section-title">
{t("addPermission")}
</h2>
<form
onSubmit={(e) => {
e.preventDefault();
handleUpsert(new FormData(e.currentTarget));
}}
className="admin-card"
>
<div className="flex gap-2 flex-wrap">
<input
name="permission"
placeholder={t("permissionKey")}
required
className="min-w-[200px] flex-1"
/>
<input
name="minRank"
type="number"
min={0}
placeholder={t("minRank")}
required
className="w-[110px]"
/>
<input
name="description"
placeholder={t("description")}
className="flex-1 min-w-[160px]"
/>
<select name="groupName" className="w-[150px]">
<option value="">{t("noGroup")}</option>
{props.groups.map((g) => (
<option key={g} value={g}>
{g}
</option>
))}
</select>
<input
name="dependsOn"
placeholder={t("dependsOn")}
className="min-w-[160px] flex-1"
/>
<button type="submit" className="btn btn-primary">
{t("save")}
</button>
</div>
</form>
</section>
<section>
<h2 className="admin-section-title">
{t("permissions")}{" "}
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--admin-accent)]/18 text-[var(--admin-text)]">
{filtered.length}
</span>
</h2>
{filtered.length === 0 ? (
<div className="admin-empty">{t("noPermissions")}</div>
) : (
<div className="overflow-x-auto">
<table>
<thead>
<tr>
<th className="w-[40px]">#</th>
<th>{t("colPermission")}</th>
<th>{t("colDescription")}</th>
<th className="w-[120px]">{t("colGroup")}</th>
<th className="w-[100px]">{t("colMinRank")}</th>
<th className="w-[180px]">{t("colDepends")}</th>
<th className="w-[80px]" />
</tr>
</thead>
<tbody>
{paginated.map((p, i) => (
<tr key={String(p.id)}>
<td className="muted w-[40px]">
{(safePage - 1) * PAGE_SIZE + i + 1}
</td>
<td>
<strong>{p.permission}</strong>
</td>
<td className="muted">{p.description || "\u2014"}</td>
<td>
{p.groupName ? (
<span className="inline-block px-2 py-0.5 rounded-full bg-[var(--admin-accent)]/12 text-xs font-medium">
{p.groupName}
</span>
) : (
<span className="text-xs opacity-50">\u2014</span>
)}
</td>
<td>
<form
onSubmit={(e) => {
e.preventDefault();
handleUpsert(new FormData(e.currentTarget));
}}
style={{ display: "flex", gap: "0.5rem" }}
>
<input
type="hidden"
name="permission"
value={p.permission}
/>
<input
type="hidden"
name="description"
value={p.description ?? ""}
/>
<input
type="hidden"
name="groupName"
value={p.groupName ?? ""}
/>
<input
type="hidden"
name="dependsOn"
value={p.dependsOn ?? ""}
/>
<input
name="minRank"
type="number"
min={0}
defaultValue={p.minRank}
style={{ width: 80 }}
/>
<button
type="submit"
className="btn btn-outline btn-sm"
>
{t("save")}
</button>
</form>
</td>
<td className="text-xs">
{p.dependsOn ? (
<span
className={
props.permSet.has(p.dependsOn)
? "opacity-70"
: "opacity-100 font-semibold"
}
style={
!props.permSet.has(p.dependsOn)
? { color: "var(--color-danger)" }
: {}
}
>
{p.dependsOn}
{!props.permSet.has(p.dependsOn) ? " " + t("missing") : ""}
</span>
) : (
<span className="opacity-50">\u2014</span>
)}
</td>
<td>
<button
type="button"
className="btn btn-danger btn-sm"
onClick={() => handleDelete(String(p.id))}
disabled={pendingDel === String(p.id)}
>
{pendingDel === String(p.id) ? "..." : "\u2715"}
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2 mt-4">
<button
type="button"
className="btn btn-outline btn-sm"
disabled={safePage <= 1}
onClick={() => setPage(safePage - 1)}
>
{t("prev")}
</button>
<span className="text-xs opacity-60">
{safePage} / {totalPages}
</span>
<button
type="button"
className="btn btn-outline btn-sm"
disabled={safePage >= totalPages}
onClick={() => setPage(safePage + 1)}
>
{t("next")}
</button>
</div>
)}
</section>
</div>
);
}
export function PresetsSection() {
const t = useTranslations("pages.admin.housekeeping");
const router = useRouter();
const [busy, setBusy] = useState<string | null>(null);
const handleApplyPreset = useCallback(
async (preset: string) => {
setBusy(preset);
try {
const fd = new FormData();
fd.set("preset", preset);
await applyPreset(fd);
toast.success(t("presetApplied"));
router.refresh();
} catch {
toast.error(t("errorOccurred"));
}
setBusy(null);
},
[router, t],
);
const handleClearAll = useCallback(async () => {
if (!confirm(t("confirmClearAll"))) return;
setBusy("__clear__");
try {
await clearAllPermissions();
toast.success(t("cleared"));
router.refresh();
} catch {
toast.error(t("errorOccurred"));
}
setBusy(null);
}, [router, t]);
return (
<section>
<h2 className="admin-section-title">{t("presets")}</h2>
<p className="text-xs text-[var(--admin-text-muted)] -mt-2 mb-3">
{t("presetsHint")}
</p>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{(["moderator", "admin", "superadmin"] as const).map((preset) => {
const labels: Record<string, string> = {
moderator: t("presetModerator"),
admin: t("presetAdmin"),
superadmin: t("presetSuperAdmin"),
};
const descs: Record<string, string> = {
moderator: t("presetModeratorDesc"),
admin: t("presetAdminDesc"),
superadmin: t("presetSuperAdminDesc"),
};
const loading = busy === preset;
return (
<div key={preset} className="admin-card">
<h3 className="font-bold text-lg mb-1">{labels[preset]}</h3>
<p className="text-xs opacity-60 mb-3">{descs[preset]}</p>
<button
type="button"
onClick={() => handleApplyPreset(preset)}
disabled={loading || busy === "__clear__"}
className="btn btn-primary w-full"
>
{loading ? t("loading") : t("applyPreset")}
</button>
</div>
);
})}
</div>
<div className="mt-4">
<button
type="button"
onClick={handleClearAll}
disabled={busy !== null}
className="btn btn-danger"
>
{busy === "__clear__" ? t("loading") : t("clearAll")}
</button>
</div>
</section>
);
}
export function TestSection({ permissions }: { permissions: HKPerm[] }) {
const t = useTranslations("pages.admin.housekeeping");
const [testRank, setTestRank] = useState("");
const [testResult, setTestResult] = useState<{
rank: number;
permissions: string[];
} | null>(null);
const [testing, setTesting] = useState(false);
const handleTest = useCallback(async () => {
const rank = Number(testRank);
if (!Number.isFinite(rank) || rank < 0)
return toast.error(t("invalidRank"));
setTesting(true);
try {
const fd = new FormData();
fd.set("testRank", testRank);
await testRankPermission(fd);
const matching = permissions.filter((p) => p.minRank <= rank);
setTestResult({ rank, permissions: matching.map((p) => p.permission) });
toast.success(t("testDone", { count: matching.length }));
} catch {
toast.error(t("errorOccurred"));
}
setTesting(false);
}, [testRank, permissions, t]);
return (
<section>
<h2 className="admin-section-title">{t("testTitle")}</h2>
<p className="text-xs text-[var(--admin-text-muted)] -mt-2 mb-3">
{t("testHint")}
</p>
<div className="admin-card flex gap-2 flex-wrap">
<input
value={testRank}
onChange={(e) => setTestRank(e.target.value)}
type="number"
min={0}
placeholder={t("rank")}
className="w-[150px]"
/>
<button
type="button"
onClick={handleTest}
disabled={testing}
className="btn btn-primary"
>
{testing ? t("testing") : t("test")}
</button>
</div>
{testResult && (
<div className="admin-card mt-3">
<div className="font-semibold mb-2">
{t("rank")} {testResult.rank}: {testResult.permissions.length}{" "}
{t("permissions")}
</div>
<div className="max-h-48 overflow-y-auto text-xs space-y-0.5">
{testResult.permissions.map((p) => (
<div key={p} className="font-mono">
{p}
</div>
))}
</div>
</div>
)}
</section>
);
}
export function ImportSection() {
const t = useTranslations("pages.admin.housekeeping");
const router = useRouter();
const textareaRef = useRef<HTMLTextAreaElement>(null);
const [importing, setImporting] = useState(false);
const handleBulkImport = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const raw = String(fd.get("json") ?? "").trim();
if (!raw) return toast.error(t("emptyInput"));
try {
JSON.parse(raw);
} catch {
return toast.error(t("invalidJson"));
}
setImporting(true);
try {
await bulkImportPermissions(fd);
toast.success(t("imported"));
if (textareaRef.current) textareaRef.current.value = "";
router.refresh();
} catch {
toast.error(t("errorOccurred"));
}
setImporting(false);
},
[router, t],
);
return (
<section>
<h2 className="admin-section-title">{t("importTitle")}</h2>
<p className="text-xs text-[var(--admin-text-muted)] -mt-2 mb-3">
{t("importHint")}
</p>
<form onSubmit={handleBulkImport} className="admin-card">
<div className="flex flex-col gap-2">
<textarea
ref={textareaRef}
name="json"
placeholder={t("importPlaceholder")}
required
rows={6}
className="w-full font-mono text-sm"
/>
<button
type="submit"
disabled={importing}
className="btn btn-primary self-start"
>
{importing ? t("loading") : t("import")}
</button>
</div>
</form>
</section>
);
}
export function ExportSection() {
const t = useTranslations("pages.admin.housekeeping");
const [data, setData] = useState<string | null>(null);
const [copying, setCopying] = useState(false);
const [exporting, setExporting] = useState(false);
const handleExport = useCallback(async () => {
setExporting(true);
try {
const json = await exportPermissions();
setData(json);
} finally {
setExporting(false);
}
}, []);
const handleCopy = useCallback(async () => {
if (!data) return;
setCopying(true);
try {
await navigator.clipboard.writeText(data);
} catch {
/* fallback */
}
setTimeout(() => setCopying(false), 1500);
}, [data]);
return (
<section>
<h2 className="admin-section-title">{t("exportTitle")}</h2>
<p className="text-xs text-[var(--admin-text-muted)] -mt-2 mb-3">
{t("exportHint")}
</p>
<div>
<button
type="button"
onClick={handleExport}
disabled={exporting}
className="btn btn-outline mb-3"
>
{exporting ? t("loading") : t("export")}
</button>
{data && (
<div className="relative">
<pre className="admin-card font-mono text-xs overflow-auto max-h-[300px] p-3">
{data}
</pre>
<button
type="button"
onClick={handleCopy}
className="btn btn-outline btn-sm absolute top-2 right-2"
>
{copying ? t("copied") : t("copy")}
</button>
</div>
)}
</div>
</section>
);
}