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

@@ -0,0 +1,29 @@
import { describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ findMany: vi.fn() }));
vi.mock("~/utils/db.server", () => ({
db: { form: { findMany: mocks.findMany } },
}));
import { uniqueFormSlug } from "./createDraftForm.server";
describe("uniqueFormSlug", () => {
it("finds the first free tenant slug with one bounded database read", async () => {
mocks.findMany.mockResolvedValue([
{ slug: "anfrage-formular" },
{ slug: "anfrage-formular-2" },
{ slug: "anfrage-formular-3" },
]);
await expect(uniqueFormSlug("tenant-1", "Anfrage Formular")).resolves.toBe("anfrage-formular-4");
expect(mocks.findMany).toHaveBeenCalledOnce();
expect(mocks.findMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant-1",
slug: { in: expect.arrayContaining(["anfrage-formular", "anfrage-formular-2", "anfrage-formular-99"]) },
},
select: { slug: true },
});
});
});
@@ -0,0 +1,158 @@
/**
* Shared draft-form factory used by the forms admin list actions and the
* S01 "Neues Formular" type-selection flow (WF-P16 Form Builder).
*/
import { randomUUID } from "node:crypto";
import slugify from "@sindresorhus/slugify";
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@hivegrid/form-widget";
import { db } from "~/utils/db.server";
export const FORM_SUBTYPE_CHOICES = ["standard", "lead", "survey", "internal"] as const;
export type FormSubtypeChoice = (typeof FORM_SUBTYPE_CHOICES)[number];
export function isFormSubtypeChoice(value: string): value is FormSubtypeChoice {
return (FORM_SUBTYPE_CHOICES as readonly string[]).includes(value);
}
/** Finds a tenant-unique slug derived from the given name. */
export async function uniqueFormSlug(tenantId: string, name: string): Promise<string> {
const baseSlug = slugify(name).slice(0, 80) || "form";
const candidates = [baseSlug, ...Array.from({ length: 98 }, (_, index) => `${baseSlug}-${index + 2}`)];
const existingRows = await db.form.findMany({
where: { tenantId, slug: { in: candidates } },
select: { slug: true },
});
const existing = new Set(existingRows.map((row) => row.slug).filter((slug): slug is string => slug !== null));
return candidates.find((candidate) => !existing.has(candidate)) ?? `${baseSlug}-${randomUUID().slice(0, 8)}`;
}
export async function createDraftForm(options: {
tenantId: string;
userId: string;
name: string;
subtype: FormSubtypeChoice;
allowedOrigin?: string;
t: (key: string) => string;
}): Promise<{ id: string }> {
const { tenantId, userId, name, subtype, allowedOrigin, t } = options;
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 slug = await uniqueFormSlug(tenantId, name);
return db.$transaction(async (tx) => {
const created = await tx.form.create({
data: {
tenantId,
createdByUserId: userId,
name,
slug,
subtype,
status: "draft",
definition: definition as object,
allowedOrigins: allowedOrigin ? [allowedOrigin] : [],
config: { honeypotEnabled: true } as object,
},
select: { id: true },
});
// Lead forms promise "Antworten landen direkt als Lead" (S01 card), so the
// create_lead post-submit action starts enabled and can be tuned in S02L.
if (subtype === "lead") {
await tx.formAction.create({
data: {
formId: created.id,
tenantId,
actionType: "create_lead",
name: t("settings.forms.admin.defaults.leadActionName"),
position: 0,
enabled: true,
},
});
}
return created;
});
}
/** Duplicates a form (definition, fields and post-submit actions) as a new draft. */
export async function duplicateForm(options: {
tenantId: string;
userId: string;
sourceId: string;
ownerWhere: { createdByUserId?: string };
copyName: (sourceName: string) => string;
}): Promise<{ id: string } | null> {
const { tenantId, userId, sourceId, ownerWhere, copyName } = options;
const source = await db.form.findFirst({
where: { id: sourceId, tenantId, ...ownerWhere },
include: { fields: true, actions: true },
});
if (!source) return null;
const name = copyName(source.name);
const slug = await uniqueFormSlug(tenantId, name);
return db.$transaction(async (tx) => {
const created = await tx.form.create({
data: {
tenantId,
createdByUserId: userId,
name,
slug,
subtype: source.subtype,
status: "draft",
isPublic: false,
isEnabled: true,
definition: source.definition as object,
theme: source.theme as object,
targetType: source.targetType,
targetEntityId: source.targetEntityId,
fieldMapping: source.fieldMapping as object,
allowedOrigins: source.allowedOrigins,
notifyEmails: source.notifyEmails,
webhookUrl: source.webhookUrl,
config: source.config as object,
},
select: { id: true },
});
if (source.fields.length > 0) {
await tx.formField.createMany({
data: source.fields.map((field) => ({
formId: created.id,
tenantId,
fieldKey: field.fieldKey,
fieldType: field.fieldType,
label: field.label,
helpText: field.helpText,
placeholder: field.placeholder,
required: field.required,
position: field.position,
options: field.options ?? [],
validationRules: field.validationRules ?? {},
conditionalLogic: field.conditionalLogic ?? [],
isSystem: field.isSystem,
})),
});
}
if (source.actions.length > 0) {
await tx.formAction.createMany({
data: source.actions.map((action) => ({
formId: created.id,
tenantId,
actionType: action.actionType,
name: action.name,
position: action.position,
enabled: action.enabled,
fieldMapping: action.fieldMapping ?? {},
actionConfig: action.actionConfig ?? {},
})),
});
}
return created;
});
}
@@ -1,5 +1,15 @@
import { describe, expect, it } from "vitest";
import { buildShkFormTemplateDefinition, SHK_FORM_TEMPLATES } from "./shkFormTemplates.server";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ upsert: vi.fn(), withTenantRLS: vi.fn() }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
import { buildShkFormTemplateDefinition, seedShkFormTemplates, seedShkFormTemplatesWithTx, SHK_FORM_TEMPLATES } from "./shkFormTemplates.server";
beforeEach(() => {
mocks.upsert.mockReset().mockResolvedValue({ id: "form" });
mocks.withTenantRLS.mockReset().mockImplementation(async (_tenantId, callback) => callback({ form: { upsert: mocks.upsert } }));
});
describe("SHK form templates", () => {
it("builds valid localized form definitions for every SHK template", () => {
@@ -14,4 +24,42 @@ describe("SHK form templates", () => {
expect(definitions[1].title).toBe("SHK Abnahmeprotokoll");
expect(definitions[1].fields.some((field) => field.key === "accepted")).toBe(true);
});
it("persists tenant-created templates as normal rows by default", async () => {
await seedShkFormTemplates({ tenantId: "tenant-staging-business", userId: "user-1", t: (key) => key });
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant-staging-business", expect.any(Function));
expect(mocks.upsert).toHaveBeenCalledTimes(2);
for (const [call] of mocks.upsert.mock.calls) {
expect(call).toEqual(
expect.objectContaining({
create: expect.objectContaining({ isDemoData: false }),
update: expect.objectContaining({ isDemoData: false }),
})
);
}
});
it("only marks templates as demo data when an explicit demo seed requests it", async () => {
await seedShkFormTemplates({ tenantId: "tenant-demo", userId: "user-1", t: (key) => key, isDemoData: true });
for (const [call] of mocks.upsert.mock.calls) {
expect(call.create.isDemoData).toBe(true);
expect(call.update.isDemoData).toBe(true);
}
});
it("uses an existing transaction without opening a nested RLS transaction", async () => {
const tx = { form: { upsert: mocks.upsert } };
const result = await seedShkFormTemplatesWithTx(tx as never, {
tenantId: "tenant-atomic-bootstrap",
userId: "user-1",
t: (key) => key,
});
expect(result).toEqual({ upserted: 2 });
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
expect(mocks.upsert).toHaveBeenCalledTimes(2);
});
});
@@ -1,5 +1,5 @@
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@hivegrid/form-widget";
import { db } from "~/utils/db.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
export const SHK_FORM_TEMPLATES = [
{
@@ -64,11 +64,33 @@ export function buildShkFormTemplateDefinition(template: (typeof SHK_FORM_TEMPLA
});
}
export async function seedShkFormTemplates(input: { tenantId: string; userId: string; t: FormTemplateTranslationFn }): Promise<{ upserted: number }> {
export type PreparedShkFormTemplate = {
template: (typeof SHK_FORM_TEMPLATES)[number];
definition: ReturnType<typeof buildShkFormTemplateDefinition>;
};
/** Prepares localized, schema-validated definitions before opening a DB transaction. */
export function prepareShkFormTemplates(t: FormTemplateTranslationFn): PreparedShkFormTemplate[] {
return SHK_FORM_TEMPLATES.map((template) => ({
template,
definition: buildShkFormTemplateDefinition(template, t),
}));
}
export type SeedShkFormTemplatesInput = {
tenantId: string;
userId: string;
t: FormTemplateTranslationFn;
isDemoData?: boolean;
preparedTemplates?: ReadonlyArray<PreparedShkFormTemplate>;
};
export async function seedShkFormTemplatesWithTx(tx: TenantRlsClient, input: SeedShkFormTemplatesInput): Promise<{ upserted: number }> {
let upserted = 0;
for (const template of SHK_FORM_TEMPLATES) {
const definition = buildShkFormTemplateDefinition(template, input.t);
await db.form.upsert({
const isDemoData = input.isDemoData ?? false;
const preparedTemplates = input.preparedTemplates ?? prepareShkFormTemplates(input.t);
for (const { template, definition } of preparedTemplates) {
await tx.form.upsert({
where: { tenantId_slug: { tenantId: input.tenantId, slug: template.slug } },
create: {
tenantId: input.tenantId,
@@ -80,16 +102,21 @@ export async function seedShkFormTemplates(input: { tenantId: string; userId: st
definition: definition as object,
allowedOrigins: [],
config: { honeypotEnabled: true, captchaEnabled: true } as object,
isDemoData: true,
isDemoData,
},
update: {
name: template.name,
subtype: template.subtype,
definition: definition as object,
isDemoData: true,
isDemoData,
},
});
upserted += 1;
}
return { upserted };
}
export async function seedShkFormTemplates(input: SeedShkFormTemplatesInput): Promise<{ upserted: number }> {
const preparedTemplates = input.preparedTemplates ?? prepareShkFormTemplates(input.t);
return withTenantRLS(input.tenantId, (tx) => seedShkFormTemplatesWithTx(tx, { ...input, preparedTemplates }));
}