@revenexx/cover 0.12.0 → 0.14.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.
- package/app/api/product.ts +1 -0
- package/app/components/cart/recommend/CartCrossSell.vue +2 -1
- package/app/components/layout/header/LocaleSwitcher.vue +18 -1
- package/app/components/listing/ListingFilterBar.vue +1 -0
- package/app/components/listing/ListingFilterDrawer.vue +1 -0
- package/app/components/listing/ListingFilterRail.vue +1 -0
- package/app/components/search/filter/SearchFacets.vue +10 -3
- package/app/components/search/filter/SearchFacetsBar.vue +7 -3
- package/app/components/search/filter/SearchFacetsDrawer.vue +7 -2
- package/app/components/ui/forms/SearchInput.vue +4 -1
- package/app/composables/useFacetMeta.ts +6 -6
- package/app/composables/useProductListing.ts +18 -2
- package/app/composables/useProductLocales.ts +56 -0
- package/app/composables/useSearchListing.ts +16 -0
- package/app/layouts/default.vue +10 -1
- package/app/shared/locale.ts +114 -0
- package/app/shared/productLocales.ts +109 -0
- package/i18n/locales/de/common.json +2 -1
- package/i18n/locales/en/common.json +2 -1
- package/nuxt.config.ts +22 -0
- package/package.json +1 -1
- package/server/api/account/quotes/[id]/order.post.ts +14 -3
- package/server/api/cart/calculate.post.ts +4 -0
- package/server/api/categories/[slug]/subcategories.get.ts +34 -31
- package/server/api/orders/index.post.ts +78 -31
- package/server/api/payment/psp-config.get.ts +11 -21
- package/server/api/product/[id]/locales.get.ts +57 -0
- package/server/api/quotes/request.post.ts +2 -2
- package/server/api/typesense/search.post.ts +61 -317
- package/server/api/typesense/suggest.post.ts +14 -9
- package/server/{api/typesense/drop.get.ts → dev/typesense/drop.ts} +2 -1
- package/server/{api/typesense/health.get.ts → dev/typesense/health.ts} +1 -0
- package/server/dev/typesense/seed.ts +59 -0
- package/server/dev/typesense/seedDocuments.ts +105 -0
- package/server/interfaces/product.ts +8 -0
- package/server/routes/punchout/start.get.ts +40 -3
- package/server/services/ApiBrandService.ts +28 -42
- package/server/services/ApiProductService.ts +14 -11
- package/server/utils/buyerIdentity.ts +11 -0
- package/server/utils/liveCatalog.ts +200 -48
- package/server/utils/liveListingSearch.ts +201 -0
- package/server/utils/livePrices.ts +24 -9
- package/server/utils/orderLinePrices.ts +72 -0
- package/server/utils/paymentFee.ts +59 -0
- package/server/utils/pspConfig.ts +42 -0
- package/server/utils/revenexxSdk.ts +25 -2
- package/server/utils/searchClient.ts +305 -0
- package/server/utils/searchMultiSearchFallback.ts +216 -0
- package/server/api/typesense/seed.get.ts +0 -111
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import type { H3Event } from "h3";
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
defineEventHandler,
|
|
4
|
+
getQuery,
|
|
5
|
+
getRequestHeader,
|
|
6
|
+
sendRedirect,
|
|
7
|
+
setResponseHeader,
|
|
8
|
+
setResponseStatus,
|
|
9
|
+
} from "h3";
|
|
3
10
|
|
|
4
11
|
import type { StoredSession } from "../../../app/interfaces/auth";
|
|
5
12
|
import type { PunchoutClaim, PunchoutVisit } from "../../interfaces/punchout";
|
|
@@ -136,7 +143,7 @@ export default defineEventHandler(async (event) => {
|
|
|
136
143
|
// WHERE the buyer goes and this is about how this storefront spells it.
|
|
137
144
|
const punchoutConfig = (useRuntimeConfig(event).punchout ?? {}) as { localeStrategy?: string; defaultLocale?: string };
|
|
138
145
|
const path = punchoutLocalePath(
|
|
139
|
-
await landingPath(claim),
|
|
146
|
+
await landingPath(event, claim),
|
|
140
147
|
resolveLocale(event),
|
|
141
148
|
String(punchoutConfig.localeStrategy ?? "no_prefix"),
|
|
142
149
|
String(punchoutConfig.defaultLocale ?? ""),
|
|
@@ -152,7 +159,7 @@ export default defineEventHandler(async (event) => {
|
|
|
152
159
|
* article needs the catalogue, because an external system names an article
|
|
153
160
|
* NUMBER and the shop's product pages are addressed by id and slug.
|
|
154
161
|
*/
|
|
155
|
-
async function landingPath(claim: PunchoutClaim): Promise<string> {
|
|
162
|
+
async function landingPath(event: H3Event, claim: PunchoutClaim): Promise<string> {
|
|
156
163
|
const target = punchoutLandingTarget(claim.entry_action, claim.entry_intent, claim.cart_id);
|
|
157
164
|
const direct = punchoutLandingPath(target);
|
|
158
165
|
if (direct) {
|
|
@@ -165,6 +172,7 @@ async function landingPath(claim: PunchoutClaim): Promise<string> {
|
|
|
165
172
|
const found = await $fetch<SearchAnswer>("/api/typesense/search", {
|
|
166
173
|
method: "POST",
|
|
167
174
|
body: { q: supplierPartId, page: 1, perPage: 5 },
|
|
175
|
+
headers: searchRequestHeaders(event),
|
|
168
176
|
});
|
|
169
177
|
return punchoutArticlePath(found?.products ?? [], supplierPartId);
|
|
170
178
|
}
|
|
@@ -176,6 +184,35 @@ async function landingPath(claim: PunchoutClaim): Promise<string> {
|
|
|
176
184
|
}
|
|
177
185
|
}
|
|
178
186
|
|
|
187
|
+
/**
|
|
188
|
+
* What the internal search call needs to see the same shop as this request.
|
|
189
|
+
*
|
|
190
|
+
* An internal `$fetch` starts a fresh request with none of the caller's
|
|
191
|
+
* headers, so the search ran without the brokered tenant context, without
|
|
192
|
+
* the market and service-mode cookies, and in whatever locale it could guess:
|
|
193
|
+
* an article number could resolve in the wrong catalogue or not at all.
|
|
194
|
+
*/
|
|
195
|
+
const FORWARDED_SEARCH_HEADERS = [
|
|
196
|
+
"cookie",
|
|
197
|
+
"accept-language",
|
|
198
|
+
"x-revenexx-tenant",
|
|
199
|
+
"x-revenexx-context",
|
|
200
|
+
"x-revenexx-market",
|
|
201
|
+
"x-revenexx-channel",
|
|
202
|
+
] as const;
|
|
203
|
+
|
|
204
|
+
function searchRequestHeaders(event: H3Event): Record<string, string> {
|
|
205
|
+
const headers: Record<string, string> = {};
|
|
206
|
+
for (const name of FORWARDED_SEARCH_HEADERS) {
|
|
207
|
+
const value = getRequestHeader(event, name);
|
|
208
|
+
if (value) {
|
|
209
|
+
headers[name] = value;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
headers["x-locale"] = resolveLocale(event);
|
|
213
|
+
return headers;
|
|
214
|
+
}
|
|
215
|
+
|
|
179
216
|
/** Why a visit could not be opened — one page per cause, in plain words. */
|
|
180
217
|
type RefusalCause = "missing" | "unusable" | "unavailable";
|
|
181
218
|
|
|
@@ -1,14 +1,12 @@
|
|
|
1
1
|
import type { ShopBrand } from "../../app/interfaces/brand";
|
|
2
2
|
import type { IBrandService } from "../interfaces/brand";
|
|
3
|
+
import type { SearchClientResult } from "../utils/searchClient";
|
|
3
4
|
import type { Locale } from "../utils/locale";
|
|
4
5
|
|
|
5
6
|
const BRAND_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
6
7
|
|
|
7
|
-
/**
|
|
8
|
-
|
|
9
|
-
* would silently cap the grid at 10 brands. Mirrors search.post.ts.
|
|
10
|
-
*/
|
|
11
|
-
const LIVE_MAX_FACET_VALUES = 250;
|
|
8
|
+
/** Logo lookups in flight at once — one search per brand. */
|
|
9
|
+
const LOGO_LOOKUP_CONCURRENCY = 8;
|
|
12
10
|
|
|
13
11
|
// Partitioned by tenant — a multi-tenant theme must never serve one tenant's
|
|
14
12
|
// brands to another (see revenexxTenantKey()). Locale and limit are part of the
|
|
@@ -16,18 +14,16 @@ const LIVE_MAX_FACET_VALUES = 250;
|
|
|
16
14
|
const cache = new Map<string, { brands: ShopBrand[]; loadedAt: number }>();
|
|
17
15
|
|
|
18
16
|
/**
|
|
19
|
-
* Live brands from the platform's Typesense product index
|
|
17
|
+
* Live brands from the platform's Typesense product index, through the
|
|
18
|
+
* search service's `brand` view (searchClient.ts):
|
|
19
|
+
* 1. the view's `manufacturer` facet over the whole catalogue → names +
|
|
20
|
+
* article counts, already ranked by count descending.
|
|
21
|
+
* 2. one 1-hit search per top brand → the logo, which lives on the product
|
|
22
|
+
* document (`attrs.<logoAttribute>`), not on any brand entity.
|
|
20
23
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* 2. ONE multi_search with a sub-search per top brand → the logo, which lives
|
|
25
|
-
* on the product document (`attrs.<logoAttribute>`), not on any brand
|
|
26
|
-
* entity. `include_fields` cannot narrow this: asking for `attrs` returns
|
|
27
|
-
* an empty object, so the full document has to come back.
|
|
28
|
-
*
|
|
29
|
-
* Both carry the same pinned filters the storefront's search uses — without
|
|
30
|
-
* them the counts drift from what the search page reports for the same brand.
|
|
24
|
+
* The service pins locale and enabled products on both, the same pins the
|
|
25
|
+
* storefront's search gets — so the counts match what the search page reports
|
|
26
|
+
* for the same brand.
|
|
31
27
|
*/
|
|
32
28
|
export class ApiBrandService implements IBrandService {
|
|
33
29
|
async listBrands(limit: number, locale: Locale): Promise<ShopBrand[]> {
|
|
@@ -48,19 +44,22 @@ export class ApiBrandService implements IBrandService {
|
|
|
48
44
|
// Same attribute the product detail reads its logo from (liveCatalog).
|
|
49
45
|
const attribute = manufacturerLogoAttribute();
|
|
50
46
|
|
|
51
|
-
// One representative product per brand
|
|
52
|
-
//
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
47
|
+
// One representative product per brand. Settled one by one: a brand
|
|
48
|
+
// whose lookup fails costs that brand its logo and nothing more.
|
|
49
|
+
const logoResults: (PromiseSettledResult<SearchClientResult> | undefined)[] = [];
|
|
50
|
+
for (let index = 0; index < top.length; index += LOGO_LOOKUP_CONCURRENCY) {
|
|
51
|
+
const batch = top.slice(index, index + LOGO_LOOKUP_CONCURRENCY);
|
|
52
|
+
logoResults.push(...await Promise.allSettled(batch.map(entry => searchClient.search({
|
|
53
|
+
view: "brand",
|
|
54
|
+
filters: { manufacturer: [entry.value] },
|
|
55
|
+
perPage: 1,
|
|
56
|
+
locale,
|
|
57
|
+
}))));
|
|
58
|
+
}
|
|
61
59
|
|
|
62
60
|
const brands = top.map((entry, index): ShopBrand => {
|
|
63
|
-
const
|
|
61
|
+
const settled = logoResults[index];
|
|
62
|
+
const raw = settled?.status === "fulfilled" ? settled.value.docs[0]?.attrs?.[attribute] : undefined;
|
|
64
63
|
const logo = typeof raw === "string" && raw.trim().length > 0
|
|
65
64
|
? liveImageSrc(raw.trim())
|
|
66
65
|
: null;
|
|
@@ -90,21 +89,8 @@ export class ApiBrandService implements IBrandService {
|
|
|
90
89
|
|
|
91
90
|
/** Round trip 1 of listBrands: names + counts, count-descending. */
|
|
92
91
|
private async facetManufacturers(locale: Locale): Promise<{ value: string; count: number }[]> {
|
|
93
|
-
const
|
|
94
|
-
q: "*",
|
|
95
|
-
queryBy: "name",
|
|
96
|
-
filterBy: this.pinnedFilter(locale),
|
|
97
|
-
facetBy: "manufacturer",
|
|
98
|
-
maxFacetValues: LIVE_MAX_FACET_VALUES,
|
|
99
|
-
perPage: 0,
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
return (facetResult.facet_counts ?? [])
|
|
103
|
-
.find(facet => facet.field_name === "manufacturer")
|
|
104
|
-
?.counts ?? [];
|
|
105
|
-
}
|
|
92
|
+
const result = await searchClient.search({ view: "brand", locale });
|
|
106
93
|
|
|
107
|
-
|
|
108
|
-
return `locale:=${tsFilterValue(locale)} && enabled:=true`;
|
|
94
|
+
return result.facets.find(facet => facet.field === "manufacturer")?.counts ?? [];
|
|
109
95
|
}
|
|
110
96
|
}
|
|
@@ -11,32 +11,31 @@ const LIST_PAGE_SIZE = 48;
|
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Live product reads via the public revenexx API: the products app's real
|
|
14
|
-
* Typesense collection, scoped per locale (document id = `{entity_id}:{locale}
|
|
14
|
+
* Typesense collection, scoped per locale (document id = `{entity_id}:{locale}`,
|
|
15
|
+
* the locale a full code like `de-DE` or, before the migration, a bare `de`).
|
|
16
|
+
* Listings go through the search service's `listing` view (searchClient.ts);
|
|
17
|
+
* single products are looked up by document id (getLiveProductDoc).
|
|
15
18
|
* Prices, stocks and images are not in the index yet — the mapping serves
|
|
16
19
|
* neutral defaults (see liveCatalog.ts).
|
|
17
20
|
*/
|
|
18
21
|
export class ApiProductService implements IProductService {
|
|
19
22
|
async listProducts(filter?: ProductListFilter): Promise<Product[]> {
|
|
20
23
|
const locale: Locale = filter?.locale ?? "de";
|
|
21
|
-
const filterParts = [`locale:=${tsFilterValue(locale)}`, "enabled:=true"];
|
|
22
24
|
|
|
23
25
|
// Category facets carry the category CODE — our category slugs.
|
|
24
26
|
// Products are indexed with their LEAF category only, so a branch
|
|
25
27
|
// filters across its whole subtree, however deep the tree runs.
|
|
26
28
|
const branch = filter?.subcategory ?? filter?.category;
|
|
27
|
-
|
|
28
|
-
const codes = await liveCategorySubtreeCodes([branch]);
|
|
29
|
-
filterParts.push(`categories:=[${codes.map(tsFilterValue).join(",")}]`);
|
|
30
|
-
}
|
|
29
|
+
const categories = branch ? await liveCategorySubtreeCodes([branch]) : [];
|
|
31
30
|
|
|
32
|
-
const result = await
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
filterBy: filterParts.join(" && "),
|
|
31
|
+
const result = await searchClient.search({
|
|
32
|
+
view: "listing",
|
|
33
|
+
...(categories.length ? { filters: { categories } } : {}),
|
|
36
34
|
perPage: LIST_PAGE_SIZE,
|
|
35
|
+
locale,
|
|
37
36
|
});
|
|
38
37
|
|
|
39
|
-
return
|
|
38
|
+
return result.docs.map(doc => mapLiveDocToProduct(doc));
|
|
40
39
|
}
|
|
41
40
|
|
|
42
41
|
async getProductById(id: string, locale: Locale = "de"): Promise<Product | null> {
|
|
@@ -52,6 +51,10 @@ export class ApiProductService implements IProductService {
|
|
|
52
51
|
return doc ? mapLiveDocToDetail(doc, locale) : null;
|
|
53
52
|
}
|
|
54
53
|
|
|
54
|
+
async getProductLanguages(id: string, languages: readonly string[]): Promise<string[]> {
|
|
55
|
+
return getLiveProductLanguages(id, languages);
|
|
56
|
+
}
|
|
57
|
+
|
|
55
58
|
/**
|
|
56
59
|
* Model siblings from the products app's REST rows — the search index has
|
|
57
60
|
* no parent link, so this is the one read that bypasses it.
|
|
@@ -88,6 +88,17 @@ export function buyerPrincipal(event: H3Event | undefined): string {
|
|
|
88
88
|
return typeof value === "string" ? value : "";
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
/**
|
|
92
|
+
* The contact the request acts for, or undefined. A body that names a contact
|
|
93
|
+
* to an app enforcing the principal (payments 1.0) has to name exactly this
|
|
94
|
+
* one, or is refused as `buyer_mismatch` — so it is read from the principal,
|
|
95
|
+
* not from the session cookie.
|
|
96
|
+
*/
|
|
97
|
+
export function principalContactId(event: H3Event | undefined): string | undefined {
|
|
98
|
+
const principal = buyerPrincipal(event);
|
|
99
|
+
return principal.startsWith("contact:") ? principal.slice("contact:".length) || undefined : undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
91
102
|
/**
|
|
92
103
|
* Least → most privileged, as the customers app orders its built-ins. A role
|
|
93
104
|
* the shop does not know ranks below all of them, so it can grant nothing.
|
|
@@ -13,6 +13,8 @@ import type {
|
|
|
13
13
|
ProductVariantAxis,
|
|
14
14
|
ProductVariants,
|
|
15
15
|
} from "../../app/interfaces/product-variants";
|
|
16
|
+
import { pickLocalizedLabel, searchLocaleKeys } from "../../app/shared/locale";
|
|
17
|
+
import { languagesWithDocuments } from "../../app/shared/productLocales";
|
|
16
18
|
import type { Locale } from "./locale";
|
|
17
19
|
|
|
18
20
|
/**
|
|
@@ -72,6 +74,8 @@ export interface LiveSearchParams {
|
|
|
72
74
|
perPage?: number;
|
|
73
75
|
/** Facet values per field. Typesense returns only 10 when unset. */
|
|
74
76
|
maxFacetValues?: number;
|
|
77
|
+
/** Only these document fields in the hits (`include_fields`). */
|
|
78
|
+
includeFields?: string;
|
|
75
79
|
}
|
|
76
80
|
|
|
77
81
|
/** Where the platform's CDN is mounted, on every storefront domain. */
|
|
@@ -164,7 +168,13 @@ const LIVE_DEFAULT_TAX_RATE = 19;
|
|
|
164
168
|
|
|
165
169
|
|
|
166
170
|
/**
|
|
167
|
-
* Several product searches in ONE request.
|
|
171
|
+
* Several product searches in ONE request, over the raw multi_search route.
|
|
172
|
+
*
|
|
173
|
+
* Searches go through searchClient.ts (the view-based query endpoint) now.
|
|
174
|
+
* What remains here: the deprecated fallback for gateways without that route
|
|
175
|
+
* (searchMultiSearchFallback.ts), and the document lookups by id below
|
|
176
|
+
* (getLiveProductDoc, association targets) — fetching known documents is a
|
|
177
|
+
* different contract from a search and is not part of the query endpoint.
|
|
168
178
|
*
|
|
169
179
|
* Raw call: the gateway 404s the POST single-search route its spec declares and
|
|
170
180
|
* the GET contract does not declare facet_by, so neither the generated search
|
|
@@ -201,6 +211,7 @@ export async function searchLiveProductsMulti(
|
|
|
201
211
|
...(p.facetBy ? { facet_by: p.facetBy } : {}),
|
|
202
212
|
...(p.maxFacetValues ? { max_facet_values: p.maxFacetValues } : {}),
|
|
203
213
|
...(p.sortBy ? { sort_by: p.sortBy } : {}),
|
|
214
|
+
...(p.includeFields ? { include_fields: p.includeFields } : {}),
|
|
204
215
|
page: p.page ?? 1,
|
|
205
216
|
per_page: p.perPage ?? 24,
|
|
206
217
|
})),
|
|
@@ -230,6 +241,69 @@ export function tsFilterValue(value: string): string {
|
|
|
230
241
|
return "`" + value.replace(/`/g, "") + "`";
|
|
231
242
|
}
|
|
232
243
|
|
|
244
|
+
// ---------------------------------------------------------------------------
|
|
245
|
+
// Locale scoping — one document per product AND locale (`{entity_id}:{locale}`).
|
|
246
|
+
// The index is moving from bare languages (`de`) to full codes (`de-DE`); every
|
|
247
|
+
// live query accepts both and prefers the full code (app/shared/locale.ts), so
|
|
248
|
+
// the storefront keeps working before, during and after that migration.
|
|
249
|
+
// ---------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
/** `locale:=[`de-DE`,`de`]` — the documents of one storefront locale. */
|
|
252
|
+
export function liveLocaleClause(locale: string): string {
|
|
253
|
+
return `locale:=[${searchLocaleKeys(locale).map(tsFilterValue).join(",")}]`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The clauses every live catalogue query pins: the request's locale and
|
|
258
|
+
* enabled products only. Kept as separate parts so a caller can drop one the
|
|
259
|
+
* collection turns out not to declare without losing the other.
|
|
260
|
+
*
|
|
261
|
+
* Searches no longer build these: the query endpoint pins locale and enabled
|
|
262
|
+
* on the server (searchClient.ts). They remain for the deprecated multi_search
|
|
263
|
+
* fallback and the document lookups by id below.
|
|
264
|
+
*/
|
|
265
|
+
export function liveCatalogFilterParts(locale: string): string[] {
|
|
266
|
+
return [liveLocaleClause(locale), "enabled:=true"];
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The pinned clauses plus any extra ones, joined into one `filter_by`. */
|
|
270
|
+
export function liveCatalogFilter(locale: string, ...extra: string[]): string {
|
|
271
|
+
return [...liveCatalogFilterParts(locale), ...extra].join(" && ");
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** `id:=[…]` over every document id these products may carry in this locale. */
|
|
275
|
+
export function liveDocIdClause(entityIds: readonly string[], locale: string): string {
|
|
276
|
+
const keys = searchLocaleKeys(locale);
|
|
277
|
+
const ids = entityIds.flatMap(id => keys.map(key => tsFilterValue(`${id}:${key}`)));
|
|
278
|
+
return `id:=[${ids.join(",")}]`;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* One document per product, the best-matching locale winning, in the order the
|
|
283
|
+
* products first appear. While both `{id}:de` and `{id}:de-DE` exist, a query
|
|
284
|
+
* over both keys returns the product twice; this keeps the full-code one.
|
|
285
|
+
*/
|
|
286
|
+
export function preferLocaleDocs<T extends Pick<LiveProductDoc, "id" | "entity_id" | "locale">>(
|
|
287
|
+
docs: readonly T[],
|
|
288
|
+
locale: string,
|
|
289
|
+
): T[] {
|
|
290
|
+
const keys = searchLocaleKeys(locale);
|
|
291
|
+
const rank = (doc: T): number => {
|
|
292
|
+
const docLocale = doc.locale || doc.id.slice(doc.id.lastIndexOf(":") + 1);
|
|
293
|
+
const index = keys.indexOf(docLocale);
|
|
294
|
+
return index === -1 ? keys.length : index;
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
const best = new Map<string, T>();
|
|
298
|
+
for (const doc of docs) {
|
|
299
|
+
const current = best.get(doc.entity_id);
|
|
300
|
+
if (!current || rank(doc) < rank(current)) {
|
|
301
|
+
best.set(doc.entity_id, doc);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return [...best.values()];
|
|
305
|
+
}
|
|
306
|
+
|
|
233
307
|
export function mapLiveDocToProduct(doc: LiveProductDoc): Product {
|
|
234
308
|
const categorySlug = doc.categories?.[0] ?? "";
|
|
235
309
|
const category = doc.category_labels?.[0] ?? categorySlug;
|
|
@@ -307,69 +381,110 @@ export async function mapLiveDocToDetail(doc: LiveProductDoc, locale: Locale = "
|
|
|
307
381
|
* Uses a filtered search instead of the document-GET route — the search
|
|
308
382
|
* proxy's document endpoint currently rejects gateway-trust calls
|
|
309
383
|
* (responds 401 "x-typesense-api-key"), and `id` is filterable anyway.
|
|
384
|
+
*
|
|
385
|
+
* Stays on multi_search rather than the view-based query endpoint: a lookup
|
|
386
|
+
* by document id is not a search, and the query endpoint has no contract for
|
|
387
|
+
* it (it takes no `id` filter and folds locale variants itself).
|
|
310
388
|
*/
|
|
311
389
|
export async function getLiveProductDoc(entityId: string, locale: Locale): Promise<LiveProductDoc | null> {
|
|
312
390
|
const result = await searchLiveProducts({
|
|
313
391
|
q: "*",
|
|
314
392
|
queryBy: "name",
|
|
315
|
-
filterBy:
|
|
316
|
-
perPage:
|
|
393
|
+
filterBy: liveDocIdClause([entityId], locale),
|
|
394
|
+
perPage: searchLocaleKeys(locale).length,
|
|
317
395
|
});
|
|
318
|
-
|
|
396
|
+
const docs = (result.hits ?? []).map(hit => hit.document);
|
|
397
|
+
return preferLocaleDocs(docs, locale)[0] ?? null;
|
|
319
398
|
}
|
|
320
399
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
400
|
+
/**
|
|
401
|
+
* `id:=[…]` over every document id one product may carry in any of these
|
|
402
|
+
* locales, each id once: `42` in `de`, `en` → `42:de-DE`, `42:de`, `42:en-US`,
|
|
403
|
+
* `42:en`.
|
|
404
|
+
*/
|
|
405
|
+
export function liveDocIdClauseForLocales(entityId: string, locales: readonly string[]): string {
|
|
406
|
+
const keys = [...new Set(locales.flatMap(locale => searchLocaleKeys(locale)))];
|
|
407
|
+
return `id:=[${keys.map(key => tsFilterValue(`${entityId}:${key}`)).join(",")}]`;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const PRODUCT_LANGUAGES_TTL_MS = 5 * 60 * 1000;
|
|
411
|
+
const PRODUCT_LANGUAGES_MAX_ENTRIES = 5000;
|
|
412
|
+
|
|
413
|
+
// Partitioned by tenant like the category cache. Translations change rarely
|
|
414
|
+
// and every product page asks (switcher and hreflang), so a short TTL keeps
|
|
415
|
+
// it to one search per product and tenant every few minutes.
|
|
416
|
+
const productLanguagesCache = new Map<string, { languages: string[]; loadedAt: number }>();
|
|
417
|
+
|
|
418
|
+
/** Clears the per-product language cache — tests only. */
|
|
419
|
+
export function resetProductLanguagesCache(): void {
|
|
420
|
+
productLanguagesCache.clear();
|
|
421
|
+
}
|
|
326
422
|
|
|
327
423
|
/**
|
|
328
|
-
*
|
|
424
|
+
* The storefront languages (of `languages`) this product has a page in.
|
|
329
425
|
*
|
|
330
|
-
*
|
|
331
|
-
*
|
|
332
|
-
*
|
|
333
|
-
*
|
|
334
|
-
* specification rows reading `schneidbreite_bs`.
|
|
335
|
-
*
|
|
336
|
-
* Exact key first, then the first key whose language subtag matches, taken in
|
|
337
|
-
* sorted key order so a map carrying several regions (`de-AT`, `de-DE`) always
|
|
338
|
-
* answers the same way whatever the insertion order was. An empty string counts
|
|
339
|
-
* as no label — it renders as a blank name, which is worse than the code.
|
|
426
|
+
* ONE request across every language: a lookup by document id over all their
|
|
427
|
+
* keys. It goes through multi_search, which does not pin a locale (the query
|
|
428
|
+
* endpoint does, via X-Revenexx-Locale, and so could only answer for one
|
|
429
|
+
* language per request). Only `id` and `locale` come back.
|
|
340
430
|
*/
|
|
341
|
-
function
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
return exact;
|
|
431
|
+
export async function getLiveProductLanguages(entityId: string, languages: readonly string[]): Promise<string[]> {
|
|
432
|
+
if (!entityId || !languages.length) {
|
|
433
|
+
return [];
|
|
345
434
|
}
|
|
346
435
|
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
436
|
+
const cacheKey = `${revenexxTenantKey()}|${entityId}|${languages.join(",")}`;
|
|
437
|
+
const cached = productLanguagesCache.get(cacheKey);
|
|
438
|
+
if (cached && Date.now() - cached.loadedAt < PRODUCT_LANGUAGES_TTL_MS) {
|
|
439
|
+
return cached.languages;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const keyCount = new Set(languages.flatMap(language => searchLocaleKeys(language))).size;
|
|
443
|
+
const result = await searchLiveProducts({
|
|
444
|
+
q: "*",
|
|
445
|
+
queryBy: "name",
|
|
446
|
+
filterBy: liveDocIdClauseForLocales(entityId, languages),
|
|
447
|
+
includeFields: "id,locale",
|
|
448
|
+
perPage: keyCount,
|
|
449
|
+
});
|
|
450
|
+
const docLocales = (result.hits ?? []).map(({ document }) =>
|
|
451
|
+
document.locale || document.id.slice(document.id.lastIndexOf(":") + 1));
|
|
452
|
+
const available = languagesWithDocuments(docLocales, languages);
|
|
453
|
+
|
|
454
|
+
if (productLanguagesCache.size >= PRODUCT_LANGUAGES_MAX_ENTRIES) {
|
|
455
|
+
// Oldest first (insertion order) — a bound, not an LRU.
|
|
456
|
+
const oldest = productLanguagesCache.keys().next().value;
|
|
457
|
+
if (oldest !== undefined) {
|
|
458
|
+
productLanguagesCache.delete(oldest);
|
|
352
459
|
}
|
|
353
460
|
}
|
|
354
|
-
|
|
461
|
+
productLanguagesCache.set(cacheKey, { languages: available, loadedAt: Date.now() });
|
|
462
|
+
return available;
|
|
355
463
|
}
|
|
356
464
|
|
|
465
|
+
// ---------------------------------------------------------------------------
|
|
466
|
+
// Labels — every localized name the catalogue carries (categories, attributes,
|
|
467
|
+
// select options, association types) arrives as the same `labels` map, so it is
|
|
468
|
+
// read in exactly one place.
|
|
469
|
+
// ---------------------------------------------------------------------------
|
|
470
|
+
|
|
357
471
|
/**
|
|
358
472
|
* Localised label with the products app's fallback chain: requested locale,
|
|
359
473
|
* then German, then English, then the technical code.
|
|
474
|
+
*
|
|
475
|
+
* Tenants do not agree on the key form: one PIM writes `de` / `en`, another
|
|
476
|
+
* writes BCP-47 tags (`de-DE`, `en-GB`) for the same two languages. An
|
|
477
|
+
* exact-key lookup silently missed the second kind and EVERY label degraded to
|
|
478
|
+
* its technical code — a whole navigation reading `1`, `10837`, `10876`, and
|
|
479
|
+
* specification rows reading `schneidbreite_bs`. Full and short codes match in
|
|
480
|
+
* both directions (app/shared/locale.ts, shared with the client's facet labels).
|
|
360
481
|
*/
|
|
361
482
|
export function pickLiveLabel(
|
|
362
483
|
labels: Record<string, string> | null | undefined,
|
|
363
|
-
locale: Locale,
|
|
484
|
+
locale: Locale | string,
|
|
364
485
|
fallback: string,
|
|
365
486
|
): string {
|
|
366
|
-
|
|
367
|
-
return fallback;
|
|
368
|
-
}
|
|
369
|
-
return labelForLanguage(labels, locale)
|
|
370
|
-
?? labelForLanguage(labels, "de")
|
|
371
|
-
?? labelForLanguage(labels, "en")
|
|
372
|
-
?? fallback;
|
|
487
|
+
return pickLocalizedLabel(labels, locale, fallback);
|
|
373
488
|
}
|
|
374
489
|
|
|
375
490
|
// ---------------------------------------------------------------------------
|
|
@@ -596,6 +711,34 @@ export function subcategoryIndex(
|
|
|
596
711
|
return { labels, branchOf };
|
|
597
712
|
}
|
|
598
713
|
|
|
714
|
+
/**
|
|
715
|
+
* The top level of the storefront's category tree as a facet axis: each
|
|
716
|
+
* top-level category's label, and every code beneath it mapped back to it.
|
|
717
|
+
*
|
|
718
|
+
* The search page offers a `category` facet; the live index only facets
|
|
719
|
+
* `categories`, at the leaf. Rolled up through this, leaf counts become
|
|
720
|
+
* counts per top-level category — the same categories the navigation shows,
|
|
721
|
+
* because the same tree builder decides what "top level" means.
|
|
722
|
+
*/
|
|
723
|
+
export async function liveTopCategoryIndex(locale: Locale): Promise<LiveSubcategoryIndex> {
|
|
724
|
+
return topCategoryIndex(await loadLiveCategoryRows(), locale);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** Pure core of liveTopCategoryIndex(), exported for tests. */
|
|
728
|
+
export function topCategoryIndex(rows: LiveCategoryRow[], locale: Locale): LiveSubcategoryIndex {
|
|
729
|
+
const labels = new Map<string, string>();
|
|
730
|
+
const branchOf = new Map<string, string>();
|
|
731
|
+
for (const top of buildLiveCategoryTree(rows, locale)) {
|
|
732
|
+
labels.set(top.slug, top.label);
|
|
733
|
+
for (const code of subtreeCodes(rows, [top.slug])) {
|
|
734
|
+
if (!branchOf.has(code)) {
|
|
735
|
+
branchOf.set(code, top.slug);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
return { labels, branchOf };
|
|
740
|
+
}
|
|
741
|
+
|
|
599
742
|
/**
|
|
600
743
|
* Roll `categories` facet counts up onto the direct children they belong to.
|
|
601
744
|
*
|
|
@@ -914,8 +1057,13 @@ function liveOrderUnitLabel(raw: unknown, locale: Locale): string | null {
|
|
|
914
1057
|
}
|
|
915
1058
|
|
|
916
1059
|
function livePimName(product: LivePimProduct, locale: Locale): string {
|
|
917
|
-
const
|
|
918
|
-
|
|
1060
|
+
const names: Record<string, string> = {};
|
|
1061
|
+
for (const [key, values] of Object.entries(product.attribute_values?.locale_specific ?? {})) {
|
|
1062
|
+
if (values?.name) {
|
|
1063
|
+
names[key] = values.name;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
return pickLiveLabel(names, locale, product.sku);
|
|
919
1067
|
}
|
|
920
1068
|
|
|
921
1069
|
/**
|
|
@@ -1114,7 +1262,10 @@ function isMandatoryAssociation(type: LiveAssociationTypeRow): boolean {
|
|
|
1114
1262
|
return type.is_quantified === true || type.code === "mandatory";
|
|
1115
1263
|
}
|
|
1116
1264
|
|
|
1117
|
-
/**
|
|
1265
|
+
/**
|
|
1266
|
+
* Typesense caps a batch; resolve targets in chunks and keep one round trip per
|
|
1267
|
+
* chunk. 100 targets × two locale keys stays under its 250 hits per page.
|
|
1268
|
+
*/
|
|
1118
1269
|
const TARGET_CHUNK_SIZE = 100;
|
|
1119
1270
|
|
|
1120
1271
|
async function resolveAssociationTargets(
|
|
@@ -1128,19 +1279,20 @@ async function resolveAssociationTargets(
|
|
|
1128
1279
|
|
|
1129
1280
|
// Filtering on `id` (the `{entity_id}:{locale}` document id) rather than
|
|
1130
1281
|
// `entity_id`, which is not a filterable field — same reason
|
|
1131
|
-
// getLiveProductDoc() goes through `id:=`.
|
|
1282
|
+
// getLiveProductDoc() goes through `id:=`. Each target may answer under
|
|
1283
|
+
// the full and the short locale code, hence the page size.
|
|
1284
|
+
const perTarget = searchLocaleKeys(locale).length;
|
|
1132
1285
|
const results = await searchLiveProductsMulti(chunks.map(chunk => ({
|
|
1133
1286
|
q: "*",
|
|
1134
1287
|
queryBy: "name",
|
|
1135
|
-
filterBy:
|
|
1136
|
-
perPage: chunk.length,
|
|
1288
|
+
filterBy: liveDocIdClause(chunk, locale),
|
|
1289
|
+
perPage: chunk.length * perTarget,
|
|
1137
1290
|
})));
|
|
1138
1291
|
|
|
1292
|
+
const docs = results.flatMap(result => (result.hits ?? []).map(hit => hit.document));
|
|
1139
1293
|
const byId = new Map<string, Product>();
|
|
1140
|
-
for (const
|
|
1141
|
-
|
|
1142
|
-
byId.set(hit.document.entity_id, mapLiveDocToProduct(hit.document));
|
|
1143
|
-
}
|
|
1294
|
+
for (const doc of preferLocaleDocs(docs, locale)) {
|
|
1295
|
+
byId.set(doc.entity_id, mapLiveDocToProduct(doc));
|
|
1144
1296
|
}
|
|
1145
1297
|
return byId;
|
|
1146
1298
|
}
|