@revenexx/cover 0.12.0 → 0.14.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 (49) hide show
  1. package/app/api/product.ts +1 -0
  2. package/app/components/cart/recommend/CartCrossSell.vue +2 -1
  3. package/app/components/layout/header/LocaleSwitcher.vue +18 -1
  4. package/app/components/listing/ListingFilterBar.vue +1 -0
  5. package/app/components/listing/ListingFilterDrawer.vue +1 -0
  6. package/app/components/listing/ListingFilterRail.vue +1 -0
  7. package/app/components/search/filter/SearchFacets.vue +10 -3
  8. package/app/components/search/filter/SearchFacetsBar.vue +7 -3
  9. package/app/components/search/filter/SearchFacetsDrawer.vue +7 -2
  10. package/app/components/ui/forms/SearchInput.vue +4 -1
  11. package/app/composables/useFacetMeta.ts +6 -6
  12. package/app/composables/useProductListing.ts +18 -2
  13. package/app/composables/useProductLocales.ts +56 -0
  14. package/app/composables/useSearchListing.ts +16 -0
  15. package/app/layouts/default.vue +10 -1
  16. package/app/shared/locale.ts +114 -0
  17. package/app/shared/productLocales.ts +109 -0
  18. package/i18n/locales/de/common.json +2 -1
  19. package/i18n/locales/en/common.json +2 -1
  20. package/nuxt.config.ts +22 -0
  21. package/package.json +1 -1
  22. package/server/api/account/quotes/[id]/order.post.ts +14 -3
  23. package/server/api/cart/calculate.post.ts +4 -0
  24. package/server/api/categories/[slug]/subcategories.get.ts +34 -31
  25. package/server/api/orders/index.post.ts +78 -31
  26. package/server/api/payment/psp-config.get.ts +11 -21
  27. package/server/api/product/[id]/locales.get.ts +57 -0
  28. package/server/api/quotes/request.post.ts +2 -2
  29. package/server/api/typesense/search.post.ts +61 -317
  30. package/server/api/typesense/suggest.post.ts +14 -9
  31. package/server/{api/typesense/drop.get.ts → dev/typesense/drop.ts} +2 -1
  32. package/server/{api/typesense/health.get.ts → dev/typesense/health.ts} +1 -0
  33. package/server/dev/typesense/seed.ts +59 -0
  34. package/server/dev/typesense/seedDocuments.ts +105 -0
  35. package/server/interfaces/product.ts +8 -0
  36. package/server/routes/punchout/start.get.ts +40 -3
  37. package/server/services/ApiBrandService.ts +28 -42
  38. package/server/services/ApiProductService.ts +14 -11
  39. package/server/utils/buyerIdentity.ts +11 -0
  40. package/server/utils/liveCatalog.ts +200 -48
  41. package/server/utils/liveListingSearch.ts +201 -0
  42. package/server/utils/livePrices.ts +24 -9
  43. package/server/utils/orderLinePrices.ts +72 -0
  44. package/server/utils/paymentFee.ts +59 -0
  45. package/server/utils/pspConfig.ts +42 -0
  46. package/server/utils/revenexxSdk.ts +25 -2
  47. package/server/utils/searchClient.ts +305 -0
  48. package/server/utils/searchMultiSearchFallback.ts +216 -0
  49. package/server/api/typesense/seed.get.ts +0 -111
