@revenexx/cover 0.19.0 → 0.21.0

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 (95) hide show
  1. package/app/api/marketing.ts +24 -0
  2. package/app/app.config.ts +22 -0
  3. package/app/components/account/approvals/AccountPendingApprovals.vue +54 -13
  4. package/app/components/account/approvals/AccountPendingOrderDetail.vue +156 -0
  5. package/app/components/account/loyalty/AccountLoyalty.vue +205 -0
  6. package/app/components/account/orders/AccountOrderContents.vue +142 -0
  7. package/app/components/account/orders/AccountOrderDetail.vue +16 -178
  8. package/app/components/account/orders/AccountOrderHead.vue +79 -0
  9. package/app/components/account/orders/AccountOrderPay.vue +13 -3
  10. package/app/components/account/orders/AccountOrdersTable.vue +2 -0
  11. package/app/components/cart/position/CartPosition.vue +6 -6
  12. package/app/components/cart/view/CartSummaryPanel.vue +4 -0
  13. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +20 -8
  14. package/app/components/checkout/onepage/CheckoutSummarySection.vue +4 -0
  15. package/app/components/checkout/return/CheckoutPaymentReturn.vue +209 -0
  16. package/app/components/loyalty/hint/LoyaltyPerkHint.vue +28 -0
  17. package/app/components/newsletter/confirm/NewsletterConfirmation.vue +54 -0
  18. package/app/components/newsletter/preferences/NewsletterPreferenceCentre.vue +183 -0
  19. package/app/components/newsletter/state/NewsletterLinkRefusal.vue +45 -0
  20. package/app/components/review/form/ReviewForm.vue +211 -0
  21. package/app/composables/useAccountDashboard.ts +1 -0
  22. package/app/composables/useCampaignAttribution.ts +120 -0
  23. package/app/composables/useCheckoutOnePage.ts +80 -7
  24. package/app/composables/useLoyaltyAccount.ts +79 -0
  25. package/app/composables/useMarketingConsent.ts +49 -0
  26. package/app/composables/usePendingApprovals.ts +11 -3
  27. package/app/composables/usePspCheckout.ts +130 -29
  28. package/app/config/colorRamp.ts +55 -0
  29. package/app/config/navigation.ts +1 -1
  30. package/app/config/quickActions.ts +1 -0
  31. package/app/interfaces/account/approvals.ts +34 -1
  32. package/app/interfaces/account/order-list.ts +8 -1
  33. package/app/interfaces/cart-calculation.ts +7 -1
  34. package/app/interfaces/cart-item.ts +12 -0
  35. package/app/interfaces/payment.ts +22 -0
  36. package/app/pages/account/points.vue +26 -0
  37. package/app/pages/checkout/payment-return.vue +17 -0
  38. package/app/pages/newsletter/confirm/[token].vue +23 -0
  39. package/app/pages/newsletter/preferences/[token].vue +24 -0
  40. package/app/pages/review/[token].vue +23 -0
  41. package/app/payments/psp/novalnet.ts +255 -0
  42. package/app/payments/psp/registry.ts +7 -3
  43. package/app/payments/psp/rules.ts +99 -0
  44. package/app/payments/psp/stripe.ts +6 -2
  45. package/app/payments/psp/types.ts +72 -6
  46. package/app/plugins/campaign-attribution.client.ts +47 -0
  47. package/app/shared/campaignAttribution.ts +281 -0
  48. package/app/shared/personalisation.ts +107 -0
  49. package/app/shared/pspReturn.ts +62 -0
  50. package/i18n/locales/de/account.json +20 -5
  51. package/i18n/locales/de/cart.json +4 -2
  52. package/i18n/locales/de/checkout.json +32 -0
  53. package/i18n/locales/de/editor.json +10 -0
  54. package/i18n/locales/de/marketing.json +71 -0
  55. package/i18n/locales/en/account.json +20 -5
  56. package/i18n/locales/en/cart.json +4 -2
  57. package/i18n/locales/en/checkout.json +32 -0
  58. package/i18n/locales/en/editor.json +10 -0
  59. package/i18n/locales/en/marketing.json +71 -0
  60. package/package.json +3 -2
  61. package/server/api/account/orders/[id]/pay.post.ts +47 -7
  62. package/server/api/account/pending-approvals/index.get.ts +16 -12
  63. package/server/api/account/pending-approvals/orders/[number]/approve.post.ts +6 -0
  64. package/server/api/account/pending-approvals/orders/[number]/reject.post.ts +6 -0
  65. package/server/api/account/pending-approvals/orders/[number].get.ts +15 -0
  66. package/server/api/campaigns/touches.post.ts +42 -0
  67. package/server/api/cart/attribution.put.ts +31 -0
  68. package/server/api/checkout/payment-return.post.ts +30 -0
  69. package/server/api/loyalty/account.get.ts +27 -0
  70. package/server/api/newsletter/confirm/[token].post.ts +21 -0
  71. package/server/api/newsletter/preferences/[token].get.ts +14 -0
  72. package/server/api/newsletter/preferences/[token].post.ts +36 -0
  73. package/server/api/orders/index.post.ts +47 -12
  74. package/server/api/payment/methods.post.ts +19 -9
  75. package/server/api/payment/psp-config.get.ts +5 -4
  76. package/server/api/reviews/requests/[token].get.ts +14 -0
  77. package/server/api/reviews/submit/[token].post.ts +31 -0
  78. package/server/interfaces/cart.ts +6 -0
  79. package/server/interfaces/marketing.ts +150 -0
  80. package/server/services/ApiCartService.ts +22 -0
  81. package/server/services/ApiMarketingService.ts +292 -0
  82. package/server/services/ApiProductService.ts +6 -2
  83. package/server/services/MockCartCalculationService.ts +29 -0
  84. package/server/services/MockMarketingService.ts +178 -0
  85. package/server/utils/cartItemHints.ts +29 -0
  86. package/server/utils/checkoutSession.ts +16 -0
  87. package/server/utils/liveCatalog.ts +244 -31
  88. package/server/utils/liveOrders.ts +33 -0
  89. package/server/utils/marketingService.ts +63 -0
  90. package/server/utils/orderAttribution.ts +65 -0
  91. package/server/utils/orderPayment.ts +79 -0
  92. package/server/utils/pendingApprovals.ts +157 -2
  93. package/server/utils/personalisationViewer.ts +28 -0
  94. package/server/utils/pspConfig.ts +125 -13
  95. package/server/utils/pspReturn.ts +267 -0
