@revenexx/cover 0.11.0 → 0.13.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 (61) hide show
  1. package/app/components/account/carts/AccountCartsTable.vue +4 -2
  2. package/app/components/auth/AuthLoginPanel.vue +71 -16
  3. package/app/components/auth/AuthRegisterPanel.vue +1 -1
  4. package/app/components/cart/recommend/CartCrossSell.vue +2 -1
  5. package/app/components/cart/switcher/CartSwitcher.vue +5 -2
  6. package/app/components/listing/ListingFilterBar.vue +1 -0
  7. package/app/components/listing/ListingFilterDrawer.vue +1 -0
  8. package/app/components/listing/ListingFilterRail.vue +1 -0
  9. package/app/components/search/filter/SearchFacets.vue +10 -3
  10. package/app/components/search/filter/SearchFacetsBar.vue +7 -3
  11. package/app/components/search/filter/SearchFacetsDrawer.vue +7 -2
  12. package/app/components/ui/forms/SearchInput.vue +4 -1
  13. package/app/composables/useAuthStore.ts +4 -2
  14. package/app/composables/useFacetMeta.ts +6 -6
  15. package/app/composables/useProductListing.ts +18 -2
  16. package/app/composables/useSearchListing.ts +16 -0
  17. package/app/interfaces/auth.ts +12 -2
  18. package/app/interfaces/shopSettings.ts +84 -0
  19. package/app/shared/locale.ts +114 -0
  20. package/i18n/locales/de/auth.json +41 -2
  21. package/i18n/locales/de/cart.json +2 -1
  22. package/i18n/locales/en/auth.json +41 -2
  23. package/i18n/locales/en/cart.json +2 -1
  24. package/nuxt.config.ts +22 -0
  25. package/package.json +1 -1
  26. package/server/api/account/quotes/[id]/order.post.ts +14 -3
  27. package/server/api/auth/login.post.ts +16 -3
  28. package/server/api/cart/calculate.post.ts +4 -0
  29. package/server/api/carts/[id]/activate.post.ts +7 -0
  30. package/server/api/carts/[id]/index.delete.ts +2 -0
  31. package/server/api/carts/index.post.ts +4 -0
  32. package/server/api/categories/[slug]/subcategories.get.ts +34 -31
  33. package/server/api/orders/index.post.ts +78 -31
  34. package/server/api/payment/psp-config.get.ts +11 -21
  35. package/server/api/quotes/request.post.ts +2 -2
  36. package/server/api/typesense/search.post.ts +61 -317
  37. package/server/api/typesense/suggest.post.ts +14 -9
  38. package/server/{api/typesense/drop.get.ts → dev/typesense/drop.ts} +2 -1
  39. package/server/{api/typesense/health.get.ts → dev/typesense/health.ts} +1 -0
  40. package/server/dev/typesense/seed.ts +59 -0
  41. package/server/dev/typesense/seedDocuments.ts +105 -0
  42. package/server/interfaces/auth.ts +10 -1
  43. package/server/routes/punchout/start.get.ts +44 -16
  44. package/server/services/ApiAuthService.ts +22 -6
  45. package/server/services/ApiBrandService.ts +28 -42
  46. package/server/services/ApiCartService.ts +64 -22
  47. package/server/services/ApiProductService.ts +10 -11
  48. package/server/services/MockAuthService.ts +21 -2
  49. package/server/utils/buyerIdentity.ts +11 -0
  50. package/server/utils/cartOwnership.ts +40 -0
  51. package/server/utils/liveCatalog.ts +132 -49
  52. package/server/utils/liveListingSearch.ts +201 -0
  53. package/server/utils/livePrices.ts +24 -9
  54. package/server/utils/orderLinePrices.ts +72 -0
  55. package/server/utils/paymentFee.ts +59 -0
  56. package/server/utils/pspConfig.ts +42 -0
  57. package/server/utils/revenexxSdk.ts +25 -2
  58. package/server/utils/searchClient.ts +305 -0
  59. package/server/utils/searchMultiSearchFallback.ts +216 -0
  60. package/server/utils/shopSettings.ts +5 -0
  61. package/server/api/typesense/seed.get.ts +0 -111
@@ -13,6 +13,7 @@ import type {
13
13
  ProductVariantAxis,
14
14
  ProductVariants,
15
15
  } from "../../app/interfaces/product-variants";
16
+ import { pickLocalizedLabel, searchLocaleKeys } from "../../app/shared/locale";
16
17
  import type { Locale } from "./locale";
17
18
 
