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

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/README.md CHANGED
@@ -13,121 +13,26 @@ npm install @unchainedshop/core-products
13
13
 
14
14
  ## Usage
15
15
 
16
- ```typescript
17
- import { configureProductsModule, ProductType } from '@unchainedshop/core-products';
16
+ The platform initializes this module as `platform.unchainedAPI.modules.products`.
18
17
 
19
- const productsModule = await configureProductsModule({ db });
18
+ ```typescript
19
+ import { ProductType } from '@unchainedshop/core-products';
20
20
 
21
- // Create a product
22
- const productId = await productsModule.create({
23
- type: ProductType.SimpleProduct,
24
- slugs: ['my-product'],
21
+ const { products } = platform.unchainedAPI.modules;
22
+ const product = await products.create({
23
+ type: ProductType.SIMPLE_PRODUCT,
24
+ tags: ['featured'],
25
25
  });
26
-
27
- // Find products
28
- const products = await productsModule.findProducts({
26
+ await products.publish(product);
27
+ const publishedProducts = await products.findProducts({
29
28
  tags: ['featured'],
30
29
  includeDrafts: false,
31
30
  });
32
-
33
- // Publish a product
34
- await productsModule.publish(productId);
35
31
  ```
36
32
 
37
- ## API Overview
38
-
39
- ### Module Configuration
40
-
41
- | Export | Description |
42
- |--------|-------------|
43
- | `configureProductsModule` | Configure and return the products module |
44
-
45
- ### Queries
46
-
47
- | Method | Description |
48
- |--------|-------------|
49
- | `findProduct` | Find product by ID or slug |
50
- | `findProducts` | Find products with filtering and pagination |
51
- | `count` | Count products matching query |
52
- | `productExists` | Check if product exists |
53
-
54
- ### Mutations
55
-
56
- | Method | Description |
57
- |--------|-------------|
58
- | `create` | Create a new product |
59
- | `update` | Update product data |
60
- | `delete` | Soft delete a product |
61
- | `publish` | Publish a draft product |
62
- | `unpublish` | Unpublish a product |
63
- | `addAssignment` | Add product proxy assignment |
64
- | `removeAssignment` | Remove product assignment |
65
-
66
- ### Submodules
67
-
68
- #### Media (`products.media`)
69
- | Method | Description |
70
- |--------|-------------|
71
- | `findProductMedia` | Find media for a product |
72
- | `createMedia` | Add media to product |
73
- | `updateMedia` | Update media metadata |
74
- | `deleteMedia` | Remove media from product |
75
- | `reorderMedia` | Reorder product media |
76
-
77
- #### Prices (`products.prices`)
78
- | Method | Description |
79
- |--------|-------------|
80
- | `findProductPrices` | Get product prices |
81
- | `createPrice` | Add a price |
82
- | `updatePrice` | Update a price |
83
- | `deletePrice` | Remove a price |
84
-
85
- #### Reviews (`products.reviews`)
86
- | Method | Description |
87
- |--------|-------------|
88
- | `findProductReviews` | Find reviews for product |
89
- | `createReview` | Add a review |
90
- | `updateReview` | Update a review |
91
- | `deleteReview` | Remove a review |
92
-
93
- #### Texts (`products.texts`)
94
- | Method | Description |
95
- |--------|-------------|
96
- | `findProductTexts` | Find localized texts |
97
- | `updateTexts` | Update product texts |
98
-
99
- #### Variations (`products.variations`)
100
- | Method | Description |
101
- |--------|-------------|
102
- | `findProductVariations` | Find product variations |
103
- | `createVariation` | Add a variation |
104
- | `updateVariation` | Update a variation |
105
- | `deleteVariation` | Remove a variation |
106
-
107
- ### Constants
108
-
109
- | Export | Description |
110
- |--------|-------------|
111
- | `ProductType` | Product types (SimpleProduct, ConfigurableProduct, BundleProduct, PlanProduct, TokenizedProduct) |
112
- | `ProductStatus` | Product status values (ACTIVE, DRAFT) |
113
-
114
- ### Types
115
-
116
- | Export | Description |
117
- |--------|-------------|
118
- | `Product` | Product document type |
119
- | `ProductQuery` | Query parameters type |
120
- | `ProductsModule` | Module interface type |
121
-
122
- ## Events
33
+ `create` returns the product document, and `publish` accepts that document. The module exposes `media`, `prices`, `reviews`, `texts`, `variations`, `assignments`, and `bundleItems` submodules. Catalog prices are written as `commerce.pricing` entries with `minQuantity` tiers; computed pricing is coordinated by the core pricing services and plugins.
123
34
 
124
- | Event | Description |
125
- |-------|-------------|
126
- | `PRODUCT_CREATE` | Product created |
127
- | `PRODUCT_UPDATE` | Product updated |
128
- | `PRODUCT_REMOVE` | Product deleted |
129
- | `PRODUCT_PUBLISH` | Product published |
130
- | `PRODUCT_UNPUBLISH` | Product unpublished |
35
+ See the [module guide](https://docs.unchained.shop/platform-configuration/modules/products), [pricing guide](https://docs.unchained.shop/concepts/pricing-system), [public exports](src/products-index.ts), and [module implementation](src/module/configureProductsModule.ts).
131
36
 
132
37
  ## License
133
38
 
@@ -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;
@@ -63,9 +63,9 @@ export interface ProductCommerce {
63
63
  pricing: ProductPrice[];
64
64
  }
65
65
  export interface ProductTokenization {
66
- contractAddress: string;
66
+ contractAddress?: string;
67
67
  contractStandard: ProductContractStandard;
68
- tokenId: string;
68
+ tokenId?: string;
69
69
  supply: number;
70
70
  ercMetadataProperties?: Record<string, any>;
71
71
  }
@@ -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,38 @@ 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: { status: 1, sequence: 1, published: -1 } },
48
45
  { index: { slugs: 1 } },
49
- { index: { status: 1 } },
50
46
  { index: { tags: 1 } },
51
- { index: { 'warehousing.sku': 1 } },
52
- ]);
47
+ { index: { 'warehousing.sku': 1 }, options: { sparse: true } },
48
+ { index: { 'bundleItems.productId': 1 }, options: { sparse: true } },
49
+ { index: { 'proxy.assignments.productId': 1 }, options: { sparse: true } },
50
+ ], { rebuild: false });
53
51
  await buildDbIndexes(ProductTexts, [
54
52
  { index: { productId: 1 } },
55
- { index: { locale: 1 } },
56
53
  { index: { slug: 1 } },
57
54
  { index: { locale: 1, productId: 1 } },
58
55
  ]);
@@ -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',
@@ -54,7 +54,7 @@ export const configureProductMediaModule = async ({ db }) => {
54
54
  const mediaList = ProductMedias.find(selector, {
55
55
  skip: offset,
56
56
  limit,
57
- sort: { sortKey: 1 },
57
+ sort: { sortKey: 1, _id: 1 },
58
58
  ...options,
59
59
  });
60
60
  return mediaList.toArray();
@@ -64,7 +64,7 @@ export const configureProductMediaModule = async ({ db }) => {
64
64
  const lastProductMedia = (await ProductMedias.findOne({
65
65
  productId: doc.productId,
66
66
  }, {
67
- sort: { sortKey: -1 },
67
+ sort: { sortKey: -1, _id: -1 },
68
68
  })) || { sortKey: 0 };
69
69
  sortKey = lastProductMedia.sortKey + 1;
70
70
  }
@@ -123,7 +123,7 @@ export const configureProductMediaModule = async ({ db }) => {
123
123
  }));
124
124
  const productMedias = await ProductMedias.find({
125
125
  _id: { $in: changedProductMediaIds },
126
- }, { sort: { sortKey: 1 } }).toArray();
126
+ }, { sort: { sortKey: 1, _id: 1 } }).toArray();
127
127
  await emit('PRODUCT_REORDER_MEDIA', { productMedias });
128
128
  return productMedias;
129
129
  },
@@ -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
  },
@@ -106,7 +108,7 @@ export const configureProductPricesModule = ({ proxyProducts, db, }) => {
106
108
  ],
107
109
  timestamp: { $lte: referenceDate },
108
110
  expiresAt: { $gte: referenceDate },
109
- }, { sort: { timestamp: -1 } });
111
+ }, { sort: { timestamp: -1, _id: -1 } });
110
112
  if (!mostRecentCurrencyRate)
111
113
  return null;
112
114
  const rate = normalizeRate(baseCurrency, quoteCurrency, mostRecentCurrencyRate);
@@ -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) {
@@ -1,6 +1,6 @@
1
1
  import { mongodb, type ModuleInput } from '@unchainedshop/mongodb';
2
2
  import { type SortOption, type Price } from '@unchainedshop/utils';
3
- import { type Product, type ProductAssignment, type ProductBundleItem, type ProductConfiguration, ProductStatus } from '../db/ProductsCollection.ts';
3
+ import { type Product, type ProductAssignment, type ProductBundleItem, type ProductConfiguration, ProductStatus, ProductType } from '../db/ProductsCollection.ts';
4
4
  import { type ProductsSettingsOptions } from '../products-settings.ts';
5
5
  export interface ProductQuery {
6
6
  queryString?: string;
@@ -11,6 +11,7 @@ export interface ProductQuery {
11
11
  slugs?: string[];
12
12
  tags?: string[];
13
13
  skus?: string[];
14
+ type?: ProductType;
14
15
  bundleItemProductIds?: string[];
15
16
  proxyAssignmentProductIds?: string[];
16
17
  }
@@ -22,7 +23,7 @@ export interface ProductDiscount {
22
23
  discountKey: string;
23
24
  context?: any;
24
25
  }
25
- export declare const buildFindSelector: ({ slugs, tags, includeDrafts, includeDeleted, productIds, productSelector, queryString, skus, bundleItemProductIds, proxyAssignmentProductIds, }: ProductQuery) => mongodb.Filter<Product>;
26
+ export declare const buildFindSelector: ({ slugs, tags, includeDrafts, includeDeleted, productIds, productSelector, queryString, skus, type, bundleItemProductIds, proxyAssignmentProductIds, }: ProductQuery) => mongodb.Filter<Product>;
26
27
  export declare const configureProductsModule: (moduleInput: ModuleInput<ProductsSettingsOptions>) => Promise<{
27
28
  findProduct: (params: {
28
29
  productId: string;
@@ -80,7 +81,7 @@ export declare const configureProductsModule: (moduleInput: ModuleInput<Products
80
81
  countryCode: string;
81
82
  }) => Promise<{
82
83
  minQuantity: number;
83
- maxQuantity: number;
84
+ maxQuantity: number | null;
84
85
  price: import("../db/ProductsCollection.ts").ProductPrice;
85
86
  }[]>;
86
87
  rates: {
@@ -119,6 +120,21 @@ export declare const configureProductsModule: (moduleInput: ModuleInput<Products
119
120
  }) => Promise<number>;
120
121
  publish: (product: Product) => Promise<boolean>;
121
122
  unpublish: (product: Product) => Promise<boolean>;
123
+ bulkPublish: (productIds: string[]) => Promise<{
124
+ successIds: string[];
125
+ failedIds: string[];
126
+ }>;
127
+ bulkUnpublish: (productIds: string[]) => Promise<{
128
+ successIds: string[];
129
+ failedIds: string[];
130
+ }>;
131
+ bulkUpdateTags: (productIds: string[], { add, remove }: {
132
+ add?: string[];
133
+ remove?: string[];
134
+ }) => Promise<{
135
+ successIds: string[];
136
+ failedIds: string[];
137
+ }>;
122
138
  assignments: {
123
139
  addProxyAssignment: ({ productId, proxyId, vectors, }: {
124
140
  productId: string;
@@ -1,6 +1,6 @@
1
1
  import { emit, registerEvents } from '@unchainedshop/events';
2
- import { findPreservingIds, generateDbFilterById, buildSortOptions, mongodb, generateDbObjectId, assertDocumentDBCompatMode, } from '@unchainedshop/mongodb';
3
- import { SortDirection } from '@unchainedshop/utils';
2
+ import { findPreservingIds, generateDbFilterById, buildSortOptions, mongodb, generateDbObjectId, } from '@unchainedshop/mongodb';
3
+ import { executeBulkOperation, SortDirection } from '@unchainedshop/utils';
4
4
  import { ProductsCollection, ProductStatus, ProductType, } from "../db/ProductsCollection.js";
5
5
  import { configureProductMediaModule } from "./configureProductMediaModule.js";
6
6
  import { configureProductPricesModule } from "./configureProductPrices.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,11 +24,15 @@ const PRODUCT_EVENTS = [
23
24
  const InternalProductStatus = {
24
25
  DRAFT: null,
25
26
  };
26
- export const buildFindSelector = ({ slugs, tags, includeDrafts = false, includeDeleted = false, productIds, productSelector, queryString, skus, bundleItemProductIds, proxyAssignmentProductIds, }) => {
27
+ const isDraftStatus = (status) => status === ProductStatus.DRAFT || status === InternalProductStatus.DRAFT;
28
+ export const buildFindSelector = ({ slugs, tags, includeDrafts = false, includeDeleted = false, productIds, productSelector, queryString, skus, type, bundleItemProductIds, proxyAssignmentProductIds, }) => {
27
29
  const selector = productSelector ? { ...productSelector } : {};
28
30
  if (productIds && !selector._id) {
29
31
  selector._id = { $in: productIds };
30
32
  }
33
+ if (type && !selector.type) {
34
+ selector.type = type;
35
+ }
31
36
  if (slugs && !selector.slugs) {
32
37
  selector.slugs = { $in: slugs };
33
38
  }
@@ -53,7 +58,6 @@ export const buildFindSelector = ({ slugs, tags, includeDrafts = false, includeD
53
58
  selector.$or = orConditions;
54
59
  }
55
60
  if (queryString && !selector.$text) {
56
- assertDocumentDBCompatMode();
57
61
  selector.$text = { $search: queryString };
58
62
  }
59
63
  if (!selector.status) {
@@ -70,10 +74,11 @@ export const buildFindSelector = ({ slugs, tags, includeDrafts = false, includeD
70
74
  return selector;
71
75
  };
72
76
  export const configureProductsModule = async (moduleInput) => {
73
- const { db, options: productsOptions = {} } = moduleInput;
77
+ const { db, migrationRepository, options: productsOptions = {} } = moduleInput;
74
78
  registerEvents(PRODUCT_EVENTS);
75
79
  await productsSettings.configureSettings(productsOptions);
76
80
  const { Products, ProductTexts } = await ProductsCollection(db);
81
+ migrateCommercePricingToMinQuantity(migrationRepository);
77
82
  const productTexts = configureProductTextsModule({
78
83
  Products,
79
84
  ProductTexts,
@@ -95,7 +100,7 @@ export const configureProductsModule = async (moduleInput) => {
95
100
  return deletedResult.deletedCount;
96
101
  };
97
102
  const publishProduct = async (product) => {
98
- if (product.status === InternalProductStatus.DRAFT) {
103
+ if (isDraftStatus(product.status)) {
99
104
  await Products.updateOne(generateDbFilterById(product._id), {
100
105
  $set: {
101
106
  status: ProductStatus.ACTIVE,
@@ -124,6 +129,16 @@ export const configureProductsModule = async (moduleInput) => {
124
129
  }
125
130
  return false;
126
131
  };
132
+ const updateProduct = async (productId, doc) => {
133
+ const product = await Products.findOneAndUpdate(generateDbFilterById(productId), {
134
+ $set: {
135
+ updated: new Date(),
136
+ ...doc,
137
+ },
138
+ }, { returnDocument: 'after' });
139
+ await emit('PRODUCT_UPDATE', { productId, ...doc, product });
140
+ return productId;
141
+ };
127
142
  const proxyProducts = async (product, vectors = [], { includeInactive = false } = {}) => {
128
143
  const { proxy } = product;
129
144
  let filtered = [...(proxy?.assignments || [])];
@@ -147,7 +162,7 @@ export const configureProductsModule = async (moduleInput) => {
147
162
  return {
148
163
  findProduct: async (params) => {
149
164
  if ('sku' in params) {
150
- return Products.findOne({ 'warehousing.sku': params.sku }, { sort: { sequence: 1 } });
165
+ return Products.findOne({ 'warehousing.sku': params.sku }, { sort: { sequence: 1, _id: 1 } });
151
166
  }
152
167
  if ('slug' in params && params.slug != null) {
153
168
  return Products.findOne({ slugs: params.slug }, {});
@@ -188,7 +203,7 @@ export const configureProductsModule = async (moduleInput) => {
188
203
  return product.status === ProductStatus.ACTIVE;
189
204
  },
190
205
  isDraft: (product) => {
191
- return product.status === ProductStatus.DRAFT || product.status === InternalProductStatus.DRAFT;
206
+ return isDraftStatus(product.status);
192
207
  },
193
208
  normalizedStatus: (product) => {
194
209
  return product.status === null ? ProductStatus.DRAFT : product.status;
@@ -258,17 +273,7 @@ export const configureProductsModule = async (moduleInput) => {
258
273
  await emit('PRODUCT_CREATE', { product });
259
274
  return product;
260
275
  },
261
- update: async (productId, doc) => {
262
- const updateDoc = doc;
263
- const product = await Products.findOneAndUpdate(generateDbFilterById(productId), {
264
- $set: {
265
- updated: new Date(),
266
- ...updateDoc,
267
- },
268
- }, { returnDocument: 'after' });
269
- await emit('PRODUCT_UPDATE', { productId, ...updateDoc, product });
270
- return productId;
271
- },
276
+ update: updateProduct,
272
277
  firstActiveProductProxy: async (productId) => {
273
278
  return Products.findOne({ 'proxy.assignments.productId': productId });
274
279
  },
@@ -290,6 +295,31 @@ export const configureProductsModule = async (moduleInput) => {
290
295
  deleteProductPermanently,
291
296
  publish: publishProduct,
292
297
  unpublish: unpublishProduct,
298
+ bulkPublish: async (productIds) => executeBulkOperation(productIds, async (productId) => {
299
+ const product = await Products.findOne(generateDbFilterById(productId), {});
300
+ if (!product || !(await publishProduct(product)))
301
+ throw new Error('publish-failed');
302
+ }),
303
+ bulkUnpublish: async (productIds) => executeBulkOperation(productIds, async (productId) => {
304
+ const product = await Products.findOne(generateDbFilterById(productId), {});
305
+ if (!product || !(await unpublishProduct(product)))
306
+ throw new Error('unpublish-failed');
307
+ }),
308
+ bulkUpdateTags: async (productIds, { add = [], remove = [] }) => {
309
+ const tagsToRemove = new Set(remove);
310
+ return executeBulkOperation(productIds, async (productId) => {
311
+ const product = await Products.findOne(generateDbFilterById(productId), {});
312
+ if (!product || (product.status !== ProductStatus.ACTIVE && !isDraftStatus(product.status))) {
313
+ throw new Error('not-found');
314
+ }
315
+ const tags = (product.tags || []).filter((tag) => !tagsToRemove.has(tag));
316
+ for (const tag of add) {
317
+ if (!tags.includes(tag))
318
+ tags.push(tag);
319
+ }
320
+ await updateProduct(productId, { tags });
321
+ });
322
+ },
293
323
  assignments: {
294
324
  addProxyAssignment: async ({ productId, proxyId, vectors, }) => {
295
325
  const assignment = {
@@ -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,10 @@
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.10",
5
+ "files": [
6
+ "lib"
7
+ ],
5
8
  "main": "lib/products-index.js",
6
9
  "types": "lib/products-index.d.ts",
7
10
  "type": "module",
@@ -35,11 +38,13 @@
35
38
  },
36
39
  "homepage": "https://github.com/unchainedshop/unchained#readme",
37
40
  "dependencies": {
38
- "@unchainedshop/events": "^5.0.0-alpha.1",
39
- "@unchainedshop/utils": "^5.0.0-alpha.1"
41
+ "@unchainedshop/events": "^5.0.0-alpha.10",
42
+ "@unchainedshop/logger": "^5.0.0-alpha.10",
43
+ "@unchainedshop/mongodb": "^5.0.0-alpha.10",
44
+ "@unchainedshop/utils": "^5.0.0-alpha.10"
40
45
  },
41
46
  "devDependencies": {
42
- "@types/node": "^25.0.0",
43
- "typescript": "^5.8.3"
47
+ "@types/node": "^26.2.0",
48
+ "typescript": "^6.0.3"
44
49
  }
45
50
  }