Lists, adds, renames, orders and activates/deactivates interests, gated by BO_INTERESTS. API errors map to field messages under Name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
285 lines
8.9 KiB
TypeScript
285 lines
8.9 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
|
|
import { Plus } from "lucide-react";
|
|
import type { ColumnDef } 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 { PageHeader } from "@/app/components/ui/page-header";
|
|
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
|
import { Badge } from "@/app/components/ui/badge";
|
|
import { RequireModule } from "@/app/lib/RequireModule";
|
|
import { listAdminInterests, saveAdminInterest } from "@/app/lib/services/adminInterests";
|
|
import type { AdminInterestEntity } from "@/app/lib/types";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
|
|
interface FormState {
|
|
id?: number;
|
|
name: string;
|
|
sortOrder?: number;
|
|
}
|
|
|
|
const EMPTY_FORM: FormState = { name: "", sortOrder: 0 };
|
|
|
|
function InterestFormDialog({
|
|
initial,
|
|
onClose,
|
|
onSaved,
|
|
}: {
|
|
initial: FormState;
|
|
onClose: () => void;
|
|
onSaved: () => void;
|
|
}) {
|
|
const t = useT();
|
|
const [form, setForm] = useState<FormState>(initial);
|
|
const [saving, setSaving] = useState(false);
|
|
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
|
const [formError, setFormError] = useState<string | null>(null);
|
|
|
|
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
const trimmed = form.name.trim();
|
|
|
|
const errors: Record<string, string> = {};
|
|
if (!trimmed) errors.name = t("IntNameRequired");
|
|
else if (trimmed.length > 100) errors.name = t("IntNameTooLong");
|
|
setFieldErrors(errors);
|
|
if (Object.keys(errors).length > 0) return;
|
|
|
|
setFormError(null);
|
|
setSaving(true);
|
|
try {
|
|
if (form.id) {
|
|
// Edit: only send name and sortOrder
|
|
await saveAdminInterest({ id: form.id, name: trimmed, sortOrder: form.sortOrder });
|
|
} else {
|
|
// Create: send active=true and sortOrder
|
|
await saveAdminInterest({ name: trimmed, active: true, sortOrder: form.sortOrder ?? 0 });
|
|
}
|
|
onSaved();
|
|
onClose();
|
|
} catch (err) {
|
|
if (err instanceof Error && "status" in err && "data" in err) {
|
|
const apiErr = err as Error & { status?: number; data?: unknown };
|
|
const code = (apiErr.data as { code?: string } | undefined)?.code;
|
|
if (code === "DUPLICATE_NAME") {
|
|
setFieldErrors({ name: t("IntDuplicateName") });
|
|
} else if (code === "TOO_LONG") {
|
|
setFieldErrors({ name: t("IntNameTooLong") });
|
|
} else if (code === "REQUIRED_FIELD") {
|
|
setFieldErrors({ name: t("IntNameRequired") });
|
|
} else {
|
|
setFormError(err.message || "IntSaveFailed");
|
|
}
|
|
} else {
|
|
setFormError(err instanceof Error ? err.message : "IntSaveFailed");
|
|
}
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>{form.id ? t("IntEditInterest") : t("IntAddInterest")}</DialogTitle>
|
|
</DialogHeader>
|
|
{formError && (
|
|
<div className="text-sm text-destructive" role="alert">
|
|
{t(formError)}
|
|
</div>
|
|
)}
|
|
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="interest-name">{t("IntInterestName")}</Label>
|
|
<Input
|
|
id="interest-name"
|
|
required
|
|
maxLength={100}
|
|
value={form.name}
|
|
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
|
|
disabled={saving}
|
|
aria-invalid={!!fieldErrors.name}
|
|
aria-describedby={fieldErrors.name ? "interest-name-error" : undefined}
|
|
/>
|
|
{fieldErrors.name && (
|
|
<p id="interest-name-error" role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.name}
|
|
</p>
|
|
)}
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="interest-order">{t("IntInterestOrder")}</Label>
|
|
<Input
|
|
id="interest-order"
|
|
type="number"
|
|
min={0}
|
|
value={form.sortOrder ?? 0}
|
|
onChange={(e) => setForm((f) => ({ ...f, sortOrder: parseInt(e.target.value, 10) || 0 }))}
|
|
disabled={saving}
|
|
/>
|
|
</div>
|
|
<DialogFooter>
|
|
<Button type="submit" disabled={saving}>
|
|
{t("Save")}
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
function InterestsPageContent() {
|
|
const t = useT();
|
|
const [interests, setInterests] = useState<AdminInterestEntity[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [reloadKey, setReloadKey] = useState(0);
|
|
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);
|
|
listAdminInterests()
|
|
.then((result) => {
|
|
if (!cancelled) setInterests(result);
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled) setError(err instanceof Error ? err.message : "IntLoadFailed");
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [reloadKey]);
|
|
|
|
const columns = useMemo<ColumnDef<AdminInterestEntity, unknown>[]>(
|
|
() => [
|
|
{
|
|
accessorKey: "name",
|
|
header: t("IntColInterest"),
|
|
cell: ({ row }) => <div>{row.original.name}</div>,
|
|
},
|
|
{
|
|
accessorKey: "sortOrder",
|
|
header: t("IntColOrder"),
|
|
cell: ({ row }) => <div>{row.original.sortOrder ?? 0}</div>,
|
|
},
|
|
{
|
|
accessorKey: "active",
|
|
header: t("IntColStatus"),
|
|
cell: ({ row }) => (
|
|
<Badge variant={row.original.active ? "positive" : "neutral"}>
|
|
{row.original.active ? t("IntActive") : t("IntInactive")}
|
|
</Badge>
|
|
),
|
|
},
|
|
{
|
|
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 ?? "",
|
|
sortOrder: row.original.sortOrder,
|
|
})
|
|
}
|
|
>
|
|
{t("Edit")}
|
|
</Button>
|
|
{row.original.active ? (
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={async () => {
|
|
try {
|
|
await saveAdminInterest({ id: row.original.id, active: false });
|
|
refetch();
|
|
} catch {
|
|
setError("IntDeactivateFailed");
|
|
}
|
|
}}
|
|
>
|
|
{t("IntDeactivate")}
|
|
</Button>
|
|
) : (
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={async () => {
|
|
try {
|
|
await saveAdminInterest({ id: row.original.id, active: true });
|
|
refetch();
|
|
} catch {
|
|
setError("IntActivateFailed");
|
|
}
|
|
}}
|
|
>
|
|
{t("IntActivate")}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
),
|
|
},
|
|
],
|
|
[t, refetch],
|
|
);
|
|
|
|
return (
|
|
<>
|
|
<PageHeader
|
|
title={t("BO_INTERESTS")}
|
|
actions={
|
|
<Button onClick={() => setDialog(EMPTY_FORM)}>
|
|
<Plus aria-hidden="true" className="size-4" />
|
|
{t("IntAddInterest")}
|
|
</Button>
|
|
}
|
|
/>
|
|
|
|
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
|
|
|
<DataTable
|
|
label={t("BO_INTERESTS")}
|
|
columns={columns}
|
|
data={interests}
|
|
total={interests.length}
|
|
page={1}
|
|
pageSize={interests.length || 1}
|
|
onPageChange={() => {}}
|
|
isLoading={loading}
|
|
rowKey={(r) => String(r.id ?? r.name)}
|
|
empty={<EmptyState title={t("IntNoInterests")} />}
|
|
/>
|
|
|
|
{dialog && (
|
|
<InterestFormDialog initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
export default function InterestsPage() {
|
|
return (
|
|
<RequireModule pathname="/interests">
|
|
<InterestsPageContent />
|
|
</RequireModule>
|
|
);
|
|
}
|