@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,255 @@
1
+ import { type PspInstrument, PspInputError, type PspMountContext, type PspTokenizer } from "./types";
2
+
3
+ /**
4
+ * Novalnet tokenizer — Novalnet's credit card iframe (`NovalnetUtility`).
5
+ *
6
+ * The library is loaded from Novalnet's CDN (their supported integration; it
7
+ * must not be self-hosted) and renders the card form inside an iframe served by
8
+ * secure.novalnet.de. `tokenize()` asks the iframe for the card's `pan_hash`
9
+ * and `unique_id`; only those reach the BFF, never card data.
10
+ *
11
+ * When Novalnet answers `do_redirect` (the card needs a step the iframe cannot
12
+ * do inline), `tokenize()` returns no instrument: the order is then placed
13
+ * without one and the buyer completes on Novalnet's hosted payment page.
14
+ */
15
+
16
+ export const NOVALNET_UTILITY_JS = "https://cdn.novalnet.de/js/v2/NovalnetUtility-1.1.2.js";
17
+ // Subresource integrity of the pinned version (sha384 of the file Novalnet
18
+ // serves). A changed file fails to load, and the checkout falls back to the
19
+ // hosted payment page rather than running code nobody reviewed.
20
+ export const NOVALNET_UTILITY_SRI = "sha384-wRpaQDgV62dqZ/HthwD84Gs9Mgxg5u5PrND0zS9L5rjOdWE8nTDLq+fdsCxbnj6K";
21
+
22
+ /** How long the iframe may take to answer a hash request before it counts as failed. */
23
+ const TOKENIZE_TIMEOUT_MS = 30_000;
24
+ /** How long the card form may take to appear before the checkout falls back. */
25
+ const MOUNT_TIMEOUT_MS = 20_000;
26
+
27
+ interface NovalnetHashAnswer {
28
+ hash?: string;
29
+ pan_hash?: string;
30
+ unique_id?: string;
31
+ do_redirect?: number | string | boolean;
32
+ error_message?: string;
33
+ }
34
+
35
+ interface NovalnetFormConfig {
36
+ callback: {
37
+ on_success: (data: NovalnetHashAnswer) => boolean | void;
38
+ on_error: (data: NovalnetHashAnswer) => boolean | void;
39
+ on_show_overlay?: () => void;
40
+ on_hide_overlay?: () => void;
41
+ };
42
+ iframe: { id: string; inline: number; style?: Record<string, string> };
43
+ customer?: Record<string, unknown>;
44
+ transaction?: Record<string, unknown>;
45
+ custom?: { lang?: string };
46
+ }
47
+
48
+ export interface NovalnetUtilityApi {
49
+ setClientKey: (key: string) => boolean;
50
+ createCreditCardForm: (config: NovalnetFormConfig) => unknown;
51
+ getPanHash: () => unknown;
52
+ /** The library keeps its callbacks on itself and reads them on every message. */
53
+ on_success?: unknown;
54
+ on_error?: unknown;
55
+ }
56
+
57
+ function loadNovalnetUtility(): Promise<NovalnetUtilityApi> {
58
+ const w = window as unknown as { NovalnetUtility?: NovalnetUtilityApi };
59
+ if (w.NovalnetUtility) {
60
+ return Promise.resolve(w.NovalnetUtility);
61
+ }
62
+ return new Promise((resolve, reject) => {
63
+ const onload = () => w.NovalnetUtility
64
+ ? resolve(w.NovalnetUtility)
65
+ : reject(new Error("NovalnetUtility loaded but missing"));
66
+ const onerror = () => reject(new Error("failed to load NovalnetUtility"));
67
+ const existing = document.querySelector<HTMLScriptElement>(`script[src="${NOVALNET_UTILITY_JS}"]`);
68
+ if (existing) {
69
+ existing.addEventListener("load", onload, { once: true });
70
+ existing.addEventListener("error", onerror, { once: true });
71
+ return;
72
+ }
73
+ const script = document.createElement("script");
74
+ script.src = NOVALNET_UTILITY_JS;
75
+ script.integrity = NOVALNET_UTILITY_SRI;
76
+ script.crossOrigin = "anonymous";
77
+ script.async = true;
78
+ script.addEventListener("load", onload, { once: true });
79
+ script.addEventListener("error", onerror, { once: true });
80
+ document.head.appendChild(script);
81
+ });
82
+ }
83
+
84
+ /** Novalnet takes amounts in minor units. */
85
+ export function novalnetAmount(amount: number | undefined): number | undefined {
86
+ if (typeof amount !== "number" || !Number.isFinite(amount) || amount <= 0) {
87
+ return undefined;
88
+ }
89
+ return Math.round(amount * 100);
90
+ }
91
+
92
+ /** The `createCreditCardForm` config for a mount context. Pure, so it can be tested. */
93
+ export function novalnetFormConfig(
94
+ ctx: Pick<PspMountContext, "testMode" | "locale" | "amount" | "currency" | "customer">,
95
+ iframeId: string,
96
+ callback: NovalnetFormConfig["callback"],
97
+ ): NovalnetFormConfig {
98
+ const customer = ctx.customer;
99
+ const billing = customer?.billing;
100
+ const amount = novalnetAmount(ctx.amount);
101
+ const config: NovalnetFormConfig = {
102
+ callback,
103
+ iframe: { id: iframeId, inline: 1 },
104
+ custom: { lang: (ctx.locale ?? "de").slice(0, 2).toUpperCase() },
105
+ transaction: {
106
+ ...(amount !== undefined ? { amount } : {}),
107
+ ...(ctx.currency ? { currency: ctx.currency } : {}),
108
+ // The library drops falsy values, so production sends nothing here.
109
+ ...(ctx.testMode ? { test_mode: 1 } : {}),
110
+ },
111
+ };
112
+ if (customer) {
113
+ config.customer = {
114
+ ...(customer.firstName ? { first_name: customer.firstName } : {}),
115
+ ...(customer.lastName ? { last_name: customer.lastName } : {}),
116
+ ...(customer.email ? { email: customer.email } : {}),
117
+ ...(billing
118
+ ? {
119
+ billing: {
120
+ ...(billing.street ? { street: billing.street } : {}),
121
+ ...(billing.city ? { city: billing.city } : {}),
122
+ ...(billing.zip ? { zip: billing.zip } : {}),
123
+ ...(billing.countryCode ? { country_code: billing.countryCode } : {}),
124
+ },
125
+ }
126
+ : {}),
127
+ };
128
+ }
129
+ return config;
130
+ }
131
+
132
+ /**
133
+ * What the iframe's hash answer becomes for the order: the instrument, or
134
+ * nothing when Novalnet wants the buyer redirected (hosted fallback).
135
+ */
136
+ export function novalnetInstrumentOf(answer: NovalnetHashAnswer): PspInstrument {
137
+ const redirect = answer.do_redirect;
138
+ if (redirect === 1 || redirect === "1" || redirect === true) {
139
+ return {};
140
+ }
141
+ const panHash = answer.hash ?? answer.pan_hash;
142
+ if (!panHash || !answer.unique_id) {
143
+ // Novalnet names what is wrong with the card the buyer typed; without a
144
+ // message the field itself failed.
145
+ throw answer.error_message ? new PspInputError(answer.error_message) : new Error("could not read the card");
146
+ }
147
+ return { instrument: { type: "novalnet_card", pan_hash: panHash, unique_id: answer.unique_id } };
148
+ }
149
+
150
+ let instanceCounter = 0;
151
+
152
+ export function createNovalnetTokenizer(): PspTokenizer {
153
+ let utility: NovalnetUtilityApi | null = null;
154
+ let iframe: HTMLIFrameElement | null = null;
155
+ let pending: { resolve: (v: PspInstrument) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> } | null = null;
156
+
157
+ function settle(fn: (p: NonNullable<typeof pending>) => void) {
158
+ if (!pending) {
159
+ return;
160
+ }
161
+ const p = pending;
162
+ pending = null;
163
+ clearTimeout(p.timer);
164
+ fn(p);
165
+ }
166
+
167
+ const callback: NovalnetFormConfig["callback"] = {
168
+ on_success: (data) => {
169
+ settle((p) => {
170
+ try {
171
+ p.resolve(novalnetInstrumentOf(data));
172
+ }
173
+ catch (err) {
174
+ p.reject(err instanceof Error ? err : new Error(String(err)));
175
+ }
176
+ });
177
+ return true;
178
+ },
179
+ on_error: (data) => {
180
+ // Outside a hash request (a field the buyer left invalid while typing)
181
+ // the iframe shows the message itself; nothing to settle.
182
+ settle(p => p.reject(data?.error_message
183
+ ? new PspInputError(data.error_message)
184
+ : new Error("could not read the card")));
185
+ return false;
186
+ },
187
+ };
188
+
189
+ return {
190
+ async mount(ctx: PspMountContext) {
191
+ utility = await loadNovalnetUtility();
192
+ if (!utility.setClientKey(ctx.publishableKey)) {
193
+ throw new Error("Novalnet client key was refused");
194
+ }
195
+ instanceCounter += 1;
196
+ iframe = document.createElement("iframe");
197
+ iframe.id = `novalnet-card-iframe-${instanceCounter}`;
198
+ iframe.title = "Novalnet";
199
+ iframe.setAttribute("frameborder", "0");
200
+ iframe.setAttribute("scrolling", "no");
201
+ iframe.style.width = "100%";
202
+ iframe.style.border = "0";
203
+ ctx.el.appendChild(iframe);
204
+ const frame = iframe;
205
+ await new Promise<void>((resolve, reject) => {
206
+ const timer = setTimeout(() => finish(new Error("Novalnet card form did not load")), MOUNT_TIMEOUT_MS);
207
+ function finish(err?: Error) {
208
+ clearTimeout(timer);
209
+ frame.removeEventListener("load", onload);
210
+ if (err) {
211
+ reject(err);
212
+ }
213
+ else {
214
+ resolve();
215
+ }
216
+ }
217
+ // The blank document an iframe starts with fires a load of its own;
218
+ // only Novalnet's form counts.
219
+ function onload() {
220
+ if (frame.src.startsWith("https://")) {
221
+ finish();
222
+ }
223
+ }
224
+ frame.addEventListener("load", onload);
225
+ // The library sets the iframe's src and its own onload handler.
226
+ const created = utility!.createCreditCardForm(novalnetFormConfig(ctx, frame.id, callback));
227
+ if (created === false) {
228
+ finish(new Error("Novalnet card form could not be created"));
229
+ }
230
+ });
231
+ },
232
+ tokenize() {
233
+ if (!utility || !iframe) {
234
+ return Promise.reject(new Error("card field is not ready"));
235
+ }
236
+ if (pending) {
237
+ return Promise.reject(new Error("card is already being read"));
238
+ }
239
+ return new Promise<PspInstrument>((resolve, reject) => {
240
+ pending = {
241
+ resolve,
242
+ reject,
243
+ timer: setTimeout(() => settle(p => p.reject(new Error("the card field did not answer"))), TOKENIZE_TIMEOUT_MS),
244
+ };
245
+ utility!.getPanHash();
246
+ });
247
+ },
248
+ destroy() {
249
+ settle(p => p.reject(new Error("card field was removed")));
250
+ iframe?.remove();
251
+ iframe = null;
252
+ utility = null;
253
+ },
254
+ };
255
+ }
@@ -1,3 +1,4 @@
1
+ import { createNovalnetTokenizer } from "./novalnet";
1
2
  import { createStripeTokenizer } from "./stripe";
