@revenexx/cover 0.20.0 → 0.21.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 (57) hide show
  1. package/app/components/account/approvals/AccountPendingApprovals.vue +54 -13
  2. package/app/components/account/approvals/AccountPendingOrderDetail.vue +156 -0
  3. package/app/components/account/orders/AccountOrderContents.vue +142 -0
  4. package/app/components/account/orders/AccountOrderDetail.vue +16 -178
  5. package/app/components/account/orders/AccountOrderHead.vue +79 -0
  6. package/app/components/account/orders/AccountOrderPay.vue +13 -3
  7. package/app/components/account/orders/AccountOrdersTable.vue +2 -0
  8. package/app/components/cart/position/CartPosition.vue +6 -6
  9. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +20 -8
  10. package/app/components/checkout/return/CheckoutPaymentReturn.vue +209 -0
  11. package/app/composables/useAccountDashboard.ts +1 -0
  12. package/app/composables/useCheckoutOnePage.ts +71 -7
  13. package/app/composables/usePendingApprovals.ts +11 -3
  14. package/app/composables/usePspCheckout.ts +130 -29
  15. package/app/config/colorRamp.ts +55 -0
  16. package/app/interfaces/account/approvals.ts +34 -1
  17. package/app/interfaces/account/order-list.ts +8 -1
  18. package/app/interfaces/cart-calculation.ts +7 -1
  19. package/app/interfaces/cart-item.ts +12 -0
  20. package/app/interfaces/payment.ts +22 -0
  21. package/app/pages/checkout/payment-return.vue +17 -0
  22. package/app/payments/psp/novalnet.ts +254 -0
  23. package/app/payments/psp/registry.ts +7 -3
  24. package/app/payments/psp/rules.ts +99 -0
  25. package/app/payments/psp/stripe.ts +6 -2
  26. package/app/payments/psp/types.ts +72 -6
  27. package/app/shared/pspReturn.ts +62 -0
  28. package/i18n/locales/de/account.json +17 -3
  29. package/i18n/locales/de/cart.json +4 -2
  30. package/i18n/locales/de/checkout.json +32 -0
  31. package/i18n/locales/de/editor.json +10 -0
  32. package/i18n/locales/en/account.json +17 -3
  33. package/i18n/locales/en/cart.json +4 -2
  34. package/i18n/locales/en/checkout.json +32 -0
  35. package/i18n/locales/en/editor.json +10 -0
  36. package/package.json +3 -2
  37. package/server/api/account/orders/[id]/pay.post.ts +47 -7
  38. package/server/api/account/pending-approvals/index.get.ts +16 -12
  39. package/server/api/account/pending-approvals/orders/[number]/approve.post.ts +6 -0
  40. package/server/api/account/pending-approvals/orders/[number]/reject.post.ts +6 -0
  41. package/server/api/account/pending-approvals/orders/[number].get.ts +15 -0
  42. package/server/api/checkout/payment-return.post.ts +30 -0
  43. package/server/api/orders/index.post.ts +37 -11
  44. package/server/api/payment/methods.post.ts +19 -9
  45. package/server/api/payment/psp-config.get.ts +5 -4
  46. package/server/services/ApiCartService.ts +6 -0
  47. package/server/services/ApiProductService.ts +6 -2
  48. package/server/services/MockCartCalculationService.ts +29 -0
  49. package/server/utils/cartItemHints.ts +29 -0
  50. package/server/utils/checkoutSession.ts +16 -0
  51. package/server/utils/liveCatalog.ts +244 -31
  52. package/server/utils/liveOrders.ts +33 -0
  53. package/server/utils/orderPayment.ts +79 -0
  54. package/server/utils/pendingApprovals.ts +157 -2
  55. package/server/utils/procurementCheckout.ts +5 -0
  56. package/server/utils/pspConfig.ts +125 -13
  57. package/server/utils/pspReturn.ts +267 -0
@@ -1,5 +1,21 @@
1
1
  import { pspTokenizerFor } from "../payments/psp/registry";
