@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
@@ -1586,16 +1586,308 @@ const calculateLineItemTotalPrice = lineItem => lineItem.price.value.centAmount
1586
1586
 
1587
1587
  const calculateCartTotalPrice = cart => cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
1588
1588
 
1589
+ class OrderRepository extends AbstractResourceRepository {
1590
+ constructor() {
1591
+ super(...arguments);
1592
+ this.actions = {
1593
+ addPayment: (projectKey, resource, {
1594
+ payment
1595
+ }) => {
1596
+ const resolvedPayment = this._storage.getByResourceIdentifier(projectKey, payment);
1597
+
1598
+ if (!resolvedPayment) {
1599
+ throw new Error(`Payment ${payment.id} not found`);
1600
+ }
1601
+
1602
+ if (!resource.paymentInfo) {
1603
+ resource.paymentInfo = {
1604
+ payments: []
1605
+ };
1606
+ }
1607
+
1608
+ resource.paymentInfo.payments.push({
1609
+ typeId: 'payment',
1610
+ id: payment.id
1611
+ });
1612
+ },
1613
+ changeOrderState: (projectKey, resource, {
1614
+ orderState
1615
+ }) => {
1616
+ resource.orderState = orderState;
1617
+ },
1618
+ changePaymentState: (projectKey, resource, {
1619
+ paymentState
1620
+ }) => {
1621
+ resource.paymentState = paymentState;
1622
+ },
1623
+ transitionState: (projectKey, resource, {
1624
+ state
1625
+ }) => {
1626
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, state);
1627
+
1628
+ if (!resolvedType) {
1629
+ throw new Error(`No state found with key=${state.key} or id=${state.key}`);
1630
+ }
1631
+
1632
+ resource.state = {
1633
+ typeId: 'state',
1634
+ id: resolvedType.id
1635
+ };
1636
+ },
1637
+ setBillingAddress: (projectKey, resource, {
1638
+ address
1639
+ }) => {
1640
+ resource.billingAddress = address;
1641
+ },
1642
+ setCustomerEmail: (projectKey, resource, {
1643
+ email
1644
+ }) => {
1645
+ resource.customerEmail = email;
1646
+ },
1647
+ setCustomField: (projectKey, resource, {
1648
+ name,
1649
+ value
1650
+ }) => {
1651
+ if (!resource.custom) {
1652
+ throw new Error('Resource has no custom field');
1653
+ }
1654
+
1655
+ resource.custom.fields[name] = value;
1656
+ },
1657
+ setCustomType: (projectKey, resource, {
1658
+ type,
1659
+ fields
1660
+ }) => {
1661
+ if (!type) {
1662
+ resource.custom = undefined;
1663
+ } else {
1664
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, type);
1665
+
1666
+ if (!resolvedType) {
1667
+ throw new Error(`Type ${type} not found`);
1668
+ }
1669
+
1670
+ resource.custom = {
1671
+ type: {
1672
+ typeId: 'type',
1673
+ id: resolvedType.id
1674
+ },
1675
+ fields: fields || []
1676
+ };
1677
+ }
1678
+ },
1679
+ setLocale: (projectKey, resource, {
1680
+ locale
1681
+ }) => {
1682
+ resource.locale = locale;
1683
+ },
1684
+ setOrderNumber: (projectKey, resource, {
1685
+ orderNumber
1686
+ }) => {
1687
+ resource.orderNumber = orderNumber;
1688
+ },
1689
+ setShippingAddress: (projectKey, resource, {
1690
+ address
1691
+ }) => {
1692
+ resource.shippingAddress = address;
1693
+ },
1694
+ setStore: (projectKey, resource, {
1695
+ store
1696
+ }) => {
1697
+ if (!store) return;
1698
+
1699
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, store);
1700
+
1701
+ if (!resolvedType) {
1702
+ throw new Error(`No store found with key=${store.key}`);
1703
+ }
1704
+
1705
+ const storeReference = resolvedType;
1706
+ resource.store = {
1707
+ typeId: 'store',
1708
+ key: storeReference.key
1709
+ };
1710
+ }
1711
+ };
1712
+ }
1713
+
1714
+ getTypeId() {
1715
+ return 'order';
1716
+ }
1717
+
1718
+ create(projectKey, draft) {
1719
+ assert(draft.cart, 'draft.cart is missing');
1720
+
1721
+ const cart = this._storage.getByResourceIdentifier(projectKey, draft.cart);
1722
+
1723
+ if (!cart) {
1724
+ throw new Error('Cannot find cart');
1725
+ }
1726
+
1727
+ const resource = { ...getBaseResourceProperties(),
1728
+ orderNumber: draft.orderNumber,
1729
+ orderState: 'Open',
1730
+ lineItems: [],
1731
+ customLineItems: [],
1732
+ totalPrice: cart.totalPrice,
1733
+ refusedGifts: [],
1734
+ origin: 'Customer',
1735
+ syncInfo: [],
1736
+ lastMessageSequenceNumber: 0
1737
+ };
1738
+ this.save(projectKey, resource);
1739
+ return resource;
1740
+ }
1741
+
1742
+ import(projectKey, draft) {
1743
+ var _draft$lineItems, _draft$customLineItem;
1744
+
1745
+ // TODO: Check if order with given orderNumber already exists
1746
+ assert(this, 'OrderRepository not valid');
1747
+ const resource = { ...getBaseResourceProperties(),
1748
+ billingAddress: draft.billingAddress,
1749
+ shippingAddress: draft.shippingAddress,
1750
+ custom: createCustomFields(draft.custom, projectKey, this._storage),
1751
+ customerEmail: draft.customerEmail,
1752
+ lastMessageSequenceNumber: 0,
1753
+ orderNumber: draft.orderNumber,
1754
+ orderState: draft.orderState || 'Open',
1755
+ origin: draft.origin || 'Customer',
1756
+ paymentState: draft.paymentState,
1757
+ refusedGifts: [],
1758
+ store: resolveStoreReference(draft.store, projectKey, this._storage),
1759
+ syncInfo: [],
1760
+ lineItems: ((_draft$lineItems = draft.lineItems) == null ? void 0 : _draft$lineItems.map(item => this.lineItemFromImportDraft.bind(this)(projectKey, item))) || [],
1761
+ customLineItems: ((_draft$customLineItem = draft.customLineItems) == null ? void 0 : _draft$customLineItem.map(item => this.customLineItemFromImportDraft.bind(this)(projectKey, item))) || [],
1762
+ totalPrice: {
1763
+ type: 'centPrecision',
1764
+ ...draft.totalPrice,
1765
+ fractionDigits: 2
1766
+ }
1767
+ };
1768
+ this.save(projectKey, resource);
1769
+ return resource;
1770
+ }
1771
+
1772
+ lineItemFromImportDraft(projectKey, draft) {
1773
+ let product;
1774
+ let variant;
1775
+
1776
+ if (draft.variant.sku) {
1777
+ variant = {
1778
+ id: 0,
1779
+ sku: draft.variant.sku
1780
+ };
1781
+
1782
+ var items = this._storage.query(projectKey, 'product', {
1783
+ where: [`masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`]
1784
+ });
1785
+
1786
+ if (items.count !== 1) {
1787
+ throw new CommercetoolsError({
1788
+ code: 'General',
1789
+ message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
1790
+ });
1791
+ }
1792
+
1793
+ product = items.results[0];
1794
+
1795
+ if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
1796
+ variant = product.masterData.current.masterVariant;
1797
+ } else {
1798
+ variant = product.masterData.current.variants.find(v => v.sku === draft.variant.sku);
1799
+ }
1800
+
1801
+ if (!variant) {
1802
+ throw new Error('Internal state error');
1803
+ }
1804
+ } else {
1805
+ throw new Error('No product found');
1806
+ }
1807
+
1808
+ const lineItem = { ...getBaseResourceProperties(),
1809
+ custom: createCustomFields(draft.custom, projectKey, this._storage),
1810
+ discountedPricePerQuantity: [],
1811
+ lineItemMode: 'Standard',
1812
+ name: draft.name,
1813
+ price: createPrice(draft.price),
1814
+ priceMode: 'Platform',
1815
+ productId: product.id,
1816
+ productType: product.productType,
1817
+ quantity: draft.quantity,
1818
+ state: draft.state || [],
1819
+ taxRate: draft.taxRate,
1820
+ totalPrice: createTypedMoney(draft.price.value),
1821
+ variant: {
1822
+ id: variant.id,
1823
+ sku: variant.sku,
1824
+ price: createPrice(draft.price)
1825
+ }
1826
+ };
1827
+ return lineItem;
1828
+ }
1829
+
1830
+ customLineItemFromImportDraft(projectKey, draft) {
1831
+ const lineItem = { ...getBaseResourceProperties(),
1832
+ custom: createCustomFields(draft.custom, projectKey, this._storage),
1833
+ discountedPricePerQuantity: [],
1834
+ money: createTypedMoney(draft.money),
1835
+ name: draft.name,
1836
+ quantity: draft.quantity,
1837
+ slug: draft.slug,
1838
+ state: [],
1839
+ totalPrice: createTypedMoney(draft.money)
1840
+ };
1841
+ return lineItem;
1842
+ }
1843
+
1844
+ getWithOrderNumber(projectKey, orderNumber, params = {}) {
1845
+ const result = this._storage.query(projectKey, this.getTypeId(), { ...params,
1846
+ where: [`orderNumber="${orderNumber}"`]
1847
+ });
1848
+
1849
+ if (result.count === 1) {
1850
+ return result.results[0];
1851
+ } // Catch this for now, should be checked when creating/updating
1852
+
1853
+
1854
+ if (result.count > 1) {
1855
+ throw new Error('Duplicate order numbers');
1856
+ }
1857
+
1858
+ return;
1859
+ }
1860
+
1861
+ }
1862
+
1589
1863
  class CartService extends AbstractService {
1590
1864
  constructor(parent, storage) {
1591
1865
  super(parent);
1592
1866
  this.repository = new CartRepository(storage);
1867
+ this.orderRepository = new OrderRepository(storage);
1593
1868
  }
1594
1869
 
1595
1870
  getBasePath() {
1596
1871
  return 'carts';
1597
1872
  }
1598
1873
 
1874
+ extraRoutes(parent) {
1875
+ parent.post('/replicate', (request, response) => {
1876
+ // @ts-ignore
1877
+ 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);
1878
+
1879
+ if (!cartOrOrder) {
1880
+ return response.status(400).send();
1881
+ }
1882
+
1883
+ const newCart = this.repository.create(request.params.projectKey, { ...cartOrOrder,
1884
+ currency: cartOrOrder.totalPrice.currencyCode,
1885
+ discountCodes: []
1886
+ });
1887
+ return response.status(200).send(newCart);
1888
+ });
1889
+ }
1890
+
1599
1891
  }
