Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+413
-48
@@ -15,21 +15,26 @@
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, Form, Link, useActionData } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { QRCodeSVG } from "qrcode.react";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { buildPdfExportArtifact } from "@hivegrid/exports/pdf";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { FormDefinitionSchema, FormThemeSchema, type FormDefinition, type FormTheme } from "@toolctrl/form-widget";
|
||||
import { FormDefinitionSchema, FormThemeSchema, type FormDefinition, type FormTheme } from "@hivegrid/form-widget";
|
||||
import { FormBuilder } from "~/modules/formWidget/builder/FormBuilder";
|
||||
import type { FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
|
||||
import type { FormActionJsonObject, FormActionSetting, FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { formsOwnerWhere, loadFormsContext, requireFormsPermission } from "~/modules/forms/routes/formsAccess.server";
|
||||
|
||||
type FormDetail = {
|
||||
id: string;
|
||||
key: string;
|
||||
slug: string | null;
|
||||
name: string;
|
||||
status: string;
|
||||
isPublic: boolean;
|
||||
definition: unknown;
|
||||
theme: unknown;
|
||||
targetType: string;
|
||||
@@ -38,24 +43,93 @@ type FormDetail = {
|
||||
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 = {
|
||||
form: FormDetail;
|
||||
submissions: SubmissionRow[];
|
||||
columns: Array<{ key: string; label: string; type: string }>;
|
||||
statusFilter: string;
|
||||
embedScriptBase: string;
|
||||
publicFormUrl: string | null;
|
||||
};
|
||||
|
||||
type ActionData = { error?: string; success?: 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",
|
||||
]);
|
||||
|
||||
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);
|
||||
return `"${raw.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 {
|
||||
@@ -72,16 +146,19 @@ function isHttpUrl(value: string | null | undefined): boolean {
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const ctx = await loadFormsContext({ request, params, requireModule: true });
|
||||
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 },
|
||||
where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) },
|
||||
select: {
|
||||
id: true,
|
||||
key: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
status: true,
|
||||
isPublic: true,
|
||||
definition: true,
|
||||
theme: true,
|
||||
targetType: true,
|
||||
@@ -90,24 +167,37 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
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: { formId: id, tenantId },
|
||||
where: submissionWhere,
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1000,
|
||||
});
|
||||
const header = "id,createdAt,status,sourceOrigin,values\n";
|
||||
const header = ["id", "createdAt", "status", "sourceOrigin", ...columns.map((column) => column.key)].join(",") + "\n";
|
||||
const rows = all.map((s) => {
|
||||
const vals = typeof s.payload === "object" && s.payload && "values" in s.payload
|
||||
? JSON.stringify((s.payload as { values: unknown }).values)
|
||||
: JSON.stringify(s.payload);
|
||||
const safe = vals.replace(/"/g, '""');
|
||||
return `${s.id},${s.createdAt.toISOString()},${s.status},${s.sourceOrigin ?? ""},"${safe}"`;
|
||||
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: {
|
||||
@@ -116,30 +206,101 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url.searchParams.get("export") === "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: { formId: id, tenantId },
|
||||
where: submissionWhere,
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
select: { id: true, status: true, sourceOrigin: true, createdAt: true, payload: true },
|
||||
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 = {
|
||||
form: { ...form },
|
||||
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({ request, params }: ActionFunctionArgs): Promise<ActionData> {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const ctx = await loadFormsContext({ request, params, requireModule: true });
|
||||
requireFormsPermission(ctx, "forms.builder");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const id = params.id;
|
||||
@@ -147,7 +308,7 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
const body = await request.formData();
|
||||
const op = body.get("op")?.toString() ?? "save";
|
||||
|
||||
const target = await db.form.findFirst({ where: { id, tenantId }, select: { id: true } });
|
||||
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") {
|
||||
@@ -167,11 +328,12 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
return { error: t("settings.forms.admin.errors.invalidWebhookUrl") };
|
||||
}
|
||||
const targetTypeRaw = body.get("targetType")?.toString()?.trim() ?? "generic";
|
||||
const allowedTargets = new Set(["generic", "crm-contact", "entity-row"]);
|
||||
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() ?? "{}");
|
||||
@@ -179,6 +341,7 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
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") };
|
||||
}
|
||||
@@ -188,20 +351,109 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
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 === "publish") {
|
||||
requireFormsPermission(ctx, "forms.publisher");
|
||||
const nextPublic = body.get("isPublic")?.toString() === "true";
|
||||
await db.form.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name,
|
||||
definition: defParse.data as object,
|
||||
theme: themeParse.data as object,
|
||||
allowedOrigins,
|
||||
notifyEmails,
|
||||
webhookUrl,
|
||||
targetType,
|
||||
fieldMapping: fieldMapping as object,
|
||||
isPublic: nextPublic,
|
||||
status: nextPublic ? "published" : "draft",
|
||||
publishedAt: nextPublic ? new Date() : null,
|
||||
},
|
||||
});
|
||||
return { success: t("settings.forms.admin.messages.saved") };
|
||||
return { success: t(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 { success: t("settings.forms.admin.messages.rerunQueued") };
|
||||
}
|
||||
return { error: t("settings.forms.admin.errors.unknownOperation") };
|
||||
}
|
||||
@@ -213,6 +465,9 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
const rootData = useRootData();
|
||||
const formatters = useLocaleFormatters();
|
||||
const embedSnippet = `<script src="${data.embedScriptBase}/embed/widget.js" data-form-key="${data.form.key}" async></script>`;
|
||||
const iframeSnippet = data.publicFormUrl
|
||||
? `<iframe src="${data.publicFormUrl}" width="100%" height="720" style="border:0"></iframe>`
|
||||
: "";
|
||||
|
||||
// Initial state for the builder. The DB shapes are unknown until we
|
||||
// parse them; we use the canonical zod parsers so invalid persisted
|
||||
@@ -225,7 +480,18 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
title: data.form.name || t("settings.forms.defaults.untitled"),
|
||||
submitLabel: t("settings.forms.admin.defaults.submitLabel"),
|
||||
successMessage: t("settings.forms.admin.defaults.successMessage"),
|
||||
fields: [{ key: "email", type: "email", label: t("settings.forms.admin.defaults.fields.email"), required: true }],
|
||||
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 : {};
|
||||
@@ -239,6 +505,7 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
webhookUrl: data.form.webhookUrl ?? "",
|
||||
targetType: data.form.targetType || "generic",
|
||||
fieldMapping: initialFieldMapping,
|
||||
actions: data.form.actions,
|
||||
};
|
||||
|
||||
const [name, setName] = useState(data.form.name);
|
||||
@@ -267,6 +534,7 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
<input type="hidden" name="webhookUrl" value={settings.webhookUrl} />
|
||||
<input type="hidden" name="targetType" value={settings.targetType} />
|
||||
<input type="hidden" name="fieldMapping" value={JSON.stringify(settings.fieldMapping)} />
|
||||
<input type="hidden" name="actions" value={JSON.stringify(settings.actions)} />
|
||||
<button type="submit" className="bg-blue-600 text-white px-4 py-1.5 rounded text-sm">
|
||||
{t("shared.save")}
|
||||
</button>
|
||||
@@ -274,8 +542,33 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-600">{t("settings.forms.admin.detail.embedSnippet")}</h2>
|
||||
<pre className="text-xs bg-gray-50 p-2 rounded overflow-x-auto">{embedSnippet}</pre>
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-600">{t("settings.forms.admin.detail.sharing")}</h2>
|
||||
{data.publicFormUrl ? (
|
||||
<>
|
||||
<a className="text-sm text-blue-700 underline break-all" href={data.publicFormUrl} target="_blank" rel="noreferrer">
|
||||
{data.publicFormUrl}
|
||||
</a>
|
||||
<pre className="text-xs bg-gray-50 p-2 rounded overflow-x-auto">{iframeSnippet}</pre>
|
||||
</>
|
||||
) : null}
|
||||
<pre className="text-xs bg-gray-50 p-2 rounded overflow-x-auto">{embedSnippet}</pre>
|
||||
</div>
|
||||
{data.publicFormUrl ? (
|
||||
<div className="rounded border bg-white p-2">
|
||||
<QRCodeSVG value={data.publicFormUrl} size={128} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<Form method="post" className="mt-3">
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="publish" />
|
||||
<input type="hidden" name="isPublic" value={data.form.isPublic ? "false" : "true"} />
|
||||
<button type="submit" className="text-sm border rounded px-3 py-1">
|
||||
{data.form.isPublic ? t("settings.forms.admin.detail.unpublish") : t("settings.forms.admin.detail.publish")}
|
||||
</button>
|
||||
</Form>
|
||||
</section>
|
||||
|
||||
{action?.error ? <p className="text-red-600 text-sm">{action.error}</p> : null}
|
||||
@@ -295,25 +588,97 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
<section>
|
||||
<header className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-medium">{t("settings.forms.admin.detail.submissionsLatest")}</h2>
|
||||
<a href="?export=csv" className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.exportCsv")}</a>
|
||||
<div className="flex items-center gap-2">
|
||||
<Form method="get" className="flex items-center gap-2">
|
||||
<select name="status" defaultValue={data.statusFilter} className="rounded border px-2 py-1 text-sm">
|
||||
<option value="">{t("settings.forms.admin.detail.filters.allStatuses")}</option>
|
||||
<option value="received">{t("settings.forms.admin.detail.filters.received")}</option>
|
||||
<option value="processed">{t("settings.forms.admin.detail.filters.processed")}</option>
|
||||
<option value="route-failed">{t("settings.forms.admin.detail.filters.failed")}</option>
|
||||
</select>
|
||||
<button type="submit" className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.filters.apply")}</button>
|
||||
</Form>
|
||||
<a href={`?export=csv${data.statusFilter ? `&status=${encodeURIComponent(data.statusFilter)}` : ""}`} className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.exportCsv")}</a>
|
||||
<a href={`?export=pdf${data.statusFilter ? `&status=${encodeURIComponent(data.statusFilter)}` : ""}`} className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.exportPdf")}</a>
|
||||
</div>
|
||||
</header>
|
||||
{data.submissions.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">{t("settings.forms.admin.detail.noSubmissions")}</p>
|
||||
) : (
|
||||
<ul className="divide-y border rounded mt-2">
|
||||
{data.submissions.map((s) => (
|
||||
<li key={s.id} className="p-3">
|
||||
<div className="flex items-center gap-2 text-xs text-gray-500">
|
||||
<time dateTime={s.createdAt}>{formatters.dateTime(s.createdAt, { timeStyle: "medium" })}</time>
|
||||
<span>{"·"}</span>
|
||||
<RoutingStatusBadge status={s.status} />
|
||||
<span>{"·"}</span>
|
||||
<span>{t("settings.forms.admin.detail.origin", { origin: s.sourceOrigin ?? t("shared.notSet") })}</span>
|
||||
</div>
|
||||
<pre className="text-xs mt-1 whitespace-pre-wrap break-words">{s.preview}</pre>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="mt-2 overflow-x-auto rounded border">
|
||||
<table className="min-w-full divide-y text-sm">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium">{t("settings.forms.admin.detail.submittedAt")}</th>
|
||||
<th className="px-3 py-2 text-left font-medium">{t("settings.forms.admin.detail.status")}</th>
|
||||
{data.columns.map((column) => (
|
||||
<th key={column.key} className="px-3 py-2 text-left font-medium">{column.label}</th>
|
||||
))}
|
||||
<th className="px-3 py-2 text-left font-medium">{t("settings.forms.admin.detail.files")}</th>
|
||||
<th className="px-3 py-2 text-left font-medium">{t("settings.forms.admin.detail.actions")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-white">
|
||||
{data.submissions.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td className="px-3 py-2 align-top whitespace-nowrap">
|
||||
<time dateTime={s.createdAt}>{formatters.dateTime(s.createdAt, { timeStyle: "medium" })}</time>
|
||||
<div className="text-xs text-gray-500">{t("settings.forms.admin.detail.origin", { origin: s.sourceOrigin ?? t("shared.notSet") })}</div>
|
||||
</td>
|
||||
<td className="px-3 py-2 align-top"><RoutingStatusBadge status={s.status} /></td>
|
||||
{data.columns.map((column) => (
|
||||
<td key={column.key} className="max-w-[220px] px-3 py-2 align-top">
|
||||
<span className="line-clamp-3 break-words">{displaySubmissionValue(s.values[column.key]) || t("shared.notSet")}</span>
|
||||
</td>
|
||||
))}
|
||||
<td className="px-3 py-2 align-top">
|
||||
{s.files.length === 0 ? (
|
||||
<span className="text-gray-400">{t("shared.notSet")}</span>
|
||||
) : (
|
||||
<ul className="space-y-1">
|
||||
{s.files.map((file) => (
|
||||
<li key={`${file.fieldKey}:${file.fileId}`}>
|
||||
<Link className="text-blue-700 underline" to={`../media/${file.fileId}/original`}>
|
||||
{file.fieldKey}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 align-top">
|
||||
<details>
|
||||
<summary className="cursor-pointer text-blue-700">{t("settings.forms.admin.detail.details")}</summary>
|
||||
<dl className="mt-2 space-y-1 text-xs">
|
||||
<div><dt className="font-medium">{t("settings.forms.admin.detail.userAgent")}</dt><dd className="break-all">{s.userAgent ?? t("shared.notSet")}</dd></div>
|
||||
<div><dt className="font-medium">{t("settings.forms.admin.detail.payload")}</dt><dd><pre className="whitespace-pre-wrap break-words">{s.preview}</pre></dd></div>
|
||||
</dl>
|
||||
{s.actionLogs.length > 0 ? (
|
||||
<ul className="mt-2 space-y-1">
|
||||
{s.actionLogs.map((log) => (
|
||||
<li key={log.id} className="text-xs text-gray-600">
|
||||
<code>{log.actionType}</code> {"-"} {log.status}
|
||||
{log.targetId ? <> {"-"} {log.targetType}:{log.targetId}</> : null}
|
||||
{log.errorMessage ? <span className="text-red-600"> {"-"} {log.errorMessage}</span> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
<Form method="post" className="mt-2">
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="rerun-submission" />
|
||||
<input type="hidden" name="submissionId" value={s.id} />
|
||||
<button type="submit" className="text-xs border rounded px-2 py-1">
|
||||
{t("settings.forms.admin.detail.rerunSubmission")}
|
||||
</button>
|
||||
</Form>
|
||||
</details>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user