@labdigital/commercetools-mock 2.59.1 → 2.61.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 (222) hide show
  1. package/dist/{index.d.ts → index.d.mts} +154 -275
  2. package/dist/{index.js → index.mjs} +413 -401
  3. package/dist/index.mjs.map +1 -0
  4. package/package.json +30 -18
  5. package/src/config.ts +1 -1
  6. package/src/ctMock.test.ts +1 -1
  7. package/src/ctMock.ts +22 -21
  8. package/src/index.test.ts +1 -1
  9. package/src/index.ts +3 -3
  10. package/src/lib/haversine.test.ts +2 -2
  11. package/src/lib/masking.ts +1 -1
  12. package/src/lib/parser.ts +2 -2
  13. package/src/lib/password.ts +1 -1
  14. package/src/lib/predicateParser.test.ts +1 -1
  15. package/src/lib/predicateParser.ts +4 -4
  16. package/src/lib/product-review-statistics.test.ts +4 -8
  17. package/src/lib/productSearchFilter.test.ts +3 -3
  18. package/src/lib/productSearchFilter.ts +6 -6
  19. package/src/lib/projectionSearchFilter.test.ts +3 -3
  20. package/src/lib/projectionSearchFilter.ts +4 -4
  21. package/src/lib/review-statistics.ts +1 -1
  22. package/src/lib/searchQueryTypeChecker.test.ts +3 -3
  23. package/src/lib/searchQueryTypeChecker.ts +8 -4
  24. package/src/lib/tax.test.ts +119 -0
  25. package/src/lib/tax.ts +186 -0
  26. package/src/oauth/server.test.ts +7 -7
  27. package/src/oauth/server.ts +7 -7
  28. package/src/priceSelector.test.ts +1 -1
  29. package/src/priceSelector.ts +2 -2
  30. package/src/product-projection-search.ts +10 -12
  31. package/src/product-search-availability.test.ts +1 -1
  32. package/src/product-search.ts +6 -7
  33. package/src/projectAPI.test.ts +1 -1
  34. package/src/projectAPI.ts +7 -7
  35. package/src/repositories/abstract.ts +8 -10
  36. package/src/repositories/as-associate.test.ts +4 -4
  37. package/src/repositories/as-associate.ts +3 -3
  38. package/src/repositories/associate-role.ts +7 -9
  39. package/src/repositories/attribute-group.test.ts +3 -3
  40. package/src/repositories/attribute-group.ts +5 -5
  41. package/src/repositories/business-unit.test.ts +6 -6
  42. package/src/repositories/business-unit.ts +21 -23
  43. package/src/repositories/cart/actions.ts +79 -15
  44. package/src/repositories/cart/helpers.ts +5 -84
  45. package/src/repositories/cart/index.test.ts +53 -10
  46. package/src/repositories/cart/index.ts +17 -21
  47. package/src/repositories/cart-discount/actions.ts +5 -6
  48. package/src/repositories/cart-discount/index.ts +5 -5
  49. package/src/repositories/category/actions.ts +4 -4
  50. package/src/repositories/category/index.test.ts +3 -3
  51. package/src/repositories/category/index.ts +8 -8
  52. package/src/repositories/channel.test.ts +4 -4
  53. package/src/repositories/channel.ts +6 -6
  54. package/src/repositories/custom-object.ts +11 -8
  55. package/src/repositories/customer/actions.ts +9 -9
  56. package/src/repositories/customer/index.test.ts +3 -3
  57. package/src/repositories/customer/index.ts +12 -9
  58. package/src/repositories/customer-group.test.ts +4 -4
  59. package/src/repositories/customer-group.ts +6 -6
  60. package/src/repositories/discount-code/actions.ts +4 -4
  61. package/src/repositories/discount-code/index.ts +5 -5
  62. package/src/repositories/discount-group/actions.ts +3 -4
  63. package/src/repositories/discount-group/index.ts +4 -4
  64. package/src/repositories/errors.ts +1 -1
  65. package/src/repositories/extension.test.ts +3 -3
  66. package/src/repositories/extension.ts +6 -6
  67. package/src/repositories/helpers.ts +9 -12
  68. package/src/repositories/index.test.ts +3 -3
  69. package/src/repositories/index.ts +43 -43
  70. package/src/repositories/inventory-entry/actions.ts +15 -3
  71. package/src/repositories/inventory-entry/index.ts +5 -5
  72. package/src/repositories/my-customer.ts +5 -5
  73. package/src/repositories/my-order.ts +2 -2
  74. package/src/repositories/my-quote-request.ts +1 -1
  75. package/src/repositories/order/actions.ts +8 -9
  76. package/src/repositories/order/index.test.ts +191 -9
  77. package/src/repositories/order/index.ts +63 -21
  78. package/src/repositories/order-edit.ts +4 -4
  79. package/src/repositories/payment/actions.ts +6 -6
  80. package/src/repositories/payment/helpers.ts +3 -3
  81. package/src/repositories/payment/index.ts +7 -7
  82. package/src/repositories/product/actions.ts +7 -7
  83. package/src/repositories/product/helpers.ts +4 -4
  84. package/src/repositories/product/index.ts +13 -13
  85. package/src/repositories/product-discount.ts +9 -6
  86. package/src/repositories/product-projection.ts +7 -7
  87. package/src/repositories/product-selection.ts +9 -6
  88. package/src/repositories/product-tailoring.ts +6 -3
  89. package/src/repositories/product-type.ts +8 -5
  90. package/src/repositories/project.ts +5 -5
  91. package/src/repositories/quote/actions.ts +6 -6
  92. package/src/repositories/quote/index.ts +5 -5
  93. package/src/repositories/quote-request/actions.ts +6 -6
  94. package/src/repositories/quote-request/index.test.ts +3 -3
  95. package/src/repositories/quote-request/index.ts +5 -5
  96. package/src/repositories/quote-staged/actions.ts +6 -6
  97. package/src/repositories/quote-staged/index.ts +5 -5
  98. package/src/repositories/recurrence-policy/actions.ts +3 -3
  99. package/src/repositories/recurrence-policy/index.ts +4 -8
  100. package/src/repositories/recurring-order/actions.ts +3 -3
  101. package/src/repositories/recurring-order/index.ts +5 -5
  102. package/src/repositories/review.test.ts +5 -5
  103. package/src/repositories/review.ts +10 -9
  104. package/src/repositories/shipping-method/actions.ts +7 -9
  105. package/src/repositories/shipping-method/helpers.ts +1 -1
  106. package/src/repositories/shipping-method/index.ts +8 -8
  107. package/src/repositories/shopping-list/actions.ts +5 -5
  108. package/src/repositories/shopping-list/index.ts +7 -7
  109. package/src/repositories/standalone-price.ts +9 -6
  110. package/src/repositories/state.ts +9 -6
  111. package/src/repositories/store.ts +10 -7
  112. package/src/repositories/subscription.test.ts +3 -3
  113. package/src/repositories/subscription.ts +9 -6
  114. package/src/repositories/tax-category/actions.ts +4 -4
  115. package/src/repositories/tax-category/index.ts +6 -6
  116. package/src/repositories/type/actions.ts +4 -4
  117. package/src/repositories/type/index.ts +5 -5
  118. package/src/repositories/zone.test.ts +3 -3
  119. package/src/repositories/zone.ts +8 -5
  120. package/src/server.ts +4 -3
  121. package/src/services/abstract.ts +5 -5
  122. package/src/services/as-associate-cart.test.ts +1 -1
  123. package/src/services/as-associate-cart.ts +2 -2
  124. package/src/services/as-associate-order.test.ts +1 -1
  125. package/src/services/as-associate-order.ts +2 -2
  126. package/src/services/as-associate-quote-request.ts +2 -3
  127. package/src/services/as-associate.test.ts +1 -1
  128. package/src/services/as-associate.ts +4 -4
  129. package/src/services/associate-roles.test.ts +1 -1
  130. package/src/services/associate-roles.ts +2 -2
  131. package/src/services/attribute-group.test.ts +1 -1
  132. package/src/services/attribute-group.ts +2 -2
  133. package/src/services/business-units.test.ts +5 -5
  134. package/src/services/business-units.ts +2 -2
  135. package/src/services/cart-discount.ts +2 -2
  136. package/src/services/cart.test.ts +213 -2
  137. package/src/services/cart.ts +4 -5
  138. package/src/services/category.test.ts +1 -1
  139. package/src/services/category.ts +2 -2
  140. package/src/services/channel.test.ts +1 -1
  141. package/src/services/channel.ts +2 -2
  142. package/src/services/custom-object.test.ts +2 -2
  143. package/src/services/custom-object.ts +3 -3
  144. package/src/services/customer-group.test.ts +1 -1
  145. package/src/services/customer-group.ts +2 -2
  146. package/src/services/customer.test.ts +3 -3
  147. package/src/services/customer.ts +4 -5
  148. package/src/services/discount-code.test.ts +1 -1
  149. package/src/services/discount-code.ts +2 -2
  150. package/src/services/discount-group.test.ts +1 -1
  151. package/src/services/discount-group.ts +2 -2
  152. package/src/services/extension.test.ts +1 -1
  153. package/src/services/extension.ts +2 -2
  154. package/src/services/index.ts +44 -44
  155. package/src/services/inventory-entry.test.ts +16 -1
  156. package/src/services/inventory-entry.ts +2 -2
  157. package/src/services/my-business-unit.test.ts +1 -1
  158. package/src/services/my-business-unit.ts +2 -2
  159. package/src/services/my-cart.test.ts +1 -1
  160. package/src/services/my-cart.ts +2 -2
  161. package/src/services/my-customer.test.ts +2 -2
  162. package/src/services/my-customer.ts +6 -6
  163. package/src/services/my-order.ts +2 -2
  164. package/src/services/my-payment.test.ts +1 -1
  165. package/src/services/my-payment.ts +2 -2
  166. package/src/services/my-shopping-list.ts +2 -2
  167. package/src/services/order.test.ts +4 -11
  168. package/src/services/order.ts +4 -4
  169. package/src/services/payment.test.ts +1 -1
  170. package/src/services/payment.ts +2 -2
  171. package/src/services/product-discount.test.ts +1 -1
  172. package/src/services/product-discount.ts +2 -2
  173. package/src/services/product-projection.test.ts +2 -2
  174. package/src/services/product-projection.ts +4 -4
  175. package/src/services/product-selection.test.ts +1 -1
  176. package/src/services/product-selection.ts +2 -2
  177. package/src/services/product-type.test.ts +1 -1
  178. package/src/services/product-type.ts +2 -2
  179. package/src/services/product.test.ts +1 -1
  180. package/src/services/product.ts +3 -3
  181. package/src/services/project.test.ts +1 -1
  182. package/src/services/project.ts +4 -4
  183. package/src/services/quote-request.test.ts +2 -2
  184. package/src/services/quote-request.ts +2 -2
  185. package/src/services/quote-staged.ts +2 -2
  186. package/src/services/quote.ts +2 -2
  187. package/src/services/recurrence-policy.test.ts +1 -1
  188. package/src/services/recurrence-policy.ts +2 -2
  189. package/src/services/recurring-order.test.ts +1 -1
  190. package/src/services/recurring-order.ts +2 -2
  191. package/src/services/reviews.test.ts +1 -1
  192. package/src/services/reviews.ts +2 -2
  193. package/src/services/shipping-method.test.ts +2 -2
  194. package/src/services/shipping-method.ts +4 -4
  195. package/src/services/shopping-list.test.ts +1 -1
  196. package/src/services/shopping-list.ts +2 -2
  197. package/src/services/standalone-price.test.ts +1 -1
  198. package/src/services/standalone-price.ts +2 -2
  199. package/src/services/state.test.ts +1 -1
  200. package/src/services/state.ts +2 -2
  201. package/src/services/store.test.ts +1 -1
  202. package/src/services/store.ts +2 -2
  203. package/src/services/subscription.test.ts +1 -1
  204. package/src/services/subscription.ts +2 -2
  205. package/src/services/tax-category.test.ts +1 -1
  206. package/src/services/tax-category.ts +2 -2
  207. package/src/services/type.test.ts +1 -1
  208. package/src/services/type.ts +2 -2
  209. package/src/services/zone.test.ts +1 -1
  210. package/src/services/zone.ts +2 -2
  211. package/src/shipping.test.ts +1 -1
  212. package/src/shipping.ts +8 -8
  213. package/src/storage/abstract.ts +1 -1
  214. package/src/storage/in-memory.ts +15 -17
  215. package/src/storage/index.ts +2 -2
  216. package/src/testing/business-unit.ts +1 -2
  217. package/src/testing/customer.ts +1 -1
  218. package/src/testing/type.ts +1 -1
  219. package/src/types.ts +1 -1
  220. package/src/validate.ts +1 -1
  221. package/dist/index.d.ts.map +0 -1
  222. package/dist/index.js.map +0 -1
@@ -8,8 +8,8 @@ import auth from "basic-auth";
8
8
  import bodyParser from "body-parser";
9
9
  import { randomBytes } from "node:crypto";
10
10
  import { isDeepStrictEqual } from "node:util";
11
- import { Decimal } from "decimal.js";
12
- import { Decimal as Decimal$1 } from "decimal.js/decimal";
11
+ import { Decimal } from "decimal.js/decimal";
12
+ import { Decimal as Decimal$1 } from "decimal.js";
13
13
  import assert from "node:assert";
14
14
  import { z } from "zod";
15
15
  import { fromZodError } from "zod-validation-error";
