610 lines
23 KiB
TypeScript
610 lines
23 KiB
TypeScript
/**
|
|
* Tenant admin: form detail editor + submissions inbox (Phase 05 #58,
|
|
* Subframe re-skin WF-P16 S02/S02L/S03/S05).
|
|
*
|
|
* Loader + action remain the single data source. The default component
|
|
* is a thin wrapper around the FormEditorPage screen component
|
|
* (`~/components/screens/forms/FormEditorPage`), which autosaves via
|
|
* the unchanged `op=save` contract and drives publish / duplicate /
|
|
* delete / rerun-submission through the additional ops below.
|
|
*
|
|
* The loader also serves `?export=csv|pdf` streams for the responses
|
|
* tab.
|
|
*/
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData } from "react-router";
|
|
import { useTranslation } from "react-i18next";
|
|
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { db } from "~/utils/db.server";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { validateCSRFToken } from "~/utils/session.server";
|
|
import { FormDefinitionSchema, FormThemeSchema, type FormDefinition, type FormTheme } from "@hivegrid/form-widget";
|
|
import { neutralizeSpreadsheetFormula } from "@hivegrid/foundation/spreadsheet-safety";
|
|
import type { FormActionJsonObject, FormActionSetting, FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import { useLocaleFormatters } from "~/locale/format";
|
|
import { duplicateForm } from "~/modules/forms/services/createDraftForm.server";
|
|
import { formsOwnerWhere, loadFormsContext, requireFormsPermission, type FormsRouteContext } from "~/modules/forms/routes/formsAccess.server";
|
|
import { FormEditorPage } from "~/components/screens/forms/FormEditorPage";
|
|
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
|
|
|
type FormDetail = {
|
|
id: string;
|
|
key: string;
|
|
slug: string | null;
|
|
name: string;
|
|
subtype: string;
|
|
status: string;
|
|
isPublic: boolean;
|
|
definition: unknown;
|
|
theme: unknown;
|
|
targetType: string;
|
|
fieldMapping: unknown;
|
|
allowedOrigins: string[];
|
|
notifyEmails: string[];
|
|
webhookUrl: string | null;
|
|
isEnabled: boolean;
|
|
actions: FormActionSetting[];
|
|
};
|
|
|
|
type SubmissionRow = {
|
|
id: string;
|
|
status: string;
|
|
sourceOrigin: string | null;
|
|
userAgent: string | null;
|
|
createdAt: string;
|
|
values: Record<string, unknown>;
|
|
preview: string;
|
|
files: Array<{ fieldKey: string; fileId: string; kind: string }>;
|
|
actionLogs: Array<{ id: string; actionType: string; status: string; targetType: string | null; targetId: string | null; errorMessage: string | null }>;
|
|
};
|
|
|
|
type LoaderData = {
|
|
title: string;
|
|
form: FormDetail;
|
|
submissions: SubmissionRow[];
|
|
columns: Array<{ key: string; label: string; type: string }>;
|
|
statusFilter: string;
|
|
embedScriptBase: string;
|
|
publicFormUrl: string | null;
|
|
};
|
|
|
|
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
|
|
|
type ActionData = {
|
|
error?: string;
|
|
success?: string;
|
|
ok?: true;
|
|
intent?: string;
|
|
messageKey?: string;
|
|
duplicatedId?: string;
|
|
redirectTo?: string;
|
|
};
|
|
|
|
const FORM_ACTION_TYPES = new Set<FormActionSetting["actionType"]>([
|
|
"auto_match",
|
|
"create_lead",
|
|
"create_contact",
|
|
"create_project",
|
|
"create_task",
|
|
"send_email_to_team",
|
|
"send_email_to_submitter",
|
|
"webhook",
|
|
"trigger_automation",
|
|
"start_double_opt_in",
|
|
]);
|
|
|
|
function objectValue(value: unknown): Record<string, unknown> {
|
|
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
|
|
}
|
|
|
|
function jsonObjectValue(value: unknown): FormActionJsonObject {
|
|
const raw = objectValue(value);
|
|
return JSON.parse(JSON.stringify(raw)) as FormActionJsonObject;
|
|
}
|
|
|
|
function parseFormActions(value: unknown): FormActionSetting[] {
|
|
if (!Array.isArray(value)) return [];
|
|
return value
|
|
.flatMap((entry) => {
|
|
const raw = objectValue(entry);
|
|
const actionType = raw.actionType;
|
|
if (typeof actionType !== "string" || !FORM_ACTION_TYPES.has(actionType as FormActionSetting["actionType"])) {
|
|
return [];
|
|
}
|
|
const name = typeof raw.name === "string" && raw.name.trim() ? raw.name.trim().slice(0, 120) : actionType;
|
|
return [
|
|
{
|
|
actionType: actionType as FormActionSetting["actionType"],
|
|
name,
|
|
enabled: raw.enabled !== false,
|
|
fieldMapping: objectValue(raw.fieldMapping) as Record<string, string>,
|
|
actionConfig: jsonObjectValue(raw.actionConfig),
|
|
},
|
|
];
|
|
})
|
|
.slice(0, 20);
|
|
}
|
|
|
|
function submissionValues(payload: unknown): Record<string, unknown> {
|
|
const raw = objectValue(payload);
|
|
return objectValue(raw.values);
|
|
}
|
|
|
|
function csvCell(value: unknown): string {
|
|
const raw = Array.isArray(value)
|
|
? value.join("; ")
|
|
: value === null || value === undefined
|
|
? ""
|
|
: typeof value === "object"
|
|
? JSON.stringify(value)
|
|
: String(value);
|
|
const safeValue = neutralizeSpreadsheetFormula(raw);
|
|
return `"${safeValue.replace(/"/g, '""')}"`;
|
|
}
|
|
|
|
function displaySubmissionValue(value: unknown): string {
|
|
if (Array.isArray(value)) return value.join(", ");
|
|
if (value === true) return "true";
|
|
if (value === false) return "false";
|
|
if (value === null || value === undefined || value === "") return "";
|
|
if (typeof value === "object") return JSON.stringify(value);
|
|
return String(value);
|
|
}
|
|
|
|
function isHttpUrl(value: string | null | undefined): boolean {
|
|
if (!value) return false;
|
|
try {
|
|
const u = new URL(value);
|
|
if (u.protocol !== "https:" && u.protocol !== "http:") return false;
|
|
const host = u.hostname.toLowerCase();
|
|
if (host === "localhost" || host === "127.0.0.1" || host.endsWith(".internal")) return false;
|
|
if (host === "0.0.0.0" || host.startsWith("10.") || host.startsWith("192.168.") || host.startsWith("169.254.")) return false;
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function loader(args: LoaderFunctionArgs): Promise<Response> {
|
|
const ctx = await loadFormsContext({ request: args.request, params: args.params, requireModule: true });
|
|
return runWithRlsContext({ tenantId: ctx.tenantId, userId: ctx.userId }, () => loadFormDetail(args, ctx));
|
|
}
|
|
|
|
async function loadFormDetail({ request, params }: LoaderFunctionArgs, ctx: FormsRouteContext): Promise<Response> {
|
|
const { t } = await getTranslations(request);
|
|
requireFormsPermission(ctx, "forms.basic");
|
|
const id = params.id;
|
|
if (!id) throw new Response(t("shared.notFound"), { status: 404 });
|
|
const form = await db.form.findFirst({
|
|
where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) },
|
|
select: {
|
|
id: true,
|
|
key: true,
|
|
slug: true,
|
|
name: true,
|
|
subtype: true,
|
|
status: true,
|
|
isPublic: true,
|
|
definition: true,
|
|
theme: true,
|
|
targetType: true,
|
|
fieldMapping: true,
|
|
allowedOrigins: true,
|
|
notifyEmails: true,
|
|
webhookUrl: true,
|
|
isEnabled: true,
|
|
actions: {
|
|
orderBy: { position: "asc" },
|
|
select: { id: true, actionType: true, name: true, enabled: true, fieldMapping: true, actionConfig: true },
|
|
},
|
|
},
|
|
});
|
|
if (!form) throw new Response(t("settings.forms.admin.errors.formNotFound"), { status: 404 });
|
|
|
|
const url = new URL(request.url);
|
|
const definitionParsed = FormDefinitionSchema.safeParse(form.definition);
|
|
const columns = definitionParsed.success
|
|
? definitionParsed.data.fields.filter((field) => field.type !== "honeypot").map((field) => ({ key: field.key, label: field.label, type: field.type }))
|
|
: [];
|
|
const statusFilter = url.searchParams.get("status")?.trim() ?? "";
|
|
const submissionWhere = {
|
|
formId: id,
|
|
tenantId: ctx.tenantId,
|
|
...(statusFilter ? { status: statusFilter } : {}),
|
|
};
|
|
if (url.searchParams.get("export") === "csv") {
|
|
const all = await db.formSubmission.findMany({
|
|
where: submissionWhere,
|
|
orderBy: { createdAt: "desc" },
|
|
take: 1000,
|
|
});
|
|
const header = ["id", "createdAt", "status", "sourceOrigin", ...columns.map((column) => column.key)].map(csvCell).join(",") + "\n";
|
|
const rows = all.map((s) => {
|
|
const values = submissionValues(s.payload);
|
|
return [s.id, s.createdAt.toISOString(), s.status, s.sourceOrigin ?? "", ...columns.map((column) => values[column.key])].map(csvCell).join(",");
|
|
});
|
|
return new Response(header + rows.join("\n"), {
|
|
headers: {
|
|
"content-type": "text/csv; charset=utf-8",
|
|
"content-disposition": `attachment; filename="form-${form.key}-submissions.csv"`,
|
|
},
|
|
});
|
|
}
|
|
if (url.searchParams.get("export") === "pdf") {
|
|
const { buildPdfExportArtifact } = await import("@hivegrid/exports/pdf");
|
|
const all = await db.formSubmission.findMany({
|
|
where: submissionWhere,
|
|
orderBy: { createdAt: "desc" },
|
|
take: 1000,
|
|
});
|
|
const artifact = await buildPdfExportArtifact(
|
|
{
|
|
columns: [
|
|
{ key: "id", label: "ID" },
|
|
{ key: "createdAt", label: t("settings.forms.admin.detail.submittedAt") },
|
|
{ key: "status", label: t("settings.forms.admin.detail.status") },
|
|
{ key: "sourceOrigin", label: t("settings.forms.admin.detail.originPdf") },
|
|
...columns.map((column) => ({ key: column.key, label: column.label })),
|
|
],
|
|
rows: all.map((s) => {
|
|
const values = submissionValues(s.payload);
|
|
return {
|
|
id: s.id,
|
|
createdAt: s.createdAt.toISOString(),
|
|
status: s.status,
|
|
sourceOrigin: s.sourceOrigin ?? "",
|
|
...Object.fromEntries(columns.map((column) => [column.key, displaySubmissionValue(values[column.key])])),
|
|
};
|
|
}),
|
|
},
|
|
{ title: `${form.name} - ${t("settings.forms.admin.detail.submissionsLatest")}` }
|
|
);
|
|
return new Response(new Uint8Array(artifact.bytes).buffer, {
|
|
headers: {
|
|
"content-type": artifact.contentType,
|
|
"content-disposition": `attachment; filename="form-${form.key}-submissions.pdf"`,
|
|
},
|
|
});
|
|
}
|
|
|
|
const submissions = await db.formSubmission.findMany({
|
|
where: submissionWhere,
|
|
orderBy: { createdAt: "desc" },
|
|
take: 50,
|
|
select: {
|
|
id: true,
|
|
status: true,
|
|
sourceOrigin: true,
|
|
userAgent: true,
|
|
createdAt: true,
|
|
payload: true,
|
|
files: {
|
|
orderBy: { createdAt: "asc" },
|
|
select: { fieldKey: true, fileId: true, kind: true },
|
|
},
|
|
actionLogs: {
|
|
orderBy: { createdAt: "desc" },
|
|
take: 8,
|
|
select: { id: true, actionType: true, status: true, targetType: true, targetId: true, errorMessage: true },
|
|
},
|
|
},
|
|
});
|
|
const payload: LoaderData = {
|
|
title: `${form.name} | ${process.env.APP_NAME}`,
|
|
form: {
|
|
...form,
|
|
actions: form.actions.map((action) => ({
|
|
id: action.id,
|
|
actionType: action.actionType,
|
|
name: action.name,
|
|
enabled: action.enabled,
|
|
fieldMapping: objectValue(action.fieldMapping) as Record<string, string>,
|
|
actionConfig: jsonObjectValue(action.actionConfig),
|
|
})),
|
|
},
|
|
submissions: submissions.map((s) => ({
|
|
values: submissionValues(s.payload),
|
|
id: s.id,
|
|
status: s.status,
|
|
sourceOrigin: s.sourceOrigin,
|
|
userAgent: s.userAgent,
|
|
createdAt: s.createdAt.toISOString(),
|
|
preview: JSON.stringify(s.payload).slice(0, 240),
|
|
files: s.files,
|
|
actionLogs: s.actionLogs,
|
|
})),
|
|
columns,
|
|
statusFilter,
|
|
embedScriptBase: process.env.FORM_WIDGET_CDN_URL?.trim() || process.env.APP_URL?.trim() || "",
|
|
publicFormUrl: form.slug
|
|
? `${(process.env.APP_URL?.trim() || new URL(request.url).origin).replace(/\/+$/u, "")}/f/${encodeURIComponent(params.tenant ?? ctx.tenantId)}/${encodeURIComponent(form.slug)}`
|
|
: null,
|
|
};
|
|
return Response.json(payload);
|
|
}
|
|
|
|
export async function action(args: ActionFunctionArgs): Promise<Response | ActionData> {
|
|
const ctx = await loadFormsContext({ request: args.request, params: args.params, requireModule: true });
|
|
return runWithRlsContext({ tenantId: ctx.tenantId, userId: ctx.userId }, () => mutateFormDetail(args, ctx));
|
|
}
|
|
|
|
async function mutateFormDetail({ request, params }: ActionFunctionArgs, ctx: FormsRouteContext): Promise<Response | ActionData> {
|
|
requireFormsPermission(ctx, "forms.builder");
|
|
await validateCSRFToken(request);
|
|
const { t } = await getTranslations(request);
|
|
const id = params.id;
|
|
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
|
|
const body = await request.formData();
|
|
const op = body.get("op")?.toString() ?? "save";
|
|
|
|
const target = await db.form.findFirst({ where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) }, select: { id: true } });
|
|
if (!target) return { error: t("settings.forms.admin.errors.formNotFound") };
|
|
|
|
if (op === "save") {
|
|
const name = body.get("name")?.toString()?.trim();
|
|
if (!name) return { error: t("settings.forms.admin.errors.nameRequired") };
|
|
const allowedOrigins = (body.get("allowedOrigins")?.toString() ?? "")
|
|
.split("\n")
|
|
.map((s) => s.trim())
|
|
.filter(Boolean);
|
|
const notifyEmails = (body.get("notifyEmails")?.toString() ?? "")
|
|
.split(/[,\n]/)
|
|
.map((s) => s.trim())
|
|
.filter(Boolean);
|
|
const webhookUrlRaw = body.get("webhookUrl")?.toString()?.trim() ?? "";
|
|
const webhookUrl = webhookUrlRaw === "" ? null : webhookUrlRaw;
|
|
if (webhookUrl && !isHttpUrl(webhookUrl)) {
|
|
return { error: t("settings.forms.admin.errors.invalidWebhookUrl") };
|
|
}
|
|
const targetTypeRaw = body.get("targetType")?.toString()?.trim() ?? "generic";
|
|
const allowedTargets = new Set(["generic", "crm-contact", "create-lead"]);
|
|
const targetType = allowedTargets.has(targetTypeRaw) ? targetTypeRaw : "generic";
|
|
let definition: unknown;
|
|
let theme: unknown;
|
|
let fieldMapping: unknown = null;
|
|
let actions: unknown = [];
|
|
try {
|
|
definition = JSON.parse(body.get("definition")?.toString() ?? "{}");
|
|
theme = JSON.parse(body.get("theme")?.toString() ?? "{}");
|
|
const mappingRaw = body.get("fieldMapping")?.toString();
|
|
if (mappingRaw && mappingRaw.length > 0) {
|
|
fieldMapping = JSON.parse(mappingRaw);
|
|
}
|
|
actions = JSON.parse(body.get("actions")?.toString() ?? "[]");
|
|
} catch {
|
|
return { error: t("settings.forms.admin.errors.invalidDefinitionJson") };
|
|
}
|
|
const defParse = FormDefinitionSchema.safeParse(applyFormDefinitionDefaults(definition, (key) => t(key)));
|
|
if (!defParse.success) return { error: t("settings.forms.admin.errors.invalidDefinition", { details: defParse.error.message.slice(0, 240) }) };
|
|
const themeParse = FormThemeSchema.safeParse(theme);
|
|
if (!themeParse.success) return { error: t("settings.forms.admin.errors.invalidTheme", { details: themeParse.error.message.slice(0, 240) }) };
|
|
const actionRows = parseFormActions(actions);
|
|
await db.$transaction(async (tx) => {
|
|
await tx.form.update({
|
|
where: { id },
|
|
data: {
|
|
name,
|
|
definition: defParse.data as object,
|
|
theme: themeParse.data as object,
|
|
allowedOrigins,
|
|
notifyEmails,
|
|
webhookUrl,
|
|
targetType,
|
|
fieldMapping: fieldMapping as object,
|
|
},
|
|
});
|
|
await tx.formField.deleteMany({ where: { formId: id, tenantId: ctx.tenantId } });
|
|
if (defParse.data.fields.length > 0) {
|
|
await tx.formField.createMany({
|
|
data: defParse.data.fields.map((field, position) => ({
|
|
formId: id,
|
|
tenantId: ctx.tenantId,
|
|
fieldKey: field.key,
|
|
fieldType: field.type,
|
|
label: field.label,
|
|
helpText: field.helpText ?? null,
|
|
placeholder: field.placeholder ?? null,
|
|
required: field.required,
|
|
position,
|
|
options: field.options ?? [],
|
|
validationRules: field.validationRules ?? {},
|
|
conditionalLogic: field.conditionalLogic ?? [],
|
|
isSystem: field.type === "honeypot",
|
|
})),
|
|
});
|
|
}
|
|
await tx.formAction.deleteMany({ where: { formId: id, tenantId: ctx.tenantId } });
|
|
if (actionRows.length > 0) {
|
|
await tx.formAction.createMany({
|
|
data: actionRows.map((action, position) => ({
|
|
formId: id,
|
|
tenantId: ctx.tenantId,
|
|
actionType: action.actionType,
|
|
name: action.name,
|
|
enabled: action.enabled,
|
|
position,
|
|
fieldMapping: action.fieldMapping,
|
|
actionConfig: action.actionConfig,
|
|
})),
|
|
});
|
|
}
|
|
});
|
|
return { success: t("settings.forms.admin.messages.saved") };
|
|
}
|
|
if (op === "duplicate") {
|
|
const created = await duplicateForm({
|
|
tenantId: ctx.tenantId,
|
|
userId: ctx.userId,
|
|
sourceId: id,
|
|
ownerWhere: formsOwnerWhere(ctx),
|
|
copyName: (sourceName) => t("settings.forms.admin.list.copyName", { name: sourceName }),
|
|
});
|
|
if (!created) return { error: t("settings.forms.admin.errors.formNotFound") };
|
|
return {
|
|
ok: true,
|
|
intent: op,
|
|
messageKey: "settings.forms.admin.messages.duplicated",
|
|
duplicatedId: created.id,
|
|
};
|
|
}
|
|
if (op === "delete") {
|
|
await db.form.deleteMany({ where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) } });
|
|
// Redirect to the forms list; derived from the current pathname so it
|
|
// stays correct on both the app host (no /app prefix) and fallbacks.
|
|
const pathname = new URL(request.url).pathname;
|
|
const listPath = pathname.replace(/\/[^/]+\/?$/u, "") || "/";
|
|
return {
|
|
ok: true,
|
|
intent: op,
|
|
messageKey: "settings.forms.admin.messages.deleted",
|
|
redirectTo: listPath,
|
|
};
|
|
}
|
|
if (op === "publish") {
|
|
requireFormsPermission(ctx, "forms.publisher");
|
|
const nextPublic = body.get("isPublic")?.toString() === "true";
|
|
await db.form.update({
|
|
where: { id },
|
|
data: {
|
|
isPublic: nextPublic,
|
|
status: nextPublic ? "published" : "draft",
|
|
publishedAt: nextPublic ? new Date() : null,
|
|
},
|
|
});
|
|
return {
|
|
ok: true,
|
|
intent: op,
|
|
messageKey: nextPublic ? "settings.forms.admin.messages.published" : "settings.forms.admin.messages.unpublished",
|
|
};
|
|
}
|
|
if (op === "rerun-submission") {
|
|
requireFormsPermission(ctx, "forms.admin");
|
|
const submissionId = body.get("submissionId")?.toString();
|
|
if (!submissionId) return { error: t("settings.forms.admin.errors.missingSubmissionId") };
|
|
const submission = await db.formSubmission.findFirst({
|
|
where: { id: submissionId, formId: id, tenantId: ctx.tenantId },
|
|
select: { id: true, formId: true, tenantId: true, payload: true },
|
|
});
|
|
if (!submission) return { error: t("settings.forms.admin.errors.submissionNotFound") };
|
|
const values =
|
|
submission.payload && typeof submission.payload === "object" && "values" in submission.payload
|
|
? ((submission.payload as { values?: unknown }).values as Record<string, unknown>)
|
|
: {};
|
|
await db.$transaction(async (tx) => {
|
|
await tx.formSubmission.update({
|
|
where: { id: submission.id },
|
|
data: { status: "received", result: { rerunAt: new Date().toISOString() } },
|
|
});
|
|
const outboxPayload = {
|
|
submissionId: submission.id,
|
|
formId: submission.formId,
|
|
tenantId: ctx.tenantId,
|
|
targetType: "generic",
|
|
targetEntityId: null,
|
|
fieldMapping: {},
|
|
webhookUrl: null,
|
|
notifyEmails: [],
|
|
values,
|
|
} as unknown as Parameters<typeof publishOutboxEvent>[1]["payload"];
|
|
await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
|
|
tenantId: ctx.tenantId,
|
|
type: "form.submission.process",
|
|
payload: outboxPayload,
|
|
dispatchKey: `form-submission-rerun:${submission.id}:${Date.now()}`,
|
|
});
|
|
});
|
|
return { ok: true, intent: op, messageKey: "settings.forms.admin.messages.rerunQueued" };
|
|
}
|
|
return { error: t("settings.forms.admin.errors.unknownOperation") };
|
|
}
|
|
|
|
export default function FormDetailPage(): React.JSX.Element {
|
|
const { t } = useTranslation();
|
|
const data = useLoaderData() as LoaderData;
|
|
const rootData = useRootData();
|
|
const formatters = useLocaleFormatters();
|
|
|
|
// Initial state for the editor. The DB shapes are unknown until we
|
|
// parse them; we use the canonical zod parsers so invalid persisted
|
|
// payloads fall back to a safe minimal shape rather than crashing
|
|
// the route.
|
|
const definitionParsed = FormDefinitionSchema.safeParse(data.form.definition);
|
|
const initialDefinition: FormDefinition = definitionParsed.success
|
|
? definitionParsed.data
|
|
: ({
|
|
title: data.form.name || t("settings.forms.defaults.untitled"),
|
|
submitLabel: t("settings.forms.admin.defaults.submitLabel"),
|
|
successMessage: t("settings.forms.admin.defaults.successMessage"),
|
|
gdprConsentLabel: t("settings.forms.admin.defaults.gdprConsentLabel"),
|
|
captchaEnabled: true,
|
|
fields: [
|
|
{
|
|
key: "email",
|
|
type: "email",
|
|
label: t("settings.forms.admin.defaults.fields.email"),
|
|
required: true,
|
|
conditionalLogic: [],
|
|
validationRules: {},
|
|
},
|
|
],
|
|
} satisfies FormDefinition);
|
|
const themeParsed = FormThemeSchema.safeParse(data.form.theme ?? {});
|
|
const initialTheme: FormTheme = themeParsed.success ? themeParsed.data : {};
|
|
const initialFieldMapping =
|
|
data.form.fieldMapping && typeof data.form.fieldMapping === "object" && !Array.isArray(data.form.fieldMapping)
|
|
? (data.form.fieldMapping as Record<string, string>)
|
|
: {};
|
|
const initialSettings: FormSettingsValue = {
|
|
allowedOrigins: data.form.allowedOrigins,
|
|
notifyEmails: data.form.notifyEmails,
|
|
webhookUrl: data.form.webhookUrl ?? "",
|
|
targetType: data.form.targetType || "generic",
|
|
fieldMapping: initialFieldMapping,
|
|
actions: data.form.actions,
|
|
};
|
|
|
|
return (
|
|
<FormEditorPage
|
|
key={data.form.id}
|
|
form={{
|
|
id: data.form.id,
|
|
key: data.form.key,
|
|
slug: data.form.slug,
|
|
status: data.form.status,
|
|
isPublic: data.form.isPublic,
|
|
subtype: data.form.subtype,
|
|
}}
|
|
initialName={data.form.name}
|
|
initialDefinition={initialDefinition}
|
|
initialTheme={initialTheme}
|
|
initialSettings={initialSettings}
|
|
submissions={data.submissions}
|
|
columns={data.columns}
|
|
statusFilter={data.statusFilter}
|
|
embedScriptBase={data.embedScriptBase}
|
|
publicFormUrl={data.publicFormUrl}
|
|
csrf={rootData.csrf ?? ""}
|
|
formatDateTime={(value) => formatters.dateTime(value, { dateStyle: "medium", timeStyle: "short" })}
|
|
formatNumber={(value) => formatters.number(value)}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function applyFormDefinitionDefaults(value: unknown, t: (key: string) => string) {
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
return value;
|
|
}
|
|
|
|
const definition = value as Record<string, unknown>;
|
|
return {
|
|
...definition,
|
|
submitLabel:
|
|
typeof definition.submitLabel === "string" && definition.submitLabel.trim() ? definition.submitLabel : t("settings.forms.admin.defaults.submitLabel"),
|
|
successMessage:
|
|
typeof definition.successMessage === "string" && definition.successMessage.trim()
|
|
? definition.successMessage
|
|
: t("settings.forms.admin.defaults.successMessage"),
|
|
};
|
|
}
|