@revenexx/cover 0.7.0 → 0.10.1

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.
Files changed (101) hide show
  1. package/app/api/forms.ts +1 -0
  2. package/app/app.config.ts +17 -12
  3. package/app/components/RevenexxForm.vue +80 -12
  4. package/app/components/account/AccountShell.vue +18 -0
  5. package/app/components/account/approvals/AccountPendingApprovals.vue +178 -0
  6. package/app/components/account/orderlists/AccountOrderListDetail.vue +47 -4
  7. package/app/components/account/orders/AccountOrderDetail.vue +186 -1
  8. package/app/components/account/payments/AccountPayments.vue +129 -0
  9. package/app/components/account/quotes/AccountQuoteDetail.vue +48 -16
  10. package/app/components/auth/AuthLoginPanel.vue +131 -15
  11. package/app/components/auth/AuthMagicLinkPanel.vue +70 -0
  12. package/app/components/cart/view/CartSummaryPanel.vue +54 -0
  13. package/app/components/checkout/onepage/CheckoutDeliverySection.vue +13 -1
  14. package/app/components/checkout/onepage/CheckoutGate.vue +8 -7
  15. package/app/components/form/FormPage.vue +40 -0
  16. package/app/components/layout/header/AppBar.vue +7 -1
  17. package/app/components/layout/header/MainNav.vue +23 -1
  18. package/app/components/layout/header/MobileMenu.vue +12 -0
  19. package/app/components/product/detail/ProductDetailPriceRequest.vue +39 -0
  20. package/app/components/product/detail/ProductDetailView.vue +57 -0
  21. package/app/composables/useAccountHold.ts +45 -0
  22. package/app/composables/useAccountPayments.ts +21 -0
  23. package/app/composables/useAccountQuotes.ts +15 -2
  24. package/app/composables/useAuthStore.ts +82 -2
  25. package/app/composables/useAuthoredForms.ts +26 -0
  26. package/app/composables/useAvailableOffers.ts +42 -0
  27. package/app/composables/useGuestOrdering.ts +28 -0
  28. package/app/composables/useMasterDataEditable.ts +22 -7
  29. package/app/composables/useOrderListRules.ts +21 -1
  30. package/app/composables/usePendingApprovals.ts +37 -0
  31. package/app/config/icons.ts +2 -0
  32. package/app/config/navigation.ts +2 -2
  33. package/app/formkit.config.ts +14 -0
  34. package/app/interfaces/account/approvals.ts +37 -0
  35. package/app/interfaces/account/order-list.ts +29 -0
  36. package/app/interfaces/account/order-lists.ts +9 -0
  37. package/app/interfaces/account/payments.ts +48 -0
  38. package/app/interfaces/auth.ts +11 -0
  39. package/app/interfaces/b2b.ts +8 -8
  40. package/app/interfaces/offers.ts +35 -0
  41. package/app/interfaces/shopSettings.ts +77 -0
  42. package/app/plugins/account-hold.client.ts +20 -0
  43. package/app/plugins/shop-settings.ts +27 -12
  44. package/i18n/locales/de/account.json +80 -0
  45. package/i18n/locales/de/auth.json +29 -0
  46. package/i18n/locales/de/cart.json +7 -0
  47. package/i18n/locales/de/checkout.json +2 -1
  48. package/i18n/locales/de/common.json +4 -2
  49. package/i18n/locales/de/forms.json +27 -0
  50. package/i18n/locales/en/account.json +80 -0
  51. package/i18n/locales/en/auth.json +29 -0
  52. package/i18n/locales/en/cart.json +7 -0
  53. package/i18n/locales/en/checkout.json +2 -1
  54. package/i18n/locales/en/common.json +2 -0
  55. package/i18n/locales/en/forms.json +27 -0
  56. package/package.json +2 -1
  57. package/server/api/account/address/[id].delete.ts +1 -1
  58. package/server/api/account/address/[id].put.ts +1 -1
  59. package/server/api/account/address/index.post.ts +1 -1
  60. package/server/api/account/order-lists/[id].get.ts +37 -3
  61. package/server/api/account/orders/[id]/cancel.post.ts +54 -0
  62. package/server/api/account/orders/[id]/messages.get.ts +63 -0
  63. package/server/api/account/orders/[id]/messages.post.ts +44 -0
  64. package/server/api/account/organization.put.ts +1 -1
  65. package/server/api/account/payments.get.ts +54 -0
  66. package/server/api/account/pending-approvals/[id]/approve.post.ts +10 -0
  67. package/server/api/account/pending-approvals/[id]/decline.post.ts +10 -0
  68. package/server/api/account/pending-approvals/index.get.ts +25 -0
  69. package/server/api/account/profile.put.ts +1 -1
  70. package/server/api/account/quotes/[id]/decline.post.ts +35 -6
  71. package/server/api/account/team/[id].put.ts +1 -1
  72. package/server/api/account/team.post.ts +1 -1
  73. package/server/api/auth/magic-link.post.ts +32 -0
  74. package/server/api/auth/magic-link.put.ts +30 -0
  75. package/server/api/auth/otp.post.ts +33 -0
  76. package/server/api/auth/otp.put.ts +28 -0
  77. package/server/api/checkout/profile.get.ts +6 -3
  78. package/server/api/forms/[slug]/submit.post.ts +27 -16
  79. package/server/api/forms/[slug].get.ts +9 -1
  80. package/server/api/forms/index.get.ts +23 -0
  81. package/server/api/orders/index.post.ts +8 -0
  82. package/server/api/promotions/available.post.ts +37 -0
  83. package/server/config/account/organization.json +0 -4
  84. package/server/config/shop/app-settings.json +4 -0
  85. package/server/data/forms/authored.json +337 -0
  86. package/server/interfaces/forms.ts +51 -0
  87. package/server/services/ApiAuthService.ts +10 -0
  88. package/server/services/ApiFormsService.ts +56 -0
  89. package/server/services/MockB2BContextService.ts +1 -5
  90. package/server/services/MockFormsService.ts +63 -0
  91. package/server/utils/accountPayments.ts +45 -0
  92. package/server/utils/appSettings.ts +69 -4
  93. package/server/utils/forms.ts +62 -14
  94. package/server/utils/formsService.ts +29 -0
  95. package/server/utils/liveOrders.ts +26 -0
  96. package/server/utils/masterData.ts +31 -11
  97. package/server/utils/passwordlessSignIn.ts +73 -0
  98. package/server/utils/pendingApprovals.ts +153 -0
  99. package/server/utils/promotionsService.ts +90 -0
  100. package/server/utils/quotesService.ts +15 -0
  101. package/server/utils/shopSettings.ts +35 -4
