@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
@@ -0,0 +1,292 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type {
4
+ CampaignTouch,
5
+ ConfirmResult,
6
+ Evidence,
7
+ IMarketingService,
8
+ Labels,
9
+ LoyaltyAccount,
10
+ LoyaltyMembership,
11
+ LoyaltyProgress,
12
+ PreferenceChange,
13
+ PreferenceChoice,
14
+ PreferenceView,
15
+ ReviewInput,
16
+ ReviewRequestView,
17
+ ReviewSubmitResult,
18
+ } from "../interfaces/marketing";
19
+ import { MarketingTokenError } from "../interfaces/marketing";
20
+
21
+ /**
22
+ * The marketing apps through the public revenexx API (RAD-293).
23
+ *
24
+ * Every call goes through the transport's escape hatch: the generated SDK
25
+ * predates marketing-consents, reviews, loyalty, audiences and campaigns.
26
+ * Routes and shapes are the ones the marketing contracts settle (CONTRACTS.md
27
+ * §3 and its appendix); a token page maps 404 and 410 to the refusal the
28
+ * visitor is shown, everything else stays an error.
29
+ */
30
+
31
+ interface PreferenceAnswer {
32
+ address_hint?: string;
33
+ subscription_types?: {
34
+ code: string;
35
+ label?: string | null;
36
+ description?: string | null;
37
+ state?: string | null;
38
+ subscribed?: boolean;
39
+ consent_text?: { id?: string; wording?: string } | null;
40
+ }[];
41
+ changes?: { subscription_type: string | null; action: string }[];
42
+ }
43
+
44
+ interface LookupItem {
45
+ program?: { code?: string; labels?: Labels; kind?: string } | null;
46
+ tier?: { code?: string; labels?: Labels; perks?: Labels[] } | null;
47
+ points_balance?: number | null;
48
+ agreement?: { id?: string } | null;
49
+ }
50
+
51
+ interface ProgressAnswer {
52
+ period?: string | number | null;
53
+ currency?: string;
54
+ turnover_ytd?: number;
55
+ projected_turnover?: number | null;
56
+ tiers?: { code: string; labels?: Labels; threshold?: number | null; bonus_percent?: number; reached?: boolean; current?: boolean }[];
57
+ next_tier?: { code: string; labels?: Labels; gap?: number; bonus_percent?: number } | null;
58
+ bonus_now?: number | null;
59
+ expected_bonus?: number | null;
60
+ rules?: { requires_no_overdue?: boolean };
61
+ }
62
+
63
+ function tokenPath(base: string, token: string): string {
64
+ return `${base}/${encodeURIComponent(token)}`;
65
+ }
66
+
67
+ /** 404 and 410 on a token route are the visitor's link, not a failure of the shop. */
68
+ function asTokenRefusal(err: unknown): never {
69
+ if (err instanceof RevenexxException && (err.code === 404 || err.code === 410)) {
70
+ throw new MarketingTokenError(err.code === 410 ? "expired" : "unknown");
71
+ }
72
+ throw err;
73
+ }
74
+
75
+ function toPreferenceView(answer: PreferenceAnswer): PreferenceView {
76
+ return {
77
+ addressHint: answer.address_hint ?? "",
78
+ types: (answer.subscription_types ?? []).map(type => ({
79
+ code: type.code,
80
+ label: type.label || type.code,
81
+ description: type.description ?? null,
82
+ subscribed: type.subscribed === true,
83
+ state: type.state ?? null,
84
+ consentTextId: type.consent_text?.id ?? null,
85
+ consentText: type.consent_text?.wording ?? null,
86
+ })),
87
+ };
88
+ }
89
+
90
+ function toProgress(answer: ProgressAnswer): LoyaltyProgress {
91
+ return {
92
+ period: answer.period ?? null,
93
+ currency: answer.currency ?? "EUR",
94
+ turnoverYtd: Number(answer.turnover_ytd ?? 0),
95
+ projectedTurnover: answer.projected_turnover ?? null,
96
+ tiers: (answer.tiers ?? []).map(tier => ({
97
+ code: tier.code,
98
+ labels: tier.labels ?? null,
99
+ threshold: tier.threshold ?? null,
100
+ bonusPercent: Number(tier.bonus_percent ?? 0),
101
+ reached: tier.reached === true,
102
+ current: tier.current === true,
103
+ })),
104
+ nextTier: answer.next_tier
105
+ ? {
106
+ code: answer.next_tier.code,
107
+ labels: answer.next_tier.labels ?? null,
108
+ gap: Number(answer.next_tier.gap ?? 0),
109
+ bonusPercent: Number(answer.next_tier.bonus_percent ?? 0),
110
+ }
111
+ : null,
112
+ bonusNow: answer.bonus_now ?? null,
113
+ expectedBonus: answer.expected_bonus ?? null,
114
+ requiresNoOverdue: answer.rules?.requires_no_overdue !== false,
115
+ };
116
+ }
117
+
118
+ export class ApiMarketingService implements IMarketingService {
119
+ async confirmSubscription(_event: H3Event, token: string, evidence: Evidence): Promise<ConfirmResult> {
120
+ try {
121
+ const answer = await useRevenexxSdk().call<{ already_confirmed?: boolean }>(
122
+ "POST",
123
+ tokenPath("/v1/marketing-consents/confirm", token),
124
+ { body: { ip: evidence.ip, user_agent: evidence.user_agent, page_url: evidence.page_url ?? null } },
125
+ );
126
+ return { alreadyConfirmed: answer?.already_confirmed === true };
127
+ }
128
+ catch (err) {
129
+ return asTokenRefusal(err);
130
+ }
131
+ }
132
+
133
+ async preferences(_event: H3Event, token: string, locale: string): Promise<PreferenceView> {
134
+ try {
135
+ const answer = await useRevenexxSdk().call<PreferenceAnswer>(
136
+ "GET",
137
+ tokenPath("/v1/marketing-consents/preferences", token),
138
+ { query: { locale } },
139
+ );
140
+ return toPreferenceView(answer);
141
+ }
142
+ catch (err) {
143
+ return asTokenRefusal(err);
144
+ }
145
+ }
146
+
147
+ async savePreferences(
148
+ _event: H3Event,
149
+ token: string,
150
+ input: { choices?: PreferenceChoice[]; unsubscribeAll?: boolean; locale: string },
151
+ evidence: Evidence,
152
+ ): Promise<{ view: PreferenceView; changes: PreferenceChange[] }> {
153
+ try {
154
+ const answer = await useRevenexxSdk().call<PreferenceAnswer>(
155
+ "POST",
156
+ tokenPath("/v1/marketing-consents/preferences", token),
157
+ {
158
+ body: {
159
+ ...(input.unsubscribeAll ? { unsubscribe_all: true } : { choices: input.choices ?? [] }),
160
+ locale: input.locale,
161
+ ip: evidence.ip,
162
+ user_agent: evidence.user_agent,
163
+ },
164
+ },
165
+ );
166
+ return { view: toPreferenceView(answer), changes: answer.changes ?? [] };
167
+ }
168
+ catch (err) {
169
+ return asTokenRefusal(err);
170
+ }
171
+ }
172
+
173
+ async reviewRequest(_event: H3Event, token: string): Promise<ReviewRequestView> {
174
+ try {
175
+ const answer = await useRevenexxSdk().call<{
176
+ state?: string;
177
+ expires_at?: string | null;
178
+ order_number?: string | null;
179
+ products?: { product_id: string; sku?: string | null; name?: string; reviewed?: boolean }[];
180
+ }>("GET", tokenPath("/v1/reviews/requests", token));
181
+ // A link the app still answers but has marked expired reads as expired.
182
+ if (answer.state === "expired") {
183
+ throw new MarketingTokenError("expired");
184
+ }
185
+ return {
186
+ orderNumber: answer.order_number ?? null,
187
+ expiresAt: answer.expires_at ?? null,
188
+ products: (answer.products ?? []).map(product => ({
189
+ productId: product.product_id,
190
+ sku: product.sku ?? null,
191
+ name: product.name || product.sku || product.product_id,
192
+ reviewed: product.reviewed === true,
193
+ })),
194
+ };
195
+ }
196
+ catch (err) {
197
+ if (err instanceof MarketingTokenError) {
198
+ throw err;
199
+ }
200
+ return asTokenRefusal(err);
201
+ }
202
+ }
203
+
204
+ async submitReviews(_event: H3Event, token: string, reviews: ReviewInput[], locale: string): Promise<ReviewSubmitResult> {
205
+ try {
206
+ const answer = await useRevenexxSdk().call<{
207
+ reviews?: { product_id: string }[];
208
+ rejected?: { product_id?: string | null; reason: string }[];
209
+ }>("POST", tokenPath("/v1/reviews/submit", token), { body: { reviews, locale } });
210
+ return {
211
+ accepted: (answer.reviews ?? []).map(review => review.product_id),
212
+ rejected: (answer.rejected ?? []).map(entry => ({ productId: entry.product_id ?? null, reason: entry.reason })),
213
+ };
214
+ }
215
+ catch (err) {
216
+ // Nothing accepted at all is a 400 with the reasons — the form shows them.
217
+ if (err instanceof RevenexxException && err.code === 400 && apiErrorCode(err) === "nothing_accepted") {
218
+ return { accepted: [], rejected: reviews.map(review => ({ productId: review.product_id, reason: "nothing_accepted" })) };
219
+ }
220
+ return asTokenRefusal(err);
221
+ }
222
+ }
223
+
224
+ async loyaltyAccount(_event: H3Event, holder: { contactId: string; organizationId?: string | null }): Promise<LoyaltyAccount | null> {
225
+ const sdk = useRevenexxSdk();
226
+ let items: LookupItem[];
227
+ try {
228
+ const answer = await sdk.call<LookupItem & { items?: LookupItem[] }>("GET", "/v1/loyalty/memberships/lookup", {
229
+ query: {
230
+ contact_id: holder.contactId,
231
+ ...(holder.organizationId ? { organization_id: holder.organizationId } : {}),
232
+ },
233
+ });
234
+ items = answer.items ?? (answer.program ? [answer] : []);
235
+ }
236
+ catch (err) {
237
+ // Loyalty not installed, or not answering: the buyer simply has no
238
+ // programme to be shown — never an error page in the account.
239
+ getLogService().warn("loyalty lookup failed", apiErrorContext(err));
240
+ return null;
241
+ }
242
+ const memberships: LoyaltyMembership[] = items
243
+ .filter(item => item.program?.code)
244
+ .map(item => ({
245
+ program: { code: item.program!.code!, labels: item.program!.labels ?? null, kind: item.program!.kind ?? "points" },
246
+ tier: item.tier?.code ? { code: item.tier.code, labels: item.tier.labels ?? null, perks: item.tier.perks ?? [] } : null,
247
+ pointsBalance: typeof item.points_balance === "number" ? item.points_balance : null,
248
+ agreementId: item.agreement?.id ?? null,
249
+ }));
250
+ if (!memberships.length) {
251
+ return null;
252
+ }
253
+ const agreementId = memberships.find(m => m.agreementId)?.agreementId ?? null;
254
+ let progress: LoyaltyProgress | null = null;
255
+ if (agreementId) {
256
+ try {
257
+ progress = toProgress(await sdk.call<ProgressAnswer>(
258
+ "GET",
259
+ `/v1/loyalty/bonus-agreements/${encodeURIComponent(agreementId)}/progress`,
260
+ ));
261
+ }
262
+ catch (err) {
263
+ getLogService().warn("loyalty progress failed", apiErrorContext(err));
264
+ }
265
+ }
266
+ return { memberships, progress };
267
+ }
268
+
269
+ async audienceCodes(_event: H3Event, contactId: string): Promise<string[]> {
270
+ try {
271
+ const answer = await useRevenexxSdk().call<{ codes?: string[] }>("POST", "/v1/audiences/memberships", {
272
+ body: { contact_id: contactId },
273
+ });
274
+ return Array.isArray(answer.codes) ? answer.codes.filter(code => typeof code === "string") : [];
275
+ }
276
+ catch (err) {
277
+ // Unanswerable reads as anonymous: a visitor then sees what everybody sees.
278
+ getLogService().warn("audience memberships failed", apiErrorContext(err));
279
+ return [];
280
+ }
281
+ }
282
+
283
+ async recordTouches(
284
+ _event: H3Event,
285
+ touches: (CampaignTouch & { contact_id?: string; session_key?: string; market?: string })[],
286
+ ): Promise<void> {
287
+ if (!touches.length) {
288
+ return;
289
+ }
290
+ await useRevenexxSdk().call("POST", "/v1/campaigns/touches", { body: { touches } });
291
+ }
292
+ }
@@ -51,8 +51,12 @@ export class ApiProductService implements IProductService {
51
51
  if (!doc) {
52
52
  return null;
53
53
  }
54
- const detail = await mapLiveDocToDetail(doc, locale);
55
- return { ...detail, model: await this.getProductModel(doc.attrs ?? {}) };
54
+ // Side by side: both read the product's media and share each lookup.
55
+ const [detail, model] = await Promise.all([
56
+ mapLiveDocToDetail(doc, locale),
57
+ this.getProductModel(doc.attrs ?? {}),
58
+ ]);
59
+ return { ...detail, model };
56
60
  }
