@revenexx/cover 0.2.26 → 0.2.28

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