Files
ngqileandClaude Opus 5.5 8ce9fcf471 feat: portal password hints, company hint, interest and role delete, dashboard notes
- Login: company-code hint after an invalid-credentials failure with an empty company.
- Password forms show the active rules (label-first, count-safe) and tie hint and refusal to the input.
- Interests and roles: soft delete with confirm dialogs; deactivate now confirms too.
- Dashboard figure explanations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-02 02:59:44 +08:00

323 lines
13 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
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 { useCompanyScope } from "@/app/lib/CompanyScope";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import type { AdminUser } from "@/app/lib/types";
import { PasswordFields } from "./PasswordFields";
import { passwordRuleError } from "./PasswordRulesHint";
// 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; companyId?: number; superAdmin?: boolean };
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, isSuper } = useAdminAuth();
const scope = useCompanyScope();
// Super admins pick the new user's company on create; "super" makes another company-less super admin.
const showCompany = isSuper === true && initial?.id == null;
const [company, setCompany] = useState(scope.companyId ? String(scope.companyId) : "");
// 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>>({});
// A field's error goes away as soon as the user edits that field; the next submit re-validates.
const clearError = (k: string) => setFieldErrors((e) => (k in e ? Object.fromEntries(Object.entries(e).filter(([f]) => f !== k)) : e));
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 (showCompany && !company) errors.company = t("ChooseCompany");
else if (showCompany && company === "super" && !selectedRoleIds.has(1)) errors.company = t("SuperAdminNeedsRole");
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 } : {}),
...(showCompany ? (company === "super" ? { superAdmin: true } : { companyId: Number(company) }) : {}),
});
} catch (err) {
const rule = passwordRuleError(err, t);
if (rule) setFieldErrors({ password: rule });
else 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); clearError("name"); }}
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); clearError("username"); }}
// 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); clearError("email"); }}
disabled={saving}
aria-invalid={!!fieldErrors.email}
/>
{fieldErrors.email && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.email}
</p>
)}
</div>
{showCompany && (
<div className="space-y-1.5">
<Label htmlFor="user-company">{t("Company")}</Label>
<Select value={company} onValueChange={(v) => { setCompany(v); clearError("company"); }} disabled={saving}>
<SelectTrigger id="user-company" aria-invalid={!!fieldErrors.company} className="w-full">
<SelectValue placeholder={t("SelectCompany")} />
</SelectTrigger>
<SelectContent>
{scope.companies.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>
))}
<SelectItem value="super">{t("CompanySuperAdmin")}</SelectItem>
</SelectContent>
</Select>
{fieldErrors.company && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.company}
</p>
)}
</div>
)}
{withPassword && (
<PasswordFields
password={password}
confirmPassword={confirmPassword}
onPassword={(v) => { setPassword(v); clearError("password"); }}
onConfirmPassword={(v) => { setConfirmPassword(v); clearError("confirmPassword"); }}
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>
);
}