Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,360 @@
|
||||
/**
|
||||
* Tenant admin: form detail editor + submissions inbox (Phase 05 #58).
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* Submissions table shows the 50 most-recent rows with sourceOrigin +
|
||||
* status + an inline JSON preview, plus a CSV export action that
|
||||
* streams via Response.
|
||||
*/
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, Form, Link, useActionData } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
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 { FormBuilder } from "~/modules/formWidget/builder/FormBuilder";
|
||||
import type { FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type FormDetail = {
|
||||
id: string;
|
||||
key: string;
|
||||
name: string;
|
||||
definition: unknown;
|
||||
theme: unknown;
|
||||
targetType: string;
|
||||
fieldMapping: unknown;
|
||||
allowedOrigins: string[];
|
||||
notifyEmails: string[];
|
||||
webhookUrl: string | null;
|
||||
isEnabled: boolean;
|
||||
};
|
||||
|
||||
type SubmissionRow = {
|
||||
id: string;
|
||||
status: string;
|
||||
sourceOrigin: string | null;
|
||||
createdAt: string;
|
||||
preview: string;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
form: FormDetail;
|
||||
submissions: SubmissionRow[];
|
||||
embedScriptBase: string;
|
||||
};
|
||||
|
||||
type ActionData = { error?: string; success?: string };
|
||||
|
||||
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({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const id = params.id;
|
||||
if (!id) throw new Response(t("shared.notFound"), { status: 404 });
|
||||
const form = await db.form.findFirst({
|
||||
where: { id, tenantId },
|
||||
select: {
|
||||
id: true,
|
||||
key: true,
|
||||
name: true,
|
||||
definition: true,
|
||||
theme: true,
|
||||
targetType: true,
|
||||
fieldMapping: true,
|
||||
allowedOrigins: true,
|
||||
notifyEmails: true,
|
||||
webhookUrl: true,
|
||||
isEnabled: true,
|
||||
},
|
||||
});
|
||||
if (!form) throw new Response(t("settings.forms.admin.errors.formNotFound"), { status: 404 });
|
||||
|
||||
const url = new URL(request.url);
|
||||
if (url.searchParams.get("export") === "csv") {
|
||||
const all = await db.formSubmission.findMany({
|
||||
where: { formId: id, tenantId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1000,
|
||||
});
|
||||
const header = "id,createdAt,status,sourceOrigin,values\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}"`;
|
||||
});
|
||||
return new Response(header + rows.join("\n"), {
|
||||
headers: {
|
||||
"content-type": "text/csv; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="form-${form.key}-submissions.csv"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const submissions = await db.formSubmission.findMany({
|
||||
where: { formId: id, tenantId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
select: { id: true, status: true, sourceOrigin: true, createdAt: true, payload: true },
|
||||
});
|
||||
const payload: LoaderData = {
|
||||
form: { ...form },
|
||||
submissions: submissions.map((s) => ({
|
||||
id: s.id,
|
||||
status: s.status,
|
||||
sourceOrigin: s.sourceOrigin,
|
||||
createdAt: s.createdAt.toISOString(),
|
||||
preview: JSON.stringify(s.payload).slice(0, 240),
|
||||
})),
|
||||
embedScriptBase: process.env.FORM_WIDGET_CDN_URL?.trim() || process.env.APP_URL?.trim() || "",
|
||||
};
|
||||
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);
|
||||
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 }, 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", "entity-row"]);
|
||||
const targetType = allowedTargets.has(targetTypeRaw) ? targetTypeRaw : "generic";
|
||||
let definition: unknown;
|
||||
let theme: unknown;
|
||||
let fieldMapping: unknown = null;
|
||||
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);
|
||||
}
|
||||
} 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) }) };
|
||||
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,
|
||||
},
|
||||
});
|
||||
return { success: t("settings.forms.admin.messages.saved") };
|
||||
}
|
||||
return { error: t("settings.forms.admin.errors.unknownOperation") };
|
||||
}
|
||||
|
||||
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>`;
|
||||
|
||||
// Initial state for the builder. 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"),
|
||||
fields: [{ key: "email", type: "email", label: t("settings.forms.admin.defaults.fields.email"), required: true }],
|
||||
} 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,
|
||||
};
|
||||
|
||||
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)} />
|
||||
<button type="submit" className="bg-blue-600 text-white px-4 py-1.5 rounded text-sm">
|
||||
{t("shared.save")}
|
||||
</button>
|
||||
</Form>
|
||||
</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>
|
||||
</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>
|
||||
<a href="?export=csv" className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.exportCsv")}</a>
|
||||
</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>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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"),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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