@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,28 +1,19 @@
|
|
|
1
1
|
import type { ProductList } from "../../../app/interfaces/product-list";
|
|
2
|
-
import type { SearchFacet } from "../../../app/interfaces/search-facets";
|
|
3
|
-
import type { Locale } from "../../utils/locale";
|
|
2
|
+
import type { PriceRange, SearchFacet } from "../../../app/interfaces/search-facets";
|
|
4
3
|
|
|
5
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
buildLiveListingFilters,
|
|
6
|
+
liveListingFacets,
|
|
7
|
+
liveListingPriceFilter,
|
|
8
|
+
} from "../../utils/liveListingSearch";
|
|
6
9
|
import { FACET_FIELDS, PRODUCTS_COLLECTION } from "../../utils/productsSchema";
|
|
10
|
+
import { searchRedirect } from "../../utils/searchClient";
|
|
7
11
|
|
|
8
12
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*/
|
|
14
|
-
function isMissingFacetFieldError(err: unknown): boolean {
|
|
15
|
-
if (!err) return false;
|
|
16
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
17
|
-
return /Could not find a facet field named/i.test(msg);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Same shape, for sorting: a collection provisioned before `name` was declared
|
|
22
|
-
* `sort: true` answers 404 "Could not find a field named `name` in the schema
|
|
23
|
-
* for sorting." Sorting is a nicety; the listing is not. Retry unsorted rather
|
|
24
|
-
* than fail the page, and let it start working by itself once the tenant's
|
|
25
|
-
* collection carries the field.
|
|
13
|
+
* Same shape as the sort fallback the live path used to make: a collection
|
|
14
|
+
* provisioned before `name` was declared `sort: true` answers 404 "Could not
|
|
15
|
+
* find a field named `name` in the schema for sorting." Sorting is a nicety;
|
|
16
|
+
* the listing is not. Retry unsorted rather than fail the page.
|
|
26
17
|
*/
|
|
27
18
|
function isMissingSortFieldError(err: unknown): boolean {
|
|
28
19
|
if (!err) return false;
|
|
@@ -30,55 +21,6 @@ function isMissingSortFieldError(err: unknown): boolean {
|
|
|
30
21
|
return /Could not find a field named .* in the schema for sorting/i.test(msg);
|
|
31
22
|
}
|
|
32
23
|
|
|
33
|
-
/**
|
|
34
|
-
* Typesense's answer when a `filter_by` names a field the collection does not
|
|
35
|
-
* declare: `Could not find a filter field named \`x\` in the schema.`
|
|
36
|
-
*
|
|
37
|
-
* The same shape as the facet and sort checks below it, and the same reason —
|
|
38
|
-
* the SDK surfaces no typed error — but a filter is the one of the three that
|
|
39
|
-
* is not a nicety. `enabled:=true` is pinned on every live query, so a
|
|
40
|
-
* collection that has the field stored but not indexed answered nothing at
|
|
41
|
-
* all: every listing and every search on the storefront read "0 results" with
|
|
42
|
-
* a failure banner, in every language, while the catalogue was intact.
|
|
43
|
-
*/
|
|
44
|
-
function missingFilterField(err: unknown): string | null {
|
|
45
|
-
if (!err) return null;
|
|
46
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
47
|
-
return /Could not find a filter field named/i.test(msg)
|
|
48
|
-
? (msg.match(/filter field named `([^`]+)`/i)?.[1] ?? "")
|
|
49
|
-
: null;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* The live category codes behind the storefront's subcategory filter values.
|
|
54
|
-
*
|
|
55
|
-
* `subcategorySlug` carries a code already; the user-facing `subcategory` facet
|
|
56
|
-
* is LABEL-valued (it mirrors the mock schema, where the slug lives in its own
|
|
57
|
-
* field), so a value picked in the rail arrives as a label. Both are accepted —
|
|
58
|
-
* an unmatched value is passed through as a code so a hand-edited URL yields an
|
|
59
|
-
* honest zero-hit filter rather than silently dropping the constraint.
|
|
60
|
-
*/
|
|
61
|
-
async function resolveSubcategoryCodes(
|
|
62
|
-
values: string[],
|
|
63
|
-
parentCode: string,
|
|
64
|
-
locale: Locale,
|
|
65
|
-
): Promise<string[]> {
|
|
66
|
-
if (!parentCode) {
|
|
67
|
-
return values;
|
|
68
|
-
}
|
|
69
|
-
const { labels } = await liveSubcategoryIndex(parentCode, locale);
|
|
70
|
-
return values.map((value) => {
|
|
71
|
-
if (labels.has(value)) {
|
|
72
|
-
return value;
|
|
73
|
-
}
|
|
74
|
-
const match = [...labels.entries()].find(([, label]) => label === value);
|
|
75
|
-
return match?.[0] ?? value;
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Typesense's own ceiling for `max_facet_values`. */
|
|
80
|
-
const LIVE_MAX_FACET_VALUES = 250;
|
|
81
|
-
|
|
82
24
|
type SortOption = "relevance" | "price_asc" | "price_desc" | "name_asc" | "name_desc" | "sku_asc" | "sku_desc";
|
|
83
25
|
|
|
84
26
|
const SORT_MAP: Record<SortOption, string> = {
|
|
@@ -94,13 +36,28 @@ const SORT_MAP: Record<SortOption, string> = {
|
|
|
94
36
|
interface SearchBody {
|
|
95
37
|
q: string;
|
|
96
38
|
filters?: Record<string, string[]>;
|
|
97
|
-
priceRange?:
|
|
39
|
+
priceRange?: PriceRange;
|
|
98
40
|
sort?: SortOption;
|
|
99
41
|
page?: number;
|
|
100
42
|
perPage?: number;
|
|
101
43
|
}
|
|
102
44
|
|
|
103
|
-
|
|
45
|
+
interface SearchAnswer {
|
|
46
|
+
products: ProductList[];
|
|
47
|
+
facets: SearchFacet[];
|
|
48
|
+
found: number;
|
|
49
|
+
page: number;
|
|
50
|
+
perPage: number;
|
|
51
|
+
/** Whether a price range filters anything on this index. */
|
|
52
|
+
priceFilter: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Where curation sends this query instead of showing results (a site path
|
|
55
|
+
* or an http(s) URL). Only the search page follows it.
|
|
56
|
+
*/
|
|
57
|
+
redirect?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export default defineEventHandler(async (event): Promise<SearchAnswer | null> => {
|
|
104
61
|
const {
|
|
105
62
|
q,
|
|
106
63
|
filters,
|
|
@@ -114,258 +71,43 @@ export default defineEventHandler(async (event) => {
|
|
|
114
71
|
return null;
|
|
115
72
|
}
|
|
116
73
|
|
|
117
|
-
// Live mode
|
|
118
|
-
//
|
|
119
|
-
//
|
|
74
|
+
// Live mode asks the search service by VIEW: a category page (a pinned
|
|
75
|
+
// category) is the `category` view, everything else the `search` view.
|
|
76
|
+
// Which fields match, the facets, and the locale/enabled/channel pins are
|
|
77
|
+
// the service's (searchClient.ts); this route only translates the
|
|
78
|
+
// storefront's filter names and maps the facets back.
|
|
120
79
|
if (resolveProductServiceKey(event) === "api") {
|
|
121
80
|
const locale = resolveLocale(event);
|
|
122
|
-
const liveFilterParts = [`locale:=${tsFilterValue(locale)}`, "enabled:=true"];
|
|
123
|
-
|
|
124
|
-
// Per-tenant dynamic facets: the search-admin facet syncer mirrors
|
|
125
|
-
// every `is_filterable=true` attribute into the Typesense schema
|
|
126
|
-
// as `attrs.<code>`. We surface those codes here so the live
|
|
127
|
-
// branch can both forward `attrs.*` filter values AND ask
|
|
128
|
-
// Typesense to compute facet counts on them.
|
|
129
|
-
const attrMeta = await loadLiveAttributeMeta().catch(() => ({}));
|
|
130
|
-
const filterableCodes = Object.entries(attrMeta)
|
|
131
|
-
.filter(([, m]) => m.isFilterable && !m.hidden)
|
|
132
|
-
.map(([code]) => code);
|
|
133
|
-
|
|
134
|
-
// The category this request is pinned to, kept for the facet mapping
|
|
135
|
-
// below — the live index facets on `categories` (codes), the storefront
|
|
136
|
-
// asks for a `subcategory` facet of that category's children.
|
|
137
|
-
let pinnedCategoryCode = "";
|
|
138
|
-
|
|
139
|
-
if (filters) {
|
|
140
|
-
// The storefront filters with the demo-schema field names; the
|
|
141
|
-
// live collection (search.json) names them differently. Category
|
|
142
|
-
// slugs ARE the live category codes, but products carry their
|
|
143
|
-
// LEAF code only — a branch expands to its whole subtree.
|
|
144
|
-
// Unknown fields are dropped instead of 400ing the request.
|
|
145
|
-
//
|
|
146
|
-
// Category and subcategory are collected SEPARATELY: they used to
|
|
147
|
-
// share one array and were emitted as a single OR'd clause, which
|
|
148
|
-
// made a subcategory page return its parent's entire catalogue
|
|
149
|
-
// instead of narrowing it. The narrower of the two wins.
|
|
150
|
-
const categoryCodes: string[] = [];
|
|
151
|
-
const subcategoryValues: string[] = [];
|
|
152
|
-
|
|
153
|
-
for (const [field, values] of Object.entries(filters)) {
|
|
154
|
-
if (!values?.length) {
|
|
155
|
-
continue;
|
|
156
|
-
}
|
|
157
|
-
if (field === "categorySlug" || field === "categories") {
|
|
158
|
-
categoryCodes.push(...values);
|
|
159
|
-
}
|
|
160
|
-
else if (field === "subcategorySlug" || field === "subcategory") {
|
|
161
|
-
subcategoryValues.push(...values);
|
|
162
|
-
}
|
|
163
|
-
else if (field === "manufacturer" || field === "kind") {
|
|
164
|
-
liveFilterParts.push(`${field}:=[${values.map(v => tsFilterValue(v)).join(",")}]`);
|
|
165
|
-
}
|
|
166
|
-
else if (field === "available" || field === "enabled") {
|
|
167
|
-
// enabled:=true is already pinned; an explicit "false" can
|
|
168
|
-
// never match — keep the pinned filter authoritative.
|
|
169
|
-
}
|
|
170
|
-
else if (field.startsWith("attrs.") && filterableCodes.includes(field.slice(6))) {
|
|
171
|
-
// Tenant-defined attribute filter. Only honour codes the
|
|
172
|
-
// attribute meta knows about — protects against URL
|
|
173
|
-
// tampering that could spam Typesense with bogus filter
|
|
174
|
-
// fields (Typesense 400s on unknown filter_by paths).
|
|
175
|
-
liveFilterParts.push(`${field}:=[${values.map(v => tsFilterValue(v)).join(",")}]`);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
pinnedCategoryCode = categoryCodes[0] ?? "";
|
|
180
|
-
|
|
181
|
-
// Resolved after the loop, not inside it: `filters` merges the
|
|
182
|
-
// user's selection over the page's fixed filters, so `subcategory`
|
|
183
|
-
// can be enumerated before `categorySlug` and the parent would not
|
|
184
|
-
// be known yet.
|
|
185
|
-
const subcategoryCodes = subcategoryValues.length
|
|
186
|
-
? await resolveSubcategoryCodes(subcategoryValues, pinnedCategoryCode, locale)
|
|
187
|
-
: [];
|
|
188
|
-
|
|
189
|
-
// Deepest wins: a subcategory replaces its parent's clause rather
|
|
190
|
-
// than being OR'd next to it.
|
|
191
|
-
const branchCodes = subcategoryCodes.length ? subcategoryCodes : categoryCodes;
|
|
192
|
-
if (branchCodes.length) {
|
|
193
|
-
const leafCodes = await liveCategorySubtreeCodes(branchCodes);
|
|
194
|
-
liveFilterParts.push(`categories:=[${leafCodes.map(tsFilterValue).join(",")}]`);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
// Spine facets + tenant-defined dynamic facets. category_labels is
|
|
199
|
-
// locale-templated and not a facet in the deployed schema —
|
|
200
|
-
// `categories` (codes) is the stable facet.
|
|
201
|
-
const spineFacetBy = "manufacturer,kind,categories";
|
|
202
|
-
const dynamicFacets = filterableCodes.map(c => `attrs.${c}`);
|
|
203
|
-
const liveFacetBy = [spineFacetBy, ...dynamicFacets].filter(Boolean).join(",");
|
|
204
|
-
|
|
205
|
-
// Schema-drift fallback: the attribute meta is cached per-tenant
|
|
206
|
-
// for 5min. When an operator flips is_filterable off in Cockpit,
|
|
207
|
-
// search-admin drops the matching `attrs.<code>` field from
|
|
208
|
-
// Typesense within a second (via the NATS push path), but our
|
|
209
|
-
// cache lags. Typesense then 4xx's with "Could not find a facet
|
|
210
|
-
// field named …", which would otherwise bubble up as a 503 here.
|
|
211
|
-
// Retry once without dynamic facets so the storefront keeps
|
|
212
|
-
// rendering with spine facets only; the meta cache repairs on
|
|
213
|
-
// its next refresh.
|
|
214
|
-
// The sort the visitor picked was computed and then never sent: the
|
|
215
|
-
// dropdown has been inert in live mode. Only the sorts the live
|
|
216
|
-
// collection can actually carry are passed on — it projects no `price`
|
|
217
|
-
// field, so a price sort would 404; "relevance" is the absence of
|
|
218
|
-
// sort_by, which is what Typesense does by itself.
|
|
219
|
-
//
|
|
220
|
-
// `name` and `sku` are STRINGS, and Typesense only sorts a string field
|
|
221
|
-
// that was declared `sort: true` at schema time. A catalogue whose
|
|
222
|
-
// search.json predates that is handled below: the request is retried
|
|
223
|
-
// unsorted rather than failing the listing.
|
|
224
|
-
const LIVE_SORTABLE: readonly SortOption[] = ["name_asc", "name_desc", "sku_asc", "sku_desc"];
|
|
225
|
-
const liveSortBy = LIVE_SORTABLE.includes(sort)
|
|
226
|
-
? SORT_MAP[sort]
|
|
227
|
-
: undefined;
|
|
228
|
-
|
|
229
|
-
// Filter clauses the collection turned out not to carry, dropped for
|
|
230
|
-
// the retry. Read after the search so the mapper can enforce by hand
|
|
231
|
-
// what the index could not enforce for us.
|
|
232
|
-
const droppedFilterFields = new Set<string>();
|
|
233
|
-
|
|
234
|
-
const runSearch = async (facetBy: string, sortBy?: string) => searchLiveProducts({
|
|
235
|
-
q,
|
|
236
|
-
queryBy: "name,sku,description,manufacturer",
|
|
237
|
-
filterBy: liveFilterParts
|
|
238
|
-
.filter(part => ![...droppedFilterFields].some(f => part.startsWith(`${f}:`)))
|
|
239
|
-
.join(" && "),
|
|
240
|
-
facetBy,
|
|
241
|
-
// Typesense answers with 10 values per facet when this is unset,
|
|
242
|
-
// which silently truncates the rail AND undercounts the subcategory
|
|
243
|
-
// roll-up below (products are indexed at the leaf, so one child can
|
|
244
|
-
// span many facet values). 250 is Typesense's own ceiling.
|
|
245
|
-
maxFacetValues: LIVE_MAX_FACET_VALUES,
|
|
246
|
-
...(sortBy ? { sortBy } : {}),
|
|
247
|
-
page,
|
|
248
|
-
perPage,
|
|
249
|
-
});
|
|
250
|
-
|
|
251
|
-
// Three independent degradations, each retried once: a dynamic facet
|
|
252
|
-
// the tenant's schema no longer has, a sort field it never had, and a
|
|
253
|
-
// filter field it does not declare.
|
|
254
|
-
//
|
|
255
|
-
// The filter one is the newcomer and the one that hurt: a pinned
|
|
256
|
-
// clause naming an undeclared field fails the whole query, so the
|
|
257
|
-
// storefront showed nothing at all rather than showing too much. It is
|
|
258
|
-
// retried without that clause — and what the clause promised is then
|
|
259
|
-
// enforced on the documents instead, below, so dropping it narrows
|
|
260
|
-
// what the page can say about totals but never widens what it shows.
|
|
261
|
-
const searchWithFallbacks = async (sortBy?: string) => {
|
|
262
|
-
for (let attempt = 0; attempt < 4; attempt++) {
|
|
263
|
-
try {
|
|
264
|
-
return await runSearch(liveFacetBy, sortBy);
|
|
265
|
-
}
|
|
266
|
-
catch (err) {
|
|
267
|
-
const missing = missingFilterField(err);
|
|
268
|
-
if (missing && !droppedFilterFields.has(missing)) {
|
|
269
|
-
getLogService().warn(
|
|
270
|
-
`search: the collection does not declare the filter field \`${missing}\`, retrying without that clause`,
|
|
271
|
-
toErrorContext(err),
|
|
272
|
-
);
|
|
273
|
-
droppedFilterFields.add(missing);
|
|
274
|
-
|
|
275
|
-
continue;
|
|
276
|
-
}
|
|
277
|
-
if (dynamicFacets.length > 0 && isMissingFacetFieldError(err)) {
|
|
278
|
-
getLogService().warn(
|
|
279
|
-
"search: dynamic facet missing in Typesense, retrying with spine facets only",
|
|
280
|
-
toErrorContext(err),
|
|
281
|
-
);
|
|
282
|
-
return await runSearch(spineFacetBy, sortBy);
|
|
283
|
-
}
|
|
284
|
-
throw err;
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
// Every clause the collection rejected has been dropped once; a
|
|
288
|
-
// failure now is a real one.
|
|
289
|
-
return await runSearch(liveFacetBy, sortBy);
|
|
290
|
-
};
|
|
291
|
-
|
|
292
81
|
try {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
else {
|
|
306
|
-
throw err;
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
// A clause the collection could not carry is enforced here instead.
|
|
311
|
-
// `enabled` is the one that matters: Typesense STORES a field it
|
|
312
|
-
// does not index and hands it back on every hit, so the value is
|
|
313
|
-
// there to be read even when it could not be filtered on. Dropping
|
|
314
|
-
// the clause therefore costs an accurate `found` and accurate facet
|
|
315
|
-
// counts — never a product on the page that should not be there.
|
|
316
|
-
const hits = droppedFilterFields.has("enabled")
|
|
317
|
-
? (results.hits ?? []).filter(hit => hit.document?.enabled !== false)
|
|
318
|
-
: (results.hits ?? []);
|
|
319
|
-
const withheld = (results.hits ?? []).length - hits.length;
|
|
320
|
-
if (withheld > 0) {
|
|
321
|
-
getLogService().warn(
|
|
322
|
-
`search: withheld ${withheld} disabled product(s) the index could not filter out`,
|
|
323
|
-
{ collection: PRODUCTS_COLLECTION },
|
|
324
|
-
);
|
|
325
|
-
}
|
|
82
|
+
const request = await buildLiveListingFilters(filters, priceRange, locale);
|
|
83
|
+
const view = request.pinnedCategoryCode ? "category" : "search";
|
|
84
|
+
const result = await searchClient.search({
|
|
85
|
+
view,
|
|
86
|
+
collection: PRODUCTS_COLLECTION,
|
|
87
|
+
q,
|
|
88
|
+
filters: request.filters,
|
|
89
|
+
sort,
|
|
90
|
+
page,
|
|
91
|
+
perPage,
|
|
92
|
+
locale,
|
|
93
|
+
});
|
|
326
94
|
|
|
327
95
|
// Catalog shell only — offers (price + availability) hydrate
|
|
328
96
|
// separately via POST /api/offers, never blocking search.
|
|
329
|
-
const products: ProductList[] =
|
|
330
|
-
const
|
|
331
|
-
fieldName: fc.field_name,
|
|
332
|
-
counts: (fc.counts ?? []).map(c => ({ value: c.value, count: c.count })),
|
|
333
|
-
}));
|
|
334
|
-
|
|
335
|
-
// The category page asks for a `subcategory` facet; the live index
|
|
336
|
-
// only knows `categories`. Without this bridge the field names never
|
|
337
|
-
// meet and the drill-down is invisible in live mode. Derived rather
|
|
338
|
-
// than renamed — the search page still consumes `categories`.
|
|
339
|
-
if (pinnedCategoryCode) {
|
|
340
|
-
const { labels, branchOf } = await liveSubcategoryIndex(pinnedCategoryCode, locale);
|
|
341
|
-
// Counts arrive on the LEAF codes, so they are summed back up
|
|
342
|
-
// onto the direct child each leaf belongs to.
|
|
343
|
-
const byBranch = rollUpSubcategoryCounts(
|
|
344
|
-
facets.find(f => f.fieldName === "categories")?.counts ?? [],
|
|
345
|
-
branchOf,
|
|
346
|
-
);
|
|
347
|
-
if (byBranch.size) {
|
|
348
|
-
facets.push({
|
|
349
|
-
fieldName: "subcategory",
|
|
350
|
-
counts: [...byBranch].map(([code, count]) => ({
|
|
351
|
-
value: labels.get(code) ?? code,
|
|
352
|
-
count,
|
|
353
|
-
})),
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
}
|
|
97
|
+
const products: ProductList[] = result.docs.map(doc => mapLiveDocToProduct(doc));
|
|
98
|
+
const redirect = view === "search" ? searchRedirect(result) : undefined;
|
|
357
99
|
|
|
358
100
|
return {
|
|
359
101
|
products,
|
|
360
|
-
facets,
|
|
361
|
-
// Reduced by
|
|
362
|
-
//
|
|
363
|
-
//
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
found: Math.max(0, (results.found ?? 0) - withheld),
|
|
367
|
-
page: results.page ?? page,
|
|
102
|
+
facets: await liveListingFacets(result, request.pinnedCategoryCode, locale),
|
|
103
|
+
// Reduced by the hits dropped on this page (locale duplicates,
|
|
104
|
+
// disabled products the index could not filter), so the count and
|
|
105
|
+
// the rows agree on the page the visitor is looking at.
|
|
106
|
+
found: Math.max(0, result.found - result.withheld),
|
|
107
|
+
page: result.page,
|
|
368
108
|
perPage,
|
|
109
|
+
priceFilter: liveListingPriceFilter(result, request.priceRequested),
|
|
110
|
+
...(redirect ? { redirect } : {}),
|
|
369
111
|
};
|
|
370
112
|
}
|
|
371
113
|
catch (err) {
|
|
@@ -413,10 +155,10 @@ export default defineEventHandler(async (event) => {
|
|
|
413
155
|
});
|
|
414
156
|
|
|
415
157
|
try {
|
|
416
|
-
//
|
|
417
|
-
// `
|
|
418
|
-
//
|
|
419
|
-
//
|
|
158
|
+
// A collection provisioned before `name`/`sku` were declared
|
|
159
|
+
// `sort: true` answers 404 for those sorts. Sorting is a nicety, the
|
|
160
|
+
// listing is not — retry unsorted rather than fail the page, and let it
|
|
161
|
+
// start working once the tenant re-seeds.
|
|
420
162
|
let results;
|
|
421
163
|
try {
|
|
422
164
|
results = await runSearch(sortBy);
|
|
@@ -463,6 +205,8 @@ export default defineEventHandler(async (event) => {
|
|
|
463
205
|
found: results.found,
|
|
464
206
|
page: results.page ?? page,
|
|
465
207
|
perPage,
|
|
208
|
+
// The demo index stores a price per product.
|
|
209
|
+
priceFilter: true,
|
|
466
210
|
};
|
|
467
211
|
}
|
|
468
212
|
catch (err) {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const SUGGESTION_COUNT = 6;
|
|
2
|
+
|
|
1
3
|
export default defineEventHandler(async (event) => {
|
|
2
4
|
const { q } = await readBody<{ q: string }>(event);
|
|
3
5
|
|
|
@@ -5,21 +7,24 @@ export default defineEventHandler(async (event) => {
|
|
|
5
7
|
return { suggestions: [] };
|
|
6
8
|
}
|
|
7
9
|
|
|
8
|
-
// Live mode
|
|
9
|
-
//
|
|
10
|
+
// Live mode asks the search service's `suggest` view (searchClient.ts);
|
|
11
|
+
// the local docker index stays the mock implementation.
|
|
10
12
|
if (resolveProductServiceKey(event) === "api") {
|
|
11
13
|
const locale = resolveLocale(event);
|
|
12
14
|
try {
|
|
13
|
-
|
|
15
|
+
// Twice the suggestions: on the deprecated multi_search fallback a
|
|
16
|
+
// product still indexed under both `de` and `de-DE` comes back twice
|
|
17
|
+
// and is folded into one, which would leave the list short.
|
|
18
|
+
const result = await searchClient.search({
|
|
19
|
+
view: "suggest",
|
|
14
20
|
q,
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
perPage: 6,
|
|
21
|
+
perPage: SUGGESTION_COUNT * 2,
|
|
22
|
+
locale,
|
|
18
23
|
});
|
|
24
|
+
const docs = result.docs.slice(0, SUGGESTION_COUNT);
|
|
19
25
|
|
|
20
26
|
return {
|
|
21
|
-
suggestions:
|
|
22
|
-
const doc = hit.document;
|
|
27
|
+
suggestions: docs.map((doc) => {
|
|
23
28
|
return {
|
|
24
29
|
id: doc.entity_id,
|
|
25
30
|
name: doc.name,
|
|
@@ -43,7 +48,7 @@ export default defineEventHandler(async (event) => {
|
|
|
43
48
|
const results = await ts.collections("products").documents().search({
|
|
44
49
|
q,
|
|
45
50
|
query_by: "name,sku",
|
|
46
|
-
per_page:
|
|
51
|
+
per_page: SUGGESTION_COUNT,
|
|
47
52
|
prefix: true,
|
|
48
53
|
num_typos: 2,
|
|
49
54
|
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
import { PRODUCTS_COLLECTION as COLLECTION_NAME } from "../../utils/productsSchema";
|
|
2
2
|
|
|
3
|
+
/** GET /api/typesense/drop — dev server only. Drops the local `products` collection. */
|
|
3
4
|
export default defineEventHandler(async () => {
|
|
4
5
|
const ts = useTypesense();
|
|
5
6
|
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import productsData from "../../data/product-list.json";
|
|
2
|
+
import { PRODUCTS_COLLECTION, productsSchema } from "../../utils/productsSchema";
|
|
3
|
+
import type { SeedEntry } from "./seedDocuments";
|
|
4
|
+
import { buildSeedDocuments } from "./seedDocuments";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* GET /api/typesense/seed — dev server only (registered in the layer's
|
|
8
|
+
* nuxt.config). Recreates the local `products` collection from the demo
|
|
9
|
+
* catalogue; `?count=` inflates it for load demos.
|
|
10
|
+
*/
|
|
11
|
+
export default defineEventHandler(async (event) => {
|
|
12
|
+
const query = getQuery(event);
|
|
13
|
+
const requestedCount = parseInt(String(query.count ?? "0"), 10);
|
|
14
|
+
|
|
15
|
+
const ts = useTypesense();
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
const collections = await ts.collections().retrieve();
|
|
19
|
+
const exists = collections.some(c => c.name === PRODUCTS_COLLECTION);
|
|
20
|
+
if (exists) {
|
|
21
|
+
await ts.collections(PRODUCTS_COLLECTION).delete();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
await ts.collections().create(productsSchema);
|
|
25
|
+
}
|
|
26
|
+
catch (err) {
|
|
27
|
+
getLogService().error("Typesense error: seed collection setup", toErrorContext(err));
|
|
28
|
+
throw createError({ statusCode: 503, message: "Search service unavailable" });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const documents = buildSeedDocuments(productsData as SeedEntry[], requestedCount);
|
|
32
|
+
|
|
33
|
+
let result: { success: boolean; error?: string; document?: unknown }[] = [];
|
|
34
|
+
|
|
35
|
+
try {
|
|
36
|
+
result = await ts.collections(PRODUCTS_COLLECTION).documents().import(
|
|
37
|
+
documents,
|
|
38
|
+
{ action: "upsert" },
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
catch (e: unknown) {
|
|
42
|
+
if (e && typeof e === "object" && "importResults" in e) {
|
|
43
|
+
result = (e as { importResults: typeof result }).importResults;
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
getLogService().error("Typesense error: seed import", toErrorContext(e));
|
|
47
|
+
throw e;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const failed = result.filter(r => !r.success);
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
total: documents.length,
|
|
55
|
+
indexed: documents.length - failed.length,
|
|
56
|
+
failed: failed.length,
|
|
57
|
+
errors: failed,
|
|
58
|
+
};
|
|
59
|
+
});
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps the bundled demo catalogue (server/data/product-list.json) onto the
|
|
3
|
+
* local `products` index (server/utils/productsSchema.ts).
|
|
4
|
+
*
|
|
5
|
+
* Shared by the dev-only `GET /api/typesense/seed` route and
|
|
6
|
+
* `scripts/seed-typesense.mjs`, which seeds the index next to a production
|
|
7
|
+
* build (CI). Kept free of runtime imports so plain Node can load it.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const MAX_SEED_COUNT = 5000;
|
|
11
|
+
|
|
12
|
+
export interface SeedEntry {
|
|
13
|
+
product: { id: number; name: string; sku: string; manufacturer: string; available: boolean }[];
|
|
14
|
+
prices: Record<string, number>[];
|
|
15
|
+
descriptions: { type: string; content: string }[];
|
|
16
|
+
categories: { type: string; name: string }[];
|
|
17
|
+
images: { priority: number; url: string }[];
|
|
18
|
+
tax: { rate: number };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface SeedDocument {
|
|
22
|
+
id: string;
|
|
23
|
+
name: string;
|
|
24
|
+
sku: string;
|
|
25
|
+
manufacturer: string;
|
|
26
|
+
available: boolean;
|
|
27
|
+
price: number;
|
|
28
|
+
description?: string;
|
|
29
|
+
category: string;
|
|
30
|
+
categorySlug: string;
|
|
31
|
+
subcategory?: string;
|
|
32
|
+
subcategorySlug?: string;
|
|
33
|
+
slug: string;
|
|
34
|
+
image?: string;
|
|
35
|
+
taxRate: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function mapEntry(entry: SeedEntry, idOffset: number): SeedDocument {
|
|
39
|
+
const product = entry.product[0]!;
|
|
40
|
+
// Catalog list price only — a sort/filter key. Price tiers + stock are the
|
|
41
|
+
// Offer domain (MockOfferService), never indexed.
|
|
42
|
+
const prices = entry.prices[0] ?? {};
|
|
43
|
+
const longDescription = entry.descriptions.find(d => d.type === "long");
|
|
44
|
+
const mainCategory = entry.categories.find(c => c.type === "main");
|
|
45
|
+
const subcategory = entry.categories.find(c => c.type === "subcategory");
|
|
46
|
+
const slugCategory = entry.categories.find(c => c.type === "slug");
|
|
47
|
+
const mainImage = entry.images.find(i => i.priority === 1);
|
|
48
|
+
const basePrice = prices["1"] ?? Object.values(prices)[0] ?? 0;
|
|
49
|
+
|
|
50
|
+
const slugPath = slugCategory?.name ?? "";
|
|
51
|
+
const slugSegments = slugPath.split("/").filter(Boolean);
|
|
52
|
+
const categorySlug = slugSegments[0] ?? "";
|
|
53
|
+
const candidateSubcategory = slugSegments[1];
|
|
54
|
+
const subcategorySlug = candidateSubcategory
|
|
55
|
+
&& candidateSubcategory !== "product"
|
|
56
|
+
&& candidateSubcategory !== "products"
|
|
57
|
+
? candidateSubcategory
|
|
58
|
+
: undefined;
|
|
59
|
+
|
|
60
|
+
const id = idOffset === 0 ? product.id : product.id + idOffset * 100_000;
|
|
61
|
+
const suffix = idOffset === 0 ? "" : ` #${idOffset}`;
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
id: String(id),
|
|
65
|
+
name: `${product.name}${suffix}`,
|
|
66
|
+
sku: idOffset === 0 ? product.sku : `${product.sku}-${idOffset}`,
|
|
67
|
+
manufacturer: product.manufacturer,
|
|
68
|
+
available: product.available,
|
|
69
|
+
price: basePrice,
|
|
70
|
+
description: longDescription?.content,
|
|
71
|
+
category: mainCategory?.name ?? "",
|
|
72
|
+
categorySlug,
|
|
73
|
+
subcategory: subcategory?.name,
|
|
74
|
+
...(subcategorySlug ? { subcategorySlug } : {}),
|
|
75
|
+
slug: idOffset === 0 ? slugPath : `${slugPath}-${idOffset}`,
|
|
76
|
+
image: mainImage?.url,
|
|
77
|
+
taxRate: entry.tax.rate,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The documents to index. `requestedCount` > 0 inflates the catalogue (copies
|
|
83
|
+
* with offset ids and suffixed names) for load demos, capped at
|
|
84
|
+
* MAX_SEED_COUNT; anything else indexes the catalogue once.
|
|
85
|
+
*/
|
|
86
|
+
export function buildSeedDocuments(entries: SeedEntry[], requestedCount = 0): SeedDocument[] {
|
|
87
|
+
const targetCount = requestedCount > 0
|
|
88
|
+
? Math.min(requestedCount, MAX_SEED_COUNT)
|
|
89
|
+
: entries.length;
|
|
90
|
+
|
|
91
|
+
const documents: SeedDocument[] = [];
|
|
92
|
+
let idOffset = 0;
|
|
93
|
+
|
|
94
|
+
while (documents.length < targetCount && entries.length > 0) {
|
|
95
|
+
for (const entry of entries) {
|
|
96
|
+
if (documents.length >= targetCount) {
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
documents.push(mapEntry(entry, idOffset));
|
|
100
|
+
}
|
|
101
|
+
idOffset++;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return documents;
|
|
105
|
+
}
|
|
@@ -32,4 +32,12 @@ export interface IProductService {
|
|
|
32
32
|
* renders no associations section.
|
|
33
33
|
*/
|
|
34
34
|
getProductAssociations(id: string, locale?: Locale): Promise<ProductAssociations | null>;
|
|
35
|
+
/**
|
|
36
|
+
* The storefront languages (of `languages`) this product has a page in. A
|
|
37
|
+
* catalogue that hides untranslated products (`search_untranslated=hide`)
|
|
38
|
+
* has none in a language the product is not translated into. Optional: a
|
|
39
|
+
* service without it has the product in every language, which is what the
|
|
40
|
+
* storefront assumes when it is missing.
|
|
41
|
+
*/
|
|
42
|
+
getProductLanguages?(id: string, languages: readonly string[]): Promise<string[]>;
|
|
35
43
|
}
|