@revenexx/cover 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/app/api/product.ts +1 -0
  2. package/app/components/layout/header/LocaleSwitcher.vue +96 -12
  3. package/app/components/ui/forms/SearchInput.vue +205 -8
  4. package/app/composables/useProductCard.ts +14 -0
  5. package/app/composables/useProductListing.ts +27 -1
  6. package/app/composables/useProductLocales.ts +56 -0
  7. package/app/composables/useSearchEvents.ts +67 -0
  8. package/app/interfaces/market.ts +7 -0
  9. package/app/layouts/default.vue +10 -1
  10. package/app/plugins/search-events.client.ts +41 -0
  11. package/app/shared/locale.ts +133 -0
  12. package/app/shared/productLocales.ts +109 -0
  13. package/app/shared/searchAttribution.ts +91 -0
  14. package/app/shared/themeEvents.ts +1 -1
  15. package/i18n/locales/de/common.json +2 -1
  16. package/i18n/locales/de/search.json +7 -0
  17. package/i18n/locales/en/common.json +2 -1
  18. package/i18n/locales/en/search.json +7 -0
  19. package/package.json +1 -1
  20. package/server/api/brands.get.ts +3 -2
  21. package/server/api/categories/[slug]/subcategories.get.ts +9 -6
  22. package/server/api/product/[id]/locales.get.ts +57 -0
  23. package/server/api/products/index.get.ts +6 -1
  24. package/server/api/search/events.post.ts +65 -0
  25. package/server/api/typesense/search.post.ts +12 -1
  26. package/server/api/typesense/suggest.post.ts +43 -22
  27. package/server/interfaces/brand.ts +3 -2
  28. package/server/interfaces/product.ts +13 -0
  29. package/server/services/ApiBrandService.ts +8 -8
  30. package/server/services/ApiMarketService.ts +9 -2
  31. package/server/services/ApiProductService.ts +5 -1
  32. package/server/utils/liveCatalog.ts +69 -0
  33. package/server/utils/locale.ts +58 -4
  34. package/server/utils/searchClient.ts +27 -4
  35. package/server/utils/searchEvents.ts +46 -0
  36. package/server/utils/searchMultiSearchFallback.ts +2 -0
  37. package/server/utils/searchSuggest.ts +207 -0
  38. package/server/utils/suggestTiles.ts +141 -0
@@ -1,5 +1,14 @@
1
1
  <script setup lang="ts">
2
- const head = useLocaleHead({ seo: true });
2
+ import { filterLocaleHeadAlternates } from "../shared/productLocales";
3
+
4
+ const localeHead = useLocaleHead({ seo: true });
5
+ // A product page links only the languages the product has a page in
6
+ // (PE-859 hides untranslated products); every other page is unchanged.
7
+ const { available: productLocales } = useProductLocales();
8
+ const head = computed(() => ({
9
+ ...localeHead.value,
10
+ ...filterLocaleHeadAlternates(localeHead.value, productLocales.value),
11
+ }));
3
12
  const { navigateToSearch } = useSearch();
4
13
  const route = useRoute();
5
14
  const cart = useCartStore();
