"use strict";

var _bluebird = _interopRequireDefault(require("bluebird"));

var hybris = _interopRequireWildcard(require("hybris-occ-client"));

var _hybris = require("./hybris");

var types = _interopRequireWildcard(require("../types"));

var _testUtils = require("../utils/test-utils");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

if (_testUtils.isIntegrationTest) {
  jest.setTimeout(45000);
}

var userFixture = function userFixture(key) {
  var time = _testUtils.isIntegrationTest ? new Date().getTime() : '';
  return {
    firstName: "test-".concat(key).concat(time, "-firstName"),
    lastName: "test-".concat(key).concat(time, "-lastName"),
    email: "test-".concat(key).concat(time, "-email@example.com"),
    password: "test-".concat(key).concat(time, "-Pa55word"),
    titleCode: 'ms'
  };
};

var conf = {
  url: 'https://hybris.merlinspotions.com'
  /* eslint-disable no-unused-vars */

};
var customerInfo = {
  email: 'mobifyqa2@domain.com'
};
var registeredUser = {
  username: 'mobifyqa@gmail.com',
  password: 'p4ssword'
};
var orderAddress = {
  titleCode: 'ms',
  firstName: 'Donald',
  lastName: 'Duck',
  phone: '4449992222',
  addressLine1: '333 Rosewood Dr',
  countryCode: 'GB',
  stateCode: 'GB-KEN',
  city: 'Liverpool',
  postalCode: '83920'
};
var cartItem = {
  productId: '300515779',
  quantity: 1
};
var payment = {
  // hybris doesn't need to know payment amount.
  methodId: 'CREDIT_CARD',
  details: {
    type: 'amex',
    holderName: 'Donald Trump',
    number: 411111111111111,
    expiryMonth: 1,
    expiryYear: 2021
  }
  /* eslint-disable no-unused-vars */

};
describe("The Hybris Connector", function () {
  var makeConnector = function makeConnector() {
    return new _hybris.HybrisConnector({
      client: new hybris.ApiClient({
        basePath: "".concat(conf.url, "/rest/v2/apparel-uk/"),
        defaultHeaders: {},
        timeout: 60000
      }),
      catalogId: 'apparelProductCatalog',
      catalogVersionId: 'Online',
      authentication: {
        authorizationUrl: "".concat(conf.url, "/authorizationserver/oauth/token"),
        clientId: 'mobile_android',
        clientSecret: 'secret'
      }
    });
  };

  describe('Searching for products', function () {
    var sorts = [undefined, {
      query: 'name-asc',
      key: 'productName',
      compare: function compare(a, b) {
        return a.localeCompare(b);
      }
    }, {
      query: 'price-desc',
      key: 'price',
      compare: function compare(a, b) {
        return b - a;
      }
    }];
    sorts.forEach(function (sortOpts) {
      var spec = test("with a sort order [sort: ".concat(sortOpts && sortOpts.query, "]"), function () {
        return (0, _testUtils.record)(spec, function () {
          var connector = makeConnector();

          var query = _objectSpread({
            filters: {
              categoryId: '220000'
            }
          }, sortOpts && {
            sort: sortOpts.query
          });

          return connector.searchProducts(query).then(function (data) {
            expect((0, _testUtils.propTypeErrors)(types.ProductSearch, data)).toBeFalsy();

            if (sortOpts) {
              var key = sortOpts.key,
                  compare = sortOpts.compare; // eslint-disable-next-line max-nested-callbacks

              var values = data.results.map(function (item) {
                return item[key];
              });
              var expected = values.slice().sort(compare);
              expect(values).toEqual(expected);
            }
          });
        });
      });
    });
    var counts = [2, 8];
    counts.forEach(function (count) {
      var spec = test("with a max count (count: ".concat(count, ")"), function () {
        return (0, _testUtils.record)(spec, function () {
          var connector = makeConnector();
          var query = {
            filters: {
              categoryId: '220000'
            },
            count: count
          };
          return connector.searchProducts(query).then(function (data) {
            expect((0, _testUtils.propTypeErrors)(types.ProductSearch, data)).toBeFalsy();
            expect(data.results.length).toEqual(count);
          });
        });
      });
    });
    var spec1 = test("by query value returns results for a known search query value", function () {
      return (0, _testUtils.record)(spec1, function () {
        var connector = makeConnector();
        var searchRequest = {
          query: 'mouse'
        };
        return connector.searchProducts(searchRequest).then(function (data) {
          expect((0, _testUtils.propTypeErrors)(types.ProductSearch, data)).toBeFalsy();
          expect(data.results.length).toBeGreaterThan(0);
          expect(data.query.toLowerCase()).toEqual(searchRequest.query.toLowerCase());
        });
      });
    });
    var spec2 = test("by query value returns no results for a unknown search query value", function () {
      return (0, _testUtils.record)(spec2, function () {
        var connector = makeConnector();
        var searchRequest = {
          query: 'xxxyyyaaabbb'
        };
        return connector.searchProducts(searchRequest).then(function (data) {
          expect((0, _testUtils.propTypeErrors)(types.ProductSearch, data)).toBeFalsy();
          expect(data.results.length).toEqual(0);
          expect(data.query.toLowerCase()).toEqual(searchRequest.query.toLowerCase());
        });
      });
    });
  });
  describe('Getting a product', function () {
    var spec1 = test('with a valid id should resolve with a Product instance', function () {
      return (0, _testUtils.record)(spec1, function () {
        var connector = makeConnector();
        return connector.getProduct('300659388').then(function (data) {
          expect((0, _testUtils.propTypeErrors)(types.Product, data)).toBeFalsy();
        });
      });
    });
    var spec2 = test('with an invalid id should reject', function () {
      return (0, _testUtils.record)(spec2, function () {
        var connector = makeConnector();
        expect(connector.getProduct('1')).rejects.toThrow();
      });
    });
  });
  describe('Getting products', function () {
    var spec1 = test('with valid ids', function () {
      // should resolve with a ProductList instance with populated data
      return (0, _testUtils.record)(spec1, function () {
        var connector = makeConnector();
        var validIds = ['300659388', '300466683'];
        return connector.getProducts(validIds).then(function (result) {
          expect((0, _testUtils.propTypeErrors)(types.ProductList, result)).toBeFalsy();
          expect(result.data.length).toEqual(validIds.length);
        });
      });
    });
    var spec2 = test('with invalid ids', function () {
      // should resolve with a ProductList instance with empty data
      return (0, _testUtils.record)(spec2, function () {
        var connector = makeConnector();
        var invalidIds = ['1', '2'];
        return connector.getProducts(invalidIds).then(function (result) {
          expect((0, _testUtils.propTypeErrors)(types.ProductList, result)).toBeFalsy();
          expect(result.data.length).toEqual(0);
        });
      });
    });
    var spec3 = test('with a mix of valid and invalid ids', function () {
      // should resolve with a ProductList instance with partial data
      return (0, _testUtils.record)(spec3, function () {
        var connector = makeConnector();
        var validIds = ['300659388', '300466683'];
        var invalidIds = ['1', '2'];
        return connector.getProducts([].concat(validIds, invalidIds)).then(function (result) {
          expect((0, _testUtils.propTypeErrors)(types.ProductList, result)).toBeFalsy();
          expect(result.data.length).toEqual(validIds.length);
          expect(result.total).toEqual(validIds.length);
          expect(result.count).toEqual(validIds.length);
        });
      });
    });
  });
  var spec2 = test('Getting a store', function () {
    return (0, _testUtils.record)(spec2, function () {
      var connector = makeConnector();
      return connector.getStore('London Hospital').then(function (data) {
        expect((0, _testUtils.propTypeErrors)(types.Store, data)).toBeFalsy();
      });
    });
  });
  describe('Searching for Stores', function () {
    // searchStoreRequest is using default values for start, count if not provided
    var spec1 = test('Only longitude provided, missing latitude', function () {
      return (0, _testUtils.record)(spec1, function () {
        var connector = makeConnector();
        var searchStoreRequest = {
          latlon: {
            longitude: -0.116745
          }
        };
        expect(function () {
          connector.searchStores(searchStoreRequest);
        }).toThrowError('Provide Latitude and Longitude coordinates');
      });
    });
    var spec2 = test('Only latitude provided, missing longitude', function () {
      return (0, _testUtils.record)(spec2, function () {
        var connector = makeConnector();
        var searchStoreRequest = {
          latlon: {
            latitude: 52.514151
          }
        };
        expect(function () {
          connector.searchStores(searchStoreRequest);
        }).toThrowError('Provide Latitude and Longitude coordinates');
      });
    });
    var spec3 = test('Valid latitude and longitude provided', function () {
      return (0, _testUtils.record)(spec3, function () {
        var connector = makeConnector();
        var searchStoreRequest = {
          latlon: {
            latitude: 52.514151,
            longitude: -0.116745
          }
        };
        return connector.searchStores(searchStoreRequest).then(function (data) {
          expect(data.stores).not.toHaveLength(0);
          expect(data.stores).toHaveLength(data.count);
          expect((0, _testUtils.propTypeErrors)(types.StoreSearchResult, data)).toBeFalsy();
        });
      });
    });
    var spec4 = test('0.0, 0.0 geo-coordinates allowed', function () {
      return (0, _testUtils.record)(spec4, function () {
        var connector = makeConnector();
        var searchStoreRequest = {
          latlon: {
            latitude: 0.0,
            longitude: 0.0
          }
        };
        return expect(connector.searchStores(searchStoreRequest)).rejects.toThrowError('No stores found');
      });
    });
  });
  describe('Get Product Categories', function () {
    var spec1 = test("getCategory should resolve to a Category instance", function () {
      return (0, _testUtils.record)(spec1, function () {
        var connector = makeConnector();
        var category = 'categories';
        return connector.getCategory(category).then(function (data) {
          expect((0, _testUtils.propTypeErrors)(types.Category, data)).toBeFalsy();
          expect(data.id).toEqual(category);
        });
      });
    });
    var spec2 = test("getCategories should resolve to a CategoryList instance", function () {
      return (0, _testUtils.record)(spec2, function () {
        var connector = makeConnector();
        var categories = ['220000', '320000'];
        return connector.getCategories(categories).then(function (result) {
          expect((0, _testUtils.propTypeErrors)(types.CategoryList, result)).toBeFalsy();
          expect(result.count).toEqual(2);
          expect(result.data[0].id).toEqual(categories[0]);
          expect(result.data[1].id).toEqual(categories[1]);
        });
      });
    });
  });
  describe('Account management', function () {
    var spec = test('Should support creating a new user account', function () {
      return (0, _testUtils.record)(spec, function () {
        var data = userFixture('creating-accounts');
        var connector = makeConnector();
        return connector.login().then(function () {
          return connector.registerCustomer(data);
        }).then(function (customer) {
          return expect((0, _testUtils.propTypeErrors)(types.Customer, customer)).toBeFalsy();
        }).then(function () {
          return connector.getCustomer('current');
        }).then(function (customer) {
          expect((0, _testUtils.propTypeErrors)(types.Customer, customer)).toBeFalsy();
          expect(customer).toEqual({
            id: 'current',
            firstName: data.firstName,
            lastName: data.lastName,
            email: data.email
          });
        });
      });
    });
  });
  describe('Login', function () {
    var spec1 = test('should support logging in as a registered user', function () {
      return (0, _testUtils.record)(spec1, function () {
        var connector = makeConnector();
        var username = 'mobifyqa@gmail.com';
        var password = 'p4ssword';
        return connector.login(username, password).then(function (customer) {
          expect(connector.client.authentications.auth.accessToken).toBeDefined();
          expect(connector.client.authentications.auth.expiresIn).toBeDefined();
          expect(connector.client.authentications.auth.refreshToken).toBeDefined();
          expect((0, _testUtils.propTypeErrors)(types.Customer, customer)).toBeFalsy();
          expect(customer.id).toEqual('current');
        });
      });
    });
    var spec2 = test('should allow a session to be transferred from another instance', function () {
      return (0, _testUtils.record)(spec2, function () {
        var customer;
        var connector1 = makeConnector();
        var connector2 = makeConnector();
        return connector1.login('mobifyqa@gmail.com', 'p4ssword').then(function (_customer) {
          customer = _customer;
        }).then(function () {
          // Transfer session onto connector 2
          connector2.setAuthentications(connector1.getAuthentications());
          return connector2.getCustomer('current');
        }).then(function (_customer) {
          expect(customer).toEqual(_customer);
        });
      });
    });
    var spec3 = test('should support logging in as a guest', function () {
      return (0, _testUtils.record)(spec3, function () {
        var connector = makeConnector();
        return connector.login().then(function (customer) {
          expect(connector.client.authentications.auth.accessToken).toBeDefined();
          expect(connector.client.authentications.auth.expiresIn).toBeDefined();
          expect(connector.client.authentications.auth.refreshToken).toBeUndefined(); // expect(propTypeErrors(types.Customer, customer)).toBeFalsy()

          expect(customer.id).toEqual('anonymous');
        });
      });
    });
    var spec4 = test('login as registered user and refresh access token', function () {
      return (0, _testUtils.record)(spec4, function () {
        var connector = makeConnector();
        var username = 'mobifyqa@gmail.com';
        var password = 'p4ssword';
        var oldAuth;
        var newAuth;
        return connector.login(username, password).then(function (customer) {
          oldAuth = Object.assign({}, connector.client.authentications.auth);
          expect((0, _testUtils.propTypeErrors)(types.Customer, customer)).toBeFalsy();
          expect(customer.id).toEqual('current');
          return connector.refreshSession() // eslint-disable-next-line max-nested-callbacks
          .then(function (customer) {
            newAuth = connector.client.authentications.auth;
            expect(oldAuth.accessToken).not.toEqual(newAuth.accessToken);
            expect(oldAuth.refreshToken).not.toEqual(newAuth.refreshToken);
            expect((0, _testUtils.propTypeErrors)(types.Customer, customer)).toBeFalsy();
            expect(customer.id).toEqual('current');
          });
        });
      });
    });
    var spec5 = test('login as guest and refresh access token', function () {
      return (0, _testUtils.record)(spec5, function () {
        var connector = makeConnector();
        var oldAuth;
        var newAuth;
        return connector.login().then(function (customer) {
          oldAuth = Object.assign({}, connector.client.authentications.auth);
          expect(oldAuth.refreshToken).toBeUndefined();
          expect((0, _testUtils.propTypeErrors)(types.Customer, customer)).toBeFalsy();
          expect(customer.id).toEqual('anonymous');
          return connector.refreshSession() // eslint-disable-next-line max-nested-callbacks
          .then(function (customer) {
            newAuth = connector.client.authentications.auth;
            expect(oldAuth.accessToken).toEqual(newAuth.accessToken);
            expect(newAuth.refreshToken).toBeUndefined();
            expect((0, _testUtils.propTypeErrors)(types.Customer, customer)).toBeFalsy();
            expect(customer.id).toEqual('anonymous');
          });
        });
      });
    });
  });
  describe('Cart Integration Test', function () {
    var spec1 = test('for a guest user', function () {
      return (0, _testUtils.record)(spec1, function () {
        var connector = makeConnector();
        var cartId; // 1. Login as a guest user

        return connector.login().then(function (user) {
          expect(user.id).toEqual('anonymous');
          return null;
        }) // 2. Create a cart
        .then(function () {
          return connector.createCart();
        }).then(function (cart) {
          cartId = cart.id;
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.customerInfo.id).toEqual('anonymous');
          expect(cart.customerInfo.email).toBeUndefined();
          expect(cart.items.length).toEqual(0);
          expect(cart.selectedShippingMethodId).toBeUndefined();
          expect(cart.payments.length).toEqual(0);
          expect(cart.subtotal).toEqual(0);
          expect(cart.shipping).toBeUndefined();
          expect(cart.discounts).toEqual(0);
          expect(cart.tax).toEqual(0);
          expect(cart.total).toEqual(0);
          return cart;
        }) // Try to set a shipping address before setting an email will result in an error
        .then(function (cart) {
          // eslint-disable-next-line max-nested-callbacks
          expect(function () {
            connector.setShippingAddress(cart, orderAddress);
          }).toThrow();
          return cart;
        }) // 3. Set customer information (email) - only possible for guest user
        .then(function (cart) {
          return connector.setCustomerInformation(cart, customerInfo);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.customerInfo).toEqual({
            id: 'anonymous',
            email: customerInfo.email
          });
          return cart;
        }) // 4. Add cart item
        .then(function (cart) {
          return connector.addCartItem(cart, cartItem);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.items.length).toEqual(1);
          var cartItemUpdated = cart.items[0];
          expect(cartItemUpdated.productId).toEqual(cartItem.productId);
          expect(cartItemUpdated.quantity).toEqual(cartItem.quantity);
          expect(cartItemUpdated.id).toEqual('0'); // cart item id is entry number

          expect(cartItemUpdated.baseItemPrice).toBeGreaterThan(0);
          expect(cartItemUpdated.baseLinePrice).toBeGreaterThan(0);
          expect(cartItemUpdated.itemPrice).toBeGreaterThan(0);
          expect(cartItemUpdated.linePrice).toBeGreaterThan(0);
          expect(cart.subtotal).toBeGreaterThan(0);
          expect(cart.total).toBeGreaterThan(0);
          return cart;
        }) // 5. Update cart item
        .then(function (cart) {
          return _bluebird["default"].all([connector.updateCartItem(cart, _objectSpread({}, cartItem, {
            id: cart.items[0].id,
            quantity: 2
          })), _bluebird["default"].resolve(cart.items[0])]);
        }).then(function (_ref) {
          var _ref2 = _slicedToArray(_ref, 2),
              cart = _ref2[0],
              oldCartItem = _ref2[1];

          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.items.length).toEqual(1);
          var cartItemUpdated = cart.items[0];
          expect(cartItemUpdated.productId).toEqual(cartItem.productId);
          expect(cartItemUpdated.quantity).toEqual(2);
          expect(cartItemUpdated.id).toEqual('0'); // cart item id is entry number (0 indexed position in list of entries)

          expect(cartItemUpdated.baseItemPrice).toEqual(oldCartItem.baseItemPrice);
          expect(cartItemUpdated.baseLinePrice).toBeGreaterThan(oldCartItem.baseLinePrice);
          expect(cartItemUpdated.itemPrice).toEqual(oldCartItem.itemPrice);
          expect(cartItemUpdated.linePrice).toBeGreaterThan(oldCartItem.linePrice);
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), _bluebird["default"].resolve(cartItemUpdated)]);
        }) // 6. Delete cart item
        .then(function (_ref3) {
          var _ref4 = _slicedToArray(_ref3, 2),
              cart = _ref4[0],
              cartItemUpdated = _ref4[1];

          return connector.removeCartItem(cart, cartItemUpdated.id);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.items.length).toEqual(0);
          return cart;
        }) // 7. Get payment methods (need to set a valid card type for a payment)
        .then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.getPaymentMethods(cart)]);
        }) // Trying to add a payment before setting a billing address will result in an error
        .then(function (_ref5) {
          var _ref6 = _slicedToArray(_ref5, 2),
              cart = _ref6[0],
              paymentMethods = _ref6[1];

          var creditCardPaymentMethod = paymentMethods[0];
          payment.methodId = creditCardPaymentMethod.id;
          payment.details.type = creditCardPaymentMethod.types[0].id; // eslint-disable-next-line max-nested-callbacks

          expect(function () {
            connector.setPayment(cart, payment);
          }).toThrow();
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), _bluebird["default"].resolve(paymentMethods)]);
        }) // 8. Set billing address - need to set billing address first before adding a payment
        .then(function (_ref7) {
          var _ref8 = _slicedToArray(_ref7, 2),
              cart = _ref8[0],
              paymentMethods = _ref8[1];

          return _bluebird["default"].all([_bluebird["default"].resolve(paymentMethods), connector.setBillingAddress(cart, orderAddress)]);
        }) // 9. Add payment
        .then(function (_ref9) {
          var _ref10 = _slicedToArray(_ref9, 2),
              paymentMethods = _ref10[0],
              cart = _ref10[1];

          var creditCardPaymentMethod = paymentMethods[0];
          payment.methodId = creditCardPaymentMethod.id;
          payment.details.type = creditCardPaymentMethod.types[0].id;
          return connector.setPayment(cart, payment);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.payments.length).toEqual(1);
          var paymentUpdated = cart.payments[0];
          expect(paymentUpdated.id).toBeDefined();
          expect(paymentUpdated.amount).toEqual(cart.total); // always set payment amount to cart total.

          expect(paymentUpdated.methodId).toEqual(payment.methodId);
          expect(paymentUpdated.details.type).toEqual(payment.details.type);
          expect(paymentUpdated.details.holderName).toEqual(payment.details.holderName);
          expect(paymentUpdated.details.number).toBeUndefined(); // card number comes back as a masked number. see next expect.

          expect(paymentUpdated.details.maskedNumber).toContain('************');
          expect(paymentUpdated.details.username).toBeUndefined();
          expect(paymentUpdated.details.expiryMonth).toEqual(payment.details.expiryMonth);
          expect(paymentUpdated.details.expiryYear).toEqual(payment.details.expiryYear);
          expect(paymentUpdated.details.ccv).toBeUndefined();
          expect(cart.billingAddress).toEqual(orderAddress);
          return cart;
        }) // 10. Update payment
        .then(function (cart) {
          var paymentModified = JSON.parse(JSON.stringify(payment));
          paymentModified.details.holderName = 'Ronald Duck';
          paymentModified.details.number = 411111111111111;
          return _bluebird["default"].all([_bluebird["default"].resolve(cart.payments[0]), _bluebird["default"].resolve(paymentModified), connector.setPayment(cart, paymentModified)]);
        }).then(function (_ref11) {
          var _ref12 = _slicedToArray(_ref11, 3),
              oldPayment = _ref12[0],
              newPayment = _ref12[1],
              cart = _ref12[2];

          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.payments.length).toEqual(1);
          var paymentUpdated = cart.payments[0];
          expect(paymentUpdated.id).toBeDefined();
          expect(paymentUpdated.id).not.toEqual(oldPayment.id); // payment id changes upon update for guest users because payments do not persist on guest user account

          expect(paymentUpdated.amount).toEqual(cart.total);
          expect(paymentUpdated.amount).toEqual(oldPayment.amount);
          expect(paymentUpdated.methodId).toEqual(oldPayment.methodId);
          expect(paymentUpdated.details.type).toEqual(oldPayment.details.type);
          expect(paymentUpdated.details.holderName).toEqual(newPayment.details.holderName);
          expect(paymentUpdated.details.holderName).not.toEqual(oldPayment.details.holderName);
          expect(paymentUpdated.details.number).toBeUndefined(); // card number comes back as a masked number. see next expect.

          expect(paymentUpdated.details.maskedNumber).toContain('************');
          expect(paymentUpdated.details.username).toBeUndefined();
          expect(paymentUpdated.details.expiryMonth).toEqual(oldPayment.details.expiryMonth);
          expect(paymentUpdated.details.expiryYear).toEqual(oldPayment.details.expiryYear);
          expect(paymentUpdated.details.ccv).toBeUndefined();
          expect(cart.billingAddress).toBeDefined();
          return _bluebird["default"].resolve([cart, newPayment]);
        }) // 11. Update the billing address
        .then(function (_ref13) {
          var _ref14 = _slicedToArray(_ref13, 2),
              cart = _ref14[0],
              newPayment = _ref14[1];

          // For a guest user, if the payment details number is not re-injected, billing address will not be updated
          // eslint-disable-next-line max-nested-callbacks
          expect(function () {
            connector.setBillingAddress(cart, orderAddress);
          }).toThrow(); // For a guest user, to update billing address, re-inject payment details number for existing payment

          cart.payments[0].details.number = 411111111111111;
          return _bluebird["default"].all([_bluebird["default"].resolve(newPayment), connector.setBillingAddress(cart, orderAddress)]);
        }).then(function (_ref15) {
          var _ref16 = _slicedToArray(_ref15, 2),
              newPayment = _ref16[0],
              cart = _ref16[1];

          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.billingAddress).toEqual(orderAddress);
          var paymentUpdated = cart.payments[0];
          expect(paymentUpdated.id).toBeDefined();
          expect(paymentUpdated.id).not.toEqual(newPayment.id); // For a guest user, an updated payment is a new payment

          expect(paymentUpdated.amount).toBeGreaterThanOrEqual(0);
          expect(paymentUpdated.methodId).toEqual(newPayment.methodId);
          expect(paymentUpdated.details.type).toEqual(newPayment.details.type);
          expect(paymentUpdated.details.holderName).toEqual(newPayment.details.holderName);
          expect(paymentUpdated.details.number).toBeUndefined(); // card number comes back as a masked number. see next expect.

          expect(paymentUpdated.details.maskedNumber).toContain('************');
          expect(paymentUpdated.details.username).toBeUndefined();
          expect(paymentUpdated.details.expiryMonth).toEqual(newPayment.details.expiryMonth);
          expect(paymentUpdated.details.expiryYear).toEqual(newPayment.details.expiryYear);
          expect(paymentUpdated.details.ccv).toBeUndefined();
          return cart;
        }) // 12. Set shipping address
        .then(function (cart) {
          return connector.setShippingAddress(cart, orderAddress);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.shippingAddress).toMatchObject(orderAddress);
          return cart;
        }) // TODO: Check if the update is in the hybris instance. (when phone field is fixed)
        // 13. Get shipping methods
        .then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.getShippingMethods(cart)]);
        }).then(function (_ref17) {
          var _ref18 = _slicedToArray(_ref17, 2),
              cart = _ref18[0],
              shippingMethods = _ref18[1];

          expect(shippingMethods.length).toBeGreaterThanOrEqual(1);
          expect(shippingMethods[0].id).toBeDefined();
          expect(shippingMethods[0].cost).toBeGreaterThanOrEqual(0);
          return _bluebird["default"].resolve([cart, shippingMethods[0]]);
        }) // 14. Set shipping method
        .then(function (_ref19) {
          var _ref20 = _slicedToArray(_ref19, 2),
              cart = _ref20[0],
              shippingMethod = _ref20[1];

          return _bluebird["default"].all([shippingMethod, connector.setShippingMethod(cart, shippingMethod)]);
        }).then(function (_ref21) {
          var _ref22 = _slicedToArray(_ref21, 2),
              shippingMethod = _ref22[0],
              cart = _ref22[1];

          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.selectedShippingMethodId).toBeDefined();
          expect(cart.selectedShippingMethodId).toEqual(shippingMethod.id);
          return cart;
        }) // Check if the update is in the hybris instance
        .then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.getCart(cart.id)]);
        }).then(function (_ref23) {
          var _ref24 = _slicedToArray(_ref23, 2),
              cart = _ref24[0],
              backendCart = _ref24[1];

          return expect(backendCart.selectedShippingMethodId).toEqual(cart.selectedShippingMethodId);
        }) // 15. Delete cart
        .then(function () {
          return connector.deleteCart(cartId);
        }).then(function () {
          return expect(connector.getCart(cartId)).rejects.toThrow();
        }) // Delete the cart on error
        ["catch"](function (e) {
          connector.deleteCart(cartId);
          throw e;
        });
      });
    });
    var spec2 = test('for a registered user', function () {
      return (0, _testUtils.record)(spec2, function () {
        var connector = makeConnector();
        var cartId; // 1. Login as a registered user with username and password

        return connector.login(registeredUser.username, registeredUser.password).then(function (user) {
          expect(user.id).toEqual('current');
          return null;
        }) // 2. Create a cart
        .then(function () {
          return connector.createCart();
        }).then(function (cart) {
          cartId = cart.id;
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.customerInfo.id).toEqual('current');
          expect(cart.customerInfo.email).toBeUndefined();
          expect(cart.items.length).toEqual(0);
          expect(cart.selectedShippingMethodId).toBeUndefined();
          expect(cart.payments.length).toEqual(0);
          expect(cart.subtotal).toEqual(0);
          expect(cart.shipping).toBeUndefined();
          expect(cart.discounts).toEqual(0);
          expect(cart.tax).toEqual(0);
          expect(cart.total).toEqual(0);
          return cart;
        }) // Try to set customer information (email) - not allowed for registered user
        // Should result in error
        .then(function (cart) {
          expect(connector.setCustomerInformation(cart, customerInfo)).rejects.toThrow();
          return cart;
        }) // 3. Add cart item
        .then(function (cart) {
          return connector.addCartItem(cart, cartItem);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.items.length).toEqual(1);
          var cartItem = cart.items[0];
          expect(cart.items[0]).toMatchObject(cartItem);
          expect(cartItem.id).toEqual('0'); // cart item id is entry number

          expect(cartItem.baseItemPrice).toBeGreaterThan(0);
          expect(cartItem.baseLinePrice).toBeGreaterThan(0);
          expect(cartItem.itemPrice).toBeGreaterThan(0);
          expect(cartItem.linePrice).toBeGreaterThan(0);
          expect(cart.subtotal).toBeGreaterThan(0);
          expect(cart.total).toBeGreaterThan(0);
          return cart;
        }) // 4. Update cart item
        .then(function (cart) {
          return _bluebird["default"].all([connector.updateCartItem(cart, _objectSpread({}, cartItem, {
            id: cart.items[0].id,
            quantity: 2
          })), _bluebird["default"].resolve(cart.items[0])]);
        }).then(function (_ref25) {
          var _ref26 = _slicedToArray(_ref25, 2),
              cart = _ref26[0],
              oldCartItem = _ref26[1];

          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.items.length).toEqual(1);
          var cartItemUpdated = cart.items[0];
          expect(cartItemUpdated.productId).toEqual(cartItem.productId);
          expect(cartItemUpdated.quantity).toEqual(2);
          expect(cartItemUpdated.id).toEqual('0'); // cart item id is entry number

          expect(cartItemUpdated.baseItemPrice).toEqual(oldCartItem.baseItemPrice);
          expect(cartItemUpdated.baseLinePrice).toBeGreaterThan(oldCartItem.baseLinePrice);
          expect(cartItemUpdated.itemPrice).toEqual(oldCartItem.itemPrice);
          expect(cartItemUpdated.linePrice).toBeGreaterThan(oldCartItem.linePrice);
          return _bluebird["default"].resolve([cart, cartItemUpdated]);
        }) // 5. Delete cart item
        .then(function (_ref27) {
          var _ref28 = _slicedToArray(_ref27, 2),
              cart = _ref28[0],
              cartItemUpdated = _ref28[1];

          return connector.removeCartItem(cart, cartItemUpdated.id);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.items.length).toEqual(0);
          return cart;
        }) // 6. Get payment methods (need to set a valid card type for a payment)
        .then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.getPaymentMethods(cart)]);
        }) // Trying to add a payment before setting a billing address will result in an error
        .then(function (_ref29) {
          var _ref30 = _slicedToArray(_ref29, 2),
              cart = _ref30[0],
              paymentMethods = _ref30[1];

          payment.methodId = paymentMethods[0].id;
          payment.details.type = paymentMethods[0].types[0].id; // eslint-disable-next-line max-nested-callbacks

          expect(function () {
            connector.setPayment(cart, payment);
          }).toThrow();
          return cart;
        }) // 7. Set billing address - need to set billing address first before adding a payment
        .then(function (cart) {
          return connector.setBillingAddress(cart, orderAddress);
        }) // 8. Add payment
        .then(function (cart) {
          return connector.setPayment(cart, payment);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.payments.length).toEqual(1);
          var paymentUpdated = cart.payments[0];
          expect(paymentUpdated.id).toBeDefined();
          expect(paymentUpdated.amount).toEqual(cart.total); // always set payment amount to cart total.

          expect(paymentUpdated.methodId).toEqual(payment.methodId);
          expect(paymentUpdated.details.type).toEqual(payment.details.type);
          expect(paymentUpdated.details.holderName).toEqual(payment.details.holderName);
          expect(paymentUpdated.details.number).toBeUndefined(); // card number comes back as a masked number. see next expect.

          expect(paymentUpdated.details.maskedNumber).toContain('************');
          expect(paymentUpdated.details.username).toBeUndefined();
          expect(paymentUpdated.details.expiryMonth).toEqual(payment.details.expiryMonth);
          expect(paymentUpdated.details.expiryYear).toEqual(payment.details.expiryYear);
          expect(paymentUpdated.details.ccv).toBeUndefined();
          expect(cart.billingAddress.id).toBeUndefined(); // billing address id is only set when a payment is set in hybris.

          expect(cart.billingAddress).toMatchObject(orderAddress);
          return cart;
        }) // 9. Update the same payment
        .then(function (cart) {
          var paymentModified = JSON.parse(JSON.stringify(payment));
          paymentModified.details.holderName = 'Donald Duck';
          paymentModified.details.number = 411111111111111;
          return _bluebird["default"].all([_bluebird["default"].resolve(cart.payments[0]), _bluebird["default"].resolve(paymentModified), connector.setPayment(cart, paymentModified)]);
        }).then(function (_ref31) {
          var _ref32 = _slicedToArray(_ref31, 3),
              oldPayment = _ref32[0],
              newPayment = _ref32[1],
              cart = _ref32[2];

          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.payments.length).toEqual(1);
          var paymentUpdated = cart.payments[0];
          expect(paymentUpdated.id).toBeDefined();
          expect(paymentUpdated.id).toEqual(oldPayment.id); // the payment with the same id is updated

          expect(paymentUpdated.amount).toEqual(cart.total);
          expect(paymentUpdated.amount).toEqual(oldPayment.amount);
          expect(paymentUpdated.methodId).toEqual(oldPayment.methodId);
          expect(paymentUpdated.details.type).toEqual(oldPayment.details.type);
          expect(paymentUpdated.details.holderName).toEqual(newPayment.details.holderName);
          expect(paymentUpdated.details.holderName).not.toEqual(oldPayment.details.holderName);
          expect(paymentUpdated.details.number).toBeUndefined(); // card number comes back as a masked number. see next expect.

          expect(paymentUpdated.details.maskedNumber).toContain('************');
          expect(paymentUpdated.details.username).toBeUndefined();
          expect(paymentUpdated.details.expiryMonth).toEqual(oldPayment.details.expiryMonth);
          expect(paymentUpdated.details.expiryYear).toEqual(oldPayment.details.expiryYear);
          expect(paymentUpdated.details.ccv).toBeUndefined();
          expect(cart.billingAddress).toBeDefined();
          return cart;
        }) // 10. Update the billing address
        .then(function (cart) {
          var orderAddressModified = JSON.parse(JSON.stringify(orderAddress));
          orderAddressModified.lastName = 'Ron';
          return _bluebird["default"].all([_bluebird["default"].resolve(orderAddressModified), connector.setBillingAddress(cart, orderAddressModified)]);
        }).then(function (_ref33) {
          var _ref34 = _slicedToArray(_ref33, 2),
              orderAddressModified = _ref34[0],
              cart = _ref34[1];

          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.billingAddress).toEqual(orderAddressModified);
          return cart;
        }) // Check if the update is in the hybris instance.
        .then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.getCart(cart.id)]);
        }).then(function (_ref35) {
          var _ref36 = _slicedToArray(_ref35, 2),
              cart = _ref36[0],
              backendCart = _ref36[1];

          expect(cart.billingAddress.lastName).toEqual(backendCart.billingAddress.lastName);
          return cart;
        }) // 11. Set shipping address
        .then(function (cart) {
          return connector.setShippingAddress(cart, orderAddress);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.shippingAddress).toMatchObject(orderAddress);
          return cart;
        }) // TODO: Check if the update is in the hybris instance. (when phone field is fixed)
        // 12. Get shipping methods
        .then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.getShippingMethods(cart)]);
        }).then(function (_ref37) {
          var _ref38 = _slicedToArray(_ref37, 2),
              cart = _ref38[0],
              shippingMethods = _ref38[1];

          expect(shippingMethods.length).toBeGreaterThanOrEqual(1);
          return _bluebird["default"].resolve([cart, shippingMethods[0]]);
        }) // 13. Set shipping method
        .then(function (_ref39) {
          var _ref40 = _slicedToArray(_ref39, 2),
              cart = _ref40[0],
              shippingMethod = _ref40[1];

          return _bluebird["default"].all([shippingMethod, connector.setShippingMethod(cart, shippingMethod)]);
        }).then(function (_ref41) {
          var _ref42 = _slicedToArray(_ref41, 2),
              shippingMethod = _ref42[0],
              cart = _ref42[1];

          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.selectedShippingMethodId).toBeDefined();
          expect(cart.selectedShippingMethodId).toEqual(shippingMethod.id);
          return cart;
        }) // Check if the update is in the hybris instance
        .then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.getCart(cart.id)]);
        }).then(function (_ref43) {
          var _ref44 = _slicedToArray(_ref43, 2),
              cart = _ref44[0],
              backendCart = _ref44[1];

          return expect(cart.selectedShippingMethodId).toEqual(backendCart.selectedShippingMethodId);
        }) // 14. Delete cart
        .then(function () {
          return connector.deleteCart(cartId);
        }).then(function () {
          return expect(connector.getCart(cartId)).rejects.toThrow();
        }) // Delete the cart on error
        ["catch"](function (e) {
          connector.deleteCart(cartId);
          throw e;
        });
      });
    });
  });
  describe('Cart Migration Test', function () {
    var spec1 = test('migrate guest cart to registered user cart', function () {
      return (0, _testUtils.record)(spec1, function () {
        var connector = makeConnector();
        var cartToMigrateId;
        var newCartId; // 1. Log in as guest user

        return connector.login().then(function (user) {
          return expect(user.id).toEqual('anonymous');
        }) // 2. Create a cart for guest user
        .then(function () {
          return connector.createCart();
        }).then(function (cart) {
          cartToMigrateId = cart.id;
          expect(cart.customerInfo.id).toEqual('anonymous');
          return cart;
        }) // 3. Add cart item to guest user cart
        .then(function (cart) {
          return connector.addCartItem(cart, cartItem);
        }).then(function (cart) {
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.items.length).toEqual(1);
          expect(cart.items[0]).toMatchObject(cartItem);
          expect(cart.items[0].id).toEqual('0'); // cart item id is entry number

          expect(cart.items[0].baseItemPrice).toBeGreaterThan(0);
          expect(cart.items[0].baseLinePrice).toBeGreaterThan(0);
          expect(cart.items[0].itemPrice).toBeGreaterThan(0);
          expect(cart.items[0].linePrice).toBeGreaterThan(0);
          expect(cart.subtotal).toBeGreaterThan(0);
          expect(cart.total).toBeGreaterThan(0);
          return _bluebird["default"].resolve(cart);
        }) // 4. Logout
        .then(function (cartToMigrate) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cartToMigrate), connector.logout()]);
        }) // 5. Login as a registered user with username and password
        .then(function (_ref45) {
          var _ref46 = _slicedToArray(_ref45, 1),
              cartToMigrate = _ref46[0];

          return _bluebird["default"].all([_bluebird["default"].resolve(cartToMigrate), connector.login(registeredUser.username, registeredUser.password)]);
        }).then(function (_ref47) {
          var _ref48 = _slicedToArray(_ref47, 2),
              cartToMigrate = _ref48[0],
              user = _ref48[1];

          expect(user.id).toEqual('current');
          return _bluebird["default"].resolve(cartToMigrate);
        }) // 2. Create a cart for registered user by migrating over the guest user cart
        .then(function (cartToMigrate) {
          return connector.createCart(cartToMigrate);
        }) // Delete the guest user cart on error
        ["catch"](function (e) {
          connector.deleteCart(cartToMigrateId);
          throw e;
        }).then(function (cart) {
          newCartId = cart.id;
          expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
          expect(cart.customerInfo.id).toEqual('current');
          expect(cart.customerInfo.email).toBeUndefined();
          expect(cart.items.length).toEqual(1);
          expect(cart.items[0]).toMatchObject(cartItem);
          expect(cart.items[0].id).toEqual('0'); // cart item id is entry number (0-based index position in list)

          expect(cart.items[0].baseItemPrice).toBeGreaterThan(0);
          expect(cart.items[0].baseLinePrice).toBeGreaterThan(0);
          expect(cart.items[0].itemPrice).toBeGreaterThan(0);
          expect(cart.items[0].linePrice).toBeGreaterThan(0);
          expect(cart.selectedShippingMethodId).toBeUndefined();
          expect(cart.payments.length).toEqual(0);
          expect(cart.subtotal).toBeGreaterThan(0);
          expect(cart.total).toBeGreaterThan(0);
          return null;
        }) // 3. Delete cart for registered user (old cart already deleted upon merge through hybris api)
        .then(function () {
          return connector.deleteCart(newCartId);
        }).then(function () {
          return expect(connector.getCart(newCartId)).rejects.toThrow();
        }) // Delete the cart on error
        ["catch"](function (e) {
          connector.deleteCart(newCartId);
          throw e;
        });
      });
    });
  });
  describe('Orders flow', function () {
    var spec2 = test('Registered User', function () {
      return (0, _testUtils.record)(spec2, function () {
        var connector = makeConnector();
        var cartId; // 1. Log in as registered user

        return connector.login(registeredUser.username, registeredUser.password) // 2. Create and populate cart
        .then(function () {
          return connector.createCart();
        }).then(function (cart) {
          cartId = cart.id;
          return connector.addCartItem(cart, cartItem);
        }).then(function (cart) {
          return connector.setShippingAddress(cart, orderAddress);
        }).then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.getShippingMethods(cart)]);
        }).then(function (_ref49) {
          var _ref50 = _slicedToArray(_ref49, 2),
              cart = _ref50[0],
              shippingMethods = _ref50[1];

          return connector.setShippingMethod(cart, shippingMethods[0]);
        }).then(function (cart) {
          return connector.setBillingAddress(cart, orderAddress);
        }).then(function (cart) {
          return connector.setPayment(cart, payment);
        }).then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.createOrder(cart)]);
        }) // Delete the cart on error
        ["catch"](function (e) {
          connector.deleteCart(cartId);
          throw e;
        }).then(function (_ref51) {
          var _ref52 = _slicedToArray(_ref51, 2),
              cart = _ref52[0],
              order = _ref52[1];

          expect((0, _testUtils.propTypeErrors)(types.Order, order)).toBeFalsy();
          expect(order.id).toBeDefined();
          expect(order.creationDate).toBeDefined();
          expect(order.status).toBeDefined();
          expect(order.customerInfo.id).toEqual(cart.customerInfo.id);
          expect(order.customerInfo.email).toEqual(registeredUser.username);
          expect(order.items.length).toEqual(1);
          expect(order.items[0]).toMatchObject(cartItem); // hybris 6.4 does not return phone field, update to 6.5 if phone field needed

          var orderAddressReturned = JSON.parse(JSON.stringify(orderAddress));
          orderAddressReturned.phone = undefined;
          expect(order.shippingAddress).toMatchObject(orderAddressReturned);
          expect(order.billingAddress).toMatchObject(orderAddressReturned);
          expect(order.selectedShippingMethodId).toEqual(cart.selectedShippingMethodId);
          expect(order.items.length).toEqual(1);
          expect(order.payments[0].details.number).toBeUndefined(); // card number comes back as a masked number. see next expect.

          expect(order.payments[0].details.maskedNumber).toContain('************');
          var paymentReturned = JSON.parse(JSON.stringify(payment));
          paymentReturned.details.number = undefined;
          expect(order.payments[0]).toMatchObject(paymentReturned);
          expect(order.subtotal).toEqual(cart.subtotal); // shipping, discounts, tax may be updated after order is created

          expect(order.shipping).toBeGreaterThanOrEqual(0);
          expect(order.discounts).toBeGreaterThanOrEqual(cart.discounts);
          expect(order.tax).toBeGreaterThanOrEqual(cart.tax);
          expect(order.total).toBeGreaterThanOrEqual(cart.total);
          return _bluebird["default"].resolve(order);
        }).then(function (order) {
          return _bluebird["default"].all([connector.getOrders([order.id]), _bluebird["default"].resolve(order)]);
        }).then(function (_ref53) {
          var _ref54 = _slicedToArray(_ref53, 2),
              orders = _ref54[0],
              order = _ref54[1];

          expect(orders.count).toEqual(1);
          expect(orders.total).toEqual(1); // BUG: does not save billing address region when sending billing address through a POST cart payment detail.
          // Since getOrder/s does not take in a cart parameter, we cannot persist this field to the returned order.

          orders.data[0].billingAddress.stateCode = order.billingAddress.stateCode;
          expect(orders.data[0]).toMatchObject(order);
          expect((0, _testUtils.propTypeErrors)(types.OrderList, orders)).toBeFalsy();
        });
      });
    });
    var spec3 = test('Guest User', function () {
      return (0, _testUtils.record)(spec3, function () {
        var connector = makeConnector();
        var cartId; // 1. Log in as guest user

        return connector.login() // 2. Create a cart for guest user
        .then(function () {
          return connector.createCart();
        }).then(function (cart) {
          cartId = cart.id;
          return connector.addCartItem(cart, cartItem);
        }).then(function (cart) {
          return connector.setCustomerInformation(cart, customerInfo);
        }).then(function (cart) {
          return connector.setShippingAddress(cart, orderAddress);
        }).then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.getShippingMethods(cart)]);
        }).then(function (_ref55) {
          var _ref56 = _slicedToArray(_ref55, 2),
              cart = _ref56[0],
              shippingMethods = _ref56[1];

          return connector.setShippingMethod(cart, shippingMethods[0]);
        }).then(function (cart) {
          return connector.setBillingAddress(cart, orderAddress);
        }).then(function (cart) {
          return connector.setPayment(cart, payment);
        }).then(function (cart) {
          return _bluebird["default"].all([_bluebird["default"].resolve(cart), connector.createOrder(cart)]);
        }) // Delete the cart on error
        ["catch"](function (e) {
          connector.deleteCart(cartId);
          throw e;
        }).then(function (_ref57) {
          var _ref58 = _slicedToArray(_ref57, 2),
              cart = _ref58[0],
              order = _ref58[1];

          expect((0, _testUtils.propTypeErrors)(types.Order, order)).toBeFalsy();
          expect(order.id).toBeDefined();
          expect(order.creationDate).toBeDefined();
          expect(order.status).toBeDefined();
          expect(order.customerInfo).toMatchObject(cart.customerInfo);
          expect(order.items.length).toEqual(1);
          expect(order.items[0]).toMatchObject(cartItem); // hybris 6.4 does not return phone field, update to 6.5 if phone field needed

          var orderAddressReturned = JSON.parse(JSON.stringify(orderAddress));
          orderAddressReturned.phone = undefined;
          expect(order.shippingAddress).toMatchObject(orderAddressReturned);
          expect(order.billingAddress).toMatchObject(orderAddressReturned);
          expect(order.selectedShippingMethodId).toEqual(cart.selectedShippingMethodId);
          expect(order.items.length).toEqual(1);
          expect(order.payments[0].details.number).toBeUndefined(); // card number comes back as a masked number. see next expect.

          expect(order.payments[0].details.maskedNumber).toContain('************');
          var paymentReturned = JSON.parse(JSON.stringify(payment));
          paymentReturned.details.number = undefined;
          expect(order.payments[0]).toMatchObject(paymentReturned);
          expect(order.subtotal).toEqual(cart.subtotal); // shipping, discounts, tax may be updated after order is created

          expect(order.shipping).toBeGreaterThanOrEqual(0);
          expect(order.discounts).toBeGreaterThanOrEqual(cart.discounts);
          expect(order.tax).toBeGreaterThanOrEqual(cart.tax);
          expect(order.total).toBeGreaterThanOrEqual(cart.total);
          return _bluebird["default"].resolve(order);
        }).then(function (order) {
          return _bluebird["default"].all([connector.getOrders([order.id]), _bluebird["default"].resolve(order)]);
        }).then(function (_ref59) {
          var _ref60 = _slicedToArray(_ref59, 2),
              orders = _ref60[0],
              order = _ref60[1];

          expect(orders.count).toEqual(1);
          expect(orders.total).toEqual(1); // BUG: does not save billing address region when sending billing address through a POST cart payment detail.
          // Since getOrder/s does not take in a cart parameter, we cannot persist this field to the returned order.

          orders.data[0].billingAddress.stateCode = order.billingAddress.stateCode;
          expect(orders.data[0]).toMatchObject(order);
          expect((0, _testUtils.propTypeErrors)(types.OrderList, orders)).toBeFalsy();
        });
      });
    });
  });
  describe('Coupon support', function () {
    var coupon = 'integration-test-do-not-edit-5';

    var testBody = function testBody(connector) {
      return connector.createCart().then(function (cart) {
        return connector.addCartItem(cart, cartItem);
      }).then(function (cart) {
        return connector.addCouponEntry(cart, coupon);
      }).then(function (cart) {
        expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
        expect(cart.items.length).toEqual(1);
        expect(cart.couponEntries[0].code).toEqual(coupon);
        expect(cart.couponEntries[0].id).toBeDefined();
        expect(cart.discounts).toBeLessThan(0);
        return cart;
      }).then(function (cart) {
        return connector.removeCouponEntry(cart, cart.couponEntries[0].id);
      }).then(function (cart) {
        expect((0, _testUtils.propTypeErrors)(types.Cart, cart)).toBeFalsy();
        expect(cart.items.length).toEqual(1);
        expect(cart.couponEntries).toEqual([]);
        expect(cart.discounts).toBe(0);
      });
    };

    var spec1 = test('Should allow a registered user to add/remove a CouponEntry to/from their cart', function () {
      return (0, _testUtils.record)(spec1, function () {
        var userCreateFixture = userFixture('coupons-2');
        var connector = makeConnector();
        return connector.login().then(function () {
          return connector.registerCustomer(userCreateFixture);
        }).then(function () {
          return testBody(connector);
        });
      });
    });
    var spec2 = test('Should allow a guest user to add/remove a CouponEntry to/from their cart', function () {
      return (0, _testUtils.record)(spec2, function () {
        var connector = makeConnector();
        return connector.login().then(function () {
          return testBody(connector);
        });
      });
    });
    var spec3 = test('Should throw an exception if a cart object isn`t passed in when removing coupon', function () {
      return (0, _testUtils.record)(spec3, function () {
        var connector = makeConnector();
        return connector.login().then(function () {
          expect(function () {
            connector.removeCouponEntry(undefined, coupon);
          }).toThrowError("Parameter 'cart' is required");
        });
      });
    });
    var spec4 = test('Should throw an exception if a cart object isn`t passed in when removing coupon', function () {
      return (0, _testUtils.record)(spec4, function () {
        var dummyCart = {};
        var connector = makeConnector();
        return connector.login().then(function () {
          expect(function () {
            connector.removeCouponEntry(dummyCart, undefined);
          }).toThrowError("Parameter 'couponEntryId' is required");
        });
      });
    });
  });
});