Files

286 lines
10 KiB
TypeScript

"use client";
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { X } from "lucide-react";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Switch } from "@/app/components/ui/switch";
import { ErrorState } from "@/app/components/ui/states";
import { roleLabel } from "@/app/lib/roleLabel";
import { Skeleton } from "@/app/components/ui/skeleton";
import { listAdminRoles } from "@/app/lib/services/adminRoles";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import type { AdminUser } from "@/app/lib/types";
import { PasswordFields } from "./PasswordFields";
// Shared create/edit form for /users/new and /users/[id] (plan: "Build the admin
// add/edit-user form"). The Roles picker is populated from the admin roles list
// endpoint; the backend sets the branch from the creating admin.
// Deliberately basic (RFC-exhaustive email validation is out of scope) — mirrors
// the "basic email validation" requirement in the plan.
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
interface RoleOption {
id: number;
name: string;
}
/** On create the payload also carries the admin-typed first password and its confirmation. */
export type UserFormPayload = AdminUser & { password?: string; confirmPassword?: string };
export interface UserFormProps {
initial?: AdminUser;
onSubmit: (payload: UserFormPayload) => Promise<void>;
submitLabel?: string;
/** Create only: ask for the first password (the user must change it at first sign-in). */
withPassword?: boolean;
}
export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserFormProps) {
const t = useT();
const { id: myId } = useAdminAuth();
// The server refuses SELF_DEACTIVATION; this keeps the switch from offering it.
const isOwnAccount = initial?.id != null && initial.id === myId;
const [name, setName] = useState(initial?.name ?? "");
const [surname, setSurname] = useState(initial?.surname ?? "");
const [username, setUsername] = useState(initial?.username ?? "");
const [email, setEmail] = useState(initial?.email ?? "");
const [enabled, setEnabled] = useState(initial?.enabled ?? true);
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [selectedRoleIds, setSelectedRoleIds] = useState<Set<number>>(
() => new Set((initial?.roles ?? []).map((r) => r.id).filter((id): id is number => id != null)),
);
const [roleOptions, setRoleOptions] = useState<RoleOption[]>([]);
const [pickersError, setPickersError] = useState<string | null>(null);
const [loadingPickers, setLoadingPickers] = useState(true);
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the mount-time picker fetch below, which is the actual synchronization.
setLoadingPickers(true);
setPickersError(null);
listAdminRoles()
.then((roles) => {
if (cancelled) return;
setRoleOptions(
roles
.filter((r): r is typeof r & { id: number } => r.id != null)
.map((r) => ({ id: r.id, name: r.name })),
);
})
.catch((err: unknown) => {
if (!cancelled) {
setPickersError(err instanceof Error ? err.message : "SetupLoadOptionsFailed");
}
})
.finally(() => {
if (!cancelled) setLoadingPickers(false);
});
return () => {
cancelled = true;
};
}, []);
function toggleRole(id: number) {
setSelectedRoleIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
const selectedRoles = useMemo(
() => roleOptions.filter((r) => selectedRoleIds.has(r.id)),
[roleOptions, selectedRoleIds],
);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const errors: Record<string, string> = {};
if (!name.trim()) errors.name = t("UsrNameRequired");
if (!username.trim()) errors.username = t("UsrUsernameRequired");
if (!email.trim()) errors.email = t("UsrEmailRequired");
else if (!EMAIL_RE.test(email.trim())) errors.email = t("UsrEmailInvalid");
if (withPassword && !password) errors.password = t("UsrPasswordRequired");
else if (withPassword && password !== confirmPassword) errors.confirmPassword = t("UsrPasswordMismatch");
setFieldErrors(errors);
if (Object.keys(errors).length > 0) return;
setFormError(null);
setSaving(true);
try {
await onSubmit({
id: initial?.id,
name: name.trim(),
surname: surname.trim() || undefined,
username: username.trim(),
email: email.trim(),
enabled,
// Only `enabled` gates admin sign-in; status is derived to stay consistent.
status: enabled ? "Y" : "N",
roles: selectedRoles.map((r) => ({ id: r.id, name: r.name })),
...(withPassword ? { password, confirmPassword } : {}),
});
} catch (err) {
setFormError(err instanceof Error ? err.message : "UsrSaveFailed");
} finally {
setSaving(false);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
{formError && <ErrorState message={t(formError)} />}
{pickersError && <ErrorState message={t(pickersError)} />}
<div className="space-y-1.5">
<Label htmlFor="user-name">{t("Name")}</Label>
<Input
id="user-name"
required
value={name}
onChange={(e) => setName(e.target.value)}
disabled={saving}
aria-invalid={!!fieldErrors.name}
/>
{fieldErrors.name && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.name}
</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="user-surname">{t("Surname")}</Label>
<Input
id="user-surname"
value={surname}
onChange={(e) => setSurname(e.target.value)}
disabled={saving}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="user-username">{t("Username")}</Label>
<Input
id="user-username"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
// The backend ignores username on update, so it is fixed once the user exists.
disabled={saving || initial?.id != null}
aria-invalid={!!fieldErrors.username}
/>
{fieldErrors.username && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.username}
</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="user-email">{t("Email")}</Label>
<Input
id="user-email"
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={saving}
aria-invalid={!!fieldErrors.email}
/>
{fieldErrors.email && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.email}
</p>
)}
</div>
{withPassword && (
<PasswordFields
password={password}
confirmPassword={confirmPassword}
onPassword={setPassword}
onConfirmPassword={setConfirmPassword}
disabled={saving}
passwordError={fieldErrors.password}
confirmError={fieldErrors.confirmPassword}
/>
)}
<fieldset className="space-y-1.5">
<legend className="text-sm font-medium">{t("BO_ROLES")}</legend>
{selectedRoles.length > 0 && (
<div className="flex flex-wrap gap-2">
{selectedRoles.map((r) => (
<Badge key={r.id} variant="secondary" className="gap-1">
{roleLabel(r.name)}
<button
type="button"
aria-label={t("UsrRemoveRole", { role: roleLabel(r.name) })}
onClick={() => toggleRole(r.id)}
disabled={saving}
className="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<X aria-hidden="true" className="size-3" />
</button>
</Badge>
))}
</div>
)}
<div className="max-h-48 space-y-1 overflow-y-auto rounded-md border p-2">
{roleOptions.length === 0 ? (
loadingPickers ? (
<div role="status" className="space-y-2">
<span className="sr-only">{t("UsrLoadingRoles")}</span>
<Skeleton className="h-5 w-40" />
<Skeleton className="h-5 w-32" />
</div>
) : (
<p className="text-sm text-muted-foreground">{t("UsrNoRolesAvailable")}</p>
)
) : (
roleOptions.map((role) => (
<div key={role.id} className="flex items-center gap-2">
<Checkbox
id={`role-${role.id}`}
aria-label={roleLabel(role.name)}
checked={selectedRoleIds.has(role.id)}
disabled={saving}
onCheckedChange={() => toggleRole(role.id)}
/>
<Label htmlFor={`role-${role.id}`}>{roleLabel(role.name)}</Label>
</div>
))
)}
</div>
</fieldset>
<div className="space-y-1.5">
<div className="flex items-center gap-2">
<Switch id="user-enabled" checked={enabled} onCheckedChange={setEnabled} disabled={saving || isOwnAccount} />
<Label htmlFor="user-enabled">{t("Enabled")}</Label>
</div>
<p className="text-sm text-muted-foreground">{t(isOwnAccount ? "UsrOwnAccountHint" : "UsrDisabledHint")}</p>
</div>
<Button type="submit" disabled={saving}>
{submitLabel ?? t("Save")}
</Button>
</form>
);
}