@unchainedshop/core-orders 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,7 @@ export const OrderDeliveriesCollection = async (db) => {
8
8
  const OrderDeliveries = db.collection('order_deliveries');
9
9
  await buildDbIndexes(OrderDeliveries, [
10
10
  { index: { orderId: 1 } },
11
- { index: { orderId: 1, deliveryProviderId: 1 } },
11
+ { index: { deliveryProviderId: 1 } },
12
12
  ]);
13
13
  return OrderDeliveries;
14
14
  };
@@ -2,8 +2,8 @@ import { mongodb, buildDbIndexes } from '@unchainedshop/mongodb';
2
2
  export const OrderDiscountsCollection = async (db) => {
3
3
  const OrderDiscounts = db.collection('order_discounts');
4
4
  await buildDbIndexes(OrderDiscounts, [
5
- { index: { orderId: 1 } },
6
- { index: { trigger: 1 } },
5
+ { index: { orderId: 1, created: 1 } },
6
+ { index: { code: 1 }, options: { sparse: true } },
7
7
  ]);
8
8
  return OrderDiscounts;
9
9
  };
@@ -0,0 +1,10 @@
1
+ import { mongodb } from '@unchainedshop/mongodb';
2
+ export interface OrderLock {
3
+ key: string;
4
+ uniqueValue: string;
5
+ expireAt: Date;
6
+ }
7
+ export declare const OrderLocksCollection: (db: mongodb.Db) => Promise<mongodb.Collection<OrderLock>>;
8
+ export declare const acquireLock: (OrderLocks: mongodb.Collection<OrderLock>, key: string, ttl: number) => Promise<{
9
+ release: () => Promise<void>;
10
+ }>;
@@ -0,0 +1,40 @@
1
+ import { mongodb, buildDbIndexes } from '@unchainedshop/mongodb';
2
+ import { setTimeout as sleep } from 'node:timers/promises';
3
+ const DUPLICATE_KEY = 11000;
4
+ const LOCK_RETRIES = 10;
5
+ const LOCK_RETRY_DELAY_MS = 200;
6
+ export const OrderLocksCollection = async (db) => {
7
+ const OrderLocks = db.collection('locco-locks');
8
+ const success = await buildDbIndexes(OrderLocks, [
9
+ { index: { key: 1 }, options: { unique: true } },
10
+ { index: { expireAt: 1 }, options: { expireAfterSeconds: 0 } },
11
+ ], { rebuild: false });
12
+ if (!success) {
13
+ throw new Error('Could not ensure the unique index backing order locks, refusing to start');
14
+ }
15
+ return OrderLocks;
16
+ };
17
+ export const acquireLock = async (OrderLocks, key, ttl) => {
18
+ const uniqueValue = crypto.randomUUID();
19
+ for (let attempt = 0; attempt < LOCK_RETRIES; attempt += 1) {
20
+ try {
21
+ await OrderLocks.updateOne({ key, expireAt: { $lt: new Date() } }, { $set: { key, uniqueValue, expireAt: new Date(Date.now() + ttl) } }, { upsert: true });
22
+ return {
23
+ release: async () => {
24
+ try {
25
+ await OrderLocks.deleteOne({ key, uniqueValue, expireAt: { $gt: new Date() } });
26
+ }
27
+ catch {
28
+ }
29
+ },
30
+ };
31
+ }
32
+ catch (error) {
33
+ if (error?.code !== DUPLICATE_KEY)
34
+ throw error;
35
+ if (attempt < LOCK_RETRIES - 1)
36
+ await sleep(LOCK_RETRY_DELAY_MS);
37
+ }
38
+ }
39
+ throw new Error(`Could not acquire lock ${key}`);
40
+ };
@@ -8,9 +8,8 @@ export const OrderPaymentsCollection = async (db) => {
8
8
  const OrderPayments = db.collection('order_payments');
9
9
  await buildDbIndexes(OrderPayments, [
10
10
  { index: { orderId: 1 } },
11
- {
12
- index: { orderId: 1, paymentProviderId: 1 },
13
- },
11
+ { index: { paymentProviderId: 1 } },
12
+ { index: { transactionId: 1 }, options: { sparse: true } },
14
13
  ]);
15
14
  return OrderPayments;
16
15
  };
@@ -2,8 +2,8 @@ import { mongodb, buildDbIndexes } from '@unchainedshop/mongodb';
2
2
  export const OrderPositionsCollection = async (db) => {
3
3
  const OrderPositions = db.collection('order_positions');
4
4
  await buildDbIndexes(OrderPositions, [
5
+ { index: { orderId: 1, created: 1 } },
5
6
  { index: { productId: 1 } },
6
- { index: { orderId: 1 } },
7
7
  ]);
8
8
  return OrderPositions;
9
9
  };
@@ -1,4 +1,4 @@
1
- import { mongodb, buildDbIndexes, isDocumentDBCompatModeEnabled, } from '@unchainedshop/mongodb';
1
+ import { mongodb, buildDbIndexes, } from '@unchainedshop/mongodb';
2
2
  export const OrderStatus = {
3
3
  PENDING: 'PENDING',
4
4
  CONFIRMED: 'CONFIRMED',
@@ -7,36 +7,33 @@ export const OrderStatus = {
7
7
  };
8
8
  export const OrdersCollection = async (db) => {
9
9
  const Orders = db.collection('orders');
10
- if (!isDocumentDBCompatModeEnabled()) {
11
- await buildDbIndexes(Orders, [
12
- {
13
- index: {
14
- _id: 'text',
15
- userId: 'text',
16
- orderNumber: 'text',
17
- status: 'text',
18
- 'contact.emailAddress': 'text',
19
- 'contact.telNumber': 'text',
20
- },
21
- options: {
22
- weights: {
23
- _id: 8,
24
- userId: 3,
25
- orderNumber: 6,
26
- 'contact.telNumber': 5,
27
- 'contact.emailAddress': 4,
28
- status: 1,
29
- },
30
- name: 'order_fulltext_search',
10
+ await buildDbIndexes(Orders, [
11
+ {
12
+ index: {
13
+ _id: 'text',
14
+ userId: 'text',
15
+ orderNumber: 'text',
16
+ status: 'text',
17
+ 'contact.emailAddress': 'text',
18
+ 'contact.telNumber': 'text',
19
+ },
20
+ options: {
21
+ weights: {
22
+ _id: 8,
23
+ userId: 3,
24
+ orderNumber: 6,
25
+ 'contact.telNumber': 5,
26
+ 'contact.emailAddress': 4,
27
+ status: 1,
31
28
  },
29
+ name: 'order_fulltext_search',
32
30
  },
33
- ]);
34
- }
31
+ },
32
+ ]);
35
33
  await buildDbIndexes(Orders, [
36
- { index: { deleted: 1 } },
37
- { index: { userId: 1 } },
38
- { index: { status: 1 } },
39
- { index: { orderNumber: 1 } },
34
+ { index: { userId: 1, status: 1 } },
35
+ { index: { status: 1, updated: 1 } },
36
+ { index: { orderNumber: 1 }, options: { sparse: true } },
40
37
  ]);
41
38
  return Orders;
42
39
  };
@@ -0,0 +1,2 @@
1
+ import type { MigrationRepository } from '@unchainedshop/mongodb';
2
+ export default function normalizeContactPhone(repository: MigrationRepository): void;
@@ -0,0 +1,27 @@
1
+ import { normalizePhoneNumber } from '@unchainedshop/utils';
2
+ import { OrdersCollection } from "../orders-index.js";
3
+ export default function normalizeContactPhone(repository) {
4
+ repository?.register({
5
+ id: 20260625120000,
6
+ name: 'Normalize order.contact.telNumber to E.164 format',
7
+ up: async ({ logger }) => {
8
+ const Orders = await OrdersCollection(repository.db);
9
+ const orders = await Orders.find({ 'contact.telNumber': { $exists: true, $nin: [null, ''] } }, { projection: { _id: true, contact: true, billingAddress: true, countryCode: true } }).toArray();
10
+ let changed = 0;
11
+ let skipped = 0;
12
+ for (const order of orders) {
13
+ const current = order.contact?.telNumber;
14
+ const defaultCountry = order.billingAddress?.countryCode || order.countryCode;
15
+ const normalized = normalizePhoneNumber(current, defaultCountry);
16
+ if (!normalized || normalized === current) {
17
+ if (!normalized)
18
+ skipped += 1;
19
+ continue;
20
+ }
21
+ await Orders.updateOne({ _id: order._id }, { $set: { 'contact.telNumber': normalized } });
22
+ changed += 1;
23
+ }
24
+ logger?.info(`Normalize order.contact.telNumber: ${changed} updated, ${skipped} left unchanged (unparseable)`);
25
+ },
26
+ });
27
+ }
@@ -1,4 +1,4 @@
1
- import { assertDocumentDBCompatMode, mongodb } from '@unchainedshop/mongodb';
1
+ import { mongodb } from '@unchainedshop/mongodb';
2
2
  export const buildFindSelector = ({ includeCarts, status, userId, queryString, paymentIds, deliveryIds, dateRange, orderIds, }) => {
3
3
  const selector = {};
4
4
  if (userId) {
@@ -30,7 +30,6 @@ export const buildFindSelector = ({ includeCarts, status, userId, queryString, p
30
30
  selector.status = { $ne: null };
31
31
  }
32
32
  if (queryString) {
33
- assertDocumentDBCompatMode();
34
33
  selector.$text = { $search: queryString };
35
34
  }
36
35
  return selector;
@@ -14,7 +14,7 @@ export const configureOrderDiscountsModule = ({ OrderDiscounts, }) => {
14
14
  return OrderDiscounts.findOne(buildFindOrderDiscountByIdSelector(discountId), options);
15
15
  },
16
16
  findOrderDiscounts: async ({ orderId }) => {
17
- const discounts = OrderDiscounts.find({ orderId });
17
+ const discounts = OrderDiscounts.find({ orderId }, { sort: { created: 1 } });
18
18
  return discounts.toArray();
19
19
  },
20
20
  create: async (doc) => {
@@ -14,7 +14,7 @@ export const configureOrderPositionsModule = ({ OrderPositions, }) => {
14
14
  return OrderPositions.findOne(buildFindOrderPositionByIdSelector(itemId), options);
15
15
  },
16
16
  findOrderPositions: async ({ orderId }) => {
17
- const positions = OrderPositions.find({ orderId, quantity: { $gt: 0 } });
17
+ const positions = OrderPositions.find({ orderId, quantity: { $gt: 0 } }, { sort: { created: 1 } });
18
18
  return positions.toArray();
19
19
  },
20
20
  delete: async (orderPositionId) => {
@@ -1,4 +1,5 @@
1
1
  import { emit, registerEvents } from '@unchainedshop/events';
2
+ import { normalizePhoneNumber } from '@unchainedshop/utils';
2
3
  import { generateDbFilterById, generateDbObjectId, mongodb, } from '@unchainedshop/mongodb';
3
4
  import { OrderStatus } from "../db/OrdersCollection.js";
4
5
  const ORDER_EVENTS = [
@@ -10,6 +11,14 @@ const ORDER_EVENTS = [
10
11
  ];
11
12
  export const configureOrderModuleMutations = ({ Orders, OrderPositions, }) => {
12
13
  registerEvents(ORDER_EVENTS);
14
+ const normalizeContactPhone = (contact, defaultCountry) => {
15
+ if (!contact?.telNumber)
16
+ return contact;
17
+ return {
18
+ ...contact,
19
+ telNumber: normalizePhoneNumber(contact.telNumber, defaultCountry) || contact.telNumber,
20
+ };
21
+ };
13
22
  return {
14
23
  create: async ({ userId, orderNumber, currencyCode, countryCode, billingAddress, contact, context, }) => {
15
24
  const { insertedId: orderId } = await Orders.insertOne({
@@ -17,7 +26,7 @@ export const configureOrderModuleMutations = ({ Orders, OrderPositions, }) => {
17
26
  created: new Date(),
18
27
  status: null,
19
28
  billingAddress,
20
- contact,
29
+ contact: normalizeContactPhone(contact, billingAddress?.countryCode || countryCode),
21
30
  userId,
22
31
  currencyCode,
23
32
  countryCode,
@@ -66,9 +75,13 @@ export const configureOrderModuleMutations = ({ Orders, OrderPositions, }) => {
66
75
  },
67
76
  updateContact: async (orderId, contact) => {
68
77
  const selector = generateDbFilterById(orderId);
78
+ const existing = await Orders.findOne(selector, {
79
+ projection: { billingAddress: true, countryCode: true },
80
+ });
81
+ const defaultCountry = existing?.billingAddress?.countryCode || existing?.countryCode;
69
82
  const order = await Orders.findOneAndUpdate(selector, {
70
83
  $set: {
71
- contact,
84
+ contact: normalizeContactPhone(contact, defaultCountry),
72
85
  updated: new Date(),
73
86
  },
74
87
  }, { returnDocument: 'after' });
@@ -113,7 +126,14 @@ export const configureOrderModuleMutations = ({ Orders, OrderPositions, }) => {
113
126
  $set.billingAddress = updates.billingAddress;
114
127
  }
115
128
  if (updates.contact) {
116
- $set.contact = updates.contact;
129
+ let defaultCountry = updates.billingAddress?.countryCode;
130
+ if (!defaultCountry && updates.contact.telNumber) {
131
+ const existing = await Orders.findOne(generateDbFilterById(orderId), {
132
+ projection: { billingAddress: true, countryCode: true },
133
+ });
134
+ defaultCountry = existing?.billingAddress?.countryCode || existing?.countryCode;
135
+ }
136
+ $set.contact = normalizeContactPhone(updates.contact, defaultCountry);
117
137
  }
118
138
  if (updates.meta && Object.keys(updates.meta).length > 0) {
119
139
  const contextSetters = Object.fromEntries(Object.entries(updates.meta).map(([key, value]) => [`context.${key}`, value]));
@@ -48,12 +48,16 @@ export declare const configureOrdersModuleQueries: ({ Orders }: {
48
48
  orderNumber?: string;
49
49
  userId: string;
50
50
  }) => Promise<mongodb.WithId<Order> | null>;
51
+ findCarts: ({ userIds }: {
52
+ userIds: string[];
53
+ }, options?: mongodb.FindOptions) => Promise<Order[]>;
51
54
  count: (query: OrderQuery) => Promise<number>;
52
55
  findOrder: ({ orderId, orderNumber, }: {
53
56
  orderId?: string;
54
57
  orderNumber?: string;
55
58
  }, options?: mongodb.FindOptions) => Promise<Order | null>;
56
- findCartsToInvalidate: (maxAgeDays?: number) => Promise<mongodb.WithId<Order>[]>;
59
+ findCartUserIds: () => Promise<string[]>;
60
+ findCartIdsToInvalidate: (maxAgeDays?: number) => Promise<string[]>;
57
61
  findOrders: ({ limit, offset, queryString, sort, ...query }: OrderQuery & {
58
62
  limit?: number;
59
63
  offset?: number;
@@ -33,6 +33,9 @@ export const configureOrdersModuleQueries = ({ Orders }) => {
33
33
  };
34
34
  return Orders.findOne(selector, options);
35
35
  },
36
+ findCarts: async ({ userIds }, options) => {
37
+ return Orders.find({ status: { $eq: null }, userId: { $in: userIds } }, { sort: { updated: -1 }, ...options }).toArray();
38
+ },
36
39
  count: async (query) => {
37
40
  const orderCount = await Orders.countDocuments(buildFindSelector(query));
38
41
  return orderCount;
@@ -41,14 +44,16 @@ export const configureOrdersModuleQueries = ({ Orders }) => {
41
44
  const selector = orderId ? generateDbFilterById(orderId) : { orderNumber };
42
45
  return Orders.findOne(selector, options);
43
46
  },
44
- findCartsToInvalidate: async (maxAgeDays = 30) => {
47
+ findCartUserIds: async () => {
48
+ return Orders.distinct('userId', { status: { $eq: null } });
49
+ },
50
+ findCartIdsToInvalidate: async (maxAgeDays = 30) => {
45
51
  const ONE_DAY_IN_MILLISECONDS = 86400000;
46
52
  const minValidDate = new Date(new Date().getTime() - maxAgeDays * ONE_DAY_IN_MILLISECONDS);
47
- const orders = await Orders.find({
53
+ return Orders.distinct('_id', {
48
54
  status: { $eq: null },
49
55
  updated: { $gte: minValidDate },
50
- }).toArray();
51
- return orders;
56
+ });
52
57
  },
53
58
  findOrders: async ({ limit, offset, queryString, sort, ...query }, options) => {
54
59
  const defaultSortOption = [{ key: 'created', value: SortDirection.DESC }];
@@ -105,7 +105,9 @@ export declare const configureOrdersModule: ({ db, migrationRepository, options:
105
105
  status: OrderStatus | null;
106
106
  info?: string;
107
107
  }) => Promise<mongodb.WithId<Order> | null>;
108
- acquireLock: (orderId: string, identifier: string, timeout?: number) => Promise<import("@kontsedal/locco").Lock>;
108
+ acquireLock: (orderId: string, identifier: string, timeout?: number) => Promise<{
109
+ release: () => Promise<void>;
110
+ }>;
109
111
  setDeliveryProvider: (orderId: string, deliveryProviderId: string) => Promise<mongodb.WithId<Order> | null>;
110
112
  setPaymentProvider: (orderId: string, paymentProviderId: string) => Promise<mongodb.WithId<Order> | null>;
111
113
  create: ({ userId, orderNumber, currencyCode, countryCode, billingAddress, contact, context, }: {
@@ -142,12 +144,16 @@ export declare const configureOrdersModule: ({ db, migrationRepository, options:
142
144
  orderNumber?: string;
143
145
  userId: string;
144
146
  }) => Promise<mongodb.WithId<Order> | null>;
147
+ findCarts: ({ userIds }: {
148
+ userIds: string[];
149
+ }, options?: mongodb.FindOptions) => Promise<Order[]>;
145
150
  count: (query: import("../db/OrdersCollection.ts").OrderQuery) => Promise<number>;
146
151
  findOrder: ({ orderId, orderNumber, }: {
147
152
  orderId?: string;
148
153
  orderNumber?: string;
149
154
  }, options?: mongodb.FindOptions) => Promise<Order | null>;
150
- findCartsToInvalidate: (maxAgeDays?: number) => Promise<mongodb.WithId<Order>[]>;
155
+ findCartUserIds: () => Promise<string[]>;
156
+ findCartIdsToInvalidate: (maxAgeDays?: number) => Promise<string[]>;
151
157
  findOrders: ({ limit, offset, queryString, sort, ...query }: import("../db/OrdersCollection.ts").OrderQuery & {
152
158
  limit?: number;
153
159
  offset?: number;
@@ -1,6 +1,6 @@
1
- import { Locker, MongoAdapter } from '@kontsedal/locco';
2
1
  import { generateDbFilterById, mongodb } from '@unchainedshop/mongodb';
3
2
  import { OrderDeliveriesCollection } from "../db/OrderDeliveriesCollection.js";
3
+ import { OrderLocksCollection, acquireLock } from "../db/OrderLocksCollection.js";
4
4
  import { OrderDiscountsCollection } from "../db/OrderDiscountsCollection.js";
5
5
  import { OrderPaymentsCollection } from "../db/OrderPaymentsCollection.js";
6
6
  import { OrderPositionsCollection } from "../db/OrderPositionsCollection.js";
@@ -14,6 +14,7 @@ import { configureOrderModuleMutations } from "./configureOrdersModule-mutations
14
14
  import { configureOrdersModuleQueries } from "./configureOrdersModule-queries.js";
15
15
  import { emit, registerEvents } from '@unchainedshop/events';
16
16
  import renameCurrencyCode from "../migrations/20250502111800-currency-code.js";
17
+ import normalizeOrderContactPhone from "../migrations/20260625120000-normalize-contact-phone.js";
17
18
  const ORDER_EVENTS = [
18
19
  'ORDER_CHECKOUT',
19
20
  'ORDER_CONFIRMED',
@@ -22,6 +23,7 @@ const ORDER_EVENTS = [
22
23
  ];
23
24
  export const configureOrdersModule = async ({ db, migrationRepository, options: orderOptions = {}, }) => {
24
25
  renameCurrencyCode(migrationRepository);
26
+ normalizeOrderContactPhone(migrationRepository);
25
27
  registerEvents(ORDER_EVENTS);
26
28
  ordersSettings.configureSettings(orderOptions);
27
29
  const Orders = await OrdersCollection(db);
@@ -29,15 +31,7 @@ export const configureOrdersModule = async ({ db, migrationRepository, options:
29
31
  const OrderDiscounts = await OrderDiscountsCollection(db);
30
32
  const OrderPayments = await OrderPaymentsCollection(db);
31
33
  const OrderPositions = await OrderPositionsCollection(db);
32
- const mongoAdapter = new MongoAdapter({
33
- client: {
34
- db: () => db,
35
- },
36
- });
37
- const locker = new Locker({
38
- adapter: mongoAdapter,
39
- retrySettings: { retryDelay: 200, retryTimes: 10 },
40
- });
34
+ const OrderLocks = await OrderLocksCollection(db);
41
35
  const orderQueries = configureOrdersModuleQueries({ Orders });
42
36
  const orderMutations = configureOrderModuleMutations({
43
37
  Orders,
@@ -137,7 +131,7 @@ export const configureOrdersModule = async ({ db, migrationRepository, options:
137
131
  return modificationResult.value || Orders.findOne(selector, {});
138
132
  },
139
133
  acquireLock: async (orderId, identifier, timeout = 5000) => {
140
- return await locker.lock(`order:${identifier}:${orderId}`, timeout).acquire();
134
+ return acquireLock(OrderLocks, `order:${identifier}:${orderId}`, timeout);
141
135
  },
142
136
  setDeliveryProvider: async (orderId, deliveryProviderId) => {
143
137
  const delivery = await OrderDeliveries.findOne({
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unchainedshop/core-orders",
3
3
  "description": "Order management module for the Unchained Engine",
4
- "version": "5.0.0-alpha.1",
4
+ "version": "5.0.0-alpha.3",
5
5
  "main": "lib/orders-index.js",
6
6
  "types": "lib/orders-index.d.ts",
7
7
  "type": "module",
@@ -35,13 +35,12 @@
35
35
  },
36
36
  "homepage": "https://github.com/unchainedshop/unchained#readme",
37
37
  "dependencies": {
38
- "@kontsedal/locco": "^1.1.0",
39
38
  "@unchainedshop/events": "^5.0.0-alpha.1",
40
- "@unchainedshop/logger": "^5.0.0-alpha.1",
39
+ "@unchainedshop/mongodb": "^5.0.0-alpha.1",
41
40
  "@unchainedshop/utils": "^5.0.0-alpha.1"
42
41
  },
43
42
  "devDependencies": {
44
- "@types/node": "^25.0.0",
43
+ "@types/node": "^26.2.0",
45
44
  "typescript": "^5.8.3"
46
45
  }
47
46
  }