@unchainedshop/core-products 5.0.0-alpha.1 → 5.0.0-alpha.3

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.
@@ -8,7 +8,10 @@ export const ProductMediaCollection = async (db) => {
8
8
  { index: { tags: 1, sortKey: 1 } },
9
9
  { index: { productId: 1, tags: 1, sortKey: 1 } },
10
10
  ]);
11
- await buildDbIndexes(ProductMediaTexts, [{ index: { productMediaId: 1 } }, { index: { locale: 1 } }]);
11
+ await buildDbIndexes(ProductMediaTexts, [
12
+ { index: { productMediaId: 1 } },
13
+ { index: { locale: 1, productMediaId: 1 } },
14
+ ]);
12
15
  return {
13
16
  ProductMedias,
14
17
  ProductMediaTexts,
@@ -1,4 +1,4 @@
1
- import { mongodb, buildDbIndexes, isDocumentDBCompatModeEnabled, } from '@unchainedshop/mongodb';
1
+ import { mongodb, buildDbIndexes } from '@unchainedshop/mongodb';
2
2
  export const ProductReviewVoteType = {
3
3
  UPVOTE: 'UPVOTE',
4
4
  DOWNVOTE: 'DOWNVOTE',
@@ -6,23 +6,21 @@ export const ProductReviewVoteType = {
6
6
  };
7
7
  export const ProductReviewsCollection = async (db) => {
8
8
  const ProductReviews = db.collection('product_reviews');
9
- if (!isDocumentDBCompatModeEnabled()) {
10
- await buildDbIndexes(ProductReviews, [
11
- {
12
- index: {
13
- title: 'text',
14
- review: 'text',
15
- },
16
- options: {
17
- weights: {
18
- title: 3,
19
- review: 5,
20
- },
21
- name: 'productreview_fulltext_search',
9
+ await buildDbIndexes(ProductReviews, [
10
+ {
11
+ index: {
12
+ title: 'text',
13
+ review: 'text',
14
+ },
15
+ options: {
16
+ weights: {
17
+ title: 3,
18
+ review: 5,
22
19
  },
20
+ name: 'productreview_fulltext_search',
23
21
  },
24
- ]);
25
- }
22
+ },
23
+ ]);
26
24
  await buildDbIndexes(ProductReviews, [{ index: { productId: 1 } }, { index: { authorId: 1 } }]);
27
25
  return {
28
26
  ProductReviews,
@@ -9,7 +9,7 @@ export const ProductVariationsCollection = async (db) => {
9
9
  await buildDbIndexes(ProductVariations, [{ index: { productId: 1 } }]);
10
10
  await buildDbIndexes(ProductVariationTexts, [
11
11
  { index: { productVariationId: 1 } },
12
- { index: { locale: 1 } },
12
+ { index: { locale: 1, productVariationId: 1 } },
13
13
  ]);
14
14
  return {
15
15
  ProductVariations,
@@ -50,7 +50,7 @@ export interface ProductPrice extends Price {
50
50
  isTaxable?: boolean;
51
51
  isNetPrice?: boolean;
52
52
  countryCode: string;
53
- maxQuantity?: number;
53
+ minQuantity?: number;
54
54
  }
55
55
  export interface ProductPriceRange {
56
56
  minPrice: ProductPrice;
@@ -1,4 +1,4 @@
1
- import { mongodb, buildDbIndexes, isDocumentDBCompatModeEnabled, } from '@unchainedshop/mongodb';
1
+ import { mongodb, buildDbIndexes } from '@unchainedshop/mongodb';
2
2
  export const ProductStatus = {
3
3
  DRAFT: 'DRAFT',
4
4
  ACTIVE: 'ACTIVE',
@@ -18,41 +18,36 @@ export const ProductContractStandard = {
18
18
  export const ProductsCollection = async (db) => {
19
19
  const Products = db.collection('products');
20
20
  const ProductTexts = db.collection('product_texts');
21
- if (!isDocumentDBCompatModeEnabled()) {
22
- await buildDbIndexes(Products, [
23
- {
24
- index: { 'warehousing.sku': 'text', slugs: 'text' },
25
- options: {
26
- name: 'products_fulltext_search',
27
- },
21
+ await buildDbIndexes(Products, [
22
+ {
23
+ index: { 'warehousing.sku': 'text', slugs: 'text' },
24
+ options: {
25
+ name: 'products_fulltext_search',
28
26
  },
29
- ]);
30
- await buildDbIndexes(ProductTexts, [
31
- {
32
- index: { title: 'text', subtitle: 'text', vendor: 'text', brand: 'text' },
33
- options: {
34
- weights: {
35
- title: 8,
36
- subtitle: 6,
37
- vendor: 5,
38
- brand: 4,
39
- },
40
- name: 'product_texts_fulltext_search',
27
+ },
28
+ ]);
29
+ await buildDbIndexes(ProductTexts, [
30
+ {
31
+ index: { title: 'text', subtitle: 'text', vendor: 'text', brand: 'text' },
32
+ options: {
33
+ weights: {
34
+ title: 8,
35
+ subtitle: 6,
36
+ vendor: 5,
37
+ brand: 4,
41
38
  },
39
+ name: 'product_texts_fulltext_search',
42
40
  },
43
- ]);
44
- }
41
+ },
42
+ ]);
45
43
  await buildDbIndexes(Products, [
46
- { index: { deleted: 1 } },
47
- { index: { sequence: 1 } },
44
+ { index: { deleted: 1, status: 1, sequence: 1 } },
48
45
  { index: { slugs: 1 } },
49
- { index: { status: 1 } },
50
46
  { index: { tags: 1 } },
51
- { index: { 'warehousing.sku': 1 } },
47
+ { index: { 'warehousing.sku': 1 }, options: { sparse: true } },
52
48
  ]);
53
49
  await buildDbIndexes(ProductTexts, [
54
50
  { index: { productId: 1 } },
55
- { index: { locale: 1 } },
56
51
  { index: { slug: 1 } },
57
52
  { index: { locale: 1, productId: 1 } },
58
53
  ]);
@@ -0,0 +1,2 @@
1
+ import type { MigrationRepository } from '@unchainedshop/mongodb';
2
+ export default function migrateCommercePricingToMinQuantity(repository: MigrationRepository): void;
@@ -0,0 +1,54 @@
1
+ import { createLogger } from '@unchainedshop/logger';
2
+ import { ProductsCollection } from "../db/ProductsCollection.js";
3
+ const logger = createLogger('unchained:core-products:migrations');
4
+ const UNMIGRATED_PRICING_SELECTOR = {
5
+ 'commerce.pricing': { $elemMatch: { minQuantity: { $exists: false } } },
6
+ };
7
+ const convertPricingToMinQuantity = (pricing = []) => {
8
+ const groups = new Map();
9
+ for (const level of pricing) {
10
+ const key = `${level.countryCode}:${level.currencyCode}`;
11
+ const group = groups.get(key);
12
+ if (group)
13
+ group.push(level);
14
+ else
15
+ groups.set(key, [level]);
16
+ }
17
+ const nextPricing = [];
18
+ for (const levels of groups.values()) {
19
+ const sorted = [...levels].sort((a, b) => (a.maxQuantity || Number.POSITIVE_INFINITY) - (b.maxQuantity || Number.POSITIVE_INFINITY));
20
+ const seenMax = new Set();
21
+ let previousMax = 0;
22
+ sorted.forEach((level, index) => {
23
+ if (level.maxQuantity) {
24
+ if (seenMax.has(level.maxQuantity)) {
25
+ logger.warn(`Duplicate maxQuantity ${level.maxQuantity} for ${level.countryCode}/${level.currencyCode} — order resolved by stable sort`);
26
+ }
27
+ seenMax.add(level.maxQuantity);
28
+ }
29
+ const { maxQuantity, ...rest } = level;
30
+ nextPricing.push({ ...rest, minQuantity: index === 0 ? 0 : previousMax + 1 });
31
+ previousMax = maxQuantity || previousMax;
32
+ });
33
+ }
34
+ return nextPricing;
35
+ };
36
+ export default function migrateCommercePricingToMinQuantity(repository) {
37
+ repository?.register({
38
+ id: 20260611120000,
39
+ name: 'Convert product commerce pricing tiers from maxQuantity to minQuantity',
40
+ up: async () => {
41
+ const { Products } = await ProductsCollection(repository.db);
42
+ let migrated = 0;
43
+ const cursor = Products.find(UNMIGRATED_PRICING_SELECTOR);
44
+ for await (const product of cursor) {
45
+ const nextPricing = convertPricingToMinQuantity((product.commerce?.pricing ?? []));
46
+ await Products.updateOne({ _id: product._id }, { $set: { 'commerce.pricing': nextPricing } });
47
+ migrated += 1;
48
+ }
49
+ if (migrated > 0) {
50
+ logger.info(`Converted commerce pricing tiers to minQuantity on ${migrated} product(s)`);
51
+ }
52
+ },
53
+ });
54
+ }
@@ -8,21 +8,14 @@ declare const _default: {
8
8
  slugs: string[];
9
9
  updated: Date;
10
10
  commerce: {
11
- pricing: ({
11
+ pricing: {
12
12
  amount: number;
13
- maxQuantity: null;
13
+ minQuantity: number;
14
14
  isTaxable: boolean;
15
15
  isNetPrice: boolean;
16
16
  currencyCode: string;
17
17
  countryCode: string;
18
- } | {
19
- amount: number;
20
- maxQuantity: number;
21
- isTaxable: boolean;
22
- isNetPrice: boolean;
23
- currencyCode: string;
24
- countryCode: string;
25
- })[];
18
+ }[];
26
19
  };
27
20
  published: Date;
28
21
  };
@@ -11,7 +11,7 @@ export default {
11
11
  pricing: [
12
12
  {
13
13
  amount: 1000,
14
- maxQuantity: null,
14
+ minQuantity: 3,
15
15
  isTaxable: false,
16
16
  isNetPrice: false,
17
17
  currencyCode: 'CHF',
@@ -19,7 +19,7 @@ export default {
19
19
  },
20
20
  {
21
21
  amount: 20000,
22
- maxQuantity: 2,
22
+ minQuantity: 0,
23
23
  isTaxable: true,
24
24
  isNetPrice: true,
25
25
  currencyCode: 'ETB',
@@ -27,7 +27,7 @@ export default {
27
27
  },
28
28
  {
29
29
  amount: 1,
30
- maxQuantity: 1,
30
+ minQuantity: 0,
31
31
  isTaxable: false,
32
32
  isNetPrice: false,
33
33
  currencyCode: 'ETH',
@@ -35,7 +35,7 @@ export default {
35
35
  },
36
36
  {
37
37
  amount: 750,
38
- maxQuantity: 2,
38
+ minQuantity: 0,
39
39
  isTaxable: false,
40
40
  isNetPrice: false,
41
41
  currencyCode: 'CHF',
@@ -36,7 +36,7 @@ export declare const configureProductPricesModule: ({ proxyProducts, db, }: {
36
36
  countryCode: string;
37
37
  }) => Promise<{
38
38
  minQuantity: number;
39
- maxQuantity: number;
39
+ maxQuantity: number | null;
40
40
  price: ProductPrice;
41
41
  }[]>;
42
42
  rates: {
@@ -18,6 +18,18 @@ export const normalizeRate = (baseCurrency, quoteCurrency, rateRecord) => {
18
18
  rate = fromDecimals !== targetDecimals ? rate / 10 ** (fromDecimals - targetDecimals) : rate;
19
19
  return rate;
20
20
  };
21
+ const normalizeProductPrice = (priceLevel) => {
22
+ if (priceLevel.amount === null)
23
+ return null;
24
+ return {
25
+ amount: priceLevel.amount,
26
+ currencyCode: priceLevel.currencyCode,
27
+ countryCode: priceLevel.countryCode,
28
+ minQuantity: priceLevel.minQuantity ?? 0,
29
+ isTaxable: !!priceLevel.isTaxable,
30
+ isNetPrice: !!priceLevel.isNetPrice,
31
+ };
32
+ };
21
33
  export const configureProductPricesModule = ({ proxyProducts, db, }) => {
22
34
  const catalogPrice = async (product, { countryCode, currencyCode, quantity = 1, }) => {
23
35
  const pricing = getPriceLevels({
@@ -25,24 +37,18 @@ export const configureProductPricesModule = ({ proxyProducts, db, }) => {
25
37
  currencyCode,
26
38
  countryCode,
27
39
  });
28
- const foundPrice = pricing.find((level) => !level.maxQuantity || level.maxQuantity >= quantity);
40
+ const foundPrice = pricing.filter((level) => (level.minQuantity ?? 0) <= quantity).pop();
29
41
  if (!foundPrice)
30
42
  return null;
31
- const normalizedPrice = {
32
- isTaxable: false,
33
- isNetPrice: false,
34
- ...foundPrice,
35
- };
36
- if (normalizedPrice.amount !== null) {
37
- return normalizedPrice;
38
- }
39
- return null;
43
+ return normalizeProductPrice(foundPrice);
40
44
  };
41
45
  return {
42
46
  price: catalogPrice,
43
47
  priceRange: getPriceRange,
44
48
  async catalogPrices(product) {
45
- return (product.commerce && product.commerce.pricing) || [];
49
+ return ((product.commerce && product.commerce.pricing) || [])
50
+ .map(normalizeProductPrice)
51
+ .filter((priceLevel) => Boolean(priceLevel));
46
52
  },
47
53
  catalogPriceRange: async (product, { quantity = 0, vectors = [], includeInactive = false, countryCode, currencyCode, }) => {
48
54
  const products = await proxyProducts(product, vectors, {
@@ -65,28 +71,24 @@ export const configureProductPricesModule = ({ proxyProducts, db, }) => {
65
71
  };
66
72
  },
67
73
  catalogPricesLeveled: async (product, { currencyCode, countryCode }) => {
68
- let previousMax;
69
- const filteredAndSortedPriceLevels = getPriceLevels({
74
+ const sortedPriceLevels = getPriceLevels({
70
75
  product,
71
76
  currencyCode,
72
77
  countryCode,
73
78
  });
74
- return filteredAndSortedPriceLevels.map((priceLevel, i) => {
75
- const max = priceLevel.maxQuantity || 0;
76
- const min = previousMax ? previousMax + 1 : 0;
77
- previousMax = priceLevel.maxQuantity;
79
+ return sortedPriceLevels.flatMap((priceLevel, i) => {
80
+ const nextLevel = sortedPriceLevels[i + 1];
81
+ const price = normalizeProductPrice({
82
+ ...priceLevel,
83
+ currencyCode,
84
+ countryCode,
85
+ });
86
+ if (!price)
87
+ return [];
78
88
  return {
79
- minQuantity: min,
80
- maxQuantity: i === 0 && priceLevel.maxQuantity && priceLevel.maxQuantity > 0
81
- ? priceLevel.maxQuantity
82
- : max,
83
- price: {
84
- isTaxable: !!priceLevel.isTaxable,
85
- isNetPrice: !!priceLevel.isNetPrice,
86
- amount: priceLevel.amount,
87
- currencyCode,
88
- countryCode,
89
- },
89
+ minQuantity: priceLevel.minQuantity ?? 0,
90
+ maxQuantity: nextLevel?.minQuantity != null ? nextLevel.minQuantity - 1 : null,
91
+ price,
90
92
  };
91
93
  });
92
94
  },
@@ -1,4 +1,4 @@
1
- import { assertDocumentDBCompatMode } from '@unchainedshop/mongodb';
1
+ import {} from '@unchainedshop/mongodb';
2
2
  import { emit, registerEvents } from '@unchainedshop/events';
3
3
  import { generateDbFilterById, buildSortOptions, mongodb, generateDbObjectId, } from '@unchainedshop/mongodb';
4
4
  import { SortDirection } from '@unchainedshop/utils';
@@ -17,7 +17,6 @@ const buildFindSelector = ({ productId, authorId, queryString, created, updated,
17
17
  deleted: null,
18
18
  };
19
19
  if (queryString) {
20
- assertDocumentDBCompatMode();
21
20
  selector.$text = { $search: queryString };
22
21
  }
23
22
  if (created) {
@@ -80,7 +80,7 @@ export declare const configureProductsModule: (moduleInput: ModuleInput<Products
80
80
  countryCode: string;
81
81
  }) => Promise<{
82
82
  minQuantity: number;
83
- maxQuantity: number;
83
+ maxQuantity: number | null;
84
84
  price: import("../db/ProductsCollection.ts").ProductPrice;
85
85
  }[]>;
86
86
  rates: {
@@ -1,5 +1,5 @@
1
1
  import { emit, registerEvents } from '@unchainedshop/events';
2
- import { findPreservingIds, generateDbFilterById, buildSortOptions, mongodb, generateDbObjectId, assertDocumentDBCompatMode, } from '@unchainedshop/mongodb';
2
+ import { findPreservingIds, generateDbFilterById, buildSortOptions, mongodb, generateDbObjectId, } from '@unchainedshop/mongodb';
3
3
  import { SortDirection } from '@unchainedshop/utils';
4
4
  import { ProductsCollection, ProductStatus, ProductType, } from "../db/ProductsCollection.js";
5
5
  import { configureProductMediaModule } from "./configureProductMediaModule.js";
@@ -8,6 +8,7 @@ import { configureProductReviewsModule } from "./configureProductReviewsModule.j
8
8
  import { configureProductTextsModule } from "./configureProductTextsModule.js";
9
9
  import { configureProductVariationsModule } from "./configureProductVariationsModule.js";
10
10
  import { productsSettings } from "../products-settings.js";
11
+ import migrateCommercePricingToMinQuantity from "../migrations/20260611120000-pricing-maxquantity-to-minquantity.js";
11
12
  const PRODUCT_EVENTS = [
12
13
  'PRODUCT_CREATE',
13
14
  'PRODUCT_REMOVE',
@@ -23,6 +24,7 @@ const PRODUCT_EVENTS = [
23
24
  const InternalProductStatus = {
24
25
  DRAFT: null,
25
26
  };
27
+ const isDraftStatus = (status) => status === ProductStatus.DRAFT || status === InternalProductStatus.DRAFT;
26
28
  export const buildFindSelector = ({ slugs, tags, includeDrafts = false, includeDeleted = false, productIds, productSelector, queryString, skus, bundleItemProductIds, proxyAssignmentProductIds, }) => {
27
29
  const selector = productSelector ? { ...productSelector } : {};
28
30
  if (productIds && !selector._id) {
@@ -53,7 +55,6 @@ export const buildFindSelector = ({ slugs, tags, includeDrafts = false, includeD
53
55
  selector.$or = orConditions;
54
56
  }
55
57
  if (queryString && !selector.$text) {
56
- assertDocumentDBCompatMode();
57
58
  selector.$text = { $search: queryString };
58
59
  }
59
60
  if (!selector.status) {
@@ -70,10 +71,11 @@ export const buildFindSelector = ({ slugs, tags, includeDrafts = false, includeD
70
71
  return selector;
71
72
  };
72
73
  export const configureProductsModule = async (moduleInput) => {
73
- const { db, options: productsOptions = {} } = moduleInput;
74
+ const { db, migrationRepository, options: productsOptions = {} } = moduleInput;
74
75
  registerEvents(PRODUCT_EVENTS);
75
76
  await productsSettings.configureSettings(productsOptions);
76
77
  const { Products, ProductTexts } = await ProductsCollection(db);
78
+ migrateCommercePricingToMinQuantity(migrationRepository);
77
79
  const productTexts = configureProductTextsModule({
78
80
  Products,
79
81
  ProductTexts,
@@ -95,7 +97,7 @@ export const configureProductsModule = async (moduleInput) => {
95
97
  return deletedResult.deletedCount;
96
98
  };
97
99
  const publishProduct = async (product) => {
98
- if (product.status === InternalProductStatus.DRAFT) {
100
+ if (isDraftStatus(product.status)) {
99
101
  await Products.updateOne(generateDbFilterById(product._id), {
100
102
  $set: {
101
103
  status: ProductStatus.ACTIVE,
@@ -188,7 +190,7 @@ export const configureProductsModule = async (moduleInput) => {
188
190
  return product.status === ProductStatus.ACTIVE;
189
191
  },
190
192
  isDraft: (product) => {
191
- return product.status === ProductStatus.DRAFT || product.status === InternalProductStatus.DRAFT;
193
+ return isDraftStatus(product.status);
192
194
  },
193
195
  normalizedStatus: (product) => {
194
196
  return product.status === null ? ProductStatus.DRAFT : product.status;
@@ -1,17 +1,10 @@
1
1
  export const getPriceLevels = (params) => {
2
- return (params.product?.commerce?.pricing || [])
3
- .toSorted(({ maxQuantity: leftMaxQuantity = 0 }, { maxQuantity: rightMaxQuantity = 0 }) => {
4
- if (leftMaxQuantity === rightMaxQuantity || (!leftMaxQuantity && !rightMaxQuantity))
5
- return 0;
6
- if (!leftMaxQuantity)
7
- return 1;
8
- if (!rightMaxQuantity)
9
- return -1;
10
- return leftMaxQuantity - rightMaxQuantity;
11
- })
2
+ return ((params.product?.commerce?.pricing || [])
3
+ .toSorted((left, right) => (left.minQuantity ?? 0) - (right.minQuantity ?? 0))
12
4
  .filter((priceLevel) => {
13
5
  if (!params.currencyCode)
14
6
  return priceLevel.countryCode === params.countryCode;
15
- return (priceLevel.currencyCode === params.currencyCode && priceLevel.countryCode === params.countryCode);
16
- });
7
+ return (priceLevel.currencyCode === params.currencyCode &&
8
+ priceLevel.countryCode === params.countryCode);
9
+ }));
17
10
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unchainedshop/core-products",
3
3
  "description": "Product catalog management module for the Unchained Engine",
4
- "version": "5.0.0-alpha.1",
4
+ "version": "5.0.0-alpha.3",
5
5
  "main": "lib/products-index.js",
6
6
  "types": "lib/products-index.d.ts",
7
7
  "type": "module",
@@ -36,10 +36,12 @@
36
36
  "homepage": "https://github.com/unchainedshop/unchained#readme",
37
37
  "dependencies": {
38
38
  "@unchainedshop/events": "^5.0.0-alpha.1",
39
+ "@unchainedshop/logger": "^5.0.0-alpha.1",
40
+ "@unchainedshop/mongodb": "^5.0.0-alpha.1",
39
41
  "@unchainedshop/utils": "^5.0.0-alpha.1"
40
42
  },
41
43
  "devDependencies": {
42
- "@types/node": "^25.0.0",
44
+ "@types/node": "^26.2.0",
43
45
  "typescript": "^5.8.3"
44
46
  }
45
47
  }