Found by the manual e2e of the production build: - paste guests preview counted an array, so it read "[object Object]" and never offered Save guests; - New event and Add user errors now clear when the field is fixed; - "Send to all unsent" says when nothing was unsent; - the check-in lookup shows an error on an empty submit and carries the typed email or mobile into the walk-in form; - invitation emails sent over Pub/Sub now save their recipient's link, so the Emails page shows the recipient. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
398 lines
15 KiB
TypeScript
398 lines
15 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState, type FormEvent } from "react";
|
|
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 { DatePicker } from "@/app/components/ui/date-picker";
|
|
import { ErrorState } from "@/app/components/ui/states";
|
|
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
|
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
|
import { listSalespersonOptions } from "@/app/lib/services/adminEvents";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import type { AdminEvent, AdminEventPayload, SalespersonOption } from "@/app/lib/types";
|
|
import type { ApiError } from "@/app/lib/clientApi";
|
|
|
|
interface SalespersonOptionExtended extends SalespersonOption {
|
|
active: boolean;
|
|
}
|
|
|
|
export interface EventFormProps {
|
|
initial?: AdminEvent;
|
|
onSubmit: (payload: AdminEventPayload) => Promise<void>;
|
|
submitLabel?: string;
|
|
}
|
|
|
|
/** Missing-field codes the API lists in errors[], mapped to the message shown under that field. */
|
|
const REQUIRED_MESSAGE: Record<string, string> = {
|
|
name: "EvtNameRequired",
|
|
location: "EvtLocationRequired",
|
|
startDate: "EvtStartRequired",
|
|
endDate: "EvtEndRequired",
|
|
};
|
|
/** Fields the form can show an API error under; anything else goes to the top of the form. */
|
|
const FIELD_ERROR_SLOTS = ["company", "name", "location", "startDate", "endDate", "salespersonIds", "capacity", "invitationCap"];
|
|
|
|
export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
|
const t = useT();
|
|
const { isSuper, hasModule } = useAdminAuth();
|
|
const canSetLimits = hasModule("BO_EVENT_GUESTS");
|
|
const scope = useCompanyScope();
|
|
// Super admins choose the company on create; on edit it is the event's own (it cannot move).
|
|
const showCompany = isSuper === true && !initial;
|
|
const [companyChoice, setCompanyChoice] = useState(scope.companyId ? String(scope.companyId) : "");
|
|
const optionsCompanyId = isSuper === true ? (initial ? initial.companyId : Number(companyChoice) || undefined) : undefined;
|
|
|
|
const [name, setName] = useState(initial?.name ?? "");
|
|
const [location, setLocation] = useState(initial?.location ?? "");
|
|
const [startDate, setStartDate] = useState(initial?.startDate ?? "");
|
|
const [endDate, setEndDate] = useState(initial?.endDate ?? "");
|
|
const [enabled, setEnabled] = useState(initial?.enabled ?? true);
|
|
const [capacity, setCapacity] = useState(initial?.capacity != null ? String(initial.capacity) : "");
|
|
const [invitationCap, setInvitationCap] = useState(initial?.invitationCap != null ? String(initial.invitationCap) : "");
|
|
|
|
const [optionList, setOptionList] = useState<SalespersonOptionExtended[]>([]);
|
|
const [loadingPickers, setLoadingPickers] = useState(true);
|
|
const [pickersError, setPickersError] = useState<string | null>(null);
|
|
|
|
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 -- loading/picker reset is the actual synchronization; initial is in the deps below.
|
|
setLoadingPickers(true);
|
|
setPickersError(null);
|
|
(optionsCompanyId ? listSalespersonOptions(optionsCompanyId) : listSalespersonOptions())
|
|
.then((opts) => {
|
|
if (cancelled) return;
|
|
const activeOpts = opts.map((o) => ({ ...o, active: true } as SalespersonOptionExtended));
|
|
// Merge deactivated team members from initial.
|
|
const activeIds = new Set(activeOpts.map((o) => o.id));
|
|
if (initial?.team) {
|
|
for (const m of initial.team) {
|
|
if (m.id != null && !activeIds.has(m.id)) {
|
|
activeOpts.push({
|
|
id: m.id as number,
|
|
name: m.name ?? "",
|
|
username: m.username ?? "",
|
|
active: false,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
setOptionList(activeOpts);
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled) {
|
|
setPickersError(err instanceof Error ? err.message : "SetupLoadOptionsFailed");
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoadingPickers(false);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [initial, optionsCompanyId]);
|
|
|
|
// Build the set of initially selected team member IDs.
|
|
// Members from initial.team that are also in the active options → checked.
|
|
// Members from initial.team that are NOT in the options (deactivated) → still shown, checked, with "Inactive" marker.
|
|
const [selectedIds, setSelectedIds] = useState<Set<number>>(() => {
|
|
if (!initial?.team) return new Set<number>();
|
|
return new Set(initial.team.map((m) => m.id).filter((id): id is number => id != null));
|
|
});
|
|
|
|
function toggleSalesperson(id: number) {
|
|
setSelectedIds((prev) => {
|
|
const next = new Set(prev);
|
|
if (next.has(id)) next.delete(id);
|
|
else next.add(id);
|
|
return next;
|
|
});
|
|
}
|
|
|
|
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
|
|
const trimmedName = name.trim();
|
|
const trimmedLocation = location.trim();
|
|
const errors: Record<string, string> = {};
|
|
|
|
if (!trimmedName) errors.name = t("EvtNameRequired");
|
|
if (!trimmedLocation) errors.location = t("EvtLocationRequired");
|
|
if (!startDate) errors.startDate = t("EvtStartRequired");
|
|
if (!endDate) errors.endDate = t("EvtEndRequired");
|
|
if (endDate && startDate && endDate < startDate) errors.endDate = t("EvtEndBeforeStart");
|
|
if (trimmedName.length > 100) errors.name = t("EvtNameTooLong");
|
|
if (showCompany && !companyChoice) errors.company = t("ChooseCompany");
|
|
if (trimmedLocation.length > 200) errors.location = t("EvtLocationTooLong");
|
|
|
|
setFieldErrors(errors);
|
|
if (Object.keys(errors).length > 0) return;
|
|
|
|
setFormError(null);
|
|
setSaving(true);
|
|
try {
|
|
const payload: AdminEventPayload = {
|
|
name: trimmedName,
|
|
location: trimmedLocation,
|
|
startDate,
|
|
endDate,
|
|
salespersonIds: Array.from(selectedIds).filter((id): id is number => id != null),
|
|
};
|
|
if (showCompany) payload.companyId = Number(companyChoice);
|
|
// `enabled` is only sent on edit (when initial exists).
|
|
if (initial) {
|
|
payload.enabled = enabled;
|
|
// Empty clears the limit; the server ignores these without BO_EVENT_GUESTS, so do not send them.
|
|
if (canSetLimits) {
|
|
payload.capacity = capacity.trim() === "" ? null : Number(capacity);
|
|
payload.invitationCap = invitationCap.trim() === "" ? null : Number(invitationCap);
|
|
}
|
|
}
|
|
await onSubmit(payload);
|
|
} catch (err) {
|
|
if (err instanceof Error && "status" in err && "data" in err) {
|
|
// The API sends errors[] (every missing field) and details.field (the failing field).
|
|
const data = (err as ApiError).data as { code?: unknown; errors?: unknown; details?: { field?: unknown } } | undefined;
|
|
if (data?.code === "CAP_BELOW_GUESTS") {
|
|
// The server sends no field for this one; it is always the invitation cap.
|
|
setFieldErrors({ invitationCap: err.message });
|
|
return;
|
|
}
|
|
const missing = (Array.isArray(data?.errors) ? data.errors : []).filter((f): f is string => typeof f === "string" && Object.hasOwn(REQUIRED_MESSAGE, f));
|
|
const field = data?.details?.field;
|
|
if (missing.length > 0) {
|
|
setFieldErrors(Object.fromEntries(missing.map((f) => [f, t(REQUIRED_MESSAGE[f])])));
|
|
return;
|
|
}
|
|
if (typeof field === "string" && FIELD_ERROR_SLOTS.includes(field)) {
|
|
setFieldErrors({ [field]: err.message });
|
|
return;
|
|
}
|
|
}
|
|
setFormError(err instanceof Error ? err.message : "EvtSaveFailed");
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
const label = submitLabel ?? (initial ? t("Edit") : t("Create"));
|
|
|
|
return (
|
|
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
|
{formError && <ErrorState message={t(formError)} />}
|
|
{pickersError && <ErrorState message={t(pickersError)} />}
|
|
|
|
{showCompany && (
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="evt-company">{t("Company")}</Label>
|
|
<Select
|
|
value={companyChoice}
|
|
onValueChange={(v) => {
|
|
setCompanyChoice(v);
|
|
clearError("company");
|
|
setSelectedIds(new Set()); // the team is company-specific
|
|
}}
|
|
disabled={saving}
|
|
>
|
|
<SelectTrigger id="evt-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>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
{fieldErrors.company && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.company}
|
|
</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="evt-name">{t("Name")}</Label>
|
|
<Input
|
|
id="evt-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="evt-location">{t("Location")}</Label>
|
|
<Input
|
|
id="evt-location"
|
|
required
|
|
value={location}
|
|
onChange={(e) => { setLocation(e.target.value); clearError("location"); }}
|
|
disabled={saving}
|
|
aria-invalid={!!fieldErrors.location}
|
|
/>
|
|
{fieldErrors.location && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.location}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="evt-start">{t("EvtStartDate")}</Label>
|
|
<DatePicker
|
|
id="evt-start"
|
|
value={startDate}
|
|
onChange={(v) => { setStartDate(v); clearError("startDate"); }}
|
|
aria-label={t("EvtStartDate")}
|
|
required
|
|
disabled={saving}
|
|
aria-invalid={!!fieldErrors.startDate}
|
|
/>
|
|
{fieldErrors.startDate && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.startDate}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="evt-end">{t("EvtEndDate")}</Label>
|
|
<DatePicker
|
|
id="evt-end"
|
|
value={endDate}
|
|
onChange={(v) => { setEndDate(v); clearError("endDate"); }}
|
|
aria-label={t("EvtEndDate")}
|
|
required
|
|
disabled={saving}
|
|
min={startDate}
|
|
aria-invalid={!!fieldErrors.endDate}
|
|
/>
|
|
{fieldErrors.endDate && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.endDate}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
{initial && (
|
|
<div className="space-y-1.5">
|
|
<div className="flex items-center gap-2">
|
|
<Switch
|
|
id="evt-enabled"
|
|
checked={enabled}
|
|
onCheckedChange={setEnabled}
|
|
disabled={saving}
|
|
/>
|
|
<Label htmlFor="evt-enabled">{t("Enabled")}</Label>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{initial && (
|
|
<>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="evt-capacity">{t("EvtCapacity")}</Label>
|
|
<Input
|
|
id="evt-capacity"
|
|
type="number"
|
|
min={1}
|
|
value={capacity}
|
|
onChange={(e) => { setCapacity(e.target.value); clearError("capacity"); }}
|
|
disabled={saving || !canSetLimits}
|
|
aria-invalid={!!fieldErrors.capacity}
|
|
/>
|
|
{fieldErrors.capacity && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.capacity}
|
|
</p>
|
|
)}
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="evt-invitation-cap">{t("EvtInvitationCap")}</Label>
|
|
<Input
|
|
id="evt-invitation-cap"
|
|
type="number"
|
|
min={1}
|
|
value={invitationCap}
|
|
onChange={(e) => { setInvitationCap(e.target.value); clearError("invitationCap"); }}
|
|
disabled={saving || !canSetLimits}
|
|
aria-invalid={!!fieldErrors.invitationCap}
|
|
/>
|
|
{fieldErrors.invitationCap && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.invitationCap}
|
|
</p>
|
|
)}
|
|
</div>
|
|
</>
|
|
)}
|
|
|
|
<fieldset className="space-y-1.5">
|
|
<legend className="text-sm font-medium">{t("EvtTeamLabel")}</legend>
|
|
{fieldErrors.salespersonIds && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{fieldErrors.salespersonIds}
|
|
</p>
|
|
)}
|
|
<div className="max-h-48 space-y-1 overflow-y-auto rounded-md border p-2">
|
|
{showCompany && !companyChoice ? (
|
|
<p className="text-sm text-muted-foreground">{t("TeamNeedsCompany")}</p>
|
|
) : loadingPickers ? (
|
|
<p className="text-sm text-muted-foreground">{t("Loading")}</p>
|
|
) : (
|
|
optionList.map((opt) => {
|
|
const name = opt.name ?? "";
|
|
const username = opt.username ?? "";
|
|
const displayName = name || username || String(opt.id);
|
|
const displayUsername = name ? username : undefined;
|
|
return (
|
|
<div key={opt.id} className="flex items-center gap-2">
|
|
<Checkbox
|
|
id={`salesperson-${opt.id}`}
|
|
checked={selectedIds.has(opt.id)}
|
|
disabled={saving}
|
|
onCheckedChange={() => toggleSalesperson(opt.id)}
|
|
aria-label={displayUsername ? `${displayName} (${displayUsername})` : displayName}
|
|
/>
|
|
<Label htmlFor={`salesperson-${opt.id}`}>
|
|
{displayName}
|
|
{displayUsername && ` (${displayUsername})`}
|
|
{!opt.active && (
|
|
<span className="ml-1 text-xs text-muted-foreground">
|
|
({t("EvtInactiveMember")})
|
|
</span>
|
|
)}
|
|
</Label>
|
|
</div>
|
|
);
|
|
})
|
|
)}
|
|
</div>
|
|
</fieldset>
|
|
|
|
<Button type="submit" disabled={saving}>
|
|
{label}
|
|
</Button>
|
|
</form>
|
|
);
|
|
}
|