@labdigital/commercetools-mock 2.8.0 → 2.9.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.
package/dist/index.cjs CHANGED
@@ -720,7 +720,7 @@ var resolveValue = (obj, val) => {
720
720
  if (Array.isArray(obj)) {
721
721
  return Object.values(obj).filter((v) => val.value in v).map((v) => v[val.value]);
722
722
  }
723
- throw new PredicateError(`The field '${val.value}' does not exist.`);
723
+ return void 0;
724
724
  }
725
725
  return obj[val.value];
726
726
  };
@@ -800,22 +800,43 @@ var generateMatchFunc = (predicate) => {
800
800
  const expr = parser.parse();
801
801
  lexer.expect(")");
802
802
  return (obj, vars) => {
803
- const value = resolveValue(obj, left);
804
- if (value) {
805
- return expr(value, vars);
803
+ if (Array.isArray(obj)) {
804
+ return obj.some((item) => {
805
+ const value = resolveValue(item, left);
806
+ if (value) {
807
+ return expr(value, vars);
808
+ }
809
+ return false;
810
+ });
811
+ } else {
812
+ const value = resolveValue(obj, left);
813
+ if (value) {
814
+ return expr(value, vars);
815
+ }
816
+ return false;
806
817
  }
807
- return false;
808
818
  };
809
819
  }).bp(")", 0).led("=", 20, ({ left, bp }) => {
810
820
  const expr = parser.parse({ terminals: [bp - 1] });
811
821
  validateSymbol(expr);
812
822
  return (obj, vars) => {
813
- const resolvedValue = resolveValue(obj, left);
814
- const resolvedSymbol = resolveSymbol(expr, vars);
815
- if (Array.isArray(resolvedValue)) {
816
- return !!resolvedValue.some((elem) => elem === resolvedSymbol);
823
+ if (Array.isArray(obj)) {
824
+ return obj.some((item) => {
825
+ const value = resolveValue(item, left);
826
+ const other = resolveSymbol(expr, vars);
827
+ if (Array.isArray(value)) {
828
+ return !!value.some((elem) => elem === other);
829
+ }
830
+ return value === other;
831
+ });
832
+ } else {
833
+ const resolvedValue = resolveValue(obj, left);
834
+ const resolvedSymbol = resolveSymbol(expr, vars);
835
+ if (Array.isArray(resolvedValue)) {
836
+ return !!resolvedValue.some((elem) => elem === resolvedSymbol);
837
+ }
838
+ return resolvedValue === resolvedSymbol;
817
839
  }
818
- return resolvedValue === resolvedSymbol;
819
840
  };
820
841
  }).led("!=", 20, ({ left, bp }) => {
821
842
  const expr = parser.parse({ terminals: [bp - 1] });
@@ -883,10 +904,11 @@ var generateMatchFunc = (predicate) => {
883
904
  if (!Array.isArray(symbols)) {
884
905
  symbols = [expr];
885
906
  }
886
- const inValues = symbols.map(
907
+ const inValues = symbols.flatMap(
887
908
  (item) => resolveSymbol(item, vars)
888
909
  );
889
- return inValues.includes(resolveValue(obj, left));
910
+ const value = resolveValue(obj, left);
911
+ return inValues.includes(value);
890
912
  };
891
913
  }).led("MATCHES_IGNORE_CASE", 20, ({ left, bp }) => {
892
914
  const expr = parser.parse({ terminals: [bp - 1] });
@@ -1064,9 +1086,12 @@ var InMemoryStorage = class extends AbstractStorage {
1064
1086
  }
1065
1087
  let resources = this.all(projectKey, typeId);
1066
1088
  if (params.where) {
1089
+ const vars = Object.fromEntries(
1090
+ Object.entries(params).filter(([key]) => key.startsWith("var.")).map(([key, value]) => [key.slice(4), value])
1091
+ );
1067
1092
  try {
1068
1093
  const filterFunc = parseQueryExpression(params.where);
1069
- resources = resources.filter((resource) => filterFunc(resource, {}));
1094
+ resources = resources.filter((resource) => filterFunc(resource, vars));
1070
1095
  } catch (err) {
1071
1096
  throw new CommercetoolsError(
1072
1097
  {
@@ -1133,28 +1158,34 @@ var InMemoryStorage = class extends AbstractStorage {
1133
1158
  if (resource) {
1134
1159
  return resource;
1135
1160
  }
1136
- console.error(
1137
- `No resource found with typeId=${identifier.typeId}, id=${identifier.id}`
1138
- );
1139
- return null;
1161
+ throw new CommercetoolsError({
1162
+ code: "ReferencedResourceNotFound",
1163
+ message: `The referenced object of type '${identifier.typeId}' with id '${identifier.id}' was not found. It either doesn't exist, or it can't be accessed from this endpoint (e.g., if the endpoint filters by store or customer account).`,
1164
+ typeId: identifier.typeId,
1165
+ id: identifier.id
1166
+ });
1140
1167
  }
1141
1168
  if (identifier.key) {
1142
- const store = this.forProjectKey(projectKey)[identifier.typeId];
1143
- if (store) {
1144
- const resource = Array.from(store.values()).find(
1145
- // @ts-ignore
1146
- (r) => r.key === identifier.key
1147
- );
1148
- if (resource) {
1149
- return resource;
1150
- }
1151
- } else {
1152
- throw new Error(
1153
- `No storage found for resource type: ${identifier.typeId}`
1154
- );
1169
+ const resource = this.getByKey(
1170
+ projectKey,
1171
+ identifier.typeId,
1172
+ identifier.key
1173
+ );
1174
+ if (resource) {
1175
+ return resource;
1155
1176
  }
1177
+ throw new CommercetoolsError({
1178
+ code: "ReferencedResourceNotFound",
1179
+ message: `The referenced object of type '${identifier.typeId}' with key '${identifier.key}' was not found. It either doesn't exist, or it can't be accessed from this endpoint (e.g., if the endpoint filters by store or customer account).`,
1180
+ typeId: identifier.typeId,
1181
+ key: identifier.key
1182
+ });
1156
1183
  }
1157
- return null;
1184
+ throw new CommercetoolsError({
1185
+ code: "InvalidJsonInput",
1186
+ message: "Request body does not contain valid JSON.",
1187
+ detailedErrorMessage: "ResourceIdentifier requires an 'id' xor a 'key'"
1188
+ });
1158
1189
  }
1159
1190
  addProject = (projectKey) => {
1160
1191
  if (!this.projects[projectKey]) {
@@ -1308,11 +1339,12 @@ var hashPassword = (clearPassword) => Buffer.from(clearPassword).toString("base6
1308
1339
 
1309
1340
  // src/oauth/server.ts
1310
1341
  var OAuth2Server = class {
1311
- store;
1312
- customerRepository;
1313
1342
  constructor(options) {
1343
+ this.options = options;
1314
1344
  this.store = new OAuth2Store(options.validate);
1315
1345
  }
1346
+ store;
1347
+ customerRepository;
1316
1348
  setCustomerRepository(repository) {
1317
1349
  this.customerRepository = repository;
1318
1350
  }
@@ -1336,6 +1368,11 @@ var OAuth2Server = class {
1336
1368
  return router;
1337
1369
  }
1338
1370
  createMiddleware() {
1371
+ if (!this.options.validate) {
1372
+ return async (request, response, next) => {
1373
+ next();
1374
+ };
1375
+ }
1339
1376
  return async (request, response, next) => {
1340
1377
  const token = getBearerToken(request);
1341
1378
  if (!token) {
@@ -1873,10 +1910,7 @@ var AbstractResourceRepository = class extends AbstractRepository {
1873
1910
  }
1874
1911
  query(context, params = {}) {
1875
1912
  const result = this._storage.query(context.projectKey, this.getTypeId(), {
1876
- expand: params.expand,
1877
- where: params.where,
1878
- offset: params.offset,
1879
- limit: params.limit
1913
+ ...params
1880
1914
  });
1881
1915
  result.results = result.results.map(this.postProcessResource);
1882
1916
  return result;
@@ -2196,6 +2230,11 @@ var CartRepository = class extends AbstractResourceRepository {
2196
2230
  fractionDigits: 0
2197
2231
  },
2198
2232
  shippingMode: "Single",
2233
+ shippingAddress: createAddress(
2234
+ draft.shippingAddress,
2235
+ context.projectKey,
2236
+ this._storage
2237
+ ),
2199
2238
  shipping: [],
2200
2239
  origin: draft.origin ?? "Customer",
2201
2240
  refusedGifts: [],
@@ -2397,9 +2436,6 @@ var CartRepository = class extends AbstractResourceRepository {
2397
2436
  context.projectKey,
2398
2437
  shippingMethod
2399
2438
  );
2400
- if (!method) {
2401
- throw new Error(`Type ${shippingMethod} not found`);
2402
- }
2403
2439
  resource.shippingInfo = {
2404
2440
  shippingMethod: {
2405
2441
  typeId: "shipping-method",
@@ -2423,6 +2459,33 @@ var CartRepository = class extends AbstractResourceRepository {
2423
2459
  }
2424
2460
  resource.custom.fields[name] = value;
2425
2461
  },
2462
+ setCustomShippingMethod: (context, resource, {
2463
+ shippingMethodName,
2464
+ shippingRate,
2465
+ taxCategory,
2466
+ externalTaxRate
2467
+ }) => {
2468
+ if (externalTaxRate) {
2469
+ throw new Error("External tax rate is not supported");
2470
+ }
2471
+ const tax = taxCategory ? this._storage.getByResourceIdentifier(
2472
+ context.projectKey,
2473
+ taxCategory
2474
+ ) : void 0;
2475
+ resource.shippingInfo = {
2476
+ shippingMethodName,
2477
+ price: createCentPrecisionMoney(shippingRate.price),
2478
+ shippingRate: {
2479
+ price: createTypedMoney(shippingRate.price),
2480
+ tiers: []
2481
+ },
2482
+ taxCategory: tax ? {
2483
+ typeId: "tax-category",
2484
+ id: tax?.id
2485
+ } : void 0,
2486
+ shippingMethodState: "MatchesCart"
2487
+ };
2488
+ },
2426
2489
  setCustomType: (context, resource, { type, fields }) => {
2427
2490
  if (!type) {
2428
2491
  resource.custom = void 0;
@@ -2974,6 +3037,16 @@ var CustomObjectRepository = class extends AbstractResourceRepository {
2974
3037
  return resource;
2975
3038
  }
2976
3039
  }
3040
+ queryWithContainer(context, container, params = {}) {
3041
+ const whereClause = params.where || [];
3042
+ whereClause.push(`container="${container}"`);
3043
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
3044
+ ...params,
3045
+ where: whereClause
3046
+ });
3047
+ result.results = result.results.map(this.postProcessResource);
3048
+ return result;
3049
+ }
2977
3050
  getWithContainerAndKey(context, container, key) {
2978
3051
  const items = this._storage.all(context.projectKey, this.getTypeId());
2979
3052
  return items.find(
@@ -5502,6 +5575,50 @@ var ReviewRepository = class extends AbstractResourceRepository {
5502
5575
 
5503
5576
  // src/repositories/shipping-method.ts
5504
5577
  var import_deep_equal3 = __toESM(require("deep-equal"), 1);
5578
+
5579
+ // src/shippingCalculator.ts
5580
+ var markMatchingShippingRate = (cart, shippingRate) => {
5581
+ const isMatching = shippingRate.price.currencyCode === cart.totalPrice.currencyCode;
5582
+ return {
5583
+ ...shippingRate,
5584
+ tiers: markMatchingShippingRatePriceTiers(cart, shippingRate.tiers),
5585
+ isMatching
5586
+ };
5587
+ };
5588
+ var markMatchingShippingRatePriceTiers = (cart, tiers) => {
5589
+ if (tiers.length === 0) {
5590
+ return [];
5591
+ }
5592
+ if (new Set(tiers.map((tier) => tier.type)).size > 1) {
5593
+ throw new Error("Can't handle multiple types of tiers");
5594
+ }
5595
+ const tierType = tiers[0].type;
5596
+ switch (tierType) {
5597
+ case "CartValue":
5598
+ return markMatchingCartValueTiers(cart, tiers);
5599
+ default:
5600
+ throw new Error(`Unsupported tier type: ${tierType}`);
5601
+ }
5602
+ };
5603
+ var markMatchingCartValueTiers = (cart, tiers) => {
5604
+ const sortedTiers = [...tiers].sort(
5605
+ (a, b) => b.minimumCentAmount - a.minimumCentAmount
5606
+ );
5607
+ const result = {};
5608
+ let hasMatchingTier = false;
5609
+ for (const tier of sortedTiers) {
5610
+ const isMatching = !hasMatchingTier && cart.totalPrice.currencyCode === tier.price.currencyCode && cart.totalPrice.centAmount >= tier.minimumCentAmount;
5611
+ if (isMatching)
5612
+ hasMatchingTier = true;
5613
+ result[tier.minimumCentAmount] = {
5614
+ ...tier,
5615
+ isMatching
5616
+ };
5617
+ }
5618
+ return tiers.map((tier) => result[tier.minimumCentAmount]);
5619
+ };
5620
+
5621
+ // src/repositories/shipping-method.ts
5505
5622
  var ShippingMethodRepository = class extends AbstractResourceRepository {
5506
5623
  getTypeId() {
5507
5624
  return "shipping-method";
@@ -5541,6 +5658,53 @@ var ShippingMethodRepository = class extends AbstractResourceRepository {
5541
5658
  freeAbove: rate.freeAbove && createTypedMoney(rate.freeAbove),
5542
5659
  tiers: rate.tiers || []
5543
5660
  });
5661
+ /*
5662
+ * Retrieves all the ShippingMethods that can ship to the shipping address of
5663
+ * the given Cart. Each ShippingMethod contains exactly one ShippingRate with
5664
+ * the flag isMatching set to true. This ShippingRate is used when the
5665
+ * ShippingMethod is added to the Cart.
5666
+ */
5667
+ matchingCart(context, cartId, params = {}) {
5668
+ const cart = this._storage.get(context.projectKey, "cart", cartId);
5669
+ if (!cart) {
5670
+ return void 0;
5671
+ }
5672
+ if (!cart.shippingAddress?.country) {
5673
+ throw new CommercetoolsError({
5674
+ code: "InvalidOperation",
5675
+ message: `The cart with ID '${cart.id}' does not have a shipping address set.`
5676
+ });
5677
+ }
5678
+ const zones = this._storage.query(context.projectKey, "zone", {
5679
+ where: [`locations(country="${cart.shippingAddress.country}"))`],
5680
+ limit: 100
5681
+ });
5682
+ const zoneIds = zones.results.map((zone) => zone.id);
5683
+ const shippingMethods = this.query(context, {
5684
+ where: [
5685
+ `zoneRates(zone(id in (:zoneIds)))`,
5686
+ `zoneRates(shippingRates(price(currencyCode="${cart.totalPrice.currencyCode}")))`
5687
+ ],
5688
+ "var.zoneIds": zoneIds,
5689
+ expand: params.expand
5690
+ });
5691
+ const results = shippingMethods.results.map((shippingMethod) => {
5692
+ const rates = shippingMethod.zoneRates.map((zoneRate) => ({
5693
+ zone: zoneRate.zone,
5694
+ // Iterate through the shippingRates and mark the matching ones
5695
+ // then we filter out the non-matching ones
5696
+ shippingRates: zoneRate.shippingRates.map((rate) => markMatchingShippingRate(cart, rate)).filter((rate) => rate.isMatching)
5697
+ })).filter((zoneRate) => zoneRate.shippingRates.length > 0);
5698
+ return {
5699
+ ...shippingMethod,
5700
+ zoneRates: rates
5701
+ };
5702
+ }).filter((shippingMethod) => shippingMethod.zoneRates.length > 0);
5703
+ return {
5704
+ ...shippingMethods,
5705
+ results
5706
+ };
5707
+ }
5544
5708
  actions = {
5545
5709
  addShippingRate: (_context, resource, { shippingRate, zone }) => {
5546
5710
  const rate = this._transformShippingRate(shippingRate);
@@ -6394,10 +6558,26 @@ var CustomObjectService = class extends AbstractService {
6394
6558
  return "custom-objects";
6395
6559
  }
6396
6560
  extraRoutes(router) {
6561
+ router.get("/:container", this.getWithContainer.bind(this));
6397
6562
  router.get("/:container/:key", this.getWithContainerAndKey.bind(this));
6398
6563
  router.post("/:container/:key", this.createWithContainerAndKey.bind(this));
6399
6564
  router.delete("/:container/:key", this.deleteWithContainerAndKey.bind(this));
6400
6565
  }
6566
+ getWithContainer(request, response) {
6567
+ const limit = this._parseParam(request.query.limit);
6568
+ const offset = this._parseParam(request.query.offset);
6569
+ const result = this.repository.queryWithContainer(
6570
+ getRepositoryContext(request),
6571
+ request.params.container,
6572
+ {
6573
+ expand: this._parseParam(request.query.expand),
6574
+ where: this._parseParam(request.query.where),
6575
+ limit: limit !== void 0 ? Number(limit) : void 0,
6576
+ offset: offset !== void 0 ? Number(offset) : void 0
6577
+ }
6578
+ );
6579
+ return response.status(200).send(result);
6580
+ }
6401
6581
  getWithContainerAndKey(request, response) {
6402
6582
  const result = this.repository.getWithContainerAndKey(
6403
6583
  getRepositoryContext(request),
@@ -6836,7 +7016,21 @@ var ShippingMethodService = class extends AbstractService {
6836
7016
  return "shipping-methods";
6837
7017
  }
6838
7018
  extraRoutes(parent) {
6839
- parent.get("/matching-cart", this.get.bind(this));
7019
+ parent.get("/matching-cart", this.matchingCart.bind(this));
7020
+ }
7021
+ matchingCart(request, response) {
7022
+ const cartId = queryParamsValue(request.query.cartId);
7023
+ if (!cartId) {
7024
+ return response.status(400).send();
7025
+ }
7026
+ const result = this.repository.matchingCart(
7027
+ getRepositoryContext(request),
7028
+ cartId,
7029
+ {
7030
+ expand: this._parseParam(request.query.expand)
7031
+ }
7032
+ );
7033
+ return response.status(200).send(result);
6840
7034
  }
6841
7035
  };
6842
7036