@revenexx/cover 0.2.14 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ /** BFF paths for storefront forms (built in the Cockpit, rendered here). */
2
+ export const formsApi = {
3
+ schema: (slug: string) => `/api/forms/${slug}`,
4
+ submit: (slug: string) => `/api/forms/${slug}/submit`,
5
+ };
@@ -0,0 +1,273 @@
1
+ <script setup lang="ts">
2
+ import type { FormKitSchemaDefinition } from "@formkit/core";
3
+
4
+ import { getNode } from "@formkit/core";
5
+
6
+ import { formsApi } from "../api/forms";
7
+
8
+ /**
9
+ * Renders a form built in the Cockpit (the `forms` app) by its slug, using the
10
+ * same FormKit engine as the rest of the storefront — the `definition` is the
11
+ * FormKit schema authored in the Form Builder, rendered verbatim (SSR).
12
+ *
13
+ * Multi-step: the definition may contain `$rxStep` markers that split it into
14
+ * pages (and an optional content-only "thank-you" page). We render a stepper
15
+ * with Back/Continue and validate each step before advancing; on submit the
16
+ * collected values POST to the BFF (firing `revenexx.forms.form.submitted`),
17
+ * then the thank-you page (or a success message) is shown.
18
+ *
19
+ * <RevenexxForm slug="contact" />
20
+ */
21
+ const props = defineProps<{
22
+ /** The form's slug, as published in the Cockpit. */
23
+ slug: string;
24
+ /** Origin recorded with the submission (defaults to the current path). */
25
+ source?: string;
26
+ /**
27
+ * Values to pre-fill, keyed by field name — e.g. a linked product for a
28
+ * price request: `:context="{ product: 'SKU-123' }"`. Product fields also
29
+ * read the matching URL query param automatically (`?product=SKU-123`).
30
+ */
31
+ context?: Record<string, unknown>;
32
+ }>();
33
+
34
+ const { icon } = useIcons();
35
+ const { locale } = useI18n();
36
+ const route = useRoute();
37
+
38
+ interface FormPayload {
39
+ name: string;
40
+ slug: string;
41
+ definition: Record<string, unknown>[];
42
+ settings?: { submit_label?: string; success_message?: string } | null;
43
+ }
44
+
45
+ interface FormStep {
46
+ id: string;
47
+ kind: "fields" | "thankyou";
48
+ title?: string;
49
+ nodes: Record<string, unknown>[];
50
+ }
51
+
52
+ const STEP_MARKER = "$rxStep";
53
+
54
+ /** Mirror of the Cockpit's normalizeSteps: split a flat definition on markers. */
55
+ function normalizeSteps(definition: Record<string, unknown>[]): FormStep[] {
56
+ const steps: FormStep[] = [];
57
+ let current: FormStep = { id: "step_1", kind: "fields", nodes: [] };
58
+ let started = false;
59
+ for (const node of definition) {
60
+ if (node && typeof node === "object" && STEP_MARKER in node) {
61
+ const marker = (node[STEP_MARKER] ?? {}) as { id?: string; kind?: string; title?: string };
62
+ if (started) steps.push(current);
63
+ current = { id: marker.id || `step_${steps.length + 1}`, kind: marker.kind === "thankyou" ? "thankyou" : "fields", title: marker.title, nodes: [] };
64
+ started = true;
65
+ }
66
+ else {
67
+ current.nodes.push(node);
68
+ started = true;
69
+ }
70
+ }
71
+ steps.push(current);
72
+ return steps;
73
+ }
74
+
75
+ // No top-level await — keep this a sync component so it renders its own
76
+ // pending/empty states. Re-fetches on locale change (BFF localises labels).
77
+ const { data: form, pending } = useAsyncData(
78
+ () => `revenexx-form-${props.slug}-${locale.value}`,
79
+ () => $fetch<FormPayload>(formsApi.schema(props.slug), {
80
+ headers: { "x-locale": locale.value },
81
+ }).catch(() => null),
82
+ { watch: [() => props.slug, locale] },
83
+ );
84
+
85
+ const steps = computed(() => normalizeSteps(form.value?.definition ?? []));
86
+ const fieldSteps = computed(() => steps.value.filter(s => s.kind === "fields"));
87
+ const thankStep = computed(() => steps.value.find(s => s.kind === "thankyou") ?? null);
88
+ const submitLabel = computed(() => form.value?.settings?.submit_label || "Submit");
89
+
90
+ // Product (reference) fields pre-fill from the `context` prop or the matching
91
+ // URL query param — so a price request linked from a product page carries it.
92
+ const productFields = computed(() => steps.value
93
+ .flatMap(s => s.nodes)
94
+ .filter(n => n.rxKind === "product")
95
+ .map(n => n.name)
96
+ .filter((n): n is string => typeof n === "string"));
97
+
98
+ const prefill = computed<Record<string, unknown>>(() => {
99
+ const out: Record<string, unknown> = { ...(props.context ?? {}) };
100
+ for (const name of productFields.value) {
101
+ if (out[name] == null) {
102
+ const q = route.query[name] ?? route.query.product ?? route.query.sku;
103
+ if (q != null) out[name] = Array.isArray(q) ? q[0] : q;
104
+ }
105
+ }
106
+ return out;
107
+ });
108
+
109
+ /** Strip our internal `rxKind` marker; lock a product field once pre-filled. */
110
+ function cleanNodes(nodes: Record<string, unknown>[]): FormKitSchemaDefinition {
111
+ return nodes.map((n) => {
112
+ if (!n.rxKind) return n;
113
+ const { rxKind, ...rest } = n;
114
+ if (rxKind === "product" && typeof n.name === "string" && prefill.value[n.name] != null) {
115
+ (rest as Record<string, unknown>).readonly = true;
116
+ }
117
+ return rest;
118
+ }) as FormKitSchemaDefinition;
119
+ }
120
+
121
+ const formId = useId();
122
+ const stepIndex = ref(0);
123
+ const tick = ref(0);
124
+ const submitting = ref(false);
125
+ const submitted = ref(false);
126
+ const successMessage = ref<string | null>(null);
127
+ const submitError = ref<string | null>(null);
128
+
129
+ watch(() => props.slug, () => { stepIndex.value = 0; submitted.value = false; });
130
+
131
+ const isLastStep = computed(() => stepIndex.value >= fieldSteps.value.length - 1);
132
+
133
+ /** Validity of the fields on the current step (drives Continue/Submit). */
134
+ const activeStepValid = computed(() => {
135
+ void tick.value;
136
+ const node = getNode(formId);
137
+ if (!node) return true;
138
+ const fields = (fieldSteps.value[stepIndex.value]?.nodes ?? []).filter(n => typeof n.name === "string");
139
+ return fields.every((n) => {
140
+ const child = node.at(n.name as string);
141
+ return child ? child.context?.state.valid !== false : true;
142
+ });
143
+ });
144
+
145
+ function next() {
146
+ if (activeStepValid.value && !isLastStep.value) stepIndex.value += 1;
147
+ }
148
+ function back() {
149
+ if (stepIndex.value > 0) stepIndex.value -= 1;
150
+ }
151
+ function triggerSubmit() {
152
+ getNode(formId)?.submit();
153
+ }
154
+
155
+ async function onSubmit(values: Record<string, unknown>) {
156
+ submitError.value = null;
157
+ submitting.value = true;
158
+ try {
159
+ const res = await $fetch<{ ok: boolean; success_message: string | null }>(
160
+ formsApi.submit(props.slug),
161
+ {
162
+ method: "POST",
163
+ body: {
164
+ data: values,
165
+ source: props.source ?? (import.meta.client ? window.location.pathname : undefined),
166
+ },
167
+ },
168
+ );
169
+ successMessage.value = res.success_message || "Thank you — your message has been sent.";
170
+ submitted.value = true;
171
+ }
172
+ catch {
173
+ submitError.value = "Something went wrong. Please try again.";
174
+ }
175
+ finally {
176
+ submitting.value = false;
177
+ }
178
+ }
179
+ </script>
180
+
181
+ <template>
182
+ <div
183
+ v-if="pending"
184
+ class="flex justify-center py-8"
185
+ >
186
+ <UIcon
187
+ :name="icon('loading')"
188
+ class="w-5 h-5 animate-spin text-muted"
189
+ />
190
+ </div>
191
+
192
+ <!-- Confirmation: the designed thank-you page (if any) + the success message. -->
193
+ <div
194
+ v-else-if="submitted"
195
+ class="space-y-6"
196
+ >
197
+ <FormKitSchema
198
+ v-if="thankStep && thankStep.nodes.length"
199
+ :schema="cleanNodes(thankStep.nodes)"
200
+ />
201
+ <UAlert
202
+ color="success"
203
+ variant="soft"
204
+ :icon="icon('success')"
205
+ :title="successMessage ?? undefined"
206
+ />
207
+ </div>
208
+
209
+ <FormKit
210
+ v-else-if="form"
211
+ :id="formId"
212
+ type="form"
213
+ :value="prefill"
214
+ :actions="false"
215
+ :incomplete-message="false"
216
+ @input="tick++"
217
+ @submit="onSubmit"
218
+ >
219
+ <!-- Step progress -->
220
+ <p
221
+ v-if="fieldSteps.length > 1"
222
+ class="mb-4 text-sm text-muted"
223
+ >
224
+ Step {{ stepIndex + 1 }} of {{ fieldSteps.length }}<template v-if="fieldSteps[stepIndex]?.title"> · {{ fieldSteps[stepIndex]?.title }}</template>
225
+ </p>
226
+
227
+ <div
228
+ v-for="(step, i) in fieldSteps"
229
+ v-show="i === stepIndex"
230
+ :key="step.id"
231
+ >
232
+ <FormKitSchema :schema="cleanNodes(step.nodes)" />
233
+ </div>
234
+
235
+ <div class="mt-6 flex items-center justify-between gap-3">
236
+ <UButton
237
+ v-if="stepIndex > 0"
238
+ type="button"
239
+ color="neutral"
240
+ variant="ghost"
241
+ :label="'Back'"
242
+ @click="back"
243
+ />
244
+ <span v-else />
245
+
246
+ <UButton
247
+ v-if="!isLastStep"
248
+ type="button"
249
+ color="primary"
250
+ :disabled="!activeStepValid"
251
+ :label="'Continue'"
252
+ @click="next"
253
+ />
254
+ <UButton
255
+ v-else
256
+ type="button"
257
+ color="primary"
258
+ :loading="submitting"
259
+ :disabled="!activeStepValid"
260
+ :label="submitLabel"
261
+ @click="triggerSubmit"
262
+ />
263
+ </div>
264
+
265
+ <UAlert
266
+ v-if="submitError"
267
+ class="mt-4"
268
+ color="error"
269
+ variant="soft"
270
+ :title="submitError"
271
+ />
272
+ </FormKit>
273
+ </template>
@@ -17,6 +17,13 @@ const { t } = useI18n();
17
17
  const auth = useAuthStore();
