@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
@@ -0,0 +1,280 @@
1
+ import type { ProductSubcategory } from "../../../../app/config/navigation";
2
+ import type { SubcategoryTile } from "../../../../app/interfaces/category";
3
+ import type { Locale } from "../../../utils/locale";
4
+
5
+ import {
6
+ liveCategorySubtreeCodes,
7
+ liveSubcategoryIndex,
8
+ mapLiveDocToProduct,
9
+ rollUpSubcategoryCounts,
10
+ searchLiveProducts,
11
+ searchLiveProductsMulti,
12
+ tsFilterValue,
13
+ } from "../../../utils/liveCatalog";
14
+ import { PRODUCTS_COLLECTION } from "../../../utils/productsSchema";
15
+
16
+ /**
17
+ * The subcategory card grid's data: one category's children, each with a product
18
+ * count and a preview image.
19
+ *
20
+ * Neither category tree carries either fact — `ProductSubcategory` is
21
+ * label/slug/icon — so both are derived from the product index. The tree stays
22
+ * authoritative for which children exist and in what order; the index only
23
+ * enriches them.
24
+ *
25
+ * Counts and images are fetched INDEPENDENTLY, each best-effort. They used to
26
+ * share one grouped query, and that cost both: Typesense counts GROUPS rather
27
+ * than documents in `facet_counts` whenever `group_by` is active, so the counts
28
+ * came back as "how many leaf codes" instead of "how many products" (28 where
29
+ * the facet rail rightly said 698), and the grouped hits never yielded an image
30
+ * because `categories` is an array field whose group keys are not bare leaf
31
+ * codes. Splitting them also means an image failure can no longer take the
32
+ * counts down with it, and a category page never 500s because the index is
33
+ * unseeded or unreachable in dev: the tiles then keep `productCount: 0` and
34
+ * `image: null`, which the grid renders as its icon variant.
35
+ */
36
+
37
+ /** Typesense's ceiling for `max_facet_values` — 250 is its own limit. */
38
+ const MAX_SUBCATEGORY_VALUES = 250;
39
+
40
+ /**
41
+ * Sub-searches per multi_search request. Typesense's `limit_multi_searches`
42
+ * defaults to 50; staying under it keeps a category with many children working.
43
+ */
44
+ const SEARCH_BATCH_SIZE = 40;
45
+
46
+ /** Narrowed shape of the mock index's multi_search response. */
47
+ interface MockMultiSearchResponse {
48
+ results?: {
49
+ facet_counts?: { field_name: string; counts?: { value: string; count: number }[] }[];
50
+ hits?: { document: { image?: string } }[];
51
+ }[];
52
+ }
53
+
54
+ function chunk<T>(items: readonly T[], size: number): T[][] {
55
+ const batches: T[][] = [];
56
+ for (let i = 0; i < items.length; i += size) {
57
+ batches.push(items.slice(i, i + size));
58
+ }
59
+ return batches;
60
+ }
61
+
62
+ function toTiles(
63
+ subcategories: readonly ProductSubcategory[],
64
+ counts: Map<string, number>,
65
+ images: Map<string, string>,
66
+ ): SubcategoryTile[] {
67
+ return subcategories.map(sub => ({
68
+ slug: sub.slug,
69
+ label: sub.label,
70
+ icon: sub.icon,
71
+ productCount: counts.get(sub.slug) ?? 0,
72
+ image: images.get(sub.slug) ?? null,
73
+ }));
74
+ }
75
+
76
+ // ---------------------------------------------------------------------------
77
+ // Live index — products are indexed at their LEAF category, so a direct child's
78
+ // products are spread over every code beneath it.
79
+ // ---------------------------------------------------------------------------
80
+
81
+ /** `locale:=… && enabled:=true && categories:=[…]`, the live catalogue's baseline. */
82
+ function liveFilter(locale: Locale, codes: readonly string[]): string {
83
+ return [
84
+ `locale:=${tsFilterValue(locale)}`,
85
+ "enabled:=true",
86
+ `categories:=[${codes.map(tsFilterValue).join(",")}]`,
87
+ ].join(" && ");
88
+ }
89
+
90
+ /**
91
+ * Product counts per direct child. Deliberately the same call shape
92
+ * `api/typesense/search.post.ts` makes for its derived `subcategory` facet, so
93
+ * the cards and the filter rail can never disagree.
94
+ */
95
+ async function liveCounts(categorySlug: string, locale: Locale): Promise<Map<string, number>> {
96
+ const { branchOf } = await liveSubcategoryIndex(categorySlug, locale);
97
+ const leafCodes = await liveCategorySubtreeCodes([categorySlug]);
98
+ if (!leafCodes.length) {
99
+ return new Map();
100
+ }
101
+
102
+ const results = await searchLiveProducts({
103
+ q: "*",
104
+ filterBy: liveFilter(locale, leafCodes),
105
+ facetBy: "categories",
106
+ maxFacetValues: MAX_SUBCATEGORY_VALUES,
107
+ perPage: 1,
108
+ });
109
+
110
+ return rollUpSubcategoryCounts(
111
+ results.facet_counts?.find(fc => fc.field_name === "categories")?.counts ?? [],
112
+ branchOf,
113
+ );
114
+ }
115
+
116
+ /**
117
+ * One representative product image per direct child: a 1-hit search per child,
118
+ * batched into as few multi_search requests as possible.
119
+ *
120
+ * Per child rather than one big page of hits, because a page is capped at 250
121
+ * documents and a category with thousands of products would leave most children
122
+ * imageless — which is exactly how this looked when it was broken.
123
+ */
124
+ async function liveImages(categorySlug: string, locale: Locale): Promise<Map<string, string>> {
125
+ const { branchOf } = await liveSubcategoryIndex(categorySlug, locale);
126
+
127
+ // Invert leaf → child into child → its leaves. No extra catalogue call: the
128
+ // index is already loaded and cached per tenant.
129
+ const leavesByChild = new Map<string, string[]>();
130
+ for (const [leaf, child] of branchOf) {
131
+ const leaves = leavesByChild.get(child) ?? [];
132
+ leaves.push(leaf);
133
+ leavesByChild.set(child, leaves);
134
+ }
135
+
136
+ const children = [...leavesByChild.keys()];
137
+ const images = new Map<string, string>();
138
+
139
+ for (const batch of chunk(children, SEARCH_BATCH_SIZE)) {
140
+ const results = await searchLiveProductsMulti(batch.map(child => ({
141
+ q: "*",
142
+ filterBy: liveFilter(locale, leavesByChild.get(child) ?? [child]),
143
+ perPage: 1,
144
+ })));
145
+
146
+ batch.forEach((child, index) => {
147
+ const doc = results[index]?.hits?.[0]?.document;
148
+ if (doc) {
149
+ images.set(child, mapLiveDocToProduct(doc).image);
150
+ }
151
+ });
152
+ }
153
+
154
+ return images;
155
+ }
156
+
157
+ // ---------------------------------------------------------------------------
158
+ // Mock index — products carry `subcategorySlug` directly, so both halves read
159
+ // that one field. Same two-step shape as the live branch on purpose.
160
+ // ---------------------------------------------------------------------------
161
+
162
+ /** `categorySlug:=[…]`, the clause both mock halves are pinned to. */
163
+ function mockCategoryFilter(categorySlug: string): string {
164
+ return `categorySlug:=[${tsFilterValue(categorySlug)}]`;
165
+ }
166
+
167
+ /**
168
+ * Run a runtime-built list of searches against the mock index.
169
+ *
170
+ * The client's `multiSearch.perform` typings are generic over a TUPLE of
171
+ * document schemas and cannot describe a list whose length is only known at
172
+ * runtime, so the response is narrowed here — the one boundary cast.
173
+ */
174
+ async function mockMultiSearch(
175
+ searches: readonly Record<string, unknown>[],
176
+ ): Promise<NonNullable<MockMultiSearchResponse["results"]>> {
177
+ const results: NonNullable<MockMultiSearchResponse["results"]> = [];
178
+ for (const batch of chunk(searches, SEARCH_BATCH_SIZE)) {
179
+ const response = await useTypesense()
180
+ .multiSearch
181
+ .perform({ searches: batch }) as unknown as MockMultiSearchResponse;
182
+ results.push(...(response.results ?? []));
183
+ }
184
+ return results;
185
+ }
186
+
187
+ async function mockCounts(categorySlug: string): Promise<Map<string, number>> {
188
+ const [result] = await mockMultiSearch([{
189
+ collection: PRODUCTS_COLLECTION,
190
+ q: "*",
191
+ query_by: "name",
192
+ filter_by: mockCategoryFilter(categorySlug),
193
+ facet_by: "subcategorySlug",
194
+ max_facet_values: MAX_SUBCATEGORY_VALUES,
195
+ per_page: 1,
196
+ }]);
197
+
198
+ const counts = result?.facet_counts?.find(fc => fc.field_name === "subcategorySlug")?.counts ?? [];
199
+ return new Map(counts.map(c => [c.value, c.count]));
200
+ }
201
+
202
+ async function mockImages(
203
+ categorySlug: string,
204
+ subcategories: readonly ProductSubcategory[],
205
+ ): Promise<Map<string, string>> {
206
+ // Unique slugs: categories.json ships a category whose subcategories repeat
207
+ // a slug, and a second search for the same slug would be wasted.
208
+ const slugs = [...new Set(subcategories.map(sub => sub.slug))];
209
+
210
+ const results = await mockMultiSearch(slugs.map(slug => ({
211
+ collection: PRODUCTS_COLLECTION,
212
+ q: "*",
213
+ query_by: "name",
214
+ filter_by: `${mockCategoryFilter(categorySlug)} && subcategorySlug:=[${tsFilterValue(slug)}]`,
215
+ include_fields: "image",
216
+ per_page: 1,
217
+ })));
218
+
219
+ const images = new Map<string, string>();
220
+ slugs.forEach((slug, index) => {
221
+ const image = results[index]?.hits?.[0]?.document.image;
222
+ if (image) {
223
+ images.set(slug, image);
224
+ }
225
+ });
226
+ return images;
227
+ }
228
+
229
+ export default defineEventHandler(async (event): Promise<SubcategoryTile[]> => {
230
+ const locale = resolveLocale(event);
231
+ const slug = getRouterParam(event, "slug");
232
+ if (!slug) {
233
+ throw createError({ status: 400, message: "Missing slug" });
234
+ }
235
+
236
+ const category = await getCategoryService(event)
237
+ .getCategoryBySlug(slug, locale)
238
+ .catch((err: unknown) => {
239
+ getLogService().error("Service error: categories/subcategories", { slug, ...toErrorContext(err) });
240
+ throw createError({ statusCode: 500, message: "Internal server error" });
241
+ });
242
+
243
+ if (!category) {
244
+ throw createError({ status: 404, message: "Category not found" });
245
+ }
246
+
247
+ if (!category.subcategories.length) {
248
+ return [];
249
+ }
250
+
251
+ /**
252
+ * Best-effort: the navigation data alone still renders a usable grid, and the
253
+ * two enrichments degrade separately — a failed image lookup must not cost
254
+ * the counts, which is what a single shared query used to do.
255
+ */
256
+ function degrade<T>(what: string) {
257
+ return (err: unknown): Map<string, T> => {
258
+ getLogService().warn(
259
+ `categories/subcategories: ${what} unavailable, serving tiles without them`,
260
+ { slug, ...toErrorContext(err) },
261
+ );
262
+ return new Map<string, T>();
263
+ };
264
+ }
265
+
266
+ const isLive = resolveProductServiceKey(event) === "api";
267
+
268
+ const [counts, images] = await Promise.all([
269
+ (isLive
270
+ ? liveCounts(category.slug, locale)
271
+ : mockCounts(category.slug)
272
+ ).catch(degrade<number>("product counts")),
273
+ (isLive
274
+ ? liveImages(category.slug, locale)
275
+ : mockImages(category.slug, category.subcategories)
276
+ ).catch(degrade<string>("preview images")),
277
+ ]);
278
+
279
+ return toTiles(category.subcategories, counts, images);
280
+ });
@@ -0,0 +1,27 @@
1
+ import type { ProductAssociations } from "../../../../app/interfaces/product-associations";
2
+
3
+ /** A product that relates to nothing — an answer, not an error. */
4
+ const NO_ASSOCIATIONS: ProductAssociations = { groups: [] };
5
+
6
+ export default defineEventHandler(async (event): Promise<ProductAssociations> => {
7
+ const id = getRouterParam(event, "id") ?? "";
8
+ if (!id) {
9
+ throw createError({ statusCode: 400, message: "Invalid product id" });
10
+ }
11
+
12
+ const locale = resolveLocale(event);
13
+
14
+ try {
15
+ // A product with no relations answers 200 with no groups: the grid is an
16
+ // enrichment, so "this product has none" must not read as a failure the
17
+ // client has to special-case.
18
+ return await getProductService(event).getProductAssociations(id, locale) ?? NO_ASSOCIATIONS;
19
+ }
20
+ catch (err) {
21
+ if (err !== null && typeof err === "object" && "statusCode" in err) {
22
+ throw err;
23
+ }
24
+ getLogService().error("Service error: product/associations", { id, ...toErrorContext(err) });
25
+ throw createError({ statusCode: 500, message: "Internal server error" });
26
+ }
27
+ });
@@ -0,0 +1,27 @@
1
+ import type { ProductVariants } from "../../../../app/interfaces/product-variants";
2
+
3
+ /** A product that belongs to no model — an answer, not an error. */
4
+ const NO_VARIANTS: ProductVariants = { variants: [], axes: [], model: null };
5
+
6
+ export default defineEventHandler(async (event): Promise<ProductVariants> => {
7
+ const id = getRouterParam(event, "id") ?? "";
8
+ if (!id) {
9
+ throw createError({ statusCode: 400, message: "Invalid product id" });
10
+ }
11
+
12
+ const locale = resolveLocale(event);
13
+
14
+ try {
15
+ // A standalone article answers 200 with an empty group: the variants
16
+ // section is an enrichment, so "this product has none" must not read as
17
+ // a failure the client has to special-case.
18
+ return await getProductService(event).getProductVariants(id, locale) ?? NO_VARIANTS;
19
+ }
20
+ catch (err) {
21
+ if (err !== null && typeof err === "object" && "statusCode" in err) {
22
+ throw err;
23
+ }
24
+ getLogService().error("Service error: product/variants", { id, ...toErrorContext(err) });
25
+ throw createError({ statusCode: 500, message: "Internal server error" });
26
+ }
27
+ });
@@ -0,0 +1,43 @@
1
+ import { quickActions } from "../../app/config/quickActions";
2
+
3
+ /**
4
+ * The shortcut catalogue behind the `quick_actions` block, with its i18n keys
5
+ * already resolved.
6
+ *
7
+ * This exists for the blökkli picker overlay: that component is compiled
8
+ * through the editor's own runtime pipeline, so it has neither Nuxt's `$fetch`
9
+ * nor `useI18n()` and cannot translate a key itself. The block on the page does
10
+ * NOT call this — it holds the same registry and resolves the keys through
11
+ * `useI18n()` with no round-trip.
12
+ *
13
+ * Static config, not a BFF domain: no service interface, no app.config registry
14
+ * key, nothing to switch between mock and live.
15
+ */
16
+
17
+ /**
18
+ * `serverT` scopes a key to one locale FILE, but the registry's keys span two
19
+ * (`header.cart` lives in common.json, the rest in account.json). A miss
20
+ * returns the key unchanged, which is the signal to try the next namespace.
21
+ */
22
+ const NAMESPACES = ["account", "common"];
23
+
24
+ function translate(key: string, locale: string): string {
25
+ for (const namespace of NAMESPACES) {
26
+ const value = serverT(key, locale, namespace);
27
+ if (value !== key) {
28
+ return value;
29
+ }
30
+ }
31
+ return key;
32
+ }
33
+
34
+ export default defineEventHandler(async (event) => {
35
+ const locale = resolveLocale(event);
36
+ await preloadLocaleNamespaces(locale, NAMESPACES);
37
+
38
+ return quickActions.map(action => ({
39
+ id: action.id,
40
+ label: translate(action.labelKey, locale),
41
+ description: translate(action.descriptionKey, locale),
42
+ }));
43
+ });
@@ -1,7 +1,8 @@
1
1
  import type { ProductList } from "../../../app/interfaces/product-list";
