@labdigital/commercetools-mock 0.5.19 → 0.5.22

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 (41) hide show
  1. package/dist/commercetools-mock.cjs.development.js +478 -335
  2. package/dist/commercetools-mock.cjs.development.js.map +1 -1
  3. package/dist/commercetools-mock.cjs.production.min.js +1 -1
  4. package/dist/commercetools-mock.cjs.production.min.js.map +1 -1
  5. package/dist/commercetools-mock.esm.js +478 -335
  6. package/dist/commercetools-mock.esm.js.map +1 -1
  7. package/dist/repositories/customer.d.ts +5 -1
  8. package/dist/repositories/order.d.ts +2 -1
  9. package/dist/repositories/store.d.ts +1 -0
  10. package/dist/services/cart.d.ts +3 -0
  11. package/dist/services/customer.d.ts +1 -0
  12. package/dist/services/my-customer.d.ts +1 -0
  13. package/dist/services/my-order.d.ts +10 -0
  14. package/dist/services/store.d.ts +3 -1
  15. package/dist/types.d.ts +1 -1
  16. package/package.json +1 -1
  17. package/src/.env +0 -0
  18. package/src/ctMock.ts +2 -0
  19. package/src/lib/masking.ts +1 -3
  20. package/src/repositories/abstract.ts +1 -0
  21. package/src/repositories/category.ts +6 -6
  22. package/src/repositories/customer.ts +14 -0
  23. package/src/repositories/helpers.ts +0 -1
  24. package/src/repositories/order.ts +22 -0
  25. package/src/repositories/product-type.ts +3 -3
  26. package/src/repositories/project.ts +0 -1
  27. package/src/repositories/shipping-method.ts +11 -12
  28. package/src/repositories/store.ts +15 -0
  29. package/src/repositories/subscription.ts +2 -2
  30. package/src/repositories/tax-category.ts +1 -1
  31. package/src/repositories/type.ts +10 -10
  32. package/src/repositories/zone.ts +3 -1
  33. package/src/services/cart.ts +32 -0
  34. package/src/services/customer.ts +21 -0
  35. package/src/services/my-customer.ts +25 -0
  36. package/src/services/my-order.ts +35 -0
  37. package/src/services/product.test.ts +1 -5
  38. package/src/services/project.ts +1 -1
  39. package/src/services/shipping-method.ts +1 -1
  40. package/src/services/store.ts +16 -1
  41. package/src/types.ts +1 -0
@@ -1579,16 +1579,308 @@ const calculateLineItemTotalPrice = lineItem => lineItem.price.value.centAmount
1579
1579
 
1580
1580
  const calculateCartTotalPrice = cart => cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
1581
1581
 