2
- import type { PspTokenizer } from "../payments/psp/types";
2
+ import {
3
+ type PspCheckoutProvider,
4
+ pspCheckoutMode,
5
+ pspFallsBackToHosted,
6
+ pspNeedsCardField,
7
+ pspPaymentInstrument,
8
+ pspProviderFor,
9
+ pspPublicKey,
10
+ } from "../payments/psp/rules";
11
+ import {
12
+ PspFieldUnavailableError,
13
+ type PspInstrument,
14
+ PspInputError,
15
+ type PspMountContext,
16
+ type PspTokenizer,
17
+ } from "../payments/psp/types";
18
+ import type { CartCalculation } from "../interfaces/cart-calculation";
3
19
  import type { PaymentOption } from "../interfaces/payment";
4
20
 
5
21
  /**
@@ -11,11 +27,17 @@ import type { PaymentOption } from "../interfaces/payment";
11
27
  */
12
28
 
13
29
  interface PspConfig {
14
- providers: Record<string, { publishableKey: string; testMode: boolean }>;
30
+ providers: Record<string, PspCheckoutProvider>;
15
31
  }
16
32
 
17
- // Client-only imperative handle; never used during SSR.
18
- let active: PspTokenizer | null = null;
33
+ /** What the payment section may tell the field beyond the key — all optional. */
34
+ export type PspMountDetails = Partial<Pick<PspMountContext, "amount" | "currency" | "customer">>;
35
+
36
+ // Client-only imperative handle; never used during SSR. Holds the PSP's config
37
+ // next to its tokenizer so a failed tokenize knows whether it may fall back.
38
+ // `broken`: the field failed to mount and the PSP has no hosted page — the
39
+ // order must not go out without an instrument, so tokenize refuses.
40
+ let active: { tokenizer: PspTokenizer; provider: PspCheckoutProvider; broken?: boolean } | null = null;
19
41
 
20
42
  export function usePspCheckout() {
21
43
  const { locale } = useI18n();
@@ -23,33 +45,80 @@ export function usePspCheckout() {
23
45
  key: "psp-config",
24
46
  default: () => ({ providers: {} }),
25
47
  });
48
+ // The server-calculated totals the summary shows: what the field is told
49
+ // the buyer is about to pay, when the section does not say.
50
+ const calculation = useState<CartCalculation | null>("cart-calculation", () => null);
51
+ /**
52
+ * True when the card field of an embedded-checkout provider could not be
53
+ * used, so the order goes to the provider's hosted page instead.
54
+ */
55
+ const hostedFallback = useState<boolean>("psp-hosted-fallback", () => false);
26
56
 
27
- /** True when this method needs inline tokenization (PSP + registered + has a public key). */
57
+ /** True when this method mounts a card field (PSP in embedded mode, a public key, a registered tokenizer). */
28
58
  function requiresInstrument(option?: PaymentOption | null): boolean {
29
- if (!option || option.kind !== "psp" || !option.provider) {
30
- return false;
31
- }
32
- if (!pspTokenizerFor(option.provider)) {
33
- return false;
34
- }
35
- return Boolean(config.value?.providers[option.provider]?.publishableKey);
59
+ return pspNeedsCardField(option, config.value?.providers);
36
60
  }
37
61
 
