@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
@@ -2,4 +2,5 @@ export const productApi = {
2
2
  detail: (id: string) => `/api/product/${id}`,
3
3
  variants: (id: string) => `/api/product/${id}/variants`,
4
4
  associations: (id: string) => `/api/product/${id}/associations`,
5
+ locales: (id: string) => `/api/product/${id}/locales`,
5
6
  };
@@ -1,18 +1,33 @@
1
1
  <script setup lang="ts">
2
+ import { marketLanguageOptions } from "../../../shared/locale";
3
+
2
4
  /**
3
5
  * Locale selector (Smashing Magazine, "Designing A Better Language
4
6
  * Selector"): a non-modal popover that decouples language and market.
5
7
  * Markets come from the markets app (live: /v1/markets via the BFF) and
6
8
  * carry region + currency; languages show their native full names (never
7
- * flags or codes) and are limited to the locales the selected market
8
- * offers. The trigger shows the current combination prominently.
9
+ * flags or codes) and are exactly the languages the selected market offers
10
+ * — its default first, a `preparing` locale never (PE-866). A language the
11
+ * shop has no UI strings for is offered too: the catalogue and search answer
12
+ * in it, the pages render in the default UI language. A market without
13
+ * locales offers the shop's UI languages, as before.
14
+ *
15
+ * On a product page a language the product has no page in (PE-859 hides
16
+ * untranslated products) still switches the language, but lands on the
17
+ * product's category instead of a 404; a hint under the select says so.
9
18
  */
10
19
  const { icon } = useIcons();
11
20
  const { t, locale, locales } = useI18n();
12
21
  const switchLocalePath = useSwitchLocalePath();
22
+ const localePath = useLocalePath();
23
+ const { hasPage, fallbackPath } = useProductLocales();
24
+ const runtimeConfig = useRuntimeConfig();
13
25
  const { markets } = useMarkets();
14
26
  const { market, setMarket, region, currencies, currency, currencySymbol, setCurrency } = useLocalePreferences(markets);
15
27
 
28
+ /** The market locale the buyer chose (`de-CH`, `fr-FR`); read by the BFF for catalogue + search. */
29
+ const contentLocale = useCookie<string>("cover-content-locale", { default: () => "", watch: true });
30
+
16
31
  const open = ref(false);
17
32
 
