Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,51 +1,50 @@
/**
* Tenant admin: form-widget list + create (Phase 05 Task #58, layer 3).
* Tenant admin: form list (WF-P16 Form Builder, screen S00).
*
* Permissions: `app.settings.account.update` (admin-only) — forms expose
* a public submission endpoint so we keep authoring tightly scoped.
* Permissions: read requires `forms.basic`; mutations require
* `forms.builder` (or `forms.publisher` for publishing) — forms expose a
* public submission endpoint so we keep authoring tightly scoped.
*
* The page renders existing forms with their public key + submission
* count + embed-code snippet, plus a minimal create form that seeds a
* single text+email definition. Field editing happens on the detail
* route (forms.$id.tsx).
* The page renders existing forms with status/type filters, submission
* counts and per-row actions (edit, publish, duplicate, delete). Creation
* happens on the S01 type-selection route (forms/new); field editing on
* the detail route (forms.$id.tsx).
*/
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, Form, Link, useActionData } from "react-router";
import { useTranslation } from "react-i18next";
import slugify from "@sindresorhus/slugify";
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, useActionData, useParams } from "react-router";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { db } from "~/utils/db.server";
import { getTranslations } from "~/locale/i18next.server";
import { useLocaleFormatters } from "~/locale/format";
import { validateCSRFToken } from "~/utils/session.server";
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@hivegrid/form-widget";
import { seedShkFormTemplates } from "~/modules/forms/services/shkFormTemplates.server";
import { formsOwnerWhere, loadFormsContext, requireFormsPermission } from "~/modules/forms/routes/formsAccess.server";
import { createDraftForm, duplicateForm } from "~/modules/forms/services/createDraftForm.server";
import { formsOwnerWhere, loadFormsContext, requireFormsPermission, type FormsRouteContext } from "~/modules/forms/routes/formsAccess.server";
import { useRootData } from "~/utils/data/useRootData";
type Row = {
id: string;
key: string;
slug: string | null;
name: string;
subtype: string;
status: string;
isEnabled: boolean;
submissions: number;
createdAt: string;
};
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
import { FormsAdminPage, type FormsAdminRow } from "~/components/screens/forms/FormsAdminPage";
import { useSaveToast, type SaveActionResult } from "~/hooks/use-save-toast";
type LoaderData = {
forms: Row[];
title: string;
forms: FormsAdminRow[];
embedScriptBase: string;
};
type ActionData = { error?: string; createdId?: string };
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
export async function loader({ request, params }: LoaderFunctionArgs): Promise<LoaderData> {
const ctx = await loadFormsContext({ request, params, requireModule: true });
type ActionData = Exclude<SaveActionResult, null | undefined> & { createdId?: string };
export async function loader(args: LoaderFunctionArgs): Promise<LoaderData> {
const ctx = await loadFormsContext({ request: args.request, params: args.params, requireModule: true });
return runWithRlsContext({ tenantId: ctx.tenantId, userId: ctx.userId }, () => loadForms(args, ctx));
}
async function loadForms({ request }: LoaderFunctionArgs, ctx: FormsRouteContext): Promise<LoaderData> {
requireFormsPermission(ctx, "forms.basic");
const { t } = await getTranslations(request);
const forms = await db.form.findMany({
where: { tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) },
orderBy: { createdAt: "desc" },
orderBy: { updatedAt: "desc" },
select: {
id: true,
key: true,
@@ -54,11 +53,14 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<L
subtype: true,
status: true,
isEnabled: true,
isPublic: true,
createdAt: true,
updatedAt: true,
_count: { select: { submissions: true } },
},
});
return {
title: `${t("settings.forms.admin.title")} | ${process.env.APP_NAME}`,
forms: forms.map((f) => ({
id: f.id,
key: f.key,
@@ -67,15 +69,21 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<L
subtype: f.subtype,
status: f.status,
isEnabled: f.isEnabled,
isPublic: f.isPublic,
submissions: f._count.submissions,
createdAt: f.createdAt.toISOString(),
updatedAt: f.updatedAt.toISOString(),
})),
embedScriptBase: process.env.FORM_WIDGET_CDN_URL?.trim() || process.env.APP_URL?.trim() || "",
};
}
export async function action({ request, params }: ActionFunctionArgs): Promise<Response | 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 }, () => mutateForms(args, ctx));
}
async function mutateForms({ request }: ActionFunctionArgs, ctx: FormsRouteContext): Promise<Response | ActionData> {
requireFormsPermission(ctx, "forms.builder");
await validateCSRFToken(request);
const { t } = await getTranslations(request);
@@ -85,58 +93,78 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<R
const name = body.get("name")?.toString()?.trim();
const origin = body.get("allowedOrigin")?.toString()?.trim() ?? "";
if (!name) return { error: t("settings.forms.admin.errors.nameRequired") };
const baseSlug = slugify(name).slice(0, 80) || "form";
let slug = baseSlug;
for (let i = 2; i < 100; i += 1) {
const exists = await db.form.findFirst({ where: { tenantId: ctx.tenantId, slug }, select: { id: true } });
if (!exists) break;
slug = `${baseSlug}-${i}`;
}
const definition = FormDefinitionSchema.parse({
title: name,
submitLabel: t("settings.forms.admin.defaults.submitLabel"),
successMessage: t("settings.forms.admin.defaults.successMessage"),
gdprConsentLabel: t("settings.forms.admin.defaults.gdprConsentLabel"),
fields: [
{ key: "full_name", type: "text", label: t("settings.forms.admin.defaults.fields.fullName"), required: true },
{ key: "email", type: "email", label: t("settings.forms.admin.defaults.fields.email"), required: true },
{ key: "message", type: "textarea", label: t("settings.forms.admin.defaults.fields.message"), required: false },
{ key: HONEYPOT_FIELD_KEY, type: "honeypot", label: t("settings.forms.admin.defaults.fields.honeypot") },
],
});
const created = await db.form.create({
data: {
tenantId: ctx.tenantId,
createdByUserId: ctx.userId,
name,
slug,
subtype: "standard",
status: "draft",
definition: definition as object,
allowedOrigins: origin ? [origin] : [],
config: { honeypotEnabled: true } as object,
},
select: { id: true },
const created = await createDraftForm({
tenantId: ctx.tenantId,
userId: ctx.userId,
name,
subtype: "standard",
allowedOrigin: origin || undefined,
t,
});
return { createdId: created.id };
}
if (op === "seed-shk-templates") {
await seedShkFormTemplates({ tenantId: ctx.tenantId, userId: ctx.userId, t });
return { error: undefined };
const result = await seedShkFormTemplates({ tenantId: ctx.tenantId, userId: ctx.userId, t });
return {
ok: true,
intent: op,
messageKey: "settings.forms.admin.list.templatesLoaded",
messageValues: { count: result.upserted },
};
}
if (op === "duplicate") {
const id = body.get("id")?.toString();
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
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", createdId: created.id };
}
if (op === "publish") {
requireFormsPermission(ctx, "forms.publisher");
const id = body.get("id")?.toString();
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
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") };
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,
...(nextPublic ? { isEnabled: true } : {}),
},
});
return {
ok: true,
intent: op,
messageKey: nextPublic ? "settings.forms.admin.messages.published" : "settings.forms.admin.messages.unpublished",
};
}
if (op === "toggle") {
const id = body.get("id")?.toString();
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
const target = await db.form.findFirst({ where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) }, select: { isEnabled: true } });
if (!target) return { error: t("settings.forms.admin.errors.formNotFound") };
await db.form.update({ where: { id }, data: { isEnabled: !target.isEnabled } });
return { error: undefined };
const nextEnabled = !target.isEnabled;
await db.form.update({ where: { id }, data: { isEnabled: nextEnabled } });
return {
ok: true,
intent: op,
messageKey: nextEnabled ? "settings.forms.admin.messages.enabled" : "settings.forms.admin.messages.disabled",
};
}
if (op === "delete") {
const id = body.get("id")?.toString();
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
await db.form.deleteMany({ where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) } });
return { error: undefined };
return { ok: true, intent: op, messageKey: "settings.forms.admin.messages.deleted" };
}
return { error: t("settings.forms.admin.errors.unknownOperation") };
}
@@ -144,89 +172,19 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<R
export default function FormsAdmin(): React.JSX.Element {
const data = useLoaderData() as LoaderData;
const actionData = useActionData() as ActionData | undefined;
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const rootData = useRootData();
const params = useParams();
useSaveToast(actionData?.ok ? actionData : undefined);
return (
<div className="p-6 space-y-6">
<header>
<h1 className="text-2xl font-semibold">{t("settings.forms.admin.title")}</h1>
<p className="text-sm text-gray-600">
{t("settings.forms.admin.description")}
</p>
</header>
<section>
<h2 className="text-lg font-medium mb-2">{t("settings.forms.admin.create.title")}</h2>
{actionData?.error ? <p className="text-red-600 text-sm mb-2">{actionData.error}</p> : null}
<Form method="post" className="mb-3">
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
<input type="hidden" name="op" value="seed-shk-templates" />
<button type="submit" className="text-sm border rounded px-3 py-1">
{t("settings.forms.admin.create.seedShkTemplates")}
</button>
</Form>
<Form method="post" className="flex gap-2 items-end">
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
<input type="hidden" name="op" value="create" />
<label className="flex flex-col gap-1 flex-1">
<span className="text-sm">{t("settings.forms.admin.create.name")}</span>
<input name="name" required className="border rounded px-2 py-1" />
</label>
<label className="flex flex-col gap-1 flex-1">
<span className="text-sm">{t("settings.forms.admin.create.allowedOrigin")}</span>
<input name="allowedOrigin" placeholder={t("settings.forms.admin.create.allowedOriginPlaceholder")} className="border rounded px-2 py-1" />
</label>
<button type="submit" className="bg-blue-600 text-white px-4 py-1.5 rounded">{t("settings.forms.admin.create.submit")}</button>
</Form>
</section>
<section>
<h2 className="text-lg font-medium mb-2">{t("settings.forms.admin.existing.title")}</h2>
{data.forms.length === 0 ? (
<p className="text-sm text-gray-500">{t("settings.forms.admin.existing.empty")}</p>
) : (
<ul className="divide-y border rounded">
{data.forms.map((f) => (
<li key={f.id} className="p-3 flex items-center justify-between">
<div>
<Link to={f.id} className="font-medium text-blue-700 hover:underline">{f.name}</Link>
<div className="text-xs text-gray-500">
{t("settings.forms.admin.existing.key")}: <code>{f.key}</code> ·{" "}
{t("settings.forms.admin.existing.slug")}: <code>{f.slug ?? "n/a"}</code> ·{" "}
{t("settings.forms.admin.existing.status")}: {f.status} ·{" "}
{t("settings.forms.admin.existing.submissionsCount", {
count: f.submissions,
formattedCount: formatters.number(f.submissions),
})}{" "}
· {f.isEnabled ? t("shared.enabled") : t("shared.disabled")} ·{" "}
{t("settings.forms.admin.existing.createdAtWithDate", {
date: formatters.date(f.createdAt, { dateStyle: "medium", timeStyle: "short" }),
})}
</div>
<pre className="text-xs bg-gray-50 mt-1 p-1 rounded inline-block">
{`<script src="${data.embedScriptBase}/embed/widget.js" data-form-key="${f.key}" async></script>`}
</pre>
</div>
<div className="flex gap-2">
<Form method="post">
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
<input type="hidden" name="op" value="toggle" />
<input type="hidden" name="id" value={f.id} />
<button className="text-sm border rounded px-2 py-1">{f.isEnabled ? t("shared.disable") : t("shared.enable")}</button>
</Form>
<Form method="post" onSubmit={(e) => { if (!confirm(t("settings.forms.admin.delete.confirm"))) e.preventDefault(); }}>
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
<input type="hidden" name="op" value="delete" />
<input type="hidden" name="id" value={f.id} />
<button className="text-sm border rounded px-2 py-1 text-red-600">{t("shared.delete")}</button>
</Form>
</div>
</li>
))}
</ul>
)}
</section>
</div>
<FormsAdminPage
forms={data.forms}
csrf={rootData.csrf ?? ""}
embedScriptBase={data.embedScriptBase}
publicPathPrefix={`/f/${params.tenant ?? ""}`}
actionError={actionData?.error ?? undefined}
formatDate={(value) => formatters.date(value, { dateStyle: "medium", timeStyle: "short" })}
formatNumber={(value) => formatters.number(value)}
/>
);
}