18
18
  const { loading, error } = storeToRefs(auth);
19
19
 
20
+ // Registration availability (tenant setting, enforced by the customers app).
21
+ // When B2B self-registration is off we show a notice instead of the form, and
22
+ // when a VAT id is mandatory we make that field required. Defaults open.
23
+ const { data: registration } = useRegistrationConfig();
24
+ const registrationEnabled = computed(() => registration.value?.b2b !== false);
25
+ const vatRequired = computed(() => registration.value?.vatRequired === true);
26
+
20
27
  const state = reactive<RegisterFormState>({
21
28
  mode: "new",
22
29
  company: "",
@@ -99,11 +106,22 @@ async function onSubmit(): Promise<void> {
99
106
  <template>
100
107
  <div class="bg-elevated py-6 px-6 sm:px-8 rounded-lg">
101
108
  <h2 class="text-xl font-semibold text-highlighted">
102
- {{ t('auth.register.title') }}
109
+ {{ registrationEnabled ? t('auth.register.title') : t('auth.register.disabled.title') }}
103
110
  </h2>
104
111
 
112
+ <!-- Registration closed by the tenant — no form, just a notice. -->
113
+ <p
114
+ v-if="!registrationEnabled"
115
+ class="pt-6 text-sm text-muted"
116
+ >
117
+ {{ t('auth.register.disabled.description') }}
118
+ </p>
119
+
105
120
  <!-- Path selection (new vs. existing customer) -->
106
- <fieldset class="pt-6">
121
+ <fieldset
122
+ v-if="registrationEnabled"
123
+ class="pt-6"
124
+ >
107
125
  <legend class="text-sm font-medium text-highlighted">
108
126
  {{ t('auth.register.modes.title') }}
109
127
  </legend>
@@ -138,6 +156,7 @@ async function onSubmit(): Promise<void> {
138
156
  </fieldset>
139
157
 
140
158
  <FormKit
159
+ v-if="registrationEnabled"
141
160
  type="form"
142
161
  :actions="false"
143
162
  class="space-y-7 pt-7"
@@ -173,6 +192,7 @@ async function onSubmit(): Promise<void> {
173
192
  type="text"
174
193
  :label="t('auth.register.fields2.vatId')"
175
194
  name="vatId"
195
+ :validation="state.mode === 'new' && vatRequired ? 'required' : undefined"
176
196
  :help="t('auth.register.fields2.vatIdHint')"
177
197
  placeholder="DE123456789"
178
198
  />
@@ -2,17 +2,23 @@
2
2
  /** "I am a new customer" panel of the split login page. */
3
3
  const { t } = useI18n();
4
4
  const localePath = useLocalePath();
5
+
6
+ // When the tenant has closed self-registration the customers app rejects it
7
+ // (403), so the CTA points nowhere useful — show a notice instead of the link.
8
+ const { data: registration } = useRegistrationConfig();
9
+ const enabled = computed(() => registration.value?.b2b !== false);
5
10
  </script>
6
11
 
7
12
  <template>
8
13
  <div class="border border-default py-6 px-8 rounded-lg flex flex-col">
9
14
  <h2 class="text-xl font-semibold text-highlighted">
10
- {{ t('auth.login.newCustomer') }}
15
+ {{ enabled ? t('auth.login.newCustomer') : t('auth.register.disabled.title') }}
11
16
  </h2>
12
17
  <p class="pt-6 text-sm text-muted flex-1">
13
- {{ t('auth.login.newCustomerText') }}
18
+ {{ enabled ? t('auth.login.newCustomerText') : t('auth.register.disabled.description') }}
14
19
  </p>
15
20
  <UButton
21
+ v-if="enabled"
16
22
  :to="localePath('/register')"
17
23
  color="neutral"
18
24
  variant="outline"
@@ -0,0 +1,22 @@
1
+ export interface RegistrationConfig {
2
+ /** B2B self-registration (founding an organization) is open. */
3
+ b2b: boolean;
4
+ /** B2C self-registration (a standalone contact) is open. */
5
+ b2c: boolean;
6
+ /** A VAT id is mandatory when registering an organization. */
7
+ vatRequired: boolean;
8
+ }
9
+
10
+ /**
11
+ * The tenant's registration availability, resolved from the customers app's
12
+ * settings through the BFF. Drives whether the storefront shows or hides the
13
+ * register form — the customers app enforces the same flags server-side, so
14
+ * this is purely the matching UX. Shared by key across the teaser and the
15
+ * panel, and defaults open so a settings hiccup never hides registration.
16
+ */
17
+ export function useRegistrationConfig() {
18
+ return useFetch<RegistrationConfig>("/api/auth/registration-config", {
19
+ key: "registration-config",
20
+ default: () => ({ b2b: true, b2c: true, vatRequired: false }),
21
+ });
22
+ }
@@ -28,8 +28,13 @@
28
28
  "errors": {
29
29
  "emailFormat": "Bitte geben Sie eine gültige E-Mail-Adresse ein",
30
30
  "passwordsMismatch": "Passwörter stimmen nicht überein",
31
+ "registrationDisabled": "Die Registrierung ist derzeit geschlossen. Bitte kontaktieren Sie uns, um ein Konto einzurichten.",
31
32
  "unknown": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut."
32
33
  },
34
+ "disabled": {
35
+ "title": "Registrierung derzeit geschlossen",
36
+ "description": "Die Online-Registrierung ist momentan nicht verfügbar. Bitte kontaktieren Sie unser Vertriebsteam, um Ihr Geschäftskonto einzurichten."
37
+ },
33
38
  "loginTeaserText": "Sie haben bereits ein Geschäftskonto bei uns? Melden Sie sich an und greifen Sie auf Ihre Bestellungen, Bestelllisten und Konditionen zu.",
34
39
  "modes": {
35
40
  "title": "Wie möchten Sie sich registrieren?",
@@ -28,8 +28,13 @@
28
28
  "errors": {
29
29
  "emailFormat": "Please enter a valid email address",
30
30
  "passwordsMismatch": "Passwords do not match",
31
+ "registrationDisabled": "Registration is currently closed. Please contact us to set up an account.",
31
32
  "unknown": "Something went wrong. Please try again."
32
33
  },
34
+ "disabled": {
35
+ "title": "Registration is currently closed",
36
+ "description": "Online registration is not available right now. Please contact our sales team to set up your business account."
37
+ },
33
38
  "loginTeaserText": "Already have a business account with us? Sign in to access your orders, order lists and negotiated pricing.",
34
39
  "modes": {
35
40
  "title": "How would you like to register?",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.2.14",
3
+ "version": "0.2.15",
4
4
  "description": "Cover \u2014 revenexx design system for Nuxt. Distributed as a Nuxt layer: generic UI components, theming tokens and stores shared by the demo shop, custom storefronts and the Blokkli theme.",
5
5
  "type": "module",
6
6
  "main": "./nuxt.config.ts",
@@ -94,6 +94,12 @@ export default defineEventHandler(async (event) => {
94
94
  return user;
95
95
  }
96
96
  catch (err) {
97
+ // The tenant turned self-registration off — a deliberate 403 the
98
+ // customers app raises. Surface it as a clean user-facing type (not a
99
+ // 503) so the form can explain instead of looking broken.
100
+ if (err instanceof RevenexxException && err.code === 403) {
101
+ throw createError({ statusCode: 403, data: { type: "registration_disabled" } });
102
+ }
97
103
  if (isApiUserError(err)) {
98
104
  throw createError({ statusCode: err.code, data: { type: apiAuthErrorType(err) } });
99
105
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Registration availability for the storefront.
3
+ *
4
+ * The customers app exposes self-registration as tenant settings
5
+ * (b2b/b2c toggles, VAT requirement). The gateway resolves them at
6
+ * /v1/settings/apps/customers; we read them here so the register form can hide
7
+ * or disable itself when the tenant has switched registration off. The
8
+ * customers app ENFORCES the same flags (403 on a disabled path) — this is the
9
+ * matching UX so users never hit a wall after filling the form.
10
+ *
11
+ * Fails open: a settings read error never locks the form. Mock mode (the demo
12
+ * shop) reports everything enabled.
13
+ */
14
+ interface RegistrationConfig {
15
+ b2b: boolean;
16
+ b2c: boolean;
17
+ vatRequired: boolean;
18
+ }
19
+
20
+ const DEFAULTS: RegistrationConfig = { b2b: true, b2c: true, vatRequired: false };
21
+
22
+ export default defineEventHandler(async (event): Promise<RegistrationConfig> => {
23
+ if (resolveAuthServiceKey(event) === "mock") {
24
+ return DEFAULTS;
25
+ }
26
+ try {
27
+ const res = await useRevenexxSdk().settings.settingsGetAppSettings({ app: "customers" }) as {
28
+ settings?: Record<string, unknown>;
29
+ };
30
+ const s = res.settings ?? {};
31
+ return {
32
+ b2b: s.b2b_registration_enabled !== false,
33
+ b2c: s.b2c_registration_enabled !== false,
34
+ vatRequired: s.organization_vat_id_required === true,
35
+ };
36
+ }
37
+ catch (err) {
38
+ getLogService().error("API request failed: registration-config", apiErrorContext(err));
39
+ return DEFAULTS;
40
+ }
41
+ });
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Records a form submission. Resolves the live form by slug, then writes a row
3
+ * to `forms.submissions` via the gateway — Baseline emits `form.submitted` on
4
+ * insert, which Integration Studio / email automations listen to. Returns the
5
+ * form's success message for the confirmation state.
6
+ */
7
+ export default defineEventHandler(async (event) => {
8
+ const slug = getRouterParam(event, "slug");
9
+ if (!slug) {
10
+ throw createError({ statusCode: 400, message: "Missing form slug" });
11
+ }
12
+
13
+ const body = await readBody<{ data?: Record<string, unknown>; source?: string }>(event);
14
+ const data = body?.data;
15
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
16
+ throw createError({ statusCode: 400, message: "Invalid submission" });
17
+ }
18
+
19
+ try {
20
+ const form = await resolveLiveForm(slug);
21
+ if (!form) {
22
+ throw createError({ statusCode: 404, message: "Form not found" });
23
+ }
24
+
25
+ await useRevenexxSdk().call("POST", "/v1/forms/submissions", {
26
+ body: {
27
+ form_id: form.id,
28
+ form_slug: form.slug,
29
+ data,
30
+ source: body?.source ?? null,
31
+ },
32
+ });
33
+
34
+ // Run the operator-configured post-submit actions (webhook / entity write).
35
+ await runFormActions(form, data, body?.source ?? null);
36
+
37
+ return { ok: true, success_message: form.settings?.success_message ?? null };
38
+ }
39
+ catch (err) {
40
+ if (err !== null && typeof err === "object" && "statusCode" in err) {
41
+ throw err;
42
+ }
43
+ if (isApiUserError(err)) {
44
+ throw createError({ statusCode: (err as RevenexxException).code, message: "Could not submit the form" });
45
+ }
46
+ getLogService().error("Service error: forms/submit", { slug, ...apiErrorContext(err) });
47
+ throw createError({ statusCode: 500, message: "Internal server error" });
48
+ }
49
+ });
@@ -0,0 +1,40 @@
1
+ import type { FormPublic } from "../../interfaces/forms";
2
+
3
+ /**
4
+ * Returns the published form for `slug` so the storefront can render it. The
5
+ * `definition` is a FormKit schema rendered verbatim by <RevenexxForm>. 404
6
+ * when there is no live form with that slug (drafts stay invisible).
7
+ */
8
+ export default defineEventHandler(async (event): Promise<FormPublic> => {
9
+ const slug = getRouterParam(event, "slug");
10
+ if (!slug) {
11
+ throw createError({ statusCode: 400, message: "Missing form slug" });
12
+ }
13
+ const locale = resolveLocale(event);
14
+
15
+ try {
16
+ const form = await resolveLiveForm(slug);
17
+ if (!form) {
18
+ throw createError({ statusCode: 404, message: "Form not found" });
19
+ }
20
+ const definition = Array.isArray(form.definition) ? form.definition : [];
21
+ return {
22
+ name: form.name,
23
+ slug: form.slug,
24
+ definition: localizeDefinition(definition, form.settings, locale),
25
+ settings: form.settings
26
+ ? { submit_label: form.settings.submit_label, success_message: form.settings.success_message }
27
+ : null,
28
+ };
29
+ }
30
+ catch (err) {
31
+ if (err !== null && typeof err === "object" && "statusCode" in err) {
32
+ throw err;
33
+ }
34
+ if (isApiUserError(err)) {
35
+ throw createError({ statusCode: 404, message: "Form not available" });
36
+ }
37
+ getLogService().error("Service error: forms/schema", { slug, ...apiErrorContext(err) });
38
+ throw createError({ statusCode: 500, message: "Internal server error" });
39
+ }
40
+ });
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Shapes for the Forms BFF. A form is authored in the Cockpit (the `forms`
3
+ * platform app) and rendered here from its FormKit `definition`. The public
4
+ * payload never exposes the row id — the submit route re-resolves it by slug.
5
+ */
6
+ export interface FieldI18n {
7
+ label?: string;
8
+ placeholder?: string;
9
+ help?: string;
10
+ }
11
+
12
+ export interface FormActionMapping {
13
+ source: string;
14
+ target: string;
15
+ }
16
+
17
+ export interface FormAction {
18
+ id: string;
19
+ type: "webhook" | "event" | "entity";
20
+ enabled: boolean;
21
+ url?: string;
22
+ method?: "POST" | "PUT";
23
+ event_name?: string;
24
+ vendor?: string;
25
+ app?: string;
26
+ entity?: string;
27
+ path?: string;
28
+ mapping?: FormActionMapping[];
29
+ }
30
+
31
+ export interface FormSettings {
32
+ submit_label?: string;
33
+ success_message?: string;
34
+ notify_email?: string | null;
35
+ locales?: string[];
36
+ default_locale?: string;
37
+ /** locale → fieldName → translated texts, overlaid onto the base definition. */
38
+ i18n?: Record<string, Record<string, FieldI18n>>;
39
+ /** Post-submit actions (webhook / event / entity write). */
40
+ actions?: FormAction[];
41
+ }
42
+
43
+ /** A row as returned by the gateway `GET /v1/forms`. */
44
+ export interface FormRow {
45
+ id: string;
46
+ name: string;
47
+ slug: string;
48
+ status: string;
49
+ definition: Record<string, unknown>[];
50
+ settings?: FormSettings | null;
51
+ }
52
+
53
+ /** The lean settings the storefront needs (no i18n overlay, no internal config). */
54
+ export interface FormPublicSettings {
55
+ submit_label?: string;
56
+ success_message?: string;
57
+ }
58
+
59
+ /** What the storefront needs to render a form (no id, no status, localised). */
60
+ export interface FormPublic {
61
+ name: string;
62
+ slug: string;
63
+ definition: Record<string, unknown>[];
64
+ settings: FormPublicSettings | null;
65
+ }
@@ -0,0 +1,96 @@
1
+ import type { FormRow, FormSettings } from "../interfaces/forms";
2
+
3
+ /**
4
+ * Run a form's post-submit actions once a submission is recorded. Best-effort
5
+ * and non-blocking for the user: every action is isolated, failures are logged
6
+ * but never fail the submission. (`revenexx.forms.form.submitted` fires
7
+ * regardless, from Baseline.)
8
+ * • webhook — POST/PUT the submission to a URL
9
+ * • entity — create a row in another app's entity via the gateway, mapping
10
+ * form fields → entity columns
11
+ * • event — covered by the platform's form.submitted emission (no-op here)
12
+ */
13
+ export async function runFormActions(form: FormRow, data: Record<string, unknown>, source: string | null): Promise<void> {
14
+ const actions = (form.settings?.actions ?? []).filter(a => a.enabled);
15
+ if (!actions.length) return;
16
+ const sdk = useRevenexxSdk();
17
+ await Promise.allSettled(actions.map(async (action) => {
18
+ try {
19
+ if (action.type === "webhook" && action.url) {
20
+ await $fetch(action.url, {
21
+ method: action.method ?? "POST",
22
+ body: { form: form.slug, source, data },
23
+ timeout: 8000,
24
+ });
25
+ }
26
+ else if (action.type === "entity" && action.app && action.entity) {
27
+ const body: Record<string, unknown> = {};
28
+ for (const m of action.mapping ?? []) {
29
+ if (m.target && m.source in data) body[m.target] = data[m.source];
30
+ }
31
+ const rel = action.path || `/${action.app}/${action.entity}`;
32
+ await sdk.call("POST", `/v1${rel.startsWith("/") ? rel : `/${rel}`}`, { body });
33
+ }
34
+ }
35
+ catch (err) {
36
+ getLogService().error("forms action failed", { action: action.type, slug: form.slug, ...apiErrorContext(err) });
37
+ }
38
+ }));
39
+ }
40
+
41
+ const TRANSLATABLE = ["label", "placeholder", "help"] as const;
42
+
43
+ /**
44
+ * Overlay per-locale field translations (`settings.i18n[locale][fieldName]`)
45
+ * onto the base FormKit definition (authored in `default_locale`). Mirrors the
46
+ * Cockpit builder's resolveDefinition so the storefront renders exactly what
47
+ * the operator previewed. Returns the base definition for the default locale or
48
+ * when there is no overlay.
49
+ */
50
+ export function localizeDefinition(
51
+ definition: Record<string, unknown>[],
52
+ settings: FormSettings | null | undefined,
53
+ locale: string,
54
+ ): Record<string, unknown>[] {
55
+ const base = settings?.default_locale ?? "en";
56
+ if (!locale || locale === base) {
57
+ return definition;
58
+ }
59
+ const overlay = settings?.i18n?.[locale];
60
+ if (!overlay) {
61
+ return definition;
62
+ }
63
+ return definition.map((node) => {
64
+ const name = typeof node.name === "string" ? node.name : undefined;
65
+ const tx = name ? overlay[name] : undefined;
66
+ if (!tx) {
67
+ return node;
68
+ }
69
+ const next = { ...node };
70
+ for (const prop of TRANSLATABLE) {
71
+ const value = tx[prop];
72
+ if (value != null && value !== "") {
73
+ next[prop] = value;
74
+ }
75
+ }
76
+ return next;
77
+ });
78
+ }
79
+
80
+ /**
81
+ * Resolve a single LIVE form by slug from the gateway (`GET /v1/forms`). Only
82
+ * published (status: live) forms are visible to the storefront — drafts and
83
+ * archived forms return null so a page block renders nothing. Slug is unique
84
+ * per tenant, so at most one row matches.
85
+ *
86
+ * Uses the SDK escape hatch: the cover @revenexx/sdk has no generated Forms
87
+ * service yet (the app shipped after this SDK build). `?slug=&status=` are
88
+ * exact-column filters mountCrud honors and the gateway passes through.
89
+ */
90
+ export async function resolveLiveForm(slug: string): Promise<FormRow | null> {
91
+ const sdk = useRevenexxSdk();
92
+ const res = await sdk.call<{ items?: FormRow[] }>("GET", "/v1/forms", {
93
+ query: { slug, status: "live", limit: 1 },
94
+ });
95
+ return res.items?.[0] ?? null;
96
+ }
@@ -11,6 +11,7 @@ import {
11
11
  Products,
12
12
  RevenexxException,
13
13
  Search,
14
+ Settings,
14
15
  Shipping,
15
16
  } from "@revenexx/sdk";
16
17
 
@@ -46,6 +47,7 @@ export interface RevenexxSdk {
46
47
  readonly prices: Prices;
47
48
  readonly products: Products;
48
49
  readonly search: Search;
50
+ readonly settings: Settings;
49
51
  readonly shipping: Shipping;
50
52
  /**
51
53
  * Low-level escape hatch over the SDK transport (same auth, same error
@@ -234,6 +236,7 @@ export function useRevenexxSdk(): RevenexxSdk {
234
236
  prices: new Prices(client),
235
237
  products: new Products(client),
236
238
  search: new Search(client),
239
+ settings: new Settings(client),
237
240
  shipping: new Shipping(client),
238
241
  call,
239
242
  };