@endora-commerce/mod-catalog 0.103.1 → 0.105.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 (79) hide show
  1. package/dist/admin/index.d.ts.map +1 -1
  2. package/dist/admin/index.js +11 -0
  3. package/dist/admin/index.js.map +1 -1
  4. package/dist/admin/pages/AttributesManager.d.ts.map +1 -1
  5. package/dist/admin/pages/AttributesManager.js +8 -2
  6. package/dist/admin/pages/AttributesManager.js.map +1 -1
  7. package/dist/admin/pages/CategoriesTree.d.ts.map +1 -1
  8. package/dist/admin/pages/CategoriesTree.js +20 -2
  9. package/dist/admin/pages/CategoriesTree.js.map +1 -1
  10. package/dist/admin/pages/CategoryContentPage.d.ts +28 -0
  11. package/dist/admin/pages/CategoryContentPage.d.ts.map +1 -0
  12. package/dist/admin/pages/CategoryContentPage.js +159 -0
  13. package/dist/admin/pages/CategoryContentPage.js.map +1 -0
  14. package/dist/backend/commands/attribute-commands.d.ts.map +1 -1
  15. package/dist/backend/commands/attribute-commands.js +8 -0
  16. package/dist/backend/commands/attribute-commands.js.map +1 -1
  17. package/dist/backend/demo/reset.d.ts.map +1 -1
  18. package/dist/backend/demo/reset.js +8 -4
  19. package/dist/backend/demo/reset.js.map +1 -1
  20. package/dist/backend/entities/category.entity.d.ts +3 -1
  21. package/dist/backend/entities/category.entity.d.ts.map +1 -1
  22. package/dist/backend/entities/category.entity.js +14 -0
  23. package/dist/backend/entities/category.entity.js.map +1 -1
  24. package/dist/backend/entities/product-attribute.entity.d.ts +5 -3
  25. package/dist/backend/entities/product-attribute.entity.d.ts.map +1 -1
  26. package/dist/backend/entities/product-attribute.entity.js +8 -2
  27. package/dist/backend/entities/product-attribute.entity.js.map +1 -1
  28. package/dist/backend/index.d.ts.map +1 -1
  29. package/dist/backend/index.js +35 -1
  30. package/dist/backend/index.js.map +1 -1
  31. package/dist/backend/routes.admin.d.ts.map +1 -1
  32. package/dist/backend/routes.admin.js +19 -1
  33. package/dist/backend/routes.admin.js.map +1 -1
  34. package/dist/backend/routes.public.d.ts.map +1 -1
  35. package/dist/backend/routes.public.js +42 -7
  36. package/dist/backend/routes.public.js.map +1 -1
  37. package/dist/backend/services/asset-references.d.ts.map +1 -1
  38. package/dist/backend/services/asset-references.js +49 -5
  39. package/dist/backend/services/asset-references.js.map +1 -1
  40. package/dist/backend/services/bulk-operation.service.d.ts.map +1 -1
  41. package/dist/backend/services/bulk-operation.service.js +4 -1
  42. package/dist/backend/services/bulk-operation.service.js.map +1 -1
  43. package/dist/backend/services/catalog-admin.service.d.ts +6 -4
  44. package/dist/backend/services/catalog-admin.service.d.ts.map +1 -1
  45. package/dist/backend/services/catalog-admin.service.js +67 -12
  46. package/dist/backend/services/catalog-admin.service.js.map +1 -1
  47. package/dist/backend/services/catalog-attribute-read.service.d.ts.map +1 -1
  48. package/dist/backend/services/catalog-attribute-read.service.js +1 -0
  49. package/dist/backend/services/catalog-attribute-read.service.js.map +1 -1
  50. package/dist/backend/services/catalog-query.service.d.ts +28 -4
  51. package/dist/backend/services/catalog-query.service.d.ts.map +1 -1
  52. package/dist/backend/services/catalog-query.service.js +305 -30
  53. package/dist/backend/services/catalog-query.service.js.map +1 -1
  54. package/dist/backend/services/category-admin.service.d.ts +32 -1
  55. package/dist/backend/services/category-admin.service.d.ts.map +1 -1
  56. package/dist/backend/services/category-admin.service.js +54 -0
  57. package/dist/backend/services/category-admin.service.js.map +1 -1
  58. package/dist/manifest.d.ts +2 -2
  59. package/dist/manifest.d.ts.map +1 -1
  60. package/dist/manifest.js +20 -4
  61. package/dist/manifest.js.map +1 -1
  62. package/dist/migrations/20261008T080839_catalog_product_attribute_is_price_rule.d.ts +22 -0
  63. package/dist/migrations/20261008T080839_catalog_product_attribute_is_price_rule.d.ts.map +1 -0
  64. package/dist/migrations/20261008T080839_catalog_product_attribute_is_price_rule.js +29 -0
  65. package/dist/migrations/20261008T080839_catalog_product_attribute_is_price_rule.js.map +1 -0
  66. package/dist/migrations/20261008T092714_catalog_category_content.d.ts +21 -0
  67. package/dist/migrations/20261008T092714_catalog_category_content.d.ts.map +1 -0
  68. package/dist/migrations/20261008T092714_catalog_category_content.js +25 -0
  69. package/dist/migrations/20261008T092714_catalog_category_content.js.map +1 -0
  70. package/dist/migrations/index.d.ts +3 -1
  71. package/dist/migrations/index.d.ts.map +1 -1
  72. package/dist/migrations/index.js +5 -1
  73. package/dist/migrations/index.js.map +1 -1
  74. package/docs/catalog/attributes.md +9 -2
  75. package/docs/catalog/category-content.md +81 -0
  76. package/docs/catalog.md +50 -4
  77. package/i18n/en.json +16 -0
  78. package/i18n/pl.json +16 -0
  79. package/package.json +9 -9
