medusa-plugin-ses 2.0.10 → 2.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/services/ses.js CHANGED
@@ -1,1569 +1,1017 @@
1
1
  "use strict";
2
-
3
- function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
6
17
  });
7
- exports["default"] = void 0;
8
- var aws = _interopRequireWildcard(require("@aws-sdk/client-ses"));
9
- var _handlebars = _interopRequireDefault(require("handlebars"));
10
- var _nodemailer = _interopRequireDefault(require("nodemailer"));
11
- var _path = _interopRequireDefault(require("path"));
12
- var _fs = _interopRequireDefault(require("fs"));
13
- var _medusaCoreUtils = require("medusa-core-utils");
14
- var _medusaInterfaces = require("medusa-interfaces");
15
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
16
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
17
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
18
- 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); }
19
- 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; }
20
- 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; }
21
- 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; }
22
- 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); } }
23
- 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); }); }; }
24
- function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
25
- 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); } }
26
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
27
- 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); }
28
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
29
- 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); }; }
30
- 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); }
31
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
32
- 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; } }
33
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
34
- 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; }
35
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
36
- 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); }
37
- var SESService = /*#__PURE__*/function (_NotificationService) {
38
- _inherits(SESService, _NotificationService);
39
- var _super = _createSuper(SESService);
40
- /**
41
- * @param {Object} options - options defined in `medusa-config.js`
42
- * e.g.
43
- * {
44
- * access_key_id: process.env.SES_ACCESS_KEY_ID,
45
- * secret_access_key: process.env.SES_SECRET_ACCESS_KEY,
46
- * region: process.env.SES_REGION,
47
- * from: process.env.SES_FROM,
48
- * enable_endpoint: process.env.SES_ENABLE_ENDPOINT,
49
- * template_path: process.env.SES_TEMPLATE_PATH,
50
- * order_placed_template: 'order_placed',
51
- * }
52
- */
53
- function SESService(_ref, options) {
54
- var _this;
55
- var storeService = _ref.storeService,
56
- orderService = _ref.orderService,
57
- returnService = _ref.returnService,
58
- swapService = _ref.swapService,
59
- cartService = _ref.cartService,
60
- lineItemService = _ref.lineItemService,
61
- claimService = _ref.claimService,
62
- fulfillmentService = _ref.fulfillmentService,
63
- fulfillmentProviderService = _ref.fulfillmentProviderService,
64
- totalsService = _ref.totalsService,
65
- productVariantService = _ref.productVariantService;
66
- _classCallCheck(this, SESService);
67
- _this = _super.call(this);
68
- _this.options_ = options;
69
- _this.fulfillmentProviderService_ = fulfillmentProviderService;
70
- _this.storeService_ = storeService;
71
- _this.lineItemService_ = lineItemService;
72
- _this.orderService_ = orderService;
73
- _this.cartService_ = cartService;
74
- _this.claimService_ = claimService;
75
- _this.returnService_ = returnService;
76
- _this.swapService_ = swapService;
77
- _this.fulfillmentService_ = fulfillmentService;
78
- _this.totalsService_ = totalsService;
79
- _this.productVariantService_ = productVariantService;
80
- var ses = new aws.SES({
81
- region: options.region,
82
- credentials: {
83
- accessKeyId: options.access_key_id,
84
- secretAccessKey: options.secret_access_key
85
- }
86
- });
87
- _this.transporter_ = _nodemailer["default"].createTransport({
88
- SES: {
89
- ses: ses,
90
- aws: aws
91
- }
92
- });
93
- return _this;
94
- }
95
- _createClass(SESService, [{
96
- key: "sendNotification",
97
- value: function () {
98
- var _sendNotification = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(event, eventData, attachmentGenerator) {
99
- var templateId, data, _yield$this$compileTe, subject, html, text, sendOptions, attachments, status;
100
- return _regeneratorRuntime().wrap(function _callee$(_context) {
101
- while (1) switch (_context.prev = _context.next) {
102
- case 0:
103
- templateId = this.getTemplateId(event);
104
- if (templateId) {
105
- _context.next = 3;
106
- break;
107
- }
108
- return _context.abrupt("return", false);
109
- case 3:
110
- _context.next = 5;
111
- return this.fetchData(event, eventData, attachmentGenerator);
112
- case 5:
113
- data = _context.sent;
114
- if (data) {
115
- _context.next = 8;
116
- break;
117
- }
118
- return _context.abrupt("return", false);
119
- case 8:
120
- if (data.locale) {
121
- templateId = this.getLocalizedTemplateId(event, data.locale) || templateId;
122
- }
123
- _context.next = 11;
124
- return this.compileTemplate(templateId, data);
125
- case 11:
126
- _yield$this$compileTe = _context.sent;
127
- subject = _yield$this$compileTe.subject;
128
- html = _yield$this$compileTe.html;
129
- text = _yield$this$compileTe.text;
130
- if (!(!subject || !html && !text)) {
131
- _context.next = 17;
132
- break;
133
- }
134
- return _context.abrupt("return", false);
135
- case 17:
136
- sendOptions = {
137
- from: this.options_.from,
138
- to: data.email,
139
- subject: subject,
140
- html: html,
141
- text: text
142
- };
143
- _context.next = 20;
144
- return this.fetchAttachments(event, data, attachmentGenerator);
145
- case 20:
146
- attachments = _context.sent;
147
- if (attachments !== null && attachments !== void 0 && attachments.length) {
148
- sendOptions.attachments = attachments.map(function (a) {
149
- return {
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const aws = __importStar(require("@aws-sdk/client-ses"));
30
+ const handlebars_1 = __importDefault(require("handlebars"));
31
+ const nodemailer_1 = __importDefault(require("nodemailer"));
32
+ const path_1 = __importDefault(require("path"));
33
+ const fs_1 = __importDefault(require("fs"));
34
+ const utils_1 = require("@medusajs/utils");
35
+ const medusa_interfaces_1 = require("medusa-interfaces");
36
+ class SESService extends medusa_interfaces_1.NotificationService {
37
+ /**
38
+ * @param {Object} options - options defined in `medusa-config.js`
39
+ * e.g.
40
+ * {
41
+ * access_key_id: process.env.SES_ACCESS_KEY_ID,
42
+ * secret_access_key: process.env.SES_SECRET_ACCESS_KEY,
43
+ * region: process.env.SES_REGION,
44
+ * from: process.env.SES_FROM,
45
+ * enable_endpoint: process.env.SES_ENABLE_ENDPOINT,
46
+ * template_path: process.env.SES_TEMPLATE_PATH,
47
+ * order_placed_template: 'order_placed',
48
+ * }
49
+ */
50
+ constructor({ storeService, orderService, returnService, swapService, cartService, lineItemService, claimService, fulfillmentService, fulfillmentProviderService, totalsService, productVariantService, }, options) {
51
+ super();
52
+ this.options_ = options;
53
+ this.fulfillmentProviderService_ = fulfillmentProviderService;
54
+ this.storeService_ = storeService;
55
+ this.lineItemService_ = lineItemService;
56
+ this.orderService_ = orderService;
57
+ this.cartService_ = cartService;
58
+ this.claimService_ = claimService;
59
+ this.returnService_ = returnService;
60
+ this.swapService_ = swapService;
61
+ this.fulfillmentService_ = fulfillmentService;
62
+ this.totalsService_ = totalsService;
63
+ this.productVariantService_ = productVariantService;
64
+ const ses = new aws.SES({
65
+ region: options.region,
66
+ credentials: {
67
+ accessKeyId: options.access_key_id,
68
+ secretAccessKey: options.secret_access_key,
69
+ },
70
+ });
71
+ this.transporter_ = nodemailer_1.default.createTransport({
72
+ SES: { ses, aws }
73
+ });
74
+ }
75
+ async sendNotification(event, eventData, attachmentGenerator) {
76
+ let templateId = this.getTemplateId(event);
77
+ if (!templateId) {
78
+ return false;
79
+ }
80
+ const data = await this.fetchData(event, eventData, attachmentGenerator);
81
+ if (!data) {
82
+ return false;
83
+ }
84
+ if (data.locale) {
85
+ templateId = this.getLocalizedTemplateId(event, data.locale) || templateId;
86
+ }
87
+ const { subject, html, text } = await this.compileTemplate(templateId, data);
88
+ if (!subject || (!html && !text)) {
89
+ return false;
90
+ }
91
+ const sendOptions = {
92
+ from: this.options_.from,
93
+ to: data.email,
94
+ subject,
95
+ html,
96
+ text
97
+ };
98
+ const attachments = await this.fetchAttachments(event, data, attachmentGenerator);
99
+ if (attachments?.length) {
100
+ sendOptions.attachments = attachments.map((a) => {
101
+ return {
150
102
  content: a.base64,
151
103
  filename: a.name,
152
104
  encoding: 'base64',
153
105
  contentType: a.type
154
- };
155
- });
156
- }
157
-
158
- //const status = await this.transporter_.sendMail(sendOptions).then(() => "sent").catch(() => "failed")
159
- _context.next = 24;
160
- return this.transporter_.sendMail(sendOptions).then(function () {
161
- status = "sent";
162
- })["catch"](function (error) {
163
- status = "failed";
164
- console.log(error);
165
- });
166
- case 24:
167
- // We don't want heavy docs stored in DB
168
- delete sendOptions.attachments;
169
- return _context.abrupt("return", {
170
- to: data.email,
171
- status: status,
172
- data: sendOptions
173
- });
174
- case 26:
175
- case "end":
176
- return _context.stop();
177
- }
178
- }, _callee, this);
179
- }));
180
- function sendNotification(_x, _x2, _x3) {
181
- return _sendNotification.apply(this, arguments);
182
- }
183
- return sendNotification;
184
- }()
185
- }, {
186
- key: "resendNotification",
187
- value: function () {
188
- var _resendNotification = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(notification, config, attachmentGenerator) {
189
- var sendOptions, attachs, status;
190
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
191
- while (1) switch (_context2.prev = _context2.next) {
192
- case 0:
193
- sendOptions = _objectSpread(_objectSpread({}, notification.data), {}, {
194
- to: config.to || notification.to
195
- });
196
- _context2.next = 3;
197
- return this.fetchAttachments(notification.event_name, notification.data.dynamic_template_data, attachmentGenerator);
198
- case 3:
199
- attachs = _context2.sent;
200
- sendOptions.attachments = attachs.map(function (a) {
201
- return {
202
- content: a.base64,
203
- filename: a.name,
204
- encoding: 'base64',
205
- contentType: a.type
206
106
  };
207
- });
208
-
209
- //const status = await this.transporter_.sendMail(sendOptions).then(() => "sent").catch(() => "failed")
210
- _context2.next = 7;
211
- return this.transporter_.sendMail(sendOptions).then(function () {
212
- status = "sent";
213
- })["catch"](function (error) {
214
- status = "failed";
215
- console.log(error);
216
- });
217
- case 7:
218
- return _context2.abrupt("return", {
219
- to: sendOptions.to,
220
- status: status,
221
- data: sendOptions
222
- });
223
- case 8:
224
- case "end":
225
- return _context2.stop();
226
- }
227
- }, _callee2, this);
228
- }));
229
- function resendNotification(_x4, _x5, _x6) {
230
- return _resendNotification.apply(this, arguments);
231
- }
232
- return resendNotification;
233
- }()
107
+ });
108
+ }
109
+ //const status = await this.transporter_.sendMail(sendOptions).then(() => "sent").catch(() => "failed")
110
+ let status;
111
+ await this.transporter_.sendMail(sendOptions)
112
+ .then(() => { status = "sent"; })
113
+ .catch((error) => { status = "failed"; console.log(error); });
114
+ // We don't want heavy docs stored in DB
115
+ delete sendOptions.attachments;
116
+ return { to: data.email, status, data: sendOptions };
117
+ }
118
+ async resendNotification(notification, config, attachmentGenerator) {
119
+ const sendOptions = {
120
+ ...notification.data,
121
+ to: config.to || notification.to,
122
+ };
123
+ const attachs = await this.fetchAttachments(notification.event_name, notification.data.dynamic_template_data, attachmentGenerator);
124
+ sendOptions.attachments = attachs.map((a) => {
125
+ return {
126
+ content: a.base64,
127
+ filename: a.name,
128
+ encoding: 'base64',
129
+ contentType: a.type
130
+ };
131
+ });
132
+ //const status = await this.transporter_.sendMail(sendOptions).then(() => "sent").catch(() => "failed")
133
+ let status;
134
+ await this.transporter_.sendMail(sendOptions)
135
+ .then(() => { status = "sent"; })
136
+ .catch((error) => { status = "failed"; console.log(error); });
137
+ return { to: sendOptions.to, status, data: sendOptions };
138
+ }
234
139
  /**
235
- * Sends an email using SES.
236
- * @param {string} template_id - id of template to use
237
- * @param {string} from - sender of email
238
- * @param {string} to - receiver of email
239
- * @param {Object} data - data to send in mail (match with template)
240
- * @return {Promise} result of the send operation
241
- */
242
- }, {
243
- key: "sendEmail",
244
- value: function () {
245
- var _sendEmail = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(template_id, from, to, data) {
246
- var _yield$this$compileTe2, subject, html, text;
247
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
248
- while (1) switch (_context3.prev = _context3.next) {
249
- case 0:
250
- if (!(this.options_.enable_endpoint !== '42')) {
251
- _context3.next = 2;
252
- break;
253
- }
254
- return _context3.abrupt("return", false);
255
- case 2:
256
- _context3.prev = 2;
257
- _context3.next = 5;
258
- return this.compileTemplate(template_id, data);
259
- case 5:
260
- _yield$this$compileTe2 = _context3.sent;
261
- subject = _yield$this$compileTe2.subject;
262
- html = _yield$this$compileTe2.html;
263
- text = _yield$this$compileTe2.text;
264
- if (!(!subject || !html && !text)) {
265
- _context3.next = 11;
266
- break;
267
- }
268
- return _context3.abrupt("return", {
269
- message: "Message not sent. Templates were not found or a compile error was encountered.",
270
- results: {
271
- subject: subject,
272
- html: html,
273
- text: text
274
- }
275
- });
276
- case 11:
277
- return _context3.abrupt("return", this.transporter_.sendMail({
140
+ * Sends an email using SES.
141
+ * @param {string} template_id - id of template to use
142
+ * @param {string} from - sender of email
143
+ * @param {string} to - receiver of email
144
+ * @param {Object} data - data to send in mail (match with template)
145
+ * @return {Promise} result of the send operation
146
+ */
147
+ async sendEmail(template_id, from, to, data) {
148
+ // This function is used by the /ses/send API endpoint included in this plugin.
149
+ // It is disabled by default.
150
+ // This endpoint may be useful for testing purposes and for use by related applications.
151
+ // There is NO SECURITY on the endpoint by default.
152
+ // Most people will NOT need to enable it.
153
+ // If you are certain that you want to enable it and that you know what you are doing,
154
+ // set the environment variable SES_ENABLE_ENDPOINT to "42" (a string, not an int).
155
+ // The unsual setting is meant to prevent enabling by accident or without thought.
156
+ if (this.options_.enable_endpoint !== '42') {
157
+ return false;
158
+ }
159
+ try {
160
+ const { subject, html, text } = await this.compileTemplate(template_id, data);
161
+ if (!subject || (!html && !text)) {
162
+ return {
163
+ message: "Message not sent. Templates were not found or a compile error was encountered.",
164
+ results: {
165
+ subject,
166
+ html,
167
+ text
168
+ }
169
+ };
170
+ }
171
+ return this.transporter_.sendMail({
278
172
  from: from,
279
173
  to: to,
280
- subject: subject,
281
- html: html,
282
- text: text
283
- }));
284
- case 14:
285
- _context3.prev = 14;
286
- _context3.t0 = _context3["catch"](2);
287
- throw _context3.t0;
288
- case 17:
289
- case "end":
290
- return _context3.stop();
291
- }
292
- }, _callee3, this, [[2, 14]]);
293
- }));
294
- function sendEmail(_x7, _x8, _x9, _x10) {
295
- return _sendEmail.apply(this, arguments);
296
- }
297
- return sendEmail;
298
- }()
299
- }, {
300
- key: "compileTemplate",
301
- value: function () {
302
- var _compileTemplate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(templateId, data) {
303
- var base, subjectTemplate, htmlTemplate, textTemplate;
304
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
305
- while (1) switch (_context4.prev = _context4.next) {
306
- case 0:
307
- base = this.options_.template_path.startsWith('/') ? _path["default"].resolve(this.options_.template_path, templateId) :
308
- // The path given in options is absolute
309
- _path["default"].join(__dirname, '../../..', this.options_.template_path, templateId); // The path given in options is relative
310
- subjectTemplate = _fs["default"].existsSync(_path["default"].join(base, 'subject.hbs')) ? _handlebars["default"].compile(_fs["default"].readFileSync(_path["default"].join(base, 'subject.hbs'), "utf8")) : null;
311
- htmlTemplate = _fs["default"].existsSync(_path["default"].join(base, 'html.hbs')) ? _handlebars["default"].compile(_fs["default"].readFileSync(_path["default"].join(base, 'html.hbs'), "utf8")) : null;
312
- textTemplate = _fs["default"].existsSync(_path["default"].join(base, 'text.hbs')) ? _handlebars["default"].compile(_fs["default"].readFileSync(_path["default"].join(base, 'text.hbs'), "utf8")) : null;
313
- return _context4.abrupt("return", {
314
- subject: subjectTemplate ? subjectTemplate(data) : null,
315
- html: htmlTemplate ? htmlTemplate(data) : null,
316
- text: textTemplate ? textTemplate(data) : null
317
- });
318
- case 5:
319
- case "end":
320
- return _context4.stop();
321
- }
322
- }, _callee4, this);
323
- }));
324
- function compileTemplate(_x11, _x12) {
325
- return _compileTemplate.apply(this, arguments);
326
- }
327
- return compileTemplate;
328
- }()
329
- }, {
330
- key: "getLocalizedTemplateId",
331
- value: function getLocalizedTemplateId(event, locale) {
332
- if (this.options_.localization && this.options_.localization[locale]) {
333
- var map = this.options_.localization[locale];
174
+ subject,
175
+ html,
176
+ text
177
+ });
178
+ }
179
+ catch (error) {
180
+ throw error;
181
+ }
182
+ }
183
+ async compileTemplate(templateId, data) {
184
+ const base = (this.options_.template_path.startsWith('/')) ?
185
+ path_1.default.resolve(this.options_.template_path, templateId) : // The path given in options is absolute
186
+ path_1.default.join(__dirname, '../../..', this.options_.template_path, templateId); // The path given in options is relative
187
+ const subjectTemplate = fs_1.default.existsSync(path_1.default.join(base, 'subject.hbs')) ?
188
+ handlebars_1.default.compile(fs_1.default.readFileSync(path_1.default.join(base, 'subject.hbs'), "utf8")) : null;
189
+ const htmlTemplate = fs_1.default.existsSync(path_1.default.join(base, 'html.hbs')) ?
190
+ handlebars_1.default.compile(fs_1.default.readFileSync(path_1.default.join(base, 'html.hbs'), "utf8")) : null;
191
+ const textTemplate = fs_1.default.existsSync(path_1.default.join(base, 'text.hbs')) ?
192
+ handlebars_1.default.compile(fs_1.default.readFileSync(path_1.default.join(base, 'text.hbs'), "utf8")) : null;
193
+ return {
194
+ subject: subjectTemplate ? subjectTemplate(data) : null,
195
+ html: htmlTemplate ? htmlTemplate(data) : null,
196
+ text: textTemplate ? textTemplate(data) : null
197
+ };
198
+ }
199
+ getLocalizedTemplateId(event, locale) {
200
+ if (this.options_.localization && this.options_.localization[locale]) {
201
+ const map = this.options_.localization[locale];
202
+ switch (event) {
203
+ case "order.return_requested":
204
+ return map.order_return_requested_template;
205
+ case "swap.shipment_created":
206
+ return map.swap_shipment_created_template;
207
+ case "claim.shipment_created":
208
+ return map.claim_shipment_created_template;
209
+ case "order.items_returned":
210
+ return map.order_items_returned_template;
211
+ case "swap.received":
212
+ return map.swap_received_template;
213
+ case "swap.created":
214
+ return map.swap_created_template;
215
+ case "gift_card.created":
216
+ return map.gift_card_created_template;
217
+ case "order.gift_card_created":
218
+ return map.gift_card_created_template;
219
+ case "order.placed":
220
+ return map.order_placed_template;
221
+ case "order.shipment_created":
222
+ return map.order_shipped_template;
223
+ case "order.canceled":
224
+ return map.order_canceled_template;
225
+ case "user.password_reset":
226
+ return map.user_password_reset_template;
227
+ case "customer.password_reset":
228
+ return map.customer_password_reset_template;
229
+ case "restock-notification.restocked":
230
+ return map.medusa_restock_template;
231
+ case "order.refund_created":
232
+ return map.order_refund_created_template;
233
+ default:
234
+ return null;
235
+ }
236
+ }
237
+ return null;
238
+ }
239
+ getTemplateId(event) {
334
240
  switch (event) {
335
- case "order.return_requested":
336
- return map.order_return_requested_template;
337
- case "swap.shipment_created":
338
- return map.swap_shipment_created_template;
339
- case "claim.shipment_created":
340
- return map.claim_shipment_created_template;
341
- case "order.items_returned":
342
- return map.order_items_returned_template;
343
- case "swap.received":
344
- return map.swap_received_template;
345
- case "swap.created":
346
- return map.swap_created_template;
347
- case "gift_card.created":
348
- return map.gift_card_created_template;
349
- case "order.gift_card_created":
350
- return map.gift_card_created_template;
351
- case "order.placed":
352
- return map.order_placed_template;
353
- case "order.shipment_created":
354
- return map.order_shipped_template;
355
- case "order.canceled":
356
- return map.order_canceled_template;
357
- case "user.password_reset":
358
- return map.user_password_reset_template;
359
- case "customer.password_reset":
360
- return map.customer_password_reset_template;
361
- case "restock-notification.restocked":
362
- return map.medusa_restock_template;
363
- case "order.refund_created":
364
- return map.order_refund_created_template;
365
- default:
366
- return null;
241
+ case "order.return_requested":
242
+ return this.options_.order_return_requested_template;
243
+ case "swap.shipment_created":
244
+ return this.options_.swap_shipment_created_template;
245
+ case "claim.shipment_created":
246
+ return this.options_.claim_shipment_created_template;
247
+ case "order.items_returned":
248
+ return this.options_.order_items_returned_template;
249
+ case "swap.received":
250
+ return this.options_.swap_received_template;
251
+ case "swap.created":
252
+ return this.options_.swap_created_template;
253
+ case "gift_card.created":
254
+ return this.options_.gift_card_created_template;
255
+ case "order.gift_card_created":
256
+ return this.options_.gift_card_created_template;
257
+ case "order.placed":
258
+ return this.options_.order_placed_template;
259
+ case "order.shipment_created":
260
+ return this.options_.order_shipped_template;
261
+ case "order.canceled":
262
+ return this.options_.order_canceled_template;
263
+ case "user.password_reset":
264
+ return this.options_.user_password_reset_template;
265
+ case "customer.password_reset":
266
+ return this.options_.customer_password_reset_template;
267
+ case "restock-notification.restocked":
268
+ return this.options_.medusa_restock_template;
269
+ case "order.refund_created":
270
+ return this.options_.order_refund_created_template;
271
+ default:
272
+ return null;
273
+ }
274
+ }
275
+ async fetchAttachments(event, data, attachmentGenerator) {
276
+ switch (event) {
277
+ case "swap.created":
278
+ case "order.return_requested": {
279
+ let attachments = [];
280
+ const { shipping_method, shipping_data } = data.return_request;
281
+ if (shipping_method) {
282
+ const provider = shipping_method.shipping_option.provider_id;
283
+ const lbl = await this.fulfillmentProviderService_.retrieveDocuments(provider, shipping_data, "label");
284
+ attachments = attachments.concat(lbl.map((d) => ({
285
+ name: "return-label",
286
+ base64: d.base_64,
287
+ type: d.type,
288
+ })));
289
+ }
290
+ if (attachmentGenerator && attachmentGenerator.createReturnInvoice) {
291
+ const base64 = await attachmentGenerator.createReturnInvoice(data.order, data.return_request.items);
292
+ attachments.push({
293
+ name: "invoice",
294
+ base64,
295
+ type: "application/pdf",
296
+ });
297
+ }
298
+ return attachments;
299
+ }
300
+ default:
301
+ return [];
367
302
  }
368
- }
369
- return null;
370
303
  }
