Files
co-lite/solvway-admin-portal/app/components/events/EventForm.tsx
T

301 lines
11 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 { Switch } from "@/app/components/ui/switch";
import { DatePicker } from "@/app/components/ui/date-picker";
import { ErrorState } from "@/app/components/ui/states";
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 = ["name", "location", "startDate", "endDate", "salespersonIds"];
export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
const t = useT();
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 [optionList, setOptionList] = useState<SalespersonOptionExtended[]>([]);
const [loadingPickers, setLoadingPickers] = useState(true);
const [pickersError, setPickersError] = useState<string | null>(null);
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 -- loading/picker reset is the actual synchronization; initial is in the deps below.
setLoadingPickers(true);
setPickersError(null);
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]);
// 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 (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),
};
// `enabled` is only sent on edit (when initial exists).
if (initial) {
payload.enabled = enabled;
}
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 { errors?: unknown; details?: { field?: unknown } } | undefined;
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)} />}
<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)}
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)}
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={setStartDate}
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={setEndDate}
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>
)}
<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">
{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>
);
}