2
3
  import type { PspTokenizerFactory } from "./types";
3
4
 
@@ -5,12 +6,15 @@ import type { PspTokenizerFactory } from "./types";
5
6
  * PSP tokenizer registry — the single extension point. A PSP that needs inline
6
7
  * card collection gets a factory here; everything else (BFF token threading,
7
8
  * the generic redirect/next_action handler, the order flow) is provider-
8
- * agnostic. To add Novalnet/Mollie later: implement its tokenizer and add one
9
- * line here.
9
+ * agnostic. To add another PSP: implement its tokenizer and add one line here.
10
+ *
11
+ * A tokenizer here does not mean every payment of that provider uses a field:
12
+ * Novalnet mounts one only where the merchant chose the embedded checkout
13
+ * (`checkoutMode`, see /api/payment/psp-config); otherwise it redirects.
10
14
  */
11
15
  export const pspTokenizers: Record<string, PspTokenizerFactory> = {
12
16
  stripe: createStripeTokenizer,
13
- // novalnet: createNovalnetTokenizer,
17
+ novalnet: createNovalnetTokenizer,
14
18
  // mollie: createMollieTokenizer,
15
19
  };
16
20
 
@@ -0,0 +1,99 @@
1
+ import { pspTokenizerFor } from "./registry";
2
+ import type { PspInstrument } from "./types";
3
+ import type { PaymentOption } from "../../interfaces/payment";
4
+
5
+ /**
6
+ * The checkout's rules for a PSP (FE-5), provider-agnostic and kept apart from
7
+ * the composable so they can be tested without a browser. Nothing here names a
8
+ * provider: what a PSP does is its config (`checkoutMode`) plus whether the
9
+ * registry holds a tokenizer for it.
10
+ */
11
+
12
+ /** A PSP as the checkout treats it. */
13
+ export interface PspCheckoutProvider {
14
+ /** `embedded` mounts the PSP's field; `hosted` sends the buyer to the PSP's page. */
15
+ checkoutMode?: "embedded" | "hosted";
16
+ publicKey?: string;
17
+ /** Legacy name of `publicKey`. */
18
+ publishableKey?: string;
19
+ testMode: boolean;
20
+ /** True when a field that cannot be used gives way to the PSP's hosted page. */
21
+ hostedFallback?: boolean;
22
+ }
23
+
24
+ /**
25
+ * The PSP behind a method, as the checkout treats it. The method's own
26
+ * `checkout` block (the payments app's eligibility answer, RAD-364) wins; a
27
+ * method without one falls back to `/api/payment/psp-config` by provider, the
28
+ * pre-RAD-364 path. A method with a block falls back to the hosted page only
29
+ * when its provider supports one (`checkoutModes`).
30
+ */
31
+ export function pspProviderFor(option: PaymentOption | null | undefined, providers: Record<string, PspCheckoutProvider> | undefined): PspCheckoutProvider | undefined {
32
+ if (!option || option.kind !== "psp") {
33
+ return undefined;
34
+ }
35
+ if (option.checkout) {
36
+ const modes = option.checkout.checkoutModes;
37
+ return {
38
+ checkoutMode: option.checkout.checkoutMode,
39
+ publicKey: option.checkout.publicKey,
40
+ testMode: option.checkout.testMode,
41
+ // Only a provider that has a hosted page can take the order without
42
+ // the field. An older payments app does not say — then it may, as
43
+ // before: it takes both flows whatever the mode.
44
+ hostedFallback: modes ? modes.includes("hosted") : true,
45
+ };
46
+ }
47
+ return option.provider ? providers?.[option.provider] : undefined;
48
+ }
49
+
50
+ /** The PSP's public key, under either name. */
51
+ export function pspPublicKey(provider: PspCheckoutProvider | undefined): string {
52
+ return provider?.publicKey || provider?.publishableKey || "";
53
+ }
54
+
55
+ /** The mode in force; a config from before FE-5 carries none and was always a field. */
56
+ export function pspCheckoutMode(provider: PspCheckoutProvider | undefined): "embedded" | "hosted" {
57
+ return provider?.checkoutMode ?? "embedded";
58
+ }
59
+
60
+ /**
61
+ * Whether the checkout mounts a card field for this method: a PSP method in
62
+ * `embedded` mode with a public key and a registered tokenizer. In every other
63
+ * case the order carries no instrument and the checkout follows the PSP's
64
+ * redirect — which is the hosted page.
65
+ */
66
+ export function pspNeedsCardField(option: PaymentOption | null | undefined, providers: Record<string, PspCheckoutProvider> | undefined): boolean {
67
+ const name = option?.checkout?.provider ?? option?.provider;
68
+ const provider = pspProviderFor(option, providers);
69
+ if (!name || !provider || pspCheckoutMode(provider) !== "embedded" || !pspPublicKey(provider)) {
70
+ return false;
71
+ }
72
+ return Boolean(pspTokenizerFor(name));
73
+ }
74
+
75
+ /** Whether a field that cannot be used (mount or tokenize failed) may give way to the hosted page. */
76
+ export function pspFallsBackToHosted(provider: PspCheckoutProvider | undefined): boolean {
77
+ return provider?.hostedFallback === true;
78
+ }
79
+
80
+ /**
81
+ * The instrument as it travels in the order: a provider instrument
82
+ * (`{ type: "<provider>_<kind>", …fields }`), the legacy single-use token, or
83
+ * nothing — and nothing is the hosted page, not an error. Only string fields
84
+ * travel, and an instrument without a `type` is no instrument.
85
+ */
86
+ export function pspPaymentInstrument(result: PspInstrument | null | undefined): PspInstrument | null {
87
+ if (!result) {
88
+ return null;
89
+ }
90
+ const out: PspInstrument = {};
91
+ if (typeof result.token === "string" && result.token) {
92
+ out.token = result.token;
93
+ }
94
+ const raw = result.instrument;
95
+ if (raw && typeof raw === "object" && typeof raw.type === "string" && raw.type) {
96
+ out.instrument = Object.fromEntries(Object.entries(raw).filter(([, v]) => typeof v === "string" && v !== ""));
97
+ }
98
+ return out.token || out.instrument ? out : null;
99
+ }
@@ -1,4 +1,4 @@
1
- import type { PspMountContext, PspTokenizer } from "./types";
1
+ import { PspInputError, type PspMountContext, type PspTokenizer } from "./types";
2
2
 