@@ -0,0 +1,41 @@
1
+ import type { ThemeEventEnvelope } from "@revenexx/tag-manager-nuxt/events";
2
+
3
+ import { forgetSearchAttributions, searchAttributions } from "../shared/searchAttribution";
4
+ import { browserSession } from "../shared/themeEvents";
5
+
6
+ /**
7
+ * Add-to-cart and purchase as search events (PE-867).
8
+ *
9
+ * The cart and the checkout already report both as theme events, once and
10
+ * only for what really happened (theme-events.client.ts). This listens to
11
+ * those and, for every article a search led to (searchAttribution.ts), tells
12
+ * the search service — so the analytics see which searches end in a cart or
13
+ * an order, without a second set of hooks in the cart.
14
+ */
15
+ export default defineNuxtPlugin({
16
+ name: "cover:search-events",
17
+ dependsOn: ["cover:theme-events"],
18
+ setup(nuxtApp) {
19
+ const { send } = useSearchEvents();
20
+
21
+ nuxtApp.hook("revenexx:event", (envelope: ThemeEventEnvelope) => {
22
+ if (envelope.event !== "add_to_cart" && envelope.event !== "purchase") {
23
+ return;
24
+ }
25
+ const skus = (envelope.ecommerce?.items ?? []).map(item => item.sku).filter(Boolean);
26
+ const storage = browserSession();
27
+ for (const { attribution } of searchAttributions(storage, skus)) {
28
+ send({
29
+ type: envelope.event,
30
+ queryId: attribution.queryId,
31
+ collection: "products",
32
+ docId: attribution.docId,
33
+ q: attribution.q,
34
+ });
35
+ }
36
+ if (envelope.event === "purchase") {
37
+ forgetSearchAttributions(storage, skus);
38
+ }
39
+ });
40
+ },
41
+ });
@@ -112,3 +112,136 @@ export function pickLocalizedLabel(
112
112
  }
113
113
  return fallback;
114
114
  }