1582
+ class OrderRepository extends AbstractResourceRepository {
1583
+ constructor() {
1584
+ super(...arguments);
1585
+ this.actions = {
1586
+ addPayment: (projectKey, resource, {
1587
+ payment
1588
+ }) => {
1589
+ const resolvedPayment = this._storage.getByResourceIdentifier(projectKey, payment);
1590
+
1591
+ if (!resolvedPayment) {
1592
+ throw new Error(`Payment ${payment.id} not found`);
1593
+ }
1594
+
1595
+ if (!resource.paymentInfo) {
1596
+ resource.paymentInfo = {
1597
+ payments: []
1598
+ };
1599
+ }
1600
+
1601
+ resource.paymentInfo.payments.push({
1602
+ typeId: 'payment',
1603
+ id: payment.id
1604
+ });
1605
+ },
1606
+ changeOrderState: (projectKey, resource, {
1607
+ orderState
1608
+ }) => {
1609
+ resource.orderState = orderState;
1610
+ },
1611
+ changePaymentState: (projectKey, resource, {
1612
+ paymentState
1613
+ }) => {
1614
+ resource.paymentState = paymentState;
1615
+ },
1616
+ transitionState: (projectKey, resource, {
1617
+ state
1618
+ }) => {
1619
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, state);
1620
+
1621
+ if (!resolvedType) {
1622
+ throw new Error(`No state found with key=${state.key} or id=${state.key}`);
1623
+ }
1624
+
1625
+ resource.state = {
1626
+ typeId: 'state',
1627
+ id: resolvedType.id
1628
+ };
1629
+ },
1630
+ setBillingAddress: (projectKey, resource, {
1631
+ address
1632
+ }) => {
1633
+ resource.billingAddress = address;
1634
+ },
1635
+ setCustomerEmail: (projectKey, resource, {
1636
+ email
1637
+ }) => {
1638
+ resource.customerEmail = email;
1639
+ },
1640
+ setCustomField: (projectKey, resource, {
1641
+ name,
1642
+ value
1643
+ }) => {
1644
+ if (!resource.custom) {
1645
+ throw new Error('Resource has no custom field');
1646
+ }
1647
+
1648
+ resource.custom.fields[name] = value;
1649
+ },
1650
+ setCustomType: (projectKey, resource, {
1651
+ type,
1652
+ fields
1653
+ }) => {
1654
+ if (!type) {
1655
+ resource.custom = undefined;
1656
+ } else {
1657
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, type);
1658
+
1659
+ if (!resolvedType) {
1660
+ throw new Error(`Type ${type} not found`);
1661
+ }
1662
+
1663
+ resource.custom = {
1664
+ type: {
1665
+ typeId: 'type',
1666
+ id: resolvedType.id
1667
+ },
1668
+ fields: fields || []
1669
+ };
1670
+ }
1671
+ },
1672
+ setLocale: (projectKey, resource, {
1673
+ locale
1674
+ }) => {
1675
+ resource.locale = locale;
1676
+ },
1677
+ setOrderNumber: (projectKey, resource, {
1678
+ orderNumber
1679
+ }) => {
1680
+ resource.orderNumber = orderNumber;
1681
+ },
1682
+ setShippingAddress: (projectKey, resource, {
1683
+ address
1684
+ }) => {
1685
+ resource.shippingAddress = address;
1686
+ },
1687
+ setStore: (projectKey, resource, {
1688
+ store
1689
+ }) => {
1690
+ if (!store) return;
1691
+
1692
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, store);
1693
+
1694
+ if (!resolvedType) {
1695
+ throw new Error(`No store found with key=${store.key}`);
1696
+ }
1697
+
1698
+ const storeReference = resolvedType;
1699
+ resource.store = {
1700
+ typeId: 'store',
1701
+ key: storeReference.key
1702
+ };
1703
+ }
1704
+ };
1705
+ }
1706
+
1707
+ getTypeId() {
1708
+ return 'order';
1709
+ }
1710
+
1711
+ create(projectKey, draft) {
1712
+ assert(draft.cart, 'draft.cart is missing');
1713
+
1714
+ const cart = this._storage.getByResourceIdentifier(projectKey, draft.cart);
1715
+
1716
+ if (!cart) {
1717
+ throw new Error('Cannot find cart');
1718
+ }
1719
+
1720
+ const resource = { ...getBaseResourceProperties(),
1721
+ orderNumber: draft.orderNumber,
1722
+ orderState: 'Open',
1723
+ lineItems: [],
1724
+ customLineItems: [],
1725
+ totalPrice: cart.totalPrice,
1726
+ refusedGifts: [],
1727
+ origin: 'Customer',
1728
+ syncInfo: [],
1729
+ lastMessageSequenceNumber: 0
1730
+ };
1731
+ this.save(projectKey, resource);
1732
+ return resource;
1733
+ }
1734
+
1735
+ import(projectKey, draft) {
1736
+ var _draft$lineItems, _draft$customLineItem;
1737
+
1738
+ // TODO: Check if order with given orderNumber already exists
1739
+ assert(this, 'OrderRepository not valid');
1740
+ const resource = { ...getBaseResourceProperties(),
1741
+ billingAddress: draft.billingAddress,
1742
+ shippingAddress: draft.shippingAddress,
1743
+ custom: createCustomFields(draft.custom, projectKey, this._storage),
1744
+ customerEmail: draft.customerEmail,
1745
+ lastMessageSequenceNumber: 0,
1746
+ orderNumber: draft.orderNumber,
1747
+ orderState: draft.orderState || 'Open',
1748
+ origin: draft.origin || 'Customer',
1749
+ paymentState: draft.paymentState,
1750
+ refusedGifts: [],
1751
+ store: resolveStoreReference(draft.store, projectKey, this._storage),
1752
+ syncInfo: [],
1753
+ lineItems: ((_draft$lineItems = draft.lineItems) == null ? void 0 : _draft$lineItems.map(item => this.lineItemFromImportDraft.bind(this)(projectKey, item))) || [],
1754
+ customLineItems: ((_draft$customLineItem = draft.customLineItems) == null ? void 0 : _draft$customLineItem.map(item => this.customLineItemFromImportDraft.bind(this)(projectKey, item))) || [],
1755
+ totalPrice: {
1756
+ type: 'centPrecision',
1757
+ ...draft.totalPrice,
1758
+ fractionDigits: 2
1759
+ }
1760
+ };
1761
+ this.save(projectKey, resource);
1762
+ return resource;
1763
+ }
1764
+
1765
+ lineItemFromImportDraft(projectKey, draft) {
1766
+ let product;
1767
+ let variant;
1768
+
1769
+ if (draft.variant.sku) {
1770
+ variant = {
1771
+ id: 0,
1772
+ sku: draft.variant.sku
1773
+ };
1774
+
1775
+ var items = this._storage.query(projectKey, 'product', {
1776
+ where: [`masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`]
1777
+ });
1778
+
1779
+ if (items.count !== 1) {
1780
+ throw new CommercetoolsError({
1781
+ code: 'General',
1782
+ message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
1783
+ });
1784
+ }
1785
+
1786
+ product = items.results[0];
1787
+
1788
+ if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
1789
+ variant = product.masterData.current.masterVariant;
1790
+ } else {
1791
+ variant = product.masterData.current.variants.find(v => v.sku === draft.variant.sku);
1792
+ }
1793
+
1794
+ if (!variant) {
1795
+ throw new Error('Internal state error');
1796
+ }
1797
+ } else {
1798
+ throw new Error('No product found');
1799
+ }
1800
+
1801
+ const lineItem = { ...getBaseResourceProperties(),
1802
+ custom: createCustomFields(draft.custom, projectKey, this._storage),
1803
+ discountedPricePerQuantity: [],
1804
+ lineItemMode: 'Standard',
1805
+ name: draft.name,
1806
+ price: createPrice(draft.price),
1807
+ priceMode: 'Platform',
1808
+ productId: product.id,
1809
+ productType: product.productType,
1810
+ quantity: draft.quantity,
1811
+ state: draft.state || [],
1812
+ taxRate: draft.taxRate,
1813
+ totalPrice: createTypedMoney(draft.price.value),
1814
+ variant: {
1815
+ id: variant.id,
1816
+ sku: variant.sku,
1817
+ price: createPrice(draft.price)
1818
+ }
1819
+ };
1820
+ return lineItem;
1821
+ }
1822
+
1823
+ customLineItemFromImportDraft(projectKey, draft) {
1824
+ const lineItem = { ...getBaseResourceProperties(),
1825
+ custom: createCustomFields(draft.custom, projectKey, this._storage),
1826
+ discountedPricePerQuantity: [],
1827
+ money: createTypedMoney(draft.money),
1828
+ name: draft.name,
1829
+ quantity: draft.quantity,
1830
+ slug: draft.slug,
1831
+ state: [],
1832
+ totalPrice: createTypedMoney(draft.money)
1833
+ };
1834
+ return lineItem;
1835
+ }
1836
+
1837
+ getWithOrderNumber(projectKey, orderNumber, params = {}) {
1838
+ const result = this._storage.query(projectKey, this.getTypeId(), { ...params,
1839
+ where: [`orderNumber="${orderNumber}"`]
1840
+ });
1841
+
1842
+ if (result.count === 1) {
1843
+ return result.results[0];
1844
+ } // Catch this for now, should be checked when creating/updating
1845
+
1846
+
1847
+ if (result.count > 1) {
1848
+ throw new Error('Duplicate order numbers');
1849
+ }
1850
+
1851
+ return;
1852
+ }
1853
+
1854
+ }
1855
+
1582
1856
  class CartService extends AbstractService {
1583
1857
  constructor(parent, storage) {
1584
1858
  super(parent);
1585
1859
  this.repository = new CartRepository(storage);
1860
+ this.orderRepository = new OrderRepository(storage);
1586
1861
  }
1587
1862
 
1588
1863
  getBasePath() {
1589
1864
  return 'carts';
1590
1865
  }
1591
1866
 
1867
+ extraRoutes(parent) {
1868
+ parent.post('/replicate', (request, response) => {
1869
+ // @ts-ignore
1870
+ const cartOrOrder = request.body.reference.typeId === 'order' ? this.orderRepository.get(request.params.projectKey, request.body.reference.id) : this.repository.get(request.params.projectKey, request.body.reference.id);
1871
+
1872
+ if (!cartOrOrder) {
1873
+ return response.status(400).send();
1874
+ }
1875
+
1876
+ const newCart = this.repository.create(request.params.projectKey, { ...cartOrOrder,
1877
+ currency: cartOrOrder.totalPrice.currencyCode,
1878
+ discountCodes: []
1879
+ });
1880
+ return response.status(200).send(newCart);
1881
+ });
1882
+ }
1883
+
1592
1884
  }