@@ -36,8 +36,8 @@ var CommercetoolsError = class extends Error {
36
36
  //#region src/helpers.ts
37
37
  const getBaseResourceProperties = () => ({
38
38
  id: v4(),
39
- createdAt: new Date().toISOString(),
40
- lastModifiedAt: new Date().toISOString(),
39
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
40
+ lastModifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
41
41
  version: 0
42
42
  });
43
43
  /**
@@ -50,21 +50,20 @@ const nestedLookup = (obj, path) => {
50
50
  let val = obj;
51
51
  for (let i = 0; i < parts.length; i++) {
52
52
  const part = parts[i];
53
- if (val === void 0) return void 0;
53
+ if (val === void 0) return;
54
54
  val = val[part];
55
55
  }
56
56
  return val;
57
57
  };
58
58
  const queryParamsArray = (input) => {
59
- if (input === void 0) return void 0;
59
+ if (input === void 0) return;
60
60
  const values = Array.isArray(input) ? input : [input];
61
- if (values.length < 1) return void 0;
61
+ if (values.length < 1) return;
62
62
  return values;
63
63
  };
64
64
  const queryParamsValue = (value) => {
65
65
  const values = queryParamsArray(value);
66
66
  if (values && values.length > 0) return values[0];
67
- return void 0;
68
67
  };
69
68
  const cloneObject = (o) => JSON.parse(JSON.stringify(o));
70
69
  const mapHeaderType = (outgoingHttpHeaders) => {
@@ -80,7 +79,7 @@ const generateRandomString = (length) => {
80
79
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
81
80
  let result = "";
82
81
  for (let i = 0; i < length; i++) {
83
- const randomIndex = Math.floor(Math.random() * characters.length);
82
+ const randomIndex = Math.floor(Math.random() * 62);
84
83
  result += characters[randomIndex];
85
84
  }
86
85
  return result;
@@ -108,26 +107,22 @@ const hashPassword = (clearPassword) => Buffer.from(clearPassword).toString("bas
108
107
  const createPasswordResetToken = (customer, expiresAt) => Buffer.from(`${customer.id}:${PWRESET_SECRET}:${expiresAt.getTime()}`).toString("base64");
109
108
  const createEmailVerifyToken = (customer) => Buffer.from(`${customer.id}:${EMAIL_VERIFY_SECRET}:${v4()}`).toString("base64");
110
109
  const validatePasswordResetToken = (token) => {
111
- const items = Buffer.from(token, "base64").toString("utf-8").split(":");
112
- const [customerId, secret, time] = items;
113
- if (secret !== PWRESET_SECRET) return void 0;
114
- if (Number.parseInt(time) < new Date().getTime()) return void 0;
110
+ const [customerId, secret, time] = Buffer.from(token, "base64").toString("utf-8").split(":");
111
+ if (secret !== PWRESET_SECRET) return;
112
+ if (Number.parseInt(time, 10) < Date.now()) return;
115
113
  return customerId;
116
114
  };
117
115
  const validateEmailVerifyToken = (token) => {
118
- const items = Buffer.from(token, "base64").toString("utf-8").split(":");
119
- const [customerId, secret] = items;
120
- if (secret !== EMAIL_VERIFY_SECRET) return void 0;
116
+ const [customerId, secret] = Buffer.from(token, "base64").toString("utf-8").split(":");
117
+ if (secret !== EMAIL_VERIFY_SECRET) return;
121
118
  return customerId;
122
119
  };
123
120
 
124
121
  //#endregion
125
122
  //#region src/oauth/helpers.ts
126
123
  const getBearerToken = (request) => {
127
- const authHeader = request.header("Authorization");
128
- const match = authHeader?.match(/^Bearer\s(?<token>[^\s]+)$/);
124
+ const match = request.header("Authorization")?.match(/^Bearer\s(?<token>[^\s]+)$/);
129
125
  if (match) return match.groups?.token;
130
- return void 0;
131
126
  };
132
127
 
133
128
  //#endregion
@@ -177,7 +172,7 @@ var OAuth2Store = class {
177
172
  }
178
173
  refreshToken(clientId, clientSecret, refreshToken) {
179
174
  const existing = this.tokens.find((t) => t.refresh_token === refreshToken);
180
- if (!existing) return void 0;
175
+ if (!existing) return;
181
176
  const token = {
182
177
  ...existing,
183
178
  access_token: randomBytes(16).toString("base64")
@@ -192,8 +187,7 @@ var OAuth2Store = class {
192
187
  }
193
188
  validateToken(token) {
194
189
  if (!this.validate) return true;
195
- const foundToken = this.tokens.find((t) => t.access_token === token);
196
- if (foundToken) return true;
190
+ if (this.tokens.find((t) => t.access_token === token)) return true;
197
191
  return false;
198
192
  }
199
193
  };
@@ -346,8 +340,7 @@ var OAuth2Server = class {
346
340
  }, 400));
347
341
  if (grantType === "client_credentials") {
348
342
  const scope = request.query.scope?.toString() || request.body?.scope?.toString();
349
- const anonymous_id = void 0;
350
- const token = this.store.getAnonymousToken(projectKey, anonymous_id, scope);
343
+ const token = this.store.getAnonymousToken(projectKey, void 0, scope);
351
344
  response.status(200).send(token);
352
345
  return;
353
346
  }
@@ -372,8 +365,7 @@ var ProjectAPI = class {
372
365
  this.unsafeAdd(typeId, resource);
373
366
  }
374
367
  unsafeAdd(typeId, resource) {
375
- const repository = this._repositories[typeId];
376
- if (repository) this._storage.add(this.projectKey, typeId, {
368
+ if (this._repositories[typeId]) this._storage.add(this.projectKey, typeId, {
377
369
  ...getBaseResourceProperties(),
378
370
  ...resource
379
371
  });
@@ -463,7 +455,7 @@ var AbstractResourceRepository = class extends AbstractRepository {
463
455
  }, 400);
464
456
  checkConcurrentModification(current.version, version, resource.id);
465
457
  if (current.version === resource.version) throw new Error("Internal error: no changes to save");
466
- resource.lastModifiedAt = new Date().toISOString();
458
+ resource.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
467
459
  this._storage.add(context.projectKey, this.getTypeId(), resource);
468
460
  return resource;
469
461
  }
@@ -478,22 +470,16 @@ var AbstractUpdateHandler = class {
478
470
  const updatedResource = cloneObject(resource);
479
471
  const identifier = resource.id ? resource.id : resource.key;
480
472
  for (const action of actions) {
481
- if (this[action.action] === void 0) {
482
- console.info(`No handler for action ${action.action}`);
483
- throw new CommercetoolsError({
473
+ if (this[action.action] === void 0) throw new CommercetoolsError({
474
+ code: "InvalidInput",
475
+ message: `Invalid action ${action.action}`,
476
+ errors: [{
484
477
  code: "InvalidInput",
485
- message: `Invalid action ${action.action}`,
486
- errors: [{
487
- code: "InvalidInput",
488
- message: `Invalid action ${action.action}`
489
- }]
490
- });
491
- }
478
+ message: `Invalid action ${action.action}`
479
+ }]
480
+ });
492
481
  const updateFunc = this[action.action].bind(this);
493
- if (!updateFunc) {
494
- console.error(`No mock implemented for update action ${action.action}`);
495
- throw new Error(`No mock implemented for update action ${action.action}`);
496
- }
482
+ if (!updateFunc) throw new Error(`No mock implemented for update action ${action.action}`);
497
483
  const beforeUpdate = cloneObject(resource);
498
484
  updateFunc(context, updatedResource, action);
499
485
  if (!isDeepStrictEqual(beforeUpdate, updatedResource)) {
@@ -555,9 +541,9 @@ const createPrice = (draft) => ({
555
541
  */
556
542
  const roundDecimal = (decimal, roundingMode) => {
557
543
  switch (roundingMode) {
558
- case "HalfEven": return decimal.toDecimalPlaces(0, Decimal$1.ROUND_HALF_EVEN);
559
- case "HalfUp": return decimal.toDecimalPlaces(0, Decimal$1.ROUND_HALF_UP);
560
- case "HalfDown": return decimal.toDecimalPlaces(0, Decimal$1.ROUND_HALF_DOWN);
544
+ case "HalfEven": return decimal.toDecimalPlaces(0, Decimal.ROUND_HALF_EVEN);
545
+ case "HalfUp": return decimal.toDecimalPlaces(0, Decimal.ROUND_HALF_UP);
546
+ case "HalfDown": return decimal.toDecimalPlaces(0, Decimal.ROUND_HALF_DOWN);
561
547
  default: throw new Error(`Unknown rounding mode: ${roundingMode}`);
562
548
  }
563
549
  };
@@ -601,17 +587,15 @@ const createCentPrecisionMoney = (value) => {
601
587
  };
602
588
  };
603
589
  const createTypedMoney = (value) => {
604
- const result = createCentPrecisionMoney(value);
605
- return result;
590
+ return createCentPrecisionMoney(value);
606
591
  };
607
592
  const resolveStoreReference = (ref, projectKey, storage) => {
608
593
  if (!ref) return void 0;
609
594
  const resource = storage.getByResourceIdentifier(projectKey, ref);
610
595
  if (!resource) throw new Error("No such store");
611
- const store = resource;
612
596
  return {
613
597
  typeId: "store",
614
- key: store.key
598
+ key: resource.key
615
599
  };
616
600
  };
617
601
  const getReferenceFromResourceIdentifier = (resourceIdentifier, projectKey, storage) => {
@@ -686,6 +670,108 @@ const getBusinessUnitKeyReference = (id, projectKey, storage) => {
686
670
  };
687
671
  };
688
672
 
673
+ //#endregion
674
+ //#region src/lib/tax.ts
675
+ const calculateTaxTotals = (resource) => {
676
+ const taxedItemPrices = [];
677
+ resource.lineItems.forEach((item) => {
678
+ if (item.taxedPrice) taxedItemPrices.push(item.taxedPrice);
679
+ });
680
+ resource.customLineItems.forEach((item) => {
681
+ if (item.taxedPrice) taxedItemPrices.push(item.taxedPrice);
682
+ });
683
+ let taxedShippingPrice;
684
+ if (resource.shippingInfo?.taxedPrice) {
685
+ taxedShippingPrice = resource.shippingInfo.taxedPrice;
686
+ taxedItemPrices.push(resource.shippingInfo.taxedPrice);
687
+ }
688
+ if (!taxedItemPrices.length) return {
689
+ taxedPrice: void 0,
690
+ taxedShippingPrice
691
+ };
692
+ const currencyCode = resource.totalPrice.currencyCode;
693
+ const toMoney = (centAmount) => createCentPrecisionMoney({
694
+ currencyCode,
695
+ centAmount
696
+ });
697
+ let totalNet = 0;
698
+ let totalGross = 0;
699
+ let totalTax = 0;
700
+ const taxPortionsByRate = /* @__PURE__ */ new Map();
701
+ taxedItemPrices.forEach((price) => {
702
+ totalNet += price.totalNet.centAmount;
703
+ totalGross += price.totalGross.centAmount;
704
+ const priceTax = price.totalTax ? price.totalTax.centAmount : price.totalGross.centAmount - price.totalNet.centAmount;
705
+ totalTax += Math.max(priceTax, 0);
706
+ price.taxPortions?.forEach((portion) => {
707
+ const key = `${portion.rate}-${portion.name ?? ""}`;
708
+ const existing = taxPortionsByRate.get(key) ?? {
709
+ rate: portion.rate,
710
+ name: portion.name,
711
+ centAmount: 0
712
+ };
713
+ existing.centAmount += portion.amount.centAmount;
714
+ taxPortionsByRate.set(key, existing);
715
+ });
716
+ });
717
+ const taxPortions = Array.from(taxPortionsByRate.values()).map((portion) => ({
718
+ rate: portion.rate,
719
+ name: portion.name,
720
+ amount: toMoney(portion.centAmount)
721
+ }));
722
+ return {
723
+ taxedPrice: {
724
+ totalNet: toMoney(totalNet),
725
+ totalGross: toMoney(totalGross),
726
+ taxPortions,
727
+ totalTax: totalTax > 0 ? toMoney(totalTax) : void 0
728
+ },
729
+ taxedShippingPrice
730
+ };
731
+ };
732
+ const buildTaxedPriceFromRate = (amount, currencyCode, taxRate) => {
733
+ if (!taxRate) return;
734
+ const toMoney = (centAmount) => createCentPrecisionMoney({
735
+ type: "centPrecision",
736
+ currencyCode,
737
+ centAmount
738
+ });
739
+ let netAmount;
740
+ let grossAmount;
741
+ let taxAmount;
742
+ if (taxRate.includedInPrice) {
743
+ grossAmount = amount;
744
+ taxAmount = Math.round(grossAmount * taxRate.amount / (1 + taxRate.amount));
745
+ netAmount = grossAmount - taxAmount;
746
+ } else {
747
+ netAmount = amount;
748
+ taxAmount = Math.round(netAmount * taxRate.amount);
749
+ grossAmount = netAmount + taxAmount;
750
+ }
751
+ return {
752
+ totalNet: toMoney(netAmount),
753
+ totalGross: toMoney(grossAmount),
754
+ totalTax: taxAmount > 0 ? toMoney(taxAmount) : void 0,
755
+ taxPortions: taxAmount > 0 ? [{
756
+ rate: taxRate.amount,
757
+ name: taxRate.name,
758
+ amount: toMoney(taxAmount)
759
+ }] : []
760
+ };
761
+ };
762
+ const calculateTaxedPriceFromRate = (amount, currencyCode, taxRate) => buildTaxedPriceFromRate(amount, currencyCode, taxRate);
763
+ const calculateTaxedPrice = (amount, taxCategory, currency, country) => {
764
+ if (!taxCategory || !taxCategory.rates.length) return;
765
+ const taxedItemPrice = buildTaxedPriceFromRate(amount, currency, taxCategory.rates.find((rate) => !rate.country || rate.country === country) || taxCategory.rates[0]);
766
+ if (!taxedItemPrice) return;
767
+ return {
768
+ totalNet: taxedItemPrice.totalNet,
769
+ totalGross: taxedItemPrice.totalGross,
770
+ taxPortions: taxedItemPrice.taxPortions,
771
+ totalTax: taxedItemPrice.totalTax
772
+ };
773
+ };
774
+
689
775
  //#endregion
690
776
  //#region src/shipping.ts
691
777
  const markMatchingShippingRate = (cart, shippingRate) => {
@@ -724,11 +810,10 @@ const getShippingMethodsMatchingCart = (context, storage, cart, params = {}) =>
724
810
  code: "InvalidOperation",
725
811
  message: `The cart with ID '${cart.id}' does not have a shipping address set.`
726
812
  });