@@ -71,8 +71,18 @@
71
71
  "failed": "The decision could not be recorded",
72
72
  "empty": {
73
73
  "title": "Nothing is waiting on you",
74
- "description": "A request needing your approval appears here."
75
- }
74
+ "description": "A request or order needing your approval appears here."
75
+ },
76
+ "order": "Order {number}",
77
+ "review": "Review",
78
+ "declineOrderTitle": "Reject the order",
79
+ "declineOrderIntro": "The order is cancelled. The requester sees your reason.",
80
+ "reasonRequired": "Please give a reason."
81
+ },
82
+ "order": {
83
+ "title": "Order {number}",
84
+ "requestedBy": "Requested by {name}",
85
+ "notPending": "This order is no longer waiting for a decision."
76
86
  }
77
87
  },
78
88
  "payments": {
@@ -123,7 +133,11 @@
123
133
  "approval-pending": "Approval pending",
124
134
  "shipped": "Shipped",
125
135
  "delivered": "Delivered",
126
- "cancelled": "Cancelled"
136
+ "cancelled": "Cancelled",
137
+ "rejected": "Rejected"
138
+ },
139
+ "rejected": {
140
+ "title": "This order was not approved"
127
141
  },
128
142
  "payment": {
129
143
  "open": "Payment open",
@@ -270,7 +284,7 @@
270
284
  "orderTemplates": "Order templates",
271
285
  "projects": "Projects",
272
286
  "devices": "Devices",
273
- "points": "Points",
287
+ "points": "Loyalty programme",
274
288
  "configurations": "Configurations",
275
289
  "inquiries": "Inquiries",
276
290
  "quotes": "Quotes",
@@ -339,7 +353,8 @@
339
353
  "organization": { "description": "Manage your organization" },
340
354
  "team": { "description": "Access and roles" },
341
355
  "preferences": { "description": "Defaults for your orders" },
342
- "addresses": { "description": "Delivery and billing addresses" }
356
+ "addresses": { "description": "Delivery and billing addresses" },
357
+ "points": { "description": "Tier, benefits and bonus" }
343
358
  },