@@ -96,8 +96,16 @@ export default defineEventHandler(async (event): Promise<QuoteOrderResult> => {
96
96
  let placed: { id: string; number: string; grand_total?: number };
97
97
  try {
98
98
  placed = await sdk.orders.ordersPlace({
99
- contactId: draft.contact_id ?? actor.contactId,
100
- organizationId: draft.organization_id ?? actor.organizationId,
99
+ // A buyer's call is placed for the buyer the principal names, and the
100
+ // orders app refuses a body that names anybody else (RAD-174) — a
101
+ // colleague's quote included, where the draft carries the colleague.
102
+ // Only a call acting for nobody states who the order is for.
103
+ ...(principalContactId(event)
104
+ ? {}
105
+ : {
106
+ contactId: draft.contact_id ?? actor.contactId,
107
+ organizationId: draft.organization_id ?? actor.organizationId,
108
+ }),
101
109
  currency: draft.currency,
102
110
  ...(body?.customerOrderNumber?.trim() ? { customerOrderNumber: body.customerOrderNumber.trim() } : {}),
103
111
  buyer: (draft.buyer ?? { name: actor.user.name, email: actor.user.email }) as object,
@@ -135,6 +143,7 @@ export default defineEventHandler(async (event): Promise<QuoteOrderResult> => {
135
143
  }
136
144
 
137
145
  if (resolvePaymentServiceKey(event) === "api") {
146
+ const payerContactId = principalContactId(event);
138
147
  try {
139
148
  const payment = await sdk.call<{ id: string; status: string }>("POST", "/v1/payments", {
140
149
  body: {
@@ -143,6 +152,8 @@ export default defineEventHandler(async (event): Promise<QuoteOrderResult> => {
143
152
  currency: draft.currency,
144
153
  country: toIsoCountry(draft.billing_address?.country ?? draft.shipping_address?.country),
145
154
  order_ref: placed.number,
155
+ // The buyer's own payment, listed on their payments page (RAD-171).
156
+ ...(payerContactId ? { contact_id: payerContactId } : {}),
146
157
  idempotency_key: `quote-${quote.id}-${placed.id}`,
147
158
  metadata: { quote_number: quote.number },
148
159
  },
@@ -150,7 +161,7 @@ export default defineEventHandler(async (event): Promise<QuoteOrderResult> => {
150
161
  const mapped = ["captured", "succeeded", "paid"].includes(payment.status)
151
162
  ? OrderPaymentStatus.Paid
152
163
  : payment.status === "authorized" ? OrderPaymentStatus.Authorized : OrderPaymentStatus.Pending;
153
- await sdk.orders.ordersPaymentStatusUpdate({ id: placed.id, status: mapped });
164
+ await useTenantSdk().orders.ordersPaymentStatusUpdate({ id: placed.id, status: mapped });
154
165
  }
155
166
  catch (err) {
156
167
  // An invoice order stands without a captured payment; the payment
@@ -37,6 +37,10 @@ async function resolveOverrides(
37
37
  sku: it.sku ? String(it.sku) : undefined,
38
38
  quantity: Number(it.quantity) || 1,
39
39
  })) as Models.PriceResolveItem[],
40
+ // The signed-in buyer's own prices — contract and organization
41
+ // lists included — not the anonymous ones (RAD-170). The same
42
+ // scope the order is priced under.
43
+ ...priceBuyerContext(event),
40
44
  ...(currency ? { currency } : {}),
41
45
  }) as unknown as { prices: Array<{ product_id: string | null; sku: string | null; tax_rate: number | null; on_request: boolean; unit_price: number | null }> };
42
46
  const itemTaxRates: Record<string, number> = {};
@@ -7,8 +7,6 @@ import {
7
7
  liveSubcategoryIndex,
8
8
  mapLiveDocToProduct,
9
9
  rollUpSubcategoryCounts,
10
- searchLiveProducts,
11
- searchLiveProductsMulti,
12
10
  tsFilterValue,
13
11
  } from "../../../utils/liveCatalog";
14
12
  import { PRODUCTS_COLLECTION } from "../../../utils/productsSchema";
@@ -38,11 +36,15 @@ import { PRODUCTS_COLLECTION } from "../../../utils/productsSchema";
38
36
  const MAX_SUBCATEGORY_VALUES = 250;
39
37
 
40
38
  /**
41
- * Sub-searches per multi_search request. Typesense's `limit_multi_searches`
42
- * defaults to 50; staying under it keeps a category with many children working.
39
+ * Sub-searches per multi_search request against the mock index. Typesense's
40
+ * `limit_multi_searches` defaults to 50; staying under it keeps a category with
41
+ * many children working.
43
42
  */
44
43
  const SEARCH_BATCH_SIZE = 40;
45
44
 
45
+ /** Live image lookups in flight at once — one search per child. */
46
+ const LIVE_IMAGE_CONCURRENCY = 8;
47
+
46
48
  /** Narrowed shape of the mock index's multi_search response. */
47
49
  interface MockMultiSearchResponse {
48
50
  results?: {
@@ -78,19 +80,10 @@ function toTiles(
78
80
  // products are spread over every code beneath it.
79
81
  // ---------------------------------------------------------------------------
80
82
 
81
- /** `locale:=… && enabled:=true && categories:=[…]`, the live catalogue's baseline. */
82
- function liveFilter(locale: Locale, codes: readonly string[]): string {
83
- return [
84
- `locale:=${tsFilterValue(locale)}`,
85
- "enabled:=true",
86
- `categories:=[${codes.map(tsFilterValue).join(",")}]`,
87
- ].join(" && ");
88
- }
89
-
90
83
  /**
91
- * Product counts per direct child. Deliberately the same call shape
92
- * `api/typesense/search.post.ts` makes for its derived `subcategory` facet, so
93
- * the cards and the filter rail can never disagree.
84
+ * Product counts per direct child, from the search service's `category` view —
85
+ * the view the category page's listing asks, so the cards and the filter rail
86
+ * can never disagree. The service pins locale and enabled products.
94
87
  */
95
88
  async function liveCounts(categorySlug: string, locale: Locale): Promise<Map<string, number>> {
96
89
  const { branchOf } = await liveSubcategoryIndex(categorySlug, locale);
@@ -99,27 +92,27 @@ async function liveCounts(categorySlug: string, locale: Locale): Promise<Map<str
99
92
  return new Map();
100
93
  }
101
94
 
102
- const results = await searchLiveProducts({
103
- q: "*",
104
- filterBy: liveFilter(locale, leafCodes),
105
- facetBy: "categories",
106
- maxFacetValues: MAX_SUBCATEGORY_VALUES,
95
+ const result = await searchClient.search({
96
+ view: "category",
97
+ filters: { categories: leafCodes },
107
98
  perPage: 1,
99
+ locale,
108
100
  });
109
101
 
110
102
  return rollUpSubcategoryCounts(
111
- results.facet_counts?.find(fc => fc.field_name === "categories")?.counts ?? [],
103
+ result.facets.find(facet => facet.field === "categories")?.counts ?? [],
112
104
  branchOf,
113
105
  );
114
106
  }
115
107
 
116
108
  /**
117
109
  * One representative product image per direct child: a 1-hit search per child,
118
- * batched into as few multi_search requests as possible.
110
+ * a few at a time.
119
111
  *
120
- * Per child rather than one big page of hits, because a page is capped at 250
121
- * documents and a category with thousands of products would leave most children
122
- * imageless — which is exactly how this looked when it was broken.
112
+ * Per child rather than one big page of hits, because a page is capped and a
113
+ * category with thousands of products would leave most children imageless —
114
+ * which is exactly how this looked when it was broken. A child whose lookup
115
+ * fails keeps its icon; the others keep their images.
123
116
  */
124
117
  async function liveImages(categorySlug: string, locale: Locale): Promise<Map<string, string>> {
125
118
  const { branchOf } = await liveSubcategoryIndex(categorySlug, locale);
@@ -136,15 +129,25 @@ async function liveImages(categorySlug: string, locale: Locale): Promise<Map<str
136
129
  const children = [...leavesByChild.keys()];
137
130
  const images = new Map<string, string>();
138
131
 
139
- for (const batch of chunk(children, SEARCH_BATCH_SIZE)) {
140
- const results = await searchLiveProductsMulti(batch.map(child => ({
141
- q: "*",
142
- filterBy: liveFilter(locale, leavesByChild.get(child) ?? [child]),
132
+ for (const batch of chunk(children, LIVE_IMAGE_CONCURRENCY)) {
133
+ const results = await Promise.allSettled(batch.map(child => searchClient.search({
134
+ view: "category",
135
+ filters: { categories: leavesByChild.get(child) ?? [child] },
143
136
  perPage: 1,
137
+ locale,
144
138
  })));
145
139
 
140
+ const failed = results.find((r): r is PromiseRejectedResult => r.status === "rejected");
141
+ if (failed) {
142
+ getLogService().warn(
143
+ "categories/subcategories: some preview image lookups failed",
144
+ { slug: categorySlug, ...toErrorContext(failed.reason) },
145
+ );
146
+ }
147
+
146
148
  batch.forEach((child, index) => {
147
- const doc = results[index]?.hits?.[0]?.document;
149
+ const settled = results[index];
150
+ const doc = settled?.status === "fulfilled" ? settled.value.docs[0] : undefined;
148
151
  if (doc) {
149
152
  images.set(child, mapLiveDocToProduct(doc).image);
150
153
  }
@@ -1,6 +1,9 @@
1
1
  import { OrderPaymentStatus, PromotionsRedemptionsReleaseReason } from "@revenexx/sdk";
2
2
  import type { Models } from "@revenexx/sdk";
3
3
 
4
+ import { type EligibleMethodFee, paymentFee } from "../../utils/paymentFee";
5
+ import { orderLinePrices, type PriceResolveAnswer } from "../../utils/orderLinePrices";
6
+
4
7
  // Method codes are generic — live mode validates them against the
5
8
  // payments app; the demo-only methods keep their extra fields.
6
9
  interface OrderPayment {
@@ -218,7 +221,12 @@ export default defineEventHandler(async (event) => {
218
221
  if (!rate) {
219
222
  throw createError({ status: 422, message: `Delivery method '${body.deliveryMethod}' is not available for this order` });
220
223
  }
221
- liveShippingRate = { price: rate.price, tax_rate: Number(rate.tax_rate ?? 0) };
224
+ // A null rate is unknown, not untaxed (RAD-175): shipping is not
225
+ // placed at 0 % because the shipping app could not say.
226
+ if (rate.tax_rate == null) {
227
+ throw createError({ status: 422, message: `Delivery method '${body.deliveryMethod}' could not be taxed` });
228
+ }
229
+ liveShippingRate = { price: rate.price, tax_rate: Number(rate.tax_rate) };
222
230
  }
223
231
  catch (err) {
224
232
  if (isError(err)) {
@@ -229,6 +237,38 @@ export default defineEventHandler(async (event) => {
229
237
  }
230
238
  }
231
239
 
240
+ // The payment surcharge, and the rate it is taxed at — both the payments
241
+ // app's, the same way the shipping charge above is the shipping app's
242
+ // (RX-781). The BFF resolves it server-side and never takes it from the
243
+ // browser: a fee the shopper could name is a fee the shopper could set.
244
+ //
245
+ // The orders app stores it, taxes it with the rate given and folds both
246
+ // into grand_total. It is handed no finished figure, exactly as with
247
+ // shipping.
248
+ let livePaymentFee: { fee: number; tax_rate: number } | null = null;
249
+ if (livePayments) {
250
+ const address = body.address as Record<string, unknown> | undefined;
251
+ try {
252
+ const { methods } = await useRevenexxSdk().paymentsMethods.paymentsMethodsEligible({
253
+ amount: calculation.totals.find(row => row.key === "subtotal")?.amount
254
+ ?? calculation.totals.find(row => row.key === "total")?.amount ?? 0,
255
+ country: String(address?.country ?? ""),
256
+ ...(selectedCurrency ? { currency: selectedCurrency } : {}),
257
+ }) as unknown as { methods: EligibleMethodFee[] };
258
+ const placed = paymentFee(methods, payment.method);
259
+ if (placed) {
260
+ livePaymentFee = { fee: placed.fee, tax_rate: placed.taxRate };
261
+ }
262
+ }
263
+ catch (err) {
264
+ if (isError(err)) {
265
+ throw err;
266
+ }
267
+ getLogService().error("Payment fee resolution failed", apiErrorContext(err));
268
+ throw createError({ status: 502, message: "Payment service unavailable" });
269
+ }
270
+ }
271
+
232
272
  let orderId = `ORD-${Date.now()}-${Math.random().toString(36).slice(2, 7).toUpperCase()}`;
233
273
 
234
274
  // Live orders: place through the orders app FIRST — the real order
@@ -262,35 +302,27 @@ export default defineEventHandler(async (event) => {
262
302
  const contactId = refs.contact_id ?? user?.contactId;
263
303
  const organizationId = refs.organization_id ?? user?.organizationId;
264
304
 
265
- // Per-item tax rate from the prices app (same resolve that prices
266
- // the storefront), not a BFF constant — one bulk call. The orders
267
- // app then taxes items + shipping and computes grand_total itself.
305
+ // Every line's price and tax rate from the prices app (same resolve
306
+ // that prices the storefront), one bulk call. Nothing the browser
307
+ // sent is a price here (RAD-175): a line prices cannot price, or a
308
+ // rate it cannot establish, refuses the order. The orders app then
309
+ // taxes items + shipping and computes grand_total itself.
268
310
  const orderItems = body.items as Array<Record<string, unknown>>;
269
- const itemRate = new Map<string, number>();
270
- const itemPrice = new Map<string, number>();
311
+ let answer: PriceResolveAnswer;
271
312
  try {
272
- const { prices: resolved } = await useRevenexxSdk().prices.pricesResolve({
313
+ answer = await useRevenexxSdk().prices.pricesResolve({
273
314
  items: orderItems.map(it => ({ product_id: String(it.id), sku: it.sku ? String(it.sku) : undefined, quantity: Number(it.quantity) || 1 })) as Models.PriceResolveItem[],
274
- ...(contactId ? { contactId } : {}),
275
- ...(organizationId ? { organizationId } : {}),
315
+ // Never a buyer id that could contradict the principal, which
316
+ // prices 1.0 refuses as buyer_mismatch (RAD-170).
317
+ ...priceBuyerContext(event),
276
318
  ...(selectedCurrency ? { currency: selectedCurrency } : {}),
277
- }) as unknown as { prices: Array<{ product_id: string | null; sku: string | null; tax_rate: number | null; on_request: boolean; unit_price: number | null }> };
278
- for (const p of resolved) {
279
- if (p.tax_rate != null) {
280
- if (p.product_id) itemRate.set(p.product_id, p.tax_rate);
281
- if (p.sku) itemRate.set(p.sku, p.tax_rate);
282
- }
283
- // Re-price in the resolved currency (the orders app is the SoR
284
- // for totals, but it must be fed prices in the buyer's currency).
285
- if (!p.on_request && p.unit_price != null) {
286
- if (p.product_id) itemPrice.set(p.product_id, p.unit_price);
287
- if (p.sku) itemPrice.set(p.sku, p.unit_price);
288
- }
289
- }
319
+ }) as unknown as PriceResolveAnswer;
290
320
  }
291
- catch (rateErr) {
292
- getLogService().error("Item price/tax resolution failed", apiErrorContext(rateErr));
321
+ catch (priceErr) {
322
+ getLogService().error("Item price/tax resolution failed", apiErrorContext(priceErr));
323
+ throw createError({ status: 502, message: "Price service unavailable" });
293
324
  }
325
+ const linePrices = orderLinePrices(answer, orderItems.length);
294
326
 
295
327
  // What the promotions app decided, evaluated once more against the
296
328
  // prices that were just resolved — not the figures the cart was
@@ -314,8 +346,8 @@ export default defineEventHandler(async (event) => {
314
346
  product_id: String(it.id),
315
347
  name: String(it.name ?? it.sku ?? it.id),
316
348
  quantity: calculation.lines[index]?.adjustedQuantity ?? Number(it.quantity),
317
- unit_price: itemPrice.get(String(it.id)) ?? itemPrice.get(String(it.sku ?? "")) ?? calculation.lines[index]?.unitPrice ?? Number(it.price ?? 0),
318
- tax_rate: itemRate.get(String(it.id)) ?? itemRate.get(String(it.sku ?? "")) ?? 0,
349
+ unit_price: linePrices[index]!.unitPrice,
350
+ tax_rate: linePrices[index]!.taxRate,
319
351
  })),
320
352
  });
321
353
  let discounts = (promo?.applied ?? []).map(a => ({
@@ -382,7 +414,12 @@ export default defineEventHandler(async (event) => {
382
414
  buyer: user ? { name: user.name, email: user.email } : { email: body.contactEmail ?? null },
383
415
  billingAddress: (billing ?? null) as object,
384
416
  shippingAddress: (address ?? null) as object,
385
- payment: { method: payment.method },
417
+ payment: {
418
+ method: payment.method,
419
+ // Only when there is one: a method that charges nothing
420
+ // sends no fee, rather than a zero that reads as "resolved".
421
+ ...(livePaymentFee ? { fee: livePaymentFee.fee, fee_tax_rate: livePaymentFee.tax_rate } : {}),
422
+ },
386
423
  // Shipping price + tax_rate from the shipping app; the orders
387
424
  // app taxes it and computes grand_total — the BFF sends NO
388
425
  // grand_total (orders is the single source of truth).
@@ -396,8 +433,8 @@ export default defineEventHandler(async (event) => {
396
433
  sku: String(item.sku ?? "") || undefined,
397
434
  name: String(item.name ?? item.sku ?? item.id),
398
435
  quantity: calculation.lines[index]?.adjustedQuantity ?? Number(item.quantity),
399
- unit_price: itemPrice.get(String(item.id)) ?? itemPrice.get(String(item.sku ?? "")) ?? calculation.lines[index]?.unitPrice ?? Number(item.price ?? 0),
400
- tax_rate: itemRate.get(String(item.id)) ?? itemRate.get(String(item.sku ?? "")) ?? 0,
436
+ unit_price: linePrices[index]!.unitPrice,
437
+ tax_rate: linePrices[index]!.taxRate,
401
438
  // Whether this position can be ordered at all. The orders app
402
439
  // holds the merchant's policy for one that cannot — order it,
403
440
  // leave it out, or refuse the lot — and cannot see stock
@@ -497,6 +534,11 @@ export default defineEventHandler(async (event) => {
497
534
  if (reserved === "held" && cartId) {
498
535
  await releaseRedemption(event, { cartId, reason: PromotionsRedemptionsReleaseReason.CartReleased });
499
536
  }
537
+ // Refused here on purpose (an unpriced line, an unknown rate, the
538
+ // price service down): that answer goes to the buyer as it is.
539
+ if (isError(err)) {
540
+ throw err;
541
+ }
500
542
  if (err instanceof RevenexxException && (err.code === 400 || err.code === 422)) {
501
543
  throw createError({ status: 422, message: err.message });
502
544
  }
@@ -536,6 +578,7 @@ export default defineEventHandler(async (event) => {
536
578
  // is forwarded as-is; paymentsCreate's typed params drop unknown
537
579
  // fields, so the create goes through the low-level transport.
538
580
  const instrument = body.paymentInstrument as { token?: string } | undefined;
581
+ const payerContactId = principalContactId(event);
539
582
  try {
540
583
  const created = await useRevenexxSdk().call<{ id: string; status: string; error_message?: string | null; next_action?: { type?: string; url?: string } | null }>(
541
584
  "POST",
@@ -548,6 +591,10 @@ export default defineEventHandler(async (event) => {
548
591
  currency: selectedCurrency ?? calculation.currency,
549
592
  country,
550
593
  order_ref: orderId,
594
+ // Whose payment this is: the account's payments page lists by
595
+ // it (RAD-171). The principal's contact, which payments holds
596
+ // the body to — a guest pays as nobody.
597
+ ...(payerContactId ? { contact_id: payerContactId } : {}),
551
598
  idempotency_key: body.checkoutSessionToken,
552
599
  ...(instrument?.token ? { token: instrument.token } : {}),
553
600
  ...(body.returnUrl ? { return_url: body.returnUrl } : {}),
@@ -571,7 +618,7 @@ export default defineEventHandler(async (event) => {
571
618
  // A placed live order must not survive a failed payment.
572
619
  if (liveOrderUuid) {
573
620
  try {
574
- await useRevenexxSdk().orders.ordersCancel({ id: liveOrderUuid, reason: "payment failed" });
621
+ await useTenantSdk().orders.ordersCancel({ id: liveOrderUuid, reason: "payment failed" });
575
622
  }
576
623
  catch (cancelErr) {
577
624
  getLogService().error("Order cancel after payment failure failed", apiErrorContext(cancelErr));
@@ -597,7 +644,7 @@ export default defineEventHandler(async (event) => {
597
644
  ? OrderPaymentStatus.Paid
598
645
  : livePaymentStatus === "authorized" ? OrderPaymentStatus.Authorized : OrderPaymentStatus.Pending;
599
646
  try {
600
- await useRevenexxSdk().orders.ordersPaymentStatusUpdate({ id: liveOrderUuid, status: mapped });
647
+ await useTenantSdk().orders.ordersPaymentStatusUpdate({ id: liveOrderUuid, status: mapped });
601
648
  }
602
649
  catch (err) {
603
650
  getLogService().error("Order payment-status sync failed", apiErrorContext(err));
@@ -1,3 +1,5 @@
1
+ import { pspPublicConfig, type PspProviderRow, type PspPublicConfig } from "../../utils/pspConfig";
2
+
1
3
  /**
2
4
  * Public PSP config for the checkout's client-side tokenizers — ONLY the
3
5
  * publishable/public keys of enabled PSP providers, never the secret keys.
@@ -5,36 +7,24 @@
5
7
  * which provider needs client-side tokenization and with which public key.
6
8
  *
7
9
  * Shape: { providers: { stripe: { publishableKey, testMode }, … } }
8
- * Adding Novalnet/Mollie later = they appear here automatically once enabled
9
- * with a publishable key on the provider; the FE registry gets a new entry.
10
+ * The key is read from the provider's `options.publishable_key` (see
11
+ * utils/pspConfig.ts); adding Novalnet/Mollie later = they appear here once
12
+ * enabled with one, and the FE registry gets a new entry.
10
13
  */
11
- interface ApiProviderRow {
12
- provider: string;
13
- enabled: boolean;
14
- test_mode: boolean;
15
- credentials: Record<string, unknown> | null;
16
- }
17
-
18
14
  export default defineEventHandler(async (event) => {
19
15
  if (resolvePaymentServiceKey(event) !== "api") {
20
- return { providers: {} as Record<string, { publishableKey: string; testMode: boolean }> };
16
+ return { providers: {} as PspPublicConfig };
21
17
  }
22
18
  try {
23
- const { items } = await useRevenexxSdk().call<{ items: ApiProviderRow[] }>("GET", "/v1/payments/providers");
24
- const providers: Record<string, { publishableKey: string; testMode: boolean }> = {};
25
- for (const row of items) {
26
- if (!row.enabled) {
27
- continue;
28
- }
29
- const pk = row.credentials?.publishable_key;
30
- if (typeof pk === "string" && pk.length > 0) {
31
- providers[row.provider] = { publishableKey: pk, testMode: row.test_mode !== false };
32
- }
19
+ const { items } = await useRevenexxSdk().call<{ items: PspProviderRow[] }>("GET", "/v1/payments/providers");
20
+ const { providers, refused } = pspPublicConfig(items ?? []);
21
+ if (refused.length) {
22
+ getLogService().error("Secret key configured as publishable_key — not published", { providers: refused });
33
23
  }
34
24
  return { providers };
35
25
  }
36
26
  catch (err) {
37
27
  getLogService().error("Service error: payment/psp-config", apiErrorContext(err));
38
- return { providers: {} as Record<string, { publishableKey: string; testMode: boolean }> };
28
+ return { providers: {} as PspPublicConfig };
39
29
  }
40
30
  });
@@ -0,0 +1,57 @@
1
+ import { normalizeLocaleCode } from "../../../../app/shared/locale";
2
+
3
+ /** What a product page may link to in other languages. */
4
+ export interface ProductLocalesResponse {
5
+ /**
6
+ * The requested storefront locales the product has a page in, or `null`
7
+ * when that is not known — the storefront then links every language, as
8
+ * on any other page.
9
+ */
10
+ locales: string[] | null;
11
+ }
12
+
13
+ /** A locale code as the storefront writes it (`de`, `en-US`). */
14
+ const LOCALE_CODE = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
15
+
16
+ /** More languages than any storefront offers: a bound on the lookup, not a limit. */
17
+ const MAX_LOCALES = 20;
18
+
19
+ /**
20
+ * The storefront locales `?locales=de,en` (the shop's own i18n locales) that
21
+ * this product has a page in. The language switcher and the hreflang
22
+ * alternates use it so a product is never linked into a language it has no
23
+ * document in (`search_untranslated=hide`, PE-859).
24
+ *
25
+ * Soft-failing: the answer only narrows links, so a failed lookup degrades to
26
+ * `null` (link everything, as before) instead of breaking the product page.
27
+ */
28
+ export default defineEventHandler(async (event): Promise<ProductLocalesResponse> => {
29
+ const id = getRouterParam(event, "id") ?? "";
30
+ if (!id) {
31
+ throw createError({ statusCode: 400, message: "Invalid product id" });
32
+ }
33
+
34
+ const raw = getQuery(event).locales;
35
+ const requested = [...new Set(
36
+ (Array.isArray(raw) ? raw.join(",") : String(raw ?? ""))
37
+ .split(",")
38
+ .map(code => normalizeLocaleCode(code))
39
+ .filter(code => LOCALE_CODE.test(code)),
40
+ )].slice(0, MAX_LOCALES);
41
+ if (!requested.length) {
42
+ throw createError({ statusCode: 400, message: "No locales given" });
43
+ }
44
+
45
+ const service = getProductService(event);
46
+ if (!service.getProductLanguages) {
47
+ return { locales: null };
48
+ }
49
+
50
+ try {
51
+ return { locales: await service.getProductLanguages(id, requested) };
52
+ }
53
+ catch (err) {
54
+ getLogService().warn("Product locales lookup failed", { id, ...toErrorContext(err) });
55
+ return { locales: null };
56
+ }
57
+ });
@@ -50,8 +50,8 @@ export default defineEventHandler(async (event): Promise<QuoteRequestResult> =>
50
50
  try {
51
51
  const { prices } = await useRevenexxSdk().prices.pricesResolve({
52
52
  items: body.items.map(it => ({ product_id: String(it.id), sku: it.sku || undefined, quantity: Number(it.quantity) || 1 })) as Models.PriceResolveItem[],
53
- ...(actor.contactId ? { contactId: actor.contactId } : {}),
54
- ...(actor.organizationId ? { organizationId: actor.organizationId } : {}),
53
+ // The principal decides whose prices these are (RAD-170).
54
+ ...priceBuyerContext(event),
55
55
  currency,
56
56
  }) as unknown as { prices: Array<{ product_id: string | null; sku: string | null; tax_rate: number | null; on_request: boolean; unit_price: number | null }> };
57
57
  for (const p of prices) {