727
- const zones = storage.query(context.projectKey, "zone", {
813
+ const zoneIds = storage.query(context.projectKey, "zone", {
728
814
  where: [`locations(country="${cart.shippingAddress.country}"))`],
729
815
  limit: 100
730
- });
731
- const zoneIds = zones.results.map((zone) => zone.id);
816
+ }).results.map((zone) => zone.id);
732
817
  const shippingMethods = storage.query(context.projectKey, "shipping-method", {
733
818
  where: ["zoneRates(zone(id in (:zoneIds)))", `zoneRates(shippingRates(price(currencyCode="${cart.totalPrice.currencyCode}")))`],
734
819
  "var.zoneIds": zoneIds,
@@ -774,11 +859,11 @@ const createShippingInfoFromMethod = (context, storage, resource, method) => {
774
859
  };
775
860
  const totalGross = taxRate.includedInPrice ? shippingPrice : {
776
861
  ...shippingPrice,
777
- centAmount: roundDecimal(new Decimal(shippingPrice.centAmount).mul(1 + taxRate.amount), resource.taxRoundingMode || "HalfEven").toNumber()
862
+ centAmount: roundDecimal(new Decimal$1(shippingPrice.centAmount).mul(1 + taxRate.amount), resource.taxRoundingMode || "HalfEven").toNumber()
778
863
  };
779
864
  const totalNet = taxRate.includedInPrice ? {
780
865
  ...shippingPrice,
781
- centAmount: roundDecimal(new Decimal(shippingPrice.centAmount).div(1 + taxRate.amount), resource.taxRoundingMode || "HalfEven").toNumber()
866
+ centAmount: roundDecimal(new Decimal$1(shippingPrice.centAmount).div(1 + taxRate.amount), resource.taxRoundingMode || "HalfEven").toNumber()
782
867
  } : shippingPrice;
783
868
  const taxPortions = [{
784
869
  name: taxRate.name,
@@ -788,15 +873,14 @@ const createShippingInfoFromMethod = (context, storage, resource, method) => {
788
873
  centAmount: totalGross.centAmount - totalNet.centAmount
789
874
  }
790
875
  }];
791
- const totalTax = {
792
- ...shippingPrice,
793
- centAmount: taxPortions.reduce((acc, portion) => acc + portion.amount.centAmount, 0)
794
- };
795
876
  const taxedPrice = {
796
877
  totalNet,
797
878
  totalGross,
798
879
  taxPortions,
799
- totalTax
880
+ totalTax: {
881
+ ...shippingPrice,
882
+ centAmount: taxPortions.reduce((acc, portion) => acc + portion.amount.centAmount, 0)
883
+ }
800
884
  };
801
885
  return {
802
886
  shippingMethod: {
@@ -816,7 +900,7 @@ const createShippingInfoFromMethod = (context, storage, resource, method) => {
816
900
  //#endregion
817
901
  //#region src/repositories/cart/helpers.ts
818
902
  const selectPrice = ({ prices, currency, country }) => {
819
- if (!prices) return void 0;
903
+ if (!prices) return;
820
904
  return prices.find((price) => {
821
905
  const countryMatch = !price.country || price.country === country;
822
906
  const currencyMatch = price.value.currencyCode === currency;
@@ -825,64 +909,15 @@ const selectPrice = ({ prices, currency, country }) => {
825
909
  };
826
910
  const calculateLineItemTotalPrice = (lineItem) => lineItem.price?.value.centAmount * lineItem.quantity;
827
911
  const calculateCartTotalPrice = (cart) => {
828
- const lineItemsTotal = cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
829
- const customLineItemsTotal = cart.customLineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
830
- return lineItemsTotal + customLineItemsTotal;
831
- };
832
- const calculateTaxedPrice = (amount, taxCategory, currency, country) => {
833
- if (!taxCategory || !taxCategory.rates.length) return void 0;
834
- const taxRate = taxCategory.rates.find((rate) => !rate.country || rate.country === country) || taxCategory.rates[0];
835
- if (!taxRate) return void 0;
836
- let netAmount;
837
- let grossAmount;
838
- let taxAmount;
839
- if (taxRate.includedInPrice) {
840
- grossAmount = amount;
841
- taxAmount = Math.round(grossAmount * taxRate.amount / (1 + taxRate.amount));
842
- netAmount = grossAmount - taxAmount;
843
- } else {
844
- netAmount = amount;
845
- taxAmount = Math.round(netAmount * taxRate.amount);
846
- grossAmount = netAmount + taxAmount;
847
- }
848
- return {
849
- totalNet: {
850
- type: "centPrecision",
851
- currencyCode: currency,
852
- centAmount: netAmount,
853
- fractionDigits: 2
854
- },
855
- totalGross: {
856
- type: "centPrecision",
857
- currencyCode: currency,
858
- centAmount: grossAmount,
859
- fractionDigits: 2
860
- },
861
- taxPortions: taxAmount > 0 ? [{
862
- rate: taxRate.amount,
863
- amount: {
864
- type: "centPrecision",
865
- currencyCode: currency,
866
- centAmount: taxAmount,
867
- fractionDigits: 2
868
- },
869
- name: taxRate.name
870
- }] : [],
871
- totalTax: taxAmount > 0 ? {
872
- type: "centPrecision",
873
- currencyCode: currency,
874
- centAmount: taxAmount,
875
- fractionDigits: 2
876
- } : void 0
877
- };
912
+ return cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0) + cart.customLineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
878
913
  };
879
914
  const createCustomLineItemFromDraft = (projectKey, draft, storage, country) => {
880
915
  const quantity = draft.quantity ?? 1;
881
916
  const taxCategoryRef = draft.taxCategory ? getReferenceFromResourceIdentifier(draft.taxCategory, projectKey, storage) : void 0;
882
- let taxCategory = void 0;
917
+ let taxCategory;
883
918
  if (taxCategoryRef) try {
884
919
  taxCategory = storage.get(projectKey, "tax-category", taxCategoryRef.id, {}) || void 0;
885
- } catch (error) {}
920
+ } catch (_error) {}
886
921
  const totalPrice = createCentPrecisionMoney({
887
922
  ...draft.money,
888
923
  centAmount: (draft.money.centAmount ?? 0) * quantity
@@ -941,8 +976,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
941
976
  code: "General",
942
977
  message: sku ? `A variant with SKU '${sku}' for product '${product.id}' not found.` : `A variant with ID '${variantId}' for product '${product.id}' not found.`
943
978
  });
944
- const alreadyAdded = resource.lineItems.some((x) => x.productId === product?.id && x.variant.id === variant?.id);
945
- if (alreadyAdded) resource.lineItems.forEach((x) => {
979
+ if (resource.lineItems.some((x) => x.productId === product?.id && x.variant.id === variant?.id)) resource.lineItems.forEach((x) => {
946
980
  if (x.productId === product?.id && x.variant.id === variant?.id) {
947
981
  x.quantity += quantity;
948
982
  x.totalPrice.centAmount = calculateLineItemTotalPrice(x);
@@ -963,7 +997,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
963
997
  resource.lineItems.push({
964
998
  id: v4(),
965
999
  key,
966
- addedAt: addedAt ? addedAt : new Date().toISOString(),
1000
+ addedAt: addedAt ? addedAt : (/* @__PURE__ */ new Date()).toISOString(),
967
1001
  productId: product.id,
968
1002
  productKey: product.key,
969
1003
  productSlug: product.masterData.current.slug,
@@ -1028,8 +1062,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
1028
1062
  code: "General",
1029
1063
  message: `A line item with ID '${lineItemId}' not found.`
1030
1064
  });
1031
- const shouldDelete = !quantity || quantity >= lineItem.quantity;
1032
- if (shouldDelete) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
1065
+ if (!quantity || quantity >= lineItem.quantity) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
1033
1066
  else resource.lineItems.forEach((x) => {
1034
1067
  if (x.id === lineItemId && quantity) {
1035
1068
  x.quantity -= quantity;
@@ -1228,6 +1261,39 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
1228
1261
  };
1229
1262
  }
1230
1263
  }
1264
+ setLineItemPrice(context, resource, { lineItemId, lineItemKey, externalPrice }) {
1265
+ const lineItem = resource.lineItems.find((x) => lineItemId && x.id === lineItemId || lineItemKey && x.key === lineItemKey);
1266
+ if (!lineItem) throw new CommercetoolsError({
1267
+ code: "General",
1268
+ message: lineItemKey ? `A line item with key '${lineItemKey}' not found.` : `A line item with ID '${lineItemId}' not found.`
1269
+ });
1270
+ if (!externalPrice && lineItem.priceMode !== "ExternalPrice") return;
1271
+ if (externalPrice && externalPrice.currencyCode !== resource.totalPrice.currencyCode) throw new CommercetoolsError({
1272
+ code: "General",
1273
+ message: `Currency mismatch. Expected '${resource.totalPrice.currencyCode}' but got '${externalPrice.currencyCode}'.`
1274
+ });
1275
+ if (externalPrice) {
1276
+ lineItem.priceMode = "ExternalPrice";
1277
+ const priceValue = createTypedMoney(externalPrice);
1278
+ lineItem.price = lineItem.price ?? { id: v4() };
1279
+ lineItem.price.value = priceValue;
1280
+ } else {
1281
+ lineItem.priceMode = "Platform";
1282
+ const price = selectPrice({
1283
+ prices: lineItem.variant.prices,
1284
+ currency: resource.totalPrice.currencyCode,
1285
+ country: resource.country
1286
+ });
1287
+ if (!price) throw new Error(`No valid price found for ${lineItem.productId} for country ${resource.country} and currency ${resource.totalPrice.currencyCode}`);
1288
+ lineItem.price = price;
1289
+ }
1290
+ const lineItemTotal = calculateLineItemTotalPrice(lineItem);
1291
+ lineItem.totalPrice = createCentPrecisionMoney({
1292
+ ...lineItem.price.value,
1293
+ centAmount: lineItemTotal
1294
+ });
1295
+ resource.totalPrice.centAmount = calculateCartTotalPrice(resource);
1296
+ }
1231
1297
  setLineItemShippingDetails(context, resource, { action, shippingDetails, lineItemId, lineItemKey }) {
1232
1298
  const lineItem = resource.lineItems.find((x) => lineItemId && x.id === lineItemId || lineItemKey && x.key === lineItemKey);
1233
1299
  if (!lineItem) throw new CommercetoolsError({
@@ -1247,7 +1313,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
1247
1313
  resource.shippingAddress = void 0;
1248
1314
  return;
1249
1315
  }
1250
- let custom = void 0;
1316
+ let custom;
1251
1317
  if (address.custom) custom = createCustomFields(address.custom, context.projectKey, this._storage);
1252
1318
  resource.shippingAddress = {
1253
1319
  ...address,
@@ -1306,7 +1372,7 @@ var CartRepository = class extends AbstractResourceRepository {
1306
1372
  typeId: "customer",
1307
1373
  id: draft.customerId
1308
1374
  });
1309
- let storedBusinessUnit = void 0;
1375
+ let storedBusinessUnit;
1310
1376
  if (draft.businessUnit?.id || draft.businessUnit?.key) storedBusinessUnit = this._storage.getByResourceIdentifier(context.projectKey, {
1311
1377
  typeId: "business-unit",
1312
1378
  id: draft.businessUnit.id,
@@ -1360,12 +1426,14 @@ var CartRepository = class extends AbstractResourceRepository {
1360
1426
  key: draft.store.key
1361
1427
  } : void 0;
1362
1428
  if (draft.shippingMethod) resource.shippingInfo = this.createShippingInfo(context, resource, draft.shippingMethod);
1429
+ const { taxedPrice, taxedShippingPrice } = calculateTaxTotals(resource);
1430
+ resource.taxedPrice = taxedPrice;
1431
+ resource.taxedShippingPrice = taxedShippingPrice;
1363
1432
  return this.saveNew(context, resource);
1364
1433
  }
1365
1434
  getActiveCart(projectKey) {
1366
1435
  const results = this._storage.query(projectKey, this.getTypeId(), { where: [`cartState="Active"`] });
1367
1436
  if (results.count > 0) return results.results[0];
1368
- return;
1369
1437
  }
1370
1438
  draftLineItemtoLineItem = (projectKey, draftLineItem, currency, country) => {
1371
1439
  const { productId, quantity, variantId, sku } = draftLineItem;
@@ -1420,8 +1488,7 @@ var CartRepository = class extends AbstractResourceRepository {
1420
1488
  createShippingInfo(context, resource, shippingMethodRef) {
1421
1489
  if (resource.taxMode === "External") throw new Error("External tax rate is not supported");
1422
1490
  this._storage.getByResourceIdentifier(context.projectKey, shippingMethodRef);
1423
- const shippingMethods = getShippingMethodsMatchingCart(context, this._storage, resource, { expand: ["zoneRates[*].zone"] });
1424
- const method = shippingMethods.results.find((candidate) => shippingMethodRef.id ? candidate.id === shippingMethodRef.id : candidate.key === shippingMethodRef.key);
1491
+ const method = getShippingMethodsMatchingCart(context, this._storage, resource, { expand: ["zoneRates[*].zone"] }).results.find((candidate) => shippingMethodRef.id ? candidate.id === shippingMethodRef.id : candidate.key === shippingMethodRef.key);
1425
1492
  if (!method) throw new CommercetoolsError({
1426
1493
  code: "ShippingMethodDoesNotMatchCart",
1427
1494
  message: `The shipping method with ${shippingMethodRef.id ? `ID '${shippingMethodRef.id}'` : `key '${shippingMethodRef.key}'`} is not allowed for the cart with ID '${resource.id}'.`
@@ -1434,8 +1501,7 @@ var CartRepository = class extends AbstractResourceRepository {
1434
1501
  //#region src/repositories/order/actions.ts
1435
1502
  var OrderUpdateHandler = class extends AbstractUpdateHandler {
1436
1503
  addPayment(context, resource, { payment }) {
1437
- const resolvedPayment = this._storage.getByResourceIdentifier(context.projectKey, payment);
1438
- if (!resolvedPayment) throw new Error(`Payment ${payment.id} not found`);
1504
+ if (!this._storage.getByResourceIdentifier(context.projectKey, payment)) throw new Error(`Payment ${payment.id} not found`);
1439
1505
  if (!resource.paymentInfo) resource.paymentInfo = { payments: [] };
1440
1506
  resource.paymentInfo.payments.push({
1441
1507
  typeId: "payment",
@@ -1557,10 +1623,9 @@ var OrderUpdateHandler = class extends AbstractUpdateHandler {
1557
1623
  if (!store) return;
1558
1624
  const resolvedType = this._storage.getByResourceIdentifier(context.projectKey, store);
1559
1625
  if (!resolvedType) throw new Error(`No store found with key=${store.key}`);
1560
- const storeReference = resolvedType;
1561
1626
  resource.store = {
1562
1627
  typeId: "store",
1563
- key: storeReference.key
1628
+ key: resolvedType.key
1564
1629
  };
1565
1630
  }
1566
1631
  transitionState(context, resource, { state }) {
@@ -1585,7 +1650,7 @@ var OrderUpdateHandler = class extends AbstractUpdateHandler {
1585
1650
  id: resolvedType.id
1586
1651
  },
1587
1652
  externalId,
1588
- syncedAt: syncedAt ?? new Date().toISOString()
1653
+ syncedAt: syncedAt ?? (/* @__PURE__ */ new Date()).toISOString()
1589
1654
  };
1590
1655
  if (!resource.syncInfo?.length) resource.syncInfo = [syncData];
1591
1656
  else {
@@ -1647,6 +1712,14 @@ var OrderRepository = class extends AbstractResourceRepository {
1647
1712
  totalPrice: cart.totalPrice,
1648
1713
  store: cart.store
1649
1714
  };
1715
+ const { taxedPrice, taxedShippingPrice } = calculateTaxTotals({
1716
+ lineItems: cart.lineItems,
1717
+ customLineItems: cart.customLineItems,
1718
+ shippingInfo: cart.shippingInfo,
1719
+ totalPrice: cart.totalPrice
1720
+ });
1721
+ resource.taxedPrice = resource.taxedPrice ?? taxedPrice;
1722
+ resource.taxedShippingPrice = resource.taxedShippingPrice ?? taxedShippingPrice;
1650
1723
  return this.saveNew(context, resource);
1651
1724
  }
1652
1725
  import(context, draft) {
@@ -1692,6 +1765,14 @@ var OrderRepository = class extends AbstractResourceRepository {
1692
1765
  id: shippingMethodRef.id
1693
1766
  });
1694
1767
  }
1768
+ const { taxedPrice, taxedShippingPrice } = calculateTaxTotals({
1769
+ lineItems: resource.lineItems,
1770
+ customLineItems: resource.customLineItems,
1771
+ shippingInfo: resource.shippingInfo,
1772
+ totalPrice: resource.totalPrice
1773
+ });
1774
+ resource.taxedPrice = resource.taxedPrice ?? taxedPrice;
1775
+ resource.taxedShippingPrice = resource.taxedShippingPrice ?? taxedShippingPrice;
1695
1776
  return this.saveNew(context, resource);
1696
1777
  }
1697
1778
  lineItemFromImportDraft(context, draft) {
@@ -1712,7 +1793,12 @@ var OrderRepository = class extends AbstractResourceRepository {
1712
1793
  else variant = product.masterData.current.variants.find((v) => v.sku === draft.variant.sku);
1713
1794
  if (!variant) throw new Error("Internal state error");
1714
1795
  } else throw new Error("No product found");
1715
- const lineItem = {
1796
+ const quantity = draft.quantity ?? 1;
1797
+ const totalPrice = createCentPrecisionMoney({
1798
+ ...draft.price.value,
1799
+ centAmount: (draft.price.value.centAmount ?? 0) * quantity
1800
+ });
1801
+ return {
1716
1802
  ...getBaseResourceProperties(),
1717
1803
  custom: createCustomFields(draft.custom, context.projectKey, this._storage),
1718
1804
  discountedPricePerQuantity: [],
@@ -1722,12 +1808,13 @@ var OrderRepository = class extends AbstractResourceRepository {
1722
1808
  priceMode: "Platform",
1723
1809
  productId: product.id,
1724
1810
  productType: product.productType,
1725
- quantity: draft.quantity,
1811
+ quantity,
1726
1812
  state: draft.state || [],
1727
1813
  taxRate: draft.taxRate,
1814
+ taxedPrice: calculateTaxedPriceFromRate(totalPrice.centAmount, totalPrice.currencyCode, draft.taxRate),
1728
1815
  taxedPricePortions: [],
1729
1816
  perMethodTaxRate: [],
1730
- totalPrice: createCentPrecisionMoney(draft.price.value),
1817
+ totalPrice,
1731
1818
  variant: {
1732
1819
  id: variant.id,
1733
1820
  sku: variant.sku,
@@ -1735,24 +1822,28 @@ var OrderRepository = class extends AbstractResourceRepository {
1735
1822
  attributes: variant.attributes
1736
1823
  }
1737
1824
  };
1738
- return lineItem;
1739
1825
  }
1740
1826
  customLineItemFromImportDraft(context, draft) {
1741
- const lineItem = {
1827
+ const quantity = draft.quantity ?? 1;
1828
+ const totalPrice = createCentPrecisionMoney({
1829
+ ...draft.money,
1830
+ centAmount: (draft.money.centAmount ?? 0) * quantity
1831
+ });
1832
+ return {
1742
1833
  ...getBaseResourceProperties(),
1743
1834
  custom: createCustomFields(draft.custom, context.projectKey, this._storage),
1744
1835
  discountedPricePerQuantity: [],
1745
1836
  money: createTypedMoney(draft.money),
1746
1837
  name: draft.name,
1747
- quantity: draft.quantity ?? 0,
1838
+ quantity,
1748
1839
  perMethodTaxRate: [],
1749
1840
  priceMode: draft.priceMode ?? "Standard",
1750
1841
  slug: draft.slug,
1751
1842
  state: [],
1752
- totalPrice: createCentPrecisionMoney(draft.money),
1843
+ totalPrice,
1844
+ taxedPrice: calculateTaxedPriceFromRate(totalPrice.centAmount, totalPrice.currencyCode, draft.taxRate),
1753
1845
  taxedPricePortions: []
1754
1846
  };
1755
- return lineItem;
1756
1847
  }
1757
1848
  getWithOrderNumber(context, orderNumber, params = {}) {
1758
1849
  const result = this._storage.query(context.projectKey, this.getTypeId(), {
@@ -1761,7 +1852,6 @@ var OrderRepository = class extends AbstractResourceRepository {
1761
1852
  });
1762
1853
  if (result.count === 1) return result.results[0];
1763
1854
  if (result.count > 1) throw new Error("Duplicate order numbers");
1764
- return;
1765
1855
  }
1766
1856
  createShippingInfo(context, resource, shippingMethodRef) {
1767
1857
  const cartLikeForMatching = {
@@ -1777,15 +1867,13 @@ var OrderRepository = class extends AbstractResourceRepository {
1777
1867
  directDiscounts: resource.directDiscounts || [],
1778
1868
  shippingInfo: void 0
1779
1869
  };
1780
- const shippingMethods = getShippingMethodsMatchingCart(context, this._storage, cartLikeForMatching, { expand: ["zoneRates[*].zone"] });
1781
- const method = shippingMethods.results.find((candidate) => candidate.id === shippingMethodRef.id);
1870
+ const method = getShippingMethodsMatchingCart(context, this._storage, cartLikeForMatching, { expand: ["zoneRates[*].zone"] }).results.find((candidate) => candidate.id === shippingMethodRef.id);
1782
1871
  if (!method) throw new CommercetoolsError({
1783
1872
  code: "ShippingMethodDoesNotMatchCart",
1784
1873
  message: `The shipping method with ID '${shippingMethodRef.id}' is not allowed for the order with ID '${resource.id}'.`
1785
1874
  });
1786
- const baseShippingInfo = createShippingInfoFromMethod(context, this._storage, resource, method);
1787
1875
  return {
1788
- ...baseShippingInfo,
1876
+ ...createShippingInfoFromMethod(context, this._storage, resource, method),
1789
1877
  deliveries: []
1790
1878
  };
1791
1879
  }
@@ -1813,7 +1901,7 @@ var QuoteRequestUpdateHandler = class extends AbstractUpdateHandler {
1813
1901
  }
1814
1902
  }
1815
1903
  transitionState(context, resource, { state, force }) {
1816
- let stateReference = void 0;
1904
+ let stateReference;
1817
1905
  if (state) {
1818
1906
  stateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
1819
1907
  resource.state = stateReference;
@@ -1912,7 +2000,7 @@ var AssociateRoleUpdateHandler = class extends AbstractUpdateHandler {
1912
2000
  }
1913
2001
  removePermission(context, resource, { permission }) {
1914
2002
  if (!resource.permissions) return;
1915
- resource.permissions = resource.permissions.filter((p) => {});
2003
+ resource.permissions = resource.permissions.filter((p) => p !== permission);
1916
2004
  }
1917
2005
  setBuyerAssignable(context, resource, { buyerAssignable }) {
1918
2006
  resource.buyerAssignable = buyerAssignable;
@@ -2071,8 +2159,7 @@ var BusinessUnitUpdateHandler = class extends AbstractUpdateHandler {
2071
2159
  resource.status = status;
2072
2160
  }
2073
2161
  setAssociates(context, resource, { associates }) {
2074
- const newAssociates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0);
2075
- resource.associates = newAssociates || void 0;
2162
+ resource.associates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0) || void 0;
2076
2163
  }
2077
2164
  removeAssociate(context, resource, { customer }) {
2078
2165
  resource.associates = resource.associates.filter((associate) => associate.customer.id !== customer.id);
@@ -2390,8 +2477,7 @@ var CategoryRepository = class extends AbstractResourceRepository {
2390
2477
  postProcessResource(context, resource, params) {
2391
2478
  let node = resource;
2392
2479
  const ancestors = [];
2393
- const expandClauses = params?.expand?.map(parseExpandClause) ?? [];
2394
- const addExpand = expandClauses?.find((c) => c.element === "ancestors" && c.index === "*");
2480
+ const addExpand = (params?.expand?.map(parseExpandClause) ?? [])?.find((c) => c.element === "ancestors" && c.index === "*");
2395
2481
  while (node.parent) {
2396
2482
  node = this._storage.getByResourceIdentifier(context.projectKey, node.parent);
2397
2483
  ancestors.push({
@@ -2480,9 +2566,8 @@ var CustomObjectRepository = class extends AbstractResourceRepository {
2480
2566
  code: "InvalidOperation",
2481
2567
  message: "version on create must be 0"
2482
2568
  }, 400);
2483
- const baseProperties = getBaseResourceProperties();
2484
2569
  const resource = {
2485
- ...baseProperties,
2570
+ ...getBaseResourceProperties(),
2486
2571
  container: draft.container,
2487
2572
  key: draft.key,
2488
2573
  value: draft.value
@@ -2491,8 +2576,7 @@ var CustomObjectRepository = class extends AbstractResourceRepository {
2491
2576
  return resource;
2492
2577
  }
2493
2578
  getWithContainerAndKey(context, container, key) {
2494
- const items = this._storage.all(context.projectKey, this.getTypeId());
2495
- return items.find((item) => item.container === container && item.key === key);
2579
+ return this._storage.all(context.projectKey, this.getTypeId()).find((item) => item.container === container && item.key === key);
2496
2580
  }
2497
2581
  queryWithContainer(context, container, params = {}) {
2498
2582
  const whereClause = params.where || [];
@@ -2598,10 +2682,9 @@ var CustomerUpdateHandler = class extends AbstractUpdateHandler {
2598
2682
  code: "InvalidOperation",
2599
2683
  message: "CustomerGroup is required."
2600
2684
  }, 400);
2601
- const group = this._storage.getByResourceIdentifier(context.projectKey, action.customerGroup);
2602
2685
  resource.customerGroup = {
2603
2686
  typeId: "customer-group",
2604
- id: group.id
2687
+ id: this._storage.getByResourceIdentifier(context.projectKey, action.customerGroup).id
2605
2688
  };
2606
2689
  }
2607
2690
  setCustomerNumber(_context, resource, { customerNumber }) {
@@ -2698,8 +2781,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2698
2781
  this.actions = new CustomerUpdateHandler(config.storage);
2699
2782
  }
2700
2783
  create(context, draft) {
2701
- const results = this._storage.query(context.projectKey, this.getTypeId(), { where: [`lowercaseEmail="${draft.email.toLowerCase()}"`] });
2702
- if (results.count > 0) throw new CommercetoolsError({
2784
+ if (this._storage.query(context.projectKey, this.getTypeId(), { where: [`lowercaseEmail="${draft.email.toLowerCase()}"`] }).count > 0) throw new CommercetoolsError({
2703
2785
  code: "CustomerAlreadyExists",
2704
2786
  statusCode: 400,
2705
2787
  message: "There is already an existing customer with the provided email.",
@@ -2776,7 +2858,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2776
2858
  message: `The Customer with ID '${request.email}' was not found.`
2777
2859
  });
2778
2860
  const ttlMinutes = request.ttlMinutes ?? 34560;
2779
- const expiresAt = new Date(new Date().getTime() + ttlMinutes * 60 * 1e3);
2861
+ const expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1e3);
2780
2862
  const customer = results.results[0];
2781
2863
  const rest = getBaseResourceProperties();
2782
2864
  const token = createPasswordResetToken(customer, expiresAt);
@@ -2813,7 +2895,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2813
2895
  code: "ResourceNotFound",
2814
2896
  message: `The Customer with ID '${id}' was not found.`
2815
2897
  });
2816
- const expiresAt = new Date(Date.now() + 30 * 60);
2898
+ const expiresAt = new Date(Date.now() + 1800);
2817
2899
  const customer = results.results[0];
2818
2900
  const rest = getBaseResourceProperties();
2819
2901
  const token = createEmailVerifyToken(customer);
@@ -3066,6 +3148,11 @@ var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
3066
3148
  resource.quantityOnStock = quantity;
3067
3149
  resource.availableQuantity = quantity;
3068
3150
  }
3151
+ removeQuantity(context, resource, { quantity }) {
3152
+ const newQuantity = Math.max(0, resource.quantityOnStock - quantity);
3153
+ resource.quantityOnStock = newQuantity;
3154
+ resource.availableQuantity = newQuantity;
3155
+ }
3069
3156
  setCustomField(context, resource, { name, value }) {
3070
3157
  if (!resource.custom) throw new Error("Resource has no custom field");
3071
3158
  resource.custom.fields[name] = value;
@@ -3159,12 +3246,10 @@ var MyCustomerRepository = class extends CustomerRepository {
3159
3246
  deleteMe(context) {
3160
3247
  const results = this._storage.query(context.projectKey, this.getTypeId(), {});
3161
3248
  if (results.count > 0) return this.delete(context, results.results[0].id);
3162
- return;
3163
3249
  }
3164
3250
  getMe(context) {
3165
3251
  const results = this._storage.query(context.projectKey, this.getTypeId(), {});
3166
3252
  if (results.count > 0) return results.results[0];
3167
- return;
3168
3253
  }
3169
3254
  };
3170
3255
 
@@ -3245,8 +3330,7 @@ var PaymentUpdateHandler = class extends AbstractUpdateHandler {
3245
3330
  }
3246
3331
  setCustomer(_context, resource, { customer }) {
3247
3332
  if (customer) {
3248
- const c = getReferenceFromResourceIdentifier(customer, _context.projectKey, this._storage);
3249
- resource.customer = c;
3333
+ resource.customer = getReferenceFromResourceIdentifier(customer, _context.projectKey, this._storage);
3250
3334
  resource.anonymousId = void 0;
3251
3335
  }
3252
3336
  }
@@ -3388,11 +3472,10 @@ var ReviewStatisticsService = class {
3388
3472
  this._storage = _storage;
3389
3473
  }
3390
3474
  calculateProductReviewStatistics(projectKey, productId) {
3391
- const allReviews = this._storage.all(projectKey, "review");
3392
- const productReviews = allReviews.filter((review) => review.target?.typeId === "product" && review.target?.id === productId && review.includedInStatistics && review.rating !== void 0);
3393
- if (productReviews.length === 0) return void 0;
3475
+ const productReviews = this._storage.all(projectKey, "review").filter((review) => review.target?.typeId === "product" && review.target?.id === productId && review.includedInStatistics && review.rating !== void 0);
3476
+ if (productReviews.length === 0) return;
3394
3477
  const ratings = productReviews.map((review) => review.rating).filter((rating) => rating !== void 0);
3395
- if (ratings.length === 0) return void 0;
3478
+ if (ratings.length === 0) return;
3396
3479
  const count = ratings.length;
3397
3480
  const sum = ratings.reduce((acc, rating) => acc + rating, 0);
3398
3481
  const averageRating = Math.round(sum / count * 1e5) / 1e5;
@@ -3495,11 +3578,9 @@ var Token = class {
3495
3578
  * @return {TokenPosition}
3496
3579
  */
3497
3580
  strpos() {
3498
- const start = this.lexer.strpos(this.start);
3499
- const end = this.lexer.strpos(this.end);
3500
3581
  return {
3501
- start,
3502
- end
3582
+ start: this.lexer.strpos(this.start),
3583
+ end: this.lexer.strpos(this.end)
3503
3584
  };
3504
3585
  }
3505
3586
  isEof() {
@@ -3730,7 +3811,7 @@ var Lexer = class {
3730
3811
  unexpected += e$1.unexpected;
3731
3812
  }
3732
3813
  const { line, column } = this.strpos(position);
3733
- const e = new Error(`Unexpected input: ${unexpected} at (${line}:${column})`);
3814
+ const e = /* @__PURE__ */ new Error(`Unexpected input: ${unexpected} at (${line}:${column})`);
3734
3815
  e.unexpected = unexpected;
3735
3816
  e.end = position + unexpected.length;
3736
3817
  throw e;
@@ -3743,11 +3824,9 @@ var Lexer = class {
3743
3824
  strpos(i) {
3744
3825
  let lines = this._state.source.substring(0, i).split(/\r?\n/);
3745
3826
  if (!Array.isArray(lines)) lines = [lines];
3746
- const line = lines.length;
3747
- const column = lines[lines.length - 1].length + 1;
3748
3827
  return {
3749
- line,
3750
- column
3828
+ line: lines.length,
3829
+ column: lines[lines.length - 1].length + 1
3751
3830
  };
3752
3831
  }
3753
3832
  /**
@@ -3785,7 +3864,7 @@ var Lexer = class {
3785
3864
  * @param kwd The keyword to add as a token
3786
3865
  */
3787
3866
  keyword(kwd) {
3788
- return this.token(kwd, new RegExp(`${kwd}(?=\\W|$)`));
3867
+ return this.token(kwd, /* @__PURE__ */ new RegExp(`${kwd}(?=\\W|$)`));
3789
3868
  }
3790
3869
  /**
3791
3870
  * Creates an operator
@@ -3857,9 +3936,9 @@ var Parser = class {
3857
3936
  * @type {ILexer<T>}
3858
3937
  */
3859
3938
  this.lexer = lexer;
3860
- this._nuds = new Map();
3861
- this._leds = new Map();
3862
- this._bps = new Map();
3939
+ this._nuds = /* @__PURE__ */ new Map();
3940
+ this._leds = /* @__PURE__ */ new Map();
3941
+ this._bps = /* @__PURE__ */ new Map();
3863
3942
  }
3864
3943
  _type(tokenOrType) {
3865
3944
  return tokenOrType && typeof tokenOrType.isEof == "function" ? tokenOrType.type : tokenOrType;
@@ -3927,10 +4006,9 @@ var Parser = class {
3927
4006
  }, true);
3928
4007
  };
3929
4008
  const mkinfo = (token) => {
3930
- const bp = this.bp(token);
3931
4009
  return {
3932
4010
  token,
3933
- bp,
4011
+ bp: this.bp(token),
3934
4012
  stop,
3935
4013
  ctx: opts.ctx,
3936
4014
  options: opts
@@ -4032,8 +4110,7 @@ const parseFilter = (filter) => {
4032
4110
  const parser = new Parser(lexer).builder().nud("IDENTIFIER", 100, (t) => t.token.match).led(":", 100, ({ left, bp }) => {
4033
4111
  const parsed = parser.parse({ terminals: [bp - 1] });
4034
4112
  const expressions = !Array.isArray(parsed) ? [parsed] : parsed;
4035
- const unique = new Set(expressions.map((expr) => expr.type));
4036
- if (unique.size > 1) throw new Error("Invalid expression");
4113
+ if (new Set(expressions.map((expr) => expr.type)).size > 1) throw new Error("Invalid expression");
4037
4114
  if (expressions.some((expr) => expr.type === "Symbol")) return {
4038
4115
  source: left,
4039
4116
  type: "FilterExpression",
@@ -4118,22 +4195,18 @@ const generateFacetFunc = (filter) => {
4118
4195
  return parseFilter(filter);
4119
4196
  };
4120
4197
  const filterProduct = (source, exprFunc) => (p, markMatchingVariants) => {
4121
- const value = nestedLookup(p, source);
4122
- return exprFunc(value);
4198
+ return exprFunc(nestedLookup(p, source));
4123
4199
  };
4124
4200
  const filterVariants = (source, exprFunc) => (p, markMatchingVariants) => {
4125
4201
  const [, ...paths] = source.split(".");
4126
4202
  const path = paths.join(".");
4127
4203
  const variants = getVariants(p);
4128
- for (const variant of variants) {
4129
- const value = resolveVariantValue(variant, path);
4130
- if (exprFunc(value)) {
4131
- if (markMatchingVariants) {
4132
- for (const v of variants) v.isMatchingVariant = false;
4133
- variant.isMatchingVariant = true;
4134
- }
4135
- return true;
4204
+ for (const variant of variants) if (exprFunc(resolveVariantValue(variant, path))) {
4205
+ if (markMatchingVariants) {
4206
+ for (const v of variants) v.isMatchingVariant = false;
4207
+ variant.isMatchingVariant = true;
4136
4208
  }
4209
+ return true;
4137
4210
  }
4138
4211
  return false;
4139
4212
  };
@@ -4142,7 +4215,7 @@ const resolveVariantValue = (obj, path) => {
4142
4215
  if (path.startsWith("variants.")) path = path.substring(path.indexOf(".") + 1);
4143
4216
  if (path.startsWith("attributes.")) {
4144
4217
  const [, attrName, ...rest] = path.split(".");
4145
- if (!obj.attributes) return void 0;
4218
+ if (!obj.attributes) return;
4146
4219
  for (const attr of obj.attributes) if (attr.name === attrName) return nestedLookup(attr.value, rest.join("."));
4147
4220
  }
4148
4221
  if (path === "price.centAmount") return obj.prices && obj.prices.length > 0 ? obj.prices[0].value.centAmount : void 0;
@@ -4154,17 +4227,14 @@ const getVariants = (p) => [p.masterVariant, ...p.variants ?? []];
4154
4227
  //#region src/lib/productSearchFilter.ts
4155
4228
  const parseSearchQuery = (searchQuery) => {
4156
4229
  if (isSearchAndExpression$1(searchQuery)) return (obj, markMatchingVariant) => searchQuery.and.every((expr) => {
4157
- const filterFunc = parseSearchQuery(expr);
4158
- return filterFunc(obj, markMatchingVariant);
4230
+ return parseSearchQuery(expr)(obj, markMatchingVariant);
4159
4231
  });
4160
4232
  if (isSearchOrExpression$1(searchQuery)) return (obj, markMatchingVariant) => searchQuery.or.some((expr) => {
4161
- const filterFunc = parseSearchQuery(expr);
4162
- return filterFunc(obj, markMatchingVariant);
4233
+ return parseSearchQuery(expr)(obj, markMatchingVariant);
4163
4234
  });
4164
4235
  if (isSearchNotExpression$1(searchQuery)) return (obj, markMatchingVariant) => !parseSearchQuery(searchQuery.not)(obj, markMatchingVariant);
4165
4236
  if (isSearchFilterExpression$1(searchQuery)) return (obj, markMatchingVariant) => searchQuery.filter.every((expr) => {
4166
- const filterFunc = parseSearchQuery(expr);
4167
- return filterFunc(obj, markMatchingVariant);
4237
+ return parseSearchQuery(expr)(obj, markMatchingVariant);
4168
4238
  });
4169
4239
  if (isSearchRangeExpression$1(searchQuery)) {
4170
4240
  const generateRangeMatchFunc = (value) => {
@@ -4200,18 +4270,15 @@ const generateFieldMatchFunc = (matchFunc, searchQuery) => {
4200
4270
  if (searchQuery.field.startsWith("variants.")) {
4201
4271
  const variantField = searchQuery.field.substring(searchQuery.field.indexOf(".") + 1);
4202
4272
  const variants = getVariants(obj);
4203
- for (const variant of variants) {
4204
- const value = resolveFieldValue(variant, {
4205
- ...searchQuery,
4206
- field: variantField
4207
- });
4208
- if (matchFunc(value)) {
4209
- if (markMatchingVariants) {
4210
- for (const v of variants) v.isMatchingVariant = false;
4211
- variant.isMatchingVariant = true;
4212
- }
4213
- return true;
4273
+ for (const variant of variants) if (matchFunc(resolveFieldValue(variant, {
4274
+ ...searchQuery,
4275
+ field: variantField
4276
+ }))) {
4277
+ if (markMatchingVariants) {
4278
+ for (const v of variants) v.isMatchingVariant = false;
4279
+ variant.isMatchingVariant = true;
4214
4280
  }
4281
+ return true;
4215
4282
  }
4216
4283
  return false;
4217
4284
  }
@@ -4226,7 +4293,7 @@ const resolveFieldValue = (obj, searchQuery) => {
4226
4293
  if (fieldPath.startsWith("variants.")) fieldPath = fieldPath.substring(fieldPath.indexOf(".") + 1);
4227
4294
  if (fieldPath.startsWith("attributes.")) {
4228
4295
  const [, attrName, ...rest] = fieldPath.split(".");
4229
- if (!obj.attributes) return void 0;
4296
+ if (!obj.attributes) return;
4230
4297
  for (const attr of obj.attributes) if (attr.name === attrName) return nestedLookupByLanguage(attr.value, rest.join("."), language);
4231
4298
  }
4232
4299
  if (fieldPath === "prices.currentCentAmount") return obj.prices && obj.prices.length > 0 ? obj.prices[0].value.centAmount : void 0;
@@ -4255,8 +4322,8 @@ const isSearchWildCardExpression$1 = (expr) => expr.wildcard !== void 0;
4255
4322
  //#endregion
4256
4323
  //#region src/lib/searchQueryTypeChecker.ts
4257
4324
  const validateSearchQuery = (query) => {
4258
- if (isSearchAndExpression(query)) query.and.forEach((expr) => validateSearchQuery(expr));
4259
- else if (isSearchOrExpression(query)) query.or.forEach((expr) => validateSearchQuery(expr));
4325
+ if (isSearchAndExpression(query)) for (const expr of query.and) validateSearchQuery(expr);
4326
+ else if (isSearchOrExpression(query)) for (const expr of query.or) validateSearchQuery(expr);
4260
4327
  else if (isSearchNotExpression(query)) validateSearchQuery(query.not);
4261
4328
  else if (isSearchFilterExpression(query) || isSearchRangeExpression(query) || isSearchExactExpression(query) || isSearchExistsExpression(query) || isSearchFullTextExpression(query) || isSearchFullTextPrefixExpression(query) || isSearchPrefixExpression(query) || isSearchWildCardExpression(query) || isSearchAnyValue(query)) return;
4262
4329
  else throw new Error("Unsupported search query expression");
@@ -4336,7 +4403,7 @@ var ProductSearch = class {
4336
4403
  isOnStockForChannel: existingEntry?.isOnStockForChannel ?? entry.supplyChannel?.id
4337
4404
  });
4338
4405
  return acc;
4339
- }, new Map());
4406
+ }, /* @__PURE__ */ new Map());
4340
4407
  let productResources = this._storage.all(projectKey, "product").map((r) => this.transformProduct(r, params.productProjectionParameters?.staged ?? false, availabilityBySku)).filter((p) => {
4341
4408
  if (!(params.productProjectionParameters?.staged ?? false)) return p.published;
4342
4409
  return true;
@@ -4347,7 +4414,6 @@ var ProductSearch = class {
4347
4414
  const matchFunc = parseSearchQuery(params.query);
4348
4415
  productResources = productResources.filter((resource) => matchFunc(resource, markMatchingVariant));
4349
4416
  } catch (err) {
4350
- console.error(err);
4351
4417
  throw new CommercetoolsError({
4352
4418
  code: "InvalidInput",
4353
4419
  message: err.message
@@ -4423,8 +4489,7 @@ var ProductSearch = class {
4423
4489
  //#endregion
4424
4490
  //#region src/repositories/product/helpers.ts
4425
4491
  const getVariant = (productData, variantId, sku) => {
4426
- const variants = [productData.masterVariant, ...productData.variants];
4427
- const foundVariant = variants.find((variant) => {
4492
+ const foundVariant = [productData.masterVariant, ...productData.variants].find((variant) => {
4428
4493
  if (variantId) return variant.id === variantId;
4429
4494
  if (sku) return variant.sku === sku;
4430
4495
  return false;
@@ -4451,12 +4516,11 @@ const variantFromDraft = (context, storage, variantId, variant) => ({
4451
4516
  images: variant.images ?? []
4452
4517
  });
4453
4518
  const assetFromDraft = (context, storage, draft) => {
4454
- const asset = {
4519
+ return {
4455
4520
  ...draft,
4456
4521
  id: v4(),
4457
4522
  custom: createCustomFields(draft.custom, context.projectKey, storage)
4458
4523
  };
4459
- return asset;
4460
4524
  };
4461
4525
  const priceFromDraft = (context, storage, draft) => ({
4462
4526
  id: v4(),
@@ -4474,10 +4538,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4474
4538
  const { variant, isMasterVariant, variantIndex } = getVariant(data, variantId, sku);
4475
4539
  if (!variant) throw new Error(`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`);
4476
4540
  if (!variant.images) variant.images = [];
4477
- else {
4478
- const existingImage = variant.images.find((x) => x.url === image.url);
4479
- if (existingImage) throw new Error(`Cannot add image '${image.url}' because product '${resource.id}' already has that image.`);
4480
- }
4541
+ else if (variant.images.find((x) => x.url === image.url)) throw new Error(`Cannot add image '${image.url}' because product '${resource.id}' already has that image.`);
4481
4542
  variant.images.push(image);
4482
4543
  if (isMasterVariant) data.masterVariant = variant;
4483
4544
  else data.variants[variantIndex] = variant;
@@ -4529,12 +4590,10 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4529
4590
  assets
4530
4591
  };
4531
4592
  const dataStaged = resource.masterData.staged;
4532
- const allVariants = [dataStaged.masterVariant, ...dataStaged.variants ?? []];
4533
- const maxId = allVariants.reduce((max, element) => element.id > max ? element.id : max, 0);
4593
+ const maxId = [dataStaged.masterVariant, ...dataStaged.variants ?? []].reduce((max, element) => element.id > max ? element.id : max, 0);
4534
4594
  const variant = variantFromDraft(context, this._storage, maxId + 1, variantDraft);
4535
4595
  dataStaged.variants.push(variant);
4536
- const onlyStaged = staged !== void 0 ? staged : true;
4537
- if (!onlyStaged) resource.masterData.current.variants.push(variant);
4596
+ if (!(staged !== void 0 ? staged : true)) resource.masterData.current.variants.push(variant);
4538
4597
  checkForStagedChanges(resource);
4539
4598
  return resource;
4540
4599
  }
@@ -4564,8 +4623,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4564
4623
  }
4565
4624
  changePrice(context, resource, { priceId, price, staged }) {
4566
4625
  const changeVariantPrice = (data) => {
4567
- const allVariants = [data.masterVariant, ...data.variants ?? []];
4568
- const priceVariant = allVariants.find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4626
+ const priceVariant = [data.masterVariant, ...data.variants ?? []].find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4569
4627
  if (!priceVariant) throw new Error(`Price with id ${priceId} not found on product ${resource.id}`);
4570
4628
  const { variant, isMasterVariant, variantIndex } = getVariant(data, priceVariant.id, priceVariant.sku);
4571
4629
  if (!variant) throw new Error(`Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`);
@@ -4620,11 +4678,10 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4620
4678
  const removeCategory = (data) => {
4621
4679
  if (category) {
4622
4680
  const resolvedCategory = getReferenceFromResourceIdentifier(category, context.projectKey, this._storage);
4623
- const foundCategory = data.categories.find((productCategory) => {
4681
+ if (!data.categories.find((productCategory) => {
4624
4682
  if (productCategory.id === resolvedCategory.id) return productCategory;
4625
4683
  return false;
4626
- });
4627
- if (!foundCategory) throw new CommercetoolsError({
4684
+ })) throw new CommercetoolsError({
4628
4685
  code: "InvalidOperation",
4629
4686
  message: `Cannot remove from category '${resolvedCategory.id}' because product '${resource.masterData.current.name}' is not in that category.`
4630
4687
  }, 400);
@@ -4649,8 +4706,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4649
4706
  const { variant, isMasterVariant, variantIndex } = getVariant(data, variantId, sku);
4650
4707
  if (!variant) throw new Error(`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`);
4651
4708
  const variantImages = variant.images ?? [];
4652
- const existingImage = variantImages.find((x) => x.url === imageUrl);
4653
- if (!existingImage) throw new Error(`Cannot remove image '${imageUrl}' because product '${resource.id}' does not have that image.`);
4709
+ if (!variantImages.find((x) => x.url === imageUrl)) throw new Error(`Cannot remove image '${imageUrl}' because product '${resource.id}' does not have that image.`);
4654
4710
  variant.images = variantImages.filter((image) => image.url !== imageUrl);
4655
4711
  if (isMasterVariant) data.masterVariant = variant;
4656
4712
  else data.variants[variantIndex] = variant;
@@ -4663,8 +4719,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4663
4719
  }
4664
4720
  removePrice(context, resource, { priceId, staged }) {
4665
4721
  const removeVariantPrice = (data) => {
4666
- const allVariants = [data.masterVariant, ...data.variants ?? []];
4667
- const priceVariant = allVariants.find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4722
+ const priceVariant = [data.masterVariant, ...data.variants ?? []].find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4668
4723
  if (!priceVariant) throw new Error(`Price with id ${priceId} not found on product ${resource.id}`);
4669
4724
  const { variant, isMasterVariant, variantIndex } = getVariant(data, priceVariant.id, priceVariant.sku);
4670
4725
  if (!variant) throw new Error(`Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`);
@@ -4777,8 +4832,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4777
4832
  return data;
4778
4833
  };
4779
4834
  resource.masterData.staged = updatePriceCustomFields(resource.masterData.staged);
4780
- const onlyStaged = staged !== void 0 ? staged : true;
4781
- if (!onlyStaged) resource.masterData.current = updatePriceCustomFields(resource.masterData.current);
4835
+ if (!(staged !== void 0 ? staged : true)) resource.masterData.current = updatePriceCustomFields(resource.masterData.current);
4782
4836
  checkForStagedChanges(resource);
4783
4837
  return resource;
4784
4838
  }
@@ -4794,13 +4848,12 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4794
4848
  return data;
4795
4849
  };
4796
4850
  resource.masterData.staged = updatePriceCustomType(resource.masterData.staged);
4797
- const onlyStaged = staged !== void 0 ? staged : true;
4798
- if (!onlyStaged) resource.masterData.current = updatePriceCustomType(resource.masterData.current);
4851
+ if (!(staged !== void 0 ? staged : true)) resource.masterData.current = updatePriceCustomType(resource.masterData.current);
4799
4852
  checkForStagedChanges(resource);
4800
4853
  return resource;
4801
4854
  }
4802
4855
  setTaxCategory(context, resource, { taxCategory }) {
4803
- let taxCategoryReference = void 0;
4856
+ let taxCategoryReference;
4804
4857
  if (taxCategory) taxCategoryReference = getReferenceFromResourceIdentifier(taxCategory, context.projectKey, this._storage);
4805
4858
  else throw new CommercetoolsError({
4806
4859
  code: "InvalidJsonInput",
@@ -4811,7 +4864,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4811
4864
  return resource;
4812
4865
  }
4813
4866
  transitionState(context, resource, { state, force }) {
4814
- let productStateReference = void 0;
4867
+ let productStateReference;
4815
4868
  if (state) {
4816
4869
  productStateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
4817
4870
  resource.state = productStateReference;
@@ -4841,7 +4894,7 @@ var ProductRepository = class extends AbstractResourceRepository {
4841
4894
  }
4842
4895
  create(context, draft) {
4843
4896
  if (!draft.masterVariant) throw new Error("Missing master variant");
4844
- let productType = void 0;
4897
+ let productType;
4845
4898
  try {
4846
4899
  productType = getReferenceFromResourceIdentifier(draft.productType, context.projectKey, this._storage);
4847
4900
  } catch (err) {
@@ -4861,9 +4914,9 @@ var ProductRepository = class extends AbstractResourceRepository {
4861
4914
  detailedErrorMessage: "categories: JSON object expected."
4862
4915
  }, 400);
4863
4916
  });
4864
- let taxCategoryReference = void 0;
4917
+ let taxCategoryReference;
4865
4918
  if (draft.taxCategory) taxCategoryReference = getReferenceFromResourceIdentifier(draft.taxCategory, context.projectKey, this._storage);
4866
- let productStateReference = void 0;
4919
+ let productStateReference;
4867
4920
  if (draft.state) productStateReference = getReferenceFromResourceIdentifier(draft.state, context.projectKey, this._storage);
4868
4921
  const productData = {
4869
4922
  name: draft.name,
@@ -4985,12 +5038,17 @@ const haversineDistance = (src, dst) => {
4985
5038
  const dLat = toRadian(dst.latitude - src.latitude);
4986
5039
  const dLon = toRadian(dst.longitude - src.longitude);
4987
5040
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRadian(src.latitude)) * Math.cos(toRadian(dst.latitude)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
4988
- const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
4989
- return RADIUS_OF_EARTH_IN_KM * c * 1e3;
5041
+ return RADIUS_OF_EARTH_IN_KM * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))) * 1e3;
4990
5042
  };
4991
5043
 
4992
5044
  //#endregion
4993
5045
  //#region src/lib/predicateParser.ts
5046
+ /**
5047
+ * This module implements the commercetools query predicate filter expression.
5048
+ * Support should be 100% complete.
5049
+ *
5050
+ * See https://docs.commercetools.com/api/predicates/query
5051
+ */
4994
5052
  var PredicateError = class {
4995
5053
  message;
4996
5054
  constructor(message) {
@@ -5025,7 +5083,7 @@ const resolveValue = (obj, val) => {
5025
5083
  if (val.value === "variants" && obj.masterVariant && obj.variants !== void 0) return [obj.masterVariant, ...obj.variants ?? []];
5026
5084
  if (!(val.value in obj)) {
5027
5085
  if (Array.isArray(obj)) return Object.values(obj).filter((v) => val.value in v).map((v) => v[val.value]);
5028
- return void 0;
5086
+ return;
5029
5087
  }
5030
5088
  return obj[val.value];
5031
5089
  };
@@ -5077,8 +5135,7 @@ const generateMatchFunc = (predicate) => {
5077
5135
  if (Array.isArray(expr)) return [left, ...expr];
5078
5136
  return [left, expr];
5079
5137
  }).nud("(", 100, (t) => {
5080
- const expr = parser.parse({ terminals: [")"] });
5081
- return expr;
5138
+ return parser.parse({ terminals: [")"] });
5082
5139
  }).led("(", 100, ({ left, bp }) => {
5083
5140
  const expr = parser.parse();
5084
5141
  lexer.expect(")");
@@ -5132,33 +5189,25 @@ const generateMatchFunc = (predicate) => {
5132
5189
  return (obj, vars) => resolveValue(obj, left) <= resolveSymbol(expr, vars);
5133
5190
  }).led("IS", 20, ({ left, bp }) => {
5134
5191
  let invert = false;
5135
- const next = lexer.peek();
5136
- if (next.type === "NOT") {
5192
+ if (lexer.peek().type === "NOT") {
5137
5193
  invert = true;
5138
5194
  lexer.next();
5139
5195
  }
5140
- const expr = parser.parse({ terminals: [bp - 1] });
5141
- switch (expr) {
5142
- case "empty": {
5196
+ switch (parser.parse({ terminals: [bp - 1] })) {
5197
+ case "empty":
5143
5198
  if (!invert) return (obj, vars) => {
5144
- const val = resolveValue(obj, left);
5145
- return val.length === 0;
5199
+ return resolveValue(obj, left).length === 0;
5146
5200
  };
5147
5201
  return (obj, vars) => {
5148
- const val = resolveValue(obj, left);
5149
- return val.length !== 0;
5202
+ return resolveValue(obj, left).length !== 0;
5150
5203
  };
5151
- }
5152
- case "defined": {
5204
+ case "defined":
5153
5205
  if (!invert) return (obj, vars) => {
5154
- const val = resolveValue(obj, left);
5155
- return val !== void 0;
5206
+ return resolveValue(obj, left) !== void 0;
5156
5207
  };
5157
5208
  return (obj, vars) => {
5158
- const val = resolveValue(obj, left);
5159
- return val === void 0;
5209
+ return resolveValue(obj, left) === void 0;
5160
5210
  };
5161
- }
5162
5211
  default: throw new Error("Unexpected");
5163
5212
  }
5164
5213
  }).led("IN", 20, ({ left, bp }) => {
@@ -5192,14 +5241,13 @@ const generateMatchFunc = (predicate) => {
5192
5241
  const value = resolveValue(obj, left);
5193
5242
  if (!value) return false;
5194
5243
  const maxDistance = resolveSymbol(expr[2], vars);
5195
- const distance = haversineDistance({
5244
+ return haversineDistance({
5196
5245
  longitude: value[0],
5197
5246
  latitude: value[1]
5198
5247
  }, {
5199
5248
  longitude: resolveSymbol(expr[0], vars),
5200
5249
  latitude: resolveSymbol(expr[1], vars)
5201
- });
5202
- return distance <= maxDistance;
5250
+ }) <= maxDistance;
5203
5251
  };
5204
5252
  }).led("CONTAINS", 20, ({ left, bp }) => {
5205
5253
  const keyword = lexer.next();
@@ -5247,7 +5295,6 @@ var ProductProjectionSearch = class {
5247
5295
  const filters = params.filter.map(parseFilterExpression);
5248
5296
  resources = resources.filter((resource) => filters.every((f) => f(resource, markMatchingVariant)));
5249
5297
  } catch (err) {
5250
- console.error(err);
5251
5298
  throw new CommercetoolsError({
5252
5299
  code: "InvalidInput",
5253
5300
  message: err.message
@@ -5303,7 +5350,7 @@ var ProductProjectionSearch = class {
5303
5350
  getFacets(params, products) {
5304
5351
  if (!params.facet) return {};
5305
5352
  const result = {};
5306
- const regexp = new RegExp(/ counting products$/);
5353
+ const regexp = /* @__PURE__ */ new RegExp(/ counting products$/);
5307
5354
  for (let facet of params.facet) {
5308
5355
  let countProducts = false;
5309
5356
  if (facet.endsWith(" counting products")) {
@@ -5369,36 +5416,34 @@ var ProductProjectionSearch = class {
5369
5416
  };
5370
5417
  }
5371
5418
  rangeFacet(source, ranges, products, countProducts) {
5372
- const counts = ranges?.map((range) => {
5373
- if (source.startsWith("variants.")) {
5374
- const values = [];
5375
- for (const p of products) for (const v of getVariants(p)) {
5376
- const val = resolveVariantValue(v, source);
5377
- if (val === void 0) continue;
5378
- if (range.match(val)) values.push(val);
5379
- }
5380
- const numValues = values.length;
5381
- return {
5382
- type: "double",
5383
- from: range.start || 0,
5384
- fromStr: range.start !== null ? Number(range.start).toFixed(1) : "",
5385
- to: range.stop || 0,
5386
- toStr: range.stop !== null ? Number(range.stop).toFixed(1) : "",
5387
- count: numValues,
5388
- total: values.reduce((a, b) => a + b, 0),
5389
- min: numValues > 0 ? Math.min(...values) : 0,
5390
- max: numValues > 0 ? Math.max(...values) : 0,
5391
- mean: numValues > 0 ? mean(values) : 0
5392
- };
5393
- }
5394
- throw new Error("not supported");
5395
- }) || [];
5396
- const data = {
5419
+ return {
5397
5420
  type: "range",
5398
5421
  dataType: "number",
5399
- ranges: counts
5422
+ ranges: ranges?.map((range) => {
5423
+ if (source.startsWith("variants.")) {
5424
+ const values = [];
5425
+ for (const p of products) for (const v of getVariants(p)) {
5426
+ const val = resolveVariantValue(v, source);
5427
+ if (val === void 0) continue;
5428
+ if (range.match(val)) values.push(val);
5429
+ }
5430
+ const numValues = values.length;
5431
+ return {
5432
+ type: "double",
5433
+ from: range.start || 0,
5434
+ fromStr: range.start !== null ? Number(range.start).toFixed(1) : "",
5435
+ to: range.stop || 0,
5436
+ toStr: range.stop !== null ? Number(range.stop).toFixed(1) : "",
5437
+ count: numValues,
5438
+ total: values.reduce((a, b) => a + b, 0),
5439
+ min: numValues > 0 ? Math.min(...values) : 0,
5440
+ max: numValues > 0 ? Math.max(...values) : 0,
5441
+ mean: numValues > 0 ? mean(values) : 0
5442
+ };
5443
+ }
5444
+ throw new Error("not supported");
5445
+ }) || []
5400
5446
  };
5401
- return data;
5402
5447
  }
5403
5448
  };
5404
5449
  const mean = (arr) => {
@@ -5629,12 +5674,12 @@ var ProjectUpdateHandler = class extends AbstractUpdateHandler {
5629
5674
  changeCustomerSearchStatus(context, resource, { status }) {
5630
5675
  if (!resource.searchIndexing?.customers) throw new Error("Invalid project state");
5631
5676
  resource.searchIndexing.customers.status = status;
5632
- resource.searchIndexing.customers.lastModifiedAt = new Date().toISOString();
5677
+ resource.searchIndexing.customers.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5633
5678
  }
5634
5679
  changeBusinessUnitSearchStatus(context, resource, { status }) {
5635
5680
  if (!resource.searchIndexing?.businessUnits) throw new Error("Invalid project state");
5636
5681
  resource.searchIndexing.businessUnits.status = status;
5637
- resource.searchIndexing.businessUnits.lastModifiedAt = new Date().toISOString();
5682
+ resource.searchIndexing.businessUnits.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5638
5683
  }
5639
5684
  changeLanguages(context, resource, { languages }) {
5640
5685
  resource.languages = languages;
@@ -5653,18 +5698,18 @@ var ProjectUpdateHandler = class extends AbstractUpdateHandler {
5653
5698
  changeOrderSearchStatus(context, resource, { status }) {
5654
5699
  if (!resource.searchIndexing?.orders) throw new Error("Invalid project state");
5655
5700
  resource.searchIndexing.orders.status = status;
5656
- resource.searchIndexing.orders.lastModifiedAt = new Date().toISOString();
5701
+ resource.searchIndexing.orders.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5657
5702
  }
5658
5703
  changeProductSearchIndexingEnabled(context, resource, { enabled, mode }) {
5659
5704
  if (mode === "ProductsSearch") {
5660
5705
  if (!resource.searchIndexing?.productsSearch) throw new Error("Invalid project state");
5661
5706
  resource.searchIndexing.productsSearch.status = enabled ? "Activated" : "Deactivated";
5662
- resource.searchIndexing.productsSearch.lastModifiedAt = new Date().toISOString();
5707
+ resource.searchIndexing.productsSearch.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5663
5708
  return;
5664
5709
  }
5665
5710
  if (!resource.searchIndexing?.products) throw new Error("Invalid project state");
5666
5711
  resource.searchIndexing.products.status = enabled ? "Activated" : "Deactivated";
5667
- resource.searchIndexing.products.lastModifiedAt = new Date().toISOString();
5712
+ resource.searchIndexing.products.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5668
5713
  }
5669
5714
  setExternalOAuth(context, resource, { externalOAuth }) {
5670
5715
  resource.externalOAuth = externalOAuth;
@@ -5703,7 +5748,7 @@ var QuoteUpdateHandler = class extends AbstractUpdateHandler {
5703
5748
  }
5704
5749
  }
5705
5750
  transitionState(context, resource, { state, force }) {
5706
- let stateReference = void 0;
5751
+ let stateReference;
5707
5752
  if (state) {
5708
5753
  stateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
5709
5754
  resource.state = stateReference;
@@ -5727,7 +5772,7 @@ var QuoteRepository = class extends AbstractResourceRepository {
5727
5772
  const staged = this._storage.getByResourceIdentifier(context.projectKey, draft.stagedQuote);
5728
5773
  const cart = this._storage.getByResourceIdentifier(context.projectKey, staged.quotationCart);
5729
5774
  if (!cart.customerId) throw new Error("Cart does not have a customer");
5730
- const resource = {
5775
+ return {
5731
5776
  ...getBaseResourceProperties(),
5732
5777
  quoteState: "Accepted",
5733
5778
  quoteRequest: staged.quoteRequest,
@@ -5750,7 +5795,6 @@ var QuoteRepository = class extends AbstractResourceRepository {
5750
5795
  billingAddress: cart.billingAddress,
5751
5796
  shippingAddress: cart.shippingAddress
5752
5797
  };
5753
- return resource;
5754
5798
  }
5755
5799
  };
5756
5800
 
@@ -5776,7 +5820,7 @@ var StagedQuoteUpdateHandler = class extends AbstractUpdateHandler {
5776
5820
  }
5777
5821
  }
5778
5822
  transitionState(context, resource, { state, force }) {
5779
- let stateReference = void 0;
5823
+ let stateReference;
5780
5824
  if (state) {
5781
5825
  stateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
5782
5826
  resource.state = stateReference;
@@ -5800,7 +5844,7 @@ var StagedQuoteRepository = class extends AbstractResourceRepository {
5800
5844
  const quoteRequest = this._storage.getByResourceIdentifier(context.projectKey, draft.quoteRequest);
5801
5845
  if (!quoteRequest.cart) throw new Error("Cannot find quote request");
5802
5846
  const cart = this._storage.getByResourceIdentifier(context.projectKey, quoteRequest.cart);
5803
- const resource = {
5847
+ return {
5804
5848
  ...getBaseResourceProperties(),
5805
5849
  stagedQuoteState: "InProgress",
5806
5850
  quoteRequest: {
@@ -5812,7 +5856,6 @@ var StagedQuoteRepository = class extends AbstractResourceRepository {
5812
5856
  id: cart.id
5813
5857
  }
5814
5858
  };
5815
- return resource;
5816
5859
  }
5817
5860
  };
5818
5861
 
@@ -5933,8 +5976,7 @@ var RecurringOrderRepository = class extends AbstractResourceRepository {
5933
5976
  }
5934
5977
  create(context, draft) {
5935
5978
  assert(draft.cart, "draft.cart is missing");
5936
- const orderRepo = new OrderRepository(this.config);
5937
- const initialOrder = orderRepo.createFromCart(context, {
5979
+ const initialOrder = new OrderRepository(this.config).createFromCart(context, {
5938
5980
  id: draft.cart.id,
5939
5981
  typeId: "cart"
5940
5982
  });
@@ -6139,7 +6181,7 @@ var ShippingMethodRepository = class extends AbstractResourceRepository {
6139
6181
  }
6140
6182
  matchingCart(context, cartId, params = {}) {
6141
6183
  const cart = this._storage.get(context.projectKey, "cart", cartId);
6142
- if (!cart) return void 0;
6184
+ if (!cart) return;
6143
6185
  return getShippingMethodsMatchingCart(context, this._storage, cart, params);
6144
6186
  }
6145
6187
  _transformZoneRateDraft(context, draft) {
@@ -6168,12 +6210,11 @@ var ShoppingListUpdateHandler = class extends AbstractUpdateHandler {
6168
6210
  let varId = variantId;
6169
6211
  if (sku) varId = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((x) => x.sku === sku)?.id;
6170
6212
  if (!varId) varId = product.masterData.current.masterVariant.id;
6171
- const alreadyAdded = resource.lineItems.some((x) => x.productId === product?.id && x.variantId === varId);
6172
- if (alreadyAdded) resource.lineItems.forEach((x) => {
6213
+ if (resource.lineItems.some((x) => x.productId === product?.id && x.variantId === varId)) resource.lineItems.forEach((x) => {
6173
6214
  if (x.productId === product?.id && x.variantId === varId) x.quantity += quantity;
6174
6215
  });
6175
6216
  else resource.lineItems.push({
6176
- addedAt: addedAt ? addedAt : new Date().toISOString(),
6217
+ addedAt: addedAt ? addedAt : (/* @__PURE__ */ new Date()).toISOString(),
6177
6218
  id: v4(),
6178
6219
  key,
6179
6220
  productId: product.id,
@@ -6217,8 +6258,7 @@ var ShoppingListUpdateHandler = class extends AbstractUpdateHandler {
6217
6258
  code: "General",
6218
6259
  message: `A line item with ID '${lineItemId}' not found.`
6219
6260
  });
6220
- const shouldDelete = !quantity || quantity >= lineItem.quantity;
6221
- if (shouldDelete) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
6261
+ if (!quantity || quantity >= lineItem.quantity) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
6222
6262
  else resource.lineItems.forEach((x) => {
6223
6263
  if (x.id === lineItemId && quantity) x.quantity -= quantity;
6224
6264
  });
@@ -6315,17 +6355,14 @@ var ShoppingListRepository = class extends AbstractResourceRepository {
6315
6355
  const items = this._storage.query(projectKey, "product", { where: [`masterData(current(masterVariant(sku="${sku}"))) or masterData(current(variants(sku="${sku}")))`] });
6316
6356
  if (items.count === 0) throw new Error(`Product with sku ${sku} not found`);
6317
6357
  const product = items.results[0];
6318
- const allVariants = [product.masterData.current.masterVariant, ...product.masterData.current.variants];
6319
- const variantId$1 = allVariants.find((e) => e.sku === sku)?.id;
6320
- lineItem.variantId = variantId$1;
6358
+ lineItem.variantId = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((e) => e.sku === sku)?.id;
6321
6359
  lineItem.productId = product.id;
6322
6360
  return lineItem;
6323
6361
  }
6324
6362
  if (productId) {
6325
6363
  const items = this._storage.query(projectKey, "product", { where: [`id="${productId}"`] });
6326
6364
  if (items.count === 0) throw new Error(`Product with id ${productId} not found`);
6327
- const variantId$1 = items.results[0].masterData.current.masterVariant.id;
6328
- lineItem.variantId = variantId$1;
6365
+ lineItem.variantId = items.results[0].masterData.current.masterVariant.id;
6329
6366
  return lineItem;
6330
6367
  }
6331
6368
  throw new Error("must provide either sku, productId or variantId for ShoppingListLineItem");
@@ -6490,9 +6527,7 @@ var SubscriptionRepository = class extends AbstractResourceRepository {
6490
6527
  }
6491
6528
  create(context, draft) {
6492
6529
  if (draft.destination.type === "SQS") {
6493
- const queueURL = new URL(draft.destination.queueUrl);
6494
- const accountId = queueURL.pathname.split("/")[1];
6495
- if (accountId === "0000000000") {
6530
+ if (new URL(draft.destination.queueUrl).pathname.split("/")[1] === "0000000000") {
6496
6531
  const dest = draft.destination;
6497
6532
  throw new CommercetoolsError({
6498
6533
  code: "InvalidInput",
@@ -6544,10 +6579,7 @@ var TaxCategoryUpdateHandler = class extends AbstractUpdateHandler {
6544
6579
  replaceTaxRate(context, resource, { taxRateId, taxRate }) {
6545
6580
  if (resource.rates === void 0) resource.rates = [];
6546
6581
  const taxRateObj = taxRateFromTaxRateDraft(taxRate);
6547
- for (let i = 0; i < resource.rates.length; i++) {
6548
- const rate = resource.rates[i];
6549
- if (rate.id === taxRateId) resource.rates[i] = taxRateObj;
6550
- }
6582
+ for (let i = 0; i < resource.rates.length; i++) if (resource.rates[i].id === taxRateId) resource.rates[i] = taxRateObj;
6551
6583
  }
6552
6584
  setDescription(context, resource, { description }) {
6553
6585
  resource.description = description;
@@ -6755,11 +6787,10 @@ const validateData = (data, schema) => {
6755
6787
  schema.parse(data);
6756
6788
  return data;
6757
6789
  } catch (err) {
6758
- const validationError = fromZodError(err);
6759
6790
  throw new CommercetoolsError({
6760
6791
  code: "InvalidJsonInput",
6761
6792
  message: "Request body does not contain valid JSON.",
6762
- detailedErrorMessage: validationError.toString()
6793
+ detailedErrorMessage: fromZodError(err).toString()
6763
6794
  });
6764
6795
  }
6765
6796
  };
@@ -6801,7 +6832,6 @@ var AbstractService = class {
6801
6832
  }
6802
6833
  const result = this.repository.query(getRepositoryContext(request), params);
6803
6834
  response.status(200).send(result);
6804
- return;
6805
6835
  }
6806
6836
  getWithId(request, response) {
6807
6837
  const result = this._expandWithId(request, request.params.id);
@@ -6883,8 +6913,7 @@ var AbstractService = class {
6883
6913
  response.status(200).send(result);
6884
6914
  }
6885
6915
  _expandWithId(request, resourceId) {
6886
- const result = this.repository.get(getRepositoryContext(request), resourceId, { expand: this._parseParam(request.query.expand) });
6887
- return result;
6916
+ return this.repository.get(getRepositoryContext(request), resourceId, { expand: this._parseParam(request.query.expand) });
6888
6917
  }
6889
6918
  _parseParam(value) {
6890
6919
  return queryParamsArray(value);
@@ -7171,8 +7200,7 @@ var CustomerService = class extends AbstractService {
7171
7200
  post(request, response) {
7172
7201
  const draft = request.body;
7173
7202
  const resource = this.repository.create(getRepositoryContext(request), draft);
7174
- const expanded = this._expandWithId(request, resource.id);
7175
- const result = { customer: expanded };
7203
+ const result = { customer: this._expandWithId(request, resource.id) };
7176
7204
  response.status(this.createStatusCode).send(result);
7177
7205
  }
7178
7206
  passwordResetToken(request, response) {
@@ -7482,12 +7510,7 @@ var OrderService = class extends AbstractService {
7482
7510
  }
7483
7511
  getWithOrderNumber(request, response) {
7484
7512
  const orderNumber = request.params.orderNumber;
7485
- const resource = this.repository.getWithOrderNumber(
7486
- getRepositoryContext(request),
7487
- orderNumber,
7488
- // @ts-ignore
7489
- request.query
7490
- );
7513
+ const resource = this.repository.getWithOrderNumber(getRepositoryContext(request), orderNumber, request.query);
7491
7514
  if (resource) {
7492
7515
  response.status(200).send(resource);
7493
7516
  return;
@@ -7725,7 +7748,6 @@ var ShippingMethodService = class extends AbstractService {
7725
7748
  }
7726
7749
  const result = this.repository.matchingCart(getRepositoryContext(request), cartId, { expand: this._parseParam(request.query.expand) });
7727
7750
  response.status(200).send(result);
7728
- return;
7729
7751
  }
7730
7752
  };
7731
7753
 
@@ -7987,44 +8009,44 @@ var InMemoryStorage = class extends AbstractStorage {
7987
8009
  this.addProject(projectKey);
7988
8010
  let projectStorage = this.resources[projectKey];
7989
8011
  if (!projectStorage) projectStorage = this.resources[projectKey] = {
7990
- "associate-role": new Map(),
7991
- "attribute-group": new Map(),
7992
- "business-unit": new Map(),
7993
- cart: new Map(),
7994
- "cart-discount": new Map(),
7995
- category: new Map(),
7996
- channel: new Map(),
7997
- customer: new Map(),
7998
- "customer-group": new Map(),
7999
- "discount-code": new Map(),
8000
- "discount-group": new Map(),
8001
- extension: new Map(),
8002
- "inventory-entry": new Map(),
8003
- "key-value-document": new Map(),
8004
- order: new Map(),
8005
- "order-edit": new Map(),
8006
- payment: new Map(),
8007
- product: new Map(),
8008
- quote: new Map(),
8009
- "quote-request": new Map(),
8010
- "product-discount": new Map(),
8011
- "product-selection": new Map(),
8012
- "product-type": new Map(),
8013
- "product-projection": new Map(),
8014
- "product-tailoring": new Map(),
8015
- "recurrence-policy": new Map(),
8016
- "recurring-order": new Map(),
8017
- review: new Map(),
8018
- "shipping-method": new Map(),
8019
- "staged-quote": new Map(),
8020
- state: new Map(),
8021
- store: new Map(),
8022
- "shopping-list": new Map(),
8023
- "standalone-price": new Map(),
8024
- subscription: new Map(),
8025
- "tax-category": new Map(),
8026
- type: new Map(),
8027
- zone: new Map()
8012
+ "associate-role": /* @__PURE__ */ new Map(),
8013
+ "attribute-group": /* @__PURE__ */ new Map(),
8014
+ "business-unit": /* @__PURE__ */ new Map(),
8015
+ cart: /* @__PURE__ */ new Map(),
8016
+ "cart-discount": /* @__PURE__ */ new Map(),
8017
+ category: /* @__PURE__ */ new Map(),
8018
+ channel: /* @__PURE__ */ new Map(),
8019
+ customer: /* @__PURE__ */ new Map(),
8020
+ "customer-group": /* @__PURE__ */ new Map(),
8021
+ "discount-code": /* @__PURE__ */ new Map(),
8022
+ "discount-group": /* @__PURE__ */ new Map(),
8023
+ extension: /* @__PURE__ */ new Map(),
8024
+ "inventory-entry": /* @__PURE__ */ new Map(),
8025
+ "key-value-document": /* @__PURE__ */ new Map(),
8026
+ order: /* @__PURE__ */ new Map(),
8027
+ "order-edit": /* @__PURE__ */ new Map(),
8028
+ payment: /* @__PURE__ */ new Map(),
8029
+ product: /* @__PURE__ */ new Map(),
8030
+ quote: /* @__PURE__ */ new Map(),
8031
+ "quote-request": /* @__PURE__ */ new Map(),
8032
+ "product-discount": /* @__PURE__ */ new Map(),
8033
+ "product-selection": /* @__PURE__ */ new Map(),
8034
+ "product-type": /* @__PURE__ */ new Map(),
8035
+ "product-projection": /* @__PURE__ */ new Map(),
8036
+ "product-tailoring": /* @__PURE__ */ new Map(),
8037
+ "recurrence-policy": /* @__PURE__ */ new Map(),
8038
+ "recurring-order": /* @__PURE__ */ new Map(),
8039
+ review: /* @__PURE__ */ new Map(),
8040
+ "shipping-method": /* @__PURE__ */ new Map(),
8041
+ "staged-quote": /* @__PURE__ */ new Map(),
8042
+ state: /* @__PURE__ */ new Map(),
8043
+ store: /* @__PURE__ */ new Map(),
8044
+ "shopping-list": /* @__PURE__ */ new Map(),
8045
+ "standalone-price": /* @__PURE__ */ new Map(),
8046
+ subscription: /* @__PURE__ */ new Map(),
8047
+ "tax-category": /* @__PURE__ */ new Map(),
8048
+ type: /* @__PURE__ */ new Map(),
8049
+ zone: /* @__PURE__ */ new Map()
8028
8050
  };
8029
8051
  return projectStorage;
8030
8052
  }
@@ -8037,8 +8059,7 @@ var InMemoryStorage = class extends AbstractStorage {
8037
8059
  return [];
8038
8060
  }
8039
8061
  add(projectKey, typeId, obj, params = {}) {
8040
- const store = this.forProjectKey(projectKey);
8041
- store[typeId]?.set(obj.id, obj);
8062
+ this.forProjectKey(projectKey)[typeId]?.set(obj.id, obj);
8042
8063
  const resource = this.get(projectKey, typeId, obj.id, params);
8043
8064
  assert(resource, `resource of type ${typeId} with id ${obj.id} not created`);
8044
8065
  return cloneObject(resource);
@@ -8055,8 +8076,7 @@ var InMemoryStorage = class extends AbstractStorage {
8055
8076
  const store = this.forProjectKey(projectKey);
8056
8077
  const resourceStore = store[typeId];
8057
8078
  if (!store) throw new Error("No type");
8058
- const resources = Array.from(resourceStore.values());
8059
- const resource = resources.find((e) => e.key === key);
8079
+ const resource = Array.from(resourceStore.values()).find((e) => e.key === key);
8060
8080
  if (resource) {
8061
8081
  const clone = cloneObject(resource);
8062
8082
  return this.expand(projectKey, clone, params.expand);
@@ -8072,8 +8092,7 @@ var InMemoryStorage = class extends AbstractStorage {
8072
8092
  return resource;
8073
8093
  }
8074
8094
  query(projectKey, typeId, params) {
8075
- const store = this.forProjectKey(projectKey)[typeId];
8076
- if (!store) throw new Error("No type");
8095
+ if (!this.forProjectKey(projectKey)[typeId]) throw new Error("No type");
8077
8096
  let resources = this.all(projectKey, typeId);
8078
8097
  if (params.where) {
8079
8098
  const vars = Object.fromEntries(Object.entries(params).filter(([key]) => key.startsWith("var.")).map(([key, value]) => [key.slice(4), value]));
@@ -8168,8 +8187,7 @@ var InMemoryStorage = class extends AbstractStorage {
8168
8187
  id: lineItem.productId
8169
8188
  });
8170
8189
  if (!product) return;
8171
- const variant = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((e) => e.id === lineItem.variantId);
8172
- lineItem.variant = variant;
8190
+ lineItem.variant = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((e) => e.id === lineItem.variantId);
8173
8191
  }
8174
8192
  };
8175
8193
 
@@ -8233,17 +8251,14 @@ var CommercetoolsMock = class {
8233
8251
  return this._oauth2.store;
8234
8252
  }
8235
8253
  runServer(port = 3e3, options) {
8236
- const server = this.app.listen(port, () => {
8237
- console.info(`Mock server listening at http://localhost:${port}`);
8238
- });
8254
+ const server = this.app.listen(port, () => {});
8239
8255
  server.keepAliveTimeout = 60 * 1e3;
8240
8256
  }
8241
8257
  createApp(options) {
8242
- const config = {
8258
+ this._repositories = createRepositories({
8243
8259
  strict: this.options.strict,
8244
8260
  storage: this._storage
8245
- };
8246
- this._repositories = createRepositories(config);
8261
+ });
8247
8262
  this._oauth2.setCustomerRepository(this._repositories.customer);
8248
8263
  const app = express();
8249
8264
  app.use(express.json({ limit: "16mb" }));
@@ -8276,9 +8291,7 @@ var CommercetoolsMock = class {
8276
8291
  });
8277
8292
  return;
8278
8293
  }
8279
- console.error(err);
8280
8294
  resp.status(500).send({ error: err.message });
8281
- return;
8282
8295
  });
8283
8296
  return app;
8284
8297
  }
@@ -8306,9 +8319,8 @@ var CommercetoolsMock = class {
8306
8319
  const res = await inject(app).get(`${url.pathname}?${url.searchParams.toString()}`).body(body).headers(headers).end();
8307
8320
  if (res.statusCode === 200) {
8308
8321
  const parsedBody = JSON.parse(res.body);
8309
- const resultCount = "count" in parsedBody ? parsedBody.count : Object.keys(parsedBody).length;
8310
8322
  return new HttpResponse(null, {
8311
- status: resultCount > 0 ? 200 : 404,
8323
+ status: ("count" in parsedBody ? parsedBody.count : Object.keys(parsedBody).length) > 0 ? 200 : 404,
8312
8324
  headers: mapHeaderType(res.headers)
8313
8325
  });
8314
8326
  }
@@ -8356,13 +8368,13 @@ var CommercetoolsMock = class {
8356
8368
  if (_globalListeners.length > 0) {
8357
8369
  if (this._mswServer !== void 0) throw new Error("Server already started");
8358
8370
  process.emitWarning("Server wasn't stopped properly, clearing");
8359
- _globalListeners.forEach((listener) => listener.close());
8371
+ for (const listener of _globalListeners) listener.close();
8372
+ _globalListeners.length = 0;
8360
8373
  }
8361
8374
  const server = setupServer();
8362
8375
  this.registerHandlers(server);
8363
8376
  server.listen({ onUnhandledRequest: (request, print) => {
8364
- const url = new URL(request.url);
8365
- if (url.hostname === "127.0.0.1") return;
8377
+ if (new URL(request.url).hostname === "127.0.0.1") return;
8366
8378
  print.error();
8367
8379
  } });
8368
8380
  _globalListeners.push(server);
@@ -8372,4 +8384,4 @@ var CommercetoolsMock = class {
8372
8384
 
8373
8385
  //#endregion
8374
8386
  export { CommercetoolsMock, getBaseResourceProperties };
8375
- //# sourceMappingURL=index.js.map
8387
+ //# sourceMappingURL=index.mjs.map