/** * Tenant admin: form list (WF-P16 Form Builder, screen S00). * * 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 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, 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 { seedShkFormTemplates } from "~/modules/forms/services/shkFormTemplates.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"; 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 = { title: string; forms: FormsAdminRow[]; embedScriptBase: string; }; export const meta: v2MetaFunction = ({ data }) => [{ title: data?.title }]; type ActionData = Exclude & { createdId?: string }; export async function loader(args: LoaderFunctionArgs): Promise { 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 { requireFormsPermission(ctx, "forms.basic"); const { t } = await getTranslations(request); const forms = await db.form.findMany({ where: { tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) }, orderBy: { updatedAt: "desc" }, select: { id: true, key: true, slug: true, name: true, 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, slug: f.slug, name: f.name, 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(args: ActionFunctionArgs): Promise { 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 { requireFormsPermission(ctx, "forms.builder"); await validateCSRFToken(request); const { t } = await getTranslations(request); const body = await request.formData(); const op = body.get("op")?.toString() ?? ""; if (op === "create") { 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 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") { 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") }; 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 { ok: true, intent: op, messageKey: "settings.forms.admin.messages.deleted" }; } return { error: t("settings.forms.admin.errors.unknownOperation") }; } export default function FormsAdmin(): React.JSX.Element { const data = useLoaderData() as LoaderData; const actionData = useActionData() as ActionData | undefined; const formatters = useLocaleFormatters(); const rootData = useRootData(); const params = useParams(); useSaveToast(actionData?.ok ? actionData : undefined); return ( formatters.date(value, { dateStyle: "medium", timeStyle: "short" })} formatNumber={(value) => formatters.number(value)} /> ); }