@revenexx/cover 0.2.25 → 0.2.27

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 (83) hide show
  1. package/app/api/brands.ts +5 -0
  2. package/app/api/categories.ts +1 -0
  3. package/app/api/product.ts +2 -0
  4. package/app/app.config.ts +8 -0
  5. package/app/components/cart/quickadd/CartQuickAdd.vue +110 -34
  6. package/app/components/category/view/GridView.vue +34 -13
  7. package/app/components/category/view/ListView.vue +5 -5
  8. package/app/components/checkout/onepage/CheckoutDeliverySection.vue +29 -1
  9. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +30 -1
  10. package/app/components/layout/AppLogo.vue +2 -1
  11. package/app/components/layout/footer/Footer.vue +9 -3
  12. package/app/components/layout/header/CategoryPanel.vue +92 -0
  13. package/app/components/layout/header/MainNav.vue +89 -2
  14. package/app/components/listing/ListingResults.vue +16 -2
  15. package/app/components/listing/ListingSubcategories.vue +124 -0
  16. package/app/components/product/card/Compact.vue +144 -0
  17. package/app/components/product/detail/ProductDetailAssociations.vue +96 -0
  18. package/app/components/product/detail/ProductDetailIdentity.vue +50 -5
  19. package/app/components/product/detail/ProductDetailVariantRow.vue +139 -0
  20. package/app/components/product/detail/ProductDetailVariants.vue +613 -0
  21. package/app/components/product/media/ProductMediaImage.vue +70 -0
  22. package/app/components/ui/forms/SearchInput.vue +14 -2
  23. package/app/components/ui/media/ImageSlider.vue +158 -0
  24. package/app/composables/useBranding.ts +22 -0
  25. package/app/composables/useBrands.ts +42 -0
  26. package/app/composables/useCategories.ts +55 -1
  27. package/app/composables/useProduct.ts +5 -4
  28. package/app/composables/useProductAssociations.ts +35 -0
  29. package/app/composables/useProductImage.ts +35 -2
  30. package/app/composables/useProductVariants.ts +46 -0
  31. package/app/composables/useSearchListing.ts +16 -5
  32. package/app/composables/useSubcategoryTiles.ts +36 -0
  33. package/app/config/navigation.ts +9 -0
  34. package/app/config/palette.ts +1 -0
  35. package/app/config/quickActions.ts +137 -0
  36. package/app/config/themes.ts +1 -0
  37. package/app/interfaces/brand.ts +16 -0
  38. package/app/interfaces/category.ts +45 -0
  39. package/app/interfaces/image-slider.ts +18 -0
  40. package/app/interfaces/product-associations.ts +32 -0
  41. package/app/interfaces/product-detail.ts +6 -0
  42. package/app/interfaces/product-variants.ts +73 -0
  43. package/i18n/locales/de/account.json +17 -0
  44. package/i18n/locales/de/cart.json +5 -1
  45. package/i18n/locales/de/checkout.json +2 -0
  46. package/i18n/locales/de/common.json +42 -2
  47. package/i18n/locales/de/editor.json +91 -0
  48. package/i18n/locales/de/product.json +48 -2
  49. package/i18n/locales/de/search.json +4 -2
  50. package/i18n/locales/en/account.json +17 -0
  51. package/i18n/locales/en/cart.json +4 -0
  52. package/i18n/locales/en/checkout.json +2 -0
  53. package/i18n/locales/en/common.json +42 -2
  54. package/i18n/locales/en/editor.json +91 -0
  55. package/i18n/locales/en/product.json +47 -1
  56. package/i18n/locales/en/search.json +3 -1
  57. package/nuxt.config.ts +10 -0
  58. package/package.json +3 -1
  59. package/public/img/brands/revenexx.svg +39 -0
  60. package/server/api/brands.get.ts +27 -0
  61. package/server/api/categories/[slug]/subcategories.get.ts +280 -0
  62. package/server/api/product/[id]/associations.get.ts +27 -0
  63. package/server/api/product/[id]/variants.get.ts +27 -0
  64. package/server/api/quick-actions.get.ts +43 -0
  65. package/server/api/typesense/search.post.ts +116 -13
  66. package/server/data/categories.json +5 -0
  67. package/server/data/product-associations.json +44 -0
  68. package/server/data/product-detail.json +346 -0
  69. package/server/data/product-list.json +340 -0
  70. package/server/data/product-variant-models.json +75 -0
  71. package/server/interfaces/brand.ts +17 -0
  72. package/server/interfaces/product.ts +14 -0
  73. package/server/services/ApiBrandService.ts +110 -0
  74. package/server/services/ApiProductService.ts +43 -9
  75. package/server/services/LocalFileProductService.ts +200 -6
  76. package/server/services/MockBrandService.ts +52 -0
  77. package/server/utils/brandService.ts +24 -0
  78. package/server/utils/contentTenant.ts +67 -0
  79. package/server/utils/liveCatalog.ts +744 -46
  80. package/server/utils/productService.ts +6 -1
  81. package/server/utils/productsSchema.ts +5 -2
  82. package/server/utils/revenexxCredentials.ts +258 -0
  83. package/server/utils/revenexxSdk.ts +38 -47
@@ -2,7 +2,17 @@ import { Collection } from "@revenexx/sdk";
2
2
 
3
3
  import type { ProductCategory, ProductSubcategory } from "../../app/config/navigation";
4
4
  import type { Product } from "../../app/composables/useProducts";
5
+ import type {
6
+ ProductAssociationGroup,
7
+ ProductAssociationItem,
8
+ ProductAssociations,
9
+ } from "../../app/interfaces/product-associations";
5
10
  import type { ProductDetail } from "../../app/interfaces/product-detail";
11
+ import type {
12
+ ProductVariant,
13
+ ProductVariantAxis,
14
+ ProductVariants,
15
+ } from "../../app/interfaces/product-variants";
6
16
  import type { Locale } from "./locale";
7
17
 