18
33
  const marketItems = computed(() => markets.value.map(entry => ({
@@ -21,27 +36,87 @@ const marketItems = computed(() => markets.value.map(entry => ({
21
36
  active: entry.code === market.value?.code,
22
37
  })));
23
38
 
24
- const languageItems = computed(() => {
25
- const offered = new Set(market.value?.locales.map(entry => entry.language) ?? []);
26
- return locales.value
27
- .filter(entry => offered.size === 0 || offered.has(entry.code))
28
- .map(entry => ({
39
+ const uiLanguages = computed(() => locales.value.map(entry => entry.code));
40
+
41
+ const defaultUiLanguage = computed(() => {
42
+ const i18nConfig = (runtimeConfig.public as { i18n?: { defaultLocale?: string }; defaultLocale?: string });
43
+ return i18nConfig.i18n?.defaultLocale || i18nConfig.defaultLocale || uiLanguages.value[0] || "de";
44
+ });
45
+
46
+ /** The language's own name ("Deutsch", "Français"), for languages without an i18n entry. */
47
+ function nativeLanguageName(language: string): string {
48
+ try {
49
+ const name = new Intl.DisplayNames([language], { type: "language" }).of(language);
50
+ return name ? name.charAt(0).toLocaleUpperCase(language) + name.slice(1) : language;
51
+ }
52
+ catch {
53
+ return language;
54
+ }
55
+ }
56
+
57
+ interface LanguageItem {
58
+ /** What the select reports: the market locale, or the UI language without market locales. */
59
+ code: string;
60
+ name: string;
61
+ to: string;
62
+ /** Market locale to remember, "" when the market has none. */
63
+ contentLocale: string;
64
+ active: boolean;
65
+ /** Whether the open product has a page in this language (always true off a product page). */
66
+ hasPage: boolean;
67
+ }
68
+
69
+ /** Where a UI language leads: the same page, or the product's category when the product has no page there (PE-914). */
70
+ function languageTarget(uiLocale: string): string {
71
+ return hasPage(uiLocale) ? switchLocalePath(uiLocale as typeof locale.value) : localePath(fallbackPath.value, uiLocale as typeof locale.value);
72
+ }
73
+
74
+ const languageItems = computed<LanguageItem[]>(() => {
75
+ const options = marketLanguageOptions(market.value?.locales, uiLanguages.value, defaultUiLanguage.value);
76
+ if (!options) {
77
+ return locales.value.map(entry => ({
29
78
  code: entry.code,
30
79
  /** Native full name ("Deutsch", "English") — never flags or codes. */
31
80
  name: entry.name ?? entry.code,
32
- to: switchLocalePath(entry.code),
81
+ to: languageTarget(entry.code),
82
+ contentLocale: "",
33
83
  active: entry.code === locale.value,
84
+ hasPage: hasPage(entry.code),
34
85
  }));
86
+ }
87
+ const chosen = options.find(option => option.locale === contentLocale.value && option.uiLocale === locale.value);
88
+ return options.map(option => ({
89
+ code: option.locale,
90
+ name: locales.value.find(entry => entry.code === option.language)?.name ?? nativeLanguageName(option.language),
91
+ to: languageTarget(option.uiLocale),
92
+ contentLocale: option.locale,
93
+ active: chosen ? option === chosen : option.language === locale.value,
94
+ hasPage: hasPage(option.uiLocale),
95
+ }));
35
96
  });
36
97
 
98
+ const activeLanguageCode = computed(() => languageItems.value.find(item => item.active)?.code ?? locale.value);
99
+
100
+ /** Languages the open product is missing in, by name — empty off a product page. */
101
+ const languagesWithoutProduct = computed(() =>
102
+ languageItems.value.filter(item => !item.hasPage && !item.active).map(item => item.name));
103
+
37
104
  const currentLanguageName = computed(() =>
38
105
  languageItems.value.find(item => item.active)?.name ?? locale.value);
39
106
 
40
107
  async function onLanguageChange(code: string): Promise<void> {
41
108
  const target = languageItems.value.find(item => item.code === code);
42
- if (target && !target.active) {
43
- await navigateTo(target.to);
109
+ if (!target || target.active) {
110
+ return;
111
+ }
112
+ contentLocale.value = target.contentLocale;
113
+ if (target.to === useRoute().fullPath) {
114
+ // Same UI language (no UI strings for the target): only the catalogue
115
+ // language changes, so re-render with the new cookie.
116
+ reloadNuxtApp({ ttl: 0 });
117
+ return;
44
118
  }
119
+ await navigateTo(target.to);
45
120
  }
46
121
 
47
122
  const currencyItems = computed(() =>
@@ -49,9 +124,12 @@ const currencyItems = computed(() =>
49
124
 
50
125
  async function onMarketChange(code: string): Promise<void> {
51
126
  setMarket(code);
52
- // The market may not offer the current language — fall back to its first.
127
+ // The market may not offer the current language — fall back to its
128
+ // default (listed first). The remembered locale belongs to the old market.
129
+ contentLocale.value = "";
53
130
  const fallback = languageItems.value[0];
54
131
  if (fallback && !languageItems.value.some(item => item.active)) {
132
+ contentLocale.value = fallback.contentLocale;
55
133
  await navigateTo(fallback.to);
56
134
  }
57
135
  // The market may not trade in the current currency — re-resolve prices.
@@ -114,13 +192,19 @@ const triggerLabel = computed(() =>
114
192
  <!-- Language: native full names within the market's locales -->
115
193
  <UFormField :label="t('topbar.localePanel.language')">
116
194
  <USelect
117
- :model-value="locale"
195
+ :model-value="activeLanguageCode"
118
196
  value-key="code"
119
197
  label-key="name"
120
198
  :items="languageItems"
121
199
  class="w-full"
122
200
  @update:model-value="(code: string) => onLanguageChange(code)"
123
201
  />
202
+ <template
203
+ v-if="languagesWithoutProduct.length"
204
+ #help
205
+ >
206
+ {{ t('topbar.localePanel.productNotTranslated', { languages: languagesWithoutProduct.join(', ') }) }}
207
+ </template>
124
208
  </UFormField>
125
209
 
126
210
  <!-- Currency: chosen within the currencies the market trades in -->
@@ -8,6 +8,8 @@ const { icon } = useIcons();
8
8
 
9
9
  interface Suggestion {
10
10
  id: string;
11
+ /** The record id sent back with the click event. */
12
+ docId?: string;
11
13
  name: string;
12
14
  sku: string;
13
15
  category: string;
@@ -15,6 +17,40 @@ interface Suggestion {
15
17
  subcategorySlug?: string;
16
18
  }
17
19
 
20
+ /** A category of the quick search (PE-867). `to` is a site path without locale. */
21
+ interface CategoryTile {
22
+ docId: string;
23
+ code: string;
24
+ name: string;
25
+ path: string[];
26
+ image: string | null;
27
+ productCount: number;
28
+ to: string;
29
+ }
30
+
31
+ interface ManufacturerTile {
32
+ docId: string;
33
+ code: string;
34
+ name: string;
35
+ logo: string | null;
36
+ productCount: number;
37
+ }
38
+
39
+ interface PageTile {
40
+ docId: string;
41
+ title: string;
42
+ to: string;
43
+ }
44
+
45
+ interface SuggestAnswer {
46
+ suggestions: Suggestion[];
47
+ categories?: CategoryTile[];
48
+ manufacturers?: ManufacturerTile[];
49
+ pages?: PageTile[];
50
+ queryId?: string;
51
+ redirect?: string;
52
+ }
53
+
18
54
  // Optional override for callers that author their own wording (the search_bar
19
55
  // blokkli block lets an editor set one per instance). Unset — the header's two
20
56
  // call sites — keeps the translated default.
@@ -25,6 +61,8 @@ const props = withDefaults(defineProps<{
25
61
  });
26
62
 
27
63
  const { locale, t } = useI18n();
64
+ const localePath = useLocalePath();
65
+ const searchEvents = useSearchEvents();
28
66
 
29
67
  const placeholder = computed(() => props.placeholder || t("search.input.placeholder"));
30
68
 
@@ -37,8 +75,15 @@ const query = ref<string>("");
37
75
  const emit = defineEmits<{ search: [query: string] }>();
38
76
 
39
77
  const suggestions = ref<Suggestion[]>([]);
78
+ const categories = ref<CategoryTile[]>([]);
79
+ const manufacturers = ref<ManufacturerTile[]>([]);
80
+ const pages = ref<PageTile[]>([]);
81
+ // The answer's search id and curated redirect, for the term it answered.
82
+ const answered = ref<{ q: string; queryId: string; redirect?: string } | null>(null);
40
83
  const activeIndex = ref<number>(-1);
41
- const showDropdown = computed(() => suggestions.value.length > 0);
84
+ const showDropdown = computed(() =>
85
+ suggestions.value.length + categories.value.length + manufacturers.value.length + pages.value.length > 0,
86
+ );
42
87
 
43
88
  const containerRef = ref<HTMLElement | null>(null);
44
89
 
@@ -75,29 +120,77 @@ const debouncedFetch = useDebounceFn(fetchSuggestions, 250);
75
120
  watch(query, (val) => {
76
121
  activeIndex.value = -1;
77
122
  if (!val.trim() || val.trim().length < autocompleteMinChars.value) {
78
- suggestions.value = [];
123
+ clearAnswer();
79
124
  return;
80
125
  }
81
126
  void debouncedFetch(val);
82
127
  });
83
128
 
84
129
  async function fetchSuggestions(q: string): Promise<void> {
85
- const data = await $fetch<{ suggestions: Suggestion[] }>(searchApi.suggest(), {
130
+ const data = await $fetch<SuggestAnswer>(searchApi.suggest(), {
86
131
  method: "POST",
87
132
  body: { q },
88
133
  // The BFF filters the index by locale; without it, it guesses from the
89
134
  // cookie or Accept-Language and may suggest the other language.
90
135
  headers: { "x-locale": locale.value },
91
- }).catch(() => ({ suggestions: [] }));
92
- suggestions.value = data.suggestions;
136
+ }).catch((): SuggestAnswer => ({ suggestions: [] }));
137
+ // A slower answer for an older term must not replace the current one.
138
+ if (q !== query.value) {
139
+ return;
140
+ }
141
+ suggestions.value = data.suggestions ?? [];
142
+ categories.value = data.categories ?? [];
143
+ manufacturers.value = data.manufacturers ?? [];
144
+ pages.value = data.pages ?? [];
145
+ answered.value = { q: q.trim(), queryId: data.queryId ?? "", ...(data.redirect ? { redirect: data.redirect } : {}) };
146
+ }
147
+
148
+ function clearAnswer(): void {
149
+ suggestions.value = [];
150
+ categories.value = [];
151
+ manufacturers.value = [];
152
+ pages.value = [];
153
+ answered.value = null;
93
154
  }
94
155
 
95
156
  function close(): void {
96
157
  suggestions.value = [];
158
+ categories.value = [];
159
+ manufacturers.value = [];
160
+ pages.value = [];
97
161
  activeIndex.value = -1;
98
162
  }
99
163
 
164
+ /** Tell the search service which hit or tile was taken (PE-867). */
165
+ function reportClick(collection: string, docId: string | undefined, position: number, sku?: string): void {
166
+ const shown = answered.value;
167
+ if (!shown?.queryId || !docId) {
168
+ return;
169
+ }
170
+ searchEvents.click({ queryId: shown.queryId, q: shown.q, collection, docId, position, ...(sku ? { sku } : {}) });
171
+ }
172
+
173
+ function selectCategory(tile: CategoryTile, index: number): void {
174
+ reportClick("categories", tile.docId, index + 1);
175
+ close();
176
+ void navigateTo(localePath(tile.to));
177
+ }
178
+
179
+ function selectManufacturer(tile: ManufacturerTile, index: number): void {
180
+ reportClick("manufacturers", tile.docId, index + 1);
181
+ close();
182
+ // The brand page is the search filtered to the manufacturer (brand_grid).
183
+ void navigateTo(localePath({ path: "/search", query: { q: tile.name, manufacturer: tile.name } }));
184
+ }
185
+
186
+ function selectPage(tile: PageTile, index: number): void {
187
+ reportClick("pages", tile.docId, index + 1);
188
+ close();
189
+ void navigateTo(localePath(tile.to));
190
+ }
191
+
100
192
  function select(s: Suggestion): void {
193
+ reportClick("products", s.docId ?? s.id, suggestions.value.indexOf(s) + 1, s.sku);
101
194
  query.value = s.name;
102
195
  close();
103
196
  const url = useProductUrl({
@@ -116,11 +209,17 @@ function onEnter(): void {
116
209
 
117
210
  if (activeSuggestion) {
118
211
  select(activeSuggestion);
212
+ return;
119
213
  }
120
- else {
121
- close();
122
- emit("search", query.value);
214
+ // Curation sends this term somewhere else (a category, a landing page):
215
+ // follow it instead of searching, as the search page would.
216
+ const redirect = answered.value?.q === query.value.trim() ? answered.value.redirect : undefined;
217
+ close();
218
+ if (redirect) {
219
+ void navigateTo(/^https?:\/\//i.test(redirect) ? redirect : localePath(redirect), { external: /^https?:\/\//i.test(redirect) });
220
+ return;
123
221
  }
222
+ emit("search", query.value);
124
223
  }
125
224
 
126
225
  function onDown(): void {
@@ -205,6 +304,81 @@ onUnmounted(() => document.removeEventListener("click", handleClickOutside));
205
304
  class="absolute z-50 w-full top-full mt-1 bg-(--ui-bg) border border-(--ui-border)
206
305
  rounded-lg shadow-lg overflow-hidden"
207
306
  >
307
+ <div
308
+ v-if="categories.length || manufacturers.length"
309
+ class="grid gap-2 p-2 border-b border-(--ui-border) sm:grid-cols-2"
310
+ data-testid="search-suggest-tiles"
311
+ >
312
+ <div
313
+ v-if="categories.length"
314
+ class="flex flex-col gap-1"
315
+ >
316
+ <p class="px-1 text-xs font-medium text-(--ui-text-muted)">
317
+ {{ t("search.suggest.categories") }}
318
+ </p>
319
+ <button
320
+ v-for="(tile, i) in categories"
321
+ :key="tile.docId"
322
+ type="button"
323
+ class="flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm cursor-pointer
324
+ hover:bg-(--ui-bg-elevated)"
325
+ data-testid="search-suggest-category"
326
+ @click="selectCategory(tile, i)"
327
+ >
328
+ <img
329
+ v-if="tile.image"
330
+ :src="tile.image"
331
+ alt=""
332
+ class="size-8 shrink-0 rounded object-cover"
333
+ >
334
+ <UIcon
335
+ v-else
336
+ :name="icon('folder')"
337
+ class="size-4 shrink-0 text-(--ui-text-muted)"
338
+ />
339
+ <span class="min-w-0 flex-1">
340
+ <span class="block truncate font-medium">{{ tile.name }}</span>
341
+ <span
342
+ v-if="tile.path.length"
343
+ class="block truncate text-xs text-(--ui-text-muted)"
344
+ >{{ tile.path.join(" › ") }}</span>
345
+ </span>
346
+ <span
347
+ v-if="tile.productCount"
348
+ class="shrink-0 text-xs text-(--ui-text-muted)"
349
+ >{{ t("search.suggest.productCount", tile.productCount) }}</span>
350
+ </button>
351
+ </div>
352
+ <div
353
+ v-if="manufacturers.length"
354
+ class="flex flex-col gap-1"
355
+ >
356
+ <p class="px-1 text-xs font-medium text-(--ui-text-muted)">
357
+ {{ t("search.suggest.manufacturers") }}
358
+ </p>
359
+ <button
360
+ v-for="(tile, i) in manufacturers"
361
+ :key="tile.docId"
362
+ type="button"
363
+ class="flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm cursor-pointer
364
+ hover:bg-(--ui-bg-elevated)"
365
+ data-testid="search-suggest-manufacturer"
366
+ @click="selectManufacturer(tile, i)"
367
+ >
368
+ <img
369
+ v-if="tile.logo"
370
+ :src="tile.logo"
371
+ :alt="tile.name"
372
+ class="h-6 w-12 shrink-0 object-contain"
373
+ >
374
+ <span class="min-w-0 flex-1 truncate font-medium">{{ tile.name }}</span>
375
+ <span
376
+ v-if="tile.productCount"
377
+ class="shrink-0 text-xs text-(--ui-text-muted)"
378
+ >{{ t("search.suggest.productCount", tile.productCount) }}</span>
379
+ </button>
380
+ </div>
381
+ </div>
208
382
  <button
209
383
  v-for="(s, i) in suggestions"
210
384
  :key="s.id"
@@ -226,6 +400,29 @@ onUnmounted(() => document.removeEventListener("click", handleClickOutside));
226
400
  class="shrink-0"
227
401
  />
228
402
  </button>
403
+ <div
404
+ v-if="pages.length"
405
+ class="border-t border-(--ui-border) p-2"
406
+ >
407
+ <p class="px-1 pb-1 text-xs font-medium text-(--ui-text-muted)">
408
+ {{ t("search.suggest.pages") }}
409
+ </p>
410
+ <button
411
+ v-for="(tile, i) in pages"
412
+ :key="tile.docId"
413
+ type="button"
414
+ class="w-full flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm cursor-pointer
415
+ hover:bg-(--ui-bg-elevated)"
416
+ data-testid="search-suggest-page"
417
+ @click="selectPage(tile, i)"
418
+ >
419
+ <UIcon
420
+ :name="icon('file')"
421
+ class="size-4 shrink-0 text-(--ui-text-muted)"
422
+ />
423
+ <span class="truncate">{{ tile.title }}</span>
424
+ </button>
425
+ </div>
229
426
  </div>
230
427
  </div>
231
428
  </template>
@@ -17,6 +17,7 @@ export function useProductCard(
17
17
  const { useOffer } = useOffers();
18
18
  const { offer } = useOffer(() => getProduct().id);
19
19
  const events = useThemeEvents();
20
+ const search = useSearchEvents();
20
21
 
21
22
  /** Report that the buyer opened this product from the list it was shown in. */
22
23
  function select(): void {
@@ -29,6 +30,19 @@ export function useProductCard(
29
30
  events.emit("select_item", {
30
31
  ecommerce: { items: [item], ...(list?.listId ? { list_id: list.listId } : {}) },
31
32
  });
33
+ // A result of the search page: a click on that search (PE-867).
34
+ const shown = search.shown.value;
35
+ if (list?.listId === "search" && shown) {
36
+ const product = getProduct();
37
+ search.click({
38
+ queryId: shown.queryId,
39
+ q: shown.q,
40
+ collection: "products",
41
+ docId: String(product.id),
42
+ ...(list.position ? { position: list.position } : {}),
43
+ sku: product.sku,
44
+ });
45
+ }
32
46
  }
33
47
 
34
48
  return { url, getImage, select };
@@ -59,6 +59,12 @@ export interface ListingResponse {
59
59
  priceFilter?: boolean;
60
60
  /** Where curation sends this search instead of showing results. */
61
61
  redirect?: string;
62
+ /** The search's id, for the click events its results send (PE-867). */
63
+ queryId?: string;
64
+ /** The locale whose index answered (live search only). */
65
+ locale?: string;
66
+ /** True when another language's index answered than the page asked for. */
67
+ localeFallback?: boolean;
62
68
  }
63
69
 
64
70
  /**
@@ -222,6 +228,19 @@ export function useProductListing(options: ProductListingOptions) {
222
228
  }
223
229
  }, { immediate: true });
224
230
 
231
+ /* ---- search events (PE-867) ------------------------------------ */
232
+ // The search page's results report their clicks against the search they
233
+ // came from: its id is kept where the product cards can read it.
234
+ if (import.meta.client && options.listEvent) {
235
+ const { shown } = useSearchEvents();
236
+ watch(data, (loaded) => {
237
+ const spec = options.listEvent?.();
238
+ if (spec?.event === "search" && loaded?.queryId) {
239
+ shown.value = { queryId: loaded.queryId, q: spec.term };
240
+ }
241
+ }, { immediate: true });
242
+ }
243
+
225
244
  /* ---- theme events --------------------------------------------- */
226
245
  // Reported once per shown page of results, after the offers for it have
227
246
  // settled — a list view without prices tells a tag little. Client-only:
@@ -305,6 +324,13 @@ export function useProductListing(options: ProductListingOptions) {
305
324
  /** A curated redirect for this query (search view only), or undefined. */
306
325
  const redirect = computed(() => data.value?.redirect || undefined);
307
326
 
327
+ /**
328
+ * The locale the results came from when it is another language than the
329
+ * page's — the search service had no index for the page's language and
330
+ * answered from the tenant's default one (PE-865). Undefined otherwise.
331
+ */
332
+ const servedLocale = computed(() => data.value?.localeFallback ? data.value.locale : undefined);
333
+
308
334
  const activeFilterCount = computed(() =>
309
335
  Object.values(activeFilters.value).reduce((sum, values) => sum + values.length, 0)
310
336
  + (priceFilter.value && (priceRange.value.min !== undefined || priceRange.value.max !== undefined) ? 1 : 0),
@@ -342,7 +368,7 @@ export function useProductListing(options: ProductListingOptions) {
342
368
  })));
343
369
 
344
370
  return {
345
- query, sort, sortOptions, page, activeFilters, priceRange, priceFilter, redirect,
371
+ query, sort, sortOptions, page, activeFilters, priceRange, priceFilter, redirect, servedLocale,
346
372
  data, pending, error, execute,
347
373
  products, facets, found, totalPages, isEmpty,
348
374
  chips, activeFilterCount, removeChip, clearFilters,
@@ -0,0 +1,56 @@
1
+ import { productApi } from "../api/product";
2
+ import { normalizeLocaleCode } from "../shared/locale";
3
+ import { productFallbackPath, productRouteCategorySegments } from "../shared/productLocales";
4
+ import { routeSegments, useRouteProductSubject } from "./useRouteSubject";
5
+
6
+ interface ProductLocalesResponse {
7
+ locales: string[] | null;
8
+ }
9
+
10
+ /**
11
+ * Which storefront locales the product on this page has a page in.
12
+ *
13
+ * With `search_untranslated=hide` (PE-859) a product exists only in the
14
+ * languages it is translated into, so the language switcher and the hreflang
15
+ * alternates must not link it into the others. Both call this; they share one
16
+ * request through the `product-locales:<id>` key, and the BFF caches the
17
+ * answer per product.
18
+ *
19
+ * `available` is `null` off a product page or when the lookup failed: every
20
+ * locale is linked then, exactly as before. Only a product page narrows.
21
+ */
22
+ export function useProductLocales() {
23
+ const route = useRoute();
24
+ const { id } = useRouteProductSubject();
25
+ const { locales } = useI18n();
26
+ const requestFetch = useRequestFetch();
27
+
28
+ const codes = computed(() => locales.value.map(entry => entry.code).join(","));
29
+
30
+ const { data } = useAsyncData<ProductLocalesResponse | null>(
31
+ () => `product-locales:${id.value}`,
32
+ () => (id.value && codes.value
33
+ ? requestFetch<ProductLocalesResponse>(productApi.locales(id.value), { query: { locales: codes.value } })
34
+ .catch(() => null)
35
+ : Promise.resolve(null)),
36
+ { default: () => null },
37
+ );
38
+
39
+ const available = computed<string[] | null>(() => {
40
+ const list = id.value ? data.value?.locales : null;
41
+ return list ? list.map(normalizeLocaleCode) : null;
42
+ });
43
+
44
+ /** Whether the product has a page in this locale (always true off a product page). */
45
+ function hasPage(code: string): boolean {
46
+ return available.value?.includes(normalizeLocaleCode(code)) ?? true;
47
+ }
48
+
49
+ /** Where a locale without the product goes instead: its category listing, or home. */
50
+ const fallbackPath = computed(() => productFallbackPath(productRouteCategorySegments(
51
+ routeSegments(route.params.category),
52
+ routeSegments(route.params.rest),
53
+ )));
54
+
55
+ return { available, hasPage, fallbackPath };
56
+ }
@@ -0,0 +1,67 @@
1
+ import { rememberSearchClick } from "../shared/searchAttribution";
2
+ import { browserSession } from "../shared/themeEvents";
3
+
4
+ export type SearchEventType = "click" | "add_to_cart" | "purchase";
5
+
6
+ export interface SearchEventPayload {
7
+ type: SearchEventType;
8
+ /** The search's `queryId`; required for a click. */
9
+ queryId?: string;
10
+ /** The collection of the document: products, categories, manufacturers, pages. */
11
+ collection: string;
12
+ docId?: string;
13
+ /** 1-based position in what was shown. */
14
+ position?: number;
15
+ q?: string;
16
+ }
17
+
18
+ /** The search the current results page shows, for its result clicks. */
19
+ export interface ShownSearch {
20
+ queryId: string;
21
+ q: string;
22
+ }
23
+
24
+ /**
25
+ * Tells the search service what a shopper did with a search (PE-867): a click
26
+ * on a result or a quick search tile, and — through the plugin that watches
27
+ * the theme events — the add-to-cart and purchase that follow it.
28
+ *
29
+ * Fire and forget: an event never delays the navigation it comes with, is
30
+ * sent with `keepalive` so a page change does not cancel it, and a failure is
31
+ * swallowed. Nothing is sent on the server.
32
+ */
33
+ export function useSearchEvents() {
34
+ // Not useI18n(): the search-events plugin calls this outside a component
35
+ // setup, where useI18n() throws.
36
+ const i18n = useNuxtApp().$i18n as unknown as { locale: { value: string } } | undefined;
37
+ const shown = useState<ShownSearch | null>("search:shown", () => null);
38
+
39
+ function send(payload: SearchEventPayload): void {
40
+ if (import.meta.server) {
41
+ return;
42
+ }
43
+ void $fetch("/api/search/events", {
44
+ method: "POST",
45
+ body: payload,
46
+ headers: i18n?.locale.value ? { "x-locale": i18n.locale.value } : {},
47
+ keepalive: true,
48
+ }).catch(() => {});
49
+ }
50
+
51
+ /**
52
+ * A click on a search hit or tile. A product click is also remembered by
53
+ * its article number, so the cart can be attributed to the search.
54
+ */
55
+ function click(payload: Omit<SearchEventPayload, "type"> & { sku?: string }): void {
56
+ if (!payload.queryId) {
57
+ return;
58
+ }
59
+ const { sku, ...event } = payload;
60
+ send({ type: "click", ...event });
61
+ if (sku && payload.docId && payload.collection === "products") {
62
+ rememberSearchClick(browserSession(), sku, { queryId: payload.queryId, docId: payload.docId, q: payload.q ?? "" });
63
+ }
64
+ }
65
+
66
+ return { send, click, shown };
67
+ }
@@ -3,6 +3,8 @@
3
3
  * locales (language + country) and the currencies it trades in; the locale
4
4
  * selector is driven by this.
5
5
  */
6
+ import type { MarketLocaleStatus } from "../shared/locale";
7
+
6
8
  export interface ShopMarketLocale {
7
9
  /** BCP-47 code, e.g. "de-DE". */
8
10
  code: string;
@@ -11,6 +13,11 @@ export interface ShopMarketLocale {
11
13
  /** ISO 3166-1 alpha-2 country, e.g. "DE". */
12
14
  country: string;
13
15
  isDefault: boolean;
16
+ /**
17
+ * Rollout state from the markets app. A `preparing` locale is being built
18
+ * (catalogue, search) and is never offered to buyers; absent = active.
19
+ */
20
+ status?: MarketLocaleStatus;
14
21
  }
15
22
 
16
23
  export interface ShopMarketCurrency {