@@ -0,0 +1,63 @@
1
+ import type { AccountOrderMessage } from "../../../../../app/interfaces/account/order-list";
2
+
3
+ import { OrderCommentVisibility } from "@revenexx/sdk";
4
+
5
+ /**
6
+ * What has been said about this order, buyer-visible only.
7
+ *
8
+ * The orders app keeps the desk's own notes in the same list and filters by
9
+ * visibility; asking for the customer's half is the whole of the privacy here, and
10
+ * it happens on this side of the wire so no internal note ever reaches a browser.
11
+ */
12
+ interface LiveComment {
13
+ id: string;
14
+ body?: string | null;
15
+ author?: string | null;
16
+ visibility?: string | null;
17
+ created_at?: string | null;
18
+ }
19
+
20
+ export default defineEventHandler(async (event): Promise<{ messages: AccountOrderMessage[] }> => {
21
+ const number = getRouterParam(event, "id") ?? "";
22
+ const user = await getAuthService(event).me(event);
23
+ if (!user) {
24
+ throw createError({ statusCode: 401, message: "Unauthorized" });
25
+ }
26
+ if (resolveOrderServiceKey(event) !== "api") {
27
+ return { messages: [] };
28
+ }
29
+
30
+ const order = await getLiveOrderByNumber(number);
31
+ if (!order) {
32
+ throw createError({ statusCode: 404, message: "Order not found" });
33
+ }
34
+
35
+ try {
36
+ const answer = await useRevenexxSdk().orders.ordersCommentsList({
37
+ id: order.id,
38
+ visibility: OrderCommentVisibility.Customer,
39
+ limit: 100,
40
+ }) as unknown as { items?: LiveComment[]; comments?: LiveComment[] };
41
+ const rows = answer.items ?? answer.comments ?? [];
42
+ return {
43
+ messages: rows
44
+ // Belt and braces: the filter is the app's, and a note that arrived
45
+ // anyway must not be shown because a parameter was ignored.
46
+ .filter(row => (row.visibility ?? "customer") === "customer")
47
+ .map(row => ({
48
+ id: row.id,
49
+ body: (row.body ?? "").trim(),
50
+ author: row.author ?? null,
51
+ at: row.created_at ?? "",
52
+ // The buyer's own words, told apart by the author the shop sets
53
+ // when it writes one.
54
+ fromBuyer: (row.author ?? "").startsWith("buyer:"),
55
+ }))
56
+ .filter(message => message.body.length > 0),
57
+ };
58
+ }
59
+ catch (err) {
60
+ getLogService().error(`Reading messages for order ${number} failed`, apiErrorContext(err));
61
+ throw createError({ statusCode: 502, message: "Order service unavailable" });
62
+ }
63
+ });
@@ -0,0 +1,44 @@
1
+ import { OrderCommentVisibility } from "@revenexx/sdk";
2
+
3
+ /**
4
+ * The buyer says something about this order.
5
+ *
6
+ * Written as customer-visible, because a buyer cannot write the desk an internal
7
+ * note — and marked with who they are, so the two sides of the conversation read
8
+ * apart on the page rather than as one voice.
9
+ */
10
+ export default defineEventHandler(async (event): Promise<{ ok: true }> => {
11
+ const number = getRouterParam(event, "id") ?? "";
12
+ const body = await readBody<{ body?: string }>(event).catch(() => ({} as { body?: string }));
13
+ const message = body?.body?.trim();
14
+ if (!message) {
15
+ throw createError({ statusCode: 400, message: "body required" });
16
+ }
17
+
18
+ const user = await getAuthService(event).me(event);
19
+ if (!user) {
20
+ throw createError({ statusCode: 401, message: "Unauthorized" });
21
+ }
22
+ if (resolveOrderServiceKey(event) !== "api") {
23
+ throw createError({ statusCode: 501, message: "This storefront does not take order messages on demo data" });
24
+ }
25
+
26
+ const order = await getLiveOrderByNumber(number);
27
+ if (!order) {
28
+ throw createError({ statusCode: 404, message: "Order not found" });
29
+ }
30
+
31
+ try {
32
+ await useRevenexxSdk().orders.ordersCommentsCreate({
33
+ id: order.id,
34
+ body: message,
35
+ visibility: OrderCommentVisibility.Customer,
36
+ author: `buyer:${user.name || user.email}`,
37
+ });
38
+ return { ok: true };
39
+ }
40
+ catch (err) {
41
+ getLogService().error(`Writing a message to order ${number} failed`, apiErrorContext(err));
42
+ throw createError({ statusCode: 502, message: "Order service unavailable" });
43
+ }
44
+ });
@@ -1,7 +1,7 @@
1
1
  import type { AccountOrganization, AccountOrganizationFormState } from "../../../app/interfaces/account/organization";
