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
270 lines
12 KiB
TypeScript
270 lines
12 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState, type ReactNode } from "react";
|
|
import Link from "next/link";
|
|
import { useRouter, useSearchParams } from "next/navigation";
|
|
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
|
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
|
import { Input } from "@/app/components/ui/input";
|
|
import { Label } from "@/app/components/ui/label";
|
|
import { RadioGroup, RadioGroupItem } from "@/app/components/ui/radio-group";
|
|
import { Textarea } from "@/app/components/ui/textarea";
|
|
import { ErrorState } from "@/app/components/ui/states";
|
|
import { FieldError } from "@/app/components/catalog-setup/FieldError";
|
|
import { parseServerError, type FieldErrors } from "@/app/lib/catalogSetup";
|
|
import {
|
|
draftFromView,
|
|
emptyForm,
|
|
FIELD_LABELS,
|
|
FIELD_TYPES,
|
|
formBody,
|
|
moveField,
|
|
newField,
|
|
type CmsFormDraft,
|
|
type CmsFormFieldDraft,
|
|
type FieldType,
|
|
} from "@/app/lib/cmsForms";
|
|
import { deleteForm, getForm, saveForm } from "@/app/lib/services/adminForms";
|
|
import { ApiError } from "@/app/lib/clientApi";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
|
|
// The form editor (add-cms-forms): settings plus an ordered field list. Each field keeps the key it
|
|
// was created with, so stored submissions stay matched to it after relabelling or reordering.
|
|
|
|
const SELECT_CLASS =
|
|
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
|
|
|
|
function Field({ id, label, error, name, children }: { id: string; label: string; error?: string; name?: string; children: ReactNode }) {
|
|
return (
|
|
<div className="space-y-1.5" data-field={name}>
|
|
<Label htmlFor={id}>{label}</Label>
|
|
{children}
|
|
<FieldError message={error} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** Server error paths this editor shows under a field; any other path goes to the summary alert. */
|
|
const RENDERED = /^(name|submitLabel|successMessage|status|fields|notifyEmails(\[\d+\])?|fields\[\d+\]\.(key|label|type|options))$/;
|
|
|
|
/** The first message among errors whose path is `name` or `name[i]` (e.g. notifyEmails[1]). */
|
|
function firstError(errors: FieldErrors, name: string): string | undefined {
|
|
const hit = Object.entries(errors).find(([path]) => path === name || path.startsWith(`${name}[`));
|
|
return hit?.[1];
|
|
}
|
|
|
|
export function FormEditor({ formId }: { formId?: number }) {
|
|
const t = useT();
|
|
const router = useRouter();
|
|
const justSaved = useSearchParams()?.get("saved") === "1";
|
|
const [draft, setDraft] = useState<CmsFormDraft>(() => emptyForm());
|
|
const [loading, setLoading] = useState(formId != null);
|
|
const [loadError, setLoadError] = useState<string | null>(null);
|
|
const [errors, setErrors] = useState<FieldErrors>({});
|
|
const [summary, setSummary] = useState<string | null>(null);
|
|
const [notice, setNotice] = useState<string | null>(justSaved ? "FrmSaved" : null);
|
|
const [saving, setSaving] = useState(false);
|
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
|
|
|
useEffect(() => {
|
|
if (formId == null) return;
|
|
let cancelled = false;
|
|
getForm(formId)
|
|
.then((view) => {
|
|
if (!cancelled) setDraft(draftFromView(view));
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled) setLoadError(err instanceof Error ? err.message : "FrmLoadFailed");
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [formId]);
|
|
|
|
const patch = (next: Partial<CmsFormDraft>) => setDraft((d) => ({ ...d, ...next }));
|
|
// Field errors are keyed by position, so any reorder or removal clears them.
|
|
const setFields = (fields: CmsFormFieldDraft[]) => {
|
|
setErrors({});
|
|
patch({ fields });
|
|
};
|
|
const updateField = (key: string, next: Partial<CmsFormFieldDraft>) =>
|
|
setDraft((d) => ({ ...d, fields: d.fields.map((f) => (f.key === key ? { ...f, ...next } : f)) }));
|
|
|
|
async function save() {
|
|
setSummary(null);
|
|
setNotice(null);
|
|
setErrors({});
|
|
setSaving(true);
|
|
try {
|
|
const view = await saveForm(formBody(draft));
|
|
setDraft((d) => ({ ...d, id: view.id }));
|
|
setNotice("FrmSaved");
|
|
if (draft.id == null) router.replace(`/forms/${view.id}?saved=1`);
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : "FrmSaveFailed";
|
|
const { path, message: fieldMessage } = parseServerError(message);
|
|
if (err instanceof ApiError && err.status === 422 && path && RENDERED.test(path)) setErrors({ [path]: fieldMessage });
|
|
else setSummary(message);
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
async function remove() {
|
|
if (draft.id == null) return;
|
|
try {
|
|
await deleteForm(draft.id);
|
|
router.push("/forms");
|
|
} catch (err) {
|
|
setSummary(err instanceof Error ? err.message : "FrmDeleteFailed");
|
|
}
|
|
}
|
|
|
|
if (loadError) return <ErrorState message={t(loadError)} />;
|
|
if (loading) return null;
|
|
|
|
const fieldError = (index: number, name: string) => errors[`fields[${index}].${name}`];
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
{draft.id != null ? (
|
|
<div className="flex justify-end">
|
|
<Button variant="outline" asChild>
|
|
<Link href={`/forms/${draft.id}/submissions`}>{t("FrmViewSubmissions")}</Link>
|
|
</Button>
|
|
</div>
|
|
) : null}
|
|
{summary && <p role="alert" className="text-sm text-destructive">{t(summary)}</p>}
|
|
{notice && <p role="status" className="text-sm text-positive">{t(notice)}</p>}
|
|
|
|
<div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
|
|
<div className="space-y-4">
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>{t("FrmCardForm")}</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
<Field id="form-name" label={t("Name")} error={errors.name}>
|
|
<Input id="form-name" value={draft.name} disabled={saving} onChange={(e) => patch({ name: e.target.value })} />
|
|
</Field>
|
|
<Field id="form-submit-label" label={t("FrmSubmitButtonLabel")} error={errors.submitLabel}>
|
|
<Input id="form-submit-label" value={draft.submitLabel} disabled={saving} onChange={(e) => patch({ submitLabel: e.target.value })} />
|
|
</Field>
|
|
<Field id="form-success" label={t("FrmSuccessMessage")} error={errors.successMessage}>
|
|
<Textarea id="form-success" rows={2} value={draft.successMessage} disabled={saving} onChange={(e) => patch({ successMessage: e.target.value })} />
|
|
</Field>
|
|
<Field id="form-emails" label={t("FrmNotificationEmails")} error={firstError(errors, "notifyEmails")} name="notifyEmails">
|
|
<Input id="form-emails" value={draft.notifyEmailsText} disabled={saving} onChange={(e) => patch({ notifyEmailsText: e.target.value })} />
|
|
<p className="text-xs text-muted-foreground">{t("FrmNotificationEmailsHelp")}</p>
|
|
</Field>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
{draft.fields.map((f, index) => (
|
|
<fieldset key={f.key} aria-label={t("FrmFieldN", { n: index + 1 })} className="space-y-3 rounded-xl border bg-card p-4">
|
|
<div className="flex items-center justify-between gap-2">
|
|
<span className="text-sm font-medium">{t("FrmFieldN", { n: index + 1 })}</span>
|
|
<div className="flex gap-1">
|
|
<Button type="button" variant="ghost" size="icon" aria-label={t("FrmMoveFieldUp")} disabled={saving || index === 0} onClick={() => setFields(moveField(draft.fields, index, -1))}>
|
|
<ArrowUp aria-hidden="true" className="size-4" />
|
|
</Button>
|
|
<Button type="button" variant="ghost" size="icon" aria-label={t("FrmMoveFieldDown")} disabled={saving || index === draft.fields.length - 1} onClick={() => setFields(moveField(draft.fields, index, 1))}>
|
|
<ArrowDown aria-hidden="true" className="size-4" />
|
|
</Button>
|
|
<Button type="button" variant="ghost" size="icon" aria-label={t("FrmRemoveField")} disabled={saving} onClick={() => setFields(draft.fields.filter((x) => x.key !== f.key))}>
|
|
<Trash2 aria-hidden="true" className="size-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
<FieldError message={fieldError(index, "key")} />
|
|
<Field id={`field-${f.key}-label`} label={t("FrmLabel")} error={fieldError(index, "label")}>
|
|
<Input id={`field-${f.key}-label`} value={f.label} disabled={saving} onChange={(e) => updateField(f.key, { label: e.target.value })} />
|
|
</Field>
|
|
<Field id={`field-${f.key}-type`} label={t("Type")} error={fieldError(index, "type")}>
|
|
<select id={`field-${f.key}-type`} className={SELECT_CLASS} value={f.type} disabled={saving} onChange={(e) => updateField(f.key, { type: e.target.value as FieldType })}>
|
|
{FIELD_TYPES.map((type) => (
|
|
<option key={type} value={type}>
|
|
{t(FIELD_LABELS[type])}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</Field>
|
|
<div className="flex items-center gap-2">
|
|
<input id={`field-${f.key}-required`} type="checkbox" checked={f.required} disabled={saving} onChange={(e) => updateField(f.key, { required: e.target.checked })} />
|
|
<Label htmlFor={`field-${f.key}-required`} className="font-normal">
|
|
{t("FrmRequired")}
|
|
</Label>
|
|
</div>
|
|
{f.type === "SELECT" ? (
|
|
<Field id={`field-${f.key}-options`} label={t("FrmOptionsOnePerLine")} error={fieldError(index, "options")} name="options">
|
|
<Textarea id={`field-${f.key}-options`} rows={4} value={f.optionsText} disabled={saving} onChange={(e) => updateField(f.key, { optionsText: e.target.value })} />
|
|
</Field>
|
|
) : null}
|
|
</fieldset>
|
|
))}
|
|
<FieldError message={errors.fields} />
|
|
|
|
<Button type="button" variant="outline" size="sm" disabled={saving} onClick={() => patch({ fields: [...draft.fields, newField("TEXT")] })}>
|
|
<Plus aria-hidden="true" className="size-4" />
|
|
{t("FrmAddField")}
|
|
</Button>
|
|
</div>
|
|
|
|
<div className="space-y-4">
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>{t("Visibility")}</CardTitle>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<RadioGroup aria-label={t("Visibility")} value={draft.status} disabled={saving} onValueChange={(v) => patch({ status: v as "Y" | "N" })} className="space-y-2">
|
|
{(
|
|
[
|
|
["Y", "Visible"],
|
|
["N", "Hidden"],
|
|
] as const
|
|
).map(([value, label]) => (
|
|
<div key={value} className="flex items-center gap-2">
|
|
<RadioGroupItem value={value} id={`form-status-${value}`} />
|
|
<Label htmlFor={`form-status-${value}`} className="font-normal">
|
|
{t(label)}
|
|
</Label>
|
|
</div>
|
|
))}
|
|
</RadioGroup>
|
|
<p className="mt-2 text-xs text-muted-foreground">{t("FrmHiddenHelp")}</p>
|
|
<FieldError message={errors.status} />
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
|
{draft.id != null ? (
|
|
<Button type="button" variant="destructive-outline" disabled={saving} onClick={() => setConfirmDelete(true)}>
|
|
{t("FrmDeleteForm")}
|
|
</Button>
|
|
) : (
|
|
<span />
|
|
)}
|
|
<Button type="button" disabled={saving} onClick={() => void save()}>
|
|
{t("FrmSaveForm")}
|
|
</Button>
|
|
</div>
|
|
|
|
<ConfirmDialog
|
|
open={confirmDelete}
|
|
onOpenChange={setConfirmDelete}
|
|
title={t("FrmDeleteConfirmTitle")}
|
|
description={t("FrmDeleteConfirmDesc")}
|
|
confirmLabel={t("Delete")}
|
|
onConfirm={() => void remove()}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|