@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
@@ -1,4 +1,4 @@
1
- import { Collection } from "@revenexx/sdk";
1
+ import { Collection, RevenexxException } from "@revenexx/sdk";
2
2
 
3
3
  import type { ProductCategory, ProductSubcategory } from "../../app/config/navigation";
4
4
  import type { Product } from "../../app/composables/useProducts";
@@ -144,6 +144,8 @@ interface LiveProductAssetRow {
144
144
  /** The storage service's view of an uploaded file. */
145
145
  interface LiveStorageAsset {
146
146
  kind?: string | null;
147
+ mime_type?: string | null;
148
+ url?: string | null;
147
149
  model_url?: string | null;
148
150
  preview_url?: string | null;
149
151
  }
@@ -162,29 +164,105 @@ function storageUrlToCdnSrc(url: string): string {
162
164
 
163
165
  type LiveProductModel = { url: string; poster: string | null };
164
166
 
165
- const MODEL_TTL_MS = 5 * 60 * 1000;
167
+ /** How long a media answer (file, model, gallery) is kept. */
168
+ const MEDIA_TTL_MS = 5 * 60 * 1000;
169
+ /** Entries per media cache; one per product or media code, so a cap matters on big catalogues. */
170
+ const MEDIA_CACHE_MAX = 2000;
171
+
172
+ type Timed = { loadedAt: number };
173
+
174
+ /** A fresh entry, or `undefined`; an expired entry is dropped on the way. */
175
+ function mediaCacheGet<T extends Timed>(cache: Map<string, T>, key: string): T | undefined {
176
+ const entry = cache.get(key);
177
+ if (entry && Date.now() - entry.loadedAt >= MEDIA_TTL_MS) {
178
+ cache.delete(key);
179
+ return undefined;
180
+ }
181
+ return entry;
182
+ }
183
+
184
+ /** Stores an entry; when full, drops the expired ones, then the oldest. */
185
+ function mediaCacheSet<T extends Timed>(cache: Map<string, T>, key: string, entry: T): void {
186
+ cache.delete(key);
187
+ if (cache.size >= MEDIA_CACHE_MAX) {
188
+ const now = Date.now();
189
+ for (const [k, v] of cache) {
190
+ if (now - v.loadedAt >= MEDIA_TTL_MS) {
191
+ cache.delete(k);
192
+ }
193
+ }
194
+ // Map keeps insertion order, so the first key is the oldest.
195
+ while (cache.size >= MEDIA_CACHE_MAX) {
196
+ cache.delete(cache.keys().next().value as string);
197
+ }
198
+ }
199
+ cache.set(key, entry);
200
+ }
201
+
166
202
  const modelCache = new Map<string, { model: LiveProductModel | null; loadedAt: number }>();
203
+ const assetFileCache = new Map<string, { file: Promise<LiveStorageAsset | null>; loadedAt: number }>();
167
204
 
168
205
  /**
169
- * One media code's 3D model, or `null`: not a product asset, not in storage,
170
- * or not a model. `undefined` when the lookup failed — a deleted file must not
171
- * cost the product's other media, and a failure must not be cached as "none".
206
+ * One media code's file in storage, or `null` when the code is not a product
207
+ * asset or the asset names no file. Throws when a lookup fails; callers decide
208
+ * what a failure costs.
209
+ *
210
+ * The gallery and the 3D model both read every media code of a product page,
211
+ * so the lookup is shared: kept per tenant and code (the pending promise too,
212
+ * so two callers at once make one request). A failure is not kept.
172
213
  */
173
- async function liveAssetModel(code: string): Promise<LiveProductModel | null | undefined> {
214
+ function liveAssetFile(code: string): Promise<LiveStorageAsset | null> {
215
+ const key = `${revenexxTenantKey()}:${code}`;
216
+ const cached = mediaCacheGet(assetFileCache, key);
217
+ if (cached) {
218
+ return cached.file;
219
+ }
220
+ const file = fetchLiveAssetFile(code);
221
+ const entry = { file, loadedAt: Date.now() };
222
+ mediaCacheSet(assetFileCache, key, entry);
223
+ file.catch(() => {
224
+ if (assetFileCache.get(key) === entry) {
225
+ assetFileCache.delete(key);
226
+ }
227
+ });
228
+ return file;
229
+ }
230
+
231
+ async function fetchLiveAssetFile(code: string): Promise<LiveStorageAsset | null> {
174
232
  const sdk = useRevenexxSdk();
233
+ const assets = await sdk.call<{ items?: LiveProductAssetRow[] }>(
234
+ "GET", "/v1/products/assets", { query: { code, limit: 1 } },
235
+ );
236
+ const asset = assets.items?.[0];
237
+ if (!asset?.storage_asset_id) {
238
+ return null;
239
+ }
240
+ let file: LiveStorageAsset | { data?: LiveStorageAsset };
175
241
  try {
176
- const assets = await sdk.call<{ items?: LiveProductAssetRow[] }>(
177
- "GET", "/v1/products/assets", { query: { code, limit: 1 } },
242
+ file = await sdk.call<LiveStorageAsset | { data?: LiveStorageAsset }>(
243
+ "GET", `/v1/storage/assets/${encodeURIComponent(asset.storage_asset_id)}`,
178
244
  );
179
- const asset = assets.items?.[0];
180
- if (!asset?.storage_asset_id) {
245
+ }
246
+ catch (err) {
247
+ // A deleted file stays deleted: "no file", kept like any answer, not a
248
+ // failure retried (and warned about) on every page view.
249
+ if (err instanceof RevenexxException && err.code === 404) {
181
250
  return null;
182
251
  }
183
- const file = await sdk.call<LiveStorageAsset | { data?: LiveStorageAsset }>(
184
- "GET", `/v1/storage/assets/${encodeURIComponent(asset.storage_asset_id)}`,
185
- );
186
- const stored: LiveStorageAsset = "data" in file && file.data ? file.data : file as LiveStorageAsset;
187
- if (stored.kind !== "model3d" || !stored.model_url) {
252
+ throw err;
253
+ }
254
+ return "data" in file && file.data ? file.data : file as LiveStorageAsset;
255
+ }
256
+
257
+ /**
258
+ * One media code's 3D model, or `null`: not a product asset, not in storage,
259
+ * or not a model. `undefined` when the lookup failed — a deleted file must not
260
+ * cost the product's other media, and a failure must not be cached as "none".
261
+ */
262
+ async function liveAssetModel(code: string): Promise<LiveProductModel | null | undefined> {
263
+ try {
264
+ const stored = await liveAssetFile(code);
265
+ if (!stored || stored.kind !== "model3d" || !stored.model_url) {
188
266
  return null;
189
267
  }
190
268
  return {
@@ -198,6 +276,18 @@ async function liveAssetModel(code: string): Promise<LiveProductModel | null | u
198
276
  }
199
277
  }
200
278
 
279
+ /**
280
+ * The codes in a product's `asset_collection` attributes, in the order the
281
+ * attributes are declared.
282
+ */
283
+ async function liveMediaCodes(attrs: Record<string, unknown>): Promise<string[]> {
284
+ const meta = await loadLiveAttributeMeta();
285
+ return Object.entries(attrs)
286
+ .filter(([key, value]) => meta[key]?.type === "asset_collection" && Array.isArray(value))
287
+ .sort(([a], [b]) => (meta[a]?.position ?? 999) - (meta[b]?.position ?? 999))
288
+ .flatMap(([, value]) => (value as unknown[]).filter((code): code is string => typeof code === "string" && code !== ""));
289
+ }
290
+
201
291
  /**
202
292
  * The product's 3D model, from its own media: the codes in its
203
293
  * `asset_collection` attributes name product assets, a product asset names
@@ -212,18 +302,14 @@ async function liveAssetModel(code: string): Promise<LiveProductModel | null | u
212
302
  export async function resolveLiveProductModel(
213
303
  attrs: Record<string, unknown>,
214
304
  ): Promise<LiveProductModel | null> {
215
- const meta = await loadLiveAttributeMeta();
216
- const codes = Object.entries(attrs)
217
- .filter(([key, value]) => meta[key]?.type === "asset_collection" && Array.isArray(value))
218
- .sort(([a], [b]) => (meta[a]?.position ?? 999) - (meta[b]?.position ?? 999))
219
- .flatMap(([, value]) => (value as unknown[]).filter((code): code is string => typeof code === "string" && code !== ""));
305
+ const codes = await liveMediaCodes(attrs);
220
306
  if (!codes.length) {
221
307
  return null;
222
308
  }
223
309
 
224
310
  const key = `${revenexxTenantKey()}:${codes.join("|")}`;
225
- const cached = modelCache.get(key);
226
- if (cached && Date.now() - cached.loadedAt < MODEL_TTL_MS) {
311
+ const cached = mediaCacheGet(modelCache, key);
312
+ if (cached) {
227
313
  return cached.model;
228
314
  }
229
315
  const found = await Promise.all(codes.map(code => liveAssetModel(code)));
@@ -231,11 +317,63 @@ export async function resolveLiveProductModel(
231
317
  // A model found is kept; "none" only when every lookup answered, so a
232
318
  // passing outage does not hide the 3D view for the whole TTL.
233
319
  if (model || !found.includes(undefined)) {
234
- modelCache.set(key, { model, loadedAt: Date.now() });
320
+ mediaCacheSet(modelCache, key, { model, loadedAt: Date.now() });
235
321
  }
236
322
  return model;
237
323
  }
238
324
 
325
+ const galleryCache = new Map<string, { srcs: string[]; loadedAt: number }>();
326
+
327
+ /**
328
+ * Picture formats a browser shows. Anything else stays out of the gallery:
329
+ * SVG drawings, and print masters (TIFF, PSD, HEIC) that would be broken tiles.
330
+ */
331
+ const GALLERY_MIME_TYPES = new Set(["image/jpeg", "image/png", "image/webp", "image/gif", "image/avif"]);
332
+
333
+ /**
334
+ * One media code's picture src, `null` when the file is not a picture a
335
+ * browser shows (PDF, SVG drawing, STEP, TIFF), `undefined` when the lookup failed.
336
+ */
337
+ async function liveAssetImage(code: string): Promise<string | null | undefined> {
338
+ try {
339
+ const stored = await liveAssetFile(code);
340
+ if (!stored || stored.kind !== "image" || !stored.url || !GALLERY_MIME_TYPES.has(stored.mime_type ?? "")) {
341
+ return null;
342
+ }
343
+ return storageUrlToCdnSrc(stored.url);
344
+ }
345
+ catch (err) {
346
+ getLogService().warn("Live gallery lookup failed for one asset", { code, ...toErrorContext(err) });
347
+ return undefined;
348
+ }
349
+ }
350
+
351
+ /**
352
+ * The product's pictures from its own media: the codes in its
353
+ * `asset_collection` attributes name product assets, a product asset names its
354
+ * file in storage; only image files are kept, in the order the attributes are
355
+ * declared. Looked up side by side and kept for a few minutes per tenant and
356
+ * set of codes, like the 3D model; a failed lookup is not cached.
357
+ */
358
+ export async function resolveLiveProductGallery(attrs: Record<string, unknown>): Promise<string[]> {
359
+ const codes = await liveMediaCodes(attrs);
360
+ if (!codes.length) {
361
+ return [];
362
+ }
363
+
364
+ const key = `${revenexxTenantKey()}:${codes.join("|")}`;
365
+ const cached = mediaCacheGet(galleryCache, key);
366
+ if (cached) {
367
+ return cached.srcs;
368
+ }
369
+ const found = await Promise.all(codes.map(code => liveAssetImage(code)));
370
+ const srcs = found.filter((src): src is string => typeof src === "string");
371
+ if (!found.includes(undefined)) {
372
+ mediaCacheSet(galleryCache, key, { srcs, loadedAt: Date.now() });
373
+ }
374
+ return srcs;
375
+ }
376
+
239
377
  /** Fallback attribute code holding a manufacturer's logo on the product doc. */
240
378
  const DEFAULT_LOGO_ATTRIBUTE = "manufacturer_logo";
241
379
 
@@ -434,8 +572,63 @@ export function mapLiveDocToProduct(doc: LiveProductDoc): Product {
434
572
  };
435
573
  }
436
574
 
575
+ /** A src without query or fragment and with its path decoded, for comparing only. */
576
+ function gallerySrcKey(src: string): string {
577
+ // An absolute storage URL becomes the `/cdn/` path a gallery src has.
578
+ if (/^https?:\/\//.test(src)) {
579
+ try {
580
+ src = storageUrlToCdnSrc(src);
581
+ }
582
+ catch {
583
+ // Not a parsable URL: compare as written.
584
+ }
585
+ }
586
+ const path = src.split(/[?#]/, 1)[0] ?? src;
587
+ try {
588
+ return decodeURIComponent(path);
589
+ }
590
+ catch {
591
+ // A stray `%` that is no escape: compare as written.
592
+ return path;
593
+ }
594
+ }
595
+
596
+ async function liveGalleryImages(attrs: Record<string, unknown>): Promise<ProductDetail["images"]> {
597
+ const main = typeof attrs.image === "string" && attrs.image ? liveImageSrc(attrs.image) : "";
598
+ let extra: string[] = [];
599
+ // Nothing to look up (and no attribute definitions to fetch) without a list.
600
+ const hasLists = Object.values(attrs).some(value => Array.isArray(value) && value.length > 0);
601
+ try {
602
+ extra = hasLists ? await resolveLiveProductGallery(attrs) : [];
603
+ }
604
+ catch (err) {
605
+ // A media hiccup costs the extra pictures, not the product page.
606
+ getLogService().warn("Live gallery lookup failed", toErrorContext(err));
607
+ }
608
+ // One picture once: the `image` attribute is a raw storage key or a storage
609
+ // URL, a gallery src comes from a storage URL (percent-encoded path, maybe a
610
+ // query), so they are compared in one plain form, and the first src seen is
611
+ // kept. The shown src stays as resolved.
612
+ const seen = new Set<string>();
613
+ const srcs = [...(main ? [main] : []), ...extra].filter((src) => {
614
+ const plain = gallerySrcKey(src);
615
+ if (seen.has(plain)) {
616
+ return false;
617
+ }
618
+ seen.add(plain);
619
+ return true;
620
+ });
621
+ // All "main": the product page's gallery shows every image of that type.
622
+ return srcs.map((url, index) => ({ type: "main", priority: index, url }));
623
+ }
624
+
437
625
  export async function mapLiveDocToDetail(doc: LiveProductDoc, locale: Locale = "de"): Promise<ProductDetail> {
438
626
  const syncedAt = doc.updated_at ? new Date(doc.updated_at * 1000).toISOString() : new Date().toISOString();
627
+ // Independent of each other, so side by side.
628
+ const [images, attributes] = await Promise.all([
629
+ liveGalleryImages(doc.attrs ?? {}),
630
+ buildSpecRows(doc.attrs ?? {}, doc.attrs_locale ?? {}, locale),
631
+ ]);
439
632
 
440
633
  return {
441
634
  product: [{
@@ -461,19 +654,16 @@ export async function mapLiveDocToDetail(doc: LiveProductDoc, locale: Locale = "
461
654
  ...(doc.category_labels?.[0] ? [{ type: "main", name: doc.category_labels[0] }] : []),
462
655
  ...(doc.categories?.[0] ? [{ type: "slug", name: doc.categories[0] }] : []),
463
656
  ],
464
- // Seed the gallery from the product's `image` common attribute (same
465
- // source, and same src resolution, as the catalog shell). The live index
466
- // has no multi-image gallery yet, so this is the single main image
467
- // (empty when none is declared).
468
- images: typeof doc.attrs?.image === "string" && doc.attrs.image
469
- ? [{ type: "main", priority: 0, url: liveImageSrc(doc.attrs.image) }]
470
- : [],
657
+ // The `image` common attribute first (same source, and same src
658
+ // resolution, as the catalog shell), then the pictures of the product's
659
+ // asset collections. Empty when none is declared.
660
+ images,
471
661
  // Specifications: the `attrs` catch-all holds the product's common
472
662
  // attributes as raw key→value. Resolve each through the products app's
473
663
  // attribute definitions so the storefront shows the localized LABEL
474
664
  // (never the technical code), select values as their option label, a
475
665
  // unit suffix where declared, and hides internal/media keys (e.g. image).
476
- attributes: await buildSpecRows(doc.attrs ?? {}, doc.attrs_locale ?? {}, locale),
666
+ attributes,
477
667
  prices: [],
478
668
  };
479
669
  }
@@ -898,6 +1088,17 @@ export interface LiveAttributeMeta {
898
1088
 
899
1089
  const ATTR_META_TTL_MS = 5 * 60 * 1000;
900
1090
  const attrMetaCache = new Map<string, { meta: Record<string, LiveAttributeMeta>; loadedAt: number }>();
1091
+ /** Loads in flight per tenant; removed when they settle, so a failure is retried. */
1092
+ const attrMetaPending = new Map<string, Promise<Record<string, LiveAttributeMeta>>>();
1093
+
1094
+ /** Empties the attribute and media caches. For tests, which share this module. */
1095
+ export function resetLiveMediaCaches(): void {
1096
+ attrMetaCache.clear();
1097
+ attrMetaPending.clear();
1098
+ assetFileCache.clear();
1099
+ modelCache.clear();
1100
+ galleryCache.clear();
1101
+ }
901
1102
 
902
1103
  /** Specs ordered by attribute group, then declared position. */
903
1104
  const SPEC_GROUP_RANK: Record<string, number> = { general: 0, technical: 1 };
@@ -927,7 +1128,19 @@ export async function loadLiveAttributeMeta(): Promise<Record<string, LiveAttrib
927
1128
  if (cached && Date.now() - cached.loadedAt < ATTR_META_TTL_MS) {
928
1129
  return cached.meta;
929
1130
  }
1131
+ // Callers in parallel (gallery, 3D model, spec rows) share one load.
1132
+ const pending = attrMetaPending.get(tenantKey);
1133
+ if (pending) {
1134
+ return pending;
1135
+ }
1136
+ const load = fetchLiveAttributeMeta(tenantKey).finally(() => {
1137
+ attrMetaPending.delete(tenantKey);
1138
+ });
1139
+ attrMetaPending.set(tenantKey, load);
1140
+ return load;
1141
+ }
930
1142
 
1143
+ async function fetchLiveAttributeMeta(tenantKey: string): Promise<Record<string, LiveAttributeMeta>> {
931
1144
  const [groups, attrs, options] = await Promise.all([
932
1145
  listAllProducts<LiveAttributeGroupRow>("/v1/products/attribute_groups"),
933
1146
  listAllProducts<LiveAttributeRow>("/v1/products/attributes"),
@@ -50,6 +50,21 @@ export interface LiveOrder {
50
50
  items?: LiveOrderItem[];
51
51
  shipments?: Array<{ number: string; carrier: string | null; tracking_code: string | null; shipped_at: string }>;
52
52
  returns?: LiveOrderReturn[];
53
+ /** What was taken off the order — `kind: 'rejection'` is an approver's no (orders 3.9). */
54
+ cancellations?: LiveOrderCancellation[];
55
+ /** How a whole-order cancellation ended it, written with the status (orders 3.10). */
56
+ cancellation_kind?: "cancellation" | "rejection" | null;
57
+ cancellation_reason?: string | null;
58
+ cancelled_at?: string | null;
59
+ }
60
+
61
+ export interface LiveOrderCancellation {
62
+ id: string;
63
+ scope: "order" | "items";
64
+ /** Absent on orders apps before 3.9, which could not reject. */
65
+ kind?: "cancellation" | "rejection";
66
+ reason: string | null;
67
+ created_at?: string;
53
68
  }
54
69
 
55
70
  export interface LiveOrderReturn {
@@ -74,7 +89,23 @@ export function sessionOrderRefs(event: H3Event): { contact_id?: string; organiz
74
89
  };
75
90
  }
76
91
 
92
+ /**
93
+ * The approver's no on this order, when it ended that way: the order's own word
94
+ * (orders 3.10, on list rows too), else the record an orders 3.9 wrote.
95
+ */
96
+ function rejectionOf(order: LiveOrder): { reason: string | null; at?: string | null } | undefined {
97
+ if (order.status !== "cancelled") {
98
+ return undefined;
99
+ }
100
+ if (order.cancellation_kind === "rejection") {
101
+ return { reason: order.cancellation_reason ?? null, at: order.cancelled_at };
102
+ }
103
+ const record = order.cancellations?.find(c => c.kind === "rejection");
104
+ return record ? { reason: record.reason, at: record.created_at } : undefined;
105
+ }
106
+
77
107
  function mapStatus(order: LiveOrder): AccountOrderStatus {
108
+ if (rejectionOf(order)) return "rejected";
78
109
  if (order.status === "cancelled") return "cancelled";
79
110
  // Requested rather than placed: waiting for somebody who may approve it.
80
111
  if (order.status === "pending") return "approval-pending";
@@ -154,6 +185,7 @@ export function mapLiveOrderToAccount(order: LiveOrder): AccountOrder {
154
185
  const shipments = order.shipments ?? [];
155
186
  const lastTracked = [...shipments].reverse().find(s => s.tracking_code);
156
187
  const shippedAt = shipments[0]?.shipped_at;
188
+ const rejection = rejectionOf(order);
157
189
 
158
190
  const progress: NonNullable<AccountOrder["progress"]> = [{ step: "ordered", date: day(placed) }];
159
191
  if (order.status !== "pending" && order.status !== "cancelled") {
@@ -176,6 +208,7 @@ export function mapLiveOrderToAccount(order: LiveOrder): AccountOrder {
176
208
  ...(order.customer_order_number ? { orderNumber: order.customer_order_number } : {}),
177
209
  positions: mapPositions(order.items, order.returns),
178
210
  ...(order.returns?.length ? { returns: mapReturns(order.returns) } : {}),
211
+ ...(rejection ? { rejection: { reason: rejection.reason ?? "", ...(rejection.at ? { at: rejection.at } : {}) } } : {}),
179
212
  deliveryAddress: addressLine(order.shipping_address),
180
213
  billingAddress: addressLine(order.billing_address),
181
214
  ...(order.payment?.method ? { paymentMethod: order.payment.method } : {}),
@@ -0,0 +1,63 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { Evidence, IMarketingService } from "../interfaces/marketing";
4
+ import { MarketingTokenError } from "../interfaces/marketing";
5
+ import { ApiMarketingService } from "../services/ApiMarketingService";
6
+ import { MockMarketingService } from "../services/MockMarketingService";
7
+
8
+ /**
9
+ * Registry of the marketing apps' source (RAD-293):
10
+ * - "mock" — demo answers for every marketing page
11
+ * - "api" — marketing-consents, reviews, loyalty, audiences and campaigns
12
+ * through the public revenexx API
13
+ */
14
+ const serviceRegistry: Record<string, IMarketingService> = {
15
+ mock: new MockMarketingService(),
16
+ api: new ApiMarketingService(),
17
+ };
18
+
19
+ export function resolveMarketingServiceKey(event?: H3Event): string {
20
+ return resolveServiceKey(event, {
21
+ domain: "marketingService",
22
+ mockKey: "mock",
23
+ liveKey: "api",
24
+ });
25
+ }
26
+
27
+ export function getMarketingService(event?: H3Event): IMarketingService {
28
+ return serviceRegistry[resolveMarketingServiceKey(event)] ?? serviceRegistry["mock"]!;
29
+ }
30
+
31
+ /**
32
+ * What a consent record keeps as evidence of who confirmed: the address the
33
+ * request came from and the browser it named. The double opt-in is proven by
34
+ * exactly this; marketing-consents deletes the address after its retention.
35
+ */
36
+ export function consentEvidence(event: H3Event, pageUrl?: string | null): Evidence {
37
+ return {
38
+ ip: getRequestIP(event, { xForwardedFor: true }) ?? null,
39
+ user_agent: getHeader(event, "user-agent")?.slice(0, 512) ?? null,
40
+ ...(pageUrl !== undefined ? { page_url: pageUrl } : {}),
41
+ };
42
+ }
43
+
44
+ /** A token as a route received it, or a 404 before anything is asked. */
45
+ export function routeToken(event: H3Event): string {
46
+ const token = getRouterParam(event, "token");
47
+ if (!token || token.length > 256) {
48
+ throw createError({ statusCode: 404, data: { refusal: "unknown" }, message: "Link unknown" });
49
+ }
50
+ return token;
51
+ }
52
+
53
+ /** A refused token as the page reads it: 404 unknown, 410 expired. */
54
+ export function rethrowTokenRefusal(err: unknown): never {
55
+ if (err instanceof MarketingTokenError) {
56
+ throw createError({
57
+ statusCode: err.refusal === "expired" ? 410 : 404,
58
+ data: { refusal: err.refusal },
59
+ message: err.message,
60
+ });
61
+ }
62
+ throw err;
63
+ }
@@ -0,0 +1,65 @@
1
+ import { Orders, RevenexxException } from "@revenexx/sdk";
2
+
3
+ import type { Attribution } from "../../app/shared/campaignAttribution";
4
+ import type { RevenexxSdk } from "./revenexxSdk";
5
+
6
+ /**
7
+ * `POST /v1/orders/place` with the visit's attribution (RAD-293). The orders
8
+ * app takes it from the placement body and never reads the cart for it
9
+ * (orders 3.8.0, RAD-287), so it has to travel with the order.
10
+ *
11
+ * The typed SDK builds the request body from the parameters it knows, and
12
+ * `attribution` is not one of them yet. Rather than rebuild that body by
13
+ * hand — the line, address and payment mapping is the SDK's, and two copies
14
+ * of it would drift — the call is made through the same generated method on
15
+ * a client that adds the one key on its way out.
16
+ *
17
+ * An orders app that refuses the field (one older than 3.8.0, or a value it
18
+ * reads as malformed) answers 400 before anything is placed; the order is
19
+ * then placed again without it. A buyer's order never fails over where they
20
+ * came from.
21
+ */
22
+ const ATTRIBUTION_REFUSALS = new Set(["unknown_attribution_field", "invalid_attribution", "attribution_frozen"]);
23
+
24
+ export function isAttributionRefusal(err: unknown): boolean {
25
+ if (!(err instanceof RevenexxException) || err.code !== 400) {
26
+ return false;
27
+ }
28
+ if (ATTRIBUTION_REFUSALS.has(apiErrorCode(err))) {
29
+ return true;
30
+ }
31
+ return /attribution/i.test(String(err.message ?? ""));
32
+ }
33
+
34
+ type SdkClient = RevenexxSdk["client"];
35
+
36
+ /** The SDK client, adding `extra` to the body of the request it sends. */
37
+ function clientAdding(client: SdkClient, extra: Record<string, unknown>): SdkClient {
38
+ return new Proxy(client, {
39
+ get(target, prop, receiver) {
40
+ if (prop === "call") {
41
+ return (method: string, url: URL, headers: Record<string, string>, payload?: Record<string, unknown>) =>
42
+ target.call(method, url, headers, { ...(payload ?? {}), ...extra } as never);
43
+ }
44
+ const value = Reflect.get(target, prop, receiver);
45
+ return typeof value === "function" ? value.bind(target) : value;
46
+ },
47
+ });
48
+ }
49
+
50
+ export async function placeOrderWithAttribution<T>(submission: unknown, attribution: Attribution | null): Promise<T> {
51
+ const sdk = useRevenexxSdk();
52
+ if (!attribution) {
53
+ return await sdk.orders.ordersPlace(submission as never) as unknown as T;
54
+ }
55
+ try {
56
+ return await new Orders(clientAdding(sdk.client, { attribution }) as never).ordersPlace(submission as never) as unknown as T;
57
+ }
58
+ catch (err) {
59
+ if (!isAttributionRefusal(err)) {
60
+ throw err;
61
+ }
62
+ getLogService().warn("order attribution refused, placed without it", apiErrorContext(err));
63
+ return await sdk.orders.ordersPlace(submission as never) as unknown as T;
64
+ }
65
+ }
@@ -29,11 +29,87 @@ export interface OrderPaymentInput {
29
29
  orderId?: string | null;
30
30
  contactId?: string;
31
31
  idempotencyKey: string;
32
+ /** Legacy single-use token (Stripe `pm_…`). */
32
33
  token?: string;
34
+ /**
35
+ * A PSP instrument from the checkout's card field, sent as-is:
36
+ * `{ type: "<provider>_<kind>", …fields }` (Novalnet: `novalnet_card`,
37
+ * `pan_hash`, `unique_id`). Without one — and without a token — a PSP
38
+ * method goes to the provider's hosted page (FE-5).
39
+ */
40
+ instrument?: Record<string, string>;
33
41
  returnUrl?: string;
42
+ /** Who pays, for the provider's fraud and 3-D Secure checks (RAD-364); handed on, stored nowhere. */
43
+ customer?: PaymentCustomer;
44
+ /** The buyer's language for the provider's page. */
45
+ language?: string;
34
46
  metadata?: Record<string, string>;
35
47
  }
36
48
 
49
+ /** The payments app's `customer` on a create (RAD-364). Every field optional. */
50
+ export interface PaymentCustomer {
51
+ email?: string;
52
+ first_name?: string;
53
+ last_name?: string;
54
+ customer_ip?: string;
55
+ billing?: { street?: string; house_no?: string; city?: string; zip?: string; country_code?: string };
56
+ }
57
+
58
+ /**
59
+ * The storefront keeps street and house number in one line ("Hauptstr. 5a");
60
+ * a provider wants them apart. A trailing number (with a letter or a range)
61
+ * is the house number; a line without one stays the street.
62
+ */
63
+ export function splitStreetLine(line: string): { street: string; house_no?: string } {
64
+ const trimmed = line.trim();
65
+ const match = /^(.*\D)\s+(\d+\s?[a-zA-Z]?(?:\s?[-/]\s?\d+\s?[a-zA-Z]?)?)$/.exec(trimmed);
66
+ return match?.[1] && match[2] ? { street: match[1].trim(), house_no: match[2].replace(/\s+/g, "") } : { street: trimmed };
67
+ }
68
+
69
+ /** The address the order is billed to, as the payments app's customer. */
70
+ export function paymentCustomerOf(input: {
71
+ email?: string | null;
72
+ contactName?: string | null;
73
+ ip?: string | null;
74
+ billing?: { street?: unknown; city?: unknown; postalCode?: unknown; country?: unknown } | null;
75
+ countryCode?: string | null;
76
+ }): PaymentCustomer {
77
+ const str = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
78
+ const [first, ...rest] = str(input.contactName).split(/\s+/).filter(Boolean);
79
+ const streetLine = str(input.billing?.street);
80
+ const { street, house_no } = splitStreetLine(streetLine);
81
+ const billing = {
82
+ ...(street ? { street } : {}),
83
+ ...(house_no ? { house_no } : {}),
84
+ ...(str(input.billing?.city) ? { city: str(input.billing?.city) } : {}),
85
+ ...(str(input.billing?.postalCode) ? { zip: str(input.billing?.postalCode) } : {}),
86
+ ...(input.countryCode ? { country_code: input.countryCode } : {}),
87
+ };
88
+ return {
89
+ ...(str(input.email) ? { email: str(input.email) } : {}),
90
+ ...(first ? { first_name: first } : {}),
91
+ ...(rest.length ? { last_name: rest.join(" ") } : {}),
92
+ ...(str(input.ip) ? { customer_ip: str(input.ip) } : {}),
93
+ ...(Object.keys(billing).length ? { billing } : {}),
94
+ };
95
+ }
96
+
97
+ /**
98
+ * The instrument a browser sent, as far as it may travel: a `type` and string
99
+ * fields, a bounded number of them, nothing nested. Anything else is no
100
+ * instrument — the payments app then answers with its hosted page.
101
+ */
102
+ export function sanitizePaymentInstrument(raw: unknown): Record<string, string> | undefined {
103
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
104
+ return undefined;
105
+ }
106
+ const entries = Object.entries(raw as Record<string, unknown>)
107
+ .filter(([key, value]) => /^[a-z][a-z0-9_]{0,63}$/.test(key) && typeof value === "string" && value !== "" && value.length <= 4096)
108
+ .slice(0, 16) as Array<[string, string]>;
109
+ const instrument = Object.fromEntries(entries);
110
+ return typeof instrument.type === "string" && /^[a-z0-9]+_[a-z0-9_]+$/.test(instrument.type) ? instrument : undefined;
111
+ }
112
+
37
113
  /** The body the payments app is asked to create a payment with. */
38
114
  export function orderPaymentRequest(input: OrderPaymentInput): Record<string, unknown> {
39
115
  return {
@@ -51,7 +127,10 @@ export function orderPaymentRequest(input: OrderPaymentInput): Record<string, un
51
127
  ...(input.contactId ? { contact_id: input.contactId } : {}),
52
128
  idempotency_key: input.idempotencyKey,
53
129
  ...(input.token ? { token: input.token } : {}),
130
+ ...(input.instrument ? { instrument: input.instrument } : {}),
54
131
  ...(input.returnUrl ? { return_url: input.returnUrl } : {}),
132
+ ...(input.customer && Object.keys(input.customer).length ? { customer: input.customer } : {}),
133
+ ...(input.language ? { language: input.language } : {}),
55
134
  metadata: input.metadata ?? {},
56
135
  };
57
136
  }