@@ -1,3 +1,4 @@
1
+ import { raw } from '@mikro-orm/core';
1
2
  import { Product } from '../entities/product.entity.js';
2
3
  import { ProductVariant } from '../entities/product-variant.entity.js';
3
4
  import { Category } from '../entities/category.entity.js';
@@ -15,6 +16,24 @@ import { viewerOrganizationFor } from './viewer-organization.js';
15
16
  import { ERROR_CODES, isPriceSort, isProductVisibleTo, listingPriceMoney, } from '@endora-commerce/contracts';
16
17
  import { HttpError } from '@endora-commerce/platform/http';
17
18
  import { encodeCursor, decodeCursor } from '@endora-commerce/platform/http';
19
+ /** A category id as the database spells one — anything else is a 404, not a query. */
20
+ const CATEGORY_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
21
+ /** The deepest ancestor chain {@link CatalogQueryService.getCategoryPageContent} walks. */
22
+ const MAX_CATEGORY_DEPTH = 64;
23
+ /**
24
+ * Whether a Page Builder document would render anything: a block at the top
25
+ * level, or in a legacy `zones` bucket. An editor that was opened and saved
26
+ * untouched stores a document with neither.
27
+ */
28
+ export function hasPageBuilderBlocks(tree) {
29
+ if (Array.isArray(tree['content']) && tree['content'].length > 0)
30
+ return true;
31
+ const zones = tree['zones'];
32
+ if (zones && typeof zones === 'object') {
33
+ return Object.values(zones).some((zone) => Array.isArray(zone) && zone.length > 0);
34
+ }
35
+ return false;
36
+ }
18
37
  function encodeObjectCursor(value) {
19
38
  return encodeCursor(JSON.stringify(value));
20
39
  }