18
19
  /**
@@ -164,7 +165,13 @@ const LIVE_DEFAULT_TAX_RATE = 19;
164
165
 
165
166
 
166
167
  /**
167
- * Several product searches in ONE request.
168
+ * Several product searches in ONE request, over the raw multi_search route.
169
+ *
170
+ * Searches go through searchClient.ts (the view-based query endpoint) now.
171
+ * What remains here: the deprecated fallback for gateways without that route
172
+ * (searchMultiSearchFallback.ts), and the document lookups by id below
173
+ * (getLiveProductDoc, association targets) — fetching known documents is a
174
+ * different contract from a search and is not part of the query endpoint.
168
175
  *
169
176
  * Raw call: the gateway 404s the POST single-search route its spec declares and
170
177
  * the GET contract does not declare facet_by, so neither the generated search
@@ -230,6 +237,69 @@ export function tsFilterValue(value: string): string {
230
237
  return "`" + value.replace(/`/g, "") + "`";
231
238
  }
232
239
 
240
+ // ---------------------------------------------------------------------------
241
+ // Locale scoping — one document per product AND locale (`{entity_id}:{locale}`).
242
+ // The index is moving from bare languages (`de`) to full codes (`de-DE`); every
243
+ // live query accepts both and prefers the full code (app/shared/locale.ts), so
244
+ // the storefront keeps working before, during and after that migration.
245
+ // ---------------------------------------------------------------------------
246
+
247
+ /** `locale:=[`de-DE`,`de`]` — the documents of one storefront locale. */
248
+ export function liveLocaleClause(locale: string): string {
249
+ return `locale:=[${searchLocaleKeys(locale).map(tsFilterValue).join(",")}]`;
250
+ }
251
+
252
+ /**
253
+ * The clauses every live catalogue query pins: the request's locale and
254
+ * enabled products only. Kept as separate parts so a caller can drop one the
255
+ * collection turns out not to declare without losing the other.
256
+ *
257
+ * Searches no longer build these: the query endpoint pins locale and enabled
258
+ * on the server (searchClient.ts). They remain for the deprecated multi_search
259
+ * fallback and the document lookups by id below.
260
+ */
261
+ export function liveCatalogFilterParts(locale: string): string[] {
262
+ return [liveLocaleClause(locale), "enabled:=true"];
263
+ }
264
+
265
+ /** The pinned clauses plus any extra ones, joined into one `filter_by`. */
266
+ export function liveCatalogFilter(locale: string, ...extra: string[]): string {
267
+ return [...liveCatalogFilterParts(locale), ...extra].join(" && ");
268
+ }
269
+
270
+ /** `id:=[…]` over every document id these products may carry in this locale. */
271
+ export function liveDocIdClause(entityIds: readonly string[], locale: string): string {
272
+ const keys = searchLocaleKeys(locale);
273
+ const ids = entityIds.flatMap(id => keys.map(key => tsFilterValue(`${id}:${key}`)));
274
+ return `id:=[${ids.join(",")}]`;
275
+ }
276
+
277
+ /**
278
+ * One document per product, the best-matching locale winning, in the order the
279
+ * products first appear. While both `{id}:de` and `{id}:de-DE` exist, a query
280
+ * over both keys returns the product twice; this keeps the full-code one.
281
+ */
282
+ export function preferLocaleDocs<T extends Pick<LiveProductDoc, "id" | "entity_id" | "locale">>(
283
+ docs: readonly T[],
284
+ locale: string,
285
+ ): T[] {
286
+ const keys = searchLocaleKeys(locale);
287
+ const rank = (doc: T): number => {
288
+ const docLocale = doc.locale || doc.id.slice(doc.id.lastIndexOf(":") + 1);
289
+ const index = keys.indexOf(docLocale);
290
+ return index === -1 ? keys.length : index;
291
+ };
292
+
293
+ const best = new Map<string, T>();
294
+ for (const doc of docs) {
295
+ const current = best.get(doc.entity_id);
296
+ if (!current || rank(doc) < rank(current)) {
297
+ best.set(doc.entity_id, doc);
298
+ }
299
+ }
300
+ return [...best.values()];
301
+ }
302
+
233
303
  export function mapLiveDocToProduct(doc: LiveProductDoc): Product {
234
304
  const categorySlug = doc.categories?.[0] ?? "";
235
305
  const category = doc.category_labels?.[0] ?? categorySlug;
@@ -307,15 +377,20 @@ export async function mapLiveDocToDetail(doc: LiveProductDoc, locale: Locale = "
307
377
  * Uses a filtered search instead of the document-GET route — the search
308
378
  * proxy's document endpoint currently rejects gateway-trust calls
309
379
  * (responds 401 "x-typesense-api-key"), and `id` is filterable anyway.
380
+ *
381
+ * Stays on multi_search rather than the view-based query endpoint: a lookup
382
+ * by document id is not a search, and the query endpoint has no contract for
383
+ * it (it takes no `id` filter and folds locale variants itself).
310
384
  */
311
385
  export async function getLiveProductDoc(entityId: string, locale: Locale): Promise<LiveProductDoc | null> {
312
386
  const result = await searchLiveProducts({
313
387
  q: "*",
314
388
  queryBy: "name",
315
- filterBy: `id:=${tsFilterValue(`${entityId}:${locale}`)}`,
316
- perPage: 1,
389
+ filterBy: liveDocIdClause([entityId], locale),
390
+ perPage: searchLocaleKeys(locale).length,
317
391
  });
318
- return result.hits?.[0]?.document ?? null;
392
+ const docs = (result.hits ?? []).map(hit => hit.document);
393
+ return preferLocaleDocs(docs, locale)[0] ?? null;
319
394
  }
320
395
 
321
396
  // ---------------------------------------------------------------------------
@@ -325,51 +400,22 @@ export async function getLiveProductDoc(entityId: string, locale: Locale): Promi
325
400
  // ---------------------------------------------------------------------------
326
401
 
327
402
  /**
328
- * A label map's value for one language, region-qualified keys included.
403
+ * Localised label with the products app's fallback chain: requested locale,
404
+ * then German, then English, then the technical code.
329
405
  *
330
406
  * Tenants do not agree on the key form: one PIM writes `de` / `en`, another
331
407
  * writes BCP-47 tags (`de-DE`, `en-GB`) for the same two languages. An
332
408
  * exact-key lookup silently missed the second kind and EVERY label degraded to
333
409
  * its technical code — a whole navigation reading `1`, `10837`, `10876`, and
334
- * specification rows reading `schneidbreite_bs`.
335
- *
336
- * Exact key first, then the first key whose language subtag matches, taken in
337
- * sorted key order so a map carrying several regions (`de-AT`, `de-DE`) always
338
- * answers the same way whatever the insertion order was. An empty string counts
339
- * as no label — it renders as a blank name, which is worse than the code.
340
- */
341
- function labelForLanguage(labels: Record<string, string>, language: string): string | undefined {
342
- const exact = labels[language];
343
- if (exact) {
344
- return exact;
345
- }
346
-
347
- const prefix = `${language}-`;
348
- for (const key of Object.keys(labels).sort()) {
349
- const normalized = key.toLowerCase().replace(/_/g, "-");
350
- if ((normalized === language || normalized.startsWith(prefix)) && labels[key]) {
351
- return labels[key];
352
- }
353
- }
354
- return undefined;
355
- }
356
-
357
- /**
358
- * Localised label with the products app's fallback chain: requested locale,
359
- * then German, then English, then the technical code.
410
+ * specification rows reading `schneidbreite_bs`. Full and short codes match in
411
+ * both directions (app/shared/locale.ts, shared with the client's facet labels).
360
412
  */
361
413
  export function pickLiveLabel(
362
414
  labels: Record<string, string> | null | undefined,
363
- locale: Locale,
415
+ locale: Locale | string,
364
416
  fallback: string,
365
417
  ): string {
366
- if (!labels) {
367
- return fallback;
368
- }
369
- return labelForLanguage(labels, locale)
370
- ?? labelForLanguage(labels, "de")
371
- ?? labelForLanguage(labels, "en")
372
- ?? fallback;
418
+ return pickLocalizedLabel(labels, locale, fallback);
373
419
  }
374
420
 
375
421
  // ---------------------------------------------------------------------------
@@ -596,6 +642,34 @@ export function subcategoryIndex(
596
642
  return { labels, branchOf };
597
643
  }
598
644
 
645
+ /**
646
+ * The top level of the storefront's category tree as a facet axis: each
647
+ * top-level category's label, and every code beneath it mapped back to it.
648
+ *
649
+ * The search page offers a `category` facet; the live index only facets
650
+ * `categories`, at the leaf. Rolled up through this, leaf counts become
651
+ * counts per top-level category — the same categories the navigation shows,
652
+ * because the same tree builder decides what "top level" means.
653
+ */
654
+ export async function liveTopCategoryIndex(locale: Locale): Promise<LiveSubcategoryIndex> {
655
+ return topCategoryIndex(await loadLiveCategoryRows(), locale);
656
+ }
657
+
658
+ /** Pure core of liveTopCategoryIndex(), exported for tests. */
659
+ export function topCategoryIndex(rows: LiveCategoryRow[], locale: Locale): LiveSubcategoryIndex {
660
+ const labels = new Map<string, string>();
661
+ const branchOf = new Map<string, string>();
662
+ for (const top of buildLiveCategoryTree(rows, locale)) {
663
+ labels.set(top.slug, top.label);
664
+ for (const code of subtreeCodes(rows, [top.slug])) {
665
+ if (!branchOf.has(code)) {
666
+ branchOf.set(code, top.slug);
667
+ }
668
+ }
669
+ }
670
+ return { labels, branchOf };
671
+ }
672
+
599
673
  /**
600
674
  * Roll `categories` facet counts up onto the direct children they belong to.
601
675
  *
@@ -914,8 +988,13 @@ function liveOrderUnitLabel(raw: unknown, locale: Locale): string | null {
914
988
  }
915
989
 
916
990
  function livePimName(product: LivePimProduct, locale: Locale): string {
917
- const byLocale = product.attribute_values?.locale_specific ?? {};
918
- return byLocale[locale]?.name ?? byLocale.de?.name ?? byLocale.en?.name ?? product.sku;
991
+ const names: Record<string, string> = {};
992
+ for (const [key, values] of Object.entries(product.attribute_values?.locale_specific ?? {})) {
993
+ if (values?.name) {
994
+ names[key] = values.name;
995
+ }
996
+ }
997
+ return pickLiveLabel(names, locale, product.sku);
919
998
  }
920
999
 
921
1000
  /**
@@ -1114,7 +1193,10 @@ function isMandatoryAssociation(type: LiveAssociationTypeRow): boolean {
1114
1193
  return type.is_quantified === true || type.code === "mandatory";
1115
1194
  }
1116
1195
 
1117
- /** Typesense caps a batch; resolve targets in chunks and keep one round trip per chunk. */
1196
+ /**
1197
+ * Typesense caps a batch; resolve targets in chunks and keep one round trip per
1198
+ * chunk. 100 targets × two locale keys stays under its 250 hits per page.
1199
+ */
1118
1200
  const TARGET_CHUNK_SIZE = 100;
1119
1201
 
1120
1202
  async function resolveAssociationTargets(
@@ -1128,19 +1210,20 @@ async function resolveAssociationTargets(
1128
1210
 
1129
1211
  // Filtering on `id` (the `{entity_id}:{locale}` document id) rather than
1130
1212
  // `entity_id`, which is not a filterable field — same reason
1131
- // getLiveProductDoc() goes through `id:=`.
1213
+ // getLiveProductDoc() goes through `id:=`. Each target may answer under
1214
+ // the full and the short locale code, hence the page size.
1215
+ const perTarget = searchLocaleKeys(locale).length;
1132
1216
  const results = await searchLiveProductsMulti(chunks.map(chunk => ({
1133
1217
  q: "*",
1134
1218
  queryBy: "name",
1135
- filterBy: `id:=[${chunk.map(id => tsFilterValue(`${id}:${locale}`)).join(",")}]`,
1136
- perPage: chunk.length,
1219
+ filterBy: liveDocIdClause(chunk, locale),
1220
+ perPage: chunk.length * perTarget,
1137
1221
  })));
1138
1222
 
1223
+ const docs = results.flatMap(result => (result.hits ?? []).map(hit => hit.document));
1139
1224
  const byId = new Map<string, Product>();
1140
- for (const result of results) {
1141
- for (const hit of result.hits ?? []) {
1142
- byId.set(hit.document.entity_id, mapLiveDocToProduct(hit.document));
1143
- }
1225
+ for (const doc of preferLocaleDocs(docs, locale)) {
1226
+ byId.set(doc.entity_id, mapLiveDocToProduct(doc));
1144
1227
  }
1145
1228
  return byId;
1146
1229
  }
@@ -0,0 +1,201 @@
1
+ import type { PriceRange, SearchFacet } from "../../app/interfaces/search-facets";
2
+ import type { LiveSubcategoryIndex } from "./liveCatalog";
3
+ import {
4
+ liveCategorySubtreeCodes,
5
+ liveSubcategoryIndex,
6
+ liveTopCategoryIndex,
7
+ rollUpSubcategoryCounts,
8
+ } from "./liveCatalog";
9
+ import type { Locale } from "./locale";
10
+ import type { SearchClientResult, SearchFilters } from "./searchClient";
11
+
12
+ /**
13
+ * The bridge between the storefront's listing vocabulary and the live index.
14
+ *
15
+ * The listing UI was built against the demo schema: it filters and facets on
16
+ * `category` / `subcategory` (labels), `categorySlug` / `subcategorySlug`
17
+ * (codes), `manufacturer`, `available` and `attrs.*`. The live index knows
18
+ * `categories` (leaf codes), `manufacturer`, `kind` and `attrs.*`. This module
19
+ * translates the request one way and the facets the other, and nothing else:
20
+ * which fields a query matches and which facets exist is the search service's
21
+ * business (searchClient.ts).
22
+ */
23
+
24
+ /** Price filters are in euros in the URL and in cents in the index. */
25
+ const PRICE_FIELD = "price";
26
+
27
+ /**
28
+ * A label-valued facet value back to its code. An unmatched value is passed
29
+ * through as a code, so a hand-edited URL yields an honest zero-hit filter
30
+ * rather than silently dropping the constraint.
31
+ */
32
+ function codesForLabels(values: readonly string[], labels: ReadonlyMap<string, string>): string[] {
33
+ return values.map((value) => {
34
+ if (labels.has(value)) {
35
+ return value;
36
+ }
37
+ return [...labels.entries()].find(([, label]) => label === value)?.[0] ?? value;
38
+ });
39
+ }
40
+
41
+ export interface LiveListingRequest {
42
+ /** Structured filters for the query endpoint. */
43
+ readonly filters: SearchFilters;
44
+ /** The category the listing is pinned to ("" on the search page). */
45
+ readonly pinnedCategoryCode: string;
46
+ /** Whether the visitor asked for a price range. */
47
+ readonly priceRequested: boolean;
48
+ }
49
+
50
+ /**
51
+ * The listing's filters as the query endpoint takes them.
52
+ *
53
+ * Category and subcategory are collected SEPARATELY and the narrower wins: a
54
+ * subcategory replaces its parent's clause rather than being OR'd next to it.
55
+ * Products carry their LEAF category only, so a branch expands to every code
56
+ * beneath it however deep the tree runs.
57
+ */
58
+ export async function buildLiveListingFilters(
59
+ filters: Readonly<Record<string, readonly string[] | undefined>> | undefined,
60
+ priceRange: PriceRange | undefined,
61
+ locale: Locale,
62
+ ): Promise<LiveListingRequest> {
63
+ const out: Record<string, SearchFilters[string]> = {};
64
+ const categoryCodes: string[] = [];
65
+ const categoryLabels: string[] = [];
66
+ const subcategoryValues: string[] = [];
67
+
68
+ for (const [field, values] of Object.entries(filters ?? {})) {
69
+ if (!values?.length) {
70
+ continue;
71
+ }
72
+ if (field === "categorySlug" || field === "categories") {
73
+ categoryCodes.push(...values);
74
+ }
75
+ else if (field === "category") {
76
+ categoryLabels.push(...values);
77
+ }
78
+ else if (field === "subcategorySlug" || field === "subcategory") {
79
+ subcategoryValues.push(...values);
80
+ }
81
+ else if (field === "manufacturer" || field === "kind" || field.startsWith("attrs.")) {
82
+ out[field] = [...values];
83
+ }
84
+ else if (field === "available") {
85
+ // Sent only when it narrows; the service reports it as ignored on
86
+ // an index without the field, and the facet is not offered there.
87
+ const wanted = new Set(values);
88
+ if (wanted.size === 1) {
89
+ out.available = wanted.has("true");
90
+ }
91
+ }
92
+ // `enabled` is pinned by the service and anything else is not a field
93
+ // the live index has.
94
+ }
95
+
96
+ // Only a page's own category pins the listing (category pages send it as a
97
+ // fixed filter); a category picked in the search page's facet narrows the
98
+ // results but keeps the search page's facets.
99
+ const pinnedCategoryCode = categoryCodes[0] ?? "";
100
+
101
+ // The search page's `category` facet is label-valued (see liveListingFacets).
102
+ if (categoryLabels.length) {
103
+ const { labels } = await liveTopCategoryIndex(locale);
104
+ categoryCodes.push(...codesForLabels(categoryLabels, labels));
105
+ }
106
+
107
+ // Resolved after the loop: `filters` merges the visitor's selection over
108
+ // the page's fixed filters, so `subcategory` can come before `categorySlug`.
109
+ const subcategoryCodes = subcategoryValues.length && pinnedCategoryCode
110
+ ? codesForLabels(subcategoryValues, (await liveSubcategoryIndex(pinnedCategoryCode, locale)).labels)
111
+ : subcategoryValues;
112
+
113
+ const branchCodes = subcategoryCodes.length ? subcategoryCodes : categoryCodes;
114
+ if (branchCodes.length) {
115
+ out.categories = await liveCategorySubtreeCodes(branchCodes);
116
+ }
117
+
118
+ const priceRequested = priceRange?.min !== undefined || priceRange?.max !== undefined;
119
+ if (priceRequested) {
120
+ out[PRICE_FIELD] = {
121
+ ...(priceRange?.min !== undefined ? { min: Math.round(priceRange.min * 100) } : {}),
122
+ ...(priceRange?.max !== undefined ? { max: Math.round(priceRange.max * 100) } : {}),
123
+ };
124
+ }
125
+
126
+ return { filters: out, pinnedCategoryCode, priceRequested };
127
+ }
128
+
129
+ /**
130
+ * The service's facets as the listing UI asks for them.
131
+ *
132
+ * Every facet passes through under its own name. Two are derived on top,
133
+ * because the UI's names never meet the index's otherwise:
134
+ * - `category` (search page): `categories` leaf counts rolled up to the
135
+ * top-level categories, label-valued like the demo schema's field.
136
+ * - `subcategory` (category page): the same roll-up onto the pinned
137
+ * category's direct children.
138
+ * There is no derived `available`: it shows up only when the index facets
139
+ * such a field itself.
140
+ */
141
+ export function mapListingFacets(
142
+ facets: SearchClientResult["facets"],
143
+ axes: { readonly top?: LiveSubcategoryIndex; readonly sub?: LiveSubcategoryIndex },
144
+ ): SearchFacet[] {
145
+ const out: SearchFacet[] = facets.map(facet => ({
146
+ fieldName: facet.field,
147
+ counts: facet.counts.map(c => ({ value: c.value, count: c.count })),
148
+ }));
149
+ const leafCounts = facets.find(f => f.field === "categories")?.counts ?? [];
150
+
151
+ const derive = (fieldName: string, index: LiveSubcategoryIndex | undefined) => {
152
+ if (!index || out.some(f => f.fieldName === fieldName)) {
153
+ return;
154
+ }
155
+ const byBranch = rollUpSubcategoryCounts(leafCounts, index.branchOf);
156
+ if (byBranch.size) {
157
+ out.push({
158
+ fieldName,
159
+ counts: [...byBranch]
160
+ .map(([code, count]) => ({ value: index.labels.get(code) ?? code, count }))
161
+ .sort((a, b) => b.count - a.count),
162
+ });
163
+ }
164
+ };
165
+
166
+ derive("category", axes.top);
167
+ derive("subcategory", axes.sub);
168
+ return out;
169
+ }
170
+
171
+ /** mapListingFacets with the category axes loaded for this request. */
172
+ export async function liveListingFacets(
173
+ result: SearchClientResult,
174
+ pinnedCategoryCode: string,
175
+ locale: Locale,
176
+ ): Promise<SearchFacet[]> {
177
+ const hasCategories = result.facets.some(f => f.field === "categories");
178
+ if (!hasCategories) {
179
+ return mapListingFacets(result.facets, {});
180
+ }
181
+ return mapListingFacets(result.facets, pinnedCategoryCode
182
+ ? { sub: await liveSubcategoryIndex(pinnedCategoryCode, locale) }
183
+ : { top: await liveTopCategoryIndex(locale) });
184
+ }
185
+
186
+ /**
187
+ * Whether the price filter does anything on this index. Yes when the service
188
+ * facets a price field, or applied a price range it was sent; no when it
189
+ * reported the range as ignored, and no on the fallback, whose collection
190
+ * carries no price. Without a signal it stays hidden rather than offering a
191
+ * filter that does nothing.
192
+ */
193
+ export function liveListingPriceFilter(result: SearchClientResult, priceRequested: boolean): boolean {
194
+ if (result.facets.some(f => f.field === PRICE_FIELD)) {
195
+ return true;
196
+ }
197
+ if (result.source !== "query" || !priceRequested) {
198
+ return false;
199
+ }
200
+ return !result.ignoredFilters.includes(PRICE_FIELD);
201
+ }
@@ -2,6 +2,8 @@ import type { H3Event } from "h3";
2
2
  import type { Models } from "@revenexx/sdk";
3
3
 
4
4
  import type { Offer, OfferRequestItem } from "../interfaces/offer";
5
+ import { principalContactId } from "./buyerIdentity";
6
+ import { sessionOrderRefs } from "./liveOrders";
5
7
 
6
8
  /**
7
9
  * Live prices from the prices app — THE live price call (the Offer domain's
@@ -21,15 +23,23 @@ interface ResolvedPrice {
21
23
  }
22
24
 
23
25
  /**
24
- * The buyer's price scope from the session.
26
+ * Who a prices.resolve call prices for, as body fields (RAD-170).
27
+ *
28
+ * A signed-in buyer's call carries them as `X-Revenexx-Principal` (see
29
+ * useRevenexxSdk), and prices 1.0 then takes the contact AND its organization
30
+ * from the gateway — a body id that differs from those is refused as
31
+ * `buyer_mismatch`. So where there is a principal the body names nobody and
32
+ * the principal decides. Only a request acting for no contact states a scope
33
+ * in the body, and only a verified one (RAD-155): a forged organization id
34
+ * would show another company's contract prices.
25
35
  *
26
36
  * A guest carries none, and whether they may see prices at all is the prices
27
- * app's answer (`anonymous_resolve_allowed`), read before the call is made —
28
- * see resolveLivePriceMap.
37
+ * app's answer (`anonymous_resolve_allowed`) — see resolveLivePriceMap.
29
38
  */
30
- function priceContext(event: H3Event): { contactId?: string; organizationId?: string } {
31
- // Verified, not read from the cookie (RAD-155): a forged organization id
32
- // would show another company's contract prices.
39
+ export function priceBuyerContext(event: H3Event): { contactId?: string; organizationId?: string } {
40
+ if (principalContactId(event)) {
41
+ return {};
42
+ }
33
43
  const { contact_id, organization_id } = sessionOrderRefs(event);
34
44
  return {
35
45
  ...(contact_id ? { contactId: contact_id } : {}),
@@ -37,6 +47,12 @@ function priceContext(event: H3Event): { contactId?: string; organizationId?: st
37
47
  };
38
48
  }
39
49
 
50
+ /** Whether a price call acts for a known buyer — by principal or stated scope. */
51
+ function pricesForBuyer(event: H3Event): boolean {
52
+ const context = priceBuyerContext(event);
53
+ return Boolean(principalContactId(event) || context.contactId || context.organizationId);
54
+ }
55
+
40
56
  /** Resolve tier ladder → the storefront tier map (quantity → TOTAL cents). */
41
57
  function toPriceMap(resolved: ResolvedPrice): { [key: string]: number }[] {
42
58
  if (resolved.on_request || resolved.unit_price === null) {
@@ -69,8 +85,7 @@ export async function resolveLivePriceMap(
69
85
  // a price, which is the same "price on request" the UI already renders for an
70
86
  // article the merchant quotes individually. Asking anyway would turn a
71
87
  // deliberate policy into an error page.
72
- const context = priceContext(event);
73
- if (!context.contactId && !context.organizationId) {
88
+ if (!pricesForBuyer(event)) {
74
89
  const { prices: priceTerms } = await getShopSettings(event);
75
90
  if (!priceTerms.anonymousAllowed) {
76
91
  for (const item of items) {
@@ -83,7 +98,7 @@ export async function resolveLivePriceMap(
83
98
  const currency = resolveSelectedCurrency(event);
84
99
  const { prices } = await useRevenexxSdk().prices.pricesResolve({
85
100
  items: items.map(i => ({ product_id: i.id, sku: i.sku, quantity: 1 })) as Models.PriceResolveItem[],
86
- ...context,
101
+ ...priceBuyerContext(event),
87
102
  ...(currency ? { currency } : {}),
88
103
  }) as unknown as { prices: ResolvedPrice[] };
89
104
 
@@ -0,0 +1,72 @@
1
+ /** The part of a prices.resolve answer an order line is priced from. */
2
+ export interface PriceResolveAnswer {
3
+ prices?: Array<{
4
+ product_id?: string | null;
5
+ sku?: string | null;
6
+ on_request?: boolean;
7
+ unit_price?: number | null;
8
+ tax_rate?: number | null;
9
+ }>;
10
+ tax?: { resolved?: boolean; reason?: string; message?: string };
11
+ }
12
+
13
+ export interface OrderLinePrice {
14
+ unitPrice: number;
15
+ taxRate: number;
16
+ }
17
+
18
+ /**
19
+ * The price and tax rate every order line is placed at — taken from the
20
+ * prices app's answer and nowhere else (RAD-175).
21
+ *
22
+ * The orders app takes the prices its caller supplies, on the assumption that
23
+ * only a server sets them. So a line the prices app did not price is not
24
+ * placed at the price the browser sent, or the one the cart was last shown
25
+ * with (which is the browser's again wherever prices did not answer): the
26
+ * order is refused instead. Equally a rate nobody could establish is refused
27
+ * rather than read as 0 % — `tax.resolved: false` means unknown, not untaxed.
28
+ *
29
+ * The answer holds one entry per requested item, in request order, so lines
30
+ * are matched by index: the same article can stand on two positions.
31
+ */
32
+ export function orderLinePrices(answer: PriceResolveAnswer, lineCount: number): OrderLinePrice[] {
33
+ if (answer.tax?.resolved === false) {
34
+ throw createError({
35
+ status: 422,
36
+ message: `Prices could not be taxed${answer.tax.reason ? `: ${answer.tax.reason}` : ""}`,
37
+ data: { type: "tax_unresolved", reason: answer.tax.reason ?? null },
38
+ });
39
+ }
40
+ const prices = answer.prices ?? [];
41
+ const unpriced: string[] = [];
42
+ const untaxed: string[] = [];
43
+ const lines: OrderLinePrice[] = [];
44
+ for (let index = 0; index < lineCount; index++) {
45
+ const p = prices[index];
46
+ const label = String(p?.sku ?? p?.product_id ?? `#${index + 1}`);
47
+ if (!p || p.on_request || p.unit_price == null || !Number.isFinite(Number(p.unit_price))) {
48
+ unpriced.push(label);
49
+ continue;
50
+ }
51
+ if (p.tax_rate == null || !Number.isFinite(Number(p.tax_rate))) {
52
+ untaxed.push(label);
53
+ continue;
54
+ }
55
+ lines.push({ unitPrice: Number(p.unit_price), taxRate: Number(p.tax_rate) });
56
+ }
57
+ if (unpriced.length) {
58
+ throw createError({
59
+ status: 422,
60
+ message: `Positions without a price cannot be ordered: ${unpriced.join(", ")}`,
61
+ data: { type: "price_on_request", positions: unpriced },
62
+ });
63
+ }
64
+ if (untaxed.length) {
65
+ throw createError({
66
+ status: 422,
67
+ message: `Positions without a tax rate cannot be ordered: ${untaxed.join(", ")}`,
68
+ data: { type: "tax_unresolved", positions: untaxed },
69
+ });
70
+ }
71
+ return lines;
72
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * What a payment surcharge is placed at (RX-781).
3
+ *
4
+ * The payments app owns the surcharge: it computes the amount from the method's
5
+ * configuration and resolves the rate it is taxed at from the buyer's market
6
+ * (`markets.tax_classes`, via the method's tax class — RAD-200). The storefront
7
+ * resolves both server-side and hands them to the orders app, which taxes the
8
+ * surcharge and folds it into `grand_total`. The BFF computes no tax and sends
9
+ * no total, exactly as it already does for the shipping charge.
10
+ *
11
+ * Never from the browser. A fee the shopper could name is a fee the shopper
12
+ * could set.
13
+ */
14
+
15
+ /** An eligible method as the payments app answers it. */
16
+ export interface EligibleMethodFee {
17
+ code: string;
18
+ fee: number;
19
+ /** Null means the rate could not be established — not that there is none. */
20
+ fee_tax_rate?: number | null;
21
+ }
22
+
23
+ export interface PlacedPaymentFee {
24
+ fee: number;
25
+ taxRate: number;
26
+ }
27
+
28
+ /**
29
+ * The surcharge to place the order with, or null when there is none to place.
30
+ *
31
+ * Null covers the two cases that are not a problem: the chosen method is not in
32
+ * the answer at all (the mock payment path, or a method the shop serves without
33
+ * asking payments), and a method that charges nothing. Neither sends a `fee` —
34
+ * a zero would read as "resolved and free", which is a different claim.
35
+ *
36
+ * A surcharge whose rate the payments app could not establish throws 422. An
37
+ * unresolved rate is unknown, not zero, and the same rule already governs the
38
+ * shipping charge and the line prices (`checkout` AC-8): a surcharge placed at
39
+ * 0 % because nobody could say is an invoice the merchant owes the difference
40
+ * on, found months later.
41
+ */
42
+ export function paymentFee(methods: EligibleMethodFee[], methodCode: string): PlacedPaymentFee | null {
43
+ const chosen = methods.find(m => m.code === methodCode);
44
+ if (!chosen) {
45
+ return null;
46
+ }
47
+ const fee = Number(chosen.fee ?? 0);
48
+ if (!Number.isFinite(fee) || fee <= 0) {
49
+ return null;
50
+ }
51
+ if (chosen.fee_tax_rate == null) {
52
+ throw createError({
53
+ status: 422,
54
+ message: `The surcharge of payment method '${methodCode}' could not be taxed`,
55
+ data: { type: "payment_fee_tax_unresolved", method: methodCode },
56
+ });
57
+ }
58
+ return { fee, taxRate: Number(chosen.fee_tax_rate) };
59
+ }