8
18
  /**
@@ -39,6 +49,12 @@ export interface LiveSearchResponse {
39
49
  page: number;
40
50
  hits?: { document: LiveProductDoc; highlight?: unknown }[];
41
51
  facet_counts?: { field_name: string; counts?: { value: string; count: number }[] }[];
52
+ /** Set instead of a transport error when a sub-search of multi_search fails. */
53
+ error?: string;
54
+ }
55
+
56
+ interface LiveMultiSearchResponse {
57
+ results?: LiveSearchResponse[];
42
58
  }
43
59
 
44
60
  export interface LiveSearchParams {
@@ -49,33 +65,125 @@ export interface LiveSearchParams {
49
65
  sortBy?: string;
50
66
  page?: number;
51
67
  perPage?: number;
68
+ /** Facet values per field. Typesense returns only 10 when unset. */
69
+ maxFacetValues?: number;
70
+ }
71
+
72
+ /**
73
+ * A live catalogue image value, resolved to a src the client can load as-is.
74
+ *
75
+ * The `image` common attribute is either an absolute URL (the PIM's own media
76
+ * CDN) or a tenant-relative storage key. The key is served through the
77
+ * platform's `/cdn/` path — the edge CDN in production, the theme's `/cdn/`
78
+ * proxy route in dev and in the editor canvas.
79
+ *
80
+ * Normalising HERE is what keeps the client rule unambiguous: a bare storage
81
+ * key and a bundled demo filename look identical, and only the server knows
82
+ * which mode produced the value.
83
+ *
84
+ * Exported because manufacturer logos (ApiBrandService) are the same kind of
85
+ * value read from a different attribute.
86
+ */
87
+ export function liveImageSrc(raw: string): string {
88
+ if (/^https?:\/\//.test(raw) || raw.startsWith("/")) {
89
+ return raw;
90
+ }
91
+ return `/cdn/${raw}`;
92
+ }
93
+
94
+ /** Fallback attribute code holding a manufacturer's logo on the product doc. */
95
+ const DEFAULT_LOGO_ATTRIBUTE = "manufacturer_logo";
96
+
97
+ /**
98
+ * The attribute code carrying the manufacturer logo.
99
+ *
100
+ * This is a per-tenant PIM attribute, not a platform contract, so it is
101
+ * configurable rather than hardcoded. A tenant that does not have it degrades
102
+ * to logo-less brands, which the grid renders as wordmark tiles.
103
+ */
104
+ export function manufacturerLogoAttribute(): string {
105
+ const config = useAppConfig() as Record<string, unknown>;
106
+ const brands = config.brands as { logoAttribute?: unknown } | undefined;
107
+ return typeof brands?.logoAttribute === "string" && brands.logoAttribute
108
+ ? brands.logoAttribute
109
+ : DEFAULT_LOGO_ATTRIBUTE;
52
110
  }
53
111
 
54
- const PRODUCT_PLACEHOLDER_IMAGE = "/img/product-placeholder.svg";
112
+ /**
113
+ * A product's manufacturer logo, resolved to a loadable src — `null` when the
114
+ * catalogue carries none. Same kind of value as the gallery image (absolute
115
+ * media-CDN URL or tenant-relative storage key), read from a different
116
+ * attribute, so it goes through the same normalisation.
117
+ */
118
+ export function manufacturerLogoSrc(attrs: Record<string, unknown> | undefined): string | null {
119
+ const raw = attrs?.[manufacturerLogoAttribute()];
120
+ return typeof raw === "string" && raw.trim().length > 0 ? liveImageSrc(raw.trim()) : null;
121
+ }
55
122
 
56
123
  /** TODO(markets): resolve from the market's tax classes instead of a constant. */
57
124
  const LIVE_DEFAULT_TAX_RATE = 19;
58
125
 
59
126
 
60
- export async function searchLiveProducts(params: LiveSearchParams): Promise<LiveSearchResponse> {
61
- // Raw call (GET form): the gateway currently 404s the POST search route
62
- // its spec declares, and the GET contract does not declare facet_by —
63
- // the generated search methods can't cover this call yet.
64
- return useRevenexxSdk().call<LiveSearchResponse>(
65
- "GET",
66
- `/v1/search/collections/${Collection.Products}/documents/search`,
127
+ /**
128
+ * Several product searches in ONE request.
129
+ *
130
+ * Raw call: the gateway 404s the POST single-search route its spec declares and
131
+ * the GET contract does not declare facet_by, so neither the generated search
132
+ * methods nor the GET form cover this call.
133
+ *
134
+ * multi_search rather than the GET single search because a category filter names
135
+ * every leaf code under a branch, and a deep catalogue blows straight through
136
+ * Typesense's 4000-character query-string cap ("Use the /multi_search end-point
137
+ * for larger payloads"). The body has no such limit.
138
+ *
139
+ * A failed SUB-search is NOT thrown here: a caller asking several questions at
140
+ * once — one representative product per subcategory, say — must not lose every
141
+ * answer because one of them failed. Results come back positionally, so a
142
+ * missing or errored slot is the caller's to interpret. Typesense caps the
143
+ * batch (`limit_multi_searches` defaults to 50), so chunk longer lists.
144
+ */
145
+ export async function searchLiveProductsMulti(
146
+ params: readonly LiveSearchParams[],
147
+ ): Promise<LiveSearchResponse[]> {
148
+ if (!params.length) {
149
+ return [];
150
+ }
151
+
152
+ const response = await useRevenexxSdk().call<LiveMultiSearchResponse>(
153
+ "POST",
154
+ "/v1/search/multi_search",
67
155
  {
68
- query: {
69
- q: params.q,
70
- query_by: params.queryBy ?? "name,sku,description,manufacturer",
71
- filter_by: params.filterBy,
72
- facet_by: params.facetBy,
73
- sort_by: params.sortBy,
74
- page: params.page ?? 1,
75
- per_page: params.perPage ?? 24,
156
+ body: {
157
+ searches: params.map(p => ({
158
+ collection: Collection.Products,
159
+ q: p.q,
160
+ query_by: p.queryBy ?? "name,sku,description,manufacturer",
161
+ ...(p.filterBy ? { filter_by: p.filterBy } : {}),
162
+ ...(p.facetBy ? { facet_by: p.facetBy } : {}),
163
+ ...(p.maxFacetValues ? { max_facet_values: p.maxFacetValues } : {}),
164
+ ...(p.sortBy ? { sort_by: p.sortBy } : {}),
165
+ page: p.page ?? 1,
166
+ per_page: p.perPage ?? 24,
167
+ })),
76
168
  },
77
169
  },
78
170
  );
171
+
172
+ return response.results ?? [];
173
+ }
174
+
175
+ export async function searchLiveProducts(params: LiveSearchParams): Promise<LiveSearchResponse> {
176
+ const [result] = await searchLiveProductsMulti([params]);
177
+ if (!result) {
178
+ throw new Error("multi_search returned no result for the products search");
179
+ }
180
+ // multi_search reports a failed sub-search in the 200 body instead of a
181
+ // transport error. Rethrowing keeps the schema-drift fallbacks in
182
+ // search.post.ts — which match on the message — working unchanged.
183
+ if (result.error) {
184
+ throw new Error(result.error);
185
+ }
186
+ return result;
79
187
  }
80
188
 
81
189
  /** Escape a value for a Typesense `filter_by` exact-match clause. */
@@ -98,10 +206,14 @@ export function mapLiveDocToProduct(doc: LiveProductDoc): Product {
98
206
  stocks: [],
99
207
  tax: { rate: LIVE_DEFAULT_TAX_RATE },
100
208
  // The product's image is a common attribute (search.json `attribute:common.*`
101
- // catch-all → the doc's `attrs` object). Pass it through (full URL or a
102
- // storage key the theme's image provider resolves); fall back to the
103
- // placeholder when the product declares none.
104
- image: typeof doc.attrs?.image === "string" && doc.attrs.image ? doc.attrs.image : PRODUCT_PLACEHOLDER_IMAGE,
209
+ // catch-all → the doc's `attrs` object), resolved to a loadable src. A
210
+ // product that declares none gets an empty string, not a placeholder src:
211
+ // only the empty value lets the tile render its icon fallback (see
212
+ // `ProductMediaImage`), and a substituted grey placeholder image looked
213
+ // like a real, worse picture. Same treatment as `mapLiveDocToDetail`.
214
+ image: typeof doc.attrs?.image === "string" && doc.attrs.image
215
+ ? liveImageSrc(doc.attrs.image)
216
+ : "",
105
217
  category,
106
218
  categorySlug,
107
219
  };
@@ -117,6 +229,9 @@ export async function mapLiveDocToDetail(doc: LiveProductDoc, locale: Locale = "
117
229
  name: doc.name,
118
230
  sku: doc.sku,
119
231
  manufacturer: doc.manufacturer ?? "",
232
+ // The identity block renders it next to the product name where the
233
+ // catalogue has one (`null` otherwise, never a placeholder image).
234
+ manufacturerLogo: manufacturerLogoSrc(doc.attrs),
120
235
  createdAt: syncedAt,
121
236
  updatedAt: syncedAt,
122
237
  deletedAt: null,
@@ -132,11 +247,11 @@ export async function mapLiveDocToDetail(doc: LiveProductDoc, locale: Locale = "
132
247
  ...(doc.categories?.[0] ? [{ type: "slug", name: doc.categories[0] }] : []),
133
248
  ],
134
249
  // Seed the gallery from the product's `image` common attribute (same
135
- // source as the catalog shell). The theme's image provider resolves the
136
- // storage key to the CDN; the live index has no multi-image gallery yet,
137
- // so this is the single main image (empty when none is declared).
250
+ // source, and same src resolution, as the catalog shell). The live index
251
+ // has no multi-image gallery yet, so this is the single main image
252
+ // (empty when none is declared).
138
253
  images: typeof doc.attrs?.image === "string" && doc.attrs.image
139
- ? [{ type: "main", priority: 0, url: doc.attrs.image }]
254
+ ? [{ type: "main", priority: 0, url: liveImageSrc(doc.attrs.image) }]
140
255
  : [],
141
256
  // Specifications: the `attrs` catch-all holds the product's common
142
257
  // attributes as raw key→value. Resolve each through the products app's
@@ -164,12 +279,67 @@ export async function getLiveProductDoc(entityId: string, locale: Locale): Promi
164
279
  return result.hits?.[0]?.document ?? null;
165
280
  }
166
281
 
282
+ // ---------------------------------------------------------------------------
283
+ // Labels — every localized name the catalogue carries (categories, attributes,
284
+ // select options, association types) arrives as the same `labels` map, so it is
285
+ // read in exactly one place.
286
+ // ---------------------------------------------------------------------------
287
+
288
+ /**
289
+ * A label map's value for one language, region-qualified keys included.
290
+ *
291
+ * Tenants do not agree on the key form: one PIM writes `de` / `en`, another
292
+ * writes BCP-47 tags (`de-DE`, `en-GB`) for the same two languages. An
293
+ * exact-key lookup silently missed the second kind and EVERY label degraded to
294
+ * its technical code — a whole navigation reading `1`, `10837`, `10876`, and
295
+ * specification rows reading `schneidbreite_bs`.
296
+ *
297
+ * Exact key first, then the first key whose language subtag matches, taken in
298
+ * sorted key order so a map carrying several regions (`de-AT`, `de-DE`) always
299
+ * answers the same way whatever the insertion order was. An empty string counts
300
+ * as no label — it renders as a blank name, which is worse than the code.
301
+ */
302
+ function labelForLanguage(labels: Record<string, string>, language: string): string | undefined {
303
+ const exact = labels[language];
304
+ if (exact) {
305
+ return exact;
306
+ }
307
+
308
+ const prefix = `${language}-`;
309
+ for (const key of Object.keys(labels).sort()) {
310
+ const normalized = key.toLowerCase().replace(/_/g, "-");
311
+ if ((normalized === language || normalized.startsWith(prefix)) && labels[key]) {
312
+ return labels[key];
313
+ }
314
+ }
315
+ return undefined;
316
+ }
317
+
318
+ /**
319
+ * Localised label with the products app's fallback chain: requested locale,
320
+ * then German, then English, then the technical code.
321
+ */
322
+ export function pickLiveLabel(
323
+ labels: Record<string, string> | null | undefined,
324
+ locale: Locale,
325
+ fallback: string,
326
+ ): string {
327
+ if (!labels) {
328
+ return fallback;
329
+ }
330
+ return labelForLanguage(labels, locale)
331
+ ?? labelForLanguage(labels, "de")
332
+ ?? labelForLanguage(labels, "en")
333
+ ?? fallback;
334
+ }
335
+
167
336
  // ---------------------------------------------------------------------------
168
337
  // Categories — products app tree, cached briefly (it changes rarely and the
169
338
  // storefront asks on every navigation render).
170
339
  // ---------------------------------------------------------------------------
171
340
 
172
- interface LiveCategoryRow {
341
+ /** Flat category row as the products app returns it. Exported for tests. */
342
+ export interface LiveCategoryRow {
173
343
  id: string;
174
344
  code: string;
175
345
  parent_id: string | null;
@@ -219,7 +389,7 @@ async function loadLiveCategoryRows(): Promise<LiveCategoryRow[]> {
219
389
  }
220
390
 
221
391
  function categoryLabel(row: LiveCategoryRow, locale: Locale): string {
222
- return row.labels?.[locale] ?? row.labels?.de ?? row.labels?.en ?? row.code;
392
+ return pickLiveLabel(row.labels, locale, row.code);
223
393
  }
224
394
 
225
395
  /**
@@ -228,19 +398,31 @@ function categoryLabel(row: LiveCategoryRow, locale: Locale): string {
228
398
  * so its children become the top-level categories.
229
399
  */
230
400
  export async function getLiveCategories(locale: Locale): Promise<ProductCategory[]> {
231
- const rows = await loadLiveCategoryRows();
401
+ return buildLiveCategoryTree(await loadLiveCategoryRows(), locale);
402
+ }
232
403
 
233
- const byParent = new Map<string | null, LiveCategoryRow[]>();
234
- for (const row of rows) {
235
- const list = byParent.get(row.parent_id) ?? [];
236
- list.push(row);
237
- byParent.set(row.parent_id, list);
238
- }
404
+ /** Pure core of getLiveCategories(), exported for tests. */
405
+ export function buildLiveCategoryTree(rows: LiveCategoryRow[], locale: Locale): ProductCategory[] {
406
+ const byParent = groupByParent(rows);
239
407
  for (const list of byParent.values()) {
240
408
  list.sort((a, b) => a.position - b.position || a.code.localeCompare(b.code));
241
409
  }
242
410
 
243
411
  let roots = byParent.get(null) ?? [];
412
+
413
+ // A root with no children carries nothing to navigate in a two-level tree,
414
+ // and an import leaves them behind: this catalogue's real assortment hangs
415
+ // under one "Webkatalog" node while stray `test` / `test-rules` rows sit
416
+ // beside it at the top. Dropping them is also what lets the collapse below
417
+ // still fire — it used to require the artificial root to be the ONLY root,
418
+ // so a single leftover row put the whole assortment one level too deep.
419
+ // Guarded: a genuinely flat taxonomy, where no root has children, keeps all
420
+ // of them rather than rendering an empty navigation.
421
+ const branchRoots = roots.filter(root => (byParent.get(root.id) ?? []).length > 0);
422
+ if (branchRoots.length > 0) {
423
+ roots = branchRoots;
424
+ }
425
+
244
426
  if (roots.length === 1) {
245
427
  roots = byParent.get(roots[0]!.id) ?? [];
246
428
  }
@@ -257,6 +439,148 @@ export async function getLiveCategories(locale: Locale): Promise<ProductCategory
257
439
  }));
258
440
  }
259
441
 
442
+ /**
443
+ * A category code plus every descendant code, for a `categories:=[…]` clause.
444
+ *
445
+ * Products are indexed with their LEAF category only, so filtering by a branch
446
+ * has to name every leaf under it. getLiveCategories() deliberately flattens the
447
+ * tree to the two levels the storefront navigates, which is one level short of
448
+ * that on any deeper catalogue: `categories:=[root, child…]` then matches
449
+ * nothing and every category page renders empty. This walks the RAW rows
450
+ * instead, so the filter is right whatever the tree's depth.
451
+ *
452
+ * An unknown code yields just itself — a hand-typed URL must produce a
453
+ * well-formed zero-hit filter, never an unfiltered listing.
454
+ */
455
+ export async function liveCategorySubtreeCodes(codes: string[]): Promise<string[]> {
456
+ return subtreeCodes(await loadLiveCategoryRows(), codes);
457
+ }
458
+
459
+ /** `parent_id` → its rows, the shape both tree walks below need. */
460
+ function groupByParent(rows: LiveCategoryRow[]): Map<string | null, LiveCategoryRow[]> {
461
+ const byParent = new Map<string | null, LiveCategoryRow[]>();
462
+ for (const row of rows) {
463
+ const siblings = byParent.get(row.parent_id) ?? [];
464
+ siblings.push(row);
465
+ byParent.set(row.parent_id, siblings);
466
+ }
467
+ return byParent;
468
+ }
469
+
470
+ /** Pure core of liveCategorySubtreeCodes(), exported for tests. */
471
+ export function subtreeCodes(rows: LiveCategoryRow[], codes: string[]): string[] {
472
+ const byParent = groupByParent(rows);
473
+ const byCode = new Map(rows.map(row => [row.code, row]));
474
+
475
+ const collected = new Set<string>();
476
+ // Guards the walk against a cyclic parent link in the source data, which
477
+ // would otherwise spin forever inside a request.
478
+ const visited = new Set<string>();
479
+
480
+ for (const code of codes) {
481
+ collected.add(code);
482
+ const root = byCode.get(code);
483
+ if (!root) {
484
+ continue;
485
+ }
486
+ const queue = [root];
487
+ for (let row = queue.pop(); row; row = queue.pop()) {
488
+ if (visited.has(row.id)) {
489
+ continue;
490
+ }
491
+ visited.add(row.id);
492
+ collected.add(row.code);
493
+ queue.push(...(byParent.get(row.id) ?? []));
494
+ }
495
+ }
496
+
497
+ return [...collected];
498
+ }
499
+
500
+ /** One category's subcategory axis, as the storefront's facet needs it. */
501
+ export interface LiveSubcategoryIndex {
502
+ /** Direct child code → its localized label. */
503
+ readonly labels: Map<string, string>;
504
+ /**
505
+ * Any descendant code → the direct child it sits under. Products are indexed
506
+ * at the leaf, so facet counts have to be rolled up to the child level before
507
+ * they mean anything as a subcategory filter.
508
+ */
509
+ readonly branchOf: Map<string, string>;
510
+ }
511
+
512
+ /**
513
+ * The subcategory axis of one category: its direct children, plus the lookup
514
+ * that maps every code beneath them back to the child they belong to.
515
+ *
516
+ * The live index facets on `categories` (codes); the storefront's subcategory
517
+ * facet is label-valued (it mirrors the mock schema, which keeps the slug in a
518
+ * separate field). This is the bridge between the two.
519
+ */
520
+ export async function liveSubcategoryIndex(
521
+ parentCode: string,
522
+ locale: Locale,
523
+ ): Promise<LiveSubcategoryIndex> {
524
+ return subcategoryIndex(await loadLiveCategoryRows(), parentCode, locale);
525
+ }
526
+
527
+ /** Pure core of liveSubcategoryIndex(), exported for tests. */
528
+ export function subcategoryIndex(
529
+ rows: LiveCategoryRow[],
530
+ parentCode: string,
531
+ locale: Locale,
532
+ ): LiveSubcategoryIndex {
533
+ const parent = rows.find(row => row.code === parentCode);
534
+ if (!parent) {
535
+ return { labels: new Map(), branchOf: new Map() };
536
+ }
537
+
538
+ const byParent = groupByParent(rows);
539
+
540
+ const labels = new Map<string, string>();
541
+ const branchOf = new Map<string, string>();
542
+ const visited = new Set<string>();
543
+
544
+ for (const child of byParent.get(parent.id) ?? []) {
545
+ labels.set(child.code, categoryLabel(child, locale));
546
+ const queue = [child];
547
+ for (let row = queue.pop(); row; row = queue.pop()) {
548
+ if (visited.has(row.id)) {
549
+ continue;
550
+ }
551
+ visited.add(row.id);
552
+ branchOf.set(row.code, child.code);
553
+ queue.push(...(byParent.get(row.id) ?? []));
554
+ }
555
+ }
556
+
557
+ return { labels, branchOf };
558
+ }
559
+
560
+ /**
561
+ * Roll `categories` facet counts up onto the direct children they belong to.
562
+ *
563
+ * Products are indexed at their LEAF category, so one subcategory can span many
564
+ * facet values and none of them is the child the storefront filters by. Both the
565
+ * search endpoint's derived `subcategory` facet and the subcategory card grid
566
+ * need the same sum, so it lives here once.
567
+ *
568
+ * Returns child code → product count, children with no products omitted.
569
+ */
570
+ export function rollUpSubcategoryCounts(
571
+ counts: readonly { value: string; count: number }[],
572
+ branchOf: Map<string, string>,
573
+ ): Map<string, number> {
574
+ const byBranch = new Map<string, number>();
575
+ for (const { value, count } of counts) {
576
+ const branch = branchOf.get(value);
577
+ if (branch) {
578
+ byBranch.set(branch, (byBranch.get(branch) ?? 0) + count);
579
+ }
580
+ }
581
+ return byBranch;
582
+ }
583
+
260
584
  // ---------------------------------------------------------------------------
261
585
  // Attribute metadata — resolves the storefront specification table's raw
262
586
  // attribute keys to localized labels, select-option labels and unit suffixes
@@ -294,13 +618,16 @@ const attrMetaCache = new Map<string, { meta: Record<string, LiveAttributeMeta>;
294
618
  /** Specs ordered by attribute group, then declared position. */
295
619
  const SPEC_GROUP_RANK: Record<string, number> = { general: 0, technical: 1 };
296
620
 
297
- async function listAllProducts<T>(path: string): Promise<T[]> {
621
+ async function listAllProducts<T>(
622
+ path: string,
623
+ query: Record<string, string | number> = {},
624
+ ): Promise<T[]> {
298
625
  const sdk = useRevenexxSdk();
299
626
  const out: T[] = [];
300
627
  let offset = 0;
301
628
  for (let page = 0; page < 25; page++) {
302
629
  const res = await sdk.call<{ items?: T[]; page?: { hasMore?: boolean } }>(
303
- "GET", path, { query: { limit: 200, offset } },
630
+ "GET", path, { query: { ...query, limit: 200, offset } },
304
631
  );
305
632
  const items = res.items ?? [];
306
633
  out.push(...items);
@@ -355,6 +682,22 @@ function prettifyAttrKey(key: string): string {
355
682
  return key.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
356
683
  }
357
684
 
685
+ /**
686
+ * One attribute value as a person should read it: a select option code
687
+ * resolved to its label, a declared unit appended. Shared by the detail
688
+ * specification table and the variants axes.
689
+ */
690
+ export function renderLiveAttributeValue(
691
+ meta: LiveAttributeMeta | undefined,
692
+ value: unknown,
693
+ locale: Locale,
694
+ ): string {
695
+ const raw = String(value);
696
+ const option = meta?.options?.[raw];
697
+ const label = option ? pickLiveLabel(option, locale, raw) : raw;
698
+ return meta?.unit && !raw.includes(meta.unit) ? `${label} ${meta.unit}` : label;
699
+ }
700
+
358
701
  /**
359
702
  * Build the product detail specification rows from the doc's `attrs`:
360
703
  * localized label, option/unit-aware value, internal keys hidden. Degrades to
@@ -369,16 +712,14 @@ async function buildSpecRows(attrs: Record<string, unknown>, locale: Locale): Pr
369
712
  meta = {};
370
713
  }
371
714
 
372
- const pick = (labels: Record<string, string> | null | undefined, fallback: string): string =>
373
- labels?.[locale] ?? labels?.de ?? labels?.en ?? fallback;
715
+ const render = (m: LiveAttributeMeta | undefined, value: unknown): string =>
716
+ renderLiveAttributeValue(m, value, locale);
374
717
 
375
- // One value of an attribute, as a person should read it: an option code
376
- // resolved to its label, a declared unit appended.
377
- const render = (m: LiveAttributeMeta | undefined, value: unknown): string => {
378
- const raw = String(value);
379
- const label = m?.options?.[raw] ? pick(m.options[raw], raw) : raw;
380
- return m?.unit && !raw.includes(m.unit) ? `${label} ${m.unit}` : label;
381
- };
718
+ // The logo is rendered as an image by the identity block, so its raw value is
719
+ // never a spec row. Named explicitly (not left to the media-group `hidden`
720
+ // flag) because it must stay hidden even when the attribute metadata could
721
+ // not be loaded and every key degrades to a prettified row.
722
+ const logoAttribute = manufacturerLogoAttribute();
382
723
 
383
724
  const rows = Object.entries(attrs)
384
725
  .filter(([key, value]) => {
@@ -386,7 +727,7 @@ async function buildSpecRows(attrs: Record<string, unknown>, locale: Locale): Pr
386
727
  // A multiselect with nothing chosen is an empty array, which is not
387
728
  // `""` and would otherwise render as a row with no value at all.
388
729
  if (Array.isArray(value) && value.length === 0) return false;
389
- if (key === "image") return false;
730
+ if (key === "image" || key === logoAttribute) return false;
390
731
  return !meta[key]?.hidden;
391
732
  })
392
733
  .map(([key, value]) => {
@@ -399,9 +740,366 @@ async function buildSpecRows(attrs: Record<string, unknown>, locale: Locale): Pr
399
740
  ? value.map(v => render(m, v)).join(", ")
400
741
  : render(m, value);
401
742
  const rank = m?.groupCode && SPEC_GROUP_RANK[m.groupCode] !== undefined ? SPEC_GROUP_RANK[m.groupCode] : 5;
402
- return { label: pick(m?.labels, prettifyAttrKey(key)), value: display, sort: rank * 1000 + (m?.position ?? 999) };
743
+ return { label: pickLiveLabel(m?.labels, locale, prettifyAttrKey(key)), value: display, sort: rank * 1000 + (m?.position ?? 999) };
403
744
  })
404
745
  .sort((a, b) => a.sort - b.sort || a.label.localeCompare(b.label));
405
746
 
406
747
  return rows.map((r, i) => ({ id: i + 1, name: r.label, value: r.value }));
407
748
  }
749
+
750
+ // ---------------------------------------------------------------------------
751
+ // Variants — the PIM's model/article relations.
752
+ //
753
+ // These read the products app's REST rows (/v1/products), NOT the search
754
+ // index: the index holds one flat document per article with no parent link,
755
+ // so the model grouping is only visible on the entity itself.
756
+ // ---------------------------------------------------------------------------
757
+
758
+ /** A products-app product row as /v1/products returns it. */
759
+ interface LivePimProduct {
760
+ id: string;
761
+ sku: string;
762
+ /** "model" for the grouping parent, "variant" for an orderable article. */
763
+ kind: string;
764
+ parent_id: string | null;
765
+ enabled: boolean;
766
+ attribute_values?: {
767
+ common?: Record<string, unknown> | null;
768
+ locale_specific?: Record<string, { name?: string } | null> | null;
769
+ } | null;
770
+ }
771
+
772
+ /**
773
+ * Codes that differ between siblings without distinguishing them for a buyer:
774
+ * per-article identifiers, commercial flags and logistics data. Media-group
775
+ * attributes are excluded separately via their `hidden` metadata.
776
+ */
777
+ const NON_AXIS_ATTRIBUTES = new Set([
778
+ "ean",
779
+ "gtin",
780
+ "manufacturer",
781
+ "manufacturer_aid",
782
+ "manufacturer_logo",
783
+ "order_unit",
784
+ "content_unit",
785
+ "inhaltsmenge",
786
+ "tax_class",
787
+ "sellable",
788
+ "neuheit",
789
+ "price",
790
+ ]);
791
+
792
+ /** Most axes the table stays readable with. */
793
+ const MAX_VARIANT_AXES = 3;
794
+
795
+ /**
796
+ * UN/ECE Recommendation 20 order units, as a buyer reads them. The PIM stores
797
+ * the code (`C62`) and `order_unit` is free text there, so no option labels
798
+ * exist to resolve it — hence this map. Unknown codes pass through unchanged.
799
+ */
800
+ const ORDER_UNIT_LABELS: Record<string, Record<string, string>> = {
801
+ C62: { de: "Stück", en: "pc." },
802
+ H87: { de: "Stück", en: "pc." },
803
+ MTR: { de: "Meter", en: "m" },
804
+ MTK: { de: "m²", en: "m²" },
805
+ KGM: { de: "kg", en: "kg" },
806
+ GRM: { de: "g", en: "g" },
807
+ LTR: { de: "Liter", en: "l" },
808
+ SET: { de: "Set", en: "set" },
809
+ PR: { de: "Paar", en: "pair" },
810
+ BX: { de: "Karton", en: "box" },
811
+ RO: { de: "Rolle", en: "roll" },
812
+ };
813
+
814
+ function liveOrderUnitLabel(raw: unknown, locale: Locale): string | null {
815
+ if (typeof raw !== "string" || raw === "") {
816
+ return null;
817
+ }
818
+ return pickLiveLabel(ORDER_UNIT_LABELS[raw.toUpperCase()], locale, raw);
819
+ }
820
+
821
+ function livePimName(product: LivePimProduct, locale: Locale): string {
822
+ const byLocale = product.attribute_values?.locale_specific ?? {};
823
+ return byLocale[locale]?.name ?? byLocale.de?.name ?? byLocale.en?.name ?? product.sku;
824
+ }
825
+
826
+ /**
827
+ * Which attributes actually distinguish these siblings.
828
+ *
829
+ * The PIM carries no family-variant definition (`family_variant_id` is null
830
+ * throughout), so the axes are DERIVED: take the attributes whose value
831
+ * differs across the group, drop identifiers and internal keys, then add them
832
+ * greedily — most distinct values first — until the chosen combination
833
+ * identifies every sibling uniquely. That stops after the single real axis on
834
+ * a one-axis model instead of also listing attributes that merely correlate
835
+ * with it (a net weight taking two values across five articles), while a true
836
+ * two-axis range still gets both columns.
837
+ */
838
+ function deriveVariantAxisCodes(
839
+ siblings: readonly LivePimProduct[],
840
+ meta: Record<string, LiveAttributeMeta>,
841
+ ): string[] {
842
+ const commons = siblings.map(sibling => sibling.attribute_values?.common ?? {});
843
+ const codes = new Set<string>();
844
+ for (const common of commons) {
845
+ for (const code of Object.keys(common)) {
846
+ codes.add(code);
847
+ }
848
+ }
849
+
850
+ const distinctCount = (code: string): number =>
851
+ new Set(commons.map(common => String(common[code] ?? ""))).size;
852
+
853
+ const candidates = [...codes]
854
+ .filter((code) => {
855
+ if (NON_AXIS_ATTRIBUTES.has(code) || meta[code]?.hidden === true) {
856
+ return false;
857
+ }
858
+ // One value across the whole group distinguishes nothing.
859
+ return distinctCount(code) > 1;
860
+ })
861
+ .map(code => ({
862
+ code,
863
+ distinct: distinctCount(code),
864
+ position: meta[code]?.position ?? 999,
865
+ }))
866
+ .sort((a, b) => b.distinct - a.distinct || a.position - b.position || a.code.localeCompare(b.code));
867
+
868
+ const chosen: string[] = [];
869
+ for (const candidate of candidates) {
870
+ if (chosen.length >= MAX_VARIANT_AXES) {
871
+ break;
872
+ }
873
+ chosen.push(candidate.code);
874
+ const tuples = new Set(
875
+ commons.map(common => chosen.map(code => String(common[code] ?? "")).join("")),
876
+ );
877
+ // Every sibling now has its own combination — further attributes would
878
+ // add columns without adding information.
879
+ if (tuples.size === siblings.length) {
880
+ break;
881
+ }
882
+ }
883
+
884
+ return chosen;
885
+ }
886
+
887
+ /**
888
+ * The sibling articles of a product's model, with the axes distinguishing
889
+ * them. `null` when the product stands alone (no parent, not a model, or a
890
+ * group of one).
891
+ */
892
+ export async function getLiveProductVariants(
893
+ entityId: string,
894
+ locale: Locale,
895
+ ): Promise<ProductVariants | null> {
896
+ const sdk = useRevenexxSdk();
897
+ const product = await sdk.call<LivePimProduct>("GET", `/v1/products/${entityId}`);
898
+
899
+ // A variant points at its model; a model's own page lists its children.
900
+ const modelId = product.parent_id ?? (product.kind === "model" ? product.id : null);
901
+ if (!modelId) {
902
+ return null;
903
+ }
904
+
905
+ const [model, children] = await Promise.all([
906
+ modelId === product.id
907
+ ? Promise.resolve(product)
908
+ : sdk.call<LivePimProduct>("GET", `/v1/products/${modelId}`),
909
+ listAllProducts<LivePimProduct>("/v1/products", { parent_id: modelId }),
910
+ ]);
911
+
912
+ // Disabled articles are out of the catalogue — a row for one would link to
913
+ // a 404. Availability is still carried per row so the table can show it.
914
+ const siblings = children.filter(child => child.enabled !== false);
915
+ if (siblings.length < 2) {
916
+ return null;
917
+ }
918
+
919
+ let meta: Record<string, LiveAttributeMeta> = {};
920
+ try {
921
+ meta = await loadLiveAttributeMeta();
922
+ }
923
+ catch {
924
+ // Without attribute metadata the axes keep their technical codes as
925
+ // labels — a degraded table beats no table.
926
+ meta = {};
927
+ }
928
+
929
+ const axisCodes = deriveVariantAxisCodes(siblings, meta);
930
+
931
+ const axes: ProductVariantAxis[] = axisCodes.map(code => ({
932
+ code,
933
+ label: pickLiveLabel(meta[code]?.labels, locale, code),
934
+ unit: meta[code]?.unit ?? null,
935
+ }));
936
+
937
+ const variants: ProductVariant[] = siblings.map((sibling) => {
938
+ const common = sibling.attribute_values?.common ?? {};
939
+ const values: Record<string, string> = {};
940
+ for (const code of axisCodes) {
941
+ const raw = common[code];
942
+ if (raw !== null && raw !== undefined && raw !== "") {
943
+ values[code] = renderLiveAttributeValue(meta[code], raw, locale);
944
+ }
945
+ }
946
+
947
+ return {
948
+ id: sibling.id,
949
+ sku: sibling.sku,
950
+ name: livePimName(sibling, locale),
951
+ available: sibling.enabled !== false,
952
+ orderUnit: liveOrderUnitLabel(common.order_unit, locale),
953
+ isSelf: sibling.id === entityId,
954
+ values,
955
+ };
956
+ });
957
+
958
+ return {
959
+ variants,
960
+ axes,
961
+ model: { id: model.id, sku: model.sku, name: livePimName(model, locale) },
962
+ };
963
+ }
964
+
965
+ // ---------------------------------------------------------------------------
966
+ // Associations — the articles a product points at, grouped by relation type
967
+ // (accessories, spare parts, follow-ups, …).
968
+ //
969
+ // The relations live on the products app's REST rows; the TARGETS are resolved
970
+ // through the search index, which is what decides what a buyer can reach:
971
+ // only indexed articles have a storefront page, so an unresolvable target is
972
+ // dropped rather than rendered as a tile that leads nowhere.
973
+ // ---------------------------------------------------------------------------
974
+
975
+ interface LiveAssociationTypeRow {
976
+ id: string;
977
+ code: string;
978
+ is_two_way?: boolean;
979
+ is_quantified?: boolean;
980
+ labels?: Record<string, string> | null;
981
+ }
982
+
983
+ interface LiveProductAssociationRow {
984
+ id: string;
985
+ product_id: string;
986
+ association_type_id: string;
987
+ target_product_id: string;
988
+ quantity?: number | null;
989
+ position?: number | null;
990
+ }
991
+
992
+ const ASSOCIATION_TYPE_TTL_MS = 5 * 60 * 1000;
993
+ // Partitioned by tenant, like the category tree and the attribute metadata.
994
+ const associationTypeCache = new Map<string, { types: LiveAssociationTypeRow[]; loadedAt: number }>();
995
+
996
+ /** Association types in the products app's own order — that orders the sections. */
997
+ async function loadLiveAssociationTypes(): Promise<LiveAssociationTypeRow[]> {
998
+ const tenantKey = revenexxTenantKey();
999
+ const cached = associationTypeCache.get(tenantKey);
1000
+ if (cached && Date.now() - cached.loadedAt < ASSOCIATION_TYPE_TTL_MS) {
1001
+ return cached.types;
1002
+ }
1003
+
1004
+ const types = await listAllProducts<LiveAssociationTypeRow>("/v1/products/association_types");
1005
+ associationTypeCache.set(tenantKey, { types, loadedAt: Date.now() });
1006
+ return types;
1007
+ }
1008
+
1009
+ /**
1010
+ * Whether a relation type means "has to be ordered along with the product".
1011
+ *
1012
+ * This is the one place a tenant's association vocabulary is read: the
1013
+ * storefront only ever sees the resulting boolean. `is_quantified` is the
1014
+ * platform's own signal (a relation that carries a quantity is one you order
1015
+ * with the product); the code check covers a type that models the same thing
1016
+ * without a quantity.
1017
+ */
1018
+ function isMandatoryAssociation(type: LiveAssociationTypeRow): boolean {
1019
+ return type.is_quantified === true || type.code === "mandatory";
1020
+ }
1021
+
1022
+ /** Typesense caps a batch; resolve targets in chunks and keep one round trip per chunk. */
1023
+ const TARGET_CHUNK_SIZE = 100;
1024
+
1025
+ async function resolveAssociationTargets(
1026
+ targetIds: readonly string[],
1027
+ locale: Locale,
1028
+ ): Promise<Map<string, Product>> {
1029
+ const chunks: string[][] = [];
1030
+ for (let index = 0; index < targetIds.length; index += TARGET_CHUNK_SIZE) {
1031
+ chunks.push([...targetIds.slice(index, index + TARGET_CHUNK_SIZE)]);
1032
+ }
1033
+
1034
+ // Filtering on `id` (the `{entity_id}:{locale}` document id) rather than
1035
+ // `entity_id`, which is not a filterable field — same reason
1036
+ // getLiveProductDoc() goes through `id:=`.
1037
+ const results = await searchLiveProductsMulti(chunks.map(chunk => ({
1038
+ q: "*",
1039
+ queryBy: "name",
1040
+ filterBy: `id:=[${chunk.map(id => tsFilterValue(`${id}:${locale}`)).join(",")}]`,
1041
+ perPage: chunk.length,
1042
+ })));
1043
+
1044
+ const byId = new Map<string, Product>();
1045
+ for (const result of results) {
1046
+ for (const hit of result.hits ?? []) {
1047
+ byId.set(hit.document.entity_id, mapLiveDocToProduct(hit.document));
1048
+ }
1049
+ }
1050
+ return byId;
1051
+ }
1052
+
1053
+ /**
1054
+ * The articles this product relates to, grouped by relation type. `null` when
1055
+ * it relates to nothing a buyer can actually open.
1056
+ */
1057
+ export async function getLiveProductAssociations(
1058
+ entityId: string,
1059
+ locale: Locale,
1060
+ ): Promise<ProductAssociations | null> {
1061
+ const rows = await listAllProducts<LiveProductAssociationRow>(
1062
+ "/v1/products/product_associations",
1063
+ // NOTE: `product_id` is the filter the endpoint honours. `owner_id` is
1064
+ // accepted and silently IGNORED, answering with the whole table.
1065
+ { product_id: entityId },
1066
+ );
1067
+ if (rows.length === 0) {
1068
+ return null;
1069
+ }
1070
+
1071
+ const types = await loadLiveAssociationTypes();
1072
+ const typeById = new Map(types.map(type => [type.id, type]));
1073
+
1074
+ const targets = await resolveAssociationTargets(
1075
+ [...new Set(rows.map(row => row.target_product_id))],
1076
+ locale,
1077
+ );
1078
+
1079
+ const groups: ProductAssociationGroup[] = [];
1080
+ // Section order follows the association types, not the row order.
1081
+ for (const type of types) {
1082
+ const items: ProductAssociationItem[] = rows
1083
+ .filter(row => typeById.get(row.association_type_id)?.id === type.id)
1084
+ .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))
1085
+ .map(row => targets.get(row.target_product_id))
1086
+ .filter((product): product is Product => product !== undefined)
1087
+ .map(product => ({
1088
+ id: product.id,
1089
+ sku: product.sku,
1090
+ name: product.name,
1091
+ image: product.image,
1092
+ }));
1093
+
1094
+ if (items.length > 0) {
1095
+ groups.push({
1096
+ code: type.code,
1097
+ label: pickLiveLabel(type.labels, locale, type.code),
1098
+ isMandatory: isMandatoryAssociation(type),
1099
+ items,
1100
+ });
1101
+ }
1102
+ }
1103
+
1104
+ return groups.length > 0 ? { groups } : null;
1105
+ }