115
+
116
+ /**
117
+ * Where a market locale stands in its rollout (markets app, PE-866):
118
+ * `preparing` while the catalogue and search are being built for it, then
119
+ * `active`. A locale without a status predates the field and is active.
120
+ */
121
+ export type MarketLocaleStatus = "preparing" | "active";
122
+
123
+ /** The part of a market locale the language choice needs. */
124
+ export interface MarketLocaleRef {
125
+ /** BCP-47 code as the market stores it, e.g. "de-CH". */
126
+ code: string;
127
+ /** ISO 639-1 language, e.g. "de". Derived from the code when empty. */
128
+ language?: string;
129
+ isDefault?: boolean;
130
+ status?: MarketLocaleStatus | string | null;
131
+ }
132
+
133
+ /** Whether the storefront may offer this locale: anything but `preparing`. */
134
+ export function isOfferedLocale(locale: Pick<MarketLocaleRef, "status">): boolean {
135
+ return locale.status !== "preparing";
136
+ }
137
+
138
+ /**
139
+ * The locales a market offers its buyers, in the order to show them: the
140
+ * market's default first, the rest as the market lists them. A `preparing`
141
+ * locale is left out, and so is a second entry for the same code.
142
+ */
143
+ export function offeredLocales<T extends MarketLocaleRef>(locales: readonly T[] | null | undefined): T[] {
144
+ const seen = new Set<string>();
145
+ const offered: T[] = [];
146
+ for (const locale of locales ?? []) {
147
+ const code = normalizeLocaleCode(locale.code);
148
+ if (!code || !isOfferedLocale(locale) || seen.has(code)) {
149
+ continue;
150
+ }
151
+ seen.add(code);
152
+ offered.push(locale);
153
+ }
154
+ return [...offered.filter(l => l.isDefault), ...offered.filter(l => !l.isDefault)];
155
+ }
156
+
157
+ /** The language of a market locale, from its `language` or its code. */
158
+ export function marketLocaleLanguage(locale: MarketLocaleRef): string {
159
+ return (locale.language?.trim() || localeLanguage(locale.code)).toLowerCase();
160
+ }
161
+
162
+ /** One entry of the language choice. */
163
+ export interface LanguageOption {
164
+ /** The market locale the catalogue and search are asked in, e.g. "de-CH". */
165
+ locale: string;
166
+ language: string;
167
+ /** The UI language the pages render in: the language itself, or the default UI language. */
168
+ uiLocale: string;
169
+ /** True when there are no UI strings for this language and the default UI language stands in. */
170
+ uiFallback: boolean;
171
+ }
172
+
173
+ /**
174
+ * The languages a market offers, one per language (the first locale the
175
+ * market offers for it wins, so the market's default leads). A language the
176
+ * storefront has no UI strings for is still offered: its catalogue and
177
+ * search answer in that language, the pages render in the default UI
178
+ * language. Null when the market offers no locale: the caller keeps its
179
+ * fixed UI languages, as before markets carried locales.
180
+ */
181
+ export function marketLanguageOptions(
182
+ locales: readonly MarketLocaleRef[] | null | undefined,
183
+ uiLanguages: readonly string[],
184
+ defaultUiLanguage: string,
185
+ ): LanguageOption[] | null {
186
+ const offered = offeredLocales(locales ?? []);
187
+ if (!offered.length) {
188
+ return null;
189
+ }
190
+ const ui = new Set(uiLanguages.map(code => code.toLowerCase()));
191
+ const options: LanguageOption[] = [];
192
+ const languages = new Set<string>();
193
+ for (const entry of offered) {
194
+ const language = marketLocaleLanguage(entry);
195
+ if (!language || languages.has(language)) {
196
+ continue;
197
+ }
198
+ languages.add(language);
199
+ const hasUi = ui.has(language);
200
+ options.push({
201
+ locale: normalizeLocaleCode(entry.code),
202
+ language,
203
+ uiLocale: hasUi ? language : defaultUiLanguage,
204
+ uiFallback: !hasUi,
205
+ });
206
+ }
207
+ return options;
208
+ }
209
+
210
+ /**
211
+ * The market locale the catalogue and search are asked in, for a page that
212
+ * renders in `uiLanguage`.
213
+ *
214
+ * `chosen` is the buyer's explicit choice (a market locale code). It wins
215
+ * when it is offered and agrees with the page: same language, or a language
216
+ * without UI strings shown in the default UI language. Otherwise the
217
+ * market's locale for the page language, else `fallback` (the bare
218
+ * language's full code, what the storefront asked before markets carried
219
+ * locales). A `preparing` locale is never answered.
220
+ */
221
+ export function pickMarketLocale(input: {
222
+ locales: readonly MarketLocaleRef[] | null | undefined;
223
+ chosen?: string | null;
224
+ uiLanguage: string;
225
+ uiLanguages: readonly string[];
226
+ defaultUiLanguage: string;
227
+ }): string {
228
+ const uiLanguage = input.uiLanguage.toLowerCase();
229
+ const offered = offeredLocales(input.locales ?? []);
230
+ const ui = new Set(input.uiLanguages.map(code => code.toLowerCase()));
231
+
232
+ if (input.chosen) {
233
+ const chosen = normalizeLocaleCode(input.chosen);
234
+ const hit = offered.find(entry => normalizeLocaleCode(entry.code) === chosen);
235
+ if (hit) {
236
+ const language = marketLocaleLanguage(hit);
237
+ const agrees = language === uiLanguage
238
+ || (!ui.has(language) && uiLanguage === input.defaultUiLanguage.toLowerCase());
239
+ if (agrees) {
240
+ return normalizeLocaleCode(hit.code);
241
+ }
242
+ }
243
+ }
244
+
245
+ const sameLanguage = offered.find(entry => marketLocaleLanguage(entry) === uiLanguage);
246
+ return sameLanguage ? normalizeLocaleCode(sameLanguage.code) : fullLocaleCode(uiLanguage);
247
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Which storefront languages a product has a page in, and what that does to
3
+ * the links pointing at those pages.
4
+ *
5
+ * With `search_untranslated=hide` (baseline PE-859) a product only has search
6
+ * documents in the languages it is translated into; the tenant's main
7
+ * language is always there. The product page looks its document up under the
8
+ * request language's keys (`searchLocaleKeys`), so a language without such a
9
+ * document is a 404. The language switcher and the hreflang alternates must
10
+ * not send anyone there.
11
+ *
12
+ * Pure functions, shared by the BFF (which reads the documents) and the
13
+ * client (which filters the links), so both decide availability the same way.
14
+ */
15
+ import { localeLanguage, normalizeLocaleCode, searchLocaleKeys } from "./locale";
16
+
17
+ /**
18
+ * The languages (of `languages`, in their order) that have a document among
19
+ * `docLocales`. A language counts as available exactly when the product page
20
+ * would find a document for it: one whose locale is one of the language's
21
+ * search keys (`de` → `de-DE` or `de`). Both spellings match in both
22
+ * directions, so this holds before, during and after the full-code migration
23
+ * (PE-851). A `de-AT` document does not make `de` available, because the
24
+ * page would not find it either.
25
+ */
26
+ export function languagesWithDocuments(
27
+ docLocales: readonly string[],
28
+ languages: readonly string[],
29
+ ): string[] {
30
+ const present = new Set(docLocales.filter(Boolean).map(normalizeLocaleCode));
31
+ return languages.filter(language =>
32
+ searchLocaleKeys(language).some(key => present.has(key)));
33
+ }
34
+
35
+ /**
36
+ * The listing a language without the product sends the buyer to: the
37
+ * product's own category, as deep as a listing URL goes
38
+ * (`/category/<category>/<subcategory>`). The `_` placeholder of an
39
+ * uncategorised product is not a category, so that case (and any URL without
40
+ * a category) goes to the home page instead. Category codes are not
41
+ * translated, so the same path exists in every language.
42
+ */
43
+ export function productFallbackPath(categorySegments: readonly string[]): string {
44
+ const path = categorySegments.filter(segment => segment && segment !== "_").slice(0, 2);
45
+ return path.length ? `/category/${path.map(encodeURIComponent).join("/")}` : "/";
46
+ }
47
+
48
+ /** The category segments of a `/category/<…>/product/<slug>` route. */
49
+ export function productRouteCategorySegments(category: readonly string[], rest: readonly string[]): string[] {
50
+ const marker = rest.lastIndexOf("product");
51
+ return [...category, ...(marker >= 0 ? rest.slice(0, marker) : [])];
52
+ }
53
+
54
+ /** The parts of a `useLocaleHead()` result this module touches. */
55
+ export interface LocaleHeadLink {
56
+ id?: string;
57
+ rel?: string;
58
+ href?: string;
59
+ hreflang?: string;
60
+ [key: string]: unknown;
61
+ }
62
+
63
+ export interface LocaleHeadMeta {
64
+ id?: string;
65
+ property?: string;
66
+ content?: string;
67
+ [key: string]: unknown;
68
+ }
69
+
70
+ /**
71
+ * The locale head with alternates only for the languages that have the page.
72
+ *
73
+ * `available` is the list of available storefront locale codes, or `null`
74
+ * when it is not known (not a product page, or the lookup failed) — then the
75
+ * head is returned unchanged, which is what every other page gets.
76
+ *
77
+ * Dropped: `rel="alternate"` links whose hreflang names an unavailable
78
+ * language, `x-default` unless its URL is one of the alternates that stay
79
+ * (it points at the default locale's URL, which may be one of the dropped
80
+ * ones), and `og:locale:alternate` metas for unavailable languages. Canonical
81
+ * and `og:locale` describe the current page and stay. Matching is by language
82
+ * subtag, the same unit availability is decided in.
83
+ */
84
+ export function filterLocaleHeadAlternates<L extends LocaleHeadLink, M extends LocaleHeadMeta>(
85
+ head: { link?: L[]; meta?: M[] },
86
+ available: readonly string[] | null,
87
+ ): { link: L[]; meta: M[] } {
88
+ const link = head.link ?? [];
89
+ const meta = head.meta ?? [];
90
+ if (!available) {
91
+ return { link, meta };
92
+ }
93
+
94
+ const languages = new Set(available.map(localeLanguage));
95
+ const offered = (code: string): boolean => languages.has(localeLanguage(code));
96
+ const isAlternate = (entry: L): boolean => entry.rel === "alternate" && Boolean(entry.hreflang);
97
+
98
+ const kept = link.filter(entry =>
99
+ !isAlternate(entry) || entry.hreflang === "x-default" || offered(entry.hreflang as string));
100
+ const keptHrefs = new Set(kept
101
+ .filter(entry => isAlternate(entry) && entry.hreflang !== "x-default")
102
+ .map(entry => entry.href));
103
+
104
+ return {
105
+ link: kept.filter(entry => !isAlternate(entry) || entry.hreflang !== "x-default" || keptHrefs.has(entry.href)),
106
+ meta: meta.filter(entry =>
107
+ entry.property !== "og:locale:alternate" || !entry.content || offered(entry.content)),
108
+ };
109
+ }
@@ -0,0 +1,91 @@
1
+ import type { StorageLike } from "./themeEvents";
2
+
3
+ /**
4
+ * Which search led to a product (PE-867). A click from a search result or the
5
+ * quick search is remembered per article number, so the add-to-cart and the
6
+ * purchase that follow can be counted for that search. Kept in the tab's
7
+ * session storage only: it never leaves the browser except as the events
8
+ * themselves, and it ends with the tab.
9
+ */
10
+
11
+ export interface SearchAttribution {
12
+ queryId: string;
13
+ /** The product's search document id, sent back as the event's doc_id. */
14
+ docId: string;
15
+ q: string;
16
+ at: number;
17
+ }
18
+
19
+ const KEY = "rvx:search-attribution";
20
+ /** A click older than this no longer explains a cart. */
21
+ export const ATTRIBUTION_TTL_MS = 24 * 60 * 60 * 1000;
22
+ /** Products remembered at most; the oldest go first. */
23
+ export const ATTRIBUTION_LIMIT = 50;
24
+
25
+ type Store = Record<string, SearchAttribution>;
26
+
27
+ function read(storage: StorageLike | null | undefined, now: number): Store {
28
+ try {
29
+ const parsed = JSON.parse(storage?.getItem(KEY) ?? "{}") as Store;
30
+ const fresh: Store = {};
31
+ for (const [sku, entry] of Object.entries(parsed ?? {})) {
32
+ if (entry && typeof entry.queryId === "string" && typeof entry.at === "number" && now - entry.at < ATTRIBUTION_TTL_MS) {
33
+ fresh[sku] = entry;
34
+ }
35
+ }
36
+ return fresh;
37
+ }
38
+ catch {
39
+ return {};
40
+ }
41
+ }
42
+
43
+ function write(storage: StorageLike | null | undefined, store: Store): void {
44
+ try {
45
+ storage?.setItem(KEY, JSON.stringify(store));
46
+ }
47
+ catch {
48
+ // storage full or blocked: attribution is a nicety, never an error
49
+ }
50
+ }
51
+
52
+ /** Remember that `sku` was opened from the search `entry.queryId`. */
53
+ export function rememberSearchClick(
54
+ storage: StorageLike | null | undefined,
55
+ sku: string,
56
+ entry: Omit<SearchAttribution, "at">,
57
+ now = Date.now(),
58
+ ): void {
59
+ if (!sku || !entry.queryId) {
60
+ return;
61
+ }
62
+ const store = read(storage, now);
63
+ delete store[sku];
64
+ store[sku] = { ...entry, at: now };
65
+ const skus = Object.keys(store);
66
+ for (const old of skus.slice(0, Math.max(0, skus.length - ATTRIBUTION_LIMIT))) {
67
+ delete store[old];
68
+ }
69
+ write(storage, store);
70
+ }
71
+
72
+ /** The searches behind these article numbers, for those that have one. */
73
+ export function searchAttributions(
74
+ storage: StorageLike | null | undefined,
75
+ skus: readonly string[],
76
+ now = Date.now(),
77
+ ): { sku: string; attribution: SearchAttribution }[] {
78
+ const store = read(storage, now);
79
+ return skus
80
+ .filter((sku, i) => skus.indexOf(sku) === i && store[sku] !== undefined)
81
+ .map(sku => ({ sku, attribution: store[sku]! }));
82
+ }
83
+
84
+ /** Forget these article numbers — after a purchase, a later order is not this search's. */
85
+ export function forgetSearchAttributions(storage: StorageLike | null | undefined, skus: readonly string[], now = Date.now()): void {
86
+ const store = read(storage, now);
87
+ for (const sku of skus) {
88
+ delete store[sku];
89
+ }
90
+ write(storage, store);
91
+ }
@@ -363,7 +363,7 @@ export interface PurchaseSnapshot {
363
363
  at: number;
364
364
  }
365
365
 
366
- interface StorageLike {
366
+ export interface StorageLike {
367
367
  getItem(key: string): string | null;
368
368
  setItem(key: string, value: string): void;
369
369
  removeItem(key: string): void;
@@ -81,7 +81,8 @@
81
81
  "region": "Land",
82
82
  "currency": "Währung",
83
83
  "regionPlaceholder": "Land suchen …",
84
- "hint": "Währung und Sortiment richten sich nach dem gewählten Land."
84
+ "hint": "Währung und Sortiment richten sich nach dem gewählten Land.",
85
+ "productNotTranslated": "Diesen Artikel gibt es nicht auf {languages}. Ein Wechsel dorthin führt zu seiner Kategorie oder, wenn er keine hat, zur Startseite."
85
86
  }
86
87
  },
87
88
  "header": {
@@ -53,6 +53,13 @@
53
53
  "searchPlaceholder": "In dieser Kategorie suchen…",
54
54
  "allProducts": "Alle Produkte",
55
55
  "productCount": "{count} Produkt | {count} Produkte"
56
+ },
57
+ "suggest": {
58
+ "categories": "Kategorien",
59
+ "manufacturers": "Hersteller",
60
+ "products": "Produkte",
61
+ "pages": "Seiten",
62
+ "productCount": "{count} Artikel"
56
63
  }
57
64
  }