371
- }, {
372
- key: "getTemplateId",
373
- value: function getTemplateId(event) {
374
- switch (event) {
375
- case "order.return_requested":
376
- return this.options_.order_return_requested_template;
377
- case "swap.shipment_created":
378
- return this.options_.swap_shipment_created_template;
379
- case "claim.shipment_created":
380
- return this.options_.claim_shipment_created_template;
381
- case "order.items_returned":
382
- return this.options_.order_items_returned_template;
383
- case "swap.received":
384
- return this.options_.swap_received_template;
385
- case "swap.created":
386
- return this.options_.swap_created_template;
387
- case "gift_card.created":
388
- return this.options_.gift_card_created_template;
389
- case "order.gift_card_created":
390
- return this.options_.gift_card_created_template;
391
- case "order.placed":
392
- return this.options_.order_placed_template;
393
- case "order.shipment_created":
394
- return this.options_.order_shipped_template;
395
- case "order.canceled":
396
- return this.options_.order_canceled_template;
397
- case "user.password_reset":
398
- return this.options_.user_password_reset_template;
399
- case "customer.password_reset":
400
- return this.options_.customer_password_reset_template;
401
- case "restock-notification.restocked":
402
- return this.options_.medusa_restock_template;
403
- case "order.refund_created":
404
- return this.options_.order_refund_created_template;
405
- default:
406
- return null;
407
- }
304
+ async fetchData(event, eventData, attachmentGenerator) {
305
+ switch (event) {
306
+ case "order.return_requested":
307
+ return this.returnRequestedData(eventData, attachmentGenerator);
308
+ case "swap.shipment_created":
309
+ return this.swapShipmentCreatedData(eventData, attachmentGenerator);
310
+ case "claim.shipment_created":
311
+ return this.claimShipmentCreatedData(eventData, attachmentGenerator);
312
+ case "order.items_returned":
313
+ return this.itemsReturnedData(eventData, attachmentGenerator);
314
+ case "swap.received":
315
+ return this.swapReceivedData(eventData, attachmentGenerator);
316
+ case "swap.created":
317
+ return this.swapCreatedData(eventData, attachmentGenerator);
318
+ case "gift_card.created":
319
+ return this.gcCreatedData(eventData, attachmentGenerator);
320
+ case "order.gift_card_created":
321
+ return this.gcCreatedData(eventData, attachmentGenerator);
322
+ case "order.placed":
323
+ return this.orderPlacedData(eventData, attachmentGenerator);
324
+ case "order.shipment_created":
325
+ return this.orderShipmentCreatedData(eventData, attachmentGenerator);
326
+ case "order.canceled":
327
+ return this.orderCanceledData(eventData, attachmentGenerator);
328
+ case "user.password_reset":
329
+ return this.userPasswordResetData(eventData, attachmentGenerator);
330
+ case "customer.password_reset":
331
+ return this.customerPasswordResetData(eventData, attachmentGenerator);
332
+ case "restock-notification.restocked":
333
+ return await this.restockNotificationData(eventData, attachmentGenerator);
334
+ case "order.refund_created":
335
+ return this.orderRefundCreatedData(eventData, attachmentGenerator);
336
+ default:
337
+ return {};
338
+ }
408
339
  }
409
- }, {
410
- key: "fetchAttachments",
411
- value: function () {
412
- var _fetchAttachments = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(event, data, attachmentGenerator) {
413
- var attachments, _data$return_request, shipping_method, shipping_data, provider, lbl, base64;
414
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
415
- while (1) switch (_context5.prev = _context5.next) {
416
- case 0:
417
- _context5.t0 = event;
418
- _context5.next = _context5.t0 === "swap.created" ? 3 : _context5.t0 === "order.return_requested" ? 3 : 17;
419
- break;
420
- case 3:
421
- attachments = [];
422
- _data$return_request = data.return_request, shipping_method = _data$return_request.shipping_method, shipping_data = _data$return_request.shipping_data;
423
- if (!shipping_method) {
424
- _context5.next = 11;
425
- break;
426
- }
427
- provider = shipping_method.shipping_option.provider_id;
428
- _context5.next = 9;
429
- return this.fulfillmentProviderService_.retrieveDocuments(provider, shipping_data, "label");
430
- case 9:
431
- lbl = _context5.sent;
432
- attachments = attachments.concat(lbl.map(function (d) {
340
+ async orderShipmentCreatedData({ id, fulfillment_id }, attachmentGenerator) {
341
+ const order = await this.orderService_.retrieve(id, {
342
+ select: [
343
+ "shipping_total",
344
+ "discount_total",
345
+ "tax_total",
346
+ "refunded_total",
347
+ "gift_card_total",
348
+ "subtotal",
349
+ "total",
350
+ "refundable_amount",
351
+ ],
352
+ relations: [
353
+ "customer",
354
+ "billing_address",
355
+ "shipping_address",
356
+ "discounts",
357
+ "discounts.rule",
358
+ "shipping_methods",
359
+ "shipping_methods.shipping_option",
360
+ "payments",
361
+ "fulfillments",
362
+ "returns",
363
+ "gift_cards",
364
+ "gift_card_transactions",
365
+ ],
366
+ });
367
+ const shipment = await this.fulfillmentService_.retrieve(fulfillment_id, {
368
+ relations: ["items", "tracking_links"],
369
+ });
370
+ const locale = await this.extractLocale(order);
371
+ return {
372
+ locale,
373
+ order,
374
+ date: shipment.shipped_at.toDateString(),
375
+ email: order.email,
376
+ fulfillment: shipment,
377
+ tracking_links: shipment.tracking_links,
378
+ tracking_number: shipment.tracking_numbers.join(", "),
379
+ };
380
+ }
381
+ async orderCanceledData({ id }) {
382
+ const order = await this.orderService_.retrieve(id, {
383
+ select: [
384
+ "shipping_total",
385
+ "discount_total",
386
+ "tax_total",
387
+ "refunded_total",
388
+ "gift_card_total",
389
+ "subtotal",
390
+ "total",
391
+ ],
392
+ relations: [
393
+ "customer",
394
+ "billing_address",
395
+ "shipping_address",
396
+ "discounts",
397
+ "discounts.rule",
398
+ "shipping_methods",
399
+ "shipping_methods.shipping_option",
400
+ "payments",
401
+ "fulfillments",
402
+ "returns",
403
+ "gift_cards",
404
+ "gift_card_transactions",
405
+ ],
406
+ });
407
+ const { subtotal, tax_total, discount_total, shipping_total, gift_card_total, total, } = order;
408
+ const taxRate = order.tax_rate / 100;
409
+ const currencyCode = order.currency_code.toUpperCase();
410
+ const items = this.processItems_(order.items, taxRate, currencyCode);
411
+ let discounts = [];
412
+ if (order.discounts) {
413
+ discounts = order.discounts.map((discount) => {
433
414
  return {
434
- name: "return-label",
435
- base64: d.base_64,
436
- type: d.type
437
- };
438
- }));
439
- case 11:
440
- if (!(attachmentGenerator && attachmentGenerator.createReturnInvoice)) {
441
- _context5.next = 16;
442
- break;
443
- }
444
- _context5.next = 14;
445
- return attachmentGenerator.createReturnInvoice(data.order, data.return_request.items);
446
- case 14:
447
- base64 = _context5.sent;
448
- attachments.push({
449
- name: "invoice",
450
- base64: base64,
451
- type: "application/pdf"
452
- });
453
- case 16:
454
- return _context5.abrupt("return", attachments);
455
- case 17:
456
- return _context5.abrupt("return", []);
457
- case 18:
458
- case "end":
459
- return _context5.stop();
460
- }
461
- }, _callee5, this);
462
- }));
463
- function fetchAttachments(_x13, _x14, _x15) {
464
- return _fetchAttachments.apply(this, arguments);
465
- }
466
- return fetchAttachments;
467
- }()
468
- }, {
469
- key: "fetchData",
470
- value: function () {
471
- var _fetchData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(event, eventData, attachmentGenerator) {
472
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
473
- while (1) switch (_context6.prev = _context6.next) {
474
- case 0:
475
- _context6.t0 = event;
476
- _context6.next = _context6.t0 === "order.return_requested" ? 3 : _context6.t0 === "swap.shipment_created" ? 4 : _context6.t0 === "claim.shipment_created" ? 5 : _context6.t0 === "order.items_returned" ? 6 : _context6.t0 === "swap.received" ? 7 : _context6.t0 === "swap.created" ? 8 : _context6.t0 === "gift_card.created" ? 9 : _context6.t0 === "order.gift_card_created" ? 10 : _context6.t0 === "order.placed" ? 11 : _context6.t0 === "order.shipment_created" ? 12 : _context6.t0 === "order.canceled" ? 13 : _context6.t0 === "user.password_reset" ? 14 : _context6.t0 === "customer.password_reset" ? 15 : _context6.t0 === "restock-notification.restocked" ? 16 : _context6.t0 === "order.refund_created" ? 19 : 20;
477
- break;
478
- case 3:
479
- return _context6.abrupt("return", this.returnRequestedData(eventData, attachmentGenerator));
480
- case 4:
481
- return _context6.abrupt("return", this.swapShipmentCreatedData(eventData, attachmentGenerator));
482
- case 5:
483
- return _context6.abrupt("return", this.claimShipmentCreatedData(eventData, attachmentGenerator));
484
- case 6:
485
- return _context6.abrupt("return", this.itemsReturnedData(eventData, attachmentGenerator));
486
- case 7:
487
- return _context6.abrupt("return", this.swapReceivedData(eventData, attachmentGenerator));
488
- case 8:
489
- return _context6.abrupt("return", this.swapCreatedData(eventData, attachmentGenerator));
490
- case 9:
491
- return _context6.abrupt("return", this.gcCreatedData(eventData, attachmentGenerator));
492
- case 10:
493
- return _context6.abrupt("return", this.gcCreatedData(eventData, attachmentGenerator));
494
- case 11:
495
- return _context6.abrupt("return", this.orderPlacedData(eventData, attachmentGenerator));
496
- case 12:
497
- return _context6.abrupt("return", this.orderShipmentCreatedData(eventData, attachmentGenerator));
498
- case 13:
499
- return _context6.abrupt("return", this.orderCanceledData(eventData, attachmentGenerator));
500
- case 14:
501
- return _context6.abrupt("return", this.userPasswordResetData(eventData, attachmentGenerator));
502
- case 15:
503
- return _context6.abrupt("return", this.customerPasswordResetData(eventData, attachmentGenerator));
504
- case 16:
505
- _context6.next = 18;
506
- return this.restockNotificationData(eventData, attachmentGenerator);
507
- case 18:
508
- return _context6.abrupt("return", _context6.sent);
509
- case 19:
510
- return _context6.abrupt("return", this.orderRefundCreatedData(eventData, attachmentGenerator));
511
- case 20:
512
- return _context6.abrupt("return", {});
513
- case 21:
514
- case "end":
515
- return _context6.stop();
516
- }
517
- }, _callee6, this);
518
- }));
519
- function fetchData(_x16, _x17, _x18) {
520
- return _fetchData.apply(this, arguments);
521
- }
522
- return fetchData;
523
- }()
524
- }, {
525
- key: "orderShipmentCreatedData",
526
- value: function () {
527
- var _orderShipmentCreatedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref2, attachmentGenerator) {
528
- var id, fulfillment_id, order, shipment, locale;
529
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
530
- while (1) switch (_context7.prev = _context7.next) {
531
- case 0:
532
- id = _ref2.id, fulfillment_id = _ref2.fulfillment_id;
533
- _context7.next = 3;
534
- return this.orderService_.retrieve(id, {
535
- select: ["shipping_total", "discount_total", "tax_total", "refunded_total", "gift_card_total", "subtotal", "total", "refundable_amount"],
536
- relations: ["customer", "billing_address", "shipping_address", "discounts", "discounts.rule", "shipping_methods", "shipping_methods.shipping_option", "payments", "fulfillments", "returns", "gift_cards", "gift_card_transactions"]
537
- });
538
- case 3:
539
- order = _context7.sent;
540
- _context7.next = 6;
541
- return this.fulfillmentService_.retrieve(fulfillment_id, {
542
- relations: ["items", "tracking_links"]
543
- });
544
- case 6:
545
- shipment = _context7.sent;
546
- _context7.next = 9;
547
- return this.extractLocale(order);
548
- case 9:
549
- locale = _context7.sent;
550
- return _context7.abrupt("return", {
551
- locale: locale,
552
- order: order,
553
- date: shipment.shipped_at.toDateString(),
554
- email: order.email,
555
- fulfillment: shipment,
556
- tracking_links: shipment.tracking_links,
557
- tracking_number: shipment.tracking_numbers.join(", ")
558
- });
559
- case 11:
560
- case "end":
561
- return _context7.stop();
562
- }
563
- }, _callee7, this);
564
- }));
565
- function orderShipmentCreatedData(_x19, _x20) {
566
- return _orderShipmentCreatedData.apply(this, arguments);
567
- }
568
- return orderShipmentCreatedData;
569
- }()
570
- }, {
571
- key: "orderCanceledData",
572
- value: function () {
573
- var _orderCanceledData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref3) {
574
- var id, order, subtotal, tax_total, discount_total, shipping_total, gift_card_total, total, taxRate, currencyCode, items, discounts, giftCards, locale;
575
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
576
- while (1) switch (_context8.prev = _context8.next) {
577
- case 0:
578
- id = _ref3.id;
579
- _context8.next = 3;
580
- return this.orderService_.retrieve(id, {
581
- select: ["shipping_total", "discount_total", "tax_total", "refunded_total", "gift_card_total", "subtotal", "total"],
582
- relations: ["customer", "billing_address", "shipping_address", "discounts", "discounts.rule", "shipping_methods", "shipping_methods.shipping_option", "payments", "fulfillments", "returns", "gift_cards", "gift_card_transactions"]
583
- });
584
- case 3:
585
- order = _context8.sent;
586
- subtotal = order.subtotal, tax_total = order.tax_total, discount_total = order.discount_total, shipping_total = order.shipping_total, gift_card_total = order.gift_card_total, total = order.total;
587
- taxRate = order.tax_rate / 100;
588
- currencyCode = order.currency_code.toUpperCase();
589
- items = this.processItems_(order.items, taxRate, currencyCode);
590
- discounts = [];
591
- if (order.discounts) {
592
- discounts = order.discounts.map(function (discount) {
593
- return {
594
415
  is_giftcard: false,
595
416
  code: discount.code,
596
- descriptor: "".concat(discount.rule.value).concat(discount.rule.type === "percentage" ? "%" : " ".concat(currencyCode))
597
- };
598
- });
599
- }
600
- giftCards = [];
601
- if (order.gift_cards) {
602
- giftCards = order.gift_cards.map(function (gc) {
603
- return {
417
+ descriptor: `${discount.rule.value}${discount.rule.type === "percentage" ? "%" : ` ${currencyCode}`}`,
418
+ };
419
+ });
420
+ }
421
+ let giftCards = [];
422
+ if (order.gift_cards) {
423
+ giftCards = order.gift_cards.map((gc) => {
424
+ return {
604
425
  is_giftcard: true,
605
426
  code: gc.code,
606
- descriptor: "".concat(gc.value, " ").concat(currencyCode)
607
- };
608
- });
609
- discounts.concat(giftCards);
610
- }
611
- _context8.next = 14;
612
- return this.extractLocale(order);
613
- case 14:
614
- locale = _context8.sent;
615
- return _context8.abrupt("return", _objectSpread(_objectSpread({}, order), {}, {
616
- locale: locale,
617
- has_discounts: order.discounts.length,
618
- has_gift_cards: order.gift_cards.length,
619
- date: order.created_at.toDateString(),
620
- items: items,
621
- discounts: discounts,
622
- subtotal: "".concat(this.humanPrice_(subtotal * (1 + taxRate), currencyCode), " ").concat(currencyCode),
623
- gift_card_total: "".concat(this.humanPrice_(gift_card_total * (1 + taxRate), currencyCode), " ").concat(currencyCode),
624
- tax_total: "".concat(this.humanPrice_(tax_total, currencyCode), " ").concat(currencyCode),
625
- discount_total: "".concat(this.humanPrice_(discount_total * (1 + taxRate), currencyCode), " ").concat(currencyCode),
626
- shipping_total: "".concat(this.humanPrice_(shipping_total * (1 + taxRate), currencyCode), " ").concat(currencyCode),
627
- total: "".concat(this.humanPrice_(total, currencyCode), " ").concat(currencyCode)
628
- }));
629
- case 16:
630
- case "end":
631
- return _context8.stop();
632
- }
633
- }, _callee8, this);
634
- }));
635
- function orderCanceledData(_x21) {
636
- return _orderCanceledData.apply(this, arguments);
637
- }
638
- return orderCanceledData;
639
- }()
640
- }, {
641
- key: "orderPlacedData",
642
- value: function () {
643
- var _orderPlacedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref4) {
644
- var _this2 = this;
645
- var id, order, tax_total, shipping_total, gift_card_total, total, currencyCode, items, discounts, giftCards, locale, discountTotal, discounted_subtotal, subtotal, subtotal_ex_tax;
646
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
647
- while (1) switch (_context10.prev = _context10.next) {
648
- case 0:
649
- id = _ref4.id;
650
- _context10.next = 3;
651
- return this.orderService_.retrieve(id, {
652
- select: ["shipping_total", "discount_total", "tax_total", "refunded_total", "gift_card_total", "subtotal", "total"],
653
- relations: ["customer", "billing_address", "shipping_address", "discounts", "discounts.rule", "shipping_methods", "shipping_methods.shipping_option", "payments", "fulfillments", "returns", "gift_cards", "gift_card_transactions"]
654
- });
655
- case 3:
656
- order = _context10.sent;
657
- tax_total = order.tax_total, shipping_total = order.shipping_total, gift_card_total = order.gift_card_total, total = order.total;
658
- currencyCode = order.currency_code.toUpperCase();
659
- _context10.next = 8;
660
- return Promise.all(order.items.map( /*#__PURE__*/function () {
661
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(i) {
662
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
663
- while (1) switch (_context9.prev = _context9.next) {
664
- case 0:
665
- _context9.next = 2;
666
- return _this2.totalsService_.getLineItemTotals(i, order, {
667
- include_tax: true,
668
- use_tax_lines: true
669
- });
670
- case 2:
671
- i.totals = _context9.sent;
672
- i.thumbnail = _this2.normalizeThumbUrl_(i.thumbnail);
673
- i.discounted_price = "".concat(_this2.humanPrice_(i.totals.total / i.quantity, currencyCode), " ").concat(currencyCode);
674
- i.price = "".concat(_this2.humanPrice_(i.totals.original_total / i.quantity, currencyCode), " ").concat(currencyCode);
675
- return _context9.abrupt("return", i);
676
- case 7:
677
- case "end":
678
- return _context9.stop();
679
- }
680
- }, _callee9);
681
- }));
682
- return function (_x23) {
683
- return _ref5.apply(this, arguments);
427
+ descriptor: `${gc.value} ${currencyCode}`,
684
428
  };
685
- }()));
686
- case 8:
687
- items = _context10.sent;
688
- discounts = [];
689
- if (order.discounts) {
690
- discounts = order.discounts.map(function (discount) {
691
- return {
429
+ });
430
+ discounts.concat(giftCards);
431
+ }
432
+ const locale = await this.extractLocale(order);
433
+ return {
434
+ ...order,
435
+ locale,
436
+ has_discounts: order.discounts.length,
437
+ has_gift_cards: order.gift_cards.length,
438
+ date: order.created_at.toDateString(),
439
+ items,
440
+ discounts,
441
+ subtotal: `${this.humanPrice_(subtotal * (1 + taxRate), currencyCode)} ${currencyCode}`,
442
+ gift_card_total: `${this.humanPrice_(gift_card_total * (1 + taxRate), currencyCode)} ${currencyCode}`,
443
+ tax_total: `${this.humanPrice_(tax_total, currencyCode)} ${currencyCode}`,
444
+ discount_total: `${this.humanPrice_(discount_total * (1 + taxRate), currencyCode)} ${currencyCode}`,
445
+ shipping_total: `${this.humanPrice_(shipping_total * (1 + taxRate), currencyCode)} ${currencyCode}`,
446
+ total: `${this.humanPrice_(total, currencyCode)} ${currencyCode}`,
447
+ };
448
+ }
449
+ async orderPlacedData({ id }) {
450
+ const order = await this.orderService_.retrieve(id, {
451
+ select: [
452
+ "shipping_total",
453
+ "discount_total",
454
+ "tax_total",
455
+ "refunded_total",
456
+ "gift_card_total",
457
+ "subtotal",
458
+ "total",
459
+ ],
460
+ relations: [
461
+ "customer",
462
+ "billing_address",
463
+ "shipping_address",
464
+ "discounts",
465
+ "discounts.rule",
466
+ "shipping_methods",
467
+ "shipping_methods.shipping_option",
468
+ "payments",
469
+ "fulfillments",
470
+ "returns",
471
+ "gift_cards",
472
+ "gift_card_transactions",
473
+ ],
474
+ });
475
+ const { tax_total, shipping_total, gift_card_total, total } = order;
476
+ const currencyCode = order.currency_code.toUpperCase();
477
+ const items = await Promise.all(order.items.map(async (i) => {
478
+ i.totals = await this.totalsService_.getLineItemTotals(i, order, {
479
+ include_tax: true,
480
+ use_tax_lines: true,
481
+ });
482
+ i.thumbnail = this.normalizeThumbUrl_(i.thumbnail);
483
+ i.discounted_price = `${this.humanPrice_(i.totals.total / i.quantity, currencyCode)} ${currencyCode}`;
484
+ i.price = `${this.humanPrice_(i.totals.original_total / i.quantity, currencyCode)} ${currencyCode}`;
485
+ return i;
486
+ }));
487
+ let discounts = [];
488
+ if (order.discounts) {
489
+ discounts = order.discounts.map((discount) => {
490
+ return {
692
491
  is_giftcard: false,
693
492
  code: discount.code,
694
- descriptor: "".concat(discount.rule.value).concat(discount.rule.type === "percentage" ? "%" : " ".concat(currencyCode))
695
- };
696
- });
697
- }
698
- giftCards = [];
699
- if (order.gift_cards) {
700
- giftCards = order.gift_cards.map(function (gc) {
701
- return {
493
+ descriptor: `${discount.rule.value}${discount.rule.type === "percentage" ? "%" : ` ${currencyCode}`}`,
494
+ };
495
+ });
496
+ }
497
+ let giftCards = [];
498
+ if (order.gift_cards) {
499
+ giftCards = order.gift_cards.map((gc) => {
500
+ return {
702
501
  is_giftcard: true,
703
502
  code: gc.code,
704
- descriptor: "".concat(gc.value, " ").concat(currencyCode)
705
- };
706
- });
707
- discounts.concat(giftCards);
708
- }
709
- _context10.next = 15;
710
- return this.extractLocale(order);
711
- case 15:
712
- locale = _context10.sent;
713
- // Includes taxes in discount amount
714
- discountTotal = items.reduce(function (acc, i) {
715
- return acc + i.totals.original_total - i.totals.total;
716
- }, 0);
717
- discounted_subtotal = items.reduce(function (acc, i) {
718
- return acc + i.totals.total;
719
- }, 0);
720
- subtotal = items.reduce(function (acc, i) {
721
- return acc + i.totals.original_total;
722
- }, 0);
723
- subtotal_ex_tax = items.reduce(function (total, i) {
724
- return total + i.totals.subtotal;
725
- }, 0);
726
- return _context10.abrupt("return", _objectSpread(_objectSpread({}, order), {}, {
727
- locale: locale,
728
- has_discounts: order.discounts.length,
729
- has_gift_cards: order.gift_cards.length,
730
- date: order.created_at.toDateString(),
731
- items: items,
732
- discounts: discounts,
733
- subtotal_ex_tax: "".concat(this.humanPrice_(subtotal_ex_tax, currencyCode), " ").concat(currencyCode),
734
- subtotal: "".concat(this.humanPrice_(subtotal, currencyCode), " ").concat(currencyCode),
735
- gift_card_total: "".concat(this.humanPrice_(gift_card_total, currencyCode), " ").concat(currencyCode),
736
- tax_total: "".concat(this.humanPrice_(tax_total, currencyCode), " ").concat(currencyCode),
737
- discount_total: "".concat(this.humanPrice_(discountTotal, currencyCode), " ").concat(currencyCode),
738
- shipping_total: "".concat(this.humanPrice_(shipping_total, currencyCode), " ").concat(currencyCode),
739
- total: "".concat(this.humanPrice_(total, currencyCode), " ").concat(currencyCode)
740
- }));
741
- case 21:
742
- case "end":
743
- return _context10.stop();
744
- }
745
- }, _callee10, this);
746
- }));
747
- function orderPlacedData(_x22) {
748
- return _orderPlacedData.apply(this, arguments);
749
- }
750
- return orderPlacedData;
751
- }()
752
- }, {
753
- key: "gcCreatedData",
754
- value: function () {
755
- var _gcCreatedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref6) {
756
- var id, giftCard, taxRate, locale;
757
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
758
- while (1) switch (_context11.prev = _context11.next) {
759
- case 0:
760
- id = _ref6.id;
761
- _context11.next = 3;
762
- return this.giftCardService_.retrieve(id, {
763
- relations: ["region", "order"]
764
- });
765
- case 3:
766
- giftCard = _context11.sent;
767
- if (giftCard.order) {
768
- _context11.next = 6;
769
- break;
770
- }
771
- return _context11.abrupt("return");
772
- case 6:
773
- taxRate = giftCard.region.tax_rate / 100;
774
- _context11.next = 9;
775
- return this.extractLocale(order);
776
- case 9:
777
- locale = _context11.sent;
778
- return _context11.abrupt("return", _objectSpread(_objectSpread({}, giftCard), {}, {
779
- locale: locale,
780
- email: giftCard.order.email,
781
- display_value: giftCard.value * (1 + taxRate)
782
- }));
783
- case 11:
784
- case "end":
785
- return _context11.stop();
786
- }
787
- }, _callee11, this);
788
- }));
789
- function gcCreatedData(_x24) {
790
- return _gcCreatedData.apply(this, arguments);
791
- }
792
- return gcCreatedData;
793
- }()
794
- }, {
795
- key: "returnRequestedData",
796
- value: function () {
797
- var _returnRequestedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(_ref7) {
798
- var _this3 = this;
799
- var id, return_id, returnRequest, items, order, currencyCode, returnItems, item_subtotal, shippingTotal, base, locale;
800
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
801
- while (1) switch (_context13.prev = _context13.next) {
802
- case 0:
803
- id = _ref7.id, return_id = _ref7.return_id;
804
- _context13.next = 3;
805
- return this.returnService_.retrieve(return_id, {
806
- relations: ["items", "items.item", "items.item.tax_lines", "items.item.variant", "items.item.variant.product", "shipping_method", "shipping_method.tax_lines", "shipping_method.shipping_option"]
807
- });
808
- case 3:
809
- returnRequest = _context13.sent;
810
- _context13.next = 6;
811
- return this.lineItemService_.list({
812
- id: returnRequest.items.map(function (_ref8) {
813
- var item_id = _ref8.item_id;
814
- return item_id;
815
- })
816
- }, {
817
- relations: ["tax_lines"]
818
- });
819
- case 6:
820
- items = _context13.sent;
821
- _context13.next = 9;
822
- return this.orderService_.retrieve(id, {
823
- select: ["total"],
824
- relations: ["items", "items.tax_lines", "discounts", "discounts.rule", "shipping_address", "returns"]
825
- });
826
- case 9:
827
- order = _context13.sent;
828
- currencyCode = order.currency_code.toUpperCase(); // Calculate which items are in the return
829
- _context13.next = 13;
830
- return Promise.all(returnRequest.items.map( /*#__PURE__*/function () {
831
- var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(i) {
832
- var found;
833
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
834
- while (1) switch (_context12.prev = _context12.next) {
835
- case 0:
836
- found = items.find(function (oi) {
837
- return oi.id === i.item_id;
838
- });
839
- found.quantity = i.quantity;
840
- found.thumbnail = _this3.normalizeThumbUrl_(found.thumbnail);
841
- _context12.next = 5;
842
- return _this3.totalsService_.getLineItemTotals(found, order, {
843
- include_tax: true,
844
- use_tax_lines: true
845
- });
846
- case 5:
847
- found.totals = _context12.sent;
848
- found.price = "".concat(_this3.humanPrice_(found.totals.total, currencyCode), " ").concat(currencyCode);
849
- found.tax_lines = found.totals.tax_lines;
850
- return _context12.abrupt("return", found);
851
- case 9:
852
- case "end":
853
- return _context12.stop();
854
- }
855
- }, _callee12);
856
- }));
857
- return function (_x26) {
858
- return _ref9.apply(this, arguments);
859
- };
860
- }()));
861
- case 13:
862
- returnItems = _context13.sent;
863
- // Get total of the returned products
864
- item_subtotal = returnItems.reduce(function (acc, next) {
865
- return acc + next.totals.total;
866
- }, 0); // If the return has a shipping method get the price and any attachments
867
- shippingTotal = 0;
868
- if (returnRequest.shipping_method) {
869
- base = returnRequest.shipping_method.price;
870
- shippingTotal = base + returnRequest.shipping_method.tax_lines.reduce(function (acc, next) {
871
- return Math.round(acc + base * (next.rate / 100));
872
- }, 0);
873
- }
874
- _context13.next = 19;
875
- return this.extractLocale(order);
876
- case 19:
877
- locale = _context13.sent;
878
- return _context13.abrupt("return", {
879
- locale: locale,
880
- has_shipping: !!returnRequest.shipping_method,
881
- email: order.email,
882
- items: returnItems,
883
- subtotal: "".concat(this.humanPrice_(item_subtotal, currencyCode), " ").concat(currencyCode),
884
- shipping_total: "".concat(this.humanPrice_(shippingTotal, currencyCode), " ").concat(currencyCode),
885
- refund_amount: "".concat(this.humanPrice_(returnRequest.refund_amount, currencyCode), " ").concat(currencyCode),
886
- return_request: _objectSpread(_objectSpread({}, returnRequest), {}, {
887
- refund_amount: "".concat(this.humanPrice_(returnRequest.refund_amount, currencyCode), " ").concat(currencyCode)
888
- }),
889
- order: order,
890
- date: returnRequest.updated_at.toDateString()
891
- });
892
- case 21:
893
- case "end":
894
- return _context13.stop();
895
- }
896
- }, _callee13, this);
897
- }));
898
- function returnRequestedData(_x25) {
899
- return _returnRequestedData.apply(this, arguments);
900
- }
901
- return returnRequestedData;
902
- }()
903
- }, {
904
- key: "swapReceivedData",
905
- value: function () {
906
- var _swapReceivedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(_ref10) {
907
- var _this4 = this;
908
- var id, store, swap, returnRequest, items, swapLink, order, cart, currencyCode, decoratedItems, returnTotal, additionalTotal, refundAmount, locale;
909
- return _regeneratorRuntime().wrap(function _callee15$(_context15) {
910
- while (1) switch (_context15.prev = _context15.next) {
911
- case 0:
912
- id = _ref10.id;
913
- _context15.next = 3;
914
- return this.storeService_.retrieve();
915
- case 3:
916
- store = _context15.sent;
917
- _context15.next = 6;
918
- return this.swapService_.retrieve(id, {
919
- relations: ["additional_items", "additional_items.tax_lines", "return_order", "return_order.items", "return_order.items.item", "return_order.shipping_method", "return_order.shipping_method.shipping_option"]
920
- });
921
- case 6:
922
- swap = _context15.sent;
923
- returnRequest = swap.return_order;
924
- _context15.next = 10;
925
- return this.lineItemService_.list({
926
- id: returnRequest.items.map(function (_ref11) {
927
- var item_id = _ref11.item_id;
928
- return item_id;
929
- })
930
- }, {
931
- relations: ["tax_lines"]
932
- });
933
- case 10:
934
- items = _context15.sent;
935
- returnRequest.items = returnRequest.items.map(function (item) {
936
- var found = items.find(function (i) {
937
- return i.id === item.item_id;
938
- });
939
- return _objectSpread(_objectSpread({}, item), {}, {
940
- item: found
941
- });
942
- });
943
- swapLink = store.swap_link_template.replace(/\{cart_id\}/, swap.cart_id);
944
- _context15.next = 15;
945
- return this.orderService_.retrieve(swap.order_id, {
946
- select: ["total"],
947
- relations: ["items", "discounts", "discounts.rule", "shipping_address", "swaps", "swaps.additional_items", "swaps.additional_items.tax_lines"]
948
- });
949
- case 15:
950
- order = _context15.sent;
951
- _context15.next = 18;
952
- return this.cartService_.retrieve(swap.cart_id, {
953
- select: ["total", "tax_total", "discount_total", "shipping_total", "subtotal"]
954
- });
955
- case 18:
956
- cart = _context15.sent;
957
- currencyCode = order.currency_code.toUpperCase();
958
- _context15.next = 22;
959
- return Promise.all(cart.items.map( /*#__PURE__*/function () {
960
- var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(i) {
961
- var totals;
962
- return _regeneratorRuntime().wrap(function _callee14$(_context14) {
963
- while (1) switch (_context14.prev = _context14.next) {
964
- case 0:
965
- _context14.next = 2;
966
- return _this4.totalsService_.getLineItemTotals(i, cart, {
967
- include_tax: true
968
- });
969
- case 2:
970
- totals = _context14.sent;
971
- return _context14.abrupt("return", _objectSpread(_objectSpread({}, i), {}, {
972
- totals: totals,
973
- price: _this4.humanPrice_(totals.subtotal + totals.tax_total, currencyCode)
974
- }));
975
- case 4:
976
- case "end":
977
- return _context14.stop();
978
- }
979
- }, _callee14);
980
- }));
981
- return function (_x28) {
982
- return _ref12.apply(this, arguments);
503
+ descriptor: `${gc.value} ${currencyCode}`,
983
504
  };
984
- }()));
985
- case 22:
986
- decoratedItems = _context15.sent;
987
- returnTotal = decoratedItems.reduce(function (acc, next) {
988
- if (next.is_return) {
989
- return acc + -1 * (next.totals.subtotal + next.totals.tax_total);
990
- }
991
- return acc;
992
- }, 0);
993
- additionalTotal = decoratedItems.reduce(function (acc, next) {
994
- if (!next.is_return) {
995
- return acc + next.totals.subtotal + next.totals.tax_total;
996
- }
997
- return acc;
998
- }, 0);
999
- refundAmount = swap.return_order.refund_amount;
1000
- _context15.next = 28;
1001
- return this.extractLocale(order);
1002
- case 28:
1003
- locale = _context15.sent;
1004
- return _context15.abrupt("return", {
1005
- locale: locale,
1006
- swap: swap,
1007
- order: order,
1008
- return_request: returnRequest,
1009
- date: swap.updated_at.toDateString(),
1010
- swap_link: swapLink,
1011
- email: order.email,
1012
- items: decoratedItems.filter(function (di) {
1013
- return !di.is_return;
1014
- }),
1015
- return_items: decoratedItems.filter(function (di) {
1016
- return di.is_return;
1017
- }),
1018
- return_total: "".concat(this.humanPrice_(returnTotal, currencyCode), " ").concat(currencyCode),
1019
- tax_total: "".concat(this.humanPrice_(cart.total, currencyCode), " ").concat(currencyCode),
1020
- refund_amount: "".concat(this.humanPrice_(refundAmount, currencyCode), " ").concat(currencyCode),
1021
- additional_total: "".concat(this.humanPrice_(additionalTotal, currencyCode), " ").concat(currencyCode)
1022
- });
1023
- case 30:
1024
- case "end":
1025
- return _context15.stop();
1026
- }
1027
- }, _callee15, this);
1028
- }));
1029
- function swapReceivedData(_x27) {
1030
- return _swapReceivedData.apply(this, arguments);
1031
- }
1032
- return swapReceivedData;
1033
- }()
1034
- }, {
1035
- key: "swapCreatedData",
1036
- value: function () {
1037
- var _swapCreatedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(_ref13) {
1038
- var _this5 = this;
1039
- var id, store, swap, returnRequest, items, swapLink, order, cart, currencyCode, decoratedItems, returnTotal, additionalTotal, refundAmount, locale;
1040
- return _regeneratorRuntime().wrap(function _callee17$(_context17) {
1041
- while (1) switch (_context17.prev = _context17.next) {
1042
- case 0:
1043
- id = _ref13.id;
1044
- _context17.next = 3;
1045
- return this.storeService_.retrieve();
1046
- case 3:
1047
- store = _context17.sent;
1048
- _context17.next = 6;
1049
- return this.swapService_.retrieve(id, {
1050
- relations: ["additional_items", "additional_items.tax_lines", "return_order", "return_order.items", "return_order.items.item", "return_order.shipping_method", "return_order.shipping_method.shipping_option"]
1051
- });
1052
- case 6:
1053
- swap = _context17.sent;
1054
- returnRequest = swap.return_order;
1055
- _context17.next = 10;
1056
- return this.lineItemService_.list({
1057
- id: returnRequest.items.map(function (_ref14) {
1058
- var item_id = _ref14.item_id;
1059
- return item_id;
1060
- })
1061
- }, {
1062
- relations: ["tax_lines"]
1063
- });
1064
- case 10:
1065
- items = _context17.sent;
1066
- returnRequest.items = returnRequest.items.map(function (item) {
1067
- var found = items.find(function (i) {
1068
- return i.id === item.item_id;
1069
- });
1070
- return _objectSpread(_objectSpread({}, item), {}, {
1071
- item: found
505
+ });
506
+ discounts.concat(giftCards);
507
+ }
508
+ const locale = await this.extractLocale(order);
509
+ // Includes taxes in discount amount
510
+ const discountTotal = items.reduce((acc, i) => {
511
+ return acc + i.totals.original_total - i.totals.total;
512
+ }, 0);
513
+ const discounted_subtotal = items.reduce((acc, i) => {
514
+ return acc + i.totals.total;
515
+ }, 0);
516
+ const subtotal = items.reduce((acc, i) => {
517
+ return acc + i.totals.original_total;
518
+ }, 0);
519
+ const subtotal_ex_tax = items.reduce((total, i) => {
520
+ return total + i.totals.subtotal;
521
+ }, 0);
522
+ return {
523
+ ...order,
524
+ locale,
525
+ has_discounts: order.discounts.length,
526
+ has_gift_cards: order.gift_cards.length,
527
+ date: order.created_at.toDateString(),
528
+ items,
529
+ discounts,
530
+ subtotal_ex_tax: `${this.humanPrice_(subtotal_ex_tax, currencyCode)} ${currencyCode}`,
531
+ subtotal: `${this.humanPrice_(subtotal, currencyCode)} ${currencyCode}`,
532
+ gift_card_total: `${this.humanPrice_(gift_card_total, currencyCode)} ${currencyCode}`,
533
+ tax_total: `${this.humanPrice_(tax_total, currencyCode)} ${currencyCode}`,
534
+ discount_total: `${this.humanPrice_(discountTotal, currencyCode)} ${currencyCode}`,
535
+ shipping_total: `${this.humanPrice_(shipping_total, currencyCode)} ${currencyCode}`,
536
+ total: `${this.humanPrice_(total, currencyCode)} ${currencyCode}`,
537
+ };
538
+ }
539
+ async gcCreatedData({ id }) {
540
+ const giftCard = await this.giftCardService_.retrieve(id, {
541
+ relations: ["region", "order"],
542
+ });
543
+ if (!giftCard.order) {
544
+ return;
545
+ }
546
+ const taxRate = giftCard.region.tax_rate / 100;
547
+ const locale = await this.extractLocale(order);
548
+ return {
549
+ ...giftCard,
550
+ locale,
551
+ email: giftCard.order.email,
552
+ display_value: giftCard.value * (1 + taxRate),
553
+ };
554
+ }
555
+ async returnRequestedData({ id, return_id }) {
556
+ // Fetch the return request
557
+ const returnRequest = await this.returnService_.retrieve(return_id, {
558
+ relations: [
559
+ "items",
560
+ "items.item",
561
+ "items.item.tax_lines",
562
+ "items.item.variant",
563
+ "items.item.variant.product",
564
+ "shipping_method",
565
+ "shipping_method.tax_lines",
566
+ "shipping_method.shipping_option",
567
+ ],
568
+ });
569
+ const items = await this.lineItemService_.list({
570
+ id: returnRequest.items.map(({ item_id }) => item_id),
571
+ }, {
572
+ relations: ["tax_lines"]
573
+ });
574
+ // Fetch the order
575
+ const order = await this.orderService_.retrieve(id, {
576
+ select: ["total"],
577
+ relations: [
578
+ "items",
579
+ "items.tax_lines",
580
+ "discounts",
581
+ "discounts.rule",
582
+ "shipping_address",
583
+ "returns",
584
+ ],
585
+ });
586
+ const currencyCode = order.currency_code.toUpperCase();
587
+ // Calculate which items are in the return
588
+ const returnItems = await Promise.all(returnRequest.items.map(async (i) => {
589
+ const found = items.find((oi) => oi.id === i.item_id);
590
+ found.quantity = i.quantity;
591
+ found.thumbnail = this.normalizeThumbUrl_(found.thumbnail);
592
+ found.totals = await this.totalsService_.getLineItemTotals(found, order, {
593
+ include_tax: true,
594
+ use_tax_lines: true,
595
+ });
596
+ found.price = `${this.humanPrice_(found.totals.total, currencyCode)} ${currencyCode}`;
597
+ found.tax_lines = found.totals.tax_lines;
598
+ return found;
599
+ }));
600
+ // Get total of the returned products
601
+ const item_subtotal = returnItems.reduce((acc, next) => acc + next.totals.total, 0);
602
+ // If the return has a shipping method get the price and any attachments
603
+ let shippingTotal = 0;
604
+ if (returnRequest.shipping_method) {
605
+ const base = returnRequest.shipping_method.price;
606
+ shippingTotal =
607
+ base +
608
+ returnRequest.shipping_method.tax_lines.reduce((acc, next) => {
609
+ return Math.round(acc + base * (next.rate / 100));
610
+ }, 0);
611
+ }
612
+ const locale = await this.extractLocale(order);
613
+ return {
614
+ locale,
615
+ has_shipping: !!returnRequest.shipping_method,
616
+ email: order.email,
617
+ items: returnItems,
618
+ subtotal: `${this.humanPrice_(item_subtotal, currencyCode)} ${currencyCode}`,
619
+ shipping_total: `${this.humanPrice_(shippingTotal, currencyCode)} ${currencyCode}`,
620
+ refund_amount: `${this.humanPrice_(returnRequest.refund_amount, currencyCode)} ${currencyCode}`,
621
+ return_request: {
622
+ ...returnRequest,
623
+ refund_amount: `${this.humanPrice_(returnRequest.refund_amount, currencyCode)} ${currencyCode}`,
624
+ },
625
+ order,
626
+ date: returnRequest.updated_at.toDateString(),
627
+ };
628
+ }
629
+ async swapReceivedData({ id }) {
630
+ const store = await this.storeService_.retrieve();
631
+ const swap = await this.swapService_.retrieve(id, {
632
+ relations: [
633
+ "additional_items",
634
+ "additional_items.tax_lines",
635
+ "return_order",
636
+ "return_order.items",
637
+ "return_order.items.item",
638
+ "return_order.shipping_method",
639
+ "return_order.shipping_method.shipping_option",
640
+ ],
641
+ });
642
+ const returnRequest = swap.return_order;
643
+ const items = await this.lineItemService_.list({
644
+ id: returnRequest.items.map(({ item_id }) => item_id),
645
+ }, {
646
+ relations: ["tax_lines"],
647
+ });
648
+ returnRequest.items = returnRequest.items.map((item) => {
649
+ const found = items.find((i) => i.id === item.item_id);
650
+ return {
651
+ ...item,
652
+ item: found,
653
+ };
654
+ });
655
+ const swapLink = store.swap_link_template.replace(/\{cart_id\}/, swap.cart_id);
656
+ const order = await this.orderService_.retrieve(swap.order_id, {
657
+ select: ["total"],
658
+ relations: [
659
+ "items",
660
+ "discounts",
661
+ "discounts.rule",
662
+ "shipping_address",
663
+ "swaps",
664
+ "swaps.additional_items",
665
+ "swaps.additional_items.tax_lines",
666
+ ],
667
+ });
668
+ const cart = await this.cartService_.retrieve(swap.cart_id, {
669
+ select: [
670
+ "total",
671
+ "tax_total",
672
+ "discount_total",
673
+ "shipping_total",
674
+ "subtotal",
675
+ ],
676
+ });
677
+ const currencyCode = order.currency_code.toUpperCase();
678
+ const decoratedItems = await Promise.all(cart.items.map(async (i) => {
679
+ const totals = await this.totalsService_.getLineItemTotals(i, cart, {
680
+ include_tax: true,
681
+ });
682
+ return {
683
+ ...i,
684
+ totals,
685
+ price: this.humanPrice_(totals.subtotal + totals.tax_total, currencyCode),
686
+ };
687
+ }));
688
+ const returnTotal = decoratedItems.reduce((acc, next) => {
689
+ if (next.is_return) {
690
+ return acc + -1 * (next.totals.subtotal + next.totals.tax_total);
691
+ }
692
+ return acc;
693
+ }, 0);
694
+ const additionalTotal = decoratedItems.reduce((acc, next) => {
695
+ if (!next.is_return) {
696
+ return acc + next.totals.subtotal + next.totals.tax_total;
697
+ }
698
+ return acc;
699
+ }, 0);
700
+ const refundAmount = swap.return_order.refund_amount;
701
+ const locale = await this.extractLocale(order);
702
+ return {
703
+ locale,
704
+ swap,
705
+ order,
706
+ return_request: returnRequest,
707
+ date: swap.updated_at.toDateString(),
708
+ swap_link: swapLink,
709
+ email: order.email,
710
+ items: decoratedItems.filter((di) => !di.is_return),
711
+ return_items: decoratedItems.filter((di) => di.is_return),
712
+ return_total: `${this.humanPrice_(returnTotal, currencyCode)} ${currencyCode}`,
713
+ tax_total: `${this.humanPrice_(cart.total, currencyCode)} ${currencyCode}`,
714
+ refund_amount: `${this.humanPrice_(refundAmount, currencyCode)} ${currencyCode}`,
715
+ additional_total: `${this.humanPrice_(additionalTotal, currencyCode)} ${currencyCode}`,
716
+ };
717
+ }
718
+ async swapCreatedData({ id }) {
719
+ const store = await this.storeService_.retrieve();
720
+ const swap = await this.swapService_.retrieve(id, {
721
+ relations: [
722
+ "additional_items",
723
+ "additional_items.tax_lines",
724
+ "return_order",
725
+ "return_order.items",
726
+ "return_order.items.item",
727
+ "return_order.shipping_method",
728
+ "return_order.shipping_method.shipping_option",
729
+ ],
730
+ });
731
+ const returnRequest = swap.return_order;
732
+ const items = await this.lineItemService_.list({
733
+ id: returnRequest.items.map(({ item_id }) => item_id),
734
+ }, {
735
+ relations: ["tax_lines"],
736
+ });
737
+ returnRequest.items = returnRequest.items.map((item) => {
738
+ const found = items.find((i) => i.id === item.item_id);
739
+ return {
740
+ ...item,
741
+ item: found,
742
+ };
743
+ });
744
+ const swapLink = store.swap_link_template.replace(/\{cart_id\}/, swap.cart_id);
745
+ const order = await this.orderService_.retrieve(swap.order_id, {
746
+ select: ["total"],
747
+ relations: [
748
+ "items",
749
+ "items.tax_lines",
750
+ "discounts",
751
+ "discounts.rule",
752
+ "shipping_address",
753
+ "swaps",
754
+ "swaps.additional_items",
755
+ "swaps.additional_items.tax_lines",
756
+ ],
757
+ });
758
+ const cart = await this.cartService_.retrieve(swap.cart_id, {
759
+ select: [
760
+ "total",
761
+ "tax_total",
762
+ "discount_total",
763
+ "shipping_total",
764
+ "subtotal",
765
+ ],
766
+ });
767
+ const currencyCode = order.currency_code.toUpperCase();
768
+ const decoratedItems = await Promise.all(cart.items.map(async (i) => {
769
+ const totals = await this.totalsService_.getLineItemTotals(i, cart, {
770
+ include_tax: true,
771
+ });
772
+ return {
773
+ ...i,
774
+ totals,
775
+ tax_lines: totals.tax_lines,
776
+ price: `${this.humanPrice_(totals.original_total / i.quantity, currencyCode)} ${currencyCode}`,
777
+ discounted_price: `${this.humanPrice_(totals.total / i.quantity, currencyCode)} ${currencyCode}`,
778
+ };
779
+ }));
780
+ const returnTotal = decoratedItems.reduce((acc, next) => {
781
+ const { total } = next.totals;
782
+ if (next.is_return && next.variant_id) {
783
+ return acc + -1 * total;
784
+ }
785
+ return acc;
786
+ }, 0);
787
+ const additionalTotal = decoratedItems.reduce((acc, next) => {
788
+ const { total } = next.totals;
789
+ if (!next.is_return) {
790
+ return acc + total;
791
+ }
792
+ return acc;
793
+ }, 0);
794
+ const refundAmount = swap.return_order.refund_amount;
795
+ const locale = await this.extractLocale(order);
796
+ return {
797
+ locale,
798
+ swap,
799
+ order,
800
+ return_request: returnRequest,
801
+ date: swap.updated_at.toDateString(),
802
+ swap_link: swapLink,
803
+ email: order.email,
804
+ items: decoratedItems.filter((di) => !di.is_return),
805
+ return_items: decoratedItems.filter((di) => di.is_return),
806
+ return_total: `${this.humanPrice_(returnTotal, currencyCode)} ${currencyCode}`,
807
+ refund_amount: `${this.humanPrice_(refundAmount, currencyCode)} ${currencyCode}`,
808
+ additional_total: `${this.humanPrice_(additionalTotal, currencyCode)} ${currencyCode}`,
809
+ };
810
+ }
811
+ async itemsReturnedData(data) {
812
+ return this.returnRequestedData(data);
813
+ }
814
+ async swapShipmentCreatedData({ id, fulfillment_id }) {
815
+ const swap = await this.swapService_.retrieve(id, {
816
+ relations: [
817
+ "shipping_address",
818
+ "shipping_methods",
819
+ "shipping_methods.tax_lines",
820
+ "additional_items",
821
+ "additional_items.tax_lines",
822
+ "return_order",
823
+ "return_order.items",
824
+ ],
825
+ });
826
+ const order = await this.orderService_.retrieve(swap.order_id, {
827
+ relations: [
828
+ "region",
829
+ "items",
830
+ "items.tax_lines",
831
+ "discounts",
832
+ "discounts.rule",
833
+ "swaps",
834
+ "swaps.additional_items",
835
+ "swaps.additional_items.tax_lines",
836
+ ],
837
+ });
838
+ const cart = await this.cartService_.retrieve(swap.cart_id, {
839
+ select: [
840
+ "total",
841
+ "tax_total",
842
+ "discount_total",
843
+ "shipping_total",
844
+ "subtotal",
845
+ ],
846
+ });
847
+ const returnRequest = swap.return_order;
848
+ const items = await this.lineItemService_.list({
849
+ id: returnRequest.items.map(({ item_id }) => item_id),
850
+ }, {
851
+ relations: ["tax_lines"],
852
+ });
853
+ const taxRate = order.tax_rate / 100;
854
+ const currencyCode = order.currency_code.toUpperCase();
855
+ const returnItems = await Promise.all(swap.return_order.items.map(async (i) => {
856
+ const found = items.find((oi) => oi.id === i.item_id);
857
+ const totals = await this.totalsService_.getLineItemTotals(i, cart, {
858
+ include_tax: true,
859
+ });
860
+ return {
861
+ ...found,
862
+ thumbnail: this.normalizeThumbUrl_(found.thumbnail),
863
+ price: `${this.humanPrice_(totals.original_total / i.quantity, currencyCode)} ${currencyCode}`,
864
+ discounted_price: `${this.humanPrice_(totals.total / i.quantity, currencyCode)} ${currencyCode}`,
865
+ quantity: i.quantity,
866
+ };
867
+ }));
868
+ const returnTotal = await this.totalsService_.getRefundTotal(order, returnItems);
869
+ const constructedOrder = {
870
+ ...order,
871
+ shipping_methods: swap.shipping_methods,
872
+ items: swap.additional_items,
873
+ };
874
+ const additionalTotal = await this.totalsService_.getTotal(constructedOrder);
875
+ const refundAmount = swap.return_order.refund_amount;
876
+ const shipment = await this.fulfillmentService_.retrieve(fulfillment_id, {
877
+ relations: ["tracking_links"],
878
+ });
879
+ const locale = await this.extractLocale(order);
880
+ return {
881
+ locale,
882
+ swap,
883
+ order,
884
+ items: await Promise.all(swap.additional_items.map(async (i) => {
885
+ const totals = await this.totalsService_.getLineItemTotals(i, cart, {
886
+ include_tax: true,
1072
887
  });
1073
- });
1074
- swapLink = store.swap_link_template.replace(/\{cart_id\}/, swap.cart_id);
1075
- _context17.next = 15;
1076
- return this.orderService_.retrieve(swap.order_id, {
1077
- select: ["total"],
1078
- relations: ["items", "items.tax_lines", "discounts", "discounts.rule", "shipping_address", "swaps", "swaps.additional_items", "swaps.additional_items.tax_lines"]
1079
- });
1080
- case 15:
1081
- order = _context17.sent;
1082
- _context17.next = 18;
1083
- return this.cartService_.retrieve(swap.cart_id, {
1084
- select: ["total", "tax_total", "discount_total", "shipping_total", "subtotal"]
1085
- });
1086
- case 18:
1087
- cart = _context17.sent;
1088
- currencyCode = order.currency_code.toUpperCase();
1089
- _context17.next = 22;
1090
- return Promise.all(cart.items.map( /*#__PURE__*/function () {
1091
- var _ref15 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(i) {
1092
- var totals;
1093
- return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1094
- while (1) switch (_context16.prev = _context16.next) {
1095
- case 0:
1096
- _context16.next = 2;
1097
- return _this5.totalsService_.getLineItemTotals(i, cart, {
1098
- include_tax: true
1099
- });
1100
- case 2:
1101
- totals = _context16.sent;
1102
- return _context16.abrupt("return", _objectSpread(_objectSpread({}, i), {}, {
1103
- totals: totals,
1104
- tax_lines: totals.tax_lines,
1105
- price: "".concat(_this5.humanPrice_(totals.original_total / i.quantity, currencyCode), " ").concat(currencyCode),
1106
- discounted_price: "".concat(_this5.humanPrice_(totals.total / i.quantity, currencyCode), " ").concat(currencyCode)
1107
- }));
1108
- case 4:
1109
- case "end":
1110
- return _context16.stop();
1111
- }
1112
- }, _callee16);
1113
- }));
1114
- return function (_x30) {
1115
- return _ref15.apply(this, arguments);
1116
- };
1117
- }()));
1118
- case 22:
1119
- decoratedItems = _context17.sent;
1120
- returnTotal = decoratedItems.reduce(function (acc, next) {
1121
- var total = next.totals.total;
1122
- if (next.is_return && next.variant_id) {
1123
- return acc + -1 * total;
1124
- }
1125
- return acc;
1126
- }, 0);
1127
- additionalTotal = decoratedItems.reduce(function (acc, next) {
1128
- var total = next.totals.total;
1129
- if (!next.is_return) {
1130
- return acc + total;
1131
- }
1132
- return acc;
1133
- }, 0);
1134
- refundAmount = swap.return_order.refund_amount;
1135
- _context17.next = 28;
1136
- return this.extractLocale(order);
1137
- case 28:
1138
- locale = _context17.sent;
1139
- return _context17.abrupt("return", {
1140
- locale: locale,
1141
- swap: swap,
1142
- order: order,
1143
- return_request: returnRequest,
1144
- date: swap.updated_at.toDateString(),
1145
- swap_link: swapLink,
1146
- email: order.email,
1147
- items: decoratedItems.filter(function (di) {
1148
- return !di.is_return;
1149
- }),
1150
- return_items: decoratedItems.filter(function (di) {
1151
- return di.is_return;
1152
- }),
1153
- return_total: "".concat(this.humanPrice_(returnTotal, currencyCode), " ").concat(currencyCode),
1154
- refund_amount: "".concat(this.humanPrice_(refundAmount, currencyCode), " ").concat(currencyCode),
1155
- additional_total: "".concat(this.humanPrice_(additionalTotal, currencyCode), " ").concat(currencyCode)
1156
- });
1157
- case 30:
1158
- case "end":
1159
- return _context17.stop();
1160
- }
1161
- }, _callee17, this);
1162
- }));
1163
- function swapCreatedData(_x29) {
1164
- return _swapCreatedData.apply(this, arguments);
1165
- }
1166
- return swapCreatedData;
1167
- }()
1168
- }, {
1169
- key: "itemsReturnedData",
1170
- value: function () {
1171
- var _itemsReturnedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(data) {
1172
- return _regeneratorRuntime().wrap(function _callee18$(_context18) {
1173
- while (1) switch (_context18.prev = _context18.next) {
1174
- case 0:
1175
- return _context18.abrupt("return", this.returnRequestedData(data));
1176
- case 1:
1177
- case "end":
1178
- return _context18.stop();
1179
- }
1180
- }, _callee18, this);
1181
- }));
1182
- function itemsReturnedData(_x31) {
1183
- return _itemsReturnedData.apply(this, arguments);
1184
- }
1185
- return itemsReturnedData;
1186
- }()
1187
- }, {
1188
- key: "swapShipmentCreatedData",
1189
- value: function () {
1190
- var _swapShipmentCreatedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21(_ref16) {
1191
- var _this6 = this;
1192
- var id, fulfillment_id, swap, order, cart, returnRequest, items, taxRate, currencyCode, returnItems, returnTotal, constructedOrder, additionalTotal, refundAmount, shipment, locale;
1193
- return _regeneratorRuntime().wrap(function _callee21$(_context21) {
1194
- while (1) switch (_context21.prev = _context21.next) {
1195
- case 0:
1196
- id = _ref16.id, fulfillment_id = _ref16.fulfillment_id;
1197
- _context21.next = 3;
1198
- return this.swapService_.retrieve(id, {
1199
- relations: ["shipping_address", "shipping_methods", "shipping_methods.tax_lines", "additional_items", "additional_items.tax_lines", "return_order", "return_order.items"]
1200
- });
1201
- case 3:
1202
- swap = _context21.sent;
1203
- _context21.next = 6;
1204
- return this.orderService_.retrieve(swap.order_id, {
1205
- relations: ["region", "items", "items.tax_lines", "discounts", "discounts.rule", "swaps", "swaps.additional_items", "swaps.additional_items.tax_lines"]
1206
- });
1207
- case 6:
1208
- order = _context21.sent;
1209
- _context21.next = 9;
1210
- return this.cartService_.retrieve(swap.cart_id, {
1211
- select: ["total", "tax_total", "discount_total", "shipping_total", "subtotal"]
1212
- });
1213
- case 9:
1214
- cart = _context21.sent;
1215
- returnRequest = swap.return_order;
1216
- _context21.next = 13;
1217
- return this.lineItemService_.list({
1218
- id: returnRequest.items.map(function (_ref17) {
1219
- var item_id = _ref17.item_id;
1220
- return item_id;
1221
- })
1222
- }, {
1223
- relations: ["tax_lines"]
1224
- });
1225
- case 13:
1226
- items = _context21.sent;
1227
- taxRate = order.tax_rate / 100;
1228
- currencyCode = order.currency_code.toUpperCase();
1229
- _context21.next = 18;
1230
- return Promise.all(swap.return_order.items.map( /*#__PURE__*/function () {
1231
- var _ref18 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19(i) {
1232
- var found, totals;
1233
- return _regeneratorRuntime().wrap(function _callee19$(_context19) {
1234
- while (1) switch (_context19.prev = _context19.next) {
1235
- case 0:
1236
- found = items.find(function (oi) {
1237
- return oi.id === i.item_id;
1238
- });
1239
- _context19.next = 3;
1240
- return _this6.totalsService_.getLineItemTotals(i, cart, {
1241
- include_tax: true
1242
- });
1243
- case 3:
1244
- totals = _context19.sent;
1245
- return _context19.abrupt("return", _objectSpread(_objectSpread({}, found), {}, {
1246
- thumbnail: _this6.normalizeThumbUrl_(found.thumbnail),
1247
- price: "".concat(_this6.humanPrice_(totals.original_total / i.quantity, currencyCode), " ").concat(currencyCode),
1248
- discounted_price: "".concat(_this6.humanPrice_(totals.total / i.quantity, currencyCode), " ").concat(currencyCode),
1249
- quantity: i.quantity
1250
- }));
1251
- case 5:
1252
- case "end":
1253
- return _context19.stop();
1254
- }
1255
- }, _callee19);
1256
- }));
1257
- return function (_x33) {
1258
- return _ref18.apply(this, arguments);
1259
- };
1260
- }()));
1261
- case 18:
1262
- returnItems = _context21.sent;
1263
- _context21.next = 21;
1264
- return this.totalsService_.getRefundTotal(order, returnItems);
1265
- case 21:
1266
- returnTotal = _context21.sent;
1267
- constructedOrder = _objectSpread(_objectSpread({}, order), {}, {
1268
- shipping_methods: swap.shipping_methods,
1269
- items: swap.additional_items
1270
- });
1271
- _context21.next = 25;
1272
- return this.totalsService_.getTotal(constructedOrder);
1273
- case 25:
1274
- additionalTotal = _context21.sent;
1275
- refundAmount = swap.return_order.refund_amount;
1276
- _context21.next = 29;
1277
- return this.fulfillmentService_.retrieve(fulfillment_id, {
1278
- relations: ["tracking_links"]
1279
- });
1280
- case 29:
1281
- shipment = _context21.sent;
1282
- _context21.next = 32;
1283
- return this.extractLocale(order);
1284
- case 32:
1285
- locale = _context21.sent;
1286
- _context21.t0 = locale;
1287
- _context21.t1 = swap;
1288
- _context21.t2 = order;
1289
- _context21.next = 38;
1290
- return Promise.all(swap.additional_items.map( /*#__PURE__*/function () {
1291
- var _ref19 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(i) {
1292
- var totals;
1293
- return _regeneratorRuntime().wrap(function _callee20$(_context20) {
1294
- while (1) switch (_context20.prev = _context20.next) {
1295
- case 0:
1296
- _context20.next = 2;
1297
- return _this6.totalsService_.getLineItemTotals(i, cart, {
1298
- include_tax: true
1299
- });
1300
- case 2:
1301
- totals = _context20.sent;
1302
- return _context20.abrupt("return", _objectSpread(_objectSpread({}, i), {}, {
1303
- thumbnail: _this6.normalizeThumbUrl_(i.thumbnail),
1304
- price: "".concat(_this6.humanPrice_(totals.original_total / i.quantity, currencyCode), " ").concat(currencyCode),
1305
- discounted_price: "".concat(_this6.humanPrice_(totals.total / i.quantity, currencyCode), " ").concat(currencyCode),
1306
- quantity: i.quantity
1307
- }));
1308
- case 4:
1309
- case "end":
1310
- return _context20.stop();
1311
- }
1312
- }, _callee20);
1313
- }));
1314
- return function (_x34) {
1315
- return _ref19.apply(this, arguments);
888
+ return {
889
+ ...i,
890
+ thumbnail: this.normalizeThumbUrl_(i.thumbnail),
891
+ price: `${this.humanPrice_(totals.original_total / i.quantity, currencyCode)} ${currencyCode}`,
892
+ discounted_price: `${this.humanPrice_(totals.total / i.quantity, currencyCode)} ${currencyCode}`,
893
+ quantity: i.quantity,
1316
894
  };
1317
- }()));
1318
- case 38:
1319
- _context21.t3 = _context21.sent;
1320
- _context21.t4 = swap.updated_at.toDateString();
1321
- _context21.t5 = order.email;
1322
- _context21.t6 = "".concat(this.humanPrice_(cart.tax_total, currencyCode), " ").concat(currencyCode);
1323
- _context21.t7 = "".concat(this.humanPrice_(swap.difference_due, currencyCode), " ").concat(currencyCode);
1324
- _context21.t8 = "".concat(this.humanPrice_(returnTotal, currencyCode), " ").concat(currencyCode);
1325
- _context21.t9 = "".concat(this.humanPrice_(refundAmount, currencyCode), " ").concat(currencyCode);
1326
- _context21.t10 = "".concat(this.humanPrice_(additionalTotal, currencyCode), " ").concat(currencyCode);
1327
- _context21.t11 = shipment;
1328
- _context21.t12 = shipment.tracking_links;
1329
- _context21.t13 = shipment.tracking_numbers.join(", ");
1330
- return _context21.abrupt("return", {
1331
- locale: _context21.t0,
1332
- swap: _context21.t1,
1333
- order: _context21.t2,
1334
- items: _context21.t3,
1335
- date: _context21.t4,
1336
- email: _context21.t5,
1337
- tax_amount: _context21.t6,
1338
- paid_total: _context21.t7,
1339
- return_total: _context21.t8,
1340
- refund_amount: _context21.t9,
1341
- additional_total: _context21.t10,
1342
- fulfillment: _context21.t11,
1343
- tracking_links: _context21.t12,
1344
- tracking_number: _context21.t13
1345
- });
1346
- case 50:
1347
- case "end":
1348
- return _context21.stop();
1349
- }
1350
- }, _callee21, this);
1351
- }));
1352
- function swapShipmentCreatedData(_x32) {
1353
- return _swapShipmentCreatedData.apply(this, arguments);
1354
- }
1355
- return swapShipmentCreatedData;
1356
- }()
1357
- }, {
1358
- key: "claimShipmentCreatedData",
1359
- value: function () {
1360
- var _claimShipmentCreatedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(_ref20) {
1361
- var id, fulfillment_id, claim, shipment, locale;
1362
- return _regeneratorRuntime().wrap(function _callee22$(_context22) {
1363
- while (1) switch (_context22.prev = _context22.next) {
1364
- case 0:
1365
- id = _ref20.id, fulfillment_id = _ref20.fulfillment_id;
1366
- _context22.next = 3;
1367
- return this.claimService_.retrieve(id, {
1368
- relations: ["order", "order.items", "order.shipping_address"]
1369
- });
1370
- case 3:
1371
- claim = _context22.sent;
1372
- _context22.next = 6;
1373
- return this.fulfillmentService_.retrieve(fulfillment_id, {
1374
- relations: ["tracking_links"]
1375
- });
1376
- case 6:
1377
- shipment = _context22.sent;
1378
- _context22.next = 9;
1379
- return this.extractLocale(claim.order);
1380
- case 9:
1381
- locale = _context22.sent;
1382
- return _context22.abrupt("return", {
1383
- locale: locale,
1384
- email: claim.order.email,
1385
- claim: claim,
1386
- order: claim.order,
1387
- fulfillment: shipment,
1388
- tracking_links: shipment.tracking_links,
1389
- tracking_number: shipment.tracking_numbers.join(", ")
1390
- });
1391
- case 11:
1392
- case "end":
1393
- return _context22.stop();
1394
- }
1395
- }, _callee22, this);
1396
- }));
1397
- function claimShipmentCreatedData(_x35) {
1398
- return _claimShipmentCreatedData.apply(this, arguments);
1399
- }
1400
- return claimShipmentCreatedData;
1401
- }()
1402
- }, {
1403
- key: "restockNotificationData",
1404
- value: function () {
1405
- var _restockNotificationData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23(_ref21) {
1406
- var variant_id, emails, variant, thumb;
1407
- return _regeneratorRuntime().wrap(function _callee23$(_context23) {
1408
- while (1) switch (_context23.prev = _context23.next) {
1409
- case 0:
1410
- variant_id = _ref21.variant_id, emails = _ref21.emails;
1411
- _context23.next = 3;
1412
- return this.productVariantService_.retrieve(variant_id, {
1413
- relations: ["product"]
1414
- });
1415
- case 3:
1416
- variant = _context23.sent;
1417
- if (variant.product.thumbnail) {
1418
- thumb = this.normalizeThumbUrl_(variant.product.thumbnail);
1419
- }
1420
- return _context23.abrupt("return", {
1421
- product: _objectSpread(_objectSpread({}, variant.product), {}, {
1422
- thumbnail: thumb
1423
- }),
1424
- variant: variant,
1425
- variant_id: variant_id,
1426
- emails: emails
1427
- });
1428
- case 6:
1429
- case "end":
1430
- return _context23.stop();
1431
- }
1432
- }, _callee23, this);
1433
- }));
1434
- function restockNotificationData(_x36) {
1435
- return _restockNotificationData.apply(this, arguments);
1436
- }
1437
- return restockNotificationData;
1438
- }()
1439
- }, {
1440
- key: "userPasswordResetData",
1441
- value: function userPasswordResetData(data) {
1442
- return data;
895
+ })),
896
+ date: swap.updated_at.toDateString(),
897
+ email: order.email,
898
+ tax_amount: `${this.humanPrice_(cart.tax_total, currencyCode)} ${currencyCode}`,
899
+ paid_total: `${this.humanPrice_(swap.difference_due, currencyCode)} ${currencyCode}`,
900
+ return_total: `${this.humanPrice_(returnTotal, currencyCode)} ${currencyCode}`,
901
+ refund_amount: `${this.humanPrice_(refundAmount, currencyCode)} ${currencyCode}`,
902
+ additional_total: `${this.humanPrice_(additionalTotal, currencyCode)} ${currencyCode}`,
903
+ fulfillment: shipment,
904
+ tracking_links: shipment.tracking_links,
905
+ tracking_number: shipment.tracking_numbers.join(", "),
906
+ };
1443
907
  }