1593
1885
 
1594
1886
  class CategoryRepository extends AbstractResourceRepository {
@@ -1603,11 +1895,11 @@ class CategoryRepository extends AbstractResourceRepository {
1603
1895
  var _resource$assets;
1604
1896
 
1605
1897
  (_resource$assets = resource.assets) == null ? void 0 : _resource$assets.forEach(asset => {
1606
- if (assetId && assetId == asset.id) {
1898
+ if (assetId && assetId === asset.id) {
1607
1899
  asset.name = name;
1608
1900
  }
1609
1901
 
1610
- if (assetKey && assetKey == asset.key) {
1902
+ if (assetKey && assetKey === asset.key) {
1611
1903
  asset.name = name;
1612
1904
  }
1613
1905
  });
@@ -1630,11 +1922,11 @@ class CategoryRepository extends AbstractResourceRepository {
1630
1922
  var _resource$assets2;
1631
1923
 
1632
1924
  (_resource$assets2 = resource.assets) == null ? void 0 : _resource$assets2.forEach(asset => {
1633
- if (assetId && assetId == asset.id) {
1925
+ if (assetId && assetId === asset.id) {
1634
1926
  asset.description = description;
1635
1927
  }
1636
1928
 
1637
- if (assetKey && assetKey == asset.key) {
1929
+ if (assetKey && assetKey === asset.key) {
1638
1930
  asset.description = description;
1639
1931
  }
1640
1932
  });
@@ -1647,11 +1939,11 @@ class CategoryRepository extends AbstractResourceRepository {
1647
1939
  var _resource$assets3;
1648
1940
 
1649
1941
  (_resource$assets3 = resource.assets) == null ? void 0 : _resource$assets3.forEach(asset => {
1650
- if (assetId && assetId == asset.id) {
1942
+ if (assetId && assetId === asset.id) {
1651
1943
  asset.sources = sources;
1652
1944
  }
1653
1945
 
1654
- if (assetKey && assetKey == asset.key) {
1946
+ if (assetKey && assetKey === asset.key) {
1655
1947
  asset.sources = sources;
1656
1948
  }
1657
1949
  });
@@ -1800,6 +2092,17 @@ class CustomerGroupService extends AbstractService {
1800
2092
  }
1801
2093
 
1802
2094
  class CustomerRepository extends AbstractResourceRepository {
2095
+ constructor() {
2096
+ super(...arguments);
2097
+ this.actions = {
2098
+ changeEmail: (_projectKey, resource, {
2099
+ email
2100
+ }) => {
2101
+ resource.email = email;
2102
+ }
2103
+ };
2104
+ }
2105
+
1803
2106
  getTypeId() {
1804
2107
  return 'customer';
1805
2108
  }
@@ -1838,6 +2141,24 @@ class CustomerService extends AbstractService {
1838
2141
  return 'customers';
1839
2142
  }
1840
2143
 
2144
+ extraRoutes(parent) {
2145
+ parent.post('/password-token', (request, response) => {
2146
+ const customer = this.repository.query(request.params.projectKey, {
2147
+ where: [`email="${request.body.email}"`]
2148
+ });
2149
+ const ttlMinutes = request.params.ttlMinutes ? +request.params.ttlMinutes : 34560;
2150
+ const {
2151
+ version,
2152
+ ...rest
2153
+ } = getBaseResourceProperties();
2154
+ return response.status(200).send({ ...rest,
2155
+ customerId: customer.results[0].id,
2156
+ expiresAt: new Date(Date.now() + ttlMinutes * 60).toISOString(),
2157
+ value: v4()
2158
+ });
2159
+ });
2160
+ }
2161
+
1841
2162
  }
1842
2163
 
1843
2164
  class CustomObjectRepository extends AbstractResourceRepository {
@@ -2232,151 +2553,9 @@ class PaymentRepository extends AbstractResourceRepository {
2232
2553
  id: v4(),
2233
2554
  amount: createTypedMoney(draft.amount),
2234
2555
  custom: createCustomFields(draft.custom, projectKey, this._storage)
2235
- });
2236
-
2237
- this.actions = {
2238
- setCustomField: (projectKey, resource, {
2239
- name,
2240
- value
2241
- }) => {
2242
- if (!resource.custom) {
2243
- throw new Error('Resource has no custom field');
2244
- }
2245
-
2246
- resource.custom.fields[name] = value;
2247
- },
2248
- setCustomType: (projectKey, resource, {
2249
- type,
2250
- fields
2251
- }) => {
2252
- if (!type) {
2253
- resource.custom = undefined;
2254
- } else {
2255
- const resolvedType = this._storage.getByResourceIdentifier(projectKey, type);
2256
-
2257
- if (!resolvedType) {
2258
- throw new Error(`Type ${type} not found`);
2259
- }
2260
-
2261
- resource.custom = {
2262
- type: {
2263
- typeId: 'type',
2264
- id: resolvedType.id
2265
- },
2266
- fields: fields || []
2267
- };
2268
- }
2269
- },
2270
- addTransaction: (projectKey, resource, {
2271
- transaction
2272
- }) => {
2273
- resource.transactions = [...resource.transactions, this.transactionFromTransactionDraft(transaction, projectKey)];
2274
- },
2275
- changeTransactionState: (_projectKey, resource, {
2276
- transactionId,
2277
- state
2278
- }) => {
2279
- const index = resource.transactions.findIndex(e => e.id === transactionId);
2280
- const updatedTransaction = { ...resource.transactions[index],
2281
- state
2282
- };
2283
- resource.transactions[index] = updatedTransaction;
2284
- },
2285
- transitionState: (projectKey, resource, {
2286
- state
2287
- }) => {
2288
- const stateObj = this._storage.getByResourceIdentifier(projectKey, state);
2289
-
2290
- if (!stateObj) {
2291
- throw new Error(`State ${state} not found`);
2292
- }
2293
-
2294
- resource.paymentStatus.state = {
2295
- typeId: 'state',
2296
- id: stateObj.id,
2297
- obj: stateObj
2298
- };
2299
- }
2300
- };
2301
- }
2302
-
2303
- getTypeId() {
2304
- return 'payment';
2305
- }
2306
-
2307
- create(projectKey, draft) {
2308
- const resource = { ...getBaseResourceProperties(),
2309
- amountPlanned: createTypedMoney(draft.amountPlanned),
2310
- paymentMethodInfo: draft.paymentMethodInfo,
2311
- paymentStatus: draft.paymentStatus ? { ...draft.paymentStatus,
2312
- state: draft.paymentStatus.state ? getReferenceFromResourceIdentifier(draft.paymentStatus.state, projectKey, this._storage) : undefined
2313
- } : {},
2314
- transactions: (draft.transactions || []).map(t => this.transactionFromTransactionDraft(t, projectKey)),
2315
- interfaceInteractions: (draft.interfaceInteractions || []).map(interaction => createCustomFields(interaction, projectKey, this._storage)),
2316
- custom: createCustomFields(draft.custom, projectKey, this._storage)
2317
- };
2318
- this.save(projectKey, resource);
2319
- return resource;
2320
- }
2321
-
2322
- }
2323
-
2324
- class MyPaymentService extends AbstractService {
2325
- constructor(parent, storage) {
2326
- super(parent);
2327
- this.repository = new PaymentRepository(storage);
2328
- }
2329
-
2330
- getBasePath() {
2331
- return 'me/payments';
2332
- }
2333
-
2334
- }
2335
-
2336
- class OrderRepository extends AbstractResourceRepository {
2337
- constructor() {
2338
- super(...arguments);
2339
- this.actions = {
2340
- addPayment: (projectKey, resource, {
2341
- payment
2342
- }) => {
2343
- const resolvedPayment = this._storage.getByResourceIdentifier(projectKey, payment);
2344
-
2345
- if (!resolvedPayment) {
2346
- throw new Error(`Payment ${payment.id} not found`);
2347
- }
2348
-
2349
- if (!resource.paymentInfo) {
2350
- resource.paymentInfo = {
2351
- payments: []
2352
- };
2353
- }
2354
-
2355
- resource.paymentInfo.payments.push({
2356
- typeId: 'payment',
2357
- id: payment.id
2358
- });
2359
- },
2360
- changeOrderState: (projectKey, resource, {
2361
- orderState
2362
- }) => {
2363
- resource.orderState = orderState;
2364
- },
2365
- changePaymentState: (projectKey, resource, {
2366
- paymentState
2367
- }) => {
2368
- resource.paymentState = paymentState;
2369
- },
2370
- setBillingAddress: (projectKey, resource, {
2371
- address
2372
- }) => {
2373
- resource.billingAddress = address;
2374
- },
2375
- setCustomerEmail: (projectKey, resource, {
2376
- email
2377
- }) => {
2378
- resource.customerEmail = email;
2379
- },
2556
+ });
2557
+
2558
+ this.actions = {
2380
2559
  setCustomField: (projectKey, resource, {
2381
2560
  name,
2382
2561
  value
@@ -2409,186 +2588,68 @@ class OrderRepository extends AbstractResourceRepository {
2409
2588
  };
2410
2589
  }
2411
2590
  },
2412
- setLocale: (projectKey, resource, {
2413
- locale
2414
- }) => {
2415
- resource.locale = locale;
2416
- },
2417
- setOrderNumber: (projectKey, resource, {
2418
- orderNumber
2591
+ addTransaction: (projectKey, resource, {
2592
+ transaction
2419
2593
  }) => {
2420
- resource.orderNumber = orderNumber;
2594
+ resource.transactions = [...resource.transactions, this.transactionFromTransactionDraft(transaction, projectKey)];
2421
2595
  },
2422
- setShippingAddress: (projectKey, resource, {
2423
- address
2596
+ changeTransactionState: (_projectKey, resource, {
2597
+ transactionId,
2598
+ state
2424
2599
  }) => {
2425
- resource.shippingAddress = address;
2600
+ const index = resource.transactions.findIndex(e => e.id === transactionId);
2601
+ const updatedTransaction = { ...resource.transactions[index],
2602
+ state
2603
+ };
2604
+ resource.transactions[index] = updatedTransaction;
2426
2605
  },
2427
- setStore: (projectKey, resource, {
2428
- store
2606
+ transitionState: (projectKey, resource, {
2607
+ state
2429
2608
  }) => {
2430
- if (!store) return;
2431
-
2432
- const resolvedType = this._storage.getByResourceIdentifier(projectKey, store);
2609
+ const stateObj = this._storage.getByResourceIdentifier(projectKey, state);
2433
2610
 
2434
- if (!resolvedType) {
2435
- throw new Error(`No store found with key=${store.key}`);
2611
+ if (!stateObj) {
2612
+ throw new Error(`State ${state} not found`);
2436
2613
  }
2437
2614
 
2438
- const storeReference = resolvedType;
2439
- resource.store = {
2440
- typeId: 'store',
2441
- key: storeReference.key
2615
+ resource.paymentStatus.state = {
2616
+ typeId: 'state',
2617
+ id: stateObj.id,
2618
+ obj: stateObj
2442
2619
  };
2443
2620
  }
2444
2621
  };
2445
2622
  }
2446
2623
 
2447
2624
  getTypeId() {
2448
- return 'order';
2625
+ return 'payment';
2449
2626
  }
2450
2627
 
2451
2628
  create(projectKey, draft) {
2452
- assert(draft.cart, 'draft.cart is missing');
2453
-
2454
- const cart = this._storage.getByResourceIdentifier(projectKey, draft.cart);
2455
-
2456
- if (!cart) {
2457
- throw new Error('Cannot find cart');
2458
- }
2459
-
2460
- const resource = { ...getBaseResourceProperties(),
2461
- orderNumber: draft.orderNumber,
2462
- orderState: 'Open',
2463
- lineItems: [],
2464
- customLineItems: [],
2465
- totalPrice: cart.totalPrice,
2466
- refusedGifts: [],
2467
- origin: 'Customer',
2468
- syncInfo: [],
2469
- lastMessageSequenceNumber: 0
2470
- };
2471
- this.save(projectKey, resource);
2472
- return resource;
2473
- }
2474
-
2475
- import(projectKey, draft) {
2476
- var _draft$lineItems, _draft$customLineItem;
2477
-
2478
- // TODO: Check if order with given orderNumber already exists
2479
- assert(this, 'OrderRepository not valid');
2480
2629
  const resource = { ...getBaseResourceProperties(),
2481
- billingAddress: draft.billingAddress,
2482
- shippingAddress: draft.shippingAddress,
2483
- custom: createCustomFields(draft.custom, projectKey, this._storage),
2484
- customerEmail: draft.customerEmail,
2485
- lastMessageSequenceNumber: 0,
2486
- orderNumber: draft.orderNumber,
2487
- orderState: draft.orderState || 'Open',
2488
- origin: draft.origin || 'Customer',
2489
- paymentState: draft.paymentState,
2490
- refusedGifts: [],
2491
- store: resolveStoreReference(draft.store, projectKey, this._storage),
2492
- syncInfo: [],
2493
- lineItems: ((_draft$lineItems = draft.lineItems) == null ? void 0 : _draft$lineItems.map(item => this.lineItemFromImportDraft.bind(this)(projectKey, item))) || [],
2494
- customLineItems: ((_draft$customLineItem = draft.customLineItems) == null ? void 0 : _draft$customLineItem.map(item => this.customLineItemFromImportDraft.bind(this)(projectKey, item))) || [],
2495
- totalPrice: {
2496
- type: 'centPrecision',
2497
- ...draft.totalPrice,
2498
- fractionDigits: 2
2499
- }
2630
+ amountPlanned: createTypedMoney(draft.amountPlanned),
2631
+ paymentMethodInfo: draft.paymentMethodInfo,
2632
+ paymentStatus: draft.paymentStatus ? { ...draft.paymentStatus,
2633
+ state: draft.paymentStatus.state ? getReferenceFromResourceIdentifier(draft.paymentStatus.state, projectKey, this._storage) : undefined
2634
+ } : {},
2635
+ transactions: (draft.transactions || []).map(t => this.transactionFromTransactionDraft(t, projectKey)),
2636
+ interfaceInteractions: (draft.interfaceInteractions || []).map(interaction => createCustomFields(interaction, projectKey, this._storage)),
2637
+ custom: createCustomFields(draft.custom, projectKey, this._storage)
2500
2638
  };
2501
2639
  this.save(projectKey, resource);
2502
2640
  return resource;
2503
2641
  }
2504
2642
 
2505
- lineItemFromImportDraft(projectKey, draft) {
2506
- let product;
2507
- let variant;
2508
-
2509
- if (draft.variant.sku) {
2510
- variant = {
2511
- id: 0,
2512
- sku: draft.variant.sku
2513
- };
2514
-
2515
- var items = this._storage.query(projectKey, 'product', {
2516
- where: [`masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`]
2517
- });
2518
-
2519
- if (items.count !== 1) {
2520
- throw new CommercetoolsError({
2521
- code: 'General',
2522
- message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
2523
- });
2524
- }
2525
-
2526
- product = items.results[0];
2527
-
2528
- if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
2529
- variant = product.masterData.current.masterVariant;
2530
- } else {
2531
- variant = product.masterData.current.variants.find(v => v.sku === draft.variant.sku);
2532
- }
2533
-
2534
- if (!variant) {
2535
- throw new Error('Internal state error');
2536
- }
2537
- } else {
2538
- throw new Error('No product found');
2539
- }
2540
-
2541
- const lineItem = { ...getBaseResourceProperties(),
2542
- custom: createCustomFields(draft.custom, projectKey, this._storage),
2543
- discountedPricePerQuantity: [],
2544
- lineItemMode: 'Standard',
2545
- name: draft.name,
2546
- price: createPrice(draft.price),
2547
- priceMode: 'Platform',
2548
- productId: product.id,
2549
- productType: product.productType,
2550
- quantity: draft.quantity,
2551
- state: draft.state || [],
2552
- taxRate: draft.taxRate,
2553
- totalPrice: createTypedMoney(draft.price.value),
2554
- variant: {
2555
- id: variant.id,
2556
- sku: variant.sku,
2557
- price: createPrice(draft.price)
2558
- }
2559
- };
2560
- return lineItem;
2561
- }
2643
+ }
2562
2644
 
2563
- customLineItemFromImportDraft(projectKey, draft) {
2564
- const lineItem = { ...getBaseResourceProperties(),
2565
- custom: createCustomFields(draft.custom, projectKey, this._storage),
2566
- discountedPricePerQuantity: [],
2567
- money: createTypedMoney(draft.money),
2568
- name: draft.name,
2569
- quantity: draft.quantity,
2570
- slug: draft.slug,
2571
- state: [],
2572
- totalPrice: createTypedMoney(draft.money)
2573
- };
2574
- return lineItem;
2645
+ class MyPaymentService extends AbstractService {
2646
+ constructor(parent, storage) {
2647
+ super(parent);
2648
+ this.repository = new PaymentRepository(storage);
2575
2649
  }
2576
2650
 
2577
- getWithOrderNumber(projectKey, orderNumber, params = {}) {
2578
- const result = this._storage.query(projectKey, this.getTypeId(), { ...params,
2579
- where: [`orderNumber="${orderNumber}"`]
2580
- });
2581
-
2582
- if (result.count === 1) {
2583
- return result.results[0];
2584
- } // Catch this for now, should be checked when creating/updating
2585
-
2586
-
2587
- if (result.count > 1) {
2588
- throw new Error('Duplicate order numbers');
2589
- }
2590
-
2591
- return;
2651
+ getBasePath() {
2652
+ return 'me/payments';
2592
2653
  }
2593
2654
 
2594
2655
  }
@@ -2925,7 +2986,7 @@ class ProductTypeRepository extends AbstractResourceRepository {
2925
2986
  switch (type.name) {
2926
2987
  case 'lenum':
2927
2988
  type.values.forEach(v => {
2928
- if (v.key == newValue.key) {
2989
+ if (v.key === newValue.key) {
2929
2990
  v.label = newValue.label;
2930
2991
  }
2931
2992
  });
@@ -2938,7 +2999,7 @@ class ProductTypeRepository extends AbstractResourceRepository {
2938
2999
  };
2939
3000
 
2940
3001
  (_resource$attributes = resource.attributes) == null ? void 0 : _resource$attributes.forEach(value => {
2941
- if (value.name == attributeName) {
3002
+ if (value.name === attributeName) {
2942
3003
  updateAttributeType(value.type);
2943
3004
  }
2944
3005
  });
@@ -2950,7 +3011,7 @@ class ProductTypeRepository extends AbstractResourceRepository {
2950
3011
  var _resource$attributes2;
2951
3012
 
2952
3013
  (_resource$attributes2 = resource.attributes) == null ? void 0 : _resource$attributes2.forEach(value => {
2953
- if (value.name == attributeName) {
3014
+ if (value.name === attributeName) {
2954
3015
  value.label = label;
2955
3016
  }
2956
3017
  });
@@ -3030,7 +3091,7 @@ const maskSecretValue = (resource, path) => {
3030
3091
  const part = parts[i];
3031
3092
  val = val[part];
3032
3093
 
3033
- if (val == undefined) {
3094
+ if (val === undefined) {
3034
3095
  return resource;
3035
3096
  }
3036
3097
  }
@@ -3122,8 +3183,6 @@ class ProjectRepository extends AbstractRepository {
3122
3183
  }
3123
3184
 
3124
3185
  get(projectKey) {
3125
- const data = this._storage.getProject(projectKey);
3126
-
3127
3186
  const resource = this._storage.getProject(projectKey);
3128
3187
 
3129
3188
  const masked = maskSecretValue(resource, 'externalOAuth.authorizationHeader');
@@ -3177,7 +3236,7 @@ class ProjectService {
3177
3236
  return response.status(404).send({});
3178
3237
  }
3179
3238
 
3180
- const updatedResource = this.repository.processUpdateActions(request.params.projectKey, project, updateRequest.actions);
3239
+ this.repository.processUpdateActions(request.params.projectKey, project, updateRequest.actions);
3181
3240
  return response.status(200).send({});
3182
3241
  }
3183
3242
 
@@ -3205,14 +3264,14 @@ class ShippingMethodRepository extends AbstractResourceRepository {
3205
3264
  };
3206
3265
 
3207
3266
  this.actions = {
3208
- addShippingRate: (projectKey, resource, {
3267
+ addShippingRate: (_projectKey, resource, {
3209
3268
  shippingRate,
3210
3269
  zone
3211
3270
  }) => {
3212
3271
  const rate = this._transformShippingRate(shippingRate);
3213
3272
 
3214
3273
  resource.zoneRates.forEach(zoneRate => {
3215
- if (zoneRate.zone.id == zone.id) {
3274
+ if (zoneRate.zone.id === zone.id) {
3216
3275
  zoneRate.shippingRates.push(rate);
3217
3276
  return;
3218
3277
  }
@@ -3225,14 +3284,14 @@ class ShippingMethodRepository extends AbstractResourceRepository {
3225
3284
  shippingRates: [rate]
3226
3285
  });
3227
3286
  },
3228
- removeShippingRate: (projectKey, resource, {
3287
+ removeShippingRate: (_projectKey, resource, {
3229
3288
  shippingRate,
3230
3289
  zone
3231
3290
  }) => {
3232
3291
  const rate = this._transformShippingRate(shippingRate);
3233
3292
 
3234
3293
  resource.zoneRates.forEach(zoneRate => {
3235
- if (zoneRate.zone.id == zone.id) {
3294
+ if (zoneRate.zone.id === zone.id) {
3236
3295
  zoneRate.shippingRates = zoneRate.shippingRates.filter(otherRate => {
3237
3296
  return !deepEqual(rate, otherRate);
3238
3297
  });
@@ -3253,39 +3312,39 @@ class ShippingMethodRepository extends AbstractResourceRepository {
3253
3312
  shippingRates: []
3254
3313
  });
3255
3314
  },
3256
- removeZone: (projectKey, resource, {
3315
+ removeZone: (_projectKey, resource, {
3257
3316
  zone
3258
3317
  }) => {
3259
3318
  resource.zoneRates = resource.zoneRates.filter(zoneRate => {
3260
3319
  return zoneRate.zone.id !== zone.id;
3261
3320
  });
3262
3321
  },
3263
- setKey: (projectKey, resource, {
3322
+ setKey: (_projectKey, resource, {
3264
3323
  key
3265
3324
  }) => {
3266
3325
  resource.key = key;
3267
3326
  },
3268
- setDescription: (projectKey, resource, {
3327
+ setDescription: (_projectKey, resource, {
3269
3328
  description
3270
3329
  }) => {
3271
3330
  resource.description = description;
3272
3331
  },
3273
- setLocalizedDescription: (projectKey, resource, {
3332
+ setLocalizedDescription: (_projectKey, resource, {
3274
3333
  localizedDescription
3275
3334
  }) => {
3276
3335
  resource.localizedDescription = localizedDescription;
3277
3336
  },
3278
- setPredicate: (projectKey, resource, {
3337
+ setPredicate: (_projectKey, resource, {
3279
3338
  predicate
3280
3339
  }) => {
3281
3340
  resource.predicate = predicate;
3282
3341
  },
3283
- changeIsDefault: (projectKey, resource, {
3342
+ changeIsDefault: (_projectKey, resource, {
3284
3343
  isDefault
3285
3344
  }) => {
3286
3345
  resource.isDefault = isDefault;
3287
3346
  },
3288
- changeName: (projectKey, resource, {
3347
+ changeName: (_projectKey, resource, {
3289
3348
  name
3290
3349
  }) => {
3291
3350
  resource.name = name;
@@ -3481,6 +3540,22 @@ class StoreRepository extends AbstractResourceRepository {
3481
3540
  return channels.map(ref => getReferenceFromResourceIdentifier(ref, projectKey, this._storage));
3482
3541
  }
3483
3542
 
3543
+ getWithKey(projectKey, key) {
3544
+ const result = this._storage.query(projectKey, this.getTypeId(), {
3545
+ where: [`key="${key}"`]
3546
+ });
3547
+
3548
+ if (result.count === 1) {
3549
+ return result.results[0];
3550
+ }
3551
+
3552
+ if (result.count > 1) {
3553
+ throw new Error('Duplicate store key');
3554
+ }
3555
+
3556
+ return;
3557
+ }
3558
+
3484
3559
  }
3485
3560
 
3486
3561
  class StoreService extends AbstractService {
@@ -3493,6 +3568,20 @@ class StoreService extends AbstractService {
3493
3568
  return 'stores';
3494
3569
  }
3495
3570
 
3571
+ extraRoutes(router) {
3572
+ router.get('/key=:key', this.getWithKey.bind(this));
3573
+ }
3574
+
3575
+ getWithKey(request, response) {
3576
+ const resource = this.repository.getWithKey(request.params.projectKey, request.params.key);
3577
+
3578
+ if (resource) {
3579
+ return response.status(200).send(resource);
3580
+ }
3581
+
3582
+ return response.status(404).send('Not found');
3583
+ }
3584
+
3496
3585
  }
3497
3586
 
3498
3587
  class SubscriptionRepository extends AbstractResourceRepository {
@@ -3503,11 +3592,11 @@ class SubscriptionRepository extends AbstractResourceRepository {
3503
3592
  create(projectKey, draft) {
3504
3593
  // TODO: We could actually test this here by using the aws sdk. For now
3505
3594
  // hardcode a failed check when account id is 0000000000
3506
- if (draft.destination.type == 'SQS') {
3595
+ if (draft.destination.type === 'SQS') {
3507
3596
  const queueURL = new URL(draft.destination.queueUrl);
3508
3597
  const accountId = queueURL.pathname.split('/')[1];
3509
3598
 
3510
- if (accountId == '0000000000') {
3599
+ if (accountId === '0000000000') {
3511
3600
  const dest = draft.destination;
3512
3601
  throw new CommercetoolsError({
3513
3602
  code: 'InvalidInput',
@@ -3587,7 +3676,7 @@ class TaxCategoryRepository extends AbstractResourceRepository {
3587
3676
  for (let i = 0; i < resource.rates.length; i++) {
3588
3677
  const rate = resource.rates[i];
3589
3678
 
3590
- if (rate.id == taxRateId) {
3679
+ if (rate.id === taxRateId) {
3591
3680
  resource.rates[i] = taxRateObj;
3592
3681
  }
3593
3682
  }
@@ -3725,11 +3814,11 @@ class TypeRepository extends AbstractResourceRepository {
3725
3814
  value
3726
3815
  }) => {
3727
3816
  resource.fieldDefinitions.forEach(field => {
3728
- if (field.name == fieldName) {
3817
+ if (field.name === fieldName) {
3729
3818
  // TODO, should be done better i suppose
3730
- if (field.type.name == 'Enum') {
3819
+ if (field.type.name === 'Enum') {
3731
3820
  field.type.values.push(value);
3732
- } else if (field.type.name == 'Set' && field.type.elementType.name == 'Enum') {
3821
+ } else if (field.type.name === 'Set' && field.type.elementType.name === 'Enum') {
3733
3822
  field.type.elementType.values.push(value);
3734
3823
  } else {
3735
3824
  throw new Error('Type is not a Enum (or Set of Enum)');
@@ -3742,17 +3831,17 @@ class TypeRepository extends AbstractResourceRepository {
3742
3831
  value
3743
3832
  }) => {
3744
3833
  resource.fieldDefinitions.forEach(field => {
3745
- if (field.name == fieldName) {
3834
+ if (field.name === fieldName) {
3746
3835
  // TODO, should be done better i suppose
3747
- if (field.type.name == 'Enum') {
3836
+ if (field.type.name === 'Enum') {
3748
3837
  field.type.values.forEach(v => {
3749
- if (v.key == value.key) {
3838
+ if (v.key === value.key) {
3750
3839
  v.label = value.label;
3751
3840
  }
3752
3841
  });
3753
- } else if (field.type.name == 'Set' && field.type.elementType.name == 'Enum') {
3842
+ } else if (field.type.name === 'Set' && field.type.elementType.name === 'Enum') {
3754
3843
  field.type.elementType.values.forEach(v => {
3755
- if (v.key == value.key) {
3844
+ if (v.key === value.key) {
3756
3845
  v.label = value.label;
3757
3846
  }
3758
3847
  });
@@ -3808,7 +3897,7 @@ class ZoneRepository extends AbstractResourceRepository {
3808
3897
  location
3809
3898
  }) => {
3810
3899
  resource.locations = resource.locations.filter(loc => {
3811
- return !(loc.country == location.country && loc.state == location.state);
3900
+ return !(loc.country === location.country && loc.state === location.state);
3812
3901
  });
3813
3902
  },
3814
3903
  changeName: (projectKey, resource, {
@@ -3877,6 +3966,7 @@ class MyCustomerService extends AbstractService {
3877
3966
  this.extraRoutes(router);
3878
3967
  router.get('', this.getMe.bind(this));
3879
3968
  router.post('/signup', this.signUp.bind(this));
3969
+ router.post('/login', this.signIn.bind(this));
3880
3970
  parent.use(`/${basePath}`, router);
3881
3971
  }
3882
3972
 
@@ -3901,6 +3991,58 @@ class MyCustomerService extends AbstractService {
3901
3991
  });
3902
3992
  }
3903
3993
 
3994
+ signIn(request, response) {
3995
+ const {
3996
+ email,
3997
+ password
3998
+ } = request.body;
3999
+ const encodedPassword = Buffer.from(password).toString('base64');
4000
+ const result = this.repository.query(request.params.projectKey, {
4001
+ where: [`email = "${email}"`, `password = "${encodedPassword}"`]
4002
+ });
4003
+
4004
+ if (result.count === 0) {
4005
+ return response.status(400).send({
4006
+ message: 'Account with the given credentials not found.',
4007
+ errors: [{
4008
+ code: 'InvalidCredentials',
4009
+ message: 'Account with the given credentials not found.'
4010
+ }]
4011
+ });
4012
+ }
4013
+
4014
+ return response.status(200).send({
4015
+ customer: result.results[0]
4016
+ });
4017
+ }
4018
+
4019
+ }
4020
+
4021
+ class MyOrderService extends AbstractService {
4022
+ constructor(parent, storage) {
4023
+ super(parent);
4024
+ this.repository = new OrderRepository(storage);
4025
+ }
4026
+
4027
+ getBasePath() {
4028
+ return 'me';
4029
+ }
4030
+
4031
+ registerRoutes(parent) {
4032
+ // Overwrite this function to be able to handle /me/active-cart path.
4033
+ const basePath = this.getBasePath();
4034
+ const router = Router({
4035
+ mergeParams: true
4036
+ });
4037
+ this.extraRoutes(router);
4038
+ router.get('/orders/', this.get.bind(this));
4039
+ router.get('/orders/:id', this.getWithId.bind(this));
4040
+ router.delete('/orders/:id', this.deletewithId.bind(this));
4041
+ router.post('/orders/', this.post.bind(this));
4042
+ router.post('/orders/:id', this.postWithId.bind(this));
4043
+ parent.use(`/${basePath}`, router);
4044
+ }
4045
+
3904
4046
  }
3905
4047
 
3906
4048
  const DEFAULT_OPTIONS = {
@@ -4001,6 +4143,7 @@ class CommercetoolsMock {
4001
4143
  order: new OrderService(projectRouter, this._storage),
4002
4144
  payment: new PaymentService(projectRouter, this._storage),
4003
4145
  'my-cart': new MyCartService(projectRouter, this._storage),
4146
+ 'my-order': new MyOrderService(projectRouter, this._storage),
4004
4147
  'my-customer': new MyCustomerService(projectRouter, this._storage),
4005
4148
  'my-payment': new MyPaymentService(projectRouter, this._storage),
4006
4149
  'shipping-method': new ShippingMethodService(projectRouter, this._storage),