58
65
  }
@@ -81,7 +81,8 @@
81
81
  "region": "Country",
82
82
  "currency": "Currency",
83
83
  "regionPlaceholder": "Search country…",
84
- "hint": "Currency and catalog follow the selected country."
84
+ "hint": "Currency and catalog follow the selected country.",
85
+ "productNotTranslated": "This product is not available in {languages}. Switching there takes you to its category, or to the home page if it has none."
85
86
  }
86
87
  },
87
88
  "header": {
@@ -53,6 +53,13 @@
53
53
  "searchPlaceholder": "Search within this category…",
54
54
  "allProducts": "All products",
55
55
  "productCount": "{count} product | {count} products"
56
+ },
57
+ "suggest": {
58
+ "categories": "Categories",
59
+ "manufacturers": "Manufacturers",
60
+ "products": "Products",
61
+ "pages": "Pages",
62
+ "productCount": "{count} item | {count} items"
56
63
  }
57
64
  }
58
65
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Cover — revenexx design system for Nuxt. Distributed as a Nuxt layer: generic UI components, theming tokens and stores shared by the demo shop, custom storefronts and the Blokkli theme.",
5
5
  "type": "module",
6
6
  "main": "./nuxt.config.ts",
@@ -16,9 +16,10 @@ export default defineEventHandler(async (event) => {
16
16
  try {
17
17
  const service = getBrandService(event);
18
18
  const locale = resolveLocale(event);
19
+ const searchLocale = await resolveMarketLocale(event);
19
20
  return wantsAll
20
- ? await service.listBrandNames(locale)
21
- : await service.listBrands(limit, locale);
21
+ ? await service.listBrandNames(locale, searchLocale)
22
+ : await service.listBrands(limit, locale, searchLocale);
22
23
  }
23
24
  catch (err) {
24
25
  getLogService().error("Service error: brands/list", toErrorContext(err));
@@ -85,7 +85,7 @@ function toTiles(
85
85
  * the view the category page's listing asks, so the cards and the filter rail
86
86
  * can never disagree. The service pins locale and enabled products.
87
87
  */
88
- async function liveCounts(categorySlug: string, locale: Locale): Promise<Map<string, number>> {
88
+ async function liveCounts(categorySlug: string, locale: Locale, searchLocale: string): Promise<Map<string, number>> {
89
89
  const { branchOf } = await liveSubcategoryIndex(categorySlug, locale);
90
90
  const leafCodes = await liveCategorySubtreeCodes([categorySlug]);
91
91
  if (!leafCodes.length) {
@@ -96,7 +96,7 @@ async function liveCounts(categorySlug: string, locale: Locale): Promise<Map<str
96
96
  view: "category",
97
97
  filters: { categories: leafCodes },
98
98
  perPage: 1,
99
- locale,
99
+ locale: searchLocale,
100
100
  });
101
101
 
102
102
  return rollUpSubcategoryCounts(
@@ -114,7 +114,7 @@ async function liveCounts(categorySlug: string, locale: Locale): Promise<Map<str
114
114
  * which is exactly how this looked when it was broken. A child whose lookup
115
115
  * fails keeps its icon; the others keep their images.
116
116
  */
117
- async function liveImages(categorySlug: string, locale: Locale): Promise<Map<string, string>> {
117
+ async function liveImages(categorySlug: string, locale: Locale, searchLocale: string): Promise<Map<string, string>> {
118
118
  const { branchOf } = await liveSubcategoryIndex(categorySlug, locale);
119
119
 
120
120
  // Invert leaf → child into child → its leaves. No extra catalogue call: the
@@ -134,7 +134,7 @@ async function liveImages(categorySlug: string, locale: Locale): Promise<Map<str
134
134
  view: "category",
135
135
  filters: { categories: leavesByChild.get(child) ?? [child] },
136
136
  perPage: 1,
137
- locale,
137
+ locale: searchLocale,
138
138
  })));
139
139
 
140
140
  const failed = results.find((r): r is PromiseRejectedResult => r.status === "rejected");
@@ -267,14 +267,17 @@ export default defineEventHandler(async (event): Promise<SubcategoryTile[]> => {
267
267
  }
268
268
 
269
269
  const isLive = resolveProductServiceKey(event) === "api";
270
+ // The market's locale for this page: the counts must come from the same
271
+ // language index the category listing searches (PE-866).
272
+ const searchLocale = isLive ? await resolveMarketLocale(event) : locale;
270
273
 
271
274
  const [counts, images] = await Promise.all([
272
275
  (isLive
273
- ? liveCounts(category.slug, locale)
276
+ ? liveCounts(category.slug, locale, searchLocale)
274
277
  : mockCounts(category.slug)
275
278
  ).catch(degrade<number>("product counts")),
276
279
  (isLive
277
- ? liveImages(category.slug, locale)
280
+ ? liveImages(category.slug, locale, searchLocale)
278
281
  : mockImages(category.slug, category.subcategories)
279
282
  ).catch(degrade<string>("preview images")),
280
283
  ]);
@@ -0,0 +1,57 @@
1
+ import { normalizeLocaleCode } from "../../../../app/shared/locale";
2
+
3
+ /** What a product page may link to in other languages. */
4
+ export interface ProductLocalesResponse {
5
+ /**
6
+ * The requested storefront locales the product has a page in, or `null`
7
+ * when that is not known — the storefront then links every language, as
8
+ * on any other page.
9
+ */
10
+ locales: string[] | null;
11
+ }
12
+
13
+ /** A locale code as the storefront writes it (`de`, `en-US`). */
14
+ const LOCALE_CODE = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
15
+
16
+ /** More languages than any storefront offers: a bound on the lookup, not a limit. */
17
+ const MAX_LOCALES = 20;
18
+
19
+ /**
20
+ * The storefront locales `?locales=de,en` (the shop's own i18n locales) that
21
+ * this product has a page in. The language switcher and the hreflang
22
+ * alternates use it so a product is never linked into a language it has no
23
+ * document in (`search_untranslated=hide`, PE-859).
24
+ *
25
+ * Soft-failing: the answer only narrows links, so a failed lookup degrades to
26
+ * `null` (link everything, as before) instead of breaking the product page.
27
+ */
28
+ export default defineEventHandler(async (event): Promise<ProductLocalesResponse> => {
29
+ const id = getRouterParam(event, "id") ?? "";
30
+ if (!id) {
31
+ throw createError({ statusCode: 400, message: "Invalid product id" });
32
+ }
33
+
34
+ const raw = getQuery(event).locales;
35
+ const requested = [...new Set(
36
+ (Array.isArray(raw) ? raw.join(",") : String(raw ?? ""))
37
+ .split(",")
38
+ .map(code => normalizeLocaleCode(code))
39
+ .filter(code => LOCALE_CODE.test(code)),
40
+ )].slice(0, MAX_LOCALES);
41
+ if (!requested.length) {
42
+ throw createError({ statusCode: 400, message: "No locales given" });
43
+ }
44
+
45
+ const service = getProductService(event);
46
+ if (!service.getProductLanguages) {
47
+ return { locales: null };
48
+ }
49
+
50
+ try {
51
+ return { locales: await service.getProductLanguages(id, requested) };
52
+ }
53
+ catch (err) {
54
+ getLogService().warn("Product locales lookup failed", { id, ...toErrorContext(err) });
55
+ return { locales: null };
56
+ }
57
+ });
@@ -7,7 +7,12 @@ export default defineEventHandler(async (event) => {
7
7
  try {
8
8
  // Catalog shell only — price + availability are the Offer domain,
9
9
  // resolved separately via POST /api/offers (never blocks the catalog).
10
- return await getProductService(event).listProducts({ category, subcategory, locale });
10
+ return await getProductService(event).listProducts({
11
+ category,
12
+ subcategory,
13
+ locale,
14
+ searchLocale: await resolveMarketLocale(event),
15
+ });
11
16
  }
12
17
  catch (err) {
13
18
  getLogService().error("Service error: products/list", toErrorContext(err));
@@ -0,0 +1,65 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ import { searchLocaleKeys } from "../../../app/shared/locale";
4
+ import type { SearchEventInput } from "../../utils/searchEvents";
5
+ import { searchEventBody } from "../../utils/searchEvents";
6
+
7
+ /**
8
+ * A shopper's click on a search result or tile, and the add-to-cart and
9
+ * purchase that follow (PE-867), handed to the search service's events
10
+ * endpoint. Answers 202 and never fails the storefront: an event the gateway
11
+ * refuses is logged and dropped.
12
+ *
13
+ * An anonymous shopper is a pseudonymous token in a session cookie — a
14
+ * random id, nothing about the person, gone with the browser session. The
15
+ * search service stores it only salted and hashed.
16
+ *
17
+ * A signed-in buyer is the contact (and company) the identity service
18
+ * verified for this request: the SDK client sends it as X-Revenexx-Principal,
19
+ * as on every call made for a buyer, and the gateway resolves it into the
20
+ * contact and organization the search analytics count per customer. The same
21
+ * holds for the searches and quick searches, which go through the same client.
22
+ * Nothing here reads either id from the browser.
23
+ */
24
+
25
+ const TOKEN_COOKIE = "rvx_search";
26
+
27
+ export default defineEventHandler(async (event) => {
28
+ const input = await readBody<SearchEventInput>(event).catch(() => ({}) as SearchEventInput);
29
+ setResponseStatus(event, 202);
30
+
31
+ // The local docker index has no search service to tell.
32
+ if (resolveProductServiceKey(event) !== "api") {
33
+ return { accepted: false };
34
+ }
35
+
36
+ let token = getCookie(event, TOKEN_COOKIE);
37
+ if (!token || !/^[\w-]{8,64}$/.test(token)) {
38
+ token = randomUUID();
39
+ setCookie(event, TOKEN_COOKIE, token, {
40
+ httpOnly: true,
41
+ sameSite: "lax",
42
+ secure: !import.meta.dev,
43
+ path: "/",
44
+ });
45
+ }
46
+
47
+ const body = searchEventBody(input, token);
48
+ if (!body) {
49
+ return { accepted: false };
50
+ }
51
+
52
+ // The market locale the search was sent with (PE-866), so the event is
53
+ // logged for the same language index that answered it.
54
+ const locale = searchLocaleKeys(await resolveMarketLocale(event))[0];
55
+ try {
56
+ await useRevenexxSdk().call("POST", "/v1/search/events", {
57
+ body,
58
+ headers: locale ? { "X-Revenexx-Locale": locale } : {},
59
+ });
60
+ }
61
+ catch (err) {
62
+ getLogService().warn("search event not delivered", { type: body.type, ...apiErrorContext(err) });
63
+ }
64
+ return { accepted: true };
65
+ });