@@ -40,9 +59,9 @@ function isRecord(value) {
40
59
  * Eight times the page size. On the reference corpus it never bound: the first
41
60
  * page of 50 cost 213 source rows against a budget of 400. It binds only where
42
61
  * an operator restricts most of a catalogue from most viewers, and the answer
43
- * there is a short page — which is this listing's existing behaviour, since the
44
- * channel and audience filters already narrow a fetched page — rather than an
45
- * unbounded scan.
62
+ * there is a short page — the two price paths narrow each chunk they fetch by
63
+ * channel and audience, where the default path has those in its statement
64
+ * (issue #151) — rather than an unbounded scan.
46
65
  *
47
66
  * A setting was rejected because nobody has the number yet: the value it should
48
67
  * take is a function of how much of a catalogue a deployment hides, and shipping
@@ -68,6 +87,66 @@ function afterKeysetCursor(cursor, op) {
68
87
  const at = new Date(cursor.createdAt);
69
88
  return { $or: [{ createdAt: { [op]: at } }, { createdAt: at, id: { [op]: cursor.id } }] };
70
89
  }
90
+ /**
91
+ * JavaScript's `String(n)` for a `numeric` SQL expression.
92
+ *
93
+ * The attribute filter has always compared `String(value)`, and for a number
94
+ * that is not the text PostgreSQL stores: `jsonb` keeps `1e21` as a 22-digit
95
+ * integer where JavaScript prints `1e+21`, and keeps a hand-written `1.50` as
96
+ * written where JavaScript prints `1.5`. So the number is rendered the way
97
+ * JavaScript would render the double it parses to:
98
+ *
99
+ * - beyond a double's range it is `Infinity`, and below its smallest
100
+ * subnormal it is `0` — `JSON.parse`'s answers, and the two casts that would
101
+ * otherwise fail the statement;
102
+ * - at or above 1e21 and below 1e-6 JavaScript uses exponent notation, and so
103
+ * does `float8`'s shortest round-trip output, which differs only in padding
104
+ * the exponent to two digits (`1e-07`);
105
+ * - from 1e-4 up to 1e15 both print the same plain shortest round-trip
106
+ * decimal, which is what turns `1.50` into `1.5` and `2.0` into `2`;
107
+ * - in the two bands between, `float8` has already switched to exponent
108
+ * notation and JavaScript has not, so the stored digits are printed plain
109
+ * with trailing zeros removed. That is exact for any value JavaScript wrote
110
+ * and is the one place a value written by something else can differ: a
111
+ * number in [1e15, 1e21) or [1e-6, 1e-4) carrying more than 17 significant
112
+ * digits.
113
+ */
114
+ function jsStringOfNumeric(n) {
115
+ return (`(case ` +
116
+ `when abs(${n}) > 1.7976931348623157e308 then (case when ${n} < 0 then '-' else '' end) || 'Infinity' ` +
117
+ `when abs(${n}) < 3e-324 then '0' ` +
118
+ `when abs(${n}) >= 1e21 or abs(${n}) < 1e-6 ` +
119
+ `then regexp_replace((${n})::float8::text, 'e([+-])0', 'e\\1') ` +
120
+ `when abs(${n}) >= 1e15 or abs(${n}) < 1e-4 then trim_scale(${n})::text ` +
121
+ `else (${n})::float8::text end)`);
122
+ }
123
+ /**
124
+ * JavaScript's `String(value)` for a `jsonb` SQL expression, as the attribute
125
+ * filter needs it.
126
+ *
127
+ * A string or a boolean is its own text, a number is
128
+ * {@link jsStringOfNumeric}, a JSON `null` reads `'null'` and an object reads
129
+ * `[object Object]`. An **array** — a multiselect — joins its elements with a
130
+ * comma, each rendered the same way except that a `null` element is empty,
131
+ * which is `Array.prototype.join`'s rule.
132
+ *
133
+ * One kind is not reproduced: an array **nested inside** an array. JavaScript
134
+ * flattens it into the join (`[[1, 2], 3]` reads `1,2,3`); here the inner array
135
+ * contributes its JSON text. No attribute type stores one.
136
+ */
137
+ function jsStringOfJsonb(value) {
138
+ const scalar = (v, nullText) => `(case jsonb_typeof(${v}) ` +
139
+ `when 'null' then '${nullText}' ` +
140
+ `when 'object' then '[object Object]' ` +
141
+ `when 'number' then (select ${jsStringOfNumeric('num.n')} ` +
142
+ `from (select (${v} #>> '{}')::numeric as n) num) ` +
143
+ `else ${v} #>> '{}' end)`;
144
+ return (`(case jsonb_typeof(${value}) ` +
145
+ `when 'array' then (` +
146
+ `select coalesce(string_agg(${scalar('el.value', '')}, ',' order by el.position), '') ` +
147
+ `from jsonb_array_elements(${value}) with ordinality as el(value, position)) ` +
148
+ `else ${scalar(value, 'null')} end)`);
149
+ }
71
150
  export class CatalogQueryService {
72
151
  emFactory;
73
152
  productLinkService;
@@ -390,25 +469,45 @@ export class CatalogQueryService {
390
469
  if (decoded)
391
470
  cursorClause = keyset.after(decoded);
392
471
  }
393
- const effectiveWhere = cursorClause ? { $and: [where, cursorClause] } : where;
394
- // Over-fetch by one to detect hasMore.
395
- const products = await em.find(Product, effectiveWhere, {
396
- limit: params.limit + 1,
397
- orderBy: this.orderForSort(params.sort),
398
- });
472
+ // Issue #151 — everything that decides whether a row is on the listing is
473
+ // part of the statement the page is cut from. See `#listingNarrowing`.
474
+ const narrowing = await this.#listingNarrowing(em, params, ctx);
475
+ if (narrowing === null) {
476
+ // The category names nothing a storefront may browse, so no row matches
477
+ // and there is no statement worth issuing.
478
+ return { data: [], pagination: { cursor: null, hasMore: false, limit: params.limit } };
479
+ }
480
+ // Over-fetch by one to detect hasMore — one more **matching** row, which is
481
+ // what makes `hasMore` a statement about the listing rather than about the
482
+ // table.
483
+ //
484
+ // The `raw()` keys are created here, in the expression that hands them to
485
+ // the statement, and nowhere earlier. MikroORM registers a fragment in a
486
+ // process-wide cache the moment it is used as a key and releases it when a
487
+ // statement consumes it, so one created on a path that then returns without
488
+ // querying is held for the life of the process — which an anonymous caller
489
+ // could repeat at will. Nothing may sit between the two: no `await`, no
490
+ // early return, nothing that can throw.
491
+ const products = await em.find(Product, {
492
+ $and: [
493
+ where,
494
+ ...(cursorClause ? [cursorClause] : []),
495
+ ...narrowing.map((c) => ({ [raw(c.sql, c.params)]: [] })),
496
+ ],
497
+ }, { limit: params.limit + 1, orderBy: this.orderForSort(params.sort) });
399
498
  const hasMore = products.length > params.limit;
400
499
  const page = hasMore ? products.slice(0, params.limit) : products;
401
500
  const nextCursor = hasMore && page.length > 0 ? encodeObjectCursor(keyset.of(page[page.length - 1])) : null;
402
- // Sales Channel membership — only products associated with the channel are
403
- // returned, failing closed to the empty set.
404
- const visibleIds = await this.filterByChannel(page.map((p) => p.id), channel);
405
- // Attribute filter post-filtering (simple equality on attributeValues JSONB).
406
- const filtered = page.filter((p) => visibleIds.has(p.id) && this.#passesPageFilters(p, params, ctx));
407
- // Category filter
408
- let categoryFilteredIds = null;
409
- if (params.categorySlug) {
410
- categoryFilteredIds = await this.productIdsInCategoryTree(em, params.categorySlug);
411
- }
501
+ // The audience and attribute predicates once more, over the rows the
502
+ // statement returned — kept deliberately, as defence in depth.
503
+ // `isProductVisibleTo` is the platform's one answer to "may this caller see
504
+ // this product" and the SQL above is a restatement of it; a restatement that
505
+ // admits a row the predicate refuses must not be what decides a disclosure.
506
+ // The case that exists today is a stored allow-list that is not an array:
507
+ // the statement reads it as "no allow-list", the predicate does not. It
508
+ // costs no statement, and while the two agree it removes nothing — which is
509
+ // what the contract test holds them to, rule by rule, with full pages.
510
+ const priceable = page.filter((p) => this.#passesPageFilters(p, params, ctx));
412
511
  // Build the summaries. The page is resolved **once** — `toSummary` used to
413
512
  // ask `price_lists` for a batch of one, so a 50-card page made 50 calls and
414
513
  // paid the resolution's fixed cost (the active lists, the settings pair, the
@@ -419,7 +518,6 @@ export class CatalogQueryService {
419
518
  // Its asset and its category slugs are resolved the same way and for the
420
519
  // same reason (issue #263): both helpers took an id list already, and both
421
520
  // were being handed one id at a time from inside the loop.
422
- const priceable = filtered.filter((p) => categoryFilteredIds ? categoryFilteredIds.has(p.id) : true);
423
521
  const resolvedPrices = await this.#listingPricesFor(priceable, channel, ctx.audience);
424
522
  const cardReads = await this.#listingCardReadsFor(em, priceable.map((p) => p.id));
425
523
  const summaries = priceable.map((p) => this.toSummary(p, channel, ctx.preferredLanguage, resolvedPrices, cardReads));
@@ -428,6 +526,115 @@ export class CatalogQueryService {
428
526
  pagination: { cursor: nextCursor, hasMore, limit: params.limit },
429
527
  };
430
528
  }
529
+ /**
530
+ * What narrows the default listing, as conditions **of the statement its page
531
+ * is cut from** (issue #151) — or `null` when the category filter names
532
+ * nothing, so no row can match.
533
+ *
534
+ * These four were applied to the page after `limit + 1` rows had been fetched
535
+ * and `hasMore` and the cursor read off that cut. A page whose rows were all
536
+ * narrowed away was answered `data: []` with `hasMore: true`; one where some
537
+ * were was short. With two sales channels and the newest hundred products on
538
+ * one of them, the other's first page of a hundred was empty.
539
+ *
540
+ * - **channel membership** comes from the kernel's accessor as a fragment
541
+ * ({@link SalesChannelMembershipPort.entityIdsInChannelSubquery}); the bridge
542
+ * is still not named here (Constitution XII);
543
+ * - **the audience** is `isProductVisibleTo` restated — see
544
+ * `#audienceCondition`;
545
+ * - **the category** is an `exists` over this module's own
546
+ * `product_categories`, against the tree's ids rather than against every
547
+ * product id the tree holds, which is what the page-side test loaded;
548
+ * - **each attribute filter** is `#passesPageFilters`' string comparison
549
+ * restated — see `#attributeCondition`.
550
+ *
551
+ * **No `raw()` fragment is created here** — these are descriptions, and the
552
+ * caller turns them into keys in the expression that executes them. A
553
+ * fragment is registered process-wide when it becomes a key and released
554
+ * only by the statement that consumes it, so this method, which can answer
555
+ * `null` and awaits a read that can fail, is the wrong place to make one.
556
+ */
557
+ async #listingNarrowing(em, params, ctx) {
558
+ // First, because it is the one part that can end the request: an unknown,
559
+ // inactive or deleted category means no row matches.
560
+ let categoryIds = null;
561
+ if (params.categorySlug) {
562
+ categoryIds = await this.#categoryTreeIds(em, params.categorySlug);
563
+ if (categoryIds.length === 0)
564
+ return null;
565
+ }
566
+ const inChannel = this.#requireChannelMembership().entityIdsInChannelSubquery(ctx.resolvedChannel.id, 'product');
567
+ const conditions = [
568
+ { sql: (alias) => `${alias}.id in (${inChannel.sql})`, params: inChannel.params },
569
+ this.#audienceCondition(ctx.audience),
570
+ ];
571
+ if (categoryIds !== null) {
572
+ const ids = categoryIds;
573
+ conditions.push({
574
+ sql: (alias) => `exists (select 1 from product_categories pc ` +
575
+ `where pc.product_id = ${alias}.id ` +
576
+ `and pc.category_id in (${ids.map(() => '?').join(',')}))`,
577
+ params: ids,
578
+ });
579
+ }
580
+ for (const [key, values] of Object.entries(params.attributeFilters ?? {})) {
581
+ conditions.push(this.#attributeCondition(key, values));
582
+ }
583
+ return conditions;
584
+ }
585
+ /**
586
+ * `isProductVisibleTo`, as SQL, for the audience in front of the listing.
587
+ *
588
+ * The third restatement of that predicate in this module, and the only one
589
+ * that takes the audience as an argument: `catalog-quick-search.service.ts`
590
+ * answers for a signed-in buyer and `ANONYMOUS_AUDIENCE_CLAUSE` for nobody,
591
+ * so neither could be reused for a surface both kinds of caller read. The
592
+ * `case` follows the predicate branch for branch — a non-empty allow-list
593
+ * decides on its own, then `organization_restricted`, then `logged_in_only` —
594
+ * so a fourth visibility value falls to `else true` exactly as it falls to
595
+ * the predicate's last `return`.
596
+ *
597
+ * `@>` containment over the JSONB array, so the organisation has to be one of
598
+ * its elements rather than a substring of the serialised bag.
599
+ */
600
+ #audienceCondition(audience) {
601
+ const onAllowList = audience.organizationId !== null;
602
+ return {
603
+ sql: (alias) => `(case ` +
604
+ `when (case when jsonb_typeof(${alias}.allowed_organization_ids) = 'array' ` +
605
+ `then jsonb_array_length(${alias}.allowed_organization_ids) else 0 end) > 0 ` +
606
+ `then ${onAllowList ? `${alias}.allowed_organization_ids @> ?::jsonb` : 'false'} ` +
607
+ `when ${alias}.visibility = 'organization_restricted' then false ` +
608
+ `when ${alias}.visibility = 'logged_in_only' then ${audience.authenticated ? 'true' : 'false'} ` +
609
+ `else true end)`,
610
+ params: onAllowList ? [JSON.stringify([audience.organizationId])] : [],
611
+ };
612
+ }
613
+ /**
614
+ * One `filter[attr.<key>]`, as SQL: the product's value for `key`, rendered
615
+ * the way `#passesPageFilters` renders it, is one of the requested values.
616
+ *
617
+ * That method compares `String(value)`, so this is `String` restated for the
618
+ * JSON kinds a stored value can take — see {@link jsStringOfJsonb}. A key the
619
+ * product does not carry is SQL `NULL` throughout and matches nothing, which
620
+ * is the method's `undefined` arm.
621
+ *
622
+ * The comparison is deliberately not improved here. A multiselect holding two
623
+ * options matches neither of them alone, on either side of this change; that
624
+ * is a question about what the filter means, and answering it in the
625
+ * statement only would make the page-side predicate disagree with it.
626
+ */
627
+ #attributeCondition(key, values) {
628
+ const wanted = values.map((v) => String(v));
629
+ if (wanted.length === 0)
630
+ return { sql: () => 'false', params: [] };
631
+ return {
632
+ sql: (alias) => `(select ${jsStringOfJsonb('val.v')} ` +
633
+ `from (select ${alias}.attribute_values -> ?::text as v) val) ` +
634
+ `in (${wanted.map(() => '?').join(',')})`,
635
+ params: [key, ...wanted],
636
+ };
637
+ }
431
638
  /**
432
639
  * The channel/audience/attribute predicates a fetched page is narrowed by,
433
640
  * for one product.
@@ -441,13 +648,13 @@ export class CatalogQueryService {
441
648
  * nor the name sort could have had.
442
649
  */
443
650
  #passesPageFilters(product, params, ctx) {
444
- // Issue #227 — the second scoping axis, alongside the channel one. It is
445
- // applied on the page rather than in the `where` because the allow-list
446
- // test is a JSONB containment the ORM query object cannot spell, and
447
- // splitting the two axes across the query and the page would leave the
448
- // `limit` accounting to reason about twice instead of once. The known cost
449
- // is a page narrowed after the fetch coming back shorter than `limit`, and
450
- // it is bounded by how much of a catalogue an operator restricts.
651
+ // Issue #227 — the second scoping axis, alongside the channel one. The two
652
+ // price paths apply it here, to each chunk they collect before cutting a
653
+ // page, and their known cost is the scan budget binding where an operator
654
+ // restricts most of a catalogue. The default path no longer relies on it
655
+ // (issue #151): `#audienceCondition` puts the same answer in the statement
656
+ // its page is cut from, and this runs afterwards only as the predicate's
657
+ // own word on each row.
451
658
  if (!isProductVisibleTo(product, ctx.audience))
452
659
  return false;
453
660
  if (!params.attributeFilters)
@@ -1137,6 +1344,64 @@ export class CatalogQueryService {
1137
1344
  };
1138
1345
  return build(null);
1139
1346
  }
1347
+ /**
1348
+ * The Page Builder document the storefront renders on one category's page,
1349
+ * resolved to a language.
1350
+ *
1351
+ * **Visibility is the tree's, and it is checked here rather than trusted to
1352
+ * the caller.** {@link getCategoryTree} lists a category only when it is
1353
+ * live, active, and hangs off a chain of live, active ancestors — an
1354
+ * inactive category hides its whole branch. A category that fails any of
1355
+ * those answers 404, so its content is not reachable by id while its page
1356
+ * is not reachable by link.
1357
+ *
1358
+ * **The language is resolved like the name** ({@link pickLang}): the
1359
+ * caller's, then the channel's default, then English, then whatever exists.
1360
+ * A language whose document holds no block is skipped, because an operator
1361
+ * who opened the Polish tab and saved it empty did not ask for the English
1362
+ * text to disappear from the Polish storefront.
1363
+ */
1364
+ async getCategoryPageContent(categoryId, ctx) {
1365
+ const notFound = () => new HttpError(404, ERROR_CODES.NOT_FOUND, 'Category not found.');
1366
+ if (!CATEGORY_ID_RE.test(categoryId))
1367
+ throw notFound();
1368
+ const em = this.emFactory();
1369
+ const category = await em.findOne(Category, { id: categoryId, deletedAt: null, isActive: true }, { populate: ['content'] });
1370
+ if (!category)
1371
+ throw notFound();
1372
+ // The ancestor chain, bounded: the write path forbids a cycle, but a
1373
+ // corrupt `parent_category_id` must end in a 404 and not in a hung request.
1374
+ const seen = new Set([category.id]);
1375
+ let parentId = category.parentCategoryId ?? null;
1376
+ while (parentId !== null) {
1377
+ if (seen.has(parentId) || seen.size > MAX_CATEGORY_DEPTH)
1378
+ throw notFound();
1379
+ seen.add(parentId);
1380
+ const parent = await em.findOne(Category, {
1381
+ id: parentId,
1382
+ deletedAt: null,
1383
+ isActive: true,
1384
+ });
1385
+ if (!parent)
1386
+ throw notFound();
1387
+ parentId = parent.parentCategoryId ?? null;
1388
+ }
1389
+ const languages = category.content?.languages ?? {};
1390
+ const candidates = [
1391
+ ctx.preferredLanguage,
1392
+ ctx.resolvedChannel.defaultLanguage,
1393
+ 'en-US',
1394
+ 'en',
1395
+ ...Object.keys(languages),
1396
+ ].filter((v) => typeof v === 'string');
1397
+ for (const language of candidates) {
1398
+ const tree = languages[language];
1399
+ if (tree !== undefined && hasPageBuilderBlocks(tree)) {
1400
+ return { categoryId: category.id, language, content: tree };
1401
+ }
1402
+ }
1403
+ return { categoryId: category.id, language: null, content: null };
1404
+ }
1140
1405
  // ------------------------------------------------------------------
1141
1406
  // Filters
1142
1407
  // ------------------------------------------------------------------
@@ -1512,6 +1777,17 @@ export class CatalogQueryService {
1512
1777
  return new Set(visible);
1513
1778
  }
1514
1779
  async productIdsInCategoryTree(em, categorySlug) {
1780
+ const all = await this.#categoryTreeIds(em, categorySlug);
1781
+ if (all.length === 0)
1782
+ return new Set();
1783
+ const rows = await em.execute(`select product_id from product_categories where category_id in (${all.map(() => '?').join(',')})`, all);
1784
+ return new Set(rows.map((r) => r.product_id));
1785
+ }
1786
+ /**
1787
+ * The category a slug names and every active descendant of it — empty when
1788
+ * the slug names nothing a storefront may browse.
1789
+ */
1790
+ async #categoryTreeIds(em, categorySlug) {
1515
1791
  // Feature 068 — an inactive category narrows to nothing, and an inactive
1516
1792
  // branch contributes no products to an active ancestor.
1517
1793
  const root = await em.findOne(Category, {
@@ -1520,7 +1796,7 @@ export class CatalogQueryService {
1520
1796
  isActive: true,
1521
1797
  });
1522
1798
  if (!root)
1523
- return new Set();
1799
+ return [];
1524
1800
  // Collect descendant ids (BFS).
1525
1801
  const all = [root.id];
1526
1802
  let frontier = [root.id];
@@ -1534,8 +1810,7 @@ export class CatalogQueryService {
1534
1810
  all.push(...nextIds);
1535
1811
  frontier = nextIds;
1536
1812
  }
1537
- const rows = await em.execute(`select product_id from product_categories where category_id in (${all.map(() => '?').join(',')})`, all);
1538
- return new Set(rows.map((r) => r.product_id));
1813
+ return all;
1539
1814
  }
1540
1815
  /**
1541
1816
  * Set of channel-visible product ids directly assigned to each category