Files
co-lite/solvway-admin-portal/app/components/registration/RegistrationForm.tsx
T
ngqileandClaude Opus 5.5 bb2c5c5db7 feat(portal): landing pages list, editor, preview and public page
Pages list and Tiptap editor (ported from babyboo) with image upload on
save, the FORM event picker, field errors at their fields, delete
confirmation, unsaved-edits guard and a draft preview. The public page
/p/<company>/<slug> renders on the server with metadata, sanitize-html,
the company's logo and accent, and the sign-up form with UTM tags.
Companies get branding; the event lead detail shows the web page and
campaign. Labels in English and Chinese.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 16:30:54 +08:00

143 lines
7.2 KiB
TypeScript

"use client";
import { 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 { ApiError } from "@/app/lib/clientApi";
import type { RegistrationBody, RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const EMPTY: RegistrationBody = { name: "", mobile: "", email: "", companyName: "", jobTitle: "", interestIds: [], consent: false, website: "" };
// Fields the form renders; a server error for any other field goes to the form-level alert.
const FIELDS = ["name", "mobile", "email", "companyName", "jobTitle", "consent"];
const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3";
const CONSENT_ROW = "flex min-h-11 w-full cursor-pointer items-start gap-3 rounded-md border p-3 leading-normal";
const BOX = "size-6";
export function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } {
if (!(err instanceof ApiError)) return {};
const d = (err.data ?? {}) as { code?: string; error?: string; details?: { field?: string } };
return { status: err.status, code: d.code, error: d.error, field: d.details?.field };
}
/** Message for a failed visitor call: too-many wording, the server's text for 400/409, else the generic failure. */
export function failMessage(t: (k: string) => string, err: unknown, tooMany = "RegTooMany"): string {
const { status, code, error } = apiData(err);
if (code === "TOO_MANY") return t(tooMany);
return (status === 400 || status === 409) && error ? error : t("RegFailed");
}
interface Props {
/** i18n key for the too-many message (default RegTooMany, the /r wording). */
tooManyKey?: string;
info: RegistrationInfo;
/** Prefilled values (a personal invite); the form is blank without it. */
initial?: Partial<RegistrationBody>;
/** Sends the form; reject with the ApiError to have the form show it. */
submit: (body: RegistrationBody) => Promise<unknown>;
onDone: () => void;
/** The code or invitation was switched off: the page shows its own message. */
onInactive: () => void;
}
// The visitor registration form shared by /r, /i and /c: fields, bilingual privacy notice and consent.
// The event header comes from the VisitorCard around it.
export function RegistrationForm({ tooManyKey, info, initial, submit, onDone, onInactive }: Props) {
const t = useT();
const [form, setForm] = useState<RegistrationBody>({ ...EMPTY, ...initial });
const [errors, setErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const set = (patch: Partial<RegistrationBody>) => setForm((f) => ({ ...f, ...patch }));
async function onSubmit(e: FormEvent) {
e.preventDefault();
const errs: Record<string, string> = {};
if (!form.name.trim()) errs.name = t("RegNameRequired");
if (!form.mobile.trim() && !form.email.trim()) errs.mobile = t("RegContactRequired");
setErrors(errs);
setFormError(null);
if (Object.keys(errs).length) return;
setSaving(true);
try {
await submit({
...form,
name: form.name.trim(),
mobile: form.mobile.trim(),
email: form.email.trim(),
companyName: form.companyName.trim(),
jobTitle: form.jobTitle.trim(),
});
onDone();
} catch (err) {
const { status, code, error, field } = apiData(err);
if (code === "CODE_INACTIVE" || code === "INVITE_INACTIVE" || code === "FORM_CLOSED") onInactive();
else if (code === "EVENT_FULL") setFormError(t("RegFull"));
else if (status === 400 && error && field && FIELDS.includes(field)) setErrors({ [field]: error });
else setFormError(failMessage(t, err, tooManyKey));
setSaving(false);
}
}
const field = (id: "name" | "mobile" | "email" | "companyName" | "jobTitle", label: string, type = "text", hint?: string) => {
const describedBy = [hint && `reg-${id}-hint`, errors[id] && `reg-${id}-error`].filter(Boolean).join(" ") || undefined;
return (
<div className="space-y-1.5">
<Label htmlFor={`reg-${id}`}>{label}</Label>
<Input id={`reg-${id}`} className="h-11" type={type} value={form[id]} onChange={(e) => set({ [id]: e.target.value })} disabled={saving} aria-invalid={!!errors[id]} aria-describedby={describedBy} />
{hint && <p id={`reg-${id}-hint`} className="text-xs text-muted-foreground">{hint}</p>}
{errors[id] && <p id={`reg-${id}-error`} className="text-sm text-destructive">{errors[id]}</p>}
</div>
);
};
return (
<form onSubmit={onSubmit} className="space-y-4" noValidate>
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
{field("name", t("RegName"))}
{field("mobile", t("RegMobile"), "tel", t("RegContactHint"))}
{field("email", t("RegEmail"), "email")}
{field("companyName", t("RegCompany"))}
{field("jobTitle", t("RegJobTitle"))}
{info.interests.length > 0 && (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t("RegInterests")}</legend>
{info.interests.map((i) => (
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}>
<Checkbox
className={BOX}
id={`reg-interest-${i.id}`}
checked={form.interestIds.includes(i.id)}
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
/>
{i.name}
</Label>
))}
</fieldset>
)}
<div className="space-y-2 rounded-md bg-muted p-3 text-xs text-muted-foreground">
<h2 className="font-semibold text-foreground">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h2 className="font-semibold text-foreground">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</div>
<Label htmlFor="reg-consent" className={CONSENT_ROW}>
<Checkbox id="reg-consent" className={`${BOX} mt-0.5`} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
<span className="space-y-1 font-normal">
<span className="block">{t("RegConsentEn", { company: info.companyName })}</span>
<span className="block">{t("RegConsentMs", { company: info.companyName })}</span>
</span>
</Label>
{errors.consent && <p id="reg-consent-error" className="text-sm text-destructive">{errors.consent}</p>}
{/* Honeypot: people never see or reach it; bots fill it and the server drops the submission. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<input name="website" tabIndex={-1} autoComplete="off" value={form.website} onChange={(e) => set({ website: e.target.value })} />
</div>
<Button type="submit" className="h-11 w-full" disabled={saving}>{t("RegSubmit")}</Button>
</form>
);
}