UNPKG

medusa-payment-klarna

Version:

Klarna Payment provider for Medusa Commerce

726 lines (720 loc) 56.5 kB
"use strict"; function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _axios = _interopRequireDefault(require("axios")); var _lodash = _interopRequireDefault(require("lodash")); var _medusaInterfaces = require("medusa-interfaces"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } 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); } 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && _instanceof(outerFn.prototype, Generator) ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } 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 _classCallCheck(instance, Constructor) { if (!_instanceof(instance, 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, _toPropertyKey(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 ? Object.setPrototypeOf.bind() : 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.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var KlarnaProviderService = /*#__PURE__*/function (_PaymentService) { _inherits(KlarnaProviderService, _PaymentService); var _super = _createSuper(KlarnaProviderService); function KlarnaProviderService(_ref, options) { var _options$language; var _this; var logger = _ref.logger, shippingProfileService = _ref.shippingProfileService; _classCallCheck(this, KlarnaProviderService); _this = _super.call(this); /** * Required Klarna options: * { * backend_url: "", * url: "", * user: "", * password: "", * merchant_urls: { * terms: ``, * checkout: ``, * confirmation: ``, * } * } */ _this.options_ = options; _this.logger_ = logger; /** @private @const {Klarna} */ _this.klarna_ = _axios["default"].create({ baseURL: options.url, auth: { username: options.user, password: options.password } }); _this.klarnaOrderUrl_ = "/checkout/v3/orders"; _this.klarnaOrderManagementUrl_ = "/ordermanagement/v1/orders"; _this.backendUrl_ = options.backend_url; _this.locale_ = (_options$language = options.language) !== null && _options$language !== void 0 ? _options$language : 'en-US'; /** @private @const {ShippingProfileService} */ _this.shippingProfileService_ = shippingProfileService; return _this; } _createClass(KlarnaProviderService, [{ key: "lineItemsToOrderLines_", value: function () { var _lineItemsToOrderLines_ = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(cart) { var _cart$shipping_method, _cart$items; var order_lines, _iterator, _step, item, quantity, _tax, name, total, tax, taxRate, _iterator2, _step2, method, methodTaxRate; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: order_lines = []; _iterator = _createForOfIteratorHelper((_cart$items = cart.items) !== null && _cart$items !== void 0 ? _cart$items : []); try { for (_iterator.s(); !(_step = _iterator.n()).done;) { item = _step.value; // Withdraw discount from the total item amount quantity = item.quantity; _tax = item.tax_lines.reduce(function (acc, next) { return acc + next.rate; }, 0) / 100; order_lines.push({ name: item.title, tax_rate: _tax * 10000, quantity: quantity, unit_price: Math.round(item.original_total / item.quantity), total_amount: item.total, total_tax_amount: item.tax_total, total_discount_amount: item.original_total - item.total }); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if ((_cart$shipping_method = cart.shipping_methods) !== null && _cart$shipping_method !== void 0 && _cart$shipping_method.length) { name = []; total = 0; tax = 0; taxRate = 0; if (cart.shipping_total > 0) { _iterator2 = _createForOfIteratorHelper(cart.shipping_methods); try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { method = _step2.value; methodTaxRate = method.tax_lines.reduce(function (acc, next) { return acc + next.rate; }, 0) / 100; name.push(method.shipping_option.name); total += method.total; taxRate += method.price / cart.shipping_total * methodTaxRate; tax += method.tax_total; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } order_lines.push({ name: (name === null || name === void 0 ? void 0 : name.join(" + ")) || "Shipping fee", quantity: 1, type: "shipping_fee", unit_price: total, tax_rate: taxRate * 10000, total_amount: total, total_tax_amount: tax }); } return _context.abrupt("return", order_lines); case 5: case "end": return _context.stop(); } }, _callee); })); function lineItemsToOrderLines_(_x) { return _lineItemsToOrderLines_.apply(this, arguments); } return lineItemsToOrderLines_; }() }, { key: "cartToKlarnaOrder", value: function () { var _cartToKlarnaOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(cart) { var _cart$resource_id, _ref2, _region$currency_code, _region$currency_code2; var order, region, gift_card_total, tax_total, total, taxRate, hasCountry, shippingOptions, method, _taxRate, partitioned, f, cartesian, methods, combinations, _taxRate2; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: order = { // Cart id is stored, such that we can use it for hooks merchant_data: (_cart$resource_id = cart.resource_id) !== null && _cart$resource_id !== void 0 ? _cart$resource_id : cart.id, locale: this.locale_ }; region = cart.region, gift_card_total = cart.gift_card_total, tax_total = cart.tax_total, total = cart.total; _context2.next = 4; return this.lineItemsToOrderLines_(cart); case 4: order.order_lines = _context2.sent; if (gift_card_total) { taxRate = cart.gift_card_tax_total / cart.gift_card_total; order.order_lines.push({ name: "Gift Card", quantity: 1, type: "gift_card", unit_price: -1 * (cart.gift_card_total + cart.gift_card_tax_total), tax_rate: Math.round(taxRate * 10000), total_amount: -1 * (cart.gift_card_total + cart.gift_card_tax_total), total_tax_amount: -1 * cart.gift_card_tax_total }); } if (!_lodash["default"].isEmpty(cart.billing_address)) { order.billing_address = { email: cart.email, street_address: cart.billing_address.address_1, street_address2: cart.billing_address.address_2, postal_code: cart.billing_address.postal_code, city: cart.billing_address.city, country: cart.billing_address.country_code }; } hasCountry = !_lodash["default"].isEmpty(cart.shipping_address) && cart.shipping_address.country_code; if (hasCountry) { order.purchase_country = cart.shipping_address.country_code.toUpperCase(); } else { // Defaults to Sweden order.purchase_country = "SE"; } order.order_amount = total; order.order_tax_amount = (_ref2 = tax_total - cart.gift_card_tax_total) !== null && _ref2 !== void 0 ? _ref2 : 0; order.purchase_currency = (_region$currency_code = region === null || region === void 0 ? void 0 : (_region$currency_code2 = region.currency_code) === null || _region$currency_code2 === void 0 ? void 0 : _region$currency_code2.toUpperCase()) !== null && _region$currency_code !== void 0 ? _region$currency_code : "SE"; order.merchant_urls = { terms: this.options_.merchant_urls.terms, checkout: this.options_.merchant_urls.checkout, confirmation: this.options_.merchant_urls.confirmation, push: "".concat(this.backendUrl_, "/klarna/push?klarna_order_id={checkout.order.id}"), shipping_option_update: "".concat(this.backendUrl_, "/klarna/shipping"), address_update: "".concat(this.backendUrl_, "/klarna/address") }; if (!(cart.shipping_address && cart.shipping_address.first_name)) { _context2.next = 26; break; } _context2.next = 16; return this.shippingProfileService_.fetchCartOptions(cart); case 16: shippingOptions = _context2.sent; shippingOptions = shippingOptions.filter(function (so) { var _so$data; return !((_so$data = so.data) !== null && _so$data !== void 0 && _so$data.require_drop_point); }); // If the cart does not have shipping methods yet, preselect one from // shipping_options and set the selected shipping method if (cart.shipping_methods.length) { method = cart.shipping_methods[0]; _taxRate = method.tax_total / (method.total - method.tax_total); order.selected_shipping_option = { id: method.shipping_option.id, name: method.shipping_option.name, price: method.total, tax_amount: method.tax_total, tax_rate: _taxRate * 10000 }; } partitioned = shippingOptions.reduce(function (acc, next) { if (acc[next.profile_id]) { acc[next.profile_id] = [].concat(_toConsumableArray(acc[next.profile_id]), [next]); } else { acc[next.profile_id] = [next]; } return acc; }, {}); // Helper function that calculates the cartesian product of multiple arrays // Don't touch :D // From: https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript f = function f(a, b) { var _ref3; return (_ref3 = []).concat.apply(_ref3, _toConsumableArray(a.map(function (d) { return b.map(function (e) { return [].concat(d, e); }); }))); }; cartesian = function cartesian(a, b) { for (var _len = arguments.length, c = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { c[_key - 2] = arguments[_key]; } return b ? cartesian.apply(void 0, [f(a, b)].concat(c)) : a; }; methods = Object.keys(partitioned).map(function (k) { return partitioned[k]; }); combinations = cartesian.apply(void 0, _toConsumableArray(methods)); _taxRate2 = region.tax_rate / 100; // Use the cartesian product of shipping methods to generate correct // format for the Klarna Widget order.shipping_options = combinations.map(function (combination) { combination = Array.isArray(combination) ? combination : [combination]; var details = combination.reduce(function (acc, next) { acc.id = [].concat(_toConsumableArray(acc.id), [next.id]); acc.name = [].concat(_toConsumableArray(acc.name), [next.name]); acc.price += next.amount; return acc; }, { id: [], name: [], price: 0 }); return { id: details.id.join("."), name: details.name.join(" + "), price: details.price * (1 + _taxRate2), tax_amount: details.price * _taxRate2, tax_rate: _taxRate2 * 10000 }; }); case 26: return _context2.abrupt("return", order); case 27: case "end": return _context2.stop(); } }, _callee2, this); })); function cartToKlarnaOrder(_x2) { return _cartToKlarnaOrder.apply(this, arguments); } return cartToKlarnaOrder; }() }, { key: "validateKlarnaOrderUrls", value: function validateKlarnaOrderUrls(property) { var _this2 = this; var required = ["terms", "checkout", "confirmation"]; var isMissing = required.some(function (prop) { var _this2$options_$prope; return !((_this2$options_$prope = _this2.options_[property]) !== null && _this2$options_$prope !== void 0 && _this2$options_$prope[prop]); }); if (isMissing) { throw new Error("options.".concat(property, " is required to create a Klarna Order.\n") + "medusa-config.js file has to contain ".concat(property, " { ").concat(required.join(", "), "}")); } } }, { key: "paymentInputToKlarnaOrder", value: function () { var _paymentInputToKlarnaOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(paymentInput) { var currency_code, amount, resource_id, order; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (!paymentInput.cart) { _context3.next = 3; break; } this.validateKlarnaOrderUrls("merchant_urls"); return _context3.abrupt("return", this.cartToKlarnaOrder(paymentInput.cart)); case 3: this.validateKlarnaOrderUrls("payment_collection_urls"); currency_code = paymentInput.currency_code, amount = paymentInput.amount, resource_id = paymentInput.resource_id; order = { // Custom id is stored, such that we can use it for hooks merchant_data: resource_id, locale: this.locale_, order_lines: [{ name: "Payment Collection", quantity: 1, unit_price: amount, tax_rate: 0, total_amount: amount, total_tax_amount: 0 }], // Defaults to Sweden purchase_country: "SE", order_amount: amount, order_tax_amount: 0, purchase_currency: currency_code.toUpperCase(), merchant_urls: { terms: KlarnaProviderService.replaceStringWithPropertyValue(this.options_.payment_collection_urls.terms, paymentInput), checkout: KlarnaProviderService.replaceStringWithPropertyValue(this.options_.payment_collection_urls.checkout, paymentInput), confirmation: KlarnaProviderService.replaceStringWithPropertyValue(this.options_.payment_collection_urls.confirmation, paymentInput), push: "".concat(this.backendUrl_, "/klarna/push?klarna_order_id={checkout.order.id}") } }; return _context3.abrupt("return", order); case 7: case "end": return _context3.stop(); } }, _callee3, this); })); function paymentInputToKlarnaOrder(_x3) { return _paymentInputToKlarnaOrder.apply(this, arguments); } return paymentInputToKlarnaOrder; }() /** * Status for Klarna order. * @param {Object} paymentData - payment method data from cart * @returns {string} the status of the Klarna order */ }, { key: "getStatus", value: function () { var _getStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(paymentData) { var order_id, _yield$this$klarna_$g, order, status; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: order_id = paymentData.order_id; _context4.next = 3; return this.klarna_.get("".concat(this.klarnaOrderUrl_, "/").concat(order_id)); case 3: _yield$this$klarna_$g = _context4.sent; order = _yield$this$klarna_$g.data; status = "pending"; if (order.status === "checkout_complete") { status = "authorized"; } return _context4.abrupt("return", status); case 8: case "end": return _context4.stop(); } }, _callee4, this); })); function getStatus(_x4) { return _getStatus.apply(this, arguments); } return getStatus; }() /** * Creates Klarna PaymentIntent. * @param {string} cart - the cart to create a payment for * @returns {string} id of payment intent */ }, { key: "createPayment", value: function () { var _createPayment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(cart) { var order; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: _context5.prev = 0; _context5.next = 3; return this.cartToKlarnaOrder(cart); case 3: order = _context5.sent; _context5.next = 6; return this.klarna_.post(this.klarnaOrderUrl_, order).then(function (_ref4) { var data = _ref4.data; return data; }); case 6: return _context5.abrupt("return", _context5.sent); case 9: _context5.prev = 9; _context5.t0 = _context5["catch"](0); this.logger_.error(_context5.t0); throw _context5.t0; case 13: case "end": return _context5.stop(); } }, _callee5, this, [[0, 9]]); })); function createPayment(_x5) { return _createPayment.apply(this, arguments); } return createPayment; }() /** * Retrieves Klarna Order. * @param {string} cart - the cart to retrieve order for * @returns {Object} Klarna order */ }, { key: "retrievePayment", value: function () { var _retrievePayment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(paymentData) { return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: _context6.prev = 0; return _context6.abrupt("return", this.klarna_.get("".concat(this.klarnaOrderUrl_, "/").concat(paymentData.order_id)).then(function (_ref5) { var data = _ref5.data; return data; })); case 4: _context6.prev = 4; _context6.t0 = _context6["catch"](0); throw _context6.t0; case 7: case "end": return _context6.stop(); } }, _callee6, this, [[0, 4]]); })); function retrievePayment(_x6) { return _retrievePayment.apply(this, arguments); } return retrievePayment; }() /** * Gets a Klarna payment objec. * @param {object} sessionData - the data of the payment to retrieve * @returns {Promise<object>} Stripe payment intent */ }, { key: "getPaymentData", value: function () { var _getPaymentData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(sessionData) { return _regeneratorRuntime().wrap(function _callee7$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: _context7.prev = 0; return _context7.abrupt("return", this.klarna_.get("".concat(this.klarnaOrderUrl_, "/").concat(sessionData.data.order_id)).then(function (_ref6) { var data = _ref6.data; return data; })); case 4: _context7.prev = 4; _context7.t0 = _context7["catch"](0); throw _context7.t0; case 7: case "end": return _context7.stop(); } }, _callee7, this, [[0, 4]]); })); function getPaymentData(_x7) { return _getPaymentData.apply(this, arguments); } return getPaymentData; }() /** * Retrieves completed Klarna Order. * @param {string} klarnaOrderId - id of the order to retrieve * @returns {Object} Klarna order */ }, { key: "retrieveCompletedOrder", value: function () { var _retrieveCompletedOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(klarnaOrderId) { return _regeneratorRuntime().wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { case 0: _context8.prev = 0; return _context8.abrupt("return", this.klarna_.get("".concat(this.klarnaOrderManagementUrl_, "/").concat(klarnaOrderId)).then(function (_ref7) { var data = _ref7.data; return data; })); case 4: _context8.prev = 4; _context8.t0 = _context8["catch"](0); throw _context8.t0; case 7: case "end": return _context8.stop(); } }, _callee8, this, [[0, 4]]); })); function retrieveCompletedOrder(_x8) { return _retrieveCompletedOrder.apply(this, arguments); } return retrieveCompletedOrder; }() /** * Authorizes Klarna payment by simply returning the status for the payment * in use. * @param {object} sessionData - payment session data * @param {object} context - properties relevant to current context * @returns {Promise<{ status: string, data: object }>} result with data and status */ }, { key: "authorizePayment", value: function () { var _authorizePayment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(sessionData) { var context, paymentStatus, _args9 = arguments; return _regeneratorRuntime().wrap(function _callee9$(_context9) { while (1) switch (_context9.prev = _context9.next) { case 0: context = _args9.length > 1 && _args9[1] !== undefined ? _args9[1] : {}; _context9.prev = 1; _context9.next = 4; return this.getStatus(sessionData.data); case 4: paymentStatus = _context9.sent; return _context9.abrupt("return", { data: sessionData.data, status: paymentStatus }); case 8: _context9.prev = 8; _context9.t0 = _context9["catch"](1); throw _context9.t0; case 11: case "end": return _context9.stop(); } }, _callee9, this, [[1, 8]]); })); function authorizePayment(_x9) { return _authorizePayment.apply(this, arguments); } return authorizePayment; }() /** * Acknowledges a Klarna order as part of the order completion process * @param {string} klarnaOrderId - id of the order to acknowledge * @returns {string} id of acknowledged order */ }, { key: "acknowledgeOrder", value: function () { var _acknowledgeOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(klarnaOrderId) { var orderId, _args10 = arguments; return _regeneratorRuntime().wrap(function _callee10$(_context10) { while (1) switch (_context10.prev = _context10.next) { case 0: orderId = _args10.length > 1 && _args10[1] !== undefined ? _args10[1] : null; _context10.prev = 1; _context10.next = 4; return this.klarna_.post("".concat(this.klarnaOrderManagementUrl_, "/").concat(klarnaOrderId, "/acknowledge")); case 4: if (!(orderId !== null)) { _context10.next = 7; break; } _context10.next = 7; return this.klarna_.patch("".concat(this.klarnaOrderManagementUrl_, "/").concat(klarnaOrderId, "/merchant-references"), { merchant_reference1: orderId }); case 7: return _context10.abrupt("return", klarnaOrderId); case 10: _context10.prev = 10; _context10.t0 = _context10["catch"](1); throw _context10.t0; case 13: case "end": return _context10.stop(); } }, _callee10, this, [[1, 10]]); })); function acknowledgeOrder(_x10) { return _acknowledgeOrder.apply(this, arguments); } return acknowledgeOrder; }() /** * Adds the id of the Medusa order to the Klarna Order to create a relation * @param {string} klarnaOrderId - id of the klarna order * @param {string} orderId - id of the Medusa order * @returns {string} id of updated order */ }, { key: "addOrderToKlarnaOrder", value: function () { var _addOrderToKlarnaOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(klarnaOrderId, orderId) { return _regeneratorRuntime().wrap(function _callee11$(_context11) { while (1) switch (_context11.prev = _context11.next) { case 0: _context11.prev = 0; _context11.next = 3; return this.klarna_.post("".concat(this.klarnaOrderManagementUrl_, "/").concat(klarnaOrderId, "/merchant-references"), { merchant_reference1: orderId }); case 3: return _context11.abrupt("return", klarnaOrderId); case 6: _context11.prev = 6; _context11.t0 = _context11["catch"](0); throw _context11.t0; case 9: case "end": return _context11.stop(); } }, _callee11, this, [[0, 6]]); })); function addOrderToKlarnaOrder(_x11, _x12) { return _addOrderToKlarnaOrder.apply(this, arguments); } return addOrderToKlarnaOrder; }() }, { key: "updatePaymentData", value: function () { var _updatePaymentData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(sessionData, update) { return _regeneratorRuntime().wrap(function _callee12$(_context12) { while (1) switch (_context12.prev = _context12.next) { case 0: _context12.prev = 0; return _context12.abrupt("return", _objectSpread(_objectSpread({}, sessionData), update)); case 4: _context12.prev = 4; _context12.t0 = _context12["catch"](0); throw _context12.t0; case 7: case "end": return _context12.stop(); } }, _callee12, null, [[0, 4]]); })); function updatePaymentData(_x13, _x14) { return _updatePaymentData.apply(this, arguments); } return updatePaymentData; }() /** * Updates Klarna order. * @param {string} paymentData * @param {Object} cart * @returns {Object} updated order */ }, { key: "updatePayment", value: function () { var _updatePayment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(paymentData, cart) { var _this3 = this; var order; return _regeneratorRuntime().wrap(function _callee14$(_context14) { while (1) switch (_context14.prev = _context14.next) { case 0: if (!(cart.total !== paymentData.order_amount)) { _context14.next = 5; break; } _context14.next = 3; return this.cartToKlarnaOrder(cart); case 3: order = _context14.sent; return _context14.abrupt("return", this.klarna_.post("".concat(this.klarnaOrderUrl_, "/").concat(paymentData.order_id), order).then(function (_ref8) { var data = _ref8.data; return data; })["catch"]( /*#__PURE__*/function () { var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(_) { return _regeneratorRuntime().wrap(function _callee13$(_context13) { while (1) switch (_context13.prev = _context13.next) { case 0: return _context13.abrupt("return", _this3.klarna_.post(_this3.klarnaOrderUrl_, order).then(function (_ref10) {