3
3
  /**
4
4
  * Stripe tokenizer — loads Stripe.js (no npm dep; the CDN script is the
@@ -10,7 +10,7 @@ interface StripeCardElement { mount: (el: HTMLElement) => void; unmount: () => v
10
10
  interface StripeElements { create: (type: string, options?: unknown) => StripeCardElement }
11
11
  interface StripeInstance {
12
12
  elements: (options?: unknown) => StripeElements;
13
- createPaymentMethod: (params: unknown) => Promise<{ paymentMethod?: { id: string }; error?: { message: string } }>;
13
+ createPaymentMethod: (params: unknown) => Promise<{ paymentMethod?: { id: string }; error?: { message: string; type?: string } }>;
14
14
  }
15
15
  type StripeCtor = (key: string) => StripeInstance;
16
16
 
@@ -56,6 +56,10 @@ export function createStripeTokenizer(): PspTokenizer {
56
56
  }
57
57
  const { paymentMethod, error } = await stripe.createPaymentMethod({ type: "card", card });
58
58
  if (error || !paymentMethod) {
59
+ // Stripe's card and validation errors are the buyer's to correct.
60
+ if (error && (error.type === "card_error" || error.type === "validation_error")) {
61
+ throw new PspInputError(error.message);
62
+ }
59
63
  throw new Error(error?.message ?? "could not tokenize card");
60
64
  }
61
65
  return { token: paymentMethod.id };
@@ -3,27 +3,93 @@
3
3
  * sensitive instrument) data through the PSP's own secure field and turns it
4
4
  * into a single-use token — the raw data never touches our servers (PCI-safe).
5
5
  *
6
- * One implementation per PSP that needs inline collection (Stripe → Elements).
7
- * PSPs that only redirect need NO tokenizer — the generic next_action/redirect
8
- * handler covers them. Add Novalnet/Mollie by adding a factory to the registry.
6
+ * One implementation per PSP that needs inline collection (Stripe → Elements,
7
+ * Novalnet → its card iframe). PSPs that only redirect need NO tokenizer — the
8
+ * generic next_action/redirect handler covers them. Add one by adding a factory
9
+ * to the registry.
9
10
  */
