@revenexx/cover 0.11.0 → 0.13.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 (61) hide show
  1. package/app/components/account/carts/AccountCartsTable.vue +4 -2
  2. package/app/components/auth/AuthLoginPanel.vue +71 -16
  3. package/app/components/auth/AuthRegisterPanel.vue +1 -1
  4. package/app/components/cart/recommend/CartCrossSell.vue +2 -1
  5. package/app/components/cart/switcher/CartSwitcher.vue +5 -2
  6. package/app/components/listing/ListingFilterBar.vue +1 -0
  7. package/app/components/listing/ListingFilterDrawer.vue +1 -0
  8. package/app/components/listing/ListingFilterRail.vue +1 -0
  9. package/app/components/search/filter/SearchFacets.vue +10 -3
  10. package/app/components/search/filter/SearchFacetsBar.vue +7 -3
  11. package/app/components/search/filter/SearchFacetsDrawer.vue +7 -2
  12. package/app/components/ui/forms/SearchInput.vue +4 -1
  13. package/app/composables/useAuthStore.ts +4 -2
  14. package/app/composables/useFacetMeta.ts +6 -6
  15. package/app/composables/useProductListing.ts +18 -2
  16. package/app/composables/useSearchListing.ts +16 -0
  17. package/app/interfaces/auth.ts +12 -2
  18. package/app/interfaces/shopSettings.ts +84 -0
  19. package/app/shared/locale.ts +114 -0
  20. package/i18n/locales/de/auth.json +41 -2
  21. package/i18n/locales/de/cart.json +2 -1
  22. package/i18n/locales/en/auth.json +41 -2
  23. package/i18n/locales/en/cart.json +2 -1
  24. package/nuxt.config.ts +22 -0
  25. package/package.json +1 -1
  26. package/server/api/account/quotes/[id]/order.post.ts +14 -3
  27. package/server/api/auth/login.post.ts +16 -3
  28. package/server/api/cart/calculate.post.ts +4 -0
  29. package/server/api/carts/[id]/activate.post.ts +7 -0
  30. package/server/api/carts/[id]/index.delete.ts +2 -0
  31. package/server/api/carts/index.post.ts +4 -0
  32. package/server/api/categories/[slug]/subcategories.get.ts +34 -31
  33. package/server/api/orders/index.post.ts +78 -31
  34. package/server/api/payment/psp-config.get.ts +11 -21
  35. package/server/api/quotes/request.post.ts +2 -2
  36. package/server/api/typesense/search.post.ts +61 -317
  37. package/server/api/typesense/suggest.post.ts +14 -9
  38. package/server/{api/typesense/drop.get.ts → dev/typesense/drop.ts} +2 -1
  39. package/server/{api/typesense/health.get.ts → dev/typesense/health.ts} +1 -0
  40. package/server/dev/typesense/seed.ts +59 -0
  41. package/server/dev/typesense/seedDocuments.ts +105 -0
  42. package/server/interfaces/auth.ts +10 -1
  43. package/server/routes/punchout/start.get.ts +44 -16
  44. package/server/services/ApiAuthService.ts +22 -6
  45. package/server/services/ApiBrandService.ts +28 -42
  46. package/server/services/ApiCartService.ts +64 -22
  47. package/server/services/ApiProductService.ts +10 -11
  48. package/server/services/MockAuthService.ts +21 -2
  49. package/server/utils/buyerIdentity.ts +11 -0
  50. package/server/utils/cartOwnership.ts +40 -0
  51. package/server/utils/liveCatalog.ts +132 -49
  52. package/server/utils/liveListingSearch.ts +201 -0
  53. package/server/utils/livePrices.ts +24 -9
  54. package/server/utils/orderLinePrices.ts +72 -0
  55. package/server/utils/paymentFee.ts +59 -0
  56. package/server/utils/pspConfig.ts +42 -0
  57. package/server/utils/revenexxSdk.ts +25 -2
  58. package/server/utils/searchClient.ts +305 -0
  59. package/server/utils/searchMultiSearchFallback.ts +216 -0
  60. package/server/utils/shopSettings.ts +5 -0
  61. package/server/api/typesense/seed.get.ts +0 -111
@@ -0,0 +1,42 @@
1
+ /** A row of `GET /v1/payments/providers`, as far as the tokenizer config reads it. */
2
+ export interface PspProviderRow {
3
+ provider: string;
4
+ enabled?: boolean;
5
+ test_mode?: boolean;
6
+ options?: Record<string, unknown> | null;
7
+ }
8
+
9
+ export type PspPublicConfig = Record<string, { publishableKey: string; testMode: boolean }>;
10
+
11
+ // Stripe's secret and restricted keys. Pasted into the public slot by mistake,
12
+ // either would be handed to every browser that opens the checkout.
13
+ const SECRET_KEY = /^(sk|rk)_/;
14
+
15
+ /**
16
+ * The publishable keys of the enabled PSPs, for the checkout's client-side
17
+ * tokenizers (RAD-171) — and nothing else from the provider row.
18
+ *
19
+ * The payments app never reads `credentials` back, so the key cannot come from
20
+ * there: it is the merchant's to keep in the provider's `options` as
21
+ * `publishable_key`, which is free, non-secret configuration that the app does
22
+ * return. A value shaped like a secret key is dropped rather than published.
23
+ */
24
+ export function pspPublicConfig(rows: PspProviderRow[]): { providers: PspPublicConfig; refused: string[] } {
25
+ const providers: PspPublicConfig = {};
26
+ const refused: string[] = [];
27
+ for (const row of rows) {
28
+ if (!row.enabled) {
29
+ continue;
30
+ }
31
+ const key = row.options?.publishable_key;
32
+ if (typeof key !== "string" || key.trim() === "") {
33
+ continue;
34
+ }
35
+ if (SECRET_KEY.test(key.trim())) {
36
+ refused.push(row.provider);
37
+ continue;
38
+ }
39
+ providers[row.provider] = { publishableKey: key.trim(), testMode: row.test_mode !== false };
40
+ }
41
+ return { providers, refused };
42
+ }
@@ -59,6 +59,12 @@ export interface RevenexxSdkOptions {
59
59
  export interface RevenexxSdkCallOptions {
60
60
  readonly query?: Record<string, string | number | boolean | undefined>;
61
61
  readonly body?: unknown;
62
+ /**
63
+ * Extra request headers for this one call, over the client's own (tenant,
64
+ * auth, market, channel, principal). The search client sends the locale
65
+ * this way, and a market or channel the caller names explicitly.
66
+ */
67
+ readonly headers?: Readonly<Record<string, string>>;
62
68
  }
63
69
 
64
70
  export interface RevenexxSdk {
@@ -364,9 +370,11 @@ export function useRevenexxSdk(options: RevenexxSdkOptions = {}): RevenexxSdk {
364
370
  }
365
371
  }
366
372
 
373
+ const headers = { ...(options.headers ?? {}) };
374
+
367
375
  if (method === "GET") {
368
376
  // client.call appends flattened params to the URL for GET requests
369
- return await client.call("get", url, {}, query) as T;
377
+ return await client.call("get", url, headers, query) as T;
370
378
  }
371
379
 
372
380
  for (const [key, value] of Object.entries(query)) {
@@ -375,7 +383,7 @@ export function useRevenexxSdk(options: RevenexxSdkOptions = {}): RevenexxSdk {
375
383
  return await client.call(
376
384
  method.toLowerCase(),
377
385
  url,
378
- { "content-type": "application/json" },
386
+ { ...headers, "content-type": "application/json" },
379
387
  (options.body ?? {}) as never,
380
388
  ) as T;
381
389
  }
@@ -409,3 +417,18 @@ export function useRevenexxSdk(options: RevenexxSdkOptions = {}): RevenexxSdk {
409
417
  }
410
418
  return instance;
411
419
  }
420
+
421
+ /**
422
+ * A client that acts as the tenant, for a call that is the merchant's work and
423
+ * not the buyer's — even inside a buyer's request (RAD-174).
424
+ *
425
+ * Since every call made for a buyer carries their principal, the apps hold it
426
+ * to the buyer's own routes: the orders app answers `buyer_not_permitted` to a
427
+ * payment-status update made on a buyer's behalf, because a buyer does not say
428
+ * their own order is paid. Recording what the payments app answered, or
429
+ * undoing an order whose payment failed, is the storefront acting as the
430
+ * merchant's system, and is made as one.
431
+ */
432
+ export function useTenantSdk(): RevenexxSdk {
433
+ return useRevenexxSdk({ principal: "" });
434
+ }
@@ -0,0 +1,305 @@
1
+ import { searchLocaleKeys } from "../../app/shared/locale";
2
+ import type { LiveProductDoc } from "./liveCatalog";
3
+ import { preferLocaleDocs } from "./liveCatalog";
4
+ import { searchViaMultiSearch } from "./searchMultiSearchFallback";
5
+
6
+ /**
7
+ * The one way the BFF searches the live catalogue (PE-862).
8
+ *
9
+ * Every caller names a VIEW (search, category, suggest, brand, listing) and
10
+ * the search service decides what that view means: which fields a query
11
+ * matches, how they are weighted, which facets come back, the locale and
12
+ * enabled pins, the channel filter. Merchandisers tune that per view in the
13
+ * search admin; the storefront only says what it is asking for. That is why
14
+ * nothing here builds `query_by`, `facet_by` or a `filter_by` string.
15
+ *
16
+ * Gateways that do not route `POST /v1/search/query` yet answer 404/405; the
17
+ * request then goes the old multi_search way (searchMultiSearchFallback.ts,
18
+ * deprecated), which reproduces the same defaults on the client side. The
19
+ * fallback is remembered per tenant for a few minutes so a page does not pay
20
+ * two round trips per search, and logged once.
21
+ */
22
+
23
+ export type SearchView = "search" | "category" | "suggest" | "brand" | "listing";
24
+
25
+ /** A range on a numeric field; either bound may be left open. */
26
+ export interface SearchRangeFilter {
27
+ readonly min?: number;
28
+ readonly max?: number;
29
+ }
30
+
31
+ /** A value list (any of), a numeric range, or a pinned boolean. */
32
+ export type SearchFilterValue = readonly string[] | SearchRangeFilter | boolean;
33
+
34
+ export type SearchFilters = Readonly<Record<string, SearchFilterValue>>;
35
+
36
+ export interface SearchClientParams {
37
+ readonly view: SearchView;
38
+ /** Logical collection name; `products` when omitted. */
39
+ readonly collection?: string;
40
+ /** `*` (match all) when empty. */
41
+ readonly q?: string;
42
+ readonly filters?: SearchFilters;
43
+ /** `relevance` or `<field>_asc` / `<field>_desc`. */
44
+ readonly sort?: string;
45
+ readonly page?: number;
46
+ /** Left to the view's preset when omitted. */
47
+ readonly perPage?: number;
48
+ /** Storefront locale, bare (`de`) or full (`de-DE`). */
49
+ readonly locale?: string;
50
+ /** Overrides the market the SDK client derives from the request. */
51
+ readonly market?: string;
52
+ /** Overrides the channel the SDK client derives from the punchout visit. */
53
+ readonly channel?: string;
54
+ }
55
+
56
+ export interface SearchFacetCount {
57
+ value: string;
58
+ count: number;
59
+ }
60
+
61
+ export interface SearchFacetResult {
62
+ field: string;
63
+ counts: SearchFacetCount[];
64
+ stats?: { min?: number; max?: number };
65
+ }
66
+
67
+ /** What curation asked the storefront to do with this query. */
68
+ export type SearchAction =
69
+ | { type: "redirect"; url: string }
70
+ | { type: "banner"; [key: string]: unknown }
71
+ | { type: "metadata"; data?: unknown };
72
+
73
+ export interface SearchClientResult {
74
+ /** Which path answered: the view-based endpoint or the deprecated fallback. */
75
+ source: "query" | "multi_search";
76
+ /** For search events (wave 6); "" on the fallback. */
77
+ queryId: string;
78
+ found: number;
79
+ page: number;
80
+ perPage: number;
81
+ /** The locale the service applied, "" when none. */
82
+ locale: string;
83
+ /** One document per product, the best-matching locale winning. */
84
+ docs: LiveProductDoc[];
85
+ facets: SearchFacetResult[];
86
+ actions: SearchAction[];
87
+ /** Filter fields the collection does not carry, so nothing was filtered on them. */
88
+ ignoredFilters: string[];
89
+ /** The sort that could not be applied, or null. */
90
+ ignoredSort: string | null;
91
+ /** Hits on this page that were dropped (locale duplicates, disabled); subtract from `found`. */
92
+ withheld: number;
93
+ }
94
+
95
+ const QUERY_PATH = "/v1/search/query";
96
+ const DEFAULT_COLLECTION = "products";
97
+ const MAX_PER_PAGE = 100;
98
+
99
+ /** How long a tenant whose gateway has no query route stays on the fallback. */
100
+ const ROUTE_MISSING_TTL_MS = 5 * 60 * 1000;
101
+ const routeMissingUntil = new Map<string, number>();
102
+ const routeMissingLogged = new Set<string>();
103
+
104
+ /** Clears the fallback memory — tests only. */
105
+ export function resetSearchClientState(): void {
106
+ routeMissingUntil.clear();
107
+ routeMissingLogged.clear();
108
+ }
109
+
110
+ /** Drops empty lists and open ranges, so the body says only what narrows. */
111
+ function cleanFilters(filters: SearchFilters | undefined): Record<string, unknown> {
112
+ const out: Record<string, unknown> = {};
113
+ for (const [field, value] of Object.entries(filters ?? {})) {
114
+ if (typeof value === "boolean") {
115
+ out[field] = value;
116
+ }
117
+ else if (Array.isArray(value)) {
118
+ const values = value.map(String).filter(Boolean);
119
+ if (values.length) {
120
+ out[field] = values;
121
+ }
122
+ }
123
+ else if (value && typeof value === "object") {
124
+ const { min, max } = value as SearchRangeFilter;
125
+ const range: SearchRangeFilter = {
126
+ ...(typeof min === "number" && Number.isFinite(min) ? { min } : {}),
127
+ ...(typeof max === "number" && Number.isFinite(max) ? { max } : {}),
128
+ };
129
+ if (range.min !== undefined || range.max !== undefined) {
130
+ out[field] = range;
131
+ }
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /** The request the query endpoint gets: path, body and the scope headers. */
138
+ export function buildSearchQueryRequest(params: SearchClientParams): {
139
+ path: string;
140
+ body: Record<string, unknown>;
141
+ headers: Record<string, string>;
142
+ } {
143
+ const headers: Record<string, string> = {};
144
+ const locale = params.locale ? searchLocaleKeys(params.locale)[0] : undefined;
145
+ if (locale) {
146
+ headers["X-Revenexx-Locale"] = locale;
147
+ }
148
+ if (params.market) {
149
+ headers["X-Revenexx-Market"] = params.market;
150
+ }
151
+ if (params.channel) {
152
+ headers["X-Revenexx-Channel"] = params.channel;
153
+ }
154
+
155
+ const filters = cleanFilters(params.filters);
156
+ const body: Record<string, unknown> = {
157
+ collection: params.collection ?? DEFAULT_COLLECTION,
158
+ view: params.view,
159
+ q: params.q?.trim() || "*",
160
+ ...(Object.keys(filters).length ? { filters } : {}),
161
+ sort: params.sort || "relevance",
162
+ page: Math.max(1, Math.floor(params.page ?? 1)),
163
+ };
164
+ if (params.perPage !== undefined) {
165
+ body.per_page = Math.min(MAX_PER_PAGE, Math.max(1, Math.floor(params.perPage)));
166
+ }
167
+
168
+ return { path: QUERY_PATH, body, headers };
169
+ }
170
+
171
+ /** The query endpoint's answer, as it comes off the wire. */
172
+ export interface SearchQueryResponse {
173
+ query_id?: string;
174
+ found?: number;
175
+ page?: number;
176
+ per_page?: number;
177
+ locale?: string;
178
+ hits?: { document: LiveProductDoc }[];
179
+ facets?: { field: string; values?: SearchFacetCount[]; stats?: { min?: number; max?: number } }[];
180
+ actions?: unknown[];
181
+ ignored_filters?: string[] | null;
182
+ ignored_sort?: string | null;
183
+ }
184
+
185
+ /** A redirect target the storefront may follow: a site path or an http(s) URL. */
186
+ function safeRedirectUrl(raw: unknown): string | null {
187
+ if (typeof raw !== "string") {
188
+ return null;
189
+ }
190
+ const url = raw.trim();
191
+ if (url.startsWith("/") && !url.startsWith("//")) {
192
+ return url;
193
+ }
194
+ return /^https?:\/\//i.test(url) ? url : null;
195
+ }
196
+
197
+ function normalizeAction(raw: unknown): SearchAction | null {
198
+ if (!raw || typeof raw !== "object") {
199
+ return null;
200
+ }
201
+ const action = raw as Record<string, unknown>;
202
+ if (action.type === "redirect") {
203
+ const url = safeRedirectUrl(action.url ?? action.target);
204
+ return url ? { type: "redirect", url } : null;
205
+ }
206
+ if (action.type === "banner") {
207
+ return { ...action, type: "banner" };
208
+ }
209
+ if (action.type === "metadata") {
210
+ return { type: "metadata", data: action.data };
211
+ }
212
+ return null;
213
+ }
214
+
215
+ /** The query endpoint's answer in the shape every caller reads. */
216
+ export function mapSearchQueryResponse(
217
+ response: SearchQueryResponse,
218
+ params: SearchClientParams,
219
+ ): SearchClientResult {
220
+ const hits = response.hits ?? [];
221
+ const rawDocs = hits.map(hit => hit.document).filter((doc): doc is LiveProductDoc => Boolean(doc));
222
+ // The service already folds `<id>:de` and `<id>:de-DE` into one hit; this
223
+ // is the belt to that brace, and costs nothing when there is nothing to fold.
224
+ const docs = params.locale ? preferLocaleDocs(rawDocs, params.locale) : rawDocs;
225
+
226
+ return {
227
+ source: "query",
228
+ queryId: response.query_id ?? "",
229
+ found: response.found ?? 0,
230
+ page: response.page ?? Math.max(1, params.page ?? 1),
231
+ perPage: response.per_page ?? params.perPage ?? hits.length,
232
+ locale: response.locale ?? "",
233
+ docs,
234
+ facets: (response.facets ?? []).map(facet => ({
235
+ field: facet.field,
236
+ counts: (facet.values ?? []).map(v => ({ value: String(v.value), count: v.count })),
237
+ ...(facet.stats ? { stats: facet.stats } : {}),
238
+ })),
239
+ actions: (response.actions ?? [])
240
+ .map(normalizeAction)
241
+ .filter((action): action is SearchAction => action !== null),
242
+ ignoredFilters: response.ignored_filters ?? [],
243
+ ignoredSort: response.ignored_sort ?? null,
244
+ withheld: hits.length - docs.length,
245
+ };
246
+ }
247
+
248
+ /** The redirect curation set for this query, if any. */
249
+ export function searchRedirect(result: Pick<SearchClientResult, "actions">): string | undefined {
250
+ for (const action of result.actions) {
251
+ if (action.type === "redirect") {
252
+ return action.url;
253
+ }
254
+ }
255
+ return undefined;
256
+ }
257
+
258
+ /** 404/405 from the gateway: the query route is not deployed there yet. */
259
+ export function isSearchRouteMissing(err: unknown): boolean {
260
+ const code = (err as { code?: unknown } | null)?.code;
261
+ return code === 404 || code === 405;
262
+ }
263
+
264
+ function tenantKey(): string {
265
+ try {
266
+ return revenexxTenantKey();
267
+ }
268
+ catch {
269
+ return "";
270
+ }
271
+ }
272
+
273
+ async function search(params: SearchClientParams): Promise<SearchClientResult> {
274
+ const tenant = tenantKey();
275
+ const missingUntil = routeMissingUntil.get(tenant);
276
+ if (missingUntil && missingUntil > Date.now()) {
277
+ return await searchViaMultiSearch(params);
278
+ }
279
+
280
+ const request = buildSearchQueryRequest(params);
281
+ try {
282
+ const response = await useRevenexxSdk().call<SearchQueryResponse>("POST", request.path, {
283
+ body: request.body,
284
+ headers: request.headers,
285
+ });
286
+ routeMissingUntil.delete(tenant);
287
+ return mapSearchQueryResponse(response ?? {}, params);
288
+ }
289
+ catch (err) {
290
+ if (!isSearchRouteMissing(err)) {
291
+ throw err;
292
+ }
293
+ routeMissingUntil.set(tenant, Date.now() + ROUTE_MISSING_TTL_MS);
294
+ if (!routeMissingLogged.has(tenant)) {
295
+ routeMissingLogged.add(tenant);
296
+ getLogService().warn(
297
+ `search: the gateway has no ${QUERY_PATH} route yet, using multi_search`,
298
+ { tenant, view: params.view, ...apiErrorContext(err) },
299
+ );
300
+ }
301
+ return await searchViaMultiSearch(params);
302
+ }
303
+ }
304
+
305
+ export const searchClient = { search };
@@ -0,0 +1,216 @@
1
+ import type { LiveSearchParams, LiveSearchResponse } from "./liveCatalog";
2
+ import { liveCatalogFilterParts, loadLiveAttributeMeta, preferLocaleDocs, tsFilterValue } from "./liveCatalog";
3
+ import type { SearchClientParams, SearchClientResult, SearchFilters, SearchView } from "./searchClient";
4
+
5
+ /**
6
+ * @deprecated The pre-PE-862 search path, kept only for gateways that do not
7
+ * route `POST /v1/search/query` yet (they answer 404/405). Everything here is
8
+ * what the proxy now does on the server: the query_by and facet_by per view,
9
+ * the pinned locale/enabled clauses, and the retries on Typesense's error text
10
+ * when a collection lacks a field. Delete once every gateway serves the query
11
+ * endpoint.
12
+ */
13
+
14
+ /** Typesense's own ceiling for `max_facet_values`. */
15
+ const MAX_FACET_VALUES = 250;
16
+
17
+ /** The built-in defaults of the query endpoint (wave 3 contract §2), per view. */
18
+ const VIEW_DEFAULTS: Record<SearchView, { queryBy: string; facetBy: string; perPage: number; attrs: boolean }> = {
19
+ search: { queryBy: "name,sku,description,manufacturer", facetBy: "manufacturer,kind,categories", perPage: 20, attrs: true },
20
+ listing: { queryBy: "name,sku,description,manufacturer", facetBy: "manufacturer,kind,categories", perPage: 20, attrs: true },
21
+ category: { queryBy: "name,sku,description,manufacturer", facetBy: "manufacturer,kind,categories", perPage: 20, attrs: true },
22
+ suggest: { queryBy: "name,sku", facetBy: "", perPage: 6, attrs: false },
23
+ brand: { queryBy: "name", facetBy: "manufacturer", perPage: 0, attrs: false },
24
+ };
25
+
26
+ /** `Could not find a facet field named …` — an `attrs.*` facet the schema dropped. */
27
+ function isMissingFacetFieldError(err: unknown): boolean {
28
+ const msg = err instanceof Error ? err.message : String(err ?? "");
29
+ return /Could not find a facet field named/i.test(msg);
30
+ }
31
+
32
+ /** `Could not find a field named … in the schema for sorting` — a sort the schema cannot carry. */
33
+ function isMissingSortFieldError(err: unknown): boolean {
34
+ const msg = err instanceof Error ? err.message : String(err ?? "");
35
+ return /Could not find a field named .* in the schema for sorting/i.test(msg);
36
+ }
37
+
38
+ /** The field of `Could not find a filter field named \`x\``, or null. */
39
+ function missingFilterField(err: unknown): string | null {
40
+ const msg = err instanceof Error ? err.message : String(err ?? "");
41
+ return /Could not find a filter field named/i.test(msg)
42
+ ? (msg.match(/filter field named `([^`]+)`/i)?.[1] ?? "")
43
+ : null;
44
+ }
45
+
46
+ /**
47
+ * Structured filters as `filter_by` clauses: a list is an exact match on any
48
+ * of its values, a range is bounded on either side, a boolean is pinned.
49
+ * `enabled` is skipped — it is one of the pinned clauses already.
50
+ */
51
+ export function multiSearchFilterClauses(filters: SearchFilters | undefined): string[] {
52
+ const clauses: string[] = [];
53
+ for (const [field, value] of Object.entries(filters ?? {})) {
54
+ if (field === "enabled") {
55
+ continue;
56
+ }
57
+ if (typeof value === "boolean") {
58
+ clauses.push(`${field}:=${value}`);
59
+ }
60
+ else if (Array.isArray(value)) {
61
+ if (value.length) {
62
+ clauses.push(`${field}:=[${value.map(v => tsFilterValue(String(v))).join(",")}]`);
63
+ }
64
+ }
65
+ else if (value && typeof value === "object") {
66
+ const { min, max } = value as { min?: number; max?: number };
67
+ if (min !== undefined && max !== undefined) {
68
+ clauses.push(`${field}:[${min}..${max}]`);
69
+ }
70
+ else if (min !== undefined) {
71
+ clauses.push(`${field}:>=${min}`);
72
+ }
73
+ else if (max !== undefined) {
74
+ clauses.push(`${field}:<=${max}`);
75
+ }
76
+ }
77
+ }
78
+ return clauses;
79
+ }
80
+
81
+ /** `name_asc` → `name:asc`; `relevance` and anything unreadable → no sort. */
82
+ export function multiSearchSortBy(sort: string | undefined): string | undefined {
83
+ const match = sort?.match(/^([a-z0-9_.]+)_(asc|desc)$/i);
84
+ return match ? `${match[1]}:${match[2]!.toLowerCase()}` : undefined;
85
+ }
86
+
87
+ /**
88
+ * The tenant's filterable attributes as `attrs.<code>` facets. The query
89
+ * endpoint reads them off the schema; here they come from the attribute meta,
90
+ * which may lag the schema by its cache TTL — the facet retry below covers that.
91
+ */
92
+ async function attributeFacets(): Promise<string[]> {
93
+ const meta = await loadLiveAttributeMeta().catch(() => ({}));
94
+ return Object.entries(meta)
95
+ .filter(([, m]) => m.isFilterable && !m.hidden)
96
+ .map(([code]) => `attrs.${code}`);
97
+ }
98
+
99
+ /**
100
+ * @deprecated One search over multi_search, shaped like the query endpoint's
101
+ * answer. Three independent degradations, each retried once: a filter field the
102
+ * collection does not declare (dropped, and `enabled` then enforced on the
103
+ * documents), a dynamic facet the schema no longer has, and a sort field it
104
+ * never had.
105
+ */
106
+ export async function searchViaMultiSearch(params: SearchClientParams): Promise<SearchClientResult> {
107
+ const defaults = VIEW_DEFAULTS[params.view] ?? VIEW_DEFAULTS.search;
108
+ const locale = params.locale ?? "";
109
+ const page = Math.max(1, params.page ?? 1);
110
+ const perPage = params.perPage ?? defaults.perPage;
111
+
112
+ const filterParts = [
113
+ ...(locale ? liveCatalogFilterParts(locale) : ["enabled:=true"]),
114
+ ...multiSearchFilterClauses(params.filters),
115
+ ];
116
+ const spineFacets = defaults.facetBy;
117
+ const dynamicFacets = defaults.attrs ? await attributeFacets() : [];
118
+ let facetBy = [spineFacets, ...dynamicFacets].filter(Boolean).join(",");
119
+ let sortBy = multiSearchSortBy(params.sort);
120
+
121
+ const droppedFilterFields = new Set<string>();
122
+ let droppedSort: string | null = null;
123
+
124
+ const run = (): Promise<LiveSearchResponse> => {
125
+ const search: LiveSearchParams = {
126
+ q: params.q?.trim() || "*",
127
+ queryBy: defaults.queryBy,
128
+ filterBy: filterParts
129
+ .filter(part => ![...droppedFilterFields].some(f => part.startsWith(`${f}:`)))
130
+ .join(" && "),
131
+ ...(facetBy ? { facetBy, maxFacetValues: MAX_FACET_VALUES } : {}),
132
+ ...(sortBy ? { sortBy } : {}),
133
+ page,
134
+ perPage,
135
+ };
136
+ return searchLiveProducts(search);
137
+ };
138
+
139
+ let response: LiveSearchResponse | undefined;
140
+ // Bounded: every pass either drops something it has not dropped before or
141
+ // rethrows, and there are only so many clauses, facets and sorts.
142
+ for (let attempt = 0; attempt < filterParts.length + 3 && !response; attempt++) {
143
+ try {
144
+ response = await run();
145
+ }
146
+ catch (err) {
147
+ const missing = missingFilterField(err);
148
+ if (missing && !droppedFilterFields.has(missing)) {
149
+ getLogService().warn(
150
+ `search: the collection does not declare the filter field \`${missing}\`, retrying without that clause`,
151
+ toErrorContext(err),
152
+ );
153
+ droppedFilterFields.add(missing);
154
+ continue;
155
+ }
156
+ if (dynamicFacets.length && facetBy !== spineFacets && isMissingFacetFieldError(err)) {
157
+ getLogService().warn(
158
+ "search: dynamic facet missing in Typesense, retrying with spine facets only",
159
+ toErrorContext(err),
160
+ );
161
+ facetBy = spineFacets;
162
+ continue;
163
+ }
164
+ if (sortBy && isMissingSortFieldError(err)) {
165
+ getLogService().warn(
166
+ "search: collection has no sortable field for this sort, retrying unsorted",
167
+ toErrorContext(err),
168
+ );
169
+ droppedSort = params.sort ?? null;
170
+ sortBy = undefined;
171
+ continue;
172
+ }
173
+ throw err;
174
+ }
175
+ }
176
+ if (!response) {
177
+ response = await run();
178
+ }
179
+
180
+ // A clause the collection could not carry is enforced here instead.
181
+ // Typesense STORES a field it does not index and hands it back on every hit,
182
+ // so `enabled` can still be read: dropping the clause costs an exact count,
183
+ // never a disabled product on the page.
184
+ const allHits = response.hits ?? [];
185
+ const hits = droppedFilterFields.has("enabled")
186
+ ? allHits.filter(hit => hit.document?.enabled !== false)
187
+ : allHits;
188
+ const disabled = allHits.length - hits.length;
189
+ if (disabled > 0) {
190
+ getLogService().warn(
191
+ `search: withheld ${disabled} disabled product(s) the index could not filter out`,
192
+ { view: params.view },
193
+ );
194
+ }
195
+
196
+ const rawDocs = hits.map(hit => hit.document);
197
+ const docs = locale ? preferLocaleDocs(rawDocs, locale) : rawDocs;
198
+
199
+ return {
200
+ source: "multi_search",
201
+ queryId: "",
202
+ found: response.found ?? 0,
203
+ page: response.page ?? page,
204
+ perPage,
205
+ locale,
206
+ docs,
207
+ facets: (response.facet_counts ?? []).map(fc => ({
208
+ field: fc.field_name,
209
+ counts: (fc.counts ?? []).map(c => ({ value: c.value, count: c.count })),
210
+ })),
211
+ actions: [],
212
+ ignoredFilters: [...droppedFilterFields],
213
+ ignoredSort: droppedSort,
214
+ withheld: allHits.length - docs.length,
215
+ };
216
+ }
@@ -115,6 +115,11 @@ export async function getShopSettings(event?: H3Event): Promise<ShopSettings> {
115
115
  ["off", "on_registration", "required_for_login"] as const,
116
116
  "off",
117
117
  ),
118
+ identifiers: {
119
+ email: boolSetting(s.customers, "login_identifier_email", true),
120
+ username: boolSetting(s.customers, "login_identifier_username", false),
121
+ customerNumber: boolSetting(s.customers, "login_identifier_customer_number", false),
122
+ },
118
123
  },
119
124
  account: {
120
125
  singleDefaultAddressPerType: boolSetting(s.customers, "single_default_address_per_type", true),