38
- /** Mount the PSP's secure field into `el` for the chosen method. */
39
- async function mount(el: HTMLElement, option: PaymentOption): Promise<void> {
62
+ function defaultDetails(): PspMountDetails {
63
+ const total = calculation.value?.totals.find(row => row.key === "total")?.amount;
64
+ return {
65
+ ...(typeof total === "number" ? { amount: total } : {}),
66
+ ...(calculation.value?.currency ? { currency: calculation.value.currency } : {}),
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Mount the PSP's secure field into `el` for the chosen method. `details`
72
+ * (amount, currency, who pays) is optional; without it the field is told
73
+ * the cart's calculated total.
74
+ */
75
+ async function mount(el: HTMLElement, option: PaymentOption, details?: PspMountDetails): Promise<void> {
40
76
  destroy();
41
- const factory = pspTokenizerFor(option.provider);
42
- const pcfg = option.provider ? config.value?.providers[option.provider] : undefined;
43
- if (!factory || !pcfg) {
77
+ const factory = pspTokenizerFor(option.checkout?.provider ?? option.provider);
78
+ const pcfg = pspProviderFor(option, config.value?.providers);
79
+ if (!pcfg || pspCheckoutMode(pcfg) !== "embedded") {
80
+ return;
81
+ }
82
+ const key = pspPublicKey(pcfg);
83
+ if (!factory || !key) {
84
+ // Embedded, but nothing to mount: no tokenizer registered for this
85
+ // PSP, or no key to mount it with. The hosted page takes the card.
86
+ hostedFallback.value = pspFallsBackToHosted(pcfg);
44
87
  return;
45
88
  }
46
- active = factory();
47
- await active.mount({
48
- publishableKey: pcfg.publishableKey,
49
- testMode: pcfg.testMode,
50
- el,
51
- locale: locale.value,
52
- });
89
+ const tokenizer = factory();
90
+ const handle = { tokenizer, provider: pcfg };
91
+ active = handle;
92
+ try {
93
+ await tokenizer.mount({
94
+ publishableKey: key,
95
+ testMode: pcfg.testMode,
96
+ el,
97
+ locale: locale.value,
98
+ ...defaultDetails(),
99
+ ...details,
100
+ });
101
+ }
102
+ catch (err) {
103
+ if (!pspFallsBackToHosted(pcfg)) {
104
+ // No hosted page to fall back to: the field stays the only way,
105
+ // and placing the order is refused until it works or the buyer
106
+ // picks another method.
107
+ tokenizer.destroy();
108
+ if (active === handle) {
109
+ active = { ...handle, broken: true };
110
+ }
111
+ throw err;
112
+ }
113
+ // The field did not come up (script blocked, PSP unreachable): the
114
+ // buyer is not stuck on a dead form — the order goes to the PSP's
115
+ // hosted page, which takes the card there.
116
+ tokenizer.destroy();
117
+ if (active === handle) {
118
+ active = null;
119
+ }
120
+ hostedFallback.value = true;
121
+ }
53
122
  }
54
123
 
55
124
  /** True when a secure field is mounted and a token must be produced on submit. */
@@ -57,15 +126,47 @@ export function usePspCheckout() {
57
126
  return active !== null;
58
127
  }
59
128
 
60
- /** Produce the single-use token from the mounted field (or null if none). */
61
- async function tokenize(): Promise<{ token: string } | null> {
62
- return active ? active.tokenize() : null;
129
+ /**
130
+ * Produce the token or instrument from the mounted field. Null when there is
131
+ * no field, or when the PSP wants the buyer on its hosted page — the order
132
+ * then carries no instrument and the checkout follows the redirect. A field
133
+ * that fails to tokenize does the same where the PSP falls back to hosted —
134
+ * unless the failure is the buyer's input (PspInputError), which stays at the
135
+ * field to be corrected. Where the PSP has no hosted page (embedded only, or
136
+ * the legacy Stripe config) a failing field throws PspFieldUnavailableError
137
+ * and the order is not placed.
138
+ */
139
+ async function tokenize(): Promise<PspInstrument | null> {
140
+ if (!active) {
141
+ return null;
142
+ }
143
+ const { tokenizer, provider, broken } = active;
144
+ if (broken) {
145
+ throw new PspFieldUnavailableError();
146
+ }
147
+ try {
148
+ return pspPaymentInstrument(await tokenizer.tokenize());
149
+ }
150
+ catch (err) {
151
+ // The buyer's own input is theirs to correct at the field; a field
152
+ // that failed gives way to the hosted page where the PSP allows it.
153
+ if (err instanceof PspInputError) {
154
+ throw err;
155
+ }
156
+ if (!pspFallsBackToHosted(provider)) {
157
+ throw new PspFieldUnavailableError(err instanceof Error ? err.message : String(err));
158
+ }
159
+ return null;
160
+ }
63
161
  }
64
162
 
65
163
  function destroy(): void {
66
- active?.destroy();
164
+ if (!active?.broken) {
165
+ active?.tokenizer.destroy();
166
+ }
67
167
  active = null;
168
+ hostedFallback.value = false;
68
169
  }
69
170
 
70
- return { config, requiresInstrument, mount, hasActive, tokenize, destroy };
171
+ return { config, hostedFallback, requiresInstrument, mount, hasActive, tokenize, destroy };
71
172
  }
@@ -0,0 +1,55 @@
1
+ import { COLOR_SHADES } from "./palette";
2
+
3
+ /**
4
+ * Brand ramp: sRGB hex → OKLCH, lightness spread around the brand colour.
5
+ * Pure, so it runs in the browser too (the docs site's theming panel).
6
+ *
7
+ * Same algorithm as generateRamp() in
8
+ * packages/cover-theme/server/utils/tenantStyle.ts, which renders a tenant's
9
+ * brand colour. That copy moves to this module once a @revenexx/cover release
10
+ * ships it: the cover-theme split pins the RELEASED cover version, so
11
+ * importing an unreleased config file would break its standalone build.
12
+ */
13
+
14
+ function hexToOklch(hex: string): [number, number, number] {
15
+ const n = Number.parseInt(hex.slice(1), 16);
16
+ const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((v) => {
17
+ const c = v / 255;
18
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
19
+ }) as [number, number, number];
20
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
21
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
22
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
23
+ const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
24
+ const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
25
+ const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
26
+ return [L, Math.sqrt(A * A + B * B), ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360];
27
+ }
28
+
29
+ /** Distance of each shade from the brand colour at 500 (0 = brand, 1 = the end of the scale). */
30
+ const LIGHTER: Record<number, number> = { 50: 1, 100: 0.9, 200: 0.75, 300: 0.55, 400: 0.3 };
31
+ const DARKER: Record<number, number> = { 600: 0.15, 700: 0.32, 800: 0.5, 900: 0.68, 950: 0.85 };
32
+ const LIGHTEST = 0.975;
33
+ const DARKEST = 0.22;
34
+
35
+ /** A `#rrggbb` brand colour as a 50–950 ramp, the colour itself at 500. */
36
+ export function generateRamp(hex: string): Record<number, string> {
37
+ const [L, C, H] = hexToOklch(hex);
38
+ const oklch = (lightness: number, chroma: number): string =>
39
+ `oklch(${(lightness * 100).toFixed(1)}% ${chroma.toFixed(3)} ${H.toFixed(2)})`;
40
+ const ramp: Record<number, string> = {};
41
+ for (const shade of COLOR_SHADES) {
42
+ const lighter = LIGHTER[shade];
43
+ const darker = DARKER[shade];
44
+ if (lighter !== undefined) {
45
+ ramp[shade] = oklch(L + (Math.max(L, LIGHTEST) - L) * lighter, C * (1 - lighter * 0.85));
46
+ }
47
+ else if (darker !== undefined) {
48
+ ramp[shade] = oklch(L - (L - Math.min(L, DARKEST)) * darker, C * (1 - darker * 0.4));
49
+ }
50
+ else {
51
+ ramp[shade] = hex.toLowerCase();
52
+ }
53
+ }
54
+ return ramp;
55
+ }
@@ -1,3 +1,5 @@
1
+ import type { AccountOrder } from "./order-list";
2
+
1
3
  /**
2
4
  * What is waiting on this approver.
3
5
  *
@@ -7,7 +9,8 @@
7
9
  * requests with no buttons on it — and the deciding happened in the Cockpit, which
8
10
  * is not where a buying organisation works.
9
11
  */
10
- export interface PendingApproval {
12
+ export interface PendingRequestApproval {
13
+ kind: "request";
11
14
  id: string;
12
15
  /** The request this layer belongs to. */
13
16
  requestId: string;
@@ -32,6 +35,36 @@ export interface PendingApproval {
32
35
  at: string;
33
36
  }
34
37
 
38
+ /**
39
+ * An order of a colleague waiting in the orders app (RAD-229).
40
+ *
41
+ * The storefront that places without procurement gets these: a requester's
42
+ * order, or one above the merchant's threshold, comes back pending and waits for
43
+ * somebody of the same company holding the approving permission. One signature
44
+ * settles it — there are no layers.
45
+ */
46
+ export interface PendingOrderApproval {
47
+ kind: "order";
48
+ /** The order number, which is also how its page is addressed. */
49
+ id: string;
50
+ /** Who ordered, as the order's buyer snapshot names them. */
51
+ requestedBy: string | null;
52
+ total: number | null;
53
+ currency: string | null;
54
+ /** When it was placed into the queue. */
55
+ at: string;
56
+ }
57
+
58
+ export type PendingApproval = PendingRequestApproval | PendingOrderApproval;
59
+
60
+ /** One colleague's order, as its approver reads it before deciding. */
61
+ export interface PendingOrderDetail {
62
+ order: AccountOrder;
63
+ requestedBy: string | null;
64
+ /** Whether it still waits — a colleague may have decided it since the queue was drawn. */
65
+ pending: boolean;
66
+ }
67
+
35
68
  export interface PendingApprovalsResponse {
36
69
  approvals: PendingApproval[];
37
70
  }
@@ -3,7 +3,9 @@ export type AccountOrderStatus =
3
3
  | "approval-pending"
4
4
  | "shipped"
5
5
  | "delivered"
6
- | "cancelled";
6
+ | "cancelled"
7
+ /** Cancelled because somebody who may approve said no (RAD-229). */
8
+ | "rejected";
7
9
 
8
10
  export type AccountOrderPaymentStatus = "open" | "paid" | "refunded";
9
11
 
@@ -57,6 +59,11 @@ export interface AccountOrder {
57
59
  readonly progress?: { step: "ordered" | "processing" | "shipped" | "delivered"; date?: string }[];
58
60
  /** Approvers when the order awaits approval. */
59
61
  readonly approvers?: string[];
62
+ /**
63
+ * Why it was not approved, when it was rejected. Who rejected it is left out:
64
+ * the requester's role may not read their colleagues (RAD-229).
65
+ */
66
+ readonly rejection?: { reason: string; at?: string };
60
67
  /** Returns already requested against this order. */
61
68
  readonly returns?: AccountOrderReturn[];
62
69
  /**
@@ -25,7 +25,13 @@ export type CartLineHintType =
25
25
  * because "out of stock" and "this will be left out of your order" ask
26
26
  * different things of the buyer.
27
27
  */
28
- | "not-orderable";
28
+ | "not-orderable"
29
+ /**
30
+ * The line arrived in a unit the article is not sold in, so it was switched
31
+ * to the shop's order unit and the quantity kept (RAD-228) — 10 MTR became
32
+ * 10 ST. Carried on the line as `metadata.hints`; the buyer has to check it.
33
+ */
34
+ | "unit-changed";
29
35
 
30
36
  export interface CartLineHint {
31
37
  type: CartLineHintType;
@@ -9,6 +9,16 @@ export const CART_MAX_QUANTITY = 999999;
9
9
  /** Up to four free-text lines per position. */
10
10
  export const CART_POSITION_TEXT_COUNT = 4;
11
11
 
12
+ /**
13
+ * A note the backend wrote on a cart line (`metadata.hints`), e.g. that the
14
+ * sender's unit was switched to the shop's. Generic on purpose: a new hint is
15
+ * a type and an i18n key in the calculation, not new mapping.
16
+ */
17
+ export interface CartItemHint {
18
+ type: string;
19
+ params?: Record<string, string | number>;
20
+ }
21
+
12
22
  export interface CartItem {
13
23
  /** Product id (ProductList.id) — string, UUID in live mode. */
14
24
  id: string;
@@ -40,6 +50,8 @@ export interface CartItem {
40
50
  nonCatalog?: boolean;
41
51
  /** Set when the position belongs to a loaded requisition. */
42
52
  requisitionId?: string;
53
+ /** Hints the line carries from the backend; rendered by the calculation. */
54
+ hints?: CartItemHint[];
43
55
  categorySlug?: string;
44
56
  subcategorySlug?: string;
45
57
  }
@@ -18,4 +18,26 @@ export interface PaymentOption {
18
18
  kind?: string;
19
19
  /** PSP provider code (e.g. "stripe") for psp methods — drives the FE tokenizer. */
20
20
  provider?: string;
21
+ /**
22
+ * How a PSP method takes the buyer's instrument, as the payments app answers
23
+ * it on every eligible PSP method (RAD-364, FE-5). Absent for self-managed
24
+ * methods, and in demo mode.
25
+ */
26
+ checkout?: PaymentCheckout;
27
+ }
28
+
29
+ export interface PaymentCheckout {
30
+ /** The provider the payment would go to. */
31
+ provider: string;
32
+ /** `embedded` mounts the provider's card field; `hosted` sends the buyer to its page. */
33
+ checkoutMode: "embedded" | "hosted";
34
+ /** The non-secret key the card field needs (Novalnet client key, Stripe publishable key). */
35
+ publicKey: string;
36
+ testMode: boolean;
37
+ /**
38
+ * The modes the provider supports at all (Novalnet hosted + embedded, Stripe
39
+ * embedded only). Absent from an older payments app — then a field that
40
+ * cannot be used still gives way to the hosted page, as before.
41
+ */
42
+ checkoutModes?: Array<"embedded" | "hosted">;
21
43
  }
@@ -0,0 +1,17 @@
1
+ <script setup lang="ts">
2
+ import CheckoutPaymentReturn from "../../components/checkout/return/CheckoutPaymentReturn.vue";
3
+
4
+ /**
5
+ * /checkout/payment-return — where every payment provider returns the buyer
6
+ * (FE-5). Shipped by the layer, so every storefront has it: the BFF builds the
7
+ * return address to this route on its own host, whichever theme renders it.
8
+ */
9
+ definePageMeta({ layout: "focus" });
10
+
11
+ const { t } = useI18n();
12
+ useHead({ title: () => t("paymentReturn.title"), meta: [{ name: "robots", content: "noindex,nofollow" }] });
13
+ </script>
14
+
15
+ <template>
16
+ <CheckoutPaymentReturn />
17
+ </template>
@@ -0,0 +1,254 @@
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
+ * `do_redirect` in the iframe's answer means the card needs 3-D Secure. It is
12
+ * not a request for the hosted page: the pan hash is still the instrument, the
13
+ * payment is created with it, and Novalnet answers a `redirect_url` to the
14
+ * 3-D Secure step only. Dropping the hash there sent the buyer to the full
15
+ * payment page to type the card a second time.
16
+ */
17
+
18
+ export const NOVALNET_UTILITY_JS = "https://cdn.novalnet.de/js/v2/NovalnetUtility-1.1.2.js";
19
+ // Subresource integrity of the pinned version (sha384 of the file Novalnet
20
+ // serves). A changed file fails to load, and the checkout falls back to the
21
+ // hosted payment page rather than running code nobody reviewed.
22
+ export const NOVALNET_UTILITY_SRI = "sha384-wRpaQDgV62dqZ/HthwD84Gs9Mgxg5u5PrND0zS9L5rjOdWE8nTDLq+fdsCxbnj6K";
23
+
24
+ /** How long the iframe may take to answer a hash request before it counts as failed. */
25
+ const TOKENIZE_TIMEOUT_MS = 30_000;
26
+ /** How long the card form may take to appear before the checkout falls back. */
27
+ const MOUNT_TIMEOUT_MS = 20_000;
28
+
29
+ interface NovalnetHashAnswer {
30
+ hash?: string;
31
+ pan_hash?: string;
32
+ unique_id?: string;
33
+ do_redirect?: number | string | boolean;
34
+ error_message?: string;
35
+ }
36
+
37
+ interface NovalnetFormConfig {
38
+ callback: {
39
+ on_success: (data: NovalnetHashAnswer) => boolean | void;
40
+ on_error: (data: NovalnetHashAnswer) => boolean | void;
41
+ on_show_overlay?: () => void;
42
+ on_hide_overlay?: () => void;
43
+ };
44
+ iframe: { id: string; inline: number; style?: Record<string, string> };
45
+ customer?: Record<string, unknown>;
46
+ transaction?: Record<string, unknown>;
47
+ custom?: { lang?: string };
48
+ }
49
+
50
+ export interface NovalnetUtilityApi {
51
+ setClientKey: (key: string) => boolean;
52
+ createCreditCardForm: (config: NovalnetFormConfig) => unknown;
53
+ getPanHash: () => unknown;
54
+ /** The library keeps its callbacks on itself and reads them on every message. */
55
+ on_success?: unknown;
56
+ on_error?: unknown;
57
+ }
58
+
59
+ function loadNovalnetUtility(): Promise<NovalnetUtilityApi> {
60
+ const w = window as unknown as { NovalnetUtility?: NovalnetUtilityApi };
61
+ if (w.NovalnetUtility) {
62
+ return Promise.resolve(w.NovalnetUtility);
63
+ }
64
+ return new Promise((resolve, reject) => {
65
+ const onload = () => w.NovalnetUtility
66
+ ? resolve(w.NovalnetUtility)
67
+ : reject(new Error("NovalnetUtility loaded but missing"));
68
+ const onerror = () => reject(new Error("failed to load NovalnetUtility"));
69
+ const existing = document.querySelector<HTMLScriptElement>(`script[src="${NOVALNET_UTILITY_JS}"]`);
70
+ if (existing) {
71
+ existing.addEventListener("load", onload, { once: true });
72
+ existing.addEventListener("error", onerror, { once: true });
73
+ return;
74
+ }
75
+ const script = document.createElement("script");
76
+ script.src = NOVALNET_UTILITY_JS;
77
+ script.integrity = NOVALNET_UTILITY_SRI;
78
+ script.crossOrigin = "anonymous";
79
+ script.async = true;
80
+ script.addEventListener("load", onload, { once: true });
81
+ script.addEventListener("error", onerror, { once: true });
82
+ document.head.appendChild(script);
83
+ });
84
+ }
85
+
86
+ /** Novalnet takes amounts in minor units. */
87
+ export function novalnetAmount(amount: number | undefined): number | undefined {
88
+ if (typeof amount !== "number" || !Number.isFinite(amount) || amount <= 0) {
89
+ return undefined;
90
+ }
91
+ return Math.round(amount * 100);
92
+ }
93
+
94
+ /** The `createCreditCardForm` config for a mount context. Pure, so it can be tested. */
95
+ export function novalnetFormConfig(
96
+ ctx: Pick<PspMountContext, "testMode" | "locale" | "amount" | "currency" | "customer">,
97
+ iframeId: string,
98
+ callback: NovalnetFormConfig["callback"],
99
+ ): NovalnetFormConfig {
100
+ const customer = ctx.customer;
101
+ const billing = customer?.billing;
102
+ const amount = novalnetAmount(ctx.amount);
103
+ const config: NovalnetFormConfig = {
104
+ callback,
105
+ iframe: { id: iframeId, inline: 1 },
106
+ custom: { lang: (ctx.locale ?? "de").slice(0, 2).toUpperCase() },
107
+ transaction: {
108
+ ...(amount !== undefined ? { amount } : {}),
109
+ ...(ctx.currency ? { currency: ctx.currency } : {}),
110
+ // The library drops falsy values, so production sends nothing here.
111
+ ...(ctx.testMode ? { test_mode: 1 } : {}),
112
+ },
113
+ };
114
+ if (customer) {
115
+ config.customer = {
116
+ ...(customer.firstName ? { first_name: customer.firstName } : {}),
117
+ ...(customer.lastName ? { last_name: customer.lastName } : {}),
118
+ ...(customer.email ? { email: customer.email } : {}),
119
+ ...(billing
120
+ ? {
121
+ billing: {
122
+ ...(billing.street ? { street: billing.street } : {}),
123
+ ...(billing.city ? { city: billing.city } : {}),
124
+ ...(billing.zip ? { zip: billing.zip } : {}),
125
+ ...(billing.countryCode ? { country_code: billing.countryCode } : {}),
126
+ },
127
+ }
128
+ : {}),
129
+ };
130
+ }
131
+ return config;
132
+ }
133
+
134
+ /**
135
+ * What the iframe's hash answer becomes for the order: the instrument. A
136
+ * `do_redirect` answer carries one as well (the card needs 3-D Secure, which
137
+ * the payment's redirect takes care of), so it is handed on like any other.
138
+ */
139
+ export function novalnetInstrumentOf(answer: NovalnetHashAnswer): PspInstrument {
140
+ const panHash = answer.hash ?? answer.pan_hash;
141
+ if (!panHash || !answer.unique_id) {
142
+ // Novalnet names what is wrong with the card the buyer typed; without a
143
+ // message the field itself failed.
144
+ throw answer.error_message ? new PspInputError(answer.error_message) : new Error("could not read the card");
145
+ }
146
+ return { instrument: { type: "novalnet_card", pan_hash: panHash, unique_id: answer.unique_id } };
147
+ }
148
+
149
+ let instanceCounter = 0;
150
+
151
+ export function createNovalnetTokenizer(): PspTokenizer {
152
+ let utility: NovalnetUtilityApi | null = null;
153
+ let iframe: HTMLIFrameElement | null = null;
154
+ let pending: { resolve: (v: PspInstrument) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> } | null = null;
155
+
156
+ function settle(fn: (p: NonNullable<typeof pending>) => void) {
157
+ if (!pending) {
158
+ return;
159
+ }
160
+ const p = pending;
161
+ pending = null;
162
+ clearTimeout(p.timer);
163
+ fn(p);
164
+ }
165
+
166
+ const callback: NovalnetFormConfig["callback"] = {
167
+ on_success: (data) => {
168
+ settle((p) => {
169
+ try {
170
+ p.resolve(novalnetInstrumentOf(data));
171
+ }
172
+ catch (err) {
173
+ p.reject(err instanceof Error ? err : new Error(String(err)));
174
+ }
175
+ });
176
+ return true;
177
+ },
178
+ on_error: (data) => {
179
+ // Outside a hash request (a field the buyer left invalid while typing)
180
+ // the iframe shows the message itself; nothing to settle.
181
+ settle(p => p.reject(data?.error_message
182
+ ? new PspInputError(data.error_message)
183
+ : new Error("could not read the card")));
184
+ return false;
185
+ },
186
+ };
187
+
188
+ return {
189
+ async mount(ctx: PspMountContext) {
190
+ utility = await loadNovalnetUtility();
191
+ if (!utility.setClientKey(ctx.publishableKey)) {
192
+ throw new Error("Novalnet client key was refused");
193
+ }
194
+ instanceCounter += 1;
195
+ iframe = document.createElement("iframe");
196
+ iframe.id = `novalnet-card-iframe-${instanceCounter}`;
197
+ iframe.title = "Novalnet";
198
+ iframe.setAttribute("frameborder", "0");
199
+ iframe.setAttribute("scrolling", "no");
200
+ iframe.style.width = "100%";
201
+ iframe.style.border = "0";
202
+ ctx.el.appendChild(iframe);
203
+ const frame = iframe;
204
+ await new Promise<void>((resolve, reject) => {
205
+ const timer = setTimeout(() => finish(new Error("Novalnet card form did not load")), MOUNT_TIMEOUT_MS);
206
+ function finish(err?: Error) {
207
+ clearTimeout(timer);
208
+ frame.removeEventListener("load", onload);
209
+ if (err) {
210
+ reject(err);
211
+ }
212
+ else {
213
+ resolve();
214
+ }
215
+ }
216
+ // The blank document an iframe starts with fires a load of its own;
217
+ // only Novalnet's form counts.
218
+ function onload() {
219
+ if (frame.src.startsWith("https://")) {
220
+ finish();
221
+ }
222
+ }
223
+ frame.addEventListener("load", onload);
224
+ // The library sets the iframe's src and its own onload handler.
225
+ const created = utility!.createCreditCardForm(novalnetFormConfig(ctx, frame.id, callback));
226
+ if (created === false) {
227
+ finish(new Error("Novalnet card form could not be created"));
228
+ }
229
+ });
230
+ },
231
+ tokenize() {
232
+ if (!utility || !iframe) {
233
+ return Promise.reject(new Error("card field is not ready"));
234
+ }
235
+ if (pending) {
236
+ return Promise.reject(new Error("card is already being read"));
237
+ }
238
+ return new Promise<PspInstrument>((resolve, reject) => {
239
+ pending = {
240
+ resolve,
241
+ reject,
242
+ timer: setTimeout(() => settle(p => p.reject(new Error("the card field did not answer"))), TOKENIZE_TIMEOUT_MS),
243
+ };
244
+ utility!.getPanHash();
245
+ });
246
+ },
247
+ destroy() {
248
+ settle(p => p.reject(new Error("card field was removed")));
249
+ iframe?.remove();
250
+ iframe = null;
251
+ utility = null;
252
+ },
253
+ };
254
+ }