@pisell/pisellos
Version:
一个可扩展的前端模块化SDK框架,支持插件系统
786 lines (757 loc) • 51.9 kB
JavaScript
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError("Cannot destructure " + obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _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 e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { BaseModule } from "../../modules/BaseModule";
import { DiscountModule } from "../../modules/Discount";
import { RulesModule } from "../../modules/Rules";
import { filterDiscountListByBookingTime as _filterDiscountListByBookingTime, isAllNormalProduct } from "./utils";
import Decimal from 'decimal.js';
import { isBoolean } from 'lodash-es';
export var ShopDiscountImpl = /*#__PURE__*/function (_BaseModule) {
_inherits(ShopDiscountImpl, _BaseModule);
var _super = _createSuper(ShopDiscountImpl);
function ShopDiscountImpl(name, version) {
var _this;
_classCallCheck(this, ShopDiscountImpl);
_this = _super.call(this, name, version);
// 初始化所有必要的状态属性
_defineProperty(_assertThisInitialized(_this), "defaultName", 'shopDiscount');
_defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0');
_defineProperty(_assertThisInitialized(_this), "isSolution", true);
_defineProperty(_assertThisInitialized(_this), "request", void 0);
_defineProperty(_assertThisInitialized(_this), "window", void 0);
_defineProperty(_assertThisInitialized(_this), "store", void 0);
_defineProperty(_assertThisInitialized(_this), "options", {});
_defineProperty(_assertThisInitialized(_this), "hooks", void 0);
_this.store = {
customer: null,
productList: [],
discount: null,
rules: null,
holders: [],
originalDiscountList: [],
currentBookingTime: "",
filteredDiscountList: [],
bookingSubject: undefined,
orderTotalAmount: 0
};
return _this;
}
// =========== 生命周期方法 ===========
_createClass(ShopDiscountImpl, [{
key: "initialize",
value: function () {
var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) {
var _options$otherParams;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
this.core = core;
this.options = options;
this.store = _objectSpread(_objectSpread({}, this.store), options.store || {});
this.hooks = (_options$otherParams = options.otherParams) === null || _options$otherParams === void 0 || (_options$otherParams = _options$otherParams.rules) === null || _options$otherParams === void 0 ? void 0 : _options$otherParams.hooks;
console.log('[ShopDiscount] 初始化完成');
// 获取依赖的插件
this.initializePlugins();
// 注册依赖模块
this.registerDependentModules();
// 注册事件监听
this.registerEventListeners();
case 8:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function initialize(_x, _x2) {
return _initialize.apply(this, arguments);
}
return initialize;
}()
}, {
key: "destroy",
value: function () {
var _destroy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var _this$store$discount, _this$store$rules;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
this.store.productList = [];
this.store.customer = null;
(_this$store$discount = this.store.discount) === null || _this$store$discount === void 0 || _this$store$discount.destroy();
(_this$store$rules = this.store.rules) === null || _this$store$rules === void 0 || _this$store$rules.destroy();
this.core.effects.offByModuleDestroy(this.name);
_context2.next = 7;
return this.core.effects.emit("".concat(this.name, ":onDestroy"), {});
case 7:
console.log('[ShopDiscount] 已销毁');
case 8:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function destroy() {
return _destroy.apply(this, arguments);
}
return destroy;
}()
}, {
key: "clear",
value: function () {
var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
var _this$store$discount2, _this$store$rules2;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
this.store.productList = [];
this.store.customer = null;
(_this$store$discount2 = this.store.discount) === null || _this$store$discount2 === void 0 || _this$store$discount2.clear();
(_this$store$rules2 = this.store.rules) === null || _this$store$rules2 === void 0 || _this$store$rules2.clear();
console.log('[ShopDiscount] clear');
case 5:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
function clear() {
return _clear.apply(this, arguments);
}
return clear;
}() // =========== 初始化辅助方法 ===========
}, {
key: "initializePlugins",
value: function initializePlugins() {
this.request = this.core.getPlugin('request');
this.window = this.core.getPlugin('window');
if (!this.request) {
throw new Error('ShopDiscount需要 request 插件支持');
}
if (!this.window) {
throw new Error('ShopDiscount需要 window 插件支持');
}
}
}, {
key: "registerDependentModules",
value: function registerDependentModules() {
var _this$options$otherPa, _targetCacheData, _this$options$otherPa2, _this$options$otherPa3, _this$options$otherPa4, _this$options$otherPa5;
// 如果有传 cacheid,默认需要收集上面这些模块里用户操作选中的数据
// 并且在上面 registerModule 的时候,读取 sessionStroage 里的数据,塞进默认值
var targetCacheData = {};
if ((_this$options$otherPa = this.options.otherParams) !== null && _this$options$otherPa !== void 0 && _this$options$otherPa.cacheId) {
var sessionData = this.window.sessionStorage.getItem(this.name);
if (sessionData) {
var data = JSON.parse(sessionData);
targetCacheData = data[this.options.otherParams.cacheId];
}
}
// 注册优惠模块
var discount = new DiscountModule("".concat(this.name, "_discount"));
this.core.registerModule(discount, {
initialState: (_targetCacheData = targetCacheData) === null || _targetCacheData === void 0 ? void 0 : _targetCacheData[discount.name],
hooks: (_this$options$otherPa2 = this.options.otherParams) === null || _this$options$otherPa2 === void 0 || (_this$options$otherPa2 = _this$options$otherPa2.discount) === null || _this$options$otherPa2 === void 0 ? void 0 : _this$options$otherPa2.hooks,
otherParams: {
fatherModule: this.name,
openCache: (_this$options$otherPa3 = this.options.otherParams) !== null && _this$options$otherPa3 !== void 0 && _this$options$otherPa3.cacheId ? true : false,
cacheId: (_this$options$otherPa4 = this.options.otherParams) === null || _this$options$otherPa4 === void 0 ? void 0 : _this$options$otherPa4.cacheId
}
});
this.store.discount = discount;
// 注册规则模块
var rules = new RulesModule("".concat(this.name, "_rules"));
this.core.registerModule(rules, {
hooks: (_this$options$otherPa5 = this.options.otherParams) === null || _this$options$otherPa5 === void 0 || (_this$options$otherPa5 = _this$options$otherPa5.rules) === null || _this$options$otherPa5 === void 0 ? void 0 : _this$options$otherPa5.hooks
});
this.store.rules = rules;
}
}, {
key: "registerEventListeners",
value: function registerEventListeners() {
var _this2 = this;
this.core.effects.only("".concat(this.name, ":onCustomerChange"), function (customer) {
var _this2$options$otherP;
if ((_this2$options$otherP = _this2.options.otherParams) !== null && _this2$options$otherP !== void 0 && _this2$options$otherP.cacheId && _this2.getDiscountList().length) {
return;
}
_this2.loadPrepareConfig({
customerId: customer.id,
action: 'create',
with_good_pass: 1,
with_discount_card: 1
});
});
}
// =========== 公共 API ===========
// 设置预约时间
// public async setBookingTime(bookingTime: string | null): Promise<void> {
// if (this.store.currentBookingTime !== bookingTime) {
// this.store.currentBookingTime = bookingTime;
//
// // 更新过滤后的优惠券列表
// await this.updateFilteredDiscountList();
// }
// }
// 获取当前预约时间
}, {
key: "getCurrentBookingTime",
value: function getCurrentBookingTime() {
return this.store.currentBookingTime;
}
// 根据预约时间过滤优惠券列表
}, {
key: "filterDiscountListByBookingTime",
value: function filterDiscountListByBookingTime(discountList, bookingTime) {
// 如果全部是普通商品,不需要过滤,直接返回当前数据
if (isAllNormalProduct(this.store.productList || [])) {
return discountList;
}
// 否则使用 bookingTime 进行过滤
return _filterDiscountListByBookingTime(discountList, bookingTime);
}
// 更新过滤后的优惠券列表
// private async updateFilteredDiscountList(): Promise<void> {
// const originalList = this.store.originalDiscountList;
// const filteredList = this.filterDiscountListByBookingTime(originalList, this.store.currentBookingTime);
//
// this.store.filteredDiscountList = filteredList;
//
// // 更新 DiscountModule 中的优惠券列表
// this.setDiscountList(filteredList);
//
// if (this.store.productList?.length) {
// const result = this.calcDiscount(this.store.productList);
// await this.core.effects.emit(
// ShopDiscountHooks.onLoadPrepareCalcResult,
// result,
// );
// }
// }
// 设置客户
}, {
key: "setCustomer",
value: function () {
var _setCustomer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(customer) {
var _this$store$customer;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
if (!(((_this$store$customer = this.store.customer) === null || _this$store$customer === void 0 ? void 0 : _this$store$customer.id) !== customer.id)) {
_context4.next = 4;
break;
}
this.store.customer = customer;
_context4.next = 4;
return this.core.effects.emit("".concat(this.name, ":onCustomerChange"), customer);
case 4:
case "end":
return _context4.stop();
}
}, _callee4, this);
}));
function setCustomer(_x3) {
return _setCustomer.apply(this, arguments);
}
return setCustomer;
}()
}, {
key: "setOriginTotalAmount",
value: function setOriginTotalAmount(amount) {
this.store.orderTotalAmount = amount;
}
// 设置holders
}, {
key: "setHolders",
value: function setHolders(holders) {
this.store.holders = holders;
}
}, {
key: "setBookingSubject",
value: function setBookingSubject(bookingSubject) {
this.store.bookingSubject = bookingSubject;
}
// 计算优惠券
}, {
key: "calcDiscount",
value: function calcDiscount(productList, options) {
var _this$store$bookingSu;
this.store.productList = productList;
var rulesModule = this.core.getModule("".concat(this.name, "_rules"));
if (!rulesModule) {
return {
productList: productList,
discountList: this.getDiscountList()
};
}
var _ref = rulesModule.calcDiscount({
productList: productList,
discountList: this.getDiscountList(),
orderTotalAmount: this.store.orderTotalAmount || 0,
holders: this.store.holders || [],
isFormSubject: ((_this$store$bookingSu = this.store.bookingSubject) === null || _this$store$bookingSu === void 0 ? void 0 : _this$store$bookingSu.type) === 'form'
}, options) || {
productList: productList,
discountList: this.getDiscountList()
},
newProductList = _ref.productList,
newDiscountList = _ref.discountList;
if (newDiscountList) {
newDiscountList = this.setDiscountList(newDiscountList);
}
return {
productList: newProductList || productList,
discountList: newDiscountList || this.getDiscountList()
};
}
// 设置优惠券使用状态
}, {
key: "setDiscountSelected",
value: function setDiscountSelected(params) {
// 获取当前优惠券列表
var discountList = this.getDiscountList();
// 构建选择操作列表
var selectionOperations = [];
// 主要操作
selectionOperations.push({
discountId: params.discountId,
isSelected: params.isSelected
});
// 如果有批量操作列表,添加到操作列表中
if (params.selectedList && params.selectedList.length > 0) {
selectionOperations.push.apply(selectionOperations, _toConsumableArray(params.selectedList));
}
// 创建选择状态映射(去重处理,后面的操作会覆盖前面的)
var selectionMap = new Map();
selectionOperations.forEach(function (operation) {
selectionMap.set(operation.discountId, operation.isSelected);
});
// 找到需要修改状态的优惠券
var newDiscountList = discountList.map(function (discount) {
if (discount.isEditMode) return discount;
if (selectionMap.has(discount.id)) {
var targetIsSelected = selectionMap.get(discount.id);
return _objectSpread(_objectSpread({}, discount), {}, {
isSelected: targetIsSelected,
// 手动设置不使用
isManualSelect: !targetIsSelected
});
}
return _objectSpread(_objectSpread({}, discount), {}, {
isManualSelect: !(discount !== null && discount !== void 0 && discount.isSelected)
});
});
// 更新优惠券列表
this.setDiscountList(newDiscountList);
return this.calcDiscount(this.store.productList || [], params);
}
}, {
key: "setProductList",
value: function setProductList(productList) {
this.store.productList = productList;
}
// 扫码输入code
}, {
key: "scanCode",
value: function () {
var _scanCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(code, customerId) {
var _this$store$discount3, _this$store$bookingSu2, resultDiscountList, rulesModule, withScanList, currentSelectedDiscountList, _ref2, newProductList, newDiscountList, isAvailable, _this$options$otherPa6;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
_context5.prev = 0;
_context5.next = 3;
return (_this$store$discount3 = this.store.discount) === null || _this$store$discount3 === void 0 ? void 0 : _this$store$discount3.batchSearch(code, customerId);
case 3:
_context5.t0 = _context5.sent;
if (_context5.t0) {
_context5.next = 6;
break;
}
_context5.t0 = [];
case 6:
resultDiscountList = _context5.t0;
rulesModule = this.store.rules;
if (rulesModule) {
_context5.next = 10;
break;
}
return _context5.abrupt("return", {
type: "clientCalc",
isAvailable: false,
productList: this.store.productList || [],
discountList: this.getDiscountList()
});
case 10:
if (resultDiscountList.length) {
_context5.next = 12;
break;
}
return _context5.abrupt("return", {
type: "server",
isAvailable: false,
productList: this.store.productList || [],
discountList: this.getDiscountList()
});
case 12:
withScanList = resultDiscountList.map(function (item) {
return _objectSpread(_objectSpread({}, item), {}, {
isScan: true
});
}); // 如果扫回来的券当前有选中的,则不进行计算
currentSelectedDiscountList = this.getDiscountList().filter(function (n) {
return n.isSelected;
});
if (!(currentSelectedDiscountList.length && currentSelectedDiscountList.some(function (n) {
return withScanList.some(function (m) {
return m.id === n.id;
});
}))) {
_context5.next = 16;
break;
}
return _context5.abrupt("return", {
type: "clientCalc",
isAvailable: true,
productList: this.store.productList || [],
discountList: this.getDiscountList()
});
case 16:
_ref2 = rulesModule.isDiscountListAvailable({
productList: this.store.productList || [],
oldDiscountList: this.getDiscountList(),
newDiscountList: withScanList,
holders: this.store.holders || [],
isFormSubject: ((_this$store$bookingSu2 = this.store.bookingSubject) === null || _this$store$bookingSu2 === void 0 ? void 0 : _this$store$bookingSu2.type) === 'form',
orderTotalAmount: this.store.orderTotalAmount || 0
}) || {
isAvailable: false,
productList: this.store.productList || [],
discountList: this.getDiscountList()
}, newProductList = _ref2.productList, newDiscountList = _ref2.discountList, isAvailable = _ref2.isAvailable;
if (!isAvailable) {
_context5.next = 24;
break;
}
this.setDiscountList(newDiscountList || []);
this.store.originalDiscountList = newDiscountList || [];
this.setProductList(newProductList || []);
if (!(this.isWalkIn() && resultDiscountList.length && ((_this$options$otherPa6 = this.options.otherParams) === null || _this$options$otherPa6 === void 0 ? void 0 : _this$options$otherPa6.platform) === 'shop')) {
_context5.next = 24;
break;
}
_context5.next = 24;
return this.getCustomerWallet(resultDiscountList[0].customer_id);
case 24:
return _context5.abrupt("return", {
type: "clientCalc",
isAvailable: isAvailable || false,
productList: newProductList || this.store.productList || [],
discountList: newDiscountList || this.getDiscountList()
});
case 27:
_context5.prev = 27;
_context5.t1 = _context5["catch"](0);
console.error('[ShopDiscount] 扫码出错:', _context5.t1);
return _context5.abrupt("return", {
type: "clientCalc",
isAvailable: false,
productList: this.store.productList || [],
discountList: this.getDiscountList()
});
case 31:
case "end":
return _context5.stop();
}
}, _callee5, this, [[0, 27]]);
}));
function scanCode(_x4, _x5) {
return _scanCode.apply(this, arguments);
}
return scanCode;
}()
}, {
key: "calcDiscountApplicableProductTotalPrice",
value: function calcDiscountApplicableProductTotalPrice(discount) {
var _this$store$discount4;
return (_this$store$discount4 = this.store.discount) === null || _this$store$discount4 === void 0 ? void 0 : _this$store$discount4.calcDiscountApplicableProductTotalPrice(discount);
}
// =========== 私有辅助方法 ===========
// 获取客户
}, {
key: "getCustomer",
value: function getCustomer() {
return this.store.customer;
}
// 是否是walkIn
}, {
key: "isWalkIn",
value: function isWalkIn() {
var _this$getCustomer;
return (((_this$getCustomer = this.getCustomer()) === null || _this$getCustomer === void 0 ? void 0 : _this$getCustomer.id) || 1) === 1;
}
// 触发优惠列表变更事件
}, {
key: "emitDiscountListChange",
value: function () {
var _emitDiscountListChange = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(discountList) {
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return this.core.effects.emit("".concat(this.name, ":onDiscountListChange"), discountList);
case 2:
case "end":
return _context6.stop();
}
}, _callee6, this);
}));
function emitDiscountListChange(_x6) {
return _emitDiscountListChange.apply(this, arguments);
}
return emitDiscountListChange;
}() // 设置优惠券列表
}, {
key: "setDiscountList",
value: function setDiscountList(discountList) {
var _this3 = this,
_this$store$discount5;
var productList = this.store.productList || [];
var editModeDiscountList = [];
productList.forEach(function (item) {
if (item.booking_id) {
var _this3$hooks;
var product = (_this3$hooks = _this3.hooks) === null || _this3$hooks === void 0 ? void 0 : _this3$hooks.getProduct(item);
(item.discount_list || []).forEach(function (discount) {
if (discount.id && ['good_pass', 'discount_card'].includes(discount.type)) {
var index = editModeDiscountList.findIndex(function (n) {
var _discount$discount;
return n.id === (((_discount$discount = discount.discount) === null || _discount$discount === void 0 ? void 0 : _discount$discount.resource_id) || discount.id);
});
if (index !== -1) {
var _discount$metadata;
editModeDiscountList[index] = _objectSpread(_objectSpread({}, editModeDiscountList[index]), {}, {
amount: new Decimal(discount.amount || 0).plus(new Decimal(editModeDiscountList[index].amount || 0)).toNumber(),
savedAmount: new Decimal(discount.amount || 0).times((product === null || product === void 0 ? void 0 : product.quantity) || (product === null || product === void 0 ? void 0 : product.num) || 1).plus((discount === null || discount === void 0 || (_discount$metadata = discount.metadata) === null || _discount$metadata === void 0 ? void 0 : _discount$metadata.product_discount_difference) || 0).plus(new Decimal(editModeDiscountList[index].savedAmount || 0)).toNumber()
});
} else {
var _discount$metadata2, _discount$discount2, _discount$discount3, _discount$discount4;
if (discount.type && !discount.tag) {
discount.tag = discount.type;
}
editModeDiscountList.push(_objectSpread(_objectSpread({}, discount), {}, {
name: discount.name || discount.discount.title.auto,
isEditMode: true,
limited_relation_product_data: {},
savedAmount: new Decimal(discount.amount || 0).times((product === null || product === void 0 ? void 0 : product.quantity) || (product === null || product === void 0 ? void 0 : product.num) || 1).plus((discount === null || discount === void 0 || (_discount$metadata2 = discount.metadata) === null || _discount$metadata2 === void 0 ? void 0 : _discount$metadata2.product_discount_difference) || 0).toNumber(),
isAvailable: true,
id: ((_discount$discount2 = discount.discount) === null || _discount$discount2 === void 0 ? void 0 : _discount$discount2.resource_id) || discount.id,
format_title: ((_discount$discount3 = discount.discount) === null || _discount$discount3 === void 0 ? void 0 : _discount$discount3.title) || discount.format_title,
isDisabled: true,
isSelected: true,
product_id: ((_discount$discount4 = discount.discount) === null || _discount$discount4 === void 0 ? void 0 : _discount$discount4.product_id) || discount.product_id
}));
}
}
});
}
});
var newDiscountList = [].concat(editModeDiscountList, _toConsumableArray(discountList.filter(function (item) {
return !item.isDisabled;
})));
var isProductFree = function isProductFree(id) {
var _this3$hooks2;
var targetProduct = productList.find(function (n) {
return n.id === id;
});
if (!targetProduct) return false;
var product = (_this3$hooks2 = _this3.hooks) === null || _this3$hooks2 === void 0 ? void 0 : _this3$hooks2.getProduct(targetProduct);
// 如果 product.total 是小于等于0有可能是她已经用过商品券或者折扣卡导致的,或者本身就是负数价格,所以此时还需要判断 origin_total 是否小于等于0
// 如果 product.vouchersApplicable是布尔值,并且是 false,也当做免费商品处理,此商品不可用优惠券或折扣卡
return Number(product === null || product === void 0 ? void 0 : product.total) <= 0 && (Number(product === null || product === void 0 ? void 0 : product.origin_total) <= 0 || !(product !== null && product !== void 0 && product.origin_total)) || isBoolean(product === null || product === void 0 ? void 0 : product.vouchersApplicable) && !(product !== null && product !== void 0 && product.vouchersApplicable);
};
var allUsedProductIds = newDiscountList.filter(function (item) {
return !(item !== null && item !== void 0 && item.isEditMode);
}).map(function (n) {
var _n$appliedProductDeta;
return n.isSelected ? ((_n$appliedProductDeta = n.appliedProductDetails) === null || _n$appliedProductDeta === void 0 ? void 0 : _n$appliedProductDeta.map(function (n) {
var _n$discount;
return (_n$discount = n.discount) === null || _n$discount === void 0 ? void 0 : _n$discount.product_id;
})) || n.product_id : [];
}).flat();
newDiscountList.forEach(function (item) {
var _item$applicableProdu;
var isAllProductUsedOrFree = (_item$applicableProdu = item.applicableProductIds) === null || _item$applicableProdu === void 0 ? void 0 : _item$applicableProdu.every(function (id) {
var _item$applicableProdu2;
// 检查当前 id是否在 item.applicableProductIds 里出现了几次,且要求次数和 item.applicableProductIds 里出现的次数一致
var sameIdTimes = ((_item$applicableProdu2 = item.applicableProductIds) === null || _item$applicableProdu2 === void 0 ? void 0 : _item$applicableProdu2.filter(function (n) {
return n === id;
}).length) || 1;
var targetIdTimes = (allUsedProductIds === null || allUsedProductIds === void 0 ? void 0 : allUsedProductIds.filter(function (n) {
return n === id;
}).length) || 0;
return targetIdTimes >= sameIdTimes || isProductFree(id);
});
if (!item.isSelected && isAllProductUsedOrFree) {
item.isDisabledForProductUsed = true;
} else {
item.isDisabledForProductUsed = false;
}
});
(_this$store$discount5 = this.store.discount) === null || _this$store$discount5 === void 0 || _this$store$discount5.setDiscountList(newDiscountList);
this.emitDiscountListChange(newDiscountList);
return newDiscountList;
}
// 获取优惠券列表
}, {
key: "getDiscountList",
value: function getDiscountList() {
var _this$store$discount6;
return ((_this$store$discount6 = this.store.discount) === null || _this$store$discount6 === void 0 ? void 0 : _this$store$discount6.getDiscountList()) || [];
}
// 获取客户钱包信息
}, {
key: "getCustomerWallet",
value: function () {
var _getCustomerWallet = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(id) {
var _result, customer;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
_context7.prev = 0;
_context7.next = 3;
return this.request.get("/customer/info/".concat(id), {
with_trashed: 1
});
case 3:
_result = _context7.sent;
if (!(_result !== null && _result !== void 0 && _result.data)) {
_context7.next = 9;
break;
}
customer = Object.assign({}, (_objectDestructuringEmpty(_result.data), _result.data));
this.setCustomer(customer);
_context7.next = 9;
return this.core.effects.emit("".concat(this.name, ":onScanCustomerChange"), customer);
case 9:
_context7.next = 14;
break;
case 11:
_context7.prev = 11;
_context7.t0 = _context7["catch"](0);
console.error('[ShopDiscount] 获取客户钱包信息出错:', _context7.t0);
case 14:
case "end":
return _context7.stop();
}
}, _callee7, this, [[0, 11]]);
}));
function getCustomerWallet(_x7) {
return _getCustomerWallet.apply(this, arguments);
}
return getCustomerWallet;
}()
}, {
key: "bestDiscount",
value: function () {
var _bestDiscount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(cb) {
var _this$store$productLi;
var newDiscountList, _result2;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
newDiscountList = this.store.originalDiscountList;
this.setDiscountList(newDiscountList);
if (!((_this$store$productLi = this.store.productList) !== null && _this$store$productLi !== void 0 && _this$store$productLi.length)) {
_context8.next = 7;
break;
}
_result2 = this.calcDiscount(this.store.productList);
cb === null || cb === void 0 || cb(_result2);
_context8.next = 7;
return this.core.effects.emit("".concat(this.name, ":onLoadPrepareCalcResult"), _result2);
case 7:
_context8.next = 9;
return this.core.effects.emit("".concat(this.name, ":onLoadDiscountList"), newDiscountList);
case 9:
case "end":
return _context8.stop();
}
}, _callee8, this);
}));
function bestDiscount(_x8) {
return _bestDiscount.apply(this, arguments);
}
return bestDiscount;
}() // 加载准备配置
}, {
key: "loadPrepareConfig",
value: function () {
var _loadPrepareConfig = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(params) {
var _this$getCustomer2, _this$store$discount7, _this$getDiscountList, _this$store$discount8, _this$store$productLi2, customerId, goodPassList, scanDiscount, scanDiscountIds, newGoodPassList, newDiscountList, filteredDiscountList, _result3;
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
_context9.prev = 0;
customerId = params.customerId || ((_this$getCustomer2 = this.getCustomer()) === null || _this$getCustomer2 === void 0 ? void 0 : _this$getCustomer2.id); // if (customerId === 1 || !customerId) {
// return
// }
_context9.next = 4;
return (_this$store$discount7 = this.store.discount) === null || _this$store$discount7 === void 0 ? void 0 : _this$store$discount7.loadPrepareConfig({
customer_id: customerId,
action: 'create',
with_good_pass: 1,
with_discount_card: 1,
with_wallet_pass_holder: 1,
request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
});
case 4:
goodPassList = _context9.sent;
scanDiscount = (_this$getDiscountList = this.getDiscountList()) === null || _this$getDiscountList === void 0 ? void 0 : _this$getDiscountList.filter(function (item) {
return item.isScan;
}); // goodPassList 里可能有 scanDiscount 重合的部分,goodPassList 需要剔除
scanDiscountIds = scanDiscount.map(function (n) {
return n.id;
});
newGoodPassList = goodPassList === null || goodPassList === void 0 ? void 0 : goodPassList.filter(function (n) {
return !scanDiscountIds.includes(n.id);
});
newDiscountList = [].concat(_toConsumableArray(scanDiscount), _toConsumableArray(newGoodPassList || [])); // 存储原始优惠券列表
this.store.originalDiscountList = newDiscountList;
_context9.next = 12;
return (_this$store$discount8 = this.store.discount) === null || _this$store$discount8 === void 0 ? void 0 : _this$store$discount8.setOriginalDiscountList(newDiscountList);
case 12:
// 根据当前预约时间过滤优惠券列表
filteredDiscountList = this.filterDiscountListByBookingTime(newDiscountList, this.store.currentBookingTime);
this.store.filteredDiscountList = filteredDiscountList;
this.setDiscountList(filteredDiscountList || []);
if (!((_this$store$productLi2 = this.store.productList) !== null && _this$store$productLi2 !== void 0 && _this$store$productLi2.length)) {
_context9.next = 19;
break;
}
_result3 = this.calcDiscount(this.store.productList);
_context9.next = 19;
return this.core.effects.emit("".concat(this.name, ":onLoadPrepareCalcResult"), _result3);
case 19: