@labdigital/commercetools-mock 0.5.21 → 0.6.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.
@@ -926,8 +926,8 @@ class ProjectAPI {
926
926
  }
927
927
  }
928
928
 
929
- get(typeId, id) {
930
- return this._storage.get(this.projectKey, typeId, id, {});
929
+ get(typeId, id, params) {
930
+ return this._storage.get(this.projectKey, typeId, id, params);
931
931
  } // TODO: Not sure if we want to expose this...
932
932
 
933
933
 
@@ -1486,6 +1486,24 @@ class CartRepository extends AbstractResourceRepository {
1486
1486
  }) => {
1487
1487
  resource.billingAddress = address;
1488
1488
  },
1489
+ setShippingMethod: (projectKey, resource, {
1490
+ shippingMethod
1491
+ }) => {
1492
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, //@ts-ignore
1493
+ shippingMethod);
1494
+
1495
+ if (!resolvedType) {
1496
+ throw new Error(`Type ${shippingMethod} not found`);
1497
+ } //@ts-ignore
1498
+
1499
+
1500
+ resource.shippingInfo = {
1501
+ shippingMethod: {
1502
+ typeId: 'shipping-method',
1503
+ id: resolvedType.id
1504
+ }
1505
+ };
1506
+ },
1489
1507
  setCountry: (projectKey, resource, {
1490
1508
  country
1491
1509
  }) => {
@@ -1539,6 +1557,81 @@ class CartRepository extends AbstractResourceRepository {
1539
1557
  resource.shippingAddress = address;
1540
1558
  }
1541
1559
  };
1560
+
1561
+ this.draftLineItemtoLineItem = (projectKey, draftLineItem) => {
1562
+ var _variant$prices2;
1563
+
1564
+ const {
1565
+ productId,
1566
+ quantity
1567
+ } = draftLineItem; // @ts-ignore
1568
+
1569
+ let variantId = draftLineItem.variant.id; // @ts-ignore
1570
+
1571
+ let sku = draftLineItem.variant.sku;
1572
+ let product = null;
1573
+ let variant;
1574
+
1575
+ if (productId && variantId) {
1576
+ // Fetch product and variant by ID
1577
+ product = this._storage.get(projectKey, 'product', productId, {});
1578
+ } else if (sku) {
1579
+ // Fetch product and variant by SKU
1580
+ const items = this._storage.query(projectKey, 'product', {
1581
+ where: [`masterData(current(masterVariant(sku="${sku}"))) or masterData(current(variants(sku="${sku}")))`]
1582
+ });
1583
+
1584
+ if (items.count === 1) {
1585
+ product = items.results[0];
1586
+ }
1587
+ }
1588
+
1589
+ if (!product) {
1590
+ // Check if product is found
1591
+ throw new CommercetoolsError({
1592
+ code: 'General',
1593
+ message: sku ? `A product containing a variant with SKU '${sku}' not found.` : `A product with ID '${productId}' not found.`
1594
+ });
1595
+ } // Find matching variant
1596
+
1597
+
1598
+ variant = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find(x => {
1599
+ if (sku) return x.sku === sku;
1600
+ if (variantId) return x.id === variantId;
1601
+ return false;
1602
+ });
1603
+
1604
+ if (!variant) {
1605
+ // Check if variant is found
1606
+ throw new Error(sku ? `A variant with SKU '${sku}' for product '${product.id}' not found.` : `A variant with ID '${variantId}' for product '${product.id}' not found.`);
1607
+ }
1608
+
1609
+ const price = (_variant$prices2 = variant.prices) == null ? void 0 : _variant$prices2[0];
1610
+ const quant = quantity != null ? quantity : 1;
1611
+
1612
+ if (!price) {
1613
+ throw new Error(`Price not set on ${productId}`);
1614
+ }
1615
+
1616
+ return {
1617
+ id: uuid.v4(),
1618
+ productId: product.id,
1619
+ productKey: product.key,
1620
+ name: product.masterData.current.name,
1621
+ productSlug: product.masterData.current.slug,
1622
+ productType: product.productType,
1623
+ variant,
1624
+ price: price,
1625
+ totalPrice: { ...price.value,
1626
+ centAmount: price.value.centAmount * quant
1627
+ },
1628
+ quantity: quant,
1629
+ discountedPricePerQuantity: [],
1630
+ lineItemMode: 'Standard',
1631
+ priceMode: 'Platform',
1632
+ state: []
1633
+ };
1634
+ };
1542
1635
  }