2
2
  import type { SearchFacet } from "../../../app/interfaces/search-facets";
3
+ import type { Locale } from "../../utils/locale";
3
4
 
4
- import { loadLiveAttributeMeta } from "../../utils/liveCatalog";
5
+ import { liveCategorySubtreeCodes, liveSubcategoryIndex, loadLiveAttributeMeta, rollUpSubcategoryCounts } from "../../utils/liveCatalog";
5
6
  import { FACET_FIELDS, PRODUCTS_COLLECTION } from "../../utils/productsSchema";
6
7
 
7
8
  /**
@@ -29,6 +30,36 @@ function isMissingSortFieldError(err: unknown): boolean {
29
30
  return /Could not find a field named .* in the schema for sorting/i.test(msg);
30
31
  }
31
32
 
33
+ /**
34
+ * The live category codes behind the storefront's subcategory filter values.
35
+ *
36
+ * `subcategorySlug` carries a code already; the user-facing `subcategory` facet
37
+ * is LABEL-valued (it mirrors the mock schema, where the slug lives in its own
38
+ * field), so a value picked in the rail arrives as a label. Both are accepted —
39
+ * an unmatched value is passed through as a code so a hand-edited URL yields an
40
+ * honest zero-hit filter rather than silently dropping the constraint.
41
+ */
42
+ async function resolveSubcategoryCodes(
43
+ values: string[],
44
+ parentCode: string,
45
+ locale: Locale,
46
+ ): Promise<string[]> {
47
+ if (!parentCode) {
48
+ return values;
49
+ }
50
+ const { labels } = await liveSubcategoryIndex(parentCode, locale);
51
+ return values.map((value) => {
52
+ if (labels.has(value)) {
53
+ return value;
54
+ }
55
+ const match = [...labels.entries()].find(([, label]) => label === value);
56
+ return match?.[0] ?? value;
57
+ });
58
+ }
59
+
60
+ /** Typesense's own ceiling for `max_facet_values`. */
61
+ const LIVE_MAX_FACET_VALUES = 250;
62
+
32
63
  type SortOption = "relevance" | "price_asc" | "price_desc" | "name_asc" | "name_desc" | "sku_asc" | "sku_desc";