2
2
 
3
3
  export default defineEventHandler(async (event): Promise<AccountOrganization> => {
4
- assertMasterDataEditable("organization");
4
+ await assertMasterDataEditable(event, "organization");
5
5
  const body = await readBody<AccountOrganizationFormState>(event);
6
6
  return getOrganizationService(event).update(event, {
7
7
  name: String(body?.name ?? "").trim(),
@@ -0,0 +1,54 @@
1
+ import type { AccountPaymentsResponse } from "../../../app/interfaces/account/payments";
2
+ import type { LivePayment } from "../../utils/accountPayments";
3
+
4
+ /**
5
+ * The buyer's own payments: what is open, what is late, what is settled.
6
+ *
7
+ * Scoped to their contact, which is how the payments app scopes it — a buyer sees
8
+ * their own and nobody else's. A B2B buyer asks this because their own accounts
9
+ * department is asking them, and until now the answer was a telephone call.
10
+ *
11
+ * Amounts are kept apart by currency. Adding two currencies into one figure is
12
+ * the one thing a page about money must never do.
13
+ */
14
+ export default defineEventHandler(async (event): Promise<AccountPaymentsResponse> => {
15
+ const user = await getAuthService(event).me(event);
16
+ if (!user) {
17
+ throw createError({ statusCode: 401, message: "Unauthorized" });
18
+ }
19
+
20
+ const contactId = user.contactId ?? sessionOrderRefs(event)?.contact_id;
21
+ // No contact means no payments of one's own — an empty ledger, not an error.
22
+ // A demo persona is in exactly that position.
23
+ if (!contactId || resolvePaymentServiceKey(event) !== "api") {
24
+ return { payments: [], outstanding: [] };
25
+ }
26
+
27
+ try {
28
+ const answer = await useRevenexxSdk().call<{ payments?: LivePayment[]; items?: LivePayment[] }>(
29
+ "GET",
30
+ "/v1/payments",
31
+ { query: { contact_id: contactId, order: "created_at.desc", limit: 100 } },
32
+ );
33
+ const payments = (answer.payments ?? answer.items ?? []).map(mapPayment);
34
+
35
+ // Per currency, and only what is still owed.
36
+ const byCurrency = new Map<string, number>();
37
+ for (const payment of payments) {
38
+ if (SETTLED.has(payment.state) || payment.state === "failed") {
39
+ continue;
40
+ }
41
+ byCurrency.set(payment.currency, (byCurrency.get(payment.currency) ?? 0) + payment.amount);
42
+ }
43
+ return {
44
+ payments,
45
+ outstanding: [...byCurrency.entries()]
46
+ .filter(([, amount]) => amount > 0)
47
+ .map(([currency, amount]) => ({ currency, amount })),
48
+ };
49
+ }
50
+ catch (err) {
51
+ getLogService().error("Service error: account/payments", apiErrorContext(err));
52
+ throw createError({ statusCode: 502, message: "Payment service unavailable" });
53
+ }
54
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Say yes to one layer.
3
+ *
4
+ * One layer and not the request: approvals are stacked, so this unlocks the next
5
+ * and the request is approved when the last signature lands. The app owns that
6
+ * chain; the shop only passes the decision along.
7
+ */
8
+ export default defineEventHandler(async (event): Promise<{ ok: true }> => {
9
+ return await decidePendingApproval(event, "approve");
10
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Say no.
3
+ *
4
+ * A decline ends the whole request rather than one layer — the app terminates it
5
+ * and gives any reserved budget back — which is why the reason matters more here
6
+ * than on an approval: the requester has to know whether to ask again differently.
7
+ */
8
+ export default defineEventHandler(async (event): Promise<{ ok: true }> => {
9
+ return await decidePendingApproval(event, "decline");
10
+ });
@@ -0,0 +1,25 @@
1
+ import type { PendingApprovalsResponse } from "../../../../app/interfaces/account/approvals";
2
+
3
+ /**
4
+ * What is waiting on this approver.
5
+ *
6
+ * Empty where procurement is not the live source: the demo's approval limits are a
7
+ * different model with no queue behind them, and a made-up row here would put a
8
+ * decision in front of somebody that nothing would record.
9
+ */
10
+ export default defineEventHandler(async (event): Promise<PendingApprovalsResponse> => {
11
+ const user = await getAuthService(event).me(event);
12
+ if (!user) {
13
+ throw createError({ statusCode: 401, message: "Unauthorized" });
14
+ }
15
+ if (!isProcurementLive(event)) {
16
+ return { approvals: [] };
17
+ }
18
+
19
+ const refs = sessionOrderRefs(event);
20
+ const approvals = await listPendingApprovals(event, {
21
+ ...(user.contactId ?? refs?.contact_id ? { contactId: (user.contactId ?? refs?.contact_id) as string } : {}),
22
+ ...(user.role ? { role: user.role } : {}),
23
+ });
24
+ return { approvals };
25
+ });
@@ -59,7 +59,7 @@ function validateProfileValue(value: string, maxLength: number, field: string):
59
59
  }
60
60
 
61
61
  export default defineEventHandler(async (event): Promise<AccountProfileResponse> => {
62
- assertMasterDataEditable("profile");
62
+ await assertMasterDataEditable(event, "profile");
63
63
  const rawSession = getCookie(event, SESSION_COOKIE_NAME);
64
64
  if (!rawSession) {
65
65
  throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
@@ -1,19 +1,43 @@
1
- /** The buyer says no to a quote — every position still open is declined with it. */
1
+ /**
2
+ * The buyer says no.
3
+ *
4
+ * To the whole offer, which closes every position still open — or to some of the
5
+ * positions, leaving the rest open for a decision later. The platform takes both
6
+ * through the same mechanism, a decision per line, and a merchant who does not
7
+ * allow a basket to be taken apart gets the whole-quote refusal either way.
8
+ */
2
9
  export default defineEventHandler(async (event): Promise<{ ok: true }> => {
3
10
  const id = getRouterParam(event, "id") ?? "";
4
- const body = await readBody<{ reason?: string }>(event).catch(() => ({} as { reason?: string }));
11
+ const body = await readBody<{ reason?: string; lineIds?: string[] }>(event)
12
+ .catch(() => ({} as { reason?: string; lineIds?: string[] }));
5
13
  const actor = await quoteActor(event);
6
14
  if (!actor.user) {
7
15
  throw createError({ statusCode: 401, message: "Unauthorized" });
8
16
  }
17
+ const terms = await quoteTerms(event);
9
18
  const quote = await loadOwnQuote(event, id, actor);
10
- if (!mapQuote(quote, await quoteTerms(event)).canDecline) {
19
+ const view = mapQuote(quote, terms);
20
+ if (!view.canDecline) {
11
21
  throw createError({ statusCode: 422, message: "This quote can no longer be declined" });
12
22
  }
13
23
 
24
+ // Which positions the buyer refused. Only a real subset travels: refusing all
25
+ // of them is a refusal of the offer, and the whole-quote path says that more
26
+ // clearly than a list naming every line.
27
+ const openLineIds = new Set(view.lines.filter(line => line.decision === "open").map(line => line.id));
28
+ const picked = terms.partialAcceptance
29
+ ? (body?.lineIds ?? []).filter(lineId => openLineIds.has(lineId))
30
+ : [];
31
+ const lineIds = picked.length > 0 && picked.length < openLineIds.size ? picked : undefined;
32
+
14
33
  if (resolveQuotesServiceKey(event) === "api") {
15
34
  try {
16
- await liveQuoteDecline(id, body?.reason?.trim() || undefined);
35
+ if (lineIds) {
36
+ await liveQuoteDeclineLines(id, lineIds);
37
+ }
38
+ else {
39
+ await liveQuoteDecline(id, body?.reason?.trim() || undefined);
40
+ }
17
41
  }
18
42
  catch (err) {
19
43
  if (err instanceof RevenexxException && (err.code === 409 || err.code === 422)) {
@@ -31,8 +55,13 @@ export default defineEventHandler(async (event): Promise<{ ok: true }> => {
31
55
  ? q
32
56
  : {
33
57
  ...q,
34
- status: "declined",
35
- items: (q.items ?? []).map(i => (i.decision === "open" ? { ...i, decision: "declined" } : i)),
58
+ // Still open for the rest where only some were refused: a quote that
59
+ // read as declined while something was orderable would lose the buyer
60
+ // the part they still wanted.
61
+ status: lineIds ? "partially_accepted" : "declined",
62
+ items: (q.items ?? []).map(i => (i.decision === "open" && (!lineIds || lineIds.includes(i.id))
63
+ ? { ...i, decision: "declined" }
64
+ : i)),
36
65
  events: [...(q.events ?? []), { kind: "declined", actor: "buyer", body: body?.reason ?? null, visibility: "customer", created_at: now }],
37
66
  }));
38
67
  return { ok: true };
@@ -7,7 +7,7 @@ interface TeamUpdateBody {
7
7
  const ROLES: AccountTeamRole[] = ["buyer", "approver", "admin", "requester"];
8
8
 
9
9
  export default defineEventHandler(async (event): Promise<AccountTeamMember> => {
10
- assertMasterDataEditable("team");
10
+ await assertMasterDataEditable(event, "team");
11
11
  const id = getRouterParam(event, "id");
12
12
  if (!id) {
13
13
  throw createError({ statusCode: 400, statusMessage: "Missing member id" });
@@ -7,7 +7,7 @@ function toRole(value: unknown): AccountTeamRole {
7
7
  }
8
8
 
9
9
  export default defineEventHandler(async (event): Promise<AccountTeamMember> => {
10
- assertMasterDataEditable("team");
10
+ await assertMasterDataEditable(event, "team");
11
11
  const body = await readBody<Partial<AccountTeamMemberFormState>>(event);
12
12
  const email = String(body?.email ?? "").trim();
13
13
  if (!email) {
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Ask for a sign-in link.
3
+ *
4
+ * Answers the same way whether the address is known or not, on purpose: the
5
+ * customers app creates an account for an address it has never seen, so a
6
+ * distinguishing answer here would turn this form into a way of asking who has an
7
+ * account. The secret never reaches this response — only the mailed link carries it.
8
+ */
9
+ export default defineEventHandler(async (event): Promise<{ sent: true }> => {
10
+ const body = await readBody<{ email?: string }>(event).catch(() => ({} as { email?: string }));
11
+ const email = body?.email?.trim();
12
+ if (!email) {
13
+ throw createError({ statusCode: 400, message: "email required" });
14
+ }
15
+
16
+ const { signIn } = await getShopSettings(event);
17
+ if (!signIn.magicLink) {
18
+ throw createError({ statusCode: 404, message: "This shop does not sign buyers in with a mailed link" });
19
+ }
20
+
21
+ // Where the link lands. The app appends userId, secret and expire.
22
+ const url = new URL("/login/link", getRequestURL(event).origin).toString();
23
+ try {
24
+ await useRevenexxSdk().customers.customersAuthMagicLink({ email, url });
25
+ }
26
+ catch (err) {
27
+ getLogService().error("Magic link request failed", apiErrorContext(err));
28
+ // Still "sent": a failure that named the address would leak it, and the
29
+ // buyer's next move is the same either way — look in their mail.
30
+ }
31
+ return { sent: true };
32
+ });
@@ -0,0 +1,30 @@
1
+ import type { AuthLoginResult } from "../../interfaces/auth";
2
+ import type { PasswordlessConfirm } from "../../utils/passwordlessSignIn";
3
+
4
+ /** Turn a mailed link into a session — the same session a password produces. */
5
+ export default defineEventHandler(async (event): Promise<AuthLoginResult> => {
6
+ const body = await readBody<{ userId?: string; secret?: string }>(event)
7
+ .catch(() => ({} as { userId?: string; secret?: string }));
8
+ const userId = body?.userId?.trim();
9
+ const secret = body?.secret?.trim();
10
+ if (!userId || !secret) {
11
+ throw createError({ statusCode: 400, message: "userId and secret required" });
12
+ }
13
+
14
+ try {
15
+ const answer = await useRevenexxSdk().customers.customersAuthMagicLinkConfirm({
16
+ userId,
17
+ secret,
18
+ }) as unknown as PasswordlessConfirm;
19
+ return completeSignIn(event, answer.session, answer.contact, "");
20
+ }
21
+ catch (err) {
22
+ // A used or lapsed link is the ordinary case, not an outage: the buyer
23
+ // asks for another one.
24
+ if (err instanceof RevenexxException && [400, 401, 404].includes(err.code)) {
25
+ throw createError({ statusCode: 401, message: "This sign-in link is no longer valid" });
26
+ }
27
+ getLogService().error("Magic link confirmation failed", apiErrorContext(err));
28
+ throw createError({ statusCode: 502, message: "Sign-in service unavailable" });
29
+ }
30
+ });
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Ask for a sign-in code.
3
+ *
4
+ * The answer carries the platform's user id, which the confirm call needs beside
5
+ * the code the buyer types. That id is not a secret — the code is, and it only
6
+ * ever goes to the address.
7
+ *
8
+ * An address nobody holds gets the same answer with no id, so the form looks
9
+ * identical either way: a code typed without one fails at the confirm step with
10
+ * the same message a wrong code gets. Answering differently would turn this into
11
+ * a way of asking who has an account.
12
+ */
13
+ export default defineEventHandler(async (event): Promise<{ sent: true; userId?: string }> => {
14
+ const body = await readBody<{ email?: string }>(event).catch(() => ({} as { email?: string }));
15
+ const email = body?.email?.trim();
16
+ if (!email) {
17
+ throw createError({ statusCode: 400, message: "email required" });
18
+ }
19
+
20
+ const { signIn } = await getShopSettings(event);
21
+ if (!signIn.emailOtp) {
22
+ throw createError({ statusCode: 404, message: "This shop does not sign buyers in with a mailed code" });
23
+ }
24
+
25
+ try {
26
+ const answer = await useRevenexxSdk().customers.customersAuthOtp({ email }) as { userId?: string };
27
+ return { sent: true, ...(answer?.userId ? { userId: answer.userId } : {}) };
28
+ }
29
+ catch (err) {
30
+ getLogService().error("Sign-in code request failed", apiErrorContext(err));
31
+ return { sent: true };
32
+ }
33
+ });
@@ -0,0 +1,28 @@
1
+ import type { AuthLoginResult } from "../../interfaces/auth";
2
+ import type { PasswordlessConfirm } from "../../utils/passwordlessSignIn";
3
+
4
+ /** Turn a mailed code into a session. */
5
+ export default defineEventHandler(async (event): Promise<AuthLoginResult> => {
6
+ const body = await readBody<{ userId?: string; secret?: string }>(event)
7
+ .catch(() => ({} as { userId?: string; secret?: string }));
8
+ const userId = body?.userId?.trim();
9
+ const secret = body?.secret?.trim();
10
+ if (!userId || !secret) {
11
+ throw createError({ statusCode: 400, message: "userId and secret required" });
12
+ }
13
+
14
+ try {
15
+ const answer = await useRevenexxSdk().customers.customersAuthOtpConfirm({
16
+ userId,
17
+ secret,
18
+ }) as unknown as PasswordlessConfirm;
19
+ return completeSignIn(event, answer.session, answer.contact, "");
20
+ }
21
+ catch (err) {
22
+ if (err instanceof RevenexxException && [400, 401, 404].includes(err.code)) {
23
+ throw createError({ statusCode: 401, message: "This code is wrong or has expired" });
24
+ }
25
+ getLogService().error("Sign-in code confirmation failed", apiErrorContext(err));
26
+ throw createError({ statusCode: 502, message: "Sign-in service unavailable" });
27
+ }
28
+ });
@@ -3,10 +3,13 @@ export default defineEventHandler(async (event) => {
3
3
  // receive the guest checkout options when guest ordering is enabled.
4
4
  const user = await getAuthService(event).me(event);
5
5
 
6
+ // A visitor with no account reaches the checkout only where the merchant takes
7
+ // such an order. The orders app holds that answer and refuses the placement
8
+ // itself, so this is the matching UX rather than the rule — but it has to
9
+ // agree with it, or a guest fills a whole checkout to be turned away at the end.
6
10
  if (!user) {
7
- const context = await getB2BContextService(event).getContext(null);
8
- const guest = context.settings.checkout.guestOrdering;
9
- if (!guest.b2b && !guest.b2c) {
11
+ const { orders } = await getShopSettings(event);
12
+ if (orders.guestOrdering === "none") {
10
13
  throw createError({ statusCode: 401, message: "Unauthorized" });
11
14
  }
12
15
  }
@@ -1,8 +1,12 @@
1
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.
2
+ * Records a form submission. Resolves the live form by slug, drops anything the
3
+ * form never asked for, then hands it to the active forms service — live, that
4
+ * writes a row the platform emits `form.submitted` for, which is what an
5
+ * Integration Studio workflow or a notification email listens to.
6
+ *
7
+ * `rejected` is not an error: it is the tenant who configured `spam_handling:
8
+ * reject` and a submission that filled the decoy field in. Nothing was stored,
9
+ * on purpose, so the visitor is told that rather than thanked.
6
10
  */
7
11
  export default defineEventHandler(async (event) => {
8
12
  const slug = getRouterParam(event, "slug");
@@ -17,24 +21,31 @@ export default defineEventHandler(async (event) => {
17
21
  }
18
22
 
19
23
  try {
20
- const form = await resolveLiveForm(slug);
24
+ const [form, policy] = await Promise.all([
25
+ getFormsService(event).resolve(slug),
26
+ resolveFormSpamPolicy(event),
27
+ ]);
21
28
  if (!form) {
22
29
  throw createError({ statusCode: 404, message: "Form not found" });
23
30
  }
24
31
 
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
- });
32
+ const definition = Array.isArray(form.definition) ? form.definition : [];
33
+ const source = body?.source ?? null;
34
+ const clean = sanitizeSubmission(definition, data, policy.honeypotField);
33
35
 
34
- // Run the operator-configured post-submit actions (webhook / entity write).
35
- await runFormActions(form, data, body?.source ?? null);
36
+ const result = await getFormsService(event).submit(form, clean, source, policy);
37
+ if (result.outcome === "rejected") {
38
+ return { ok: false, outcome: result.outcome, success_message: null };
39
+ }
40
+
41
+ // The operator-configured post-submit actions (webhook / entity write).
42
+ // A submission the tenant keeps as spam is still a submission, but it is
43
+ // not one to fire an integration for.
44
+ if (result.outcome === "stored") {
45
+ await runFormActions(form, clean, source);
46
+ }
36
47
 
37
- return { ok: true, success_message: form.settings?.success_message ?? null };
48
+ return { ok: true, outcome: result.outcome, success_message: result.successMessage ?? null };
38
49
  }
39
50
  catch (err) {
40
51
  if (err !== null && typeof err === "object" && "statusCode" in err) {
@@ -13,7 +13,10 @@ export default defineEventHandler(async (event): Promise<FormPublic> => {
13
13
  const locale = resolveLocale(event);
14
14
 
15
15
  try {
16
- const form = await resolveLiveForm(slug);
16
+ const [form, policy] = await Promise.all([
17
+ getFormsService(event).resolve(slug),
18
+ resolveFormSpamPolicy(event),
19
+ ]);
17
20
  if (!form) {
18
21
  throw createError({ statusCode: 404, message: "Form not found" });
19
22
  }
@@ -25,6 +28,11 @@ export default defineEventHandler(async (event): Promise<FormPublic> => {
25
28
  settings: form.settings
26
29
  ? { submit_label: form.settings.submit_label, success_message: form.settings.success_message }
27
30
  : null,
31
+ // Never a name the form itself declares: a decoy that collides with a
32
+ // real field would drop the visitor's own answer.
33
+ honeypot: policy.honeypotField && !namedFields(definition).has(policy.honeypotField)
34
+ ? policy.honeypotField
35
+ : null,
28
36
  };
29
37
  }
30
38
  catch (err) {
@@ -0,0 +1,23 @@
1
+ import type { FormSummary } from "../../interfaces/forms";
2
+
3
+ /**
4
+ * The live forms, by slug and name.
5
+ *
6
+ * A surface that OFFERS a form — the price-request link on a product page, a
7
+ * return request beside a delivered order — has to know whether the merchant
8
+ * published one, or it links to a page that renders nothing. One cached read
9
+ * answers that for every such surface instead of a probe per link.
10
+ *
11
+ * Never more than the catalogue: no definition, no settings, no draft.
12
+ */
13
+ export default defineEventHandler(async (event): Promise<{ forms: FormSummary[] }> => {
14
+ try {
15
+ return { forms: await getFormsService(event).list() };
16
+ }
17
+ catch (err) {
18
+ // A storefront must not lose its product page because the forms app is
19
+ // unreachable: an empty catalogue hides the optional link and nothing else.
20
+ getLogService().error("Service error: forms/list", apiErrorContext(err));
21
+ return { forms: [] };
22
+ }
23
+ });
@@ -367,6 +367,14 @@ export default defineEventHandler(async (event) => {
367
367
  const submission = {
368
368
  ...(contactId ? { contactId } : {}),
369
369
  ...(organizationId ? { organizationId } : {}),
370
+ // Which kind of shopper this is, stated only where nobody is
371
+ // signed in — that is when it decides anything. The orders app
372
+ // cannot see it: a guest carries no contact and no organisation,
373
+ // so a company shopper and a private one look identical there.
374
+ // Saying it is also what makes the placement a shopper's rather
375
+ // than a system's, which is the difference between being held to
376
+ // the merchant's guest rule and being an ERP nobody gates.
377
+ ...(contactId ? {} : { customer_type: customerType === "private" ? "b2c" : "b2b" }),
370
378
  ...(cartId ? { cartId } : {}),
371
379
  ...(discounts.length ? { discounts } : {}),
372
380
  currency: selectedCurrency ?? calculation.currency,
@@ -0,0 +1,37 @@
1
+ import type { AvailableOffersResponse } from "../../../app/interfaces/offers";
2
+
3
+ /**
4
+ * What this buyer could still get, for the cart they are holding.
5
+ *
6
+ * The shop has always been able to say what a cart IS owed. This says what it
7
+ * could be owed — each offer with how far away it is — which is the only version
8
+ * of the question that can change what a buyer does next.
9
+ *
10
+ * Answers an empty list rather than an error wherever it cannot ask: an offer
11
+ * nobody sees costs a larger order, an error costs the order.
12
+ */
13
+ export default defineEventHandler(async (event): Promise<AvailableOffersResponse> => {
14
+ const body = await readBody<{ subtotal?: number; itemCount?: number }>(event)
15
+ .catch(() => ({} as { subtotal?: number; itemCount?: number }));
16
+
17
+ if (resolvePromotionsServiceKey(event) !== "api") {
18
+ // The demo has no promotions app behind it, and a made-up offer would be
19
+ // the shop inventing a term of sale — exactly what it stopped doing.
20
+ return { offers: [], total: 0 };
21
+ }
22
+
23
+ const user = await getAuthService(event).me(event);
24
+ const refs = sessionOrderRefs(event);
25
+ const { cart } = await getShopSettings(event);
26
+
27
+ const { offers, total } = await liveAvailableOffers(event, {
28
+ currency: resolveSelectedCurrency(event) ?? cart.currency,
29
+ subtotal: Math.max(0, Number(body?.subtotal) || 0),
30
+ ...(typeof body?.itemCount === "number" ? { itemCount: body.itemCount } : {}),
31
+ ...(user?.contactId ?? refs?.contact_id ? { contactId: (user?.contactId ?? refs?.contact_id) as string } : {}),
32
+ ...(user?.organizationId ?? refs?.organization_id
33
+ ? { organizationId: (user?.organizationId ?? refs?.organization_id) as string }
34
+ : {}),
35
+ });
36
+ return { offers, total };
37
+ });
@@ -18,10 +18,6 @@
18
18
  "enabled": true
19
19
  },
20
20
  "checkout": {
21
- "guestOrdering": {
22
- "b2b": true,
23
- "b2c": true
24
- },
25
21
  "orderNumberRequired": false
26
22
  }
27
23
  },
@@ -45,6 +45,10 @@
45
45
  "inventories": {
46
46
  "backorder_policy": "deny"
47
47
  },
48
+ "forms": {
49
+ "honeypot_field": "contact_reference",
50
+ "spam_handling": "flag"
51
+ },
48
52
  "customers": {
49
53
  "b2b_registration_enabled": true,
50
54
  "b2c_registration_enabled": true,