1600
1892
 
1601
1893
  class CategoryRepository extends AbstractResourceRepository {
@@ -1610,11 +1902,11 @@ class CategoryRepository extends AbstractResourceRepository {
1610
1902
  var _resource$assets;
1611
1903
 
1612
1904
  (_resource$assets = resource.assets) == null ? void 0 : _resource$assets.forEach(asset => {
1613
- if (assetId && assetId == asset.id) {
1905
+ if (assetId && assetId === asset.id) {
1614
1906
  asset.name = name;
1615
1907
  }
1616
1908
 
1617
- if (assetKey && assetKey == asset.key) {
1909
+ if (assetKey && assetKey === asset.key) {
1618
1910
  asset.name = name;
1619
1911
  }
1620
1912
  });
@@ -1637,11 +1929,11 @@ class CategoryRepository extends AbstractResourceRepository {
1637
1929
  var _resource$assets2;
1638
1930
 
1639
1931
  (_resource$assets2 = resource.assets) == null ? void 0 : _resource$assets2.forEach(asset => {
1640
- if (assetId && assetId == asset.id) {
1932
+ if (assetId && assetId === asset.id) {
1641
1933
  asset.description = description;
1642
1934
  }
1643
1935
 
1644
- if (assetKey && assetKey == asset.key) {
1936
+ if (assetKey && assetKey === asset.key) {
1645
1937
  asset.description = description;
1646
1938
  }
1647
1939
  });
@@ -1654,11 +1946,11 @@ class CategoryRepository extends AbstractResourceRepository {
1654
1946
  var _resource$assets3;
1655
1947
 
1656
1948
  (_resource$assets3 = resource.assets) == null ? void 0 : _resource$assets3.forEach(asset => {
1657
- if (assetId && assetId == asset.id) {
1949
+ if (assetId && assetId === asset.id) {
1658
1950
  asset.sources = sources;
1659
1951
  }
1660
1952
 
1661
- if (assetKey && assetKey == asset.key) {
1953
+ if (assetKey && assetKey === asset.key) {
1662
1954
  asset.sources = sources;
1663
1955
  }
1664
1956
  });
@@ -1807,6 +2099,17 @@ class CustomerGroupService extends AbstractService {
1807
2099
  }
1808
2100
 
1809
2101
  class CustomerRepository extends AbstractResourceRepository {
2102
+ constructor() {
2103
+ super(...arguments);
2104
+ this.actions = {
2105
+ changeEmail: (_projectKey, resource, {
2106
+ email
2107
+ }) => {
2108
+ resource.email = email;
2109
+ }
2110
+ };
2111
+ }
2112
+
1810
2113
  getTypeId() {
1811
2114
  return 'customer';
1812
2115
  }
@@ -1845,6 +2148,24 @@ class CustomerService extends AbstractService {
1845
2148
  return 'customers';
1846
2149
  }
1847
2150
 
2151
+ extraRoutes(parent) {
2152
+ parent.post('/password-token', (request, response) => {
2153
+ const customer = this.repository.query(request.params.projectKey, {
2154
+ where: [`email="${request.body.email}"`]
2155
+ });
2156
+ const ttlMinutes = request.params.ttlMinutes ? +request.params.ttlMinutes : 34560;
2157
+ const {
2158
+ version,
2159
+ ...rest
2160
+ } = getBaseResourceProperties();
2161
+ return response.status(200).send({ ...rest,
2162
+ customerId: customer.results[0].id,
2163
+ expiresAt: new Date(Date.now() + ttlMinutes * 60).toISOString(),
2164
+ value: uuid.v4()
2165
+ });
2166
+ });
2167
+ }
2168
+
1848
2169
  }
1849
2170
 
1850
2171
  class CustomObjectRepository extends AbstractResourceRepository {
@@ -2239,151 +2560,9 @@ class PaymentRepository extends AbstractResourceRepository {
2239
2560
  id: uuid.v4(),
2240
2561
  amount: createTypedMoney(draft.amount),
2241
2562
  custom: createCustomFields(draft.custom, projectKey, this._storage)
2242
- });
2243
-
2244
- this.actions = {
2245
- setCustomField: (projectKey, resource, {
2246
- name,
2247
- value
2248
- }) => {
2249
- if (!resource.custom) {
2250
- throw new Error('Resource has no custom field');
2251
- }
2252
-
2253
- resource.custom.fields[name] = value;
2254
- },
2255
- setCustomType: (projectKey, resource, {
2256
- type,
2257
- fields
2258
- }) => {
2259
- if (!type) {
2260
- resource.custom = undefined;
2261
- } else {
2262
- const resolvedType = this._storage.getByResourceIdentifier(projectKey, type);
2263
-
2264
- if (!resolvedType) {
2265
- throw new Error(`Type ${type} not found`);
2266
- }
2267
-
2268
- resource.custom = {
2269
- type: {
2270
- typeId: 'type',
2271
- id: resolvedType.id
2272
- },
2273
- fields: fields || []
2274
- };
2275
- }
2276
- },
2277
- addTransaction: (projectKey, resource, {
2278
- transaction
2279
- }) => {
2280
- resource.transactions = [...resource.transactions, this.transactionFromTransactionDraft(transaction, projectKey)];
2281
- },
2282
- changeTransactionState: (_projectKey, resource, {
2283
- transactionId,
2284
- state
2285
- }) => {
2286
- const index = resource.transactions.findIndex(e => e.id === transactionId);
2287
- const updatedTransaction = { ...resource.transactions[index],
2288
- state
2289
- };
2290
- resource.transactions[index] = updatedTransaction;
2291
- },
2292
- transitionState: (projectKey, resource, {
2293
- state
2294
- }) => {
2295
- const stateObj = this._storage.getByResourceIdentifier(projectKey, state);
2296
-
2297
- if (!stateObj) {
2298
- throw new Error(`State ${state} not found`);
2299
- }
2300
-
2301
- resource.paymentStatus.state = {
2302
- typeId: 'state',
2303
- id: stateObj.id,
2304
- obj: stateObj
2305
- };
2306
- }
2307
- };
2308
- }
2309
-
2310
- getTypeId() {
2311
- return 'payment';
2312
- }
2313
-
2314
- create(projectKey, draft) {
2315
- const resource = { ...getBaseResourceProperties(),
2316
- amountPlanned: createTypedMoney(draft.amountPlanned),
2317
- paymentMethodInfo: draft.paymentMethodInfo,
2318
- paymentStatus: draft.paymentStatus ? { ...draft.paymentStatus,
2319
- state: draft.paymentStatus.state ? getReferenceFromResourceIdentifier(draft.paymentStatus.state, projectKey, this._storage) : undefined
2320
- } : {},
2321
- transactions: (draft.transactions || []).map(t => this.transactionFromTransactionDraft(t, projectKey)),
2322
- interfaceInteractions: (draft.interfaceInteractions || []).map(interaction => createCustomFields(interaction, projectKey, this._storage)),
2323
- custom: createCustomFields(draft.custom, projectKey, this._storage)
2324
- };
2325
- this.save(projectKey, resource);
2326
- return resource;
2327
- }
2328
-
2329
- }
2330
-
2331
- class MyPaymentService extends AbstractService {
2332
- constructor(parent, storage) {
2333
- super(parent);
2334
- this.repository = new PaymentRepository(storage);
2335
- }
2336
-
2337
- getBasePath() {
2338
- return 'me/payments';
2339
- }
2340
-
2341
- }
2342
-
2343
- class OrderRepository extends AbstractResourceRepository {
2344
- constructor() {
2345
- super(...arguments);
2346
- this.actions = {
2347
- addPayment: (projectKey, resource, {
2348
- payment
2349
- }) => {
2350
- const resolvedPayment = this._storage.getByResourceIdentifier(projectKey, payment);
2351
-
2352
- if (!resolvedPayment) {
2353
- throw new Error(`Payment ${payment.id} not found`);
2354
- }
2355
-
2356
- if (!resource.paymentInfo) {
2357
- resource.paymentInfo = {
2358
- payments: []
2359
- };
2360
- }
2361
-
2362
- resource.paymentInfo.payments.push({
2363
- typeId: 'payment',
2364
- id: payment.id
2365
- });
2366
- },
2367
- changeOrderState: (projectKey, resource, {
2368
- orderState
2369
- }) => {
2370
- resource.orderState = orderState;
2371
- },
2372
- changePaymentState: (projectKey, resource, {
2373
- paymentState
2374
- }) => {
2375
- resource.paymentState = paymentState;
2376
- },
2377
- setBillingAddress: (projectKey, resource, {
2378
- address
2379
- }) => {
2380
- resource.billingAddress = address;
2381
- },
2382
- setCustomerEmail: (projectKey, resource, {
2383
- email
2384
- }) => {
2385
- resource.customerEmail = email;
2386
- },
2563
+ });
2564
+
2565
+ this.actions = {
2387
2566
  setCustomField: (projectKey, resource, {
2388
2567
  name,
2389
2568
  value
@@ -2416,186 +2595,68 @@ class OrderRepository extends AbstractResourceRepository {
2416
2595
  };
2417
2596
  }
2418
2597
  },
2419
- setLocale: (projectKey, resource, {
2420
- locale
2421
- }) => {
2422
- resource.locale = locale;
2423
- },
2424
- setOrderNumber: (projectKey, resource, {
2425
- orderNumber
2598
+ addTransaction: (projectKey, resource, {
2599
+ transaction
2426
2600
  }) => {
2427
- resource.orderNumber = orderNumber;
2601
+ resource.transactions = [...resource.transactions, this.transactionFromTransactionDraft(transaction, projectKey)];
2428
2602
  },
2429
- setShippingAddress: (projectKey, resource, {
2430
- address
2603
+ changeTransactionState: (_projectKey, resource, {
2604
+ transactionId,
2605
+ state
2431
2606
  }) => {
2432
- resource.shippingAddress = address;
2607
+ const index = resource.transactions.findIndex(e => e.id === transactionId);
2608
+ const updatedTransaction = { ...resource.transactions[index],
2609
+ state
2610
+ };
2611
+ resource.transactions[index] = updatedTransaction;
2433
2612
  },
2434
- setStore: (projectKey, resource, {
2435
- store
2613
+ transitionState: (projectKey, resource, {
2614
+ state
2436
2615
  }) => {
2437
- if (!store) return;
2438
-
2439
- const resolvedType = this._storage.getByResourceIdentifier(projectKey, store);
2616
+ const stateObj = this._storage.getByResourceIdentifier(projectKey, state);
2440
2617
 
2441
- if (!resolvedType) {
2442
- throw new Error(`No store found with key=${store.key}`);
2618
+ if (!stateObj) {
2619
+ throw new Error(`State ${state} not found`);
2443
2620
  }
2444
2621
 
2445
- const storeReference = resolvedType;
2446
- resource.store = {
2447
- typeId: 'store',
2448
- key: storeReference.key
2622
+ resource.paymentStatus.state = {
2623
+ typeId: 'state',
2624
+ id: stateObj.id,
2625
+ obj: stateObj
2449
2626
  };
2450
2627
  }
2451
2628
  };
2452
2629
  }
2453
2630
 
2454
2631
  getTypeId() {
2455
- return 'order';
2632
+ return 'payment';
2456
2633
  }
2457
2634
 
2458
2635
  create(projectKey, draft) {
2459
- assert(draft.cart, 'draft.cart is missing');
2460
-
2461
- const cart = this._storage.getByResourceIdentifier(projectKey, draft.cart);
2462
-
2463
- if (!cart) {
2464
- throw new Error('Cannot find cart');
2465
- }
2466
-
2467
- const resource = { ...getBaseResourceProperties(),
2468
- orderNumber: draft.orderNumber,
2469
- orderState: 'Open',
2470
- lineItems: [],
2471
- customLineItems: [],
2472
- totalPrice: cart.totalPrice,
2473
- refusedGifts: [],
2474
- origin: 'Customer',
2475
- syncInfo: [],
2476
- lastMessageSequenceNumber: 0
2477
- };
2478
- this.save(projectKey, resource);
2479
- return resource;
2480
- }
2481
-
2482
- import(projectKey, draft) {
2483
- var _draft$lineItems, _draft$customLineItem;
2484
-
2485
- // TODO: Check if order with given orderNumber already exists
2486
- assert(this, 'OrderRepository not valid');
2487
2636
  const resource = { ...getBaseResourceProperties(),
2488
- billingAddress: draft.billingAddress,
2489
- shippingAddress: draft.shippingAddress,
2490
- custom: createCustomFields(draft.custom, projectKey, this._storage),
2491
- customerEmail: draft.customerEmail,
2492
- lastMessageSequenceNumber: 0,
2493
- orderNumber: draft.orderNumber,
2494
- orderState: draft.orderState || 'Open',
2495
- origin: draft.origin || 'Customer',
2496
- paymentState: draft.paymentState,
2497
- refusedGifts: [],
2498
- store: resolveStoreReference(draft.store, projectKey, this._storage),
2499
- syncInfo: [],
2500
- lineItems: ((_draft$lineItems = draft.lineItems) == null ? void 0 : _draft$lineItems.map(item => this.lineItemFromImportDraft.bind(this)(projectKey, item))) || [],
2501
- customLineItems: ((_draft$customLineItem = draft.customLineItems) == null ? void 0 : _draft$customLineItem.map(item => this.customLineItemFromImportDraft.bind(this)(projectKey, item))) || [],
2502
- totalPrice: {
2503
- type: 'centPrecision',
2504
- ...draft.totalPrice,
2505
- fractionDigits: 2
2506
- }
2637
+ amountPlanned: createTypedMoney(draft.amountPlanned),
2638
+ paymentMethodInfo: draft.paymentMethodInfo,
2639
+ paymentStatus: draft.paymentStatus ? { ...draft.paymentStatus,
2640
+ state: draft.paymentStatus.state ? getReferenceFromResourceIdentifier(draft.paymentStatus.state, projectKey, this._storage) : undefined
2641
+ } : {},
2642
+ transactions: (draft.transactions || []).map(t => this.transactionFromTransactionDraft(t, projectKey)),
2643
+ interfaceInteractions: (draft.interfaceInteractions || []).map(interaction => createCustomFields(interaction, projectKey, this._storage)),
2644
+ custom: createCustomFields(draft.custom, projectKey, this._storage)
2507
2645
  };
2508
2646
  this.save(projectKey, resource);
2509
2647
  return resource;
2510
2648
  }
2511
2649
 
2512
- lineItemFromImportDraft(projectKey, draft) {
2513
- let product;
2514
- let variant;
2515
-
2516
- if (draft.variant.sku) {
2517
- variant = {
2518
- id: 0,
2519
- sku: draft.variant.sku
2520
- };
2521
-
2522
- var items = this._storage.query(projectKey, 'product', {
2523
- where: [`masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`]
2524
- });
2525
-
2526
- if (items.count !== 1) {
2527
- throw new CommercetoolsError({
2528
- code: 'General',
2529
- message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
2530
- });
2531
- }
2532
-
2533
- product = items.results[0];
2534
-
2535
- if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
2536
- variant = product.masterData.current.masterVariant;
2537
- } else {
2538
- variant = product.masterData.current.variants.find(v => v.sku === draft.variant.sku);
2539
- }
2540
-
2541
- if (!variant) {
2542
- throw new Error('Internal state error');
2543
- }
2544
- } else {
2545
- throw new Error('No product found');
2546
- }
2547
-
2548
- const lineItem = { ...getBaseResourceProperties(),
2549
- custom: createCustomFields(draft.custom, projectKey, this._storage),
2550
- discountedPricePerQuantity: [],
2551
- lineItemMode: 'Standard',
2552
- name: draft.name,
2553
- price: createPrice(draft.price),
2554
- priceMode: 'Platform',
2555
- productId: product.id,
2556
- productType: product.productType,
2557
- quantity: draft.quantity,
2558
- state: draft.state || [],
2559
- taxRate: draft.taxRate,
2560
- totalPrice: createTypedMoney(draft.price.value),
2561
- variant: {
2562
- id: variant.id,
2563
- sku: variant.sku,
2564
- price: createPrice(draft.price)
2565
- }
2566
- };
2567
- return lineItem;
2568
- }
2650
+ }
2569
2651
 
2570
- customLineItemFromImportDraft(projectKey, draft) {
2571
- const lineItem = { ...getBaseResourceProperties(),
2572
- custom: createCustomFields(draft.custom, projectKey, this._storage),
2573
- discountedPricePerQuantity: [],
2574
- money: createTypedMoney(draft.money),
2575
- name: draft.name,
2576
- quantity: draft.quantity,
2577
- slug: draft.slug,
2578
- state: [],
2579
- totalPrice: createTypedMoney(draft.money)
2580
- };
2581
- return lineItem;
2652
+ class MyPaymentService extends AbstractService {
2653
+ constructor(parent, storage) {
2654
+ super(parent);
2655
+ this.repository = new PaymentRepository(storage);
2582
2656
  }
2583
2657
 
2584
- getWithOrderNumber(projectKey, orderNumber, params = {}) {
2585
- const result = this._storage.query(projectKey, this.getTypeId(), { ...params,
2586
- where: [`orderNumber="${orderNumber}"`]
2587
- });
2588
-
2589
- if (result.count === 1) {
2590
- return result.results[0];
2591
- } // Catch this for now, should be checked when creating/updating
2592
-
2593
-
2594
- if (result.count > 1) {
2595
- throw new Error('Duplicate order numbers');
2596
- }
2597
-
2598
- return;
2658
+ getBasePath() {
2659
+ return 'me/payments';
2599
2660
  }
2600
2661
 
2601
2662
  }
@@ -2932,7 +2993,7 @@ class ProductTypeRepository extends AbstractResourceRepository {
2932
2993
  switch (type.name) {
2933
2994
  case 'lenum':
2934
2995
  type.values.forEach(v => {
2935
- if (v.key == newValue.key) {
2996
+ if (v.key === newValue.key) {
2936
2997
  v.label = newValue.label;
2937
2998
  }
2938
2999
  });
@@ -2945,7 +3006,7 @@ class ProductTypeRepository extends AbstractResourceRepository {
2945
3006
  };
2946
3007
 
2947
3008
  (_resource$attributes = resource.attributes) == null ? void 0 : _resource$attributes.forEach(value => {
2948
- if (value.name == attributeName) {
3009
+ if (value.name === attributeName) {
2949
3010
  updateAttributeType(value.type);
2950
3011
  }
2951
3012
  });
@@ -2957,7 +3018,7 @@ class ProductTypeRepository extends AbstractResourceRepository {
2957
3018
  var _resource$attributes2;
2958
3019
 
2959
3020
  (_resource$attributes2 = resource.attributes) == null ? void 0 : _resource$attributes2.forEach(value => {
2960
- if (value.name == attributeName) {
3021
+ if (value.name === attributeName) {
2961
3022
  value.label = label;
2962
3023
  }
2963
3024
  });
@@ -3037,7 +3098,7 @@ const maskSecretValue = (resource, path) => {
3037
3098
  const part = parts[i];
3038
3099
  val = val[part];
3039
3100
 
3040
- if (val == undefined) {
3101
+ if (val === undefined) {
3041
3102
  return resource;
3042
3103
  }
3043
3104
  }
@@ -3129,8 +3190,6 @@ class ProjectRepository extends AbstractRepository {
3129
3190
  }
3130
3191
 
3131
3192
  get(projectKey) {
3132
- const data = this._storage.getProject(projectKey);
3133
-
3134
3193
  const resource = this._storage.getProject(projectKey);
3135
3194
 
3136
3195
  const masked = maskSecretValue(resource, 'externalOAuth.authorizationHeader');
@@ -3184,7 +3243,7 @@ class ProjectService {
3184
3243
  return response.status(404).send({});
3185
3244
  }
3186
3245
 
3187
- const updatedResource = this.repository.processUpdateActions(request.params.projectKey, project, updateRequest.actions);
3246
+ this.repository.processUpdateActions(request.params.projectKey, project, updateRequest.actions);
3188
3247
  return response.status(200).send({});
3189
3248
  }
3190
3249
 
@@ -3212,14 +3271,14 @@ class ShippingMethodRepository extends AbstractResourceRepository {
3212
3271
  };
3213
3272
 
3214
3273
  this.actions = {
3215
- addShippingRate: (projectKey, resource, {
3274
+ addShippingRate: (_projectKey, resource, {
3216
3275
  shippingRate,
3217
3276
  zone
3218
3277
  }) => {
3219
3278
  const rate = this._transformShippingRate(shippingRate);
3220
3279
 
3221
3280
  resource.zoneRates.forEach(zoneRate => {
3222
- if (zoneRate.zone.id == zone.id) {
3281
+ if (zoneRate.zone.id === zone.id) {
3223
3282
  zoneRate.shippingRates.push(rate);
3224
3283
  return;
3225
3284
  }
@@ -3232,14 +3291,14 @@ class ShippingMethodRepository extends AbstractResourceRepository {
3232
3291
  shippingRates: [rate]
3233
3292
  });
3234
3293
  },
3235
- removeShippingRate: (projectKey, resource, {
3294
+ removeShippingRate: (_projectKey, resource, {
3236
3295
  shippingRate,
3237
3296
  zone
3238
3297
  }) => {
3239
3298
  const rate = this._transformShippingRate(shippingRate);
3240
3299
 
3241
3300
  resource.zoneRates.forEach(zoneRate => {
3242
- if (zoneRate.zone.id == zone.id) {
3301
+ if (zoneRate.zone.id === zone.id) {
3243
3302
  zoneRate.shippingRates = zoneRate.shippingRates.filter(otherRate => {
3244
3303
  return !deepEqual(rate, otherRate);
3245
3304
  });
@@ -3260,39 +3319,39 @@ class ShippingMethodRepository extends AbstractResourceRepository {
3260
3319
  shippingRates: []
3261
3320
  });
3262
3321
  },
3263
- removeZone: (projectKey, resource, {
3322
+ removeZone: (_projectKey, resource, {
3264
3323
  zone
3265
3324
  }) => {
3266
3325
  resource.zoneRates = resource.zoneRates.filter(zoneRate => {
3267
3326
  return zoneRate.zone.id !== zone.id;
3268
3327
  });
3269
3328
  },
3270
- setKey: (projectKey, resource, {
3329
+ setKey: (_projectKey, resource, {
3271
3330
  key
3272
3331
  }) => {
3273
3332
  resource.key = key;
3274
3333
  },
3275
- setDescription: (projectKey, resource, {
3334
+ setDescription: (_projectKey, resource, {
3276
3335
  description
3277
3336
  }) => {
3278
3337
  resource.description = description;
3279
3338
  },
3280
- setLocalizedDescription: (projectKey, resource, {
3339
+ setLocalizedDescription: (_projectKey, resource, {
3281
3340
  localizedDescription
3282
3341
  }) => {
3283
3342
  resource.localizedDescription = localizedDescription;
3284
3343
  },
3285
- setPredicate: (projectKey, resource, {
3344
+ setPredicate: (_projectKey, resource, {
3286
3345
  predicate
3287
3346
  }) => {
3288
3347
  resource.predicate = predicate;
3289
3348
  },
3290
- changeIsDefault: (projectKey, resource, {
3349
+ changeIsDefault: (_projectKey, resource, {
3291
3350
  isDefault
3292
3351
  }) => {
3293
3352
  resource.isDefault = isDefault;
3294
3353
  },
3295
- changeName: (projectKey, resource, {
3354
+ changeName: (_projectKey, resource, {
3296
3355
  name
3297
3356
  }) => {
3298
3357
  resource.name = name;
@@ -3488,6 +3547,22 @@ class StoreRepository extends AbstractResourceRepository {
3488
3547
  return channels.map(ref => getReferenceFromResourceIdentifier(ref, projectKey, this._storage));
3489
3548
  }
3490
3549
 
3550
+ getWithKey(projectKey, key) {
3551
+ const result = this._storage.query(projectKey, this.getTypeId(), {
3552
+ where: [`key="${key}"`]
3553
+ });
3554
+
3555
+ if (result.count === 1) {
3556
+ return result.results[0];
3557
+ }
3558
+
3559
+ if (result.count > 1) {
3560
+ throw new Error('Duplicate store key');
3561
+ }
3562
+
3563
+ return;
3564
+ }
3565
+
3491
3566
  }
3492
3567
 
3493
3568
  class StoreService extends AbstractService {
@@ -3500,6 +3575,20 @@ class StoreService extends AbstractService {
3500
3575
  return 'stores';
3501
3576
  }
3502
3577
 
3578
+ extraRoutes(router) {
3579
+ router.get('/key=:key', this.getWithKey.bind(this));
3580
+ }
3581
+
3582
+ getWithKey(request, response) {
3583
+ const resource = this.repository.getWithKey(request.params.projectKey, request.params.key);
3584
+
3585
+ if (resource) {
3586
+ return response.status(200).send(resource);
3587
+ }
3588
+
3589
+ return response.status(404).send('Not found');
3590
+ }
3591
+
3503
3592
  }
3504
3593
 
3505
3594
  class SubscriptionRepository extends AbstractResourceRepository {
@@ -3510,11 +3599,11 @@ class SubscriptionRepository extends AbstractResourceRepository {
3510
3599
  create(projectKey, draft) {
3511
3600
  // TODO: We could actually test this here by using the aws sdk. For now
3512
3601
  // hardcode a failed check when account id is 0000000000
3513
- if (draft.destination.type == 'SQS') {
3602
+ if (draft.destination.type === 'SQS') {
3514
3603
  const queueURL = new URL(draft.destination.queueUrl);
3515
3604
  const accountId = queueURL.pathname.split('/')[1];
3516
3605
 
3517
- if (accountId == '0000000000') {
3606
+ if (accountId === '0000000000') {
3518
3607
  const dest = draft.destination;
3519
3608
  throw new CommercetoolsError({
3520
3609
  code: 'InvalidInput',
@@ -3594,7 +3683,7 @@ class TaxCategoryRepository extends AbstractResourceRepository {
3594
3683
  for (let i = 0; i < resource.rates.length; i++) {
3595
3684
  const rate = resource.rates[i];
3596
3685
 
3597
- if (rate.id == taxRateId) {
3686
+ if (rate.id === taxRateId) {
3598
3687
  resource.rates[i] = taxRateObj;
3599
3688
  }
3600
3689
  }
@@ -3732,11 +3821,11 @@ class TypeRepository extends AbstractResourceRepository {
3732
3821
  value
3733
3822
  }) => {
3734
3823
  resource.fieldDefinitions.forEach(field => {
3735
- if (field.name == fieldName) {
3824
+ if (field.name === fieldName) {
3736
3825
  // TODO, should be done better i suppose
3737
- if (field.type.name == 'Enum') {
3826
+ if (field.type.name === 'Enum') {
3738
3827
  field.type.values.push(value);
3739
- } else if (field.type.name == 'Set' && field.type.elementType.name == 'Enum') {
3828
+ } else if (field.type.name === 'Set' && field.type.elementType.name === 'Enum') {
3740
3829
  field.type.elementType.values.push(value);
3741
3830
  } else {
3742
3831
  throw new Error('Type is not a Enum (or Set of Enum)');
@@ -3749,17 +3838,17 @@ class TypeRepository extends AbstractResourceRepository {
3749
3838
  value
3750
3839
  }) => {
3751
3840
  resource.fieldDefinitions.forEach(field => {
3752
- if (field.name == fieldName) {
3841
+ if (field.name === fieldName) {
3753
3842
  // TODO, should be done better i suppose
3754
- if (field.type.name == 'Enum') {
3843
+ if (field.type.name === 'Enum') {
3755
3844
  field.type.values.forEach(v => {
3756
- if (v.key == value.key) {
3845
+ if (v.key === value.key) {
3757
3846
  v.label = value.label;
3758
3847
  }
3759
3848
  });
3760
- } else if (field.type.name == 'Set' && field.type.elementType.name == 'Enum') {
3849
+ } else if (field.type.name === 'Set' && field.type.elementType.name === 'Enum') {
3761
3850
  field.type.elementType.values.forEach(v => {
3762
- if (v.key == value.key) {
3851
+ if (v.key === value.key) {
3763
3852
  v.label = value.label;
3764
3853
  }
3765
3854
  });
@@ -3815,7 +3904,7 @@ class ZoneRepository extends AbstractResourceRepository {
3815
3904
  location
3816
3905
  }) => {
3817
3906
  resource.locations = resource.locations.filter(loc => {
3818
- return !(loc.country == location.country && loc.state == location.state);
3907
+ return !(loc.country === location.country && loc.state === location.state);
3819
3908
  });
3820
3909
  },
3821
3910
  changeName: (projectKey, resource, {
@@ -3884,6 +3973,7 @@ class MyCustomerService extends AbstractService {
3884
3973
  this.extraRoutes(router);
3885
3974
  router.get('', this.getMe.bind(this));
3886
3975
  router.post('/signup', this.signUp.bind(this));
3976
+ router.post('/login', this.signIn.bind(this));
3887
3977
  parent.use(`/${basePath}`, router);
3888
3978
  }
3889
3979
 
@@ -3908,6 +3998,58 @@ class MyCustomerService extends AbstractService {
3908
3998
  });
3909
3999
  }
3910
4000
 
4001
+ signIn(request, response) {
4002
+ const {
4003
+ email,
4004
+ password
4005
+ } = request.body;
4006
+ const encodedPassword = Buffer.from(password).toString('base64');
4007
+ const result = this.repository.query(request.params.projectKey, {
4008
+ where: [`email = "${email}"`, `password = "${encodedPassword}"`]
4009
+ });
4010
+
4011
+ if (result.count === 0) {
4012
+ return response.status(400).send({
4013
+ message: 'Account with the given credentials not found.',
4014
+ errors: [{
4015
+ code: 'InvalidCredentials',
4016
+ message: 'Account with the given credentials not found.'
4017
+ }]
4018
+ });
4019
+ }
4020
+
4021
+ return response.status(200).send({
4022
+ customer: result.results[0]
4023
+ });
4024
+ }
4025
+
4026
+ }
4027
+
4028
+ class MyOrderService extends AbstractService {
4029
+ constructor(parent, storage) {
4030
+ super(parent);
4031
+ this.repository = new OrderRepository(storage);
4032
+ }
4033
+
4034
+ getBasePath() {
4035
+ return 'me';
4036
+ }
4037
+
4038
+ registerRoutes(parent) {
4039
+ // Overwrite this function to be able to handle /me/active-cart path.
4040
+ const basePath = this.getBasePath();
4041
+ const router = express.Router({
4042
+ mergeParams: true
4043
+ });
4044
+ this.extraRoutes(router);
4045
+ router.get('/orders/', this.get.bind(this));
4046
+ router.get('/orders/:id', this.getWithId.bind(this));
4047
+ router.delete('/orders/:id', this.deletewithId.bind(this));
4048
+ router.post('/orders/', this.post.bind(this));
4049
+ router.post('/orders/:id', this.postWithId.bind(this));
4050
+ parent.use(`/${basePath}`, router);
4051
+ }
4052
+
3911
4053
  }
3912
4054
 
3913
4055
  const DEFAULT_OPTIONS = {
@@ -4008,6 +4150,7 @@ class CommercetoolsMock {
4008
4150
  order: new OrderService(projectRouter, this._storage),
4009
4151
  payment: new PaymentService(projectRouter, this._storage),
4010
4152
  'my-cart': new MyCartService(projectRouter, this._storage),
4153
+ 'my-order': new MyOrderService(projectRouter, this._storage),
4011
4154
  'my-customer': new MyCustomerService(projectRouter, this._storage),
4012
4155
  'my-payment': new MyPaymentService(projectRouter, this._storage),
4013
4156
  'shipping-method': new ShippingMethodService(projectRouter, this._storage),