1444
- }, {
1445
- key: "customerPasswordResetData",
1446
- value: function customerPasswordResetData(data) {
1447
- return data;
908
+ async claimShipmentCreatedData({ id, fulfillment_id }) {
909
+ const claim = await this.claimService_.retrieve(id, {
910
+ relations: ["order", "order.items", "order.shipping_address"],
911
+ });
912
+ const shipment = await this.fulfillmentService_.retrieve(fulfillment_id, {
913
+ relations: ["tracking_links"],
914
+ });
915
+ const locale = await this.extractLocale(claim.order);
916
+ return {
917
+ locale,
918
+ email: claim.order.email,
919
+ claim,
920
+ order: claim.order,
921
+ fulfillment: shipment,
922
+ tracking_links: shipment.tracking_links,
923
+ tracking_number: shipment.tracking_numbers.join(", "),
924
+ };
1448
925
  }
1449
- }, {
1450
- key: "orderRefundCreatedData",
1451
- value: function () {
1452
- var _orderRefundCreatedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(_ref22) {
1453
- var id, refund_id, order, refund;
1454
- return _regeneratorRuntime().wrap(function _callee24$(_context24) {
1455
- while (1) switch (_context24.prev = _context24.next) {
1456
- case 0:
1457
- id = _ref22.id, refund_id = _ref22.refund_id;
1458
- _context24.next = 3;
1459
- return this.orderService_.retrieveWithTotals(id, {
1460
- select: ["total"],
1461
- relations: ["refunds", "items"]
1462
- });
1463
- case 3:
1464
- order = _context24.sent;
1465
- refund = order.refunds.find(function (refund) {
1466
- return refund.id === refund_id;
1467
- });
1468
- return _context24.abrupt("return", {
1469
- order: order,
1470
- refund: refund,
1471
- refund_amount: "".concat(this.humanPrice_(refund.amount, order.currency_code), " ").concat(order.currency_code),
1472
- email: order.email
1473
- });
1474
- case 6:
1475
- case "end":
1476
- return _context24.stop();
1477
- }
1478
- }, _callee24, this);
1479
- }));
1480
- function orderRefundCreatedData(_x37) {
1481
- return _orderRefundCreatedData.apply(this, arguments);
1482
- }
1483
- return orderRefundCreatedData;
1484
- }()
1485
- }, {
1486
- key: "processItems_",
1487
- value: function processItems_(items, taxRate, currencyCode) {
1488
- var _this7 = this;
1489
- return items.map(function (i) {
1490
- return _objectSpread(_objectSpread({}, i), {}, {
1491
- thumbnail: _this7.normalizeThumbUrl_(i.thumbnail),
1492
- price: "".concat(_this7.humanPrice_(i.unit_price * (1 + taxRate), currencyCode), " ").concat(currencyCode)
926
+ async restockNotificationData({ variant_id, emails }) {
927
+ const variant = await this.productVariantService_.retrieve(variant_id, {
928
+ relations: ["product"],
1493
929
  });
1494
- });
930
+ let thumb;
931
+ if (variant.product.thumbnail) {
932
+ thumb = this.normalizeThumbUrl_(variant.product.thumbnail);
933
+ }
934
+ return {
935
+ product: {
936
+ ...variant.product,
937
+ thumbnail: thumb,
938
+ },
939
+ variant,
940
+ variant_id,
941
+ emails,
942
+ };
1495
943
  }
1496
- }, {
1497
- key: "humanPrice_",
1498
- value: function humanPrice_(amount, currency) {
1499
- if (!amount) {
1500
- return "0.00";
1501
- }
1502
- var normalized = (0, _medusaCoreUtils.humanizeAmount)(amount, currency);
1503
- return normalized.toFixed(_medusaCoreUtils.zeroDecimalCurrencies.includes(currency.toLowerCase()) ? 0 : 2);
944
+ userPasswordResetData(data) {
945
+ return data;
1504
946
  }
1505
- }, {
1506
- key: "normalizeThumbUrl_",
1507
- value: function normalizeThumbUrl_(url) {
1508
- if (!url) {
1509
- return null;
1510
- }
1511
- if (url.startsWith("http")) {
947
+ customerPasswordResetData(data) {
948
+ return data;
949
+ }
950
+ async orderRefundCreatedData({ id, refund_id }) {
951
+ const order = await this.orderService_.retrieveWithTotals(id, {
952
+ select: [
953
+ "total",
954
+ ],
955
+ relations: [
956
+ "refunds",
957
+ "items",
958
+ ]
959
+ });
960
+ const refund = order.refunds.find((refund) => refund.id === refund_id);
961
+ return {
962
+ order,
963
+ refund,
964
+ refund_amount: `${this.humanPrice_(refund.amount, order.currency_code)} ${order.currency_code}`,
965
+ email: order.email
966
+ };
967
+ }
968
+ processItems_(items, taxRate, currencyCode) {
969
+ return items.map((i) => {
970
+ return {
971
+ ...i,
972
+ thumbnail: this.normalizeThumbUrl_(i.thumbnail),
973
+ price: `${this.humanPrice_(i.unit_price * (1 + taxRate), currencyCode)} ${currencyCode}`,
974
+ };
975
+ });
976
+ }
977
+ humanPrice_(amount, currency) {
978
+ if (!amount) {
979
+ return "0.00";
980
+ }
981
+ const normalized = (0, utils_1.humanizeAmount)(amount, currency);
982
+ return normalized.toFixed(utils_1.zeroDecimalCurrencies.includes(currency.toLowerCase()) ? 0 : 2);
983
+ }
984
+ normalizeThumbUrl_(url) {
985
+ if (!url) {
986
+ return null;
987
+ }
988
+ if (url.startsWith("http")) {
989
+ return url;
990
+ }
991
+ else if (url.startsWith("//")) {
992
+ return `https:${url}`;
993
+ }
1512
994
  return url;
1513
- } else if (url.startsWith("//")) {
1514
- return "https:".concat(url);
1515
- }
1516
- return url;
1517
995
  }
1518
- }, {
1519
- key: "extractLocale",
1520
- value: function () {
1521
- var _extractLocale = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25(fromOrder) {
1522
- var cart;
1523
- return _regeneratorRuntime().wrap(function _callee25$(_context25) {
1524
- while (1) switch (_context25.prev = _context25.next) {
1525
- case 0:
1526
- if (!fromOrder.cart_id) {
1527
- _context25.next = 14;
1528
- break;
1529
- }
1530
- _context25.prev = 1;
1531
- _context25.next = 4;
1532
- return this.cartService_.retrieve(fromOrder.cart_id, {
1533
- select: ["id", "context"]
1534
- });
1535
- case 4:
1536
- cart = _context25.sent;
1537
- if (!(cart.context && cart.context.locale)) {
1538
- _context25.next = 7;
1539
- break;
1540
- }
1541
- return _context25.abrupt("return", cart.context.locale);
1542
- case 7:
1543
- _context25.next = 14;
1544
- break;
1545
- case 9:
1546
- _context25.prev = 9;
1547
- _context25.t0 = _context25["catch"](1);
1548
- console.log(_context25.t0);
1549
- console.warn("Failed to gather context for order");
1550
- return _context25.abrupt("return", null);
1551
- case 14:
1552
- return _context25.abrupt("return", null);
1553
- case 15:
1554
- case "end":
1555
- return _context25.stop();
1556
- }
1557
- }, _callee25, this, [[1, 9]]);
1558
- }));
1559
- function extractLocale(_x38) {
1560
- return _extractLocale.apply(this, arguments);
1561
- }
1562
- return extractLocale;
1563
- }()
1564
- }]);
1565
- return SESService;
1566
- }(_medusaInterfaces.NotificationService);
1567
- _defineProperty(SESService, "identifier", "ses");
1568
- var _default = SESService;
1569
- exports["default"] = _default;
996
+ async extractLocale(fromOrder) {
997
+ if (fromOrder.cart_id) {
998
+ try {
999
+ const cart = await this.cartService_.retrieve(fromOrder.cart_id, {
1000
+ select: ["id", "context"],
1001
+ });
1002
+ if (cart.context && cart.context.locale) {
1003
+ return cart.context.locale;
1004
+ }
1005
+ }
1006
+ catch (err) {
1007
+ console.log(err);
1008
+ console.warn("Failed to gather context for order");
1009
+ return null;
1010
+ }
1011
+ }
1012
+ return null;
1013
+ }
1014
+ }
1015
+ SESService.identifier = "ses";
1016
+ exports.default = SESService;
1017
+ //# sourceMappingURL=ses.js.map