11
+
12
+ /** Who pays, as far as a card field may prefill or check it (all optional). */
13
+ export interface PspMountCustomer {
14
+ firstName?: string;
15
+ lastName?: string;
16
+ email?: string;
17
+ billing?: {
18
+ street?: string;
19
+ city?: string;
20
+ zip?: string;
21
+ /** ISO 3166-1 alpha-2. */
22
+ countryCode?: string;
23
+ };
24
+ }
25
+
10
26
  export interface PspMountContext {
11
- /** Public/publishable key for the PSP (from /api/payment/psp-config). */
27
+ /**
28
+ * Public key for the PSP (from /api/payment/psp-config): Stripe's
29
+ * publishable key, Novalnet's client key.
30
+ */
12
31
  publishableKey: string;
13
32
  testMode: boolean;
14
33
  /** Element the PSP mounts its secure card field into. */
15
34
  el: HTMLElement;
16
35
  /** UI locale, e.g. "de" / "en". */
17
36
  locale?: string;
37
+ /**
38
+ * What the buyer is about to pay, in major units (e.g. 119.5). Informational
39
+ * for the field (Novalnet's 3-D Secure check reads it); the charge itself is
40
+ * always the server's total. Optional — Stripe ignores it.
41
+ */
42
+ amount?: number;
43
+ /** ISO 4217, with `amount`. */
44
+ currency?: string;
45
+ /** Optional prefill (card holder name, 3-D Secure data). */
46
+ customer?: PspMountCustomer;
47
+ }
48
+
49
+ /**
50
+ * What a tokenizer hands the order: a single-use token (Stripe `pm_…`), a
51
+ * provider instrument (Novalnet `{ type: "novalnet_card", pan_hash, unique_id }`),
52
+ * or neither. Neither means "no instrument from the field — take the provider's
53
+ * hosted page": the order is placed without one and the buyer is redirected.
54
+ */
55
+ export interface PspInstrument {
56
+ token?: string;
57
+ instrument?: Record<string, string>;
18
58
  }