1543
1636
 
1544
1637
  getTypeId() {
@@ -1546,9 +1639,12 @@ class CartRepository extends AbstractResourceRepository {
1546
1639
  }
1547
1640
 
1548
1641
  create(projectKey, draft) {
1642
+ var _draft$lineItems;
1643
+
1644
+ const lineItems = (_draft$lineItems = draft.lineItems) == null ? void 0 : _draft$lineItems.map(draftLineItem => this.draftLineItemtoLineItem(projectKey, draftLineItem));
1549
1645
  const resource = { ...getBaseResourceProperties(),
1550
1646
  cartState: 'Active',
1551
- lineItems: [],
1647
+ lineItems: lineItems != null ? lineItems : [],
1552
1648
  customLineItems: [],
1553
1649
  totalPrice: {
1554
1650
  type: 'centPrecision',
@@ -1562,7 +1658,9 @@ class CartRepository extends AbstractResourceRepository {
1562
1658
  refusedGifts: [],
1563
1659
  origin: 'Customer',
1564
1660
  custom: createCustomFields(draft.custom, projectKey, this._storage)
1565
- };
1661
+ }; // @ts-ignore
1662
+
1663
+ resource.totalPrice.centAmount = calculateCartTotalPrice(resource);
1566
1664
  this.save(projectKey, resource);
1567
1665
  return resource;
1568
1666
  }
@@ -1586,16 +1684,308 @@ const calculateLineItemTotalPrice = lineItem => lineItem.price.value.centAmount
1586
1684
 
1587
1685
  const calculateCartTotalPrice = cart => cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
1588
1686
 
1687
+ class OrderRepository extends AbstractResourceRepository {
1688
+ constructor() {
1689
+ super(...arguments);
1690
+ this.actions = {
1691
+ addPayment: (projectKey, resource, {
1692
+ payment
1693
+ }) => {
1694
+ const resolvedPayment = this._storage.getByResourceIdentifier(projectKey, payment);
1695
+
1696
+ if (!resolvedPayment) {
1697
+ throw new Error(`Payment ${payment.id} not found`);
1698
+ }
1699
+
1700
+ if (!resource.paymentInfo) {
1701
+ resource.paymentInfo = {
1702
+ payments: []
1703
+ };
1704
+ }
1705
+
1706
+ resource.paymentInfo.payments.push({
1707
+ typeId: 'payment',
1708
+ id: payment.id
1709
+ });
1710
+ },
1711
+ changeOrderState: (projectKey, resource, {
1712
+ orderState
1713
+ }) => {
1714
+ resource.orderState = orderState;
1715
+ },
1716
+ changePaymentState: (projectKey, resource, {
1717
+ paymentState
1718
+ }) => {
1719
+ resource.paymentState = paymentState;
1720
+ },
1721
+ transitionState: (projectKey, resource, {
1722
+ state
1723
+ }) => {
1724
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, state);
1725
+
1726
+ if (!resolvedType) {
1727
+ throw new Error(`No state found with key=${state.key} or id=${state.key}`);
1728
+ }
1729
+
1730
+ resource.state = {
1731
+ typeId: 'state',
1732
+ id: resolvedType.id
1733
+ };
1734
+ },
1735
+ setBillingAddress: (projectKey, resource, {
1736
+ address
1737
+ }) => {
1738
+ resource.billingAddress = address;
1739
+ },
1740
+ setCustomerEmail: (projectKey, resource, {
1741
+ email
1742
+ }) => {
1743
+ resource.customerEmail = email;
1744
+ },
1745
+ setCustomField: (projectKey, resource, {
1746
+ name,
1747
+ value
1748
+ }) => {
1749
+ if (!resource.custom) {
1750
+ throw new Error('Resource has no custom field');
1751
+ }
1752
+
1753
+ resource.custom.fields[name] = value;
1754
+ },
1755
+ setCustomType: (projectKey, resource, {
1756
+ type,
1757
+ fields
1758
+ }) => {
1759
+ if (!type) {
1760
+ resource.custom = undefined;
1761
+ } else {
1762
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, type);
1763
+
1764
+ if (!resolvedType) {
1765
+ throw new Error(`Type ${type} not found`);
1766
+ }
1767
+
1768
+ resource.custom = {
1769
+ type: {
1770
+ typeId: 'type',
1771
+ id: resolvedType.id
1772
+ },
1773
+ fields: fields || []
1774
+ };
1775
+ }
1776
+ },
1777
+ setLocale: (projectKey, resource, {
1778
+ locale
1779
+ }) => {
1780
+ resource.locale = locale;
1781
+ },
1782
+ setOrderNumber: (projectKey, resource, {
1783
+ orderNumber
1784
+ }) => {
1785
+ resource.orderNumber = orderNumber;
1786
+ },
1787
+ setShippingAddress: (projectKey, resource, {
1788
+ address
1789
+ }) => {
1790
+ resource.shippingAddress = address;
1791
+ },
1792
+ setStore: (projectKey, resource, {
1793
+ store
1794
+ }) => {
1795
+ if (!store) return;
1796
+
1797
+ const resolvedType = this._storage.getByResourceIdentifier(projectKey, store);
1798
+
1799
+ if (!resolvedType) {
1800
+ throw new Error(`No store found with key=${store.key}`);
1801
+ }
1802
+
1803
+ const storeReference = resolvedType;
1804
+ resource.store = {
1805
+ typeId: 'store',
1806
+ key: storeReference.key
1807
+ };
1808
+ }
1809
+ };
1810
+ }
1811
+
1812
+ getTypeId() {
1813
+ return 'order';
1814
+ }
1815
+
1816
+ create(projectKey, draft) {
1817
+ assert(draft.cart, 'draft.cart is missing');
1818
+
1819
+ const cart = this._storage.getByResourceIdentifier(projectKey, draft.cart);
1820
+
1821
+ if (!cart) {
1822
+ throw new Error('Cannot find cart');
1823
+ }
1824
+
1825
+ const resource = { ...getBaseResourceProperties(),
1826
+ orderNumber: draft.orderNumber,
1827
+ orderState: 'Open',
1828
+ lineItems: [],
1829
+ customLineItems: [],
1830
+ totalPrice: cart.totalPrice,
1831
+ refusedGifts: [],
1832
+ origin: 'Customer',
1833
+ syncInfo: [],
1834
+ lastMessageSequenceNumber: 0
1835
+ };
1836
+ this.save(projectKey, resource);
1837
+ return resource;
1838
+ }
1839
+
1840
+ import(projectKey, draft) {
1841
+ var _draft$lineItems, _draft$customLineItem;
1842
+
1843
+ // TODO: Check if order with given orderNumber already exists
1844
+ assert(this, 'OrderRepository not valid');
1845
+ const resource = { ...getBaseResourceProperties(),
1846
+ billingAddress: draft.billingAddress,
1847
+ shippingAddress: draft.shippingAddress,
1848
+ custom: createCustomFields(draft.custom, projectKey, this._storage),
1849
+ customerEmail: draft.customerEmail,
1850
+ lastMessageSequenceNumber: 0,
1851
+ orderNumber: draft.orderNumber,
1852
+ orderState: draft.orderState || 'Open',
1853
+ origin: draft.origin || 'Customer',
1854
+ paymentState: draft.paymentState,
1855
+ refusedGifts: [],
1856
+ store: resolveStoreReference(draft.store, projectKey, this._storage),
1857
+ syncInfo: [],
1858
+ lineItems: ((_draft$lineItems = draft.lineItems) == null ? void 0 : _draft$lineItems.map(item => this.lineItemFromImportDraft.bind(this)(projectKey, item))) || [],
1859
+ customLineItems: ((_draft$customLineItem = draft.customLineItems) == null ? void 0 : _draft$customLineItem.map(item => this.customLineItemFromImportDraft.bind(this)(projectKey, item))) || [],
1860
+ totalPrice: {
1861
+ type: 'centPrecision',
1862
+ ...draft.totalPrice,
1863
+ fractionDigits: 2
1864
+ }
1865
+ };
1866
+ this.save(projectKey, resource);
1867
+ return resource;
1868
+ }
1869
+
1870
+ lineItemFromImportDraft(projectKey, draft) {
1871
+ let product;
1872
+ let variant;
1873
+
1874
+ if (draft.variant.sku) {
1875
+ variant = {
1876
+ id: 0,
1877
+ sku: draft.variant.sku
1878
+ };
1879
+
1880
+ var items = this._storage.query(projectKey, 'product', {
1881
+ where: [`masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`]
1882
+ });
1883
+
1884
+ if (items.count !== 1) {
1885
+ throw new CommercetoolsError({
1886
+ code: 'General',
1887
+ message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
1888
+ });
1889
+ }
1890
+
1891
+ product = items.results[0];
1892
+
1893
+ if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
1894
+ variant = product.masterData.current.masterVariant;
1895
+ } else {
1896
+ variant = product.masterData.current.variants.find(v => v.sku === draft.variant.sku);
1897
+ }
1898
+
1899
+ if (!variant) {
1900
+ throw new Error('Internal state error');
1901
+ }
1902
+ } else {
1903
+ throw new Error('No product found');
1904
+ }
1905
+
1906
+ const lineItem = { ...getBaseResourceProperties(),
1907
+ custom: createCustomFields(draft.custom, projectKey, this._storage),
1908
+ discountedPricePerQuantity: [],
1909
+ lineItemMode: 'Standard',
1910
+ name: draft.name,
1911
+ price: createPrice(draft.price),
1912
+ priceMode: 'Platform',
1913
+ productId: product.id,
1914
+ productType: product.productType,
1915
+ quantity: draft.quantity,
1916
+ state: draft.state || [],
1917
+ taxRate: draft.taxRate,
1918
+ totalPrice: createTypedMoney(draft.price.value),
1919
+ variant: {
1920
+ id: variant.id,
1921
+ sku: variant.sku,
1922
+ price: createPrice(draft.price)
1923
+ }
1924
+ };
1925
+ return lineItem;
1926
+ }
1927
+
1928
+ customLineItemFromImportDraft(projectKey, draft) {
1929
+ const lineItem = { ...getBaseResourceProperties(),
1930
+ custom: createCustomFields(draft.custom, projectKey, this._storage),
1931
+ discountedPricePerQuantity: [],
1932
+ money: createTypedMoney(draft.money),
1933
+ name: draft.name,
1934
+ quantity: draft.quantity,
1935
+ slug: draft.slug,
1936
+ state: [],
1937
+ totalPrice: createTypedMoney(draft.money)
1938
+ };
1939
+ return lineItem;
1940
+ }
1941
+
1942
+ getWithOrderNumber(projectKey, orderNumber, params = {}) {
1943
+ const result = this._storage.query(projectKey, this.getTypeId(), { ...params,
1944
+ where: [`orderNumber="${orderNumber}"`]
1945
+ });
1946
+
1947
+ if (result.count === 1) {
1948
+ return result.results[0];
1949
+ } // Catch this for now, should be checked when creating/updating
1950
+
1951
+
1952
+ if (result.count > 1) {
1953
+ throw new Error('Duplicate order numbers');
1954
+ }
1955
+
1956
+ return;
1957
+ }
1958
+
1959
+ }
1960
+
1589
1961
  class CartService extends AbstractService {
1590
1962
  constructor(parent, storage) {
1591
1963
  super(parent);
1592
1964
  this.repository = new CartRepository(storage);
1965
+ this.orderRepository = new OrderRepository(storage);
1593
1966
  }
1594
1967
 
1595
1968
  getBasePath() {
1596
1969
  return 'carts';
1597
1970
  }
1598
1971
 
1972
+ extraRoutes(parent) {
1973
+ parent.post('/replicate', (request, response) => {
1974
+ // @ts-ignore
1975
+ 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);
1976
+
1977
+ if (!cartOrOrder) {
1978
+ return response.status(400).send();
1979
+ }
1980
+
1981
+ const newCart = this.repository.create(request.params.projectKey, { ...cartOrOrder,
1982
+ currency: cartOrOrder.totalPrice.currencyCode,
1983
+ discountCodes: []
1984
+ });
1985
+ return response.status(200).send(newCart);
1986
+ });
1987
+ }
1988
+
1599
1989
  }
