"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

require("core-js/modules/es.object.to-string.js");

require("core-js/modules/es.reflect.construct.js");

require("core-js/modules/es.object.create.js");

require("core-js/modules/es.object.define-property.js");

require("core-js/modules/es.object.keys.js");

require("core-js/modules/es.array.index-of.js");

require("core-js/modules/es.symbol.js");

require("core-js/modules/es.array.filter.js");

require("core-js/modules/es.object.get-own-property-descriptor.js");

require("core-js/modules/es.array.for-each.js");

require("core-js/modules/web.dom-collections.for-each.js");

require("core-js/modules/es.object.get-own-property-descriptors.js");

require("core-js/modules/es.object.define-properties.js");

require("core-js/modules/es.promise.js");

require("core-js/modules/es.symbol.description.js");

require("core-js/modules/es.symbol.iterator.js");

require("core-js/modules/es.array.iterator.js");

require("core-js/modules/es.string.iterator.js");

require("core-js/modules/web.dom-collections.iterator.js");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PaymentSource = void 0;

require("regenerator-runtime/runtime.js");

require("core-js/modules/es.array.map.js");

require("core-js/modules/es.object.set-prototype-of.js");

require("core-js/modules/es.object.get-prototype-of.js");

var _common = require("../../common");

var _excluded = ["expMonth", "expYear", "isDefault"],
    _excluded2 = ["exp_month", "exp_year", "is_default"];

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(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; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var PaymentSource = /*#__PURE__*/function (_Resource) {
  _inherits(PaymentSource, _Resource);

  var _super = _createSuper(PaymentSource);

  function PaymentSource(
  /**
   * Payment methods store in Stripe
   */
  stripe,
  /**
   * Payment methods store in PayPal
   */
  paypal,
  /**
   * The chargebee data to manage the payment method
   */
  isChargebee) {
    var _this;

    _classCallCheck(this, PaymentSource);

    _this = _super.call(this);
    _this.stripe = stripe;
    _this.paypal = paypal;
    _this.isChargebee = isChargebee;
    return _this;
  }
  /**
   * The name of the PaymentMethod resource on the API server.
   */


  _createClass(PaymentSource, [{
    key: "serializeAPI",
    value:
    /**
     * Convert the payment source into a JSON serializable object for the API server.
     */
    function serializeAPI() {
      return {
        stripe: this.serializeStripeAPI(),
        paypal: this.serializePayPalAPI(),
        is_chargebee: this.isChargebee
      };
    }
    /**
     * Deserialize the data from the API server.
     *
     * @param data The payment source data from the API server.
     */

  }, {
    key: "deserializeAPI",
    value: function deserializeAPI(data) {
      this.stripe = PaymentSource.deserializeStripeAPI(data.stripe);
      this.paypal = PaymentSource.deserializePayPalAPI(data.paypal);
      this.isChargebee = data.is_chargebee;
    }
    /**
     * Serialize the payment source into a format for storing in the Redux store.
     */

  }, {
    key: "serializeRedux",
    value: function serializeRedux() {
      return {
        stripe: this.stripe,
        paypal: this.paypal,
        isChargebee: this.isChargebee
      };
    }
    /**
     * Create a payment source from the API server data.
     *
     * @param data Data from the api server.
     *
     * @returns The payment source object.
     */

  }, {
    key: "serializeStripeAPI",
    value:
    /**
     * Convert the Stripe payment source into a JSON serializable object for the API server.
     * @private
     */
    function serializeStripeAPI() {
      return this.stripe.map(function (_ref) {
        var expMonth = _ref.expMonth,
            expYear = _ref.expYear,
            isDefault = _ref.isDefault,
            commonFields = _objectWithoutProperties(_ref, _excluded);

        return _objectSpread(_objectSpread({}, commonFields), {}, {
          exp_month: expMonth,
          exp_year: expYear,
          is_default: isDefault
        });
      });
    }
    /**
     * Convert the PayPal payment source into a JSON serializable object for the API server.
     * @private
     */

  }, {
    key: "serializePayPalAPI",
    value: function serializePayPalAPI() {
      return this.paypal.map(function (_ref2) {
        var id = _ref2.id,
            email = _ref2.email,
            is_default = _ref2.isDefault;
        return {
          id: id,
          email: email,
          is_default: is_default
        };
      });
    }
    /**
     * Deserialize the Stripe payment source data from the API server.
     * @param data The Stripe payment source data from the API server.
     * @private
     */

  }], [{
    key: "resourceName",
    get: function get() {
      return "user/payment-method";
    }
    /**
     * The name of the service containing the payment source resource.
     */

  }, {
    key: "serviceName",
    get: function get() {
      return "payments";
    }
  }, {
    key: "apiFactory",
    value: function apiFactory(data) {
      return new PaymentSource(this.deserializeStripeAPI(data.stripe), this.deserializePayPalAPI(data.paypal), data.is_chargebee);
    }
    /**
     * Create a payment source from the Redux store data.
     *
     * @param data Data from the api server.
     *
     * @returns The payment source object.
     */

  }, {
    key: "reduxFactory",
    value: function reduxFactory(data) {
      return new PaymentSource(data.stripe, data.paypal, data.isChargebee);
    }
  }, {
    key: "deserializeStripeAPI",
    value: function deserializeStripeAPI(data) {
      return data.map(function (_ref3) {
        var exp_month = _ref3.exp_month,
            exp_year = _ref3.exp_year,
            is_default = _ref3.is_default,
            commonFields = _objectWithoutProperties(_ref3, _excluded2);

        return _objectSpread(_objectSpread({}, commonFields), {}, {
          expMonth: exp_month,
          expYear: exp_year,
          isDefault: is_default
        });
      });
    }
    /**
     * Deserialize the PayPal payment source data from the API server.
     * @param data The PayPal payment source data from the API server.
     * @private
     */

  }, {
    key: "deserializePayPalAPI",
    value: function deserializePayPalAPI(data) {
      return data.map(function (_ref4) {
        var id = _ref4.id,
            email = _ref4.email,
            isDefault = _ref4.is_default;
        return {
          id: id,
          email: email,
          isDefault: isDefault
        };
      });
    }
    /**
     * Method that creates the Stripe setup intent to start
     * the process to save the user's credit card.
     *
     * @returns The stripe client secret as { client_secret: "clientSecret" }
     */

  }, {
    key: "createStripeSetupIntent",
    value: function () {
      var _createStripeSetupIntent = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var server, response;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                server = new _common.APIServer();
                _context.next = 3;
                return server.post("service/".concat(this.serviceName, "/") + "stripe/setup-intent/");

              case 3:
                response = _context.sent;
                return _context.abrupt("return", response.data);

              case 5:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function createStripeSetupIntent() {
        return _createStripeSetupIntent.apply(this, arguments);
      }

      return createStripeSetupIntent;
    }()
    /**
     * Method that creates a payment intent in Stripe to start
     * the process of Afterpay payment.
     *
     * @returns The afterpay redirect URL as { redirect_url: "redirectUrl" }
     */

  }, {
    key: "createAfterpayPaymentIntent",
    value: function () {
      var _createAfterpayPaymentIntent = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(afterpayPaymentIntent) {
        var server, createPaymentIntentPath, payload, response;
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                server = new _common.APIServer();
                createPaymentIntentPath = "service/".concat(this.serviceName, "/afterpay/payment-intent/");
                payload = this.serializeAfterpayPaymentIntent(afterpayPaymentIntent);
                _context2.next = 5;
                return server.post(createPaymentIntentPath, undefined, payload);

              case 5:
                response = _context2.sent;
                return _context2.abrupt("return", response.data);

              case 7:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function createAfterpayPaymentIntent(_x) {
        return _createAfterpayPaymentIntent.apply(this, arguments);
      }

      return createAfterpayPaymentIntent;
    }()
    /**
     * Creates a PayPal token in an approval flow to vault (save) the
     * user's PayPal account and use it for future payments
     *
     * @returns url to take the user through a PayPal hosted authorization flow
     */

  }, {
    key: "createPayPalToken",
    value: function () {
      var _createPayPalToken = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
        var server, response;
        return regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                server = new _common.APIServer();
                _context3.next = 3;
                return server.post("service/".concat(this.serviceName, "/") + "paypal/create-payment-token/");

              case 3:
                response = _context3.sent;

                if (!response.error) {
                  _context3.next = 6;
                  break;
                }

                throw new _common.APIResponseError("Error creating PayPal Token", this.handleError(response));

              case 6:
                return _context3.abrupt("return", response.data);

              case 7:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function createPayPalToken() {
        return _createPayPalToken.apply(this, arguments);
      }

      return createPayPalToken;
    }()
    /**
     * Confirms a PayPal approval token after the user completes the approval flow
     * to convert it into a payment token
     */

  }, {
    key: "confirmPayPalToken",
    value: function () {
      var _confirmPayPalToken = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(approvalTokenId) {
        var server, confirmTokenPath, response;
        return regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                server = new _common.APIServer();
                confirmTokenPath = "paypal/".concat(approvalTokenId, "/confirm-payment-token/");
                _context4.next = 4;
                return server.post("service/".concat(this.serviceName, "/") + confirmTokenPath);

              case 4:
                response = _context4.sent;

                if (!response.error) {
                  _context4.next = 7;
                  break;
                }

                throw new _common.APIResponseError("Error confirming PayPal Token", this.handleError(response));

              case 7:
                return _context4.abrupt("return", response.data);

              case 8:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function confirmPayPalToken(_x2) {
        return _confirmPayPalToken.apply(this, arguments);
      }

      return confirmPayPalToken;
    }()
    /**
     * Method to set a new default payment method for the user
     * @param paymentMethod The new default payment method
     */

  }, {
    key: "updateDefaultPaymentMethod",
    value: function () {
      var _updateDefaultPaymentMethod = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(paymentMethod) {
        var server, updateDefaultPath, payload, response;
        return regeneratorRuntime.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                server = new _common.APIServer();
                updateDefaultPath = "service/".concat(this.serviceName, "/user/default-payment-method");
                payload = this.serializeMinimalPaymentMethod(paymentMethod);
                _context5.next = 5;
                return server.put(updateDefaultPath, "", undefined, payload);

              case 5:
                response = _context5.sent;

                if (!response.error) {
                  _context5.next = 8;
                  break;
                }

                throw new _common.APIResponseError("Error updating default payment method", response);

              case 8:
                return _context5.abrupt("return", this.deserializeMinimalPaymentMethod(response.data));

              case 9:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function updateDefaultPaymentMethod(_x3) {
        return _updateDefaultPaymentMethod.apply(this, arguments);
      }

      return updateDefaultPaymentMethod;
    }()
    /**
     * Method to delete a payment method from the user's accounts
     * @param paymentMethod The payment method to delete
     *
     * @returns 204 No content
     */

  }, {
    key: "deletePaymentMethod",
    value: function () {
      var _deletePaymentMethod = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(paymentMethod) {
        var server, payload, response;
        return regeneratorRuntime.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                server = new _common.APIServer();
                payload = this.serializeMinimalPaymentMethod(paymentMethod);
                _context6.next = 4;
                return server["delete"](this.path, "", payload);

              case 4:
                response = _context6.sent;

                if (!response.error) {
                  _context6.next = 7;
                  break;
                }

                throw new _common.APIResponseError("Error deleting payment method", response);

              case 7:
                return _context6.abrupt("return", response.data);

              case 8:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));

      function deletePaymentMethod(_x4) {
        return _deletePaymentMethod.apply(this, arguments);
      }

      return deletePaymentMethod;
    }()
    /**
     * Serialize the payment method from the redux store to the API for the server
     * @param storePaymentMethod Payment method from the redux store
     * @private
     */

  }, {
    key: "serializeMinimalPaymentMethod",
    value: function serializeMinimalPaymentMethod(storePaymentMethod) {
      return {
        id: storePaymentMethod.id,
        payment_gateway: storePaymentMethod.paymentGateway
      };
    }
    /**
     * Deserialize the payment method from the server to the redux store
     * @param storePaymentMethod Payment method from the redux store
     * @private
     */

  }, {
    key: "deserializeMinimalPaymentMethod",
    value: function deserializeMinimalPaymentMethod(storePaymentMethod) {
      return {
        id: storePaymentMethod.id,
        paymentGateway: storePaymentMethod.payment_gateway
      };
    }
    /**
     * Serialize the Afterpay shipping details from the redux store to the API
     * for the server
     * @param afterpayShippingDetails Afterpay shipping details from the store
     * @private
     */

  }, {
    key: "serializeAfterpayShippingDetails",
    value: function serializeAfterpayShippingDetails(afterpayShippingDetails) {
      return _objectSpread({
        postal_code: afterpayShippingDetails.postalCode
      }, afterpayShippingDetails);
    }
    /**
     * Serialize the Afterpay payment intent payload from the redux store to the API
     * @param afterpayPaymentIntent Afterpay payment intent from the store
     * @private
     */

  }, {
    key: "serializeAfterpayPaymentIntent",
    value: function serializeAfterpayPaymentIntent(afterpayPaymentIntent) {
      return {
        checkout: afterpayPaymentIntent.checkout,
        billing_address: this.serializeAfterpayShippingDetails(afterpayPaymentIntent.billingAddress),
        shipping_address: this.serializeAfterpayShippingDetails(afterpayPaymentIntent.shippingAddress)
      };
    }
  }]);

  return PaymentSource;
}(_common.Resource);

exports.PaymentSource = PaymentSource;
//# sourceMappingURL=data:application/json;charset=utf-8;base64, 