19
59
 
20
60
  export interface PspTokenizer {
21
61
  /** Mount the secure field into `ctx.el`; resolves once it is ready. */
22
62
  mount: (ctx: PspMountContext) => Promise<void>;
23
- /** Produce a single-use token (e.g. Stripe `pm_…`) from the mounted field. */
24
- tokenize: () => Promise<{ token: string }>;
63
+ /** Produce the single-use token or instrument from the mounted field. */
64
+ tokenize: () => Promise<PspInstrument>;
25
65
  /** Tear the field down (on unmount / method change). */
26
66
  destroy: () => void;
27
67
  }
28
68
 
29
69
  export type PspTokenizerFactory = () => PspTokenizer;
70
+
71
+
72
+
73
+ /**
74
+ * A card the buyer has to correct (an invalid number, an expired date) — shown
75
+ * at the field, never a reason to leave for the hosted page. A tokenizer throws
76
+ * this for the buyer's own input; anything else it throws is the field failing.
77
+ */
78
+ export class PspInputError extends Error {
79
+ constructor(message: string) {
80
+ super(message);
81
+ this.name = "PspInputError";
82
+ }
83
+ }
84
+
85
+ /**
86
+ * The card field cannot be used and the provider has no hosted page to fall
87
+ * back to. The order is not placed; the buyer is told the card field is
88
+ * unavailable and may choose another method.
89
+ */
90
+ export class PspFieldUnavailableError extends Error {
91
+ constructor(message = "card field unavailable") {
92
+ super(message);
93
+ this.name = "PspFieldUnavailableError";
94
+ }
95
+ }
@@ -0,0 +1,47 @@
1
+ import { isEditorContext } from "../shared/themeEvents";
2
+
3
+ /**
4
+ * Captures where a visit came from (RAD-293): on the first page and on every
5
+ * later one that carries a campaign, whenever the cookie choice changes, and
6
+ * once more when the first article goes into a cart that did not exist when
7
+ * the visitor landed. The editor and previews are no visit.
8
+ */
9
+ export default defineNuxtPlugin({
10
+ name: "cover:campaign-attribution",
11
+ setup(nuxtApp) {
12
+ const route = useRoute();
13
+ if (isEditorContext({ path: route.path, host: window.location.host, query: route.query })) {
14
+ return;
15
+ }
16
+ const attribution = useCampaignAttribution();
17
+ const router = useRouter();
18
+ const cart = useCartStore();
19
+
20
+ let first = true;
21
+ const run = (): void => {
22
+ // Only the landing has a referrer of its own; a later page was
23
+ // reached from this shop.
24
+ const referrer = first ? document.referrer || null : null;
25
+ first = false;
26
+ void attribution.capture(new URL(window.location.href), referrer);
27
+ };
28
+
29
+ nuxtApp.hook("app:mounted", run);
30
+ router.afterEach((to, from) => {
31
+ if (!first && to.fullPath !== from.fullPath) {
32
+ run();
33
+ }
34
+ });
35
+
36
+ const provider = nuxtApp.$consentProvider as { onChange?: (cb: () => void) => () => void } | undefined;
37
+ provider?.onChange?.(() => {
38
+ void attribution.consentChanged();
39
+ });
40
+
41
+ watch(() => cart.items.length, (now, before) => {
42
+ if (before === 0 && now > 0) {
43
+ void attribution.syncToCart();
44
+ }
45
+ });
46
+ },
47
+ });