1600
1990
 
1601
1991
  class CategoryRepository extends AbstractResourceRepository {
@@ -1825,7 +2215,7 @@ class CustomerRepository extends AbstractResourceRepository {
1825
2215
  create(projectKey, draft) {
1826
2216
  const resource = { ...getBaseResourceProperties(),
1827
2217
  email: draft.email,
1828
- password: Buffer.from(draft.password).toString('base64'),
2218
+ password: draft.password ? Buffer.from(draft.password).toString('base64') : undefined,
1829
2219
  isEmailVerified: draft.isEmailVerified || false,
1830
2220
  addresses: []
1831
2221
  };
@@ -2264,155 +2654,13 @@ class PaymentRepository extends AbstractResourceRepository {
2264
2654
  constructor() {
2265
2655
  super(...arguments);
2266
2656
 
2267
- this.transactionFromTransactionDraft = (draft, projectKey) => ({ ...draft,
2268
- id: uuid.v4(),
2269
- amount: createTypedMoney(draft.amount),
2270
- custom: createCustomFields(draft.custom, projectKey, this._storage)
2271
- });
2272
-
2273
- this.actions = {
2274
- setCustomField: (projectKey, resource, {
2275
- name,
2276
- value
2277
- }) => {
2278
- if (!resource.custom) {
2279
- throw new Error('Resource has no custom field');
2280
- }
2281
-
2282
- resource.custom.fields[name] = value;
2283
- },
2284
- setCustomType: (projectKey, resource, {
2285
- type,
2286
- fields
2287
- }) => {
2288
- if (!type) {
2289
- resource.custom = undefined;
2290
- } else {
2291
- const resolvedType = this._storage.getByResourceIdentifier(projectKey, type);
2292
-
2293
- if (!resolvedType) {
2294
- throw new Error(`Type ${type} not found`);
2295
- }
2296
-
2297
- resource.custom = {
2298
- type: {
2299
- typeId: 'type',
2300
- id: resolvedType.id
2301
- },
2302
- fields: fields || []
2303
- };
2304
- }
2305
- },
2306
- addTransaction: (projectKey, resource, {
2307
- transaction
2308
- }) => {
2309
- resource.transactions = [...resource.transactions, this.transactionFromTransactionDraft(transaction, projectKey)];
2310
- },
2311
- changeTransactionState: (_projectKey, resource, {
2312
- transactionId,
2313
- state
2314
- }) => {
2315
- const index = resource.transactions.findIndex(e => e.id === transactionId);
2316
- const updatedTransaction = { ...resource.transactions[index],
2317
- state
2318
- };
2319
- resource.transactions[index] = updatedTransaction;
2320
- },
2321
- transitionState: (projectKey, resource, {
2322
- state
2323
- }) => {
2324
- const stateObj = this._storage.getByResourceIdentifier(projectKey, state);
2325
-
2326
- if (!stateObj) {
2327
- throw new Error(`State ${state} not found`);
2328
- }
2329
-
2330
- resource.paymentStatus.state = {
2331
- typeId: 'state',
2332
- id: stateObj.id,
2333
- obj: stateObj
2334
- };
2335
- }
2336
- };
2337
- }
2338
-
2339
- getTypeId() {
2340
- return 'payment';
2341
- }
2342
-
2343
- create(projectKey, draft) {
2344
- const resource = { ...getBaseResourceProperties(),
2345
- amountPlanned: createTypedMoney(draft.amountPlanned),
2346
- paymentMethodInfo: draft.paymentMethodInfo,
2347
- paymentStatus: draft.paymentStatus ? { ...draft.paymentStatus,
2348
- state: draft.paymentStatus.state ? getReferenceFromResourceIdentifier(draft.paymentStatus.state, projectKey, this._storage) : undefined
2349
- } : {},
2350
- transactions: (draft.transactions || []).map(t => this.transactionFromTransactionDraft(t, projectKey)),
2351
- interfaceInteractions: (draft.interfaceInteractions || []).map(interaction => createCustomFields(interaction, projectKey, this._storage)),
2352
- custom: createCustomFields(draft.custom, projectKey, this._storage)
2353
- };
2354
- this.save(projectKey, resource);
2355
- return resource;
2356
- }
2357
-
2358
- }
2359
-
2360
- class MyPaymentService extends AbstractService {
2361
- constructor(parent, storage) {
2362
- super(parent);
2363
- this.repository = new PaymentRepository(storage);
2364
- }
2365
-
2366
- getBasePath() {
2367
- return 'me/payments';
2368
- }
2369
-
2370
- }
2371
-
2372
- class OrderRepository extends AbstractResourceRepository {
2373
- constructor() {
2374
- super(...arguments);
2375
- this.actions = {
2376
- addPayment: (projectKey, resource, {
2377
- payment
2378
- }) => {
2379
- const resolvedPayment = this._storage.getByResourceIdentifier(projectKey, payment);
2380
-
2381
- if (!resolvedPayment) {
2382
- throw new Error(`Payment ${payment.id} not found`);
2383
- }
2384
-
2385
- if (!resource.paymentInfo) {
2386
- resource.paymentInfo = {
2387
- payments: []
2388
- };
2389
- }
2657
+ this.transactionFromTransactionDraft = (draft, projectKey) => ({ ...draft,
2658
+ id: uuid.v4(),
2659
+ amount: createTypedMoney(draft.amount),
2660
+ custom: createCustomFields(draft.custom, projectKey, this._storage)
2661
+ });
2390
2662
 
2391
- resource.paymentInfo.payments.push({
2392
- typeId: 'payment',
2393
- id: payment.id
2394
- });
2395
- },
2396
- changeOrderState: (projectKey, resource, {
2397
- orderState
2398
- }) => {
2399
- resource.orderState = orderState;
2400
- },
2401
- changePaymentState: (projectKey, resource, {
2402
- paymentState
2403
- }) => {
2404
- resource.paymentState = paymentState;
2405
- },
2406
- setBillingAddress: (projectKey, resource, {
2407
- address
2408
- }) => {
2409
- resource.billingAddress = address;
2410
- },
2411
- setCustomerEmail: (projectKey, resource, {
2412
- email
2413
- }) => {
2414
- resource.customerEmail = email;
2415
- },
2663
+ this.actions = {
2416
2664
  setCustomField: (projectKey, resource, {
2417
2665
  name,
2418
2666
  value
@@ -2445,186 +2693,68 @@ class OrderRepository extends AbstractResourceRepository {
2445
2693
  };
2446
2694
  }
2447
2695
  },
2448
- setLocale: (projectKey, resource, {
2449
- locale
2450
- }) => {
2451
- resource.locale = locale;
2452
- },
2453
- setOrderNumber: (projectKey, resource, {
2454
- orderNumber
2696
+ addTransaction: (projectKey, resource, {
2697
+ transaction
2455
2698
  }) => {
2456
- resource.orderNumber = orderNumber;
2699
+ resource.transactions = [...resource.transactions, this.transactionFromTransactionDraft(transaction, projectKey)];
2457
2700
  },
2458
- setShippingAddress: (projectKey, resource, {
2459
- address
2701
+ changeTransactionState: (_projectKey, resource, {
2702
+ transactionId,
2703
+ state
2460
2704
  }) => {
2461
- resource.shippingAddress = address;
2705
+ const index = resource.transactions.findIndex(e => e.id === transactionId);
2706
+ const updatedTransaction = { ...resource.transactions[index],
2707
+ state
2708
+ };
2709
+ resource.transactions[index] = updatedTransaction;
2462
2710
  },
2463
- setStore: (projectKey, resource, {
2464
- store
2711
+ transitionState: (projectKey, resource, {
2712
+ state
2465
2713
  }) => {
2466
- if (!store) return;
2467
-
2468
- const resolvedType = this._storage.getByResourceIdentifier(projectKey, store);
2714
+ const stateObj = this._storage.getByResourceIdentifier(projectKey, state);
2469
2715
 
2470
- if (!resolvedType) {
2471
- throw new Error(`No store found with key=${store.key}`);
2716
+ if (!stateObj) {
2717
+ throw new Error(`State ${state} not found`);
2472
2718
  }
2473
2719
 
2474
- const storeReference = resolvedType;
2475
- resource.store = {
2476
- typeId: 'store',
2477
- key: storeReference.key
2720
+ resource.paymentStatus.state = {
2721
+ typeId: 'state',
2722
+ id: stateObj.id,
2723
+ obj: stateObj
2478
2724
  };
2479
2725
  }
2480
2726
  };
2481
2727
  }
2482
2728
 
2483
2729
  getTypeId() {
2484
- return 'order';
2730
+ return 'payment';
2485
2731
  }
2486
2732
 
2487
2733
  create(projectKey, draft) {
2488
- assert(draft.cart, 'draft.cart is missing');
2489
-
2490
- const cart = this._storage.getByResourceIdentifier(projectKey, draft.cart);
2491
-
2492
- if (!cart) {
2493
- throw new Error('Cannot find cart');
2494
- }
2495
-
2496
- const resource = { ...getBaseResourceProperties(),
2497
- orderNumber: draft.orderNumber,
2498
- orderState: 'Open',
2499
- lineItems: [],
2500
- customLineItems: [],
2501
- totalPrice: cart.totalPrice,
2502
- refusedGifts: [],
2503
- origin: 'Customer',
2504
- syncInfo: [],
2505
- lastMessageSequenceNumber: 0
2506
- };
2507
- this.save(projectKey, resource);
2508
- return resource;
2509
- }
2510
-
2511
- import(projectKey, draft) {
2512
- var _draft$lineItems, _draft$customLineItem;
2513
-
2514
- // TODO: Check if order with given orderNumber already exists
2515
- assert(this, 'OrderRepository not valid');
2516
2734
  const resource = { ...getBaseResourceProperties(),
2517
- billingAddress: draft.billingAddress,
2518
- shippingAddress: draft.shippingAddress,
2519
- custom: createCustomFields(draft.custom, projectKey, this._storage),
2520
- customerEmail: draft.customerEmail,
2521
- lastMessageSequenceNumber: 0,
2522
- orderNumber: draft.orderNumber,
2523
- orderState: draft.orderState || 'Open',
2524
- origin: draft.origin || 'Customer',
2525
- paymentState: draft.paymentState,
2526
- refusedGifts: [],
2527
- store: resolveStoreReference(draft.store, projectKey, this._storage),
2528
- syncInfo: [],
2529
- lineItems: ((_draft$lineItems = draft.lineItems) == null ? void 0 : _draft$lineItems.map(item => this.lineItemFromImportDraft.bind(this)(projectKey, item))) || [],
2530
- customLineItems: ((_draft$customLineItem = draft.customLineItems) == null ? void 0 : _draft$customLineItem.map(item => this.customLineItemFromImportDraft.bind(this)(projectKey, item))) || [],
2531
- totalPrice: {
2532
- type: 'centPrecision',
2533
- ...draft.totalPrice,
2534
- fractionDigits: 2
2535
- }
2735
+ amountPlanned: createTypedMoney(draft.amountPlanned),
2736
+ paymentMethodInfo: draft.paymentMethodInfo,
2737
+ paymentStatus: draft.paymentStatus ? { ...draft.paymentStatus,
2738
+ state: draft.paymentStatus.state ? getReferenceFromResourceIdentifier(draft.paymentStatus.state, projectKey, this._storage) : undefined
2739
+ } : {},
2740
+ transactions: (draft.transactions || []).map(t => this.transactionFromTransactionDraft(t, projectKey)),
2741
+ interfaceInteractions: (draft.interfaceInteractions || []).map(interaction => createCustomFields(interaction, projectKey, this._storage)),
2742
+ custom: createCustomFields(draft.custom, projectKey, this._storage)
2536
2743
  };
2537
2744
  this.save(projectKey, resource);
2538
2745
  return resource;
2539
2746
  }
2540
2747
 
2541
- lineItemFromImportDraft(projectKey, draft) {
2542
- let product;
2543
- let variant;
2544
-
2545
- if (draft.variant.sku) {
2546
- variant = {
2547
- id: 0,
2548
- sku: draft.variant.sku
2549
- };
2550
-
2551
- var items = this._storage.query(projectKey, 'product', {
2552
- where: [`masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`]
2553
- });
2554
-
2555
- if (items.count !== 1) {
2556
- throw new CommercetoolsError({
2557
- code: 'General',
2558
- message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
2559
- });
2560
- }
2561
-
2562
- product = items.results[0];
2563
-
2564
- if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
2565
- variant = product.masterData.current.masterVariant;
2566
- } else {
2567
- variant = product.masterData.current.variants.find(v => v.sku === draft.variant.sku);
2568
- }
2569
-
2570
- if (!variant) {
2571
- throw new Error('Internal state error');
2572
- }
2573
- } else {
2574
- throw new Error('No product found');
2575
- }
2576
-
2577
- const lineItem = { ...getBaseResourceProperties(),
2578
- custom: createCustomFields(draft.custom, projectKey, this._storage),
2579
- discountedPricePerQuantity: [],
2580
- lineItemMode: 'Standard',
2581
- name: draft.name,
2582
- price: createPrice(draft.price),
2583
- priceMode: 'Platform',
2584
- productId: product.id,
2585
- productType: product.productType,
2586
- quantity: draft.quantity,
2587
- state: draft.state || [],
2588
- taxRate: draft.taxRate,
2589
- totalPrice: createTypedMoney(draft.price.value),
2590
- variant: {
2591
- id: variant.id,
2592
- sku: variant.sku,
2593
- price: createPrice(draft.price)
2594
- }
2595
- };
2596
- return lineItem;
2597
- }
2748
+ }
2598
2749
 
2599
- customLineItemFromImportDraft(projectKey, draft) {
2600
- const lineItem = { ...getBaseResourceProperties(),
2601
- custom: createCustomFields(draft.custom, projectKey, this._storage),
2602
- discountedPricePerQuantity: [],
2603
- money: createTypedMoney(draft.money),
2604
- name: draft.name,
2605
- quantity: draft.quantity,
2606
- slug: draft.slug,
2607
- state: [],
2608
- totalPrice: createTypedMoney(draft.money)
2609
- };
2610
- return lineItem;
2750
+ class MyPaymentService extends AbstractService {
2751
+ constructor(parent, storage) {
2752
+ super(parent);
2753
+ this.repository = new PaymentRepository(storage);
2611
2754
  }
2612
2755
 
2613
- getWithOrderNumber(projectKey, orderNumber, params = {}) {
2614
- const result = this._storage.query(projectKey, this.getTypeId(), { ...params,
2615
- where: [`orderNumber="${orderNumber}"`]
2616
- });
2617
-
2618
- if (result.count === 1) {
2619
- return result.results[0];
2620
- } // Catch this for now, should be checked when creating/updating
2621
-
2622
-
2623
- if (result.count > 1) {
2624
- throw new Error('Duplicate order numbers');
2625
- }
2626
-
2627
- return;
2756
+ getBasePath() {
2757
+ return 'me/payments';
2628
2758
  }
2629
2759
 
2630
2760
  }
@@ -3993,6 +4123,33 @@ class MyCustomerService extends AbstractService {
3993
4123
 
3994
4124
  }
3995
4125
 
4126
+ class MyOrderService extends AbstractService {
4127
+ constructor(parent, storage) {
4128
+ super(parent);
4129
+ this.repository = new OrderRepository(storage);
4130
+ }
4131
+
4132
+ getBasePath() {
4133
+ return 'me';
4134
+ }
4135
+
4136
+ registerRoutes(parent) {
4137
+ // Overwrite this function to be able to handle /me/active-cart path.
4138
+ const basePath = this.getBasePath();
4139
+ const router = express.Router({
4140
+ mergeParams: true
4141
+ });
4142
+ this.extraRoutes(router);
4143
+ router.get('/orders/', this.get.bind(this));
4144
+ router.get('/orders/:id', this.getWithId.bind(this));
4145
+ router.delete('/orders/:id', this.deletewithId.bind(this));
4146
+ router.post('/orders/', this.post.bind(this));
4147
+ router.post('/orders/:id', this.postWithId.bind(this));
4148
+ parent.use(`/${basePath}`, router);
4149
+ }
4150
+
4151
+ }
4152
+
3996
4153
  const DEFAULT_OPTIONS = {
3997
4154
  enableAuthentication: false,
3998
4155
  validateCredentials: false,
@@ -4091,6 +4248,7 @@ class CommercetoolsMock {
4091
4248
  order: new OrderService(projectRouter, this._storage),
4092
4249
  payment: new PaymentService(projectRouter, this._storage),
4093
4250
  'my-cart': new MyCartService(projectRouter, this._storage),
4251
+ 'my-order': new MyOrderService(projectRouter, this._storage),
4094
4252
  'my-customer': new MyCustomerService(projectRouter, this._storage),
4095
4253
  'my-payment': new MyPaymentService(projectRouter, this._storage),
4096
4254
  'shipping-method': new ShippingMethodService(projectRouter, this._storage),