Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
468 lines
17 KiB
TypeScript
468 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useState, type FormEvent } from "react";
|
|
import { Check, ChevronsUpDown, X } from "lucide-react";
|
|
import { Badge } from "@/app/components/ui/badge";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import {
|
|
Command,
|
|
CommandEmpty,
|
|
CommandGroup,
|
|
CommandInput,
|
|
CommandItem,
|
|
CommandList,
|
|
} from "@/app/components/ui/command";
|
|
import { Popover, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover";
|
|
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 { listAdminLocations } from "@/app/lib/services/adminLocations";
|
|
import { listSellableCountries } from "@/app/lib/services/sellableCountries";
|
|
import { listEvents } from "@/app/lib/services/adminEvents";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import type { AdminUser, SellableCountry } from "@/app/lib/types";
|
|
|
|
// Shared create/edit form for /users/new and /users/[id] (plan: "Build the admin
|
|
// add/edit-user form"). Roles/Branch pickers are populated from the existing CRUD
|
|
// list endpoints; Branch is restricted to type "B" (branch-level) location nodes
|
|
// only — a user is never assigned a country/region/global node.
|
|
|
|
const NONE = "none";
|
|
|
|
// 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;
|
|
}
|
|
|
|
interface BranchOption {
|
|
id: number;
|
|
name: string;
|
|
code: string;
|
|
}
|
|
|
|
interface EventOption {
|
|
id: number;
|
|
name: string;
|
|
code: string;
|
|
closed: boolean;
|
|
}
|
|
|
|
export interface UserFormProps {
|
|
initial?: AdminUser;
|
|
onSubmit: (payload: AdminUser) => Promise<void>;
|
|
submitLabel?: string;
|
|
}
|
|
|
|
export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) {
|
|
const t = useT();
|
|
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 [selectedRoleIds, setSelectedRoleIds] = useState<Set<number>>(
|
|
() => new Set((initial?.roles ?? []).map((r) => r.id).filter((id): id is number => id != null)),
|
|
);
|
|
const [branchId, setBranchId] = useState<string>(initial?.branch ? String(initial.branch.id) : NONE);
|
|
|
|
const [eventId, setEventId] = useState<number | null>(initial?.event?.id ?? null);
|
|
const [eventOpen, setEventOpen] = useState(false);
|
|
const [eventOptions, setEventOptions] = useState<EventOption[]>([]);
|
|
|
|
const [roleOptions, setRoleOptions] = useState<RoleOption[]>([]);
|
|
const [branchOptions, setBranchOptions] = useState<BranchOption[]>([]);
|
|
const [countryOptions, setCountryOptions] = useState<SellableCountry[]>([]);
|
|
const [allCountries, setAllCountries] = useState(!initial?.countryScope?.length);
|
|
const [selectedCountries, setSelectedCountries] = useState<Set<string>>(
|
|
() => new Set(initial?.countryScope ?? []),
|
|
);
|
|
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);
|
|
Promise.all([
|
|
listAdminRoles(),
|
|
listAdminLocations(),
|
|
listSellableCountries().catch(() => [] as SellableCountry[]),
|
|
])
|
|
.then(([roles, locations, countries]) => {
|
|
if (cancelled) return;
|
|
setCountryOptions(countries);
|
|
setRoleOptions(
|
|
roles
|
|
.filter((r): r is typeof r & { id: number } => r.id != null)
|
|
.map((r) => ({ id: r.id, name: r.name })),
|
|
);
|
|
setBranchOptions(
|
|
locations
|
|
.filter((l) => l.type === "B")
|
|
.map((l) => ({ id: l.id, name: l.name, code: l.code })),
|
|
);
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled) {
|
|
setPickersError(err instanceof Error ? err.message : "SetupLoadOptionsFailed");
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoadingPickers(false);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, []);
|
|
|
|
// Events load separately so a failure never blocks the rest of the form.
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
listEvents()
|
|
.then((events) => {
|
|
if (!cancelled)
|
|
setEventOptions(
|
|
events.map((e) => ({ id: Number(e.id), name: e.name, code: e.code, closed: e.status === "C" })),
|
|
);
|
|
})
|
|
.catch(() => {});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, []);
|
|
|
|
const initialEventId = initial?.event?.id ?? null;
|
|
const visibleEvents = eventOptions.filter((e) => !e.closed || e.id === initialEventId);
|
|
const selectedEvent = eventOptions.find((e) => e.id === eventId);
|
|
|
|
function toggleRole(id: number) {
|
|
setSelectedRoleIds((prev) => {
|
|
const next = new Set(prev);
|
|
if (next.has(id)) next.delete(id);
|
|
else next.add(id);
|
|
return next;
|
|
});
|
|
}
|
|
|
|
function toggleCountry(code: string) {
|
|
setSelectedCountries((prev) => {
|
|
const next = new Set(prev);
|
|
if (next.has(code)) next.delete(code);
|
|
else next.add(code);
|
|
return next;
|
|
});
|
|
}
|
|
|
|
const showCountryScope = countryOptions.length > 1;
|
|
|
|
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");
|
|
// service-system.user.branchid is NOT NULL: a user without a branch cannot be saved.
|
|
if (branchId === NONE) errors.branch = t("UsrBranchRequired");
|
|
if (showCountryScope && !allCountries && selectedCountries.size === 0)
|
|
errors.countryScope = t("UsrCountryScopeRequired");
|
|
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 })),
|
|
branch: branchId !== NONE ? { id: Number(branchId) } : undefined,
|
|
// Omit when never tied, so an untied user keeps its stored scope untouched.
|
|
// Omit with one sellable country, so the stored scope is kept untouched.
|
|
...(showCountryScope && { countryScope: allCountries ? null : [...selectedCountries] }),
|
|
event: eventId !== null || initialEventId !== null ? { id: eventId } : undefined,
|
|
});
|
|
} 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)}
|
|
disabled={saving}
|
|
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>
|
|
|
|
<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>
|
|
|
|
{showCountryScope && (
|
|
<fieldset className="space-y-1.5">
|
|
<legend className="text-sm font-medium">{t("UsrCountryScope")}</legend>
|
|
<div className="flex items-center gap-2">
|
|
<Checkbox
|
|
id="country-all"
|
|
aria-label={t("UsrAllCountries")}
|
|
checked={allCountries}
|
|
disabled={saving}
|
|
onCheckedChange={(v) => setAllCountries(v === true)}
|
|
/>
|
|
<Label htmlFor="country-all">{t("UsrAllCountries")}</Label>
|
|
</div>
|
|
{!allCountries && (
|
|
<div className="space-y-1 rounded-md border p-2">
|
|
{[
|
|
...countryOptions,
|
|
// A stored code that is no longer sellable stays listed so it can be unticked.
|
|
...[...selectedCountries]
|
|
.filter((code) => !countryOptions.some((o) => o.code === code))
|
|
.map((code) => ({ code, name: code })),
|
|
].map((c) => (
|
|
<div key={c.code} className="flex items-center gap-2">
|
|
<Checkbox
|
|
id={`country-${c.code}`}
|
|
checked={selectedCountries.has(c.code)}
|
|
disabled={saving}
|
|
onCheckedChange={() => toggleCountry(c.code)}
|
|
/>
|
|
<Label htmlFor={`country-${c.code}`}>{c.name}</Label>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
{fieldErrors.countryScope && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.countryScope}
|
|
</p>
|
|
)}
|
|
</fieldset>
|
|
)}
|
|
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="user-branch">{t("Branch")}</Label>
|
|
<Select value={branchId} onValueChange={setBranchId} disabled={saving}>
|
|
<SelectTrigger
|
|
id="user-branch"
|
|
aria-label={t("Branch")}
|
|
aria-invalid={!!fieldErrors.branch}
|
|
className="w-full"
|
|
>
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value={NONE}>{t("UsrSelectBranch")}</SelectItem>
|
|
{branchOptions.map((b) => (
|
|
<SelectItem key={b.id} value={String(b.id)}>
|
|
{b.name} ({b.code})
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
{fieldErrors.branch && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.branch}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<Label>{t("PosEvent")}</Label>
|
|
<Popover open={eventOpen} onOpenChange={setEventOpen}>
|
|
<PopoverTrigger asChild>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
role="combobox"
|
|
aria-expanded={eventOpen}
|
|
aria-label={t("PosEvent")}
|
|
disabled={saving}
|
|
className="w-full justify-between font-normal"
|
|
>
|
|
{selectedEvent ? `${selectedEvent.name} (${selectedEvent.code})` : "\u2014"}
|
|
<ChevronsUpDown aria-hidden="true" className="size-4 opacity-50" />
|
|
</Button>
|
|
</PopoverTrigger>
|
|
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
|
|
<Command>
|
|
<CommandInput placeholder={t("EvtSearchPlaceholder")} />
|
|
<CommandList>
|
|
<CommandEmpty>{t("UiNoResults")}</CommandEmpty>
|
|
<CommandGroup>
|
|
{[{ id: null, name: t("UsrEventNone"), code: "" }, ...visibleEvents].map((e) => (
|
|
<CommandItem
|
|
key={e.id ?? "none"}
|
|
value={`${e.name} ${e.code}`}
|
|
onSelect={() => {
|
|
setEventId(e.id);
|
|
setEventOpen(false);
|
|
}}
|
|
>
|
|
<Check aria-hidden="true" className={eventId === e.id ? "size-4" : "size-4 opacity-0"} />
|
|
<span>{e.name}</span>
|
|
{e.code && <span className="text-muted-foreground">{e.code}</span>}
|
|
</CommandItem>
|
|
))}
|
|
</CommandGroup>
|
|
</CommandList>
|
|
</Command>
|
|
</PopoverContent>
|
|
</Popover>
|
|
<p className="text-sm text-muted-foreground">{t("UsrEventHint")}</p>
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<div className="flex items-center gap-2">
|
|
<Switch id="user-enabled" checked={enabled} onCheckedChange={setEnabled} disabled={saving} />
|
|
<Label htmlFor="user-enabled">{t("Enabled")}</Label>
|
|
</div>
|
|
<p className="text-sm text-muted-foreground">{t("UsrDisabledHint")}</p>
|
|
</div>
|
|
|
|
<Button type="submit" disabled={saving}>
|
|
{submitLabel ?? t("Save")}
|
|
</Button>
|
|
</form>
|
|
);
|
|
}
|