33
64
 
34
65
  const SORT_MAP: Record<SortOption, string> = {
@@ -81,24 +112,34 @@ export default defineEventHandler(async (event) => {
81
112
  .filter(([, m]) => m.isFilterable && !m.hidden)
82
113
  .map(([code]) => code);
83
114
 
115
+ // The category this request is pinned to, kept for the facet mapping
116
+ // below — the live index facets on `categories` (codes), the storefront
117
+ // asks for a `subcategory` facet of that category's children.
118
+ let pinnedCategoryCode = "";
119
+
84
120
  if (filters) {
85
121
  // The storefront filters with the demo-schema field names; the
86
122
  // live collection (search.json) names them differently. Category
87
123
  // slugs ARE the live category codes, but products carry their
88
- // LEAF code only — a top-level category expands to its children.
124
+ // LEAF code only — a branch expands to its whole subtree.
89
125
  // Unknown fields are dropped instead of 400ing the request.
126
+ //
127
+ // Category and subcategory are collected SEPARATELY: they used to
128
+ // share one array and were emitted as a single OR'd clause, which
129
+ // made a subcategory page return its parent's entire catalogue
130
+ // instead of narrowing it. The narrower of the two wins.
90
131
  const categoryCodes: string[] = [];
91
- const tree = await getLiveCategories(locale);
132
+ const subcategoryValues: string[] = [];
92
133
 
93
134
  for (const [field, values] of Object.entries(filters)) {
94
135
  if (!values?.length) {
95
136
  continue;
96
137
  }
97
- if (field === "categorySlug" || field === "subcategorySlug" || field === "categories") {
98
- for (const value of values) {
99
- const node = tree.find(c => c.slug === value);
100
- categoryCodes.push(value, ...(node?.subcategories.map(s => s.slug) ?? []));
101
- }
138
+ if (field === "categorySlug" || field === "categories") {
139
+ categoryCodes.push(...values);
140
+ }
141
+ else if (field === "subcategorySlug" || field === "subcategory") {
142
+ subcategoryValues.push(...values);
102
143
  }
103
144
  else if (field === "manufacturer" || field === "kind") {
104
145
  liveFilterParts.push(`${field}:=[${values.map(v => tsFilterValue(v)).join(",")}]`);
@@ -116,8 +157,22 @@ export default defineEventHandler(async (event) => {
116
157
  }
117
158
  }
118
159
 
119
- if (categoryCodes.length) {
120
- liveFilterParts.push(`categories:=[${[...new Set(categoryCodes)].map(tsFilterValue).join(",")}]`);
160
+ pinnedCategoryCode = categoryCodes[0] ?? "";
161
+
162
+ // Resolved after the loop, not inside it: `filters` merges the
163
+ // user's selection over the page's fixed filters, so `subcategory`
164
+ // can be enumerated before `categorySlug` and the parent would not
165
+ // be known yet.
166
+ const subcategoryCodes = subcategoryValues.length
167
+ ? await resolveSubcategoryCodes(subcategoryValues, pinnedCategoryCode, locale)
168
+ : [];
169
+
170
+ // Deepest wins: a subcategory replaces its parent's clause rather
171
+ // than being OR'd next to it.
172
+ const branchCodes = subcategoryCodes.length ? subcategoryCodes : categoryCodes;
173
+ if (branchCodes.length) {
174
+ const leafCodes = await liveCategorySubtreeCodes(branchCodes);
175
+ liveFilterParts.push(`categories:=[${leafCodes.map(tsFilterValue).join(",")}]`);
121
176
  }
122
177
  }
123
178
 
@@ -157,6 +212,11 @@ export default defineEventHandler(async (event) => {
157
212
  queryBy: "name,sku,description,manufacturer",
158
213
  filterBy: liveFilterParts.join(" && "),
159
214
  facetBy,
215
+ // Typesense answers with 10 values per facet when this is unset,
216
+ // which silently truncates the rail AND undercounts the subcategory
217
+ // roll-up below (products are indexed at the leaf, so one child can
218
+ // span many facet values). 250 is Typesense's own ceiling.
219
+ maxFacetValues: LIVE_MAX_FACET_VALUES,
160
220
  ...(sortBy ? { sortBy } : {}),
161
221
  page,
162
222
  perPage,
@@ -206,6 +266,29 @@ export default defineEventHandler(async (event) => {
206
266
  counts: (fc.counts ?? []).map(c => ({ value: c.value, count: c.count })),
207
267
  }));
208
268
 
269
+ // The category page asks for a `subcategory` facet; the live index
270
+ // only knows `categories`. Without this bridge the field names never
271
+ // meet and the drill-down is invisible in live mode. Derived rather
272
+ // than renamed — the search page still consumes `categories`.
273
+ if (pinnedCategoryCode) {
274
+ const { labels, branchOf } = await liveSubcategoryIndex(pinnedCategoryCode, locale);
275
+ // Counts arrive on the LEAF codes, so they are summed back up
276
+ // onto the direct child each leaf belongs to.
277
+ const byBranch = rollUpSubcategoryCounts(
278
+ facets.find(f => f.fieldName === "categories")?.counts ?? [],
279
+ branchOf,
280
+ );
281
+ if (byBranch.size) {
282
+ facets.push({
283
+ fieldName: "subcategory",
284
+ counts: [...byBranch].map(([code, count]) => ({
285
+ value: labels.get(code) ?? code,
286
+ count,
287
+ })),
288
+ });
289
+ }
290
+ }
291
+
209
292
  return {
210
293
  products,
211
294
  facets,
@@ -246,18 +329,38 @@ export default defineEventHandler(async (event) => {
246
329
 
247
330
  const sortBy = SORT_MAP[sort] ?? SORT_MAP.relevance;
248
331
 
249
- try {
250
- const results = await ts.collections(PRODUCTS_COLLECTION).documents().search({
332
+ const runSearch = (sortByParam: string | undefined) =>
333
+ ts.collections(PRODUCTS_COLLECTION).documents().search({
251
334
  q,
252
335
  query_by: "name,sku",
253
336
  facet_by: FACET_FIELDS.join(","),
254
337
  num_typos: 2,
255
338
  ...(filterParts.length ? { filter_by: filterParts.join(" && ") } : {}),
256
- sort_by: sortBy,
339
+ ...(sortByParam ? { sort_by: sortByParam } : {}),
257
340
  page,
258
341
  per_page: perPage,
259
342
  });
260
343
 
344
+ try {
345
+ // Same fallback the live branch makes: a collection provisioned before
346
+ // `name`/`sku` were declared `sort: true` answers 404 for those sorts.
347
+ // Sorting is a nicety, the listing is not — retry unsorted rather than
348
+ // fail the page, and let it start working once the tenant re-seeds.
349
+ let results;
350
+ try {
351
+ results = await runSearch(sortBy);
352
+ }
353
+ catch (err) {
354
+ if (!isMissingSortFieldError(err)) {
355
+ throw err;
356
+ }
357
+ getLogService().warn(
358
+ "search: collection has no sortable field for this sort, retrying unsorted",
359
+ toErrorContext(err),
360
+ );
361
+ results = await runSearch(undefined);
362
+ }
363
+
261
364
  // Catalog shell only. The index keeps a scalar `price` purely as a
262
365
  // sort/filter key (catalog list price) and the catalog tax rate; the
263
366
  // buyer-facing price tiers + availability are the Offer domain and
@@ -117,6 +117,11 @@
117
117
  "label": "Xiaomi",
118
118
  "slug": "xiaomi",
119
119
  "icon": "smartphone"
120
+ },
121
+ {
122
+ "label": "Accessories",
123
+ "slug": "phone-accessories",
124
+ "icon": "plug-circle"
120
125
  }
121
126
  ]
122
127
  },
@@ -0,0 +1,44 @@
1
+ {
2
+ "_comment": "Demo product associations. `types` fixes the group order and their labels; `byProduct` wins over `byCategory`, which keys on the MAIN category slug so every phone gets the accessory set from one entry instead of twenty. Target ids point at product-list.json, where each item's name, sku and image are read from — nothing is duplicated here.",
3
+ "types": [
4
+ {
5
+ "code": "accessories",
6
+ "labels": {
7
+ "de": "Zubehör",
8
+ "en": "Accessories"
9
+ }
10
+ },
11
+ {
12
+ "code": "mandatory",
13
+ "labels": {
14
+ "de": "Pflichtzubehör",
15
+ "en": "Mandatory accessories"
16
+ },
17
+ "isMandatory": true
18
+ },
19
+ {
20
+ "code": "sparepart",
21
+ "labels": {
22
+ "de": "Ersatzteile",
23
+ "en": "Spare parts"
24
+ }
25
+ }
26
+ ],
27
+ "byCategory": {
28
+ "mobile-phones": {
29
+ "accessories": ["7001", "7002", "7003", "7005"],
30
+ "mandatory": ["7004"]
31
+ },
32
+ "technology": {
33
+ "accessories": ["7002", "7003", "7005"]
34
+ }
35
+ },
36
+ "byProduct": {
37
+ "7001": {
38
+ "sparepart": ["7004"]
39
+ },
40
+ "7005": {
41
+ "accessories": ["7002", "7003"]
42
+ }
43
+ }
44
+ }