Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+141
-257
@@ -1,38 +1,39 @@
|
||||
/**
|
||||
* Tenant admin: form detail editor + submissions inbox (Phase 05 #58).
|
||||
* Tenant admin: form detail editor + submissions inbox (Phase 05 #58,
|
||||
* Subframe re-skin WF-P16 S02/S02L/S03/S05).
|
||||
*
|
||||
* The editor has been promoted from a JSON-textarea to a visual
|
||||
* drag-drop builder via `apps/web/app/modules/formWidget/builder/`.
|
||||
* Tabs (Builder / Settings / Preview) replace the linear form-fields
|
||||
* layout. The action endpoint accepts the same `definition` + `theme`
|
||||
* JSON shapes, plus targetType + fieldMapping persisted on the parent
|
||||
* Form row.
|
||||
* 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.
|
||||
*
|
||||
* Submissions table shows the 50 most-recent rows with sourceOrigin +
|
||||
* status + an inline JSON preview, plus a CSV export action that
|
||||
* streams via Response.
|
||||
* The loader also serves `?export=csv|pdf` streams for the responses
|
||||
* tab.
|
||||
*/
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, Form, Link, useActionData } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
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 { 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 { FormBuilder } from "~/modules/formWidget/builder/FormBuilder";
|
||||
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 { formsOwnerWhere, loadFormsContext, requireFormsPermission } from "~/modules/forms/routes/formsAccess.server";
|
||||
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;
|
||||
@@ -59,6 +60,7 @@ type SubmissionRow = {
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
form: FormDetail;
|
||||
submissions: SubmissionRow[];
|
||||
columns: Array<{ key: string; label: string; type: string }>;
|
||||
@@ -67,7 +69,17 @@ type LoaderData = {
|
||||
publicFormUrl: string | null;
|
||||
};
|
||||
|
||||
type ActionData = { error?: string; success?: string };
|
||||
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",
|
||||
@@ -79,6 +91,7 @@ const FORM_ACTION_TYPES = new Set<FormActionSetting["actionType"]>([
|
||||
"send_email_to_submitter",
|
||||
"webhook",
|
||||
"trigger_automation",
|
||||
"start_double_opt_in",
|
||||
]);
|
||||
|
||||
function objectValue(value: unknown): Record<string, unknown> {
|
||||
@@ -92,23 +105,25 @@ function jsonObjectValue(value: unknown): 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);
|
||||
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> {
|
||||
@@ -117,8 +132,15 @@ function submissionValues(payload: unknown): Record<string, unknown> {
|
||||
}
|
||||
|
||||
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, '""')}"`;
|
||||
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 {
|
||||
@@ -144,9 +166,13 @@ function isHttpUrl(value: string | null | undefined): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
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);
|
||||
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 });
|
||||
@@ -157,6 +183,7 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
key: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
subtype: true,
|
||||
status: true,
|
||||
isPublic: true,
|
||||
definition: true,
|
||||
@@ -178,9 +205,7 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
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 }))
|
||||
? 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 = {
|
||||
@@ -194,7 +219,7 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1000,
|
||||
});
|
||||
const header = ["id", "createdAt", "status", "sourceOrigin", ...columns.map((column) => column.key)].join(",") + "\n";
|
||||
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(",");
|
||||
@@ -207,6 +232,7 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
});
|
||||
}
|
||||
if (url.searchParams.get("export") === "pdf") {
|
||||
const { buildPdfExportArtifact } = await import("@hivegrid/exports/pdf");
|
||||
const all = await db.formSubmission.findMany({
|
||||
where: submissionWhere,
|
||||
orderBy: { createdAt: "desc" },
|
||||
@@ -232,7 +258,7 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
};
|
||||
}),
|
||||
},
|
||||
{ title: `${form.name} - ${t("settings.forms.admin.detail.submissionsLatest")}` },
|
||||
{ title: `${form.name} - ${t("settings.forms.admin.detail.submissionsLatest")}` }
|
||||
);
|
||||
return new Response(new Uint8Array(artifact.bytes).buffer, {
|
||||
headers: {
|
||||
@@ -265,6 +291,7 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
},
|
||||
});
|
||||
const payload: LoaderData = {
|
||||
title: `${form.name} | ${process.env.APP_NAME}`,
|
||||
form: {
|
||||
...form,
|
||||
actions: form.actions.map((action) => ({
|
||||
@@ -290,16 +317,19 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
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,
|
||||
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 ctx = await loadFormsContext({ request, params, requireModule: true });
|
||||
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);
|
||||
@@ -345,9 +375,7 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
} catch {
|
||||
return { error: t("settings.forms.admin.errors.invalidDefinitionJson") };
|
||||
}
|
||||
const defParse = FormDefinitionSchema.safeParse(
|
||||
applyFormDefinitionDefaults(definition, (key) => t(key))
|
||||
);
|
||||
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) }) };
|
||||
@@ -404,6 +432,35 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
});
|
||||
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";
|
||||
@@ -415,7 +472,11 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
publishedAt: nextPublic ? new Date() : null,
|
||||
},
|
||||
});
|
||||
return { success: t(nextPublic ? "settings.forms.admin.messages.published" : "settings.forms.admin.messages.unpublished") };
|
||||
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");
|
||||
@@ -453,7 +514,7 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
dispatchKey: `form-submission-rerun:${submission.id}:${Date.now()}`,
|
||||
});
|
||||
});
|
||||
return { success: t("settings.forms.admin.messages.rerunQueued") };
|
||||
return { ok: true, intent: op, messageKey: "settings.forms.admin.messages.rerunQueued" };
|
||||
}
|
||||
return { error: t("settings.forms.admin.errors.unknownOperation") };
|
||||
}
|
||||
@@ -461,15 +522,10 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
export default function FormDetailPage(): React.JSX.Element {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData() as LoaderData;
|
||||
const action = useActionData() as ActionData | undefined;
|
||||
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
|
||||
// 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.
|
||||
@@ -508,180 +564,30 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
actions: data.form.actions,
|
||||
};
|
||||
|
||||
const [name, setName] = useState(data.form.name);
|
||||
const [definition, setDefinition] = useState<FormDefinition>(initialDefinition);
|
||||
const [theme, setTheme] = useState<FormTheme>(initialTheme);
|
||||
const [settings, setSettings] = useState<FormSettingsValue>(initialSettings);
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<Link to=".." className="text-sm text-blue-700 hover:underline">{t("settings.forms.admin.detail.backToForms")}</Link>
|
||||
<header className="flex items-center justify-between gap-3">
|
||||
<input
|
||||
aria-label={t("settings.forms.admin.detail.formName")}
|
||||
className="text-2xl font-semibold border-b border-transparent focus:border-blue-500 focus:outline-none px-1 py-0.5"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<Form method="post" replace>
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="save" />
|
||||
<input type="hidden" name="name" value={name} />
|
||||
<input type="hidden" name="definition" value={JSON.stringify(definition)} />
|
||||
<input type="hidden" name="theme" value={JSON.stringify(theme)} />
|
||||
<input type="hidden" name="allowedOrigins" value={settings.allowedOrigins.join("\n")} />
|
||||
<input type="hidden" name="notifyEmails" value={settings.notifyEmails.join("\n")} />
|
||||
<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>
|
||||
</Form>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<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}
|
||||
{action?.success ? <p className="text-green-700 text-sm">{action.success}</p> : null}
|
||||
|
||||
<FormBuilder
|
||||
initialDefinition={initialDefinition}
|
||||
initialTheme={initialTheme}
|
||||
initialSettings={initialSettings}
|
||||
onChange={(snapshot) => {
|
||||
setDefinition(snapshot.definition);
|
||||
setTheme(snapshot.theme);
|
||||
setSettings(snapshot.settings);
|
||||
}}
|
||||
/>
|
||||
|
||||
<section>
|
||||
<header className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-medium">{t("settings.forms.admin.detail.submissionsLatest")}</h2>
|
||||
<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>
|
||||
) : (
|
||||
<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>
|
||||
<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)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -693,33 +599,11 @@ export function applyFormDefinitionDefaults(value: unknown, t: (key: string) =>
|
||||
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"),
|
||||
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"),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Visual status badge for `FormSubmission.status`. The status string is
|
||||
* produced by the form-submission-route worker (Phase 05 #58) — the
|
||||
* admin UI surfaces it inline next to each submission so operators can
|
||||
* see at a glance whether routing succeeded.
|
||||
*/
|
||||
function RoutingStatusBadge({ status }: { status: string }): React.JSX.Element {
|
||||
const palette: Record<string, string> = {
|
||||
received: "bg-gray-100 text-gray-700 border-gray-300",
|
||||
processed: "bg-blue-50 text-blue-700 border-blue-200",
|
||||
"routed-to-crm": "bg-green-50 text-green-700 border-green-200",
|
||||
"routed-to-entity": "bg-green-50 text-green-700 border-green-200",
|
||||
"route-failed": "bg-red-50 text-red-700 border-red-200",
|
||||
spam: "bg-yellow-50 text-yellow-700 border-yellow-200",
|
||||
};
|
||||
const className = palette[status] ?? "bg-gray-100 text-gray-700 border-gray-300";
|
||||
return (
|
||||
<span className={`inline-block px-1.5 py-0.5 border rounded text-[10px] uppercase tracking-wide ${className}`}>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user