Files
co-lite/solvway-admin-portal/app/roles/page.tsx
T
ngqileandClaude Opus 5.5 49966586ca fix(admin-portal): match the screens to the Co-Lite backend after the browser check
- Login copy describes the event CRM instead of orders and payouts.
- Role dialog has no parent field; the role routes require a trimmed name and forward only {name}.
- New-user banner says a temporary password was emailed; TEMP_PASSWORD_NOT_SENT shows a message and a link back to users.
- Username is read-only when editing.
- Password hint and an 8-character minimum match the backend admin password rules.

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

216 lines
6.4 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
import { Plus } from "lucide-react";
import type { ColumnDef, 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 { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
import { DataTable } from "@/app/components/ui/data-table";
import { sortRows } from "@/app/components/ui/sortable-head";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { roleLabel } from "@/app/lib/roleLabel";
import { listAdminRoles, saveAdminRole } from "@/app/lib/services/adminRoles";
import type { AdminRoleEntity } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
interface FormState {
id?: number;
name: string;
}
const EMPTY_FORM: FormState = { name: "" };
function RoleFormDialog({
initial,
onClose,
onSaved,
}: {
initial: FormState;
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);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!form.name.trim()) {
setError("RolNameRequired");
return;
}
setSaving(true);
setError(null);
try {
await saveAdminRole({ id: form.id, name: form.name.trim() });
onSaved();
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : "RolSaveFailed");
} finally {
setSaving(false);
}
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{form.id ? t("RolEditRole") : t("RolAddRole")}</DialogTitle>
</DialogHeader>
{error && <ErrorState message={t(error)} />}
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
<div className="space-y-1.5">
<Label htmlFor="role-name">{t("RolRoleName")}</Label>
<Input
id="role-name"
required
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
disabled={saving}
/>
</div>
<DialogFooter>
<Button type="submit" disabled={saving}>
{t("Save")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
function RolesPageContent() {
const t = useT();
const [roles, setRoles] = useState<AdminRoleEntity[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [sorting, setSorting] = useState<SortingState>([]);
const [dialog, setDialog] = useState<FormState | null>(null);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the reloadKey-triggered fetch below.
setLoading(true);
setError(null);
listAdminRoles()
.then((result) => {
if (!cancelled) setRoles(result);
})
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : "RolLoadFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [reloadKey]);
const parentName = useCallback(
(r: AdminRoleEntity) => {
const parent = roles.find((p) => p.id === r.parent?.id);
return parent ? roleLabel(parent.name) : null;
},
[roles],
);
const parentLabel = useCallback((r: AdminRoleEntity) => parentName(r) ?? "—", [parentName]);
const sorted = useMemo(
() => sortRows(roles, sorting, { name: (r) => roleLabel(r.name), parent: parentName }),
[roles, sorting, parentName],
);
const columns = useMemo<ColumnDef<AdminRoleEntity, unknown>[]>(
() => [
{
accessorKey: "name",
header: t("RolColRole"),
cell: ({ row }) => (
<div>
<div>{roleLabel(row.original.name)}</div>
<div className="text-xs text-muted-foreground">{row.original.name}</div>
</div>
),
},
{
id: "parent",
accessorFn: parentLabel,
header: t("ModulesParent"),
cell: ({ row }) => parentLabel(row.original),
},
{
id: "actions",
header: t("CatActions"),
cell: ({ row }) => (
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setDialog({ id: row.original.id, name: row.original.name })}
>
{t("Edit")}
</Button>
<Button variant="outline" size="sm" asChild>
<a href={`/roles/${row.original.id}/access`}>{t("RolManageAccess")}</a>
</Button>
</div>
),
},
],
[parentLabel, t],
);
return (
<>
<PageHeader
title={t("BO_ROLES")}
actions={
<Button onClick={() => setDialog(EMPTY_FORM)}>
<Plus aria-hidden="true" className="size-4" />
{t("RolAddRole")}
</Button>
}
/>
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
<DataTable
label={t("BO_ROLES")}
columns={columns}
data={sorted}
sorting={sorting}
onSortingChange={setSorting}
total={roles.length}
page={1}
pageSize={roles.length || 1}
onPageChange={() => {}}
isLoading={loading}
rowKey={(r) => String(r.id ?? r.name)}
empty={<EmptyState title={t("RolNoRoles")} />}
/>
{dialog && (
<RoleFormDialog initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />
)}
</>
);
}
export default function RolesPage() {
return (
<RequireModule pathname="/roles">
<RolesPageContent />
</RequireModule>
);
}