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,60 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildHrLeaveFormDefinition } from "~/utils/integrations/hrM05Forms";
import { InternalFormRenderer } from "./InternalFormRenderer";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
describe("InternalFormRenderer", () => {
it("renders the M05 definition and submits typed values", () => {
const onSubmit = vi.fn();
const definition = buildHrLeaveFormDefinition((key) => key);
const { container } = render(
<InternalFormRenderer
definition={definition}
initialValues={{ requestKind: "vacation" }}
submitting={false}
onSubmit={onSubmit}
uiId="ui.hr.test.m05"
/>,
);
fireEvent.change(container.querySelector("input[name='startDate']") as HTMLInputElement, {
target: { value: "2026-07-28" },
});
fireEvent.change(container.querySelector("input[name='endDate']") as HTMLInputElement, {
target: { value: "2026-07-30" },
});
fireEvent.click(container.querySelector('[data-ui-id="ui.hr.test.m05.submit"]') as HTMLElement);
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
requestKind: "vacation",
startDate: "2026-07-28",
endDate: "2026-07-30",
}),
);
expect(container.querySelector("[data-m05-renderer='true']")).toBeInTheDocument();
});
it("shows a clear validation error instead of submitting incomplete values", () => {
const onSubmit = vi.fn();
const { container } = render(
<InternalFormRenderer
definition={buildHrLeaveFormDefinition((key) => key)}
submitting={false}
onSubmit={onSubmit}
uiId="ui.hr.test.m05"
/>,
);
fireEvent.click(container.querySelector('[data-ui-id="ui.hr.test.m05.submit"]') as HTMLElement);
expect(onSubmit).not.toHaveBeenCalled();
expect(screen.getByText("hr.m05.validation.FIELD_REQUIRED")).toBeInTheDocument();
});
});
@@ -0,0 +1,190 @@
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
filterVisibleFields,
validateFormValues,
type FormDefinition,
type FormField,
type FormSubmissionPayload,
} from "@hivegrid/form-widget";
import { Alert } from "~/ui/components/Alert";
import { Button } from "~/ui/components/Button";
import { Checkbox } from "~/ui/components/Checkbox";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
import { DateField } from "~/components/screens/tasks/DateField";
export type InternalFormValues = FormSubmissionPayload["values"];
export type InternalFormRendererProps = {
definition: FormDefinition;
initialValues?: InternalFormValues;
submitting: boolean;
onSubmit: (values: InternalFormValues) => void;
onCancel?: () => void;
uiId: string;
};
function initialValuesFor(
definition: FormDefinition,
supplied: InternalFormValues | undefined,
): InternalFormValues {
return Object.fromEntries(
definition.fields.map((field) => [
field.key,
supplied?.[field.key] ??
(field.type === "boolean" ? false : field.type === "multiselect" ? [] : ""),
]),
);
}
function M05Field({
field,
value,
onChange,
}: {
field: FormField;
value: InternalFormValues[string];
onChange: (value: InternalFormValues[string]) => void;
}) {
if (field.type === "honeypot") return null;
if (field.type === "textarea") {
return (
<TextArea label={field.label} showLabel className="w-full">
<TextArea.Input
value={typeof value === "string" ? value : ""}
required={field.required}
maxLength={field.validationRules?.maxLength ?? field.maxLength}
onChange={(event) => onChange(event.target.value)}
/>
</TextArea>
);
}
if (field.type === "select") {
return (
<Select
label={field.label}
showLabel
value={typeof value === "string" && value ? value : undefined}
onValueChange={(next: string) => onChange(next)}
>
{(field.options ?? []).map((option) => (
<Select.Item key={option.value} value={option.value}>
{option.label}
</Select.Item>
))}
</Select>
);
}
if (field.type === "boolean") {
return (
<Checkbox
label={field.label}
checked={value === true}
onCheckedChange={(checked) => onChange(checked)}
/>
);
}
if (field.type === "date") {
return (
<DateField
label={field.label}
name={field.key}
value={typeof value === "string" ? value : ""}
required={field.required}
onChange={onChange}
/>
);
}
if (field.type === "file" || field.type === "photo" || field.type === "multiselect") {
return null;
}
return (
<TextInput label={field.label} showLabel fillContainer>
<TextInput.Input
type={
field.type === "email"
? "email"
: field.type === "number"
? "number"
: field.type === "phone"
? "tel"
: "text"
}
value={typeof value === "string" || typeof value === "number" ? String(value) : ""}
required={field.required}
maxLength={field.validationRules?.maxLength ?? field.maxLength}
onChange={(event) => onChange(event.target.value)}
/>
</TextInput>
);
}
export function InternalFormRenderer({
definition,
initialValues,
submitting,
onSubmit,
onCancel,
uiId,
}: InternalFormRendererProps) {
const { t } = useTranslation();
const [values, setValues] = useState<InternalFormValues>(() =>
initialValuesFor(definition, initialValues),
);
const [errorKey, setErrorKey] = useState<string | null>(null);
useEffect(() => {
setValues(initialValuesFor(definition, initialValues));
setErrorKey(null);
}, [definition, initialValues]);
const visibleFields = useMemo(
() => filterVisibleFields(definition.fields, values),
[definition.fields, values],
);
function submit() {
const error = validateFormValues(values, definition);
if (error) {
setErrorKey(`hr.m05.validation.${error.code}`);
return;
}
setErrorKey(null);
onSubmit(values);
}
return (
<div className="flex w-full flex-col gap-5" data-ui-id={uiId} data-m05-renderer="true">
{definition.description ? (
<p className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{definition.description}
</p>
) : null}
{errorKey ? <Alert variant="error" title={t(errorKey)} /> : null}
<div className="flex w-full flex-col gap-4">
{visibleFields.map((field) => (
<M05Field
key={field.key}
field={field}
value={values[field.key] ?? null}
onChange={(value) =>
setValues((current) => ({ ...current, [field.key]: value }))
}
/>
))}
</div>
<div className="flex justify-end gap-2">
{onCancel ? (
<Button variant="neutral" onClick={onCancel}>
{t("hr.action.cancel")}
</Button>
) : null}
<Button loading={submitting} onClick={submit} data-ui-id={`${uiId}.submit`}>
{definition.submitLabel}
</Button>
</div>
</div>
);
}
@@ -1,6 +1,8 @@
import type * as React from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useFetcher } from "react-router";
import { useTranslation } from "react-i18next";
import { defaultBrandTokens } from "@hivegrid/brand";
import {
filterVisibleFields,
HONEYPOT_FIELD_KEY,
@@ -15,6 +17,12 @@ export type PublicFormRendererProps = {
definition: FormDefinition;
theme: FormTheme;
captcha: { enabled: boolean; provider?: "mcaptcha" | "cap"; instanceUrl: string | undefined; sitekey: string | undefined };
/**
* Visual context (Subframe S04): "standalone" renders the tinted full-page
* backdrop + brand monogram for `/f/:tenant/:slug`; "embed" keeps a
* transparent backdrop so the widget blends into the host page's iframe.
*/
layout?: "embed" | "standalone";
};
function themeCssVars(theme: FormTheme): React.CSSProperties {
@@ -36,6 +44,69 @@ function postToParent(message: Record<string, unknown>): void {
}
}
/**
* Self-contained styles matching the Subframe target screens (S04 public
* form, V01 success, V03 submit error): centered card with an accent bar on
* top, themed accent submit button and a neutral chrome footer. Kept as plain
* `tcform-*` CSS driven by theme CSS variables — no `~/ui` imports and no
* Tailwind so the widget stays embeddable everywhere.
*/
const TCFORM_CSS = `
.tcform-root { font-family: var(--tcform-font, system-ui, -apple-system, "Segoe UI", sans-serif); color: var(--tcform-text, #16232e); box-sizing: border-box; padding: 16px; }
.tcform-root *, .tcform-root *::before, .tcform-root *::after { box-sizing: border-box; }
.tcform-root--page { min-height: 100vh; background: #f2f4f7; padding: 48px 16px; }
.tcform-shell { max-width: 576px; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }
.tcform-brand { display: flex; justify-content: center; }
.tcform-brand-badge { display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; border-radius: 50%; border: 1px solid #e0e5eb; background: #eef2f7; background: color-mix(in srgb, var(--tcform-primary, #2563eb) 10%, #ffffff); color: var(--tcform-primary, #2563eb); font-size: 1.15rem; font-weight: 700; }
.tcform-card { background: var(--tcform-bg, #ffffff); border: 1px solid #e0e5eb; border-top: 4px solid var(--tcform-primary, #2563eb); border-radius: var(--tcform-radius, 10px); box-shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 8px 24px rgba(16, 24, 40, 0.06); padding: 32px 28px; }
.tcform-root h1 { font-size: 1.35rem; line-height: 1.3; margin: 0 0 6px; font-weight: 700; }
.tcform-root p.tcform-description { margin: 0; font-size: 0.9rem; line-height: 1.5; opacity: 0.72; }
.tcform-divider { border: 0; height: 1px; background: #e7ebef; margin: 20px 0; }
.tcform-row { display: block; margin-bottom: 18px; }
.tcform-root .tcform-label { display: block; font-weight: 600; font-size: 0.9rem; margin-bottom: 6px; }
.tcform-root input[type=text], .tcform-root input[type=email], .tcform-root input[type=number], .tcform-root input[type=date], .tcform-root input[type=time], .tcform-root input[type=tel], .tcform-root textarea, .tcform-root select { width: 100%; padding: 10px 12px; border: 1px solid #cfd6dd; border-radius: var(--tcform-radius, 8px); font: inherit; font-size: 0.95rem; color: inherit; background: #fff; transition: border-color 120ms ease, box-shadow 120ms ease; }
.tcform-root input:focus, .tcform-root textarea:focus, .tcform-root select:focus { outline: none; border-color: var(--tcform-primary, #2563eb); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15); box-shadow: 0 0 0 3px color-mix(in srgb, var(--tcform-primary, #2563eb) 18%, transparent); }
.tcform-root input::placeholder, .tcform-root textarea::placeholder { color: inherit; opacity: 0.45; }
.tcform-root textarea { min-height: 110px; resize: vertical; }
.tcform-root input[type=file] { width: 100%; font: inherit; font-size: 0.9rem; }
.tcform-root input[type=checkbox] { width: 16px; height: 16px; margin: 2px 0 0; accent-color: var(--tcform-primary, #2563eb); flex: none; }
.tcform-root .tcform-help { font-size: 0.8rem; opacity: 0.65; margin-top: 5px; line-height: 1.4; }
.tcform-checkbox .tcform-label { display: flex; align-items: flex-start; gap: 10px; font-weight: 500; font-size: 0.875rem; line-height: 1.45; margin-bottom: 0; cursor: pointer; }
.tcform-consent { border: 1px solid #e0e5eb; border-radius: var(--tcform-radius, 8px); background: #fbfcfd; padding: 12px 14px; }
.tcform-captcha { margin-bottom: 18px; }
.tcform-captcha:empty { display: none; }
.tcform-error { display: flex; align-items: flex-start; gap: 10px; padding: 12px 14px; border: 1px solid #fecaca; border-radius: var(--tcform-radius, 8px); background: #fef2f2; color: #991b1b; font-size: 0.9rem; line-height: 1.45; margin: 16px 0 0; }
.tcform-error svg { flex: none; margin-top: 2px; }
.tcform-root button.tcform-submit { display: block; width: 100%; background: var(--tcform-primary, #2563eb); color: #fff; border: 0; padding: 12px 18px; border-radius: var(--tcform-radius, 8px); cursor: pointer; font: inherit; font-size: 0.95rem; font-weight: 600; transition: filter 120ms ease; }
.tcform-root button.tcform-submit:hover:not([disabled]) { filter: brightness(0.92); }
.tcform-root button.tcform-submit:focus-visible { outline: 2px solid var(--tcform-primary, #2563eb); outline-offset: 2px; }
.tcform-root button.tcform-submit[disabled] { opacity: 0.6; cursor: progress; }
.tcform-required-hint { font-size: 0.78rem; opacity: 0.65; margin: 10px 0 0; }
.tcform-success { display: flex; flex-direction: column; align-items: center; gap: 16px; text-align: center; padding: 16px 0; }
.tcform-success-icon { display: inline-flex; align-items: center; justify-content: center; width: 56px; height: 56px; border-radius: 50%; background: #ecfdf5; color: #059669; }
.tcform-success-message { margin: 0; font-size: 1.1rem; font-weight: 600; line-height: 1.4; }
.tcform-footer { display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; font-size: 0.78rem; opacity: 0.7; line-height: 1.4; }
@media (max-width: 520px) { .tcform-card { padding: 24px 16px; } .tcform-root--page { padding: 24px 12px; } }
`;
function IconCheck(): React.JSX.Element {
return (
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M20 6 9 17l-5-5" />
</svg>
);
}
function IconAlert(): React.JSX.Element {
return (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
);
}
function FieldRenderer({
field,
value,
@@ -186,7 +257,14 @@ function FieldRenderer({
);
}
export function PublicFormRenderer({ formKey, definition, theme, captcha }: PublicFormRendererProps): React.JSX.Element {
export function PublicFormRenderer({
formKey,
definition,
theme,
captcha,
layout = "embed",
}: PublicFormRendererProps): React.JSX.Element {
const { t } = useTranslation();
const fetcher = useFetcher<{ ok?: boolean; error?: string }>();
const containerRef = useRef<HTMLDivElement | null>(null);
const [values, setValues] = useState<Record<string, string | boolean | string[]>>(() => {
@@ -201,10 +279,13 @@ export function PublicFormRenderer({ formKey, definition, theme, captcha }: Publ
const styleVars = useMemo(() => themeCssVars(theme), [theme]);
const idempotencyKey = useMemo(() => {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
if (typeof crypto === "undefined" || typeof crypto.getRandomValues !== "function") {
throw new Error("Secure randomness is required to submit a public form.");
}
return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
}, []);
useEffect(() => {
@@ -267,62 +348,75 @@ export function PublicFormRenderer({ formKey, definition, theme, captcha }: Publ
});
}
const monogram = definition.title.trim().charAt(0).toUpperCase();
const rootClassName = layout === "standalone" ? "tcform-root tcform-root--page" : "tcform-root";
return (
<div ref={containerRef} className="tcform-root" style={styleVars}>
<style>{`
.tcform-root { font-family: var(--tcform-font, system-ui, sans-serif); background: var(--tcform-bg, #fff); color: var(--tcform-text, #111); padding: 16px; box-sizing: border-box; }
.tcform-root h1 { font-size: 1.25rem; margin: 0 0 0.25em; }
.tcform-root p.tcform-description { margin: 0 0 1em; opacity: 0.8; }
.tcform-row { display: block; margin-bottom: 12px; }
.tcform-root .tcform-label { display: block; font-weight: 500; margin-bottom: 4px; }
.tcform-root input[type=text], .tcform-root input[type=email], .tcform-root input[type=number], .tcform-root textarea, .tcform-root select { width: 100%; padding: 8px 10px; border: 1px solid #ccc; border-radius: var(--tcform-radius, 6px); font: inherit; color: inherit; background: #fff; box-sizing: border-box; }
.tcform-root textarea { min-height: 100px; resize: vertical; }
.tcform-root .tcform-help { font-size: 0.85em; opacity: 0.7; margin-top: 4px; }
.tcform-root button { background: var(--tcform-primary, #2563eb); color: #fff; border: 0; padding: 10px 16px; border-radius: var(--tcform-radius, 6px); cursor: pointer; font: inherit; }
.tcform-root button[disabled] { opacity: 0.6; cursor: progress; }
.tcform-root .tcform-success { padding: 12px; border-radius: var(--tcform-radius, 6px); background: #ecfdf5; color: #065f46; }
.tcform-root .tcform-error { padding: 12px; border-radius: var(--tcform-radius, 6px); background: #fef2f2; color: #991b1b; margin-bottom: 12px; }
`}</style>
<h1>{definition.title}</h1>
{definition.description ? <p className="tcform-description">{definition.description}</p> : null}
{submittedOk ? (
<div className="tcform-success" role="status">
{definition.successMessage}
</div>
) : (
<form onSubmit={handleSubmit} noValidate={false}>
{fetcher.data?.error ? (
<div className="tcform-error" role="alert">
{fetcher.data.error}
</div>
) : null}
{filterVisibleFields(definition.fields, values).map((field) => (
<FieldRenderer
key={field.key}
field={field}
value={values[field.key] ?? (field.type === "boolean" ? false : field.type === "multiselect" ? [] : "")}
onChange={(next) => setValues((prev) => ({ ...prev, [field.key]: next }))}
/>
))}
<div className="tcform-row tcform-checkbox">
<label className="tcform-label">
<input
type="checkbox"
name="__gdprAccepted"
checked={values.__gdprAccepted === true}
onChange={(e) => setValues((prev) => ({ ...prev, __gdprAccepted: e.target.checked }))}
required
/>
<span>{definition.gdprConsentLabel}</span>
</label>
<div ref={containerRef} className={rootClassName} style={styleVars}>
<style>{TCFORM_CSS}</style>
<div className="tcform-shell">
{layout === "standalone" && monogram ? (
<div className="tcform-brand" aria-hidden="true">
<span className="tcform-brand-badge">{monogram}</span>
</div>
<Captcha enabled={captcha.enabled} provider={captcha.provider} instanceUrl={captcha.instanceUrl} sitekey={captcha.sitekey} />
<input type="hidden" name="__hp_key" value={HONEYPOT_FIELD_KEY} />
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? "..." : definition.submitLabel}
</button>
</form>
)}
) : null}
<div className="tcform-card">
{submittedOk ? (
<div className="tcform-success" role="status">
<span className="tcform-success-icon" aria-hidden="true">
<IconCheck />
</span>
<p className="tcform-success-message">{definition.successMessage}</p>
</div>
) : (
<>
<h1>{definition.title}</h1>
{definition.description ? <p className="tcform-description">{definition.description}</p> : null}
{fetcher.data?.error ? (
<div className="tcform-error" role="alert">
<IconAlert />
<span>{fetcher.data.error}</span>
</div>
) : null}
<hr className="tcform-divider" />
<form onSubmit={handleSubmit} noValidate={false}>
{filterVisibleFields(definition.fields, values).map((field) => (
<FieldRenderer
key={field.key}
field={field}
value={values[field.key] ?? (field.type === "boolean" ? false : field.type === "multiselect" ? [] : "")}
onChange={(next) => setValues((prev) => ({ ...prev, [field.key]: next }))}
/>
))}
<div className="tcform-row tcform-checkbox tcform-consent">
<label className="tcform-label">
<input
type="checkbox"
name="__gdprAccepted"
checked={values.__gdprAccepted === true}
onChange={(e) => setValues((prev) => ({ ...prev, __gdprAccepted: e.target.checked }))}
required
/>
<span>{definition.gdprConsentLabel}</span>
</label>
</div>
<div className="tcform-captcha">
<Captcha enabled={captcha.enabled} provider={captcha.provider} instanceUrl={captcha.instanceUrl} sitekey={captcha.sitekey} />
</div>
<input type="hidden" name="__hp_key" value={HONEYPOT_FIELD_KEY} />
<button type="submit" className="tcform-submit" disabled={isSubmitting}>
{isSubmitting ? t("settings.forms.public.submitting", "Wird gesendet …") : definition.submitLabel}
</button>
<p className="tcform-required-hint">{t("settings.forms.public.requiredHint", "Mit * markierte Felder sind Pflichtfelder.")}</p>
</form>
</>
)}
</div>
<footer className="tcform-footer">
<span>{t("settings.forms.public.providedBy", "Bereitgestellt über {{product}}", { product: defaultBrandTokens.productName })}</span>
<span>{t("settings.forms.public.privacyNote", "Ihre Angaben werden vertraulich behandelt und nur zur Bearbeitung Ihrer Anfrage verwendet.")}</span>
</footer>
</div>
</div>
);
}
@@ -0,0 +1,171 @@
import type * as React from "react";
import { useTranslation } from "react-i18next";
/**
* Friendly "form not available" page (Subframe V02) shown instead of a bare
* 404 when a public form cannot be resolved. Self-contained `tcform-*` CSS —
* no `~/ui` imports — because the embed variant renders inside third-party
* iframes where the app shell CSS is undesirable.
*/
export type PublicFormUnavailableProps = {
/**
* "standalone" renders the full V02 page (tinted backdrop, reasons list)
* for `/f/:tenant/:slug`; "embed" renders a compact card for the iframe
* embed route.
*/
variant?: "standalone" | "embed";
};
const TCFORM_UNAVAILABLE_CSS = `
.tcform-unavail-root { font-family: system-ui, -apple-system, "Segoe UI", sans-serif; color: #16232e; box-sizing: border-box; padding: 16px; }
.tcform-unavail-root *, .tcform-unavail-root *::before, .tcform-unavail-root *::after { box-sizing: border-box; }
.tcform-unavail-root--page { min-height: 100vh; background: #f2f4f7; padding: 48px 16px; display: flex; flex-direction: column; justify-content: center; }
.tcform-unavail-shell { max-width: 480px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }
.tcform-unavail-card { background: #ffffff; border: 1px solid #e0e5eb; border-radius: 10px; box-shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 8px 24px rgba(16, 24, 40, 0.06); padding: 32px 28px; display: flex; flex-direction: column; gap: 20px; }
.tcform-unavail-head { display: flex; flex-direction: column; align-items: center; gap: 12px; text-align: center; }
.tcform-unavail-icon { display: inline-flex; align-items: center; justify-content: center; width: 56px; height: 56px; border-radius: 50%; background: #fef9ec; color: #b45309; }
.tcform-unavail-root h1 { font-size: 1.25rem; line-height: 1.35; margin: 0; font-weight: 700; }
.tcform-unavail-root p.tcform-unavail-description { margin: 0; font-size: 0.9rem; line-height: 1.5; opacity: 0.72; }
.tcform-unavail-reasons { border: 1px solid #e0e5eb; border-radius: 8px; padding: 14px 16px; display: flex; flex-direction: column; gap: 12px; }
.tcform-unavail-reasons-title { font-size: 0.72rem; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; opacity: 0.6; margin: 0; }
.tcform-unavail-reason { display: flex; align-items: flex-start; gap: 10px; }
.tcform-unavail-reason svg { flex: none; margin-top: 2px; opacity: 0.55; }
.tcform-unavail-reason-title { display: block; font-size: 0.85rem; font-weight: 600; margin: 0; }
.tcform-unavail-reason-text { display: block; font-size: 0.82rem; line-height: 1.45; opacity: 0.68; margin: 0; }
.tcform-unavail-footer { display: flex; align-items: center; justify-content: center; gap: 8px; text-align: center; font-size: 0.78rem; opacity: 0.7; line-height: 1.4; }
.tcform-unavail-footer svg { flex: none; }
.tcform-unavail-root--embed .tcform-unavail-card { padding: 24px 20px; }
@media (max-width: 520px) { .tcform-unavail-card { padding: 24px 16px; } .tcform-unavail-root--page { padding: 24px 12px; } }
`;
function IconCalendarOff(): React.JSX.Element {
return (
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M4.2 4.2A2 2 0 0 0 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 1.8-1.2" />
<path d="M21 15.5V6a2 2 0 0 0-2-2H9.5" />
<path d="M16 2v4" />
<path d="M3 10h7" />
<path d="M21 10h-5.5" />
<line x1="2" y1="2" x2="22" y2="22" />
</svg>
);
}
function IconClock(): React.JSX.Element {
return (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="10" />
<polyline points="12 6 12 12 16 14" />
</svg>
);
}
function IconLinkOff(): React.JSX.Element {
return (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M9 17H7A5 5 0 0 1 7 7" />
<path d="M15 7h2a5 5 0 0 1 4 8" />
<line x1="8" y1="12" x2="12" y2="12" />
<line x1="2" y1="2" x2="22" y2="22" />
</svg>
);
}
function IconPause(): React.JSX.Element {
return (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<rect x="6" y="4" width="4" height="16" rx="1" />
<rect x="14" y="4" width="4" height="16" rx="1" />
</svg>
);
}
function IconShield(): React.JSX.Element {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10" />
<path d="m9 12 2 2 4-4" />
</svg>
);
}
export function PublicFormUnavailable({ variant = "standalone" }: PublicFormUnavailableProps): React.JSX.Element {
const { t } = useTranslation();
const isPage = variant === "standalone";
const rootClassName = isPage ? "tcform-unavail-root tcform-unavail-root--page" : "tcform-unavail-root tcform-unavail-root--embed";
return (
<main className={rootClassName}>
<style>{TCFORM_UNAVAILABLE_CSS}</style>
<div className="tcform-unavail-shell">
<div className="tcform-unavail-card">
<div className="tcform-unavail-head">
<span className="tcform-unavail-icon" aria-hidden="true">
<IconCalendarOff />
</span>
<h1>{t("settings.forms.public.unavailable.title", "Dieses Formular ist aktuell nicht verfügbar")}</h1>
<p className="tcform-unavail-description">
{t(
"settings.forms.public.unavailable.description",
"Sie können dieses Formular momentan nicht ausfüllen. Das kann verschiedene Gründe haben.",
)}
</p>
</div>
{isPage ? (
<div className="tcform-unavail-reasons">
<p className="tcform-unavail-reasons-title">{t("settings.forms.public.unavailable.reasonsTitle", "Mögliche Gründe")}</p>
<div className="tcform-unavail-reason">
<IconClock />
<div>
<span className="tcform-unavail-reason-title">
{t("settings.forms.public.unavailable.reasonExpired.title", "Annahmezeitraum beendet")}
</span>
<span className="tcform-unavail-reason-text">
{t(
"settings.forms.public.unavailable.reasonExpired.text",
"Der Zeitraum für Einreichungen über dieses Formular ist abgelaufen.",
)}
</span>
</div>
</div>
<div className="tcform-unavail-reason">
<IconLinkOff />
<div>
<span className="tcform-unavail-reason-title">
{t("settings.forms.public.unavailable.reasonLink.title", "Link nicht mehr aktuell")}
</span>
<span className="tcform-unavail-reason-text">
{t(
"settings.forms.public.unavailable.reasonLink.text",
"Der verwendete Link ist veraltet oder wurde durch einen neuen ersetzt.",
)}
</span>
</div>
</div>
<div className="tcform-unavail-reason">
<IconPause />
<div>
<span className="tcform-unavail-reason-title">
{t("settings.forms.public.unavailable.reasonPaused.title", "Vorübergehend pausiert")}
</span>
<span className="tcform-unavail-reason-text">
{t(
"settings.forms.public.unavailable.reasonPaused.text",
"Der Anbieter hat die Annahme neuer Anfragen kurzzeitig deaktiviert.",
)}
</span>
</div>
</div>
</div>
) : null}
</div>
<div className="tcform-unavail-footer">
<IconShield />
<span>
{t("settings.forms.public.unavailable.dataNote", "Ihre Daten bleiben geschützt. Es wurden keine Angaben übermittelt.")}
</span>
</div>
</div>
</main>
);
}
@@ -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 }));
}