344
359
  "comingSoon": {
345
360
  "title": "In development",
@@ -276,13 +276,15 @@
276
276
  "place": "Only {available} available. The rest follows later.",
277
277
  "drop": "Only {available} available. This position will be left out of the order.",
278
278
  "refuse": "Only {available} available. The cart cannot be ordered while this position is in it."
279
- }
279
+ },
280
+ "unitChanged": "{sku} is not available in {sent}. Switched to {unit}."
280
281
  },
281
282
  "messages": {
282
283
  "costCentersUnassigned": "You have no cost centers assigned — please contact your organization administrator.",
283
284
  "positionsNotOrderable": "{count} position(s) cannot be ordered right now. Adjust the quantity or remove them.",
284
285
  "positionsWillBeDropped": "{count} position(s) cannot be ordered and will be left out of the order.",
285
- "costCenterRequired": "Please select a cost center for every position."
286
+ "costCenterRequired": "Please select a cost center for every position.",
287
+ "unitsChanged": "The unit of some positions was switched. Please check their quantities."
286
288
  },
287
289
  "incentives": {
288
290
  "freeShipping": "free shipping",
@@ -1,4 +1,34 @@
1
1
  {
2
+ "paymentReturn": {
3
+ "title": "Payment",
4
+ "checking": "Checking your payment …",
5
+ "toShop": "Back to the shop",
6
+ "toOrder": "View order",
7
+ "failed": {
8
+ "title": "The payment did not go through",
9
+ "text": "Your order {id} has not been paid. Nothing was charged.",
10
+ "payAgain": "Pay again",
11
+ "guestHint": "Please contact us with your order number if you would like to pay for the order."
12
+ },
13
+ "retry": {
14
+ "title": "Payment not completed",
15
+ "text": "You did not complete the payment for your order {id}. Nothing was charged. You can go back to the payment provider and pay now.",
16
+ "again": "Go to payment again"
17
+ },
18
+ "pending": {
19
+ "title": "Your payment is being processed",
20
+ "text": "The payment provider has not completed the payment for your order {id} yet. You will receive a confirmation once it has arrived.",
21
+ "checkAgain": "Check again"
22
+ },
23
+ "unverified": {
24
+ "title": "Your payment could not be verified",
25
+ "text": "We could not verify the payment for your order {id}. The order is not marked as paid. Please contact us with your order number."
26
+ },
27
+ "error": {
28
+ "title": "We could not check your payment",
29
+ "text": "Please try again later or contact us. A successful payment is not lost because of this."
30
+ }
31
+ },
2
32
  "confirmation": {
3
33
  "order": {
4
34
  "title": "Order confirmed!",
@@ -131,6 +161,8 @@
131
161
  "poNumberPlaceholder": "Enter PO number...",
132
162
  "costCenter": "Cost Center",
133
163
  "cardDetails": "Card details",
164
+ "cardOnProviderPage": "After you place the order, you enter your card details on the payment provider's page.",
165
+ "cardFieldUnavailable": "The card field is not available right now. Please try again or choose another payment method.",
134
166
  "change": "Change",
135
167
  "noMethod": "No payment method selected",
136
168
  "confirm": "Confirm",
@@ -124,6 +124,16 @@
124
124
  },
125
125
  "design": {
126
126
  "title": "Site design",
127
+ "logo": "Logo",
128
+ "logoHint": "URL or media storage path. Shown in the header, footer and checkout; empty keeps the theme logo.",
129
+ "favicon": "Favicon",
130
+ "faviconHint": "Square image, at least 180 × 180 px. The icons for browser tabs and home screens are rendered from it; empty keeps the theme favicon.",
131
+ "upload": "Upload image",
132
+ "uploading": "Uploading …",
133
+ "uploadFailed": "Could not upload the image.",
134
+ "uploadUnavailable": "Uploads are not available here: no media storage is configured. Enter a URL instead.",
135
+ "logoRejected": "Saved, but not used: this is neither a URL nor a storage path. The shop keeps showing the previous logo.",
136
+ "faviconRejected": "Saved, but not used: this is neither a URL nor a storage path. The shop keeps the theme favicon.",
127
137
  "brand": "Brand colour",
128
138
  "neutral": "Neutral colour",
129
139
  "radius": "Corner radius",
@@ -0,0 +1,71 @@
1
+ {
2
+ "marketing": {
3
+ "link": {
4
+ "unknownTitle": "This link does not work",
5
+ "unknownText": "We do not know this link. Check that it was copied in full, or use the link from the latest email.",
6
+ "expiredTitle": "This link has expired",
7
+ "errorTitle": "That did not work",
8
+ "errorText": "Please try again in a few minutes.",
9
+ "toShop": "Back to the shop"
10
+ },
11
+ "confirm": {
12
+ "title": "Confirm your sign-up",
13
+ "working": "Confirming your sign-up …",
14
+ "doneTitle": "Sign-up confirmed",
15
+ "doneText": "Thank you. From now on you will receive our emails. You can unsubscribe at any time with the link in every email.",
16
+ "alreadyText": "This sign-up was already confirmed. There is nothing else to do.",
17
+ "expiredText": "Confirmation links are only valid for a few days. Please sign up again and we will send you a new one."
18
+ },
19
+ "preferences": {
20
+ "title": "Email settings",
21
+ "intro": "Choose which emails we send to {address}.",
22
+ "save": "Save settings",
23
+ "saved": "Your settings are saved.",
24
+ "requested": "We will send you an email for {types}. The sign-up is active once you confirm the link in it.",
25
+ "unsubscribeAll": "Unsubscribe from all emails",
26
+ "unsubscribedAll": "You are unsubscribed from all emails. You will only receive messages about your orders.",
27
+ "empty": "There are no emails to choose for this address.",
28
+ "expiredText": "Use the link from the latest email you received from us."
29
+ },
30
+ "review": {
31
+ "title": "Your review",
32
+ "intro": "How happy are you with the articles from order {order}? Rate as many as you like.",
33
+ "introNoOrder": "How happy are you with your articles? Rate as many as you like.",
34
+ "rating": "Rating for {name}",
35
+ "star": "{count} of 5 stars",
36
+ "titleField": "Headline (optional)",
37
+ "bodyField": "Your experience (optional)",
38
+ "reviewed": "Already reviewed",
39
+ "submit": "Send reviews",
40
+ "nothingRated": "Choose a star rating for at least one article.",
41
+ "doneTitle": "Thank you for your review",
42
+ "doneText": "We check every review before it appears in the shop.",
43
+ "partlyRejected": "We could not accept {count} review(s), for example because the article was already reviewed.",
44
+ "allDone": "You have reviewed every article of this order. Thank you!",
45
+ "expiredText": "Review links are only valid for a while. You can still find the article on its product page."
46
+ },
47
+ "loyalty": {
48
+ "title": "Loyalty programme",
49
+ "description": "Your tier, your benefits and how far you are this year.",
50
+ "none": "You are not part of a loyalty programme.",
51
+ "error": "Your loyalty programme cannot be loaded right now.",
52
+ "tier": "Your tier",
53
+ "perks": "Your benefits",
54
+ "points": "Points balance",
55
+ "pointsValue": "{points} points",
56
+ "progressTitle": "Bonus {period}",
57
+ "turnoverYtd": "Turnover so far",
58
+ "projected": "Projection to year end",
59
+ "bonusNow": "Bonus as of today",
60
+ "expectedBonus": "Expected bonus",
61
+ "nextTier": "{gap} to go until {tier} ({percent} % bonus).",
62
+ "topTier": "You have reached the highest tier.",
63
+ "stage": "{tier}: from {threshold}, {percent} % bonus",
64
+ "reached": "reached",
65
+ "current": "current",
66
+ "rules": "The bonus applies to the whole year's turnover at the tier reached, not stepwise. It is paid out after the fiscal year closes.",
67
+ "rulesOverdue": "All due invoices must be paid.",
68
+ "perkHint": "Your benefit as {tier}:"
69
+ }
70
+ }
71
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Cover — 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",
@@ -26,6 +26,7 @@
26
26
  "./composables/*": "./app/composables/*.ts",
27
27
  "./config/*": "./app/config/*.ts",
28
28
  "./interfaces/*": "./app/interfaces/*.ts",
29
+ "./payments/*": "./app/payments/*.ts",
29
30
  "./server/interfaces/*": "./server/interfaces/*.ts",
30
31
  "./server/services/*": "./server/services/*.ts",
31
32
  "./server/utils/*": "./server/utils/*.ts",
@@ -43,7 +44,7 @@
43
44
  "@internationalized/date": "^3.12.0",
44
45
  "@nuxt/scripts": "^1.3.0",
45
46
  "@revenexx/consent-manager-nuxt": "^0.1.0",
46
- "@revenexx/sdk": "^0.2.0",
47
+ "@revenexx/sdk": "^0.5.0",
47
48
  "@revenexx/storage-model-viewer": "^0.3.0",
48
49
  "@revenexx/tag-manager-nuxt": "^0.1.0",
49
50
  "@vueuse/core": "^14.3.0",
@@ -1,10 +1,15 @@
1
- import { orderAwaitsPayment, orderPaymentRequest, recordOrderPaymentStatus } from "../../../../utils/orderPayment";
1
+ import {
2
+ orderAwaitsPayment,
3
+ orderPaymentRequest,
4
+ paymentCustomerOf,
5
+ recordOrderPaymentStatus,
6
+ sanitizePaymentInstrument,
7
+ } from "../../../../utils/orderPayment";
8
+ import { pspReturnUrl, rememberPspReturn } from "../../../../utils/pspReturn";
2
9
 
3
10
  interface PayOrderPayload {
4
- /** PSP single-use token from the order page's card field. */
5
- paymentInstrument?: { token?: string };
6
- /** Where the PSP returns the buyer after a redirect/3DS step-up. */
7
- returnUrl?: string;
11
+ /** From the order page's card field: a provider instrument, or the legacy single-use token. */
12
+ paymentInstrument?: { token?: string; instrument?: Record<string, unknown> };
8
13
  /** One per attempt, so a double click pays once. */
9
14
  idempotencyKey?: string;
10
15
  }
@@ -69,8 +74,22 @@ export default defineEventHandler(async (event) => {
69
74
  orderId: order.id,
70
75
  contactId: principalContactId(event),
71
76
  idempotencyKey,
72
- token: body?.paymentInstrument?.token,
73
- returnUrl: body?.returnUrl,
77
+ token: typeof body?.paymentInstrument?.token === "string" && body.paymentInstrument.token
78
+ ? body.paymentInstrument.token
79
+ : undefined,
80
+ instrument: sanitizePaymentInstrument(body?.paymentInstrument?.instrument),
81
+ // The PSP brings the buyer back to the return page, which confirms
82
+ // the payment — built here, on this host, never taken from the
83
+ // browser (FE-5).
84
+ returnUrl: pspReturnUrl(event, order.number),
85
+ customer: paymentCustomerOf({
86
+ email: user.email,
87
+ contactName: user.name,
88
+ ip: getRequestIP(event, { xForwardedFor: true }) ?? null,
89
+ billing: billingForPayment(order.billing_address),
90
+ countryCode: paymentCountry(order) ?? null,
91
+ }),
92
+ language: resolveLocale(event),
74
93
  }),
75
94
  });
76
95
  }
@@ -94,7 +113,28 @@ export default defineEventHandler(async (event) => {
94
113
  // The PSP needs the buyer (3DS / redirect PSPs): hand the redirect back, the
95
114
  // payment settles on their return.
96
115
  if (created.status === "requires_action" && created.next_action?.url) {
116
+ rememberPspReturn(event, { paymentId: created.id, orderRef: order.number, orderUuid: order.id });
97
117
  return { status: "requires-action" as const, requiresAction: true, redirectUrl: created.next_action.url, paymentId: created.id };
98
118
  }
99
119
  return { status: created.status, requiresAction: false, paymentId: created.id };
100
120
  });
121
+
122
+ /** An orders-app address as the payment's billing: street line, town, postal code. */
123
+ function billingForPayment(address: Record<string, unknown> | null): { street?: string; city?: string; postalCode?: string } | null {
124
+ if (!address) {
125
+ return null;
126
+ }
127
+ const text = (...keys: string[]): string => {
128
+ for (const key of keys) {
129
+ const value = address[key];
130
+ if (typeof value === "string" && value.trim()) {
131
+ return value.trim();
132
+ }
133
+ }
134
+ return "";
135
+ };
136
+ const street = text("address_line1")
137
+ || [text("street_name"), text("house_number"), text("house_number_addition")].filter(Boolean).join(" ")
138
+ || text("street");
139
+ return { street, city: text("locality", "city"), postalCode: text("postal_code", "zip", "postalCode") };
140
+ }
@@ -1,10 +1,12 @@
1
1
  import type { PendingApprovalsResponse } from "../../../../app/interfaces/account/approvals";
2
2
 
3
3
  /**
4
- * What is waiting on this approver.
4
+ * What is waiting on this approver: the procurement layers waiting on them, and
5
+ * the orders of their company waiting in the orders app (RAD-229) — one inbox,
6
+ * because the approver signs in with one question.
5
7
  *
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
+ * Each half is empty where its source is not live: the demo's approval limits are
9
+ * a different model with no queue behind them, and a made-up row here would put a
8
10
  * decision in front of somebody that nothing would record.
9
11
  */
10
12
  export default defineEventHandler(async (event): Promise<PendingApprovalsResponse> => {
@@ -12,15 +14,17 @@ export default defineEventHandler(async (event): Promise<PendingApprovalsRespons
12
14
  if (!user) {
13
15
  throw createError({ statusCode: 401, message: "Unauthorized" });
14
16
  }
15
- if (!isProcurementLive(event)) {
16
- return { approvals: [] };
17
- }
18
17
 
19
18
  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
- ...(user.organizationId ? { organizationId: user.organizationId } : {}),
24
- });
25
- return { approvals };
19
+ const [requests, orders] = await Promise.all([
20
+ isProcurementLive(event)
21
+ ? listPendingApprovals(event, {
22
+ ...(user.contactId ?? refs?.contact_id ? { contactId: (user.contactId ?? refs?.contact_id) as string } : {}),
23
+ ...(user.role ? { role: user.role } : {}),
24
+ ...(user.organizationId ? { organizationId: user.organizationId } : {}),
25
+ })
26
+ : [],
27
+ listPendingOrderApprovals(event, user),
28
+ ]);
29
+ return { approvals: [...requests, ...orders] };
26
30
  });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Say yes to a colleague's order (RAD-229): it is placed now, and announced as placed.
3
+ */
4
+ export default defineEventHandler(async (event): Promise<{ ok: true }> => {
5
+ return await decidePendingOrder(event, "approve");
6
+ });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Say no to a colleague's order (RAD-229): it is cancelled, with the reason the requester reads.
3
+ */
4
+ export default defineEventHandler(async (event): Promise<{ ok: true }> => {
5
+ return await decidePendingOrder(event, "reject");
6
+ });
@@ -0,0 +1,15 @@
1
+ import type { PendingOrderDetail } from "../../../../../app/interfaces/account/approvals";
2
+
3
+ /** A colleague's order, as the person who may approve it sees it (RAD-229). */
4
+ export default defineEventHandler(async (event): Promise<PendingOrderDetail> => {
5
+ try {
6
+ return await readPendingOrder(event);
7
+ }
8
+ catch (err) {
9
+ if (isError(err)) {
10
+ throw err;
11
+ }
12
+ getLogService().error("Pending order detail failed", apiErrorContext(err));
13
+ throw createError({ statusCode: 502, message: "Order service unavailable" });
14
+ }
15
+ });
@@ -0,0 +1,42 @@
1
+ import type { CampaignTouch } from "../../interfaces/marketing";
2
+
3
+ /**
4
+ * Onsite impressions and clicks of a campaign's pop-up (RAD-293), counted in
5
+ * the campaigns app. The browser only sends them once the visitor allowed the
6
+ * statistics purpose; the contact and the market are added here, from the
7
+ * session, never taken from the browser.
8
+ */
9
+ export default defineEventHandler(async (event) => {
10
+ const body = await readBody<{ touches?: unknown }>(event).catch(() => null);
11
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ const touches: CampaignTouch[] = Array.isArray(body?.touches)
13
+ ? (body.touches as Record<string, unknown>[])
14
+ .filter(touch => touch && typeof touch.campaign_id === "string" && UUID.test(touch.campaign_id)
15
+ && (touch.kind === "onsite_impression" || touch.kind === "onsite_click"))
16
+ .slice(0, 50)
17
+ .map(touch => ({
18
+ campaign_id: String(touch.campaign_id),
19
+ kind: touch.kind as CampaignTouch["kind"],
20
+ ...(typeof touch.ref === "string" ? { ref: touch.ref.slice(0, 128) } : {}),
21
+ ...(typeof touch.key === "string" ? { key: touch.key.slice(0, 200) } : {}),
22
+ }))
23
+ : [];
24
+ if (!touches.length) {
25
+ return { recorded: 0 };
26
+ }
27
+ const contactId = sessionOrderRefs(event).contact_id;
28
+ const market = resolveSelectedMarket(event);
29
+ const sessionKey = getOrCreateCartSessionId(event);
30
+ try {
31
+ await getMarketingService(event).recordTouches(event, touches.map(touch => ({
32
+ ...touch,
33
+ ...(contactId ? { contact_id: contactId } : { session_key: sessionKey }),
34
+ ...(market ? { market } : {}),
35
+ })));
36
+ }
37
+ catch (err) {
38
+ // A count that did not arrive is not the visitor's problem.
39
+ getLogService().warn("campaign touches failed", apiErrorContext(err));
40
+ }
41
+ return { recorded: touches.length };
42
+ });
@@ -0,0 +1,31 @@
1
+ import { sanitizeAttribution } from "../../../app/shared/campaignAttribution";
2
+
3
+ /**
4
+ * Where the visit came from, onto the current cart (RAD-293): the carts app
5
+ * keeps it until the cart is ordered, and an abandoned cart's journey reads
6
+ * it. The browser sends it on landing, on every further campaign touch and
7
+ * when the first article goes in; `null` takes it off again once the visitor
8
+ * withdrew the consent it rested on.
9
+ *
10
+ * Best effort by design: no cart yet, the demo cart, or a carts app that
11
+ * refuses the field answer `{ stored: false }` and the visit goes on. Where
12
+ * the visit came from is never a reason to fail a page.
13
+ */
14
+ export default defineEventHandler(async (event) => {
15
+ const body = await readBody<{ attribution?: unknown }>(event).catch(() => null);
16
+ const attribution = body?.attribution === null ? null : sanitizeAttribution(body?.attribution);
17
+ if (attribution === null && body?.attribution !== null) {
18
+ return { stored: false };
19
+ }
20
+ const manager = getCartManager(event);
21
+ if (!manager) {
22
+ return { stored: false };
23
+ }
24
+ try {
25
+ return { stored: await manager.setActiveCartAttribution(event, attribution) };
26
+ }
27
+ catch (err) {
28
+ getLogService().warn("cart attribution not stored", apiErrorContext(err));
29
+ return { stored: false };
30
+ }
31
+ });
@@ -0,0 +1,30 @@
1
+ import { pspReturnParams } from "../../../app/shared/pspReturn";
2
+ import { confirmPspReturn } from "../../utils/pspReturn";
3
+
4
+ interface PaymentReturnPayload {
5
+ /** The order's number, as the return address carried it (`?order=`). */
6
+ order?: string;
7
+ /** Every query parameter the provider returned the buyer with, `rx_payment` included. */
8
+ params?: Record<string, unknown>;
9
+ }
10
+
11
+ /**
12
+ * The return from a payment provider (FE-5): confirm the payment the buyer was
13
+ * sent off for, and say how it ended — `paid`, `failed` or `pending`.
14
+ *
15
+ * Provider-agnostic: the payments app reads the provider's own parameters.
16
+ * Not an open confirm proxy: only the payment of the order the return names,
17
+ * and only for the browser the checkout sent off, or the buyer whose order it
18
+ * is (see utils/pspReturn.ts). Anything else is a 404.
19
+ */
20
+ export default defineEventHandler(async (event) => {
21
+ if (resolvePaymentServiceKey(event) !== "api") {
22
+ throw createError({ statusCode: 501, message: "This storefront does not take payments on demo data" });
23
+ }
24
+ const body = await readBody<PaymentReturnPayload>(event).catch(() => ({} as PaymentReturnPayload));
25
+ const params = pspReturnParams(body?.params && typeof body.params === "object" ? body.params : {});
26
+ return await confirmPspReturn(event, {
27
+ order: typeof body?.order === "string" ? body.order : "",
28
+ params,
29
+ });
30
+ });
@@ -0,0 +1,27 @@
1
+ import type { LoyaltyAccount } from "../../interfaces/marketing";
2
+
3
+ /**
4
+ * The signed-in buyer's loyalty membership (RAD-293): the programme and tier,
5
+ * the points balance, and — for a yearly turnover bonus like eltric "Premium"
6
+ * — how far the company is this year. A company agreement is the
7
+ * organisation's, so the buyer's organisation goes along.
8
+ *
9
+ * Nobody signed in is a 401; a buyer in no programme, or a shop without the
10
+ * loyalty app, is `null` — the page then says there is nothing to show.
11
+ */
12
+ export default defineEventHandler(async (event): Promise<LoyaltyAccount | null> => {
13
+ const user = await getAuthService(event).me(event);
14
+ if (!user) {
15
+ throw createError({ statusCode: 401, message: "Unauthorized" });
16
+ }
17
+ const refs = sessionOrderRefs(event);
18
+ const contactId = user.contactId ?? refs.contact_id;
19
+ // A demo persona has no contact; the mock answers for it anyway.
20
+ if (!contactId && resolveMarketingServiceKey(event) === "api") {
21
+ return null;
22
+ }
23
+ return await getMarketingService(event).loyaltyAccount(event, {
24
+ contactId: contactId ?? "",
25
+ organizationId: refs.organization_id ?? null,
26
+ });
27
+ });
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The double opt-in click (RAD-293): the link in the confirmation mail opens
3
+ * the shop's confirmation page, and the page — in the browser, never while it
4
+ * is rendered on the server — confirms here. A mail scanner that fetches the
5
+ * link without running the page confirms nothing.
6
+ *
7
+ * The address and the browser go along as the evidence marketing-consents
8
+ * keeps for the confirmation.
9
+ */
10
+ export default defineEventHandler(async (event) => {
11
+ const token = routeToken(event);
12
+ const body = await readBody<{ page_url?: unknown }>(event).catch(() => null);
13
+ const pageUrl = typeof body?.page_url === "string" ? body.page_url.slice(0, 2048) : null;
14
+ try {
15
+ const result = await getMarketingService(event).confirmSubscription(event, token, consentEvidence(event, pageUrl));
16
+ return { confirmed: true, alreadyConfirmed: result.alreadyConfirmed };
17
+ }
18
+ catch (err) {
19
+ return rethrowTokenRefusal(err);
20
+ }
21
+ });
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The preference centre (RAD-293): what a recipient of the shop's mails is
3
+ * subscribed to, behind the personal link in every mail's footer. The address
4
+ * comes back masked; the link is the only proof of who is asking.
5
+ */
6
+ export default defineEventHandler(async (event) => {
7
+ const token = routeToken(event);
8
+ try {
9
+ return await getMarketingService(event).preferences(event, token, resolveLocale(event));
10
+ }
11
+ catch (err) {
12
+ return rethrowTokenRefusal(err);
13
+ }
14
+ });
@@ -0,0 +1,36 @@
1
+ import type { PreferenceChoice } from "../../../interfaces/marketing";
2
+
3
+ /**
4
+ * What a recipient changed in the preference centre: one choice per type, or
5
+ * leaving everything at once. A type that needs a double opt-in is requested,
6
+ * not subscribed — marketing-consents sends the confirmation mail.
7
+ */
8
+ export default defineEventHandler(async (event) => {
9
+ const token = routeToken(event);
10
+ const body = await readBody<{ choices?: unknown; unsubscribe_all?: unknown }>(event).catch(() => null);
11
+ const unsubscribeAll = body?.unsubscribe_all === true;
12
+ const choices: PreferenceChoice[] = Array.isArray(body?.choices)
13
+ ? (body.choices as Record<string, unknown>[])
14
+ .filter(choice => choice && typeof choice.subscription_type === "string" && typeof choice.subscribed === "boolean")
15
+ .slice(0, 50)
16
+ .map(choice => ({
17
+ subscription_type: String(choice.subscription_type),
18
+ subscribed: choice.subscribed === true,
19
+ ...(typeof choice.consent_text_id === "string" ? { consent_text_id: choice.consent_text_id } : {}),
20
+ }))
21
+ : [];
22
+ if (!unsubscribeAll && !choices.length) {
23
+ throw createError({ statusCode: 422, message: "Nothing to change" });
24
+ }
25
+ try {
26
+ return await getMarketingService(event).savePreferences(
27
+ event,
28
+ token,
29
+ { choices, unsubscribeAll, locale: resolveLocale(event) },
30
+ consentEvidence(event),
31
+ );
32
+ }
33
+ catch (err) {
34
+ return rethrowTokenRefusal(err);
35
+ }
36
+ });