57
61
 
58
62
  /**
@@ -4,6 +4,7 @@ import type {
4
4
  CartCalculation,
5
5
  CartCalculationRequest,
6
6
  CartLineHint,
7
+ CartLineHintType,
7
8
  CartMessage,
8
9
  CartTotalRow,
9
10
  PriceLabelCode,
@@ -11,6 +12,15 @@ import type {
11
12
  import type { CartItem } from "../../app/interfaces/cart-item";
12
13
 
13
14
  import type { CartCalculationOverrides, ICartCalculationService } from "../interfaces/cartCalculation";
15
+ import { readCartItemHints } from "../utils/cartItemHints";
16
+
17
+ /**
18
+ * Hints a cart line carries from the backend (`CartItem.hints`) that the cart
19
+ * renders, by type → i18n key. A type missing here is not shown.
20
+ */
21
+ const ITEM_HINT_KEYS = new Map<string, { type: CartLineHintType; messageKey: string }>([
22
+ ["unit-changed", { type: "unit-changed", messageKey: "calc.hints.unitChanged" }],
23
+ ]);
14
24
 
15
25
  /* ------------------------------------------------------------------ */
16
26
  /* Demo rule tables — stand-ins for ERP master data */
@@ -199,6 +209,15 @@ export class MockCartCalculationService implements ICartCalculationService {
199
209
  });
200
210
  }
201
211
 
212
+ // Hints the line was sent with. Only known types render: a hint without
213
+ // a message would be an empty alert.
214
+ for (const hint of readCartItemHints(item.hints) ?? []) {
215
+ const known = ITEM_HINT_KEYS.get(hint.type);
216
+ if (known) {
217
+ hints.push({ ...known, ...(hint.params ? { params: hint.params } : {}) });
218
+ }
219
+ }
220
+
202
221
  if ((skuCounts.get(item.sku ?? "") ?? 0) > 1) {
203
222
  hints.push({ type: "duplicate", messageKey: "calc.hints.duplicate" });
204
223
  }
@@ -379,6 +398,16 @@ export class MockCartCalculationService implements ICartCalculationService {
379
398
  }
380
399
  }
381
400
 
401
+ // A switched unit keeps the quantity, and 10 metres are not 10 pieces —
402
+ // a warning, not a block: the buyer may well have meant 10 pieces.
403
+ if (lines.some(l => l.hints.some(h => h.type === "unit-changed"))) {
404
+ messages.push({
405
+ severity: "warning",
406
+ code: "units-changed",
407
+ messageKey: "calc.messages.unitsChanged",
408
+ });
409
+ }
410
+
382
411
  if (settings.costCenters.enabled && settings.costCenters.required && role) {
383
412
  const missing = lines.some(l => l.hints.some(h => h.type === "missing-cost-center"));
384
413
  if (context.costCenters.length === 0) {
@@ -0,0 +1,178 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type {
4
+ ConfirmResult,
5
+ IMarketingService,
6
+ LoyaltyAccount,
7
+ PreferenceChange,
8
+ PreferenceChoice,
9
+ PreferenceView,
10
+ ReviewInput,
11
+ ReviewRequestView,
12
+ ReviewSubmitResult,
13
+ } from "../interfaces/marketing";
14
+ import { MarketingTokenError } from "../interfaces/marketing";
15
+
16
+ /**
17
+ * Demo answers for the marketing pages (RAD-293), so a storefront without
18
+ * gateway credentials can show every page and a test has something to drive.
19
+ *
20
+ * A token containing `expired` answers as an expired link, one containing
21
+ * `unknown` as a link nobody issued; any other token is a valid one. The
22
+ * loyalty account is the eltric "Premium" agreement of the click dummy
23
+ * (designer draft 2026-10-14): last year 88.300 €, three stages at 100, 105
24
+ * and 110 % of it.
25
+ */
26
+
27
+ const PREFERENCE_TYPES = [
28
+ { code: "newsletter", label: { de: "Newsletter", en: "Newsletter" }, description: { de: "Neuheiten und Angebote, etwa zweimal im Monat.", en: "News and offers, about twice a month." } },
29
+ { code: "product-news", label: { de: "Produktinformationen", en: "Product information" }, description: { de: "Wenn ein Artikel aus Ihren Bestellungen ein Update bekommt.", en: "When an article you ordered gets an update." } },
30
+ ] as const;
31
+
32
+ const BASE = 88300;
33
+
34
+ function refuse(token: string): void {
35
+ if (token.includes("expired")) {
36
+ throw new MarketingTokenError("expired");
37
+ }
38
+ if (token.includes("unknown")) {
39
+ throw new MarketingTokenError("unknown");
40
+ }
41
+ }
42
+
43
+ function lang(locale: string): "de" | "en" {
44
+ return locale.startsWith("en") ? "en" : "de";
45
+ }
46
+
47
+ export class MockMarketingService implements IMarketingService {
48
+ /** Per token, which types are subscribed — survives a reload in one dev server. */
49
+ private readonly subscriptions = new Map<string, Set<string>>();
50
+ private readonly reviewed = new Map<string, Set<string>>();
51
+
52
+ async confirmSubscription(_event: H3Event, token: string): Promise<ConfirmResult> {
53
+ refuse(token);
54
+ return { alreadyConfirmed: token.includes("confirmed") };
55
+ }
56
+
57
+ private view(token: string, locale: string): PreferenceView {
58
+ const subscribed = this.subscriptions.get(token) ?? new Set(["newsletter"]);
59
+ this.subscriptions.set(token, subscribed);
60
+ return {
61
+ addressHint: "e•••@example.com",
62
+ types: PREFERENCE_TYPES.map(type => ({
63
+ code: type.code,
64
+ label: type.label[lang(locale)],
65
+ description: type.description[lang(locale)],
66
+ subscribed: subscribed.has(type.code),
67
+ state: subscribed.has(type.code) ? "confirmed" : null,
68
+ consentTextId: null,
69
+ consentText: lang(locale) === "en"
70
+ ? "I would like to receive this by email. I can withdraw at any time."
71
+ : "Ich möchte das per E-Mail erhalten. Ich kann jederzeit widerrufen.",
72
+ })),
73
+ };
74
+ }
75
+
76
+ async preferences(_event: H3Event, token: string, locale: string): Promise<PreferenceView> {
77
+ refuse(token);
78
+ return this.view(token, locale);
79
+ }
80
+
81
+ async savePreferences(
82
+ _event: H3Event,
83
+ token: string,
84
+ input: { choices?: PreferenceChoice[]; unsubscribeAll?: boolean; locale: string },
85
+ ): Promise<{ view: PreferenceView; changes: PreferenceChange[] }> {
86
+ refuse(token);
87
+ const subscribed = this.subscriptions.get(token) ?? new Set(["newsletter"]);
88
+ const changes: PreferenceChange[] = [];
89
+ if (input.unsubscribeAll) {
90
+ for (const code of subscribed) {
91
+ changes.push({ subscription_type: code, action: "withdrawn" });
92
+ }
93
+ subscribed.clear();
94
+ }
95
+ else {
96
+ for (const choice of input.choices ?? []) {
97
+ const had = subscribed.has(choice.subscription_type);
98
+ if (choice.subscribed && !had) {
99
+ // A new type with double opt-in waits for its confirmation mail.
100
+ changes.push({ subscription_type: choice.subscription_type, action: "requested" });
101
+ }
102
+ else if (!choice.subscribed && had) {
103
+ subscribed.delete(choice.subscription_type);
104
+ changes.push({ subscription_type: choice.subscription_type, action: "withdrawn" });
105
+ }
106
+ else {
107
+ changes.push({ subscription_type: choice.subscription_type, action: "unchanged" });
108
+ }
109
+ }
110
+ }
111
+ this.subscriptions.set(token, subscribed);
112
+ return { view: this.view(token, input.locale), changes };
113
+ }
114
+
115
+ async reviewRequest(_event: H3Event, token: string): Promise<ReviewRequestView> {
116
+ refuse(token);
117
+ const done = this.reviewed.get(token) ?? new Set<string>();
118
+ return {
119
+ orderNumber: "100234",
120
+ expiresAt: null,
121
+ products: [
122
+ { productId: "demo-drill", sku: "BM-4711", name: "Akku-Bohrschrauber 18 V", reviewed: done.has("demo-drill") },
123
+ { productId: "demo-bits", sku: "BT-0815", name: "Bit-Set 32-teilig", reviewed: done.has("demo-bits") },
124
+ ],
125
+ };
126
+ }
127
+
128
+ async submitReviews(_event: H3Event, token: string, reviews: ReviewInput[]): Promise<ReviewSubmitResult> {
129
+ refuse(token);
130
+ const done = this.reviewed.get(token) ?? new Set<string>();
131
+ const result: ReviewSubmitResult = { accepted: [], rejected: [] };
132
+ for (const review of reviews) {
133
+ if (done.has(review.product_id)) {
134
+ result.rejected.push({ productId: review.product_id, reason: "already_reviewed" });
135
+ continue;
136
+ }
137
+ done.add(review.product_id);
138
+ result.accepted.push(review.product_id);
139
+ }
140
+ this.reviewed.set(token, done);
141
+ return result;
142
+ }
143
+
144
+ async loyaltyAccount(): Promise<LoyaltyAccount | null> {
145
+ const perks = [{ de: "Premiumversand: frachtfrei ab 75 € statt 145 €", en: "Premium shipping: free from €75 instead of €145" }];
146
+ return {
147
+ memberships: [{
148
+ program: { code: "premium", labels: { de: "eltric Premium", en: "eltric Premium" }, kind: "turnover_bonus" },
149
+ tier: { code: "stufe-2", labels: { de: "Stufe 2", en: "Stage 2" }, perks },
150
+ pointsBalance: null,
151
+ agreementId: "demo-agreement",
152
+ }],
153
+ progress: {
154
+ period: new Date().getFullYear(),
155
+ currency: "EUR",
156
+ turnoverYtd: 93148,
157
+ projectedTurnover: 101420,
158
+ tiers: [
159
+ { code: "stufe-1", labels: { de: "Stufe 1", en: "Stage 1" }, threshold: BASE, bonusPercent: 1, reached: true, current: false },
160
+ { code: "stufe-2", labels: { de: "Stufe 2", en: "Stage 2" }, threshold: 92715, bonusPercent: 2, reached: true, current: true },
161
+ { code: "stufe-3", labels: { de: "Stufe 3", en: "Stage 3" }, threshold: 97130, bonusPercent: 3, reached: false, current: false },
162
+ ],
163
+ nextTier: { code: "stufe-3", labels: { de: "Stufe 3", en: "Stage 3" }, gap: 3982, bonusPercent: 3 },
164
+ bonusNow: 1862.96,
165
+ expectedBonus: 3042.6,
166
+ requiresNoOverdue: true,
167
+ },
168
+ };
169
+ }
170
+
171
+ async audienceCodes(): Promise<string[]> {
172
+ return [];
173
+ }
174
+
175
+ async recordTouches(): Promise<void> {
176
+ // The demo counts nothing: there is no campaign to count for.
177
+ }
178
+ }
@@ -0,0 +1,29 @@
1
+ import type { CartItemHint } from "../../app/interfaces/cart-item";
2
+
3
+ /** A plain object — not null and not an array, which `typeof` lets through. */
4
+ function isRecord(value: unknown): value is Record<string, unknown> {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+
8
+ /**
9
+ * The well-formed entries of a cart line's hints. The line metadata is not
10
+ * only ours — punchout writes the hints on an inbound cart — and the client
11
+ * sends the items back whole on every sync and calculation, so the hints are
12
+ * cleaned wherever they come in rather than cast: on read, on write and in
13
+ * the calculation.
14
+ */
15
+ export function readCartItemHints(value: unknown): CartItemHint[] | undefined {
16
+ if (!Array.isArray(value)) {
17
+ return undefined;
18
+ }
19
+ const hints = value.flatMap((entry: unknown): CartItemHint[] => {
20
+ if (!isRecord(entry) || typeof entry.type !== "string" || !entry.type) {
21
+ return [];
22
+ }
23
+ const params = Object.fromEntries(Object.entries(isRecord(entry.params) ? entry.params : {}).filter(
24
+ (pair): pair is [string, string | number] => ["string", "number"].includes(typeof pair[1]),
25
+ ));
26
+ return [{ type: entry.type, ...(Object.keys(params).length ? { params } : {}) }];
27
+ });
28
+ return hints.length ? hints : undefined;
29
+ }
@@ -25,6 +25,22 @@ function sign(payload: string): string {
25
25
  return createHmac("sha256", sessionSecret()).update(payload).digest("hex");
26
26
  }
27
27
 
28
+ /**
29
+ * The same signature, under its own purpose label, for other short-lived
30
+ * browser-held claims of the checkout (the PSP return, FE-5). The label keeps
31
+ * one kind of token from being replayed as another.
32
+ */
33
+ export function checkoutSignature(purpose: string, payload: string): string {
34
+ return sign(`${purpose}:${payload}`);
35
+ }
36
+
37
+ /** Constant-time comparison of two signatures. */
38
+ export function signaturesMatch(given: string, expected: string): boolean {
39
+ const a = Buffer.from(given, "utf8");
40
+ const b = Buffer.from(expected, "utf8");
41
+ return a.length === b.length && timingSafeEqual(a, b);
42
+ }
43
+
28
44
  /** Per-instance replay cache (best-effort one-time use). */
29
45
  const consumed = new Map<string, number>();
30
46