@revenexx/cover 0.12.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.
- package/app/components/cart/recommend/CartCrossSell.vue +2 -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/useSearchListing.ts +16 -0
- package/app/shared/locale.ts +114 -0
- 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/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/routes/punchout/start.get.ts +40 -3
- package/server/services/ApiBrandService.ts +28 -42
- package/server/services/ApiProductService.ts +10 -11
- package/server/utils/buyerIdentity.ts +11 -0
- package/server/utils/liveCatalog.ts +132 -49
- 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
|
@@ -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
|
+
}
|
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
import productsData from "../../data/product-list.json";
|
|
2
|
-
import { PRODUCTS_COLLECTION, productsSchema } from "../../utils/productsSchema";
|
|
3
|
-
|
|
4
|
-
const MAX_COUNT = 5000;
|
|
5
|
-
|
|
6
|
-
function mapEntry(entry: (typeof productsData)[number], idOffset: number) {
|
|
7
|
-
const product = entry.product[0];
|
|
8
|
-
// Catalog list price only — a sort/filter key. Price tiers + stock are the
|
|
9
|
-
// Offer domain (MockOfferService), never indexed.
|
|
10
|
-
const prices = entry.prices[0] as Record<string, number>;
|
|
11
|
-
const longDescription = entry.descriptions.find(d => d.type === "long");
|
|
12
|
-
const mainCategory = entry.categories.find(c => c.type === "main");
|
|
13
|
-
const subcategory = entry.categories.find(c => c.type === "subcategory");
|
|
14
|
-
const slugCategory = entry.categories.find(c => c.type === "slug");
|
|
15
|
-
const mainImage = entry.images.find(i => i.priority === 1);
|
|
16
|
-
const basePrice = prices["1"] ?? Object.values(prices)[0] ?? 0;
|
|
17
|
-
|
|
18
|
-
const slugPath = slugCategory?.name ?? "";
|
|
19
|
-
const slugSegments = slugPath.split("/").filter(Boolean);
|
|
20
|
-
const categorySlug = slugSegments[0] ?? "";
|
|
21
|
-
const candidateSubcategory = slugSegments[1];
|
|
22
|
-
const subcategorySlug = candidateSubcategory
|
|
23
|
-
&& candidateSubcategory !== "product"
|
|
24
|
-
&& candidateSubcategory !== "products"
|
|
25
|
-
? candidateSubcategory
|
|
26
|
-
: undefined;
|
|
27
|
-
|
|
28
|
-
const id = idOffset === 0 ? product.id : product.id + idOffset * 100_000;
|
|
29
|
-
const suffix = idOffset === 0 ? "" : ` #${idOffset}`;
|
|
30
|
-
|
|
31
|
-
return {
|
|
32
|
-
id: String(id),
|
|
33
|
-
name: `${product.name}${suffix}`,
|
|
34
|
-
sku: idOffset === 0 ? product.sku : `${product.sku}-${idOffset}`,
|
|
35
|
-
manufacturer: product.manufacturer,
|
|
36
|
-
available: product.available,
|
|
37
|
-
price: basePrice,
|
|
38
|
-
description: longDescription?.content,
|
|
39
|
-
category: mainCategory?.name ?? "",
|
|
40
|
-
categorySlug,
|
|
41
|
-
subcategory: subcategory?.name,
|
|
42
|
-
...(subcategorySlug ? { subcategorySlug } : {}),
|
|
43
|
-
slug: idOffset === 0 ? slugPath : `${slugPath}-${idOffset}`,
|
|
44
|
-
image: mainImage?.url,
|
|
45
|
-
taxRate: entry.tax.rate,
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export default defineEventHandler(async (event) => {
|
|
50
|
-
const query = getQuery(event);
|
|
51
|
-
const requestedCount = parseInt(String(query.count ?? "0"), 10);
|
|
52
|
-
const targetCount = requestedCount > 0
|
|
53
|
-
? Math.min(requestedCount, MAX_COUNT)
|
|
54
|
-
: productsData.length;
|
|
55
|
-
|
|
56
|
-
const ts = useTypesense();
|
|
57
|
-
|
|
58
|
-
try {
|
|
59
|
-
const collections = await ts.collections().retrieve();
|
|
60
|
-
const exists = collections.some(c => c.name === PRODUCTS_COLLECTION);
|
|
61
|
-
if (exists) {
|
|
62
|
-
await ts.collections(PRODUCTS_COLLECTION).delete();
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
await ts.collections().create(productsSchema);
|
|
66
|
-
}
|
|
67
|
-
catch (err) {
|
|
68
|
-
getLogService().error("Typesense error: seed collection setup", toErrorContext(err));
|
|
69
|
-
throw createError({ statusCode: 503, message: "Search service unavailable" });
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const documents: ReturnType<typeof mapEntry>[] = [];
|
|
73
|
-
let idOffset = 0;
|
|
74
|
-
|
|
75
|
-
while (documents.length < targetCount) {
|
|
76
|
-
for (const entry of productsData) {
|
|
77
|
-
if (documents.length >= targetCount) {
|
|
78
|
-
break;
|
|
79
|
-
}
|
|
80
|
-
documents.push(mapEntry(entry, idOffset));
|
|
81
|
-
}
|
|
82
|
-
idOffset++;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
let result: { success: boolean; error?: string; document?: unknown }[] = [];
|
|
86
|
-
|
|
87
|
-
try {
|
|
88
|
-
result = await ts.collections(PRODUCTS_COLLECTION).documents().import(
|
|
89
|
-
documents,
|
|
90
|
-
{ action: "upsert" },
|
|
91
|
-
);
|
|
92
|
-
}
|
|
93
|
-
catch (e: unknown) {
|
|
94
|
-
if (e && typeof e === "object" && "importResults" in e) {
|
|
95
|
-
result = (e as { importResults: typeof result }).importResults;
|
|
96
|
-
}
|
|
97
|
-
else {
|
|
98
|
-
getLogService().error("Typesense error: seed import", toErrorContext(e));
|
|
99
|
-
throw e;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
const failed = result.filter(r => !r.success);
|
|
104
|
-
|
|
105
|
-
return {
|
|
106
|
-
total: documents.length,
|
|
107
|
-
indexed: documents.length - failed.length,
|
|
108
|
-
failed: failed.length,
|
|
109
|
-
errors: failed,
|
|
110
|
-
};
|
|
111
|
-
});
|