@pisell/pisellos
Version:
一个可扩展的前端模块化SDK框架,支持插件系统
637 lines (597 loc) • 44.1 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 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 _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 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 "../BaseModule";
import { RulesHooks } from "./types";
import { uniqueById } from "../../solution/ShopDiscount/utils";
import { getProductOriginTotalPrice, getProductTotalPrice } from "../Cart/utils";
import Decimal from 'decimal.js';
export var RulesModule = /*#__PURE__*/function (_BaseModule) {
_inherits(RulesModule, _BaseModule);
var _super = _createSuper(RulesModule);
function RulesModule(name, version) {
var _this;
_classCallCheck(this, RulesModule);
_this = _super.call(this, name, version);
_defineProperty(_assertThisInitialized(_this), "defaultName", 'rules');
_defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0');
_defineProperty(_assertThisInitialized(_this), "store", void 0);
_defineProperty(_assertThisInitialized(_this), "hooks", void 0);
_this.hooks = {};
return _this;
}
_createClass(RulesModule, [{
key: "initialize",
value: function () {
var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
this.core = core;
this.hooks = options === null || options === void 0 ? void 0 : options.hooks;
this.store = options === null || options === void 0 ? void 0 : options.store;
case 3:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function initialize(_x, _x2) {
return _initialize.apply(this, arguments);
}
return initialize;
}()
}, {
key: "setRulesList",
value: function () {
var _setRulesList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(rulesList) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
this.store.rulesList = rulesList;
_context2.next = 3;
return this.core.effects.emit(RulesHooks.OnRulesListChange, rulesList);
case 3:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function setRulesList(_x3) {
return _setRulesList.apply(this, arguments);
}
return setRulesList;
}()
}, {
key: "getRulesList",
value: function getRulesList() {
return this.store.rulesList;
}
// 判断discountList 是否可以对当前productList生效
}, {
key: "isDiscountListAvailable",
value: function isDiscountListAvailable(_ref) {
var _this2 = this;
var oldDiscountList = _ref.oldDiscountList,
newDiscountList = _ref.newDiscountList,
productList = _ref.productList;
// 首先检查是否有新的优惠券可应用
if (!newDiscountList || newDiscountList.length === 0) {
return {
isAvailable: false,
discountList: oldDiscountList,
productList: productList
};
}
// 编辑商品已有商品券
if (productList.every(function (item) {
var _item$discount_list;
return item.booking_id && (((_item$discount_list = item.discount_list) === null || _item$discount_list === void 0 ? void 0 : _item$discount_list.length) || item.price == 0);
})) {
return {
isAvailable: false,
discountList: oldDiscountList,
productList: productList
};
}
// 合并新旧折扣列表,并计算折扣结果
var mergedDiscountList = uniqueById(uniqueById([].concat(_toConsumableArray(oldDiscountList), _toConsumableArray(newDiscountList))), 'product_id');
var result = this.calcDiscount({
discountList: mergedDiscountList,
productList: _toConsumableArray(productList)
}, {
scan: true
});
// 检查是否有产品使用了新折扣
var hasApplicableDiscount = false;
var newDiscountIds = newDiscountList.map(function (discount) {
return discount.id;
});
// 遍历处理后的产品列表,检查是否有产品使用了新折扣
result.productList.forEach(function (product) {
var _this2$hooks$getProdu = _this2.hooks.getProduct(product),
discount_list = _this2$hooks$getProdu.discount_list;
if (discount_list && discount_list.length > 0) {
// 检查是否有使用新折扣的情况
var usedNewDiscount = discount_list.some(function (discount) {
var _discount$discount;
return newDiscountIds.includes(discount === null || discount === void 0 || (_discount$discount = discount.discount) === null || _discount$discount === void 0 ? void 0 : _discount$discount.resource_id);
});
if (usedNewDiscount) {
hasApplicableDiscount = true;
}
}
});
return {
isAvailable: hasApplicableDiscount,
discountList: hasApplicableDiscount ? result.discountList : oldDiscountList,
productList: hasApplicableDiscount ? result.productList : productList
};
}
}, {
key: "calcDiscount",
value: function calcDiscount(_ref2, options) {
var _this3 = this;
var discountList = _ref2.discountList,
productList = _ref2.productList;
// 识别出来是不是在编辑的界面里又新增了商品
// 这种情况下,如果有可用的优惠券,也会自动勾选上
var isEditModeAddNewProduct = productList.find(function (n) {
return n.booking_id;
}) && productList.find(function (n) {
return !n.booking_id;
});
var editModeDiscount = [];
var addModeDiscount = [];
discountList.forEach(function (discount) {
if (discount.isEditMode) {
editModeDiscount.push(discount);
} else {
addModeDiscount.push(discount);
}
});
// 过滤掉手动取消false的优惠券,但仅用于应用优惠逻辑
var filteredDiscountList = addModeDiscount.filter(function (discount) {
return !discount.isManualSelect;
});
// 优惠力度排序,传进来的数据里可能有商品券,也可能有优惠券
// 商品券(n.tag=good_pass)视为最优惠(免费),折扣券(n.tag=product_discount_card)按照n.par_value排序
// 如果最后拍出来商品券有多个,或者说没有商品券,但是有多个相同折扣的折扣券(比如 6 折券有 3张),则按照过期时间(n.expire_time)排序
var sortedDiscountList = _toConsumableArray(filteredDiscountList).sort(function (a, b) {
// 1. 商品券优先级最高
if (a.tag === 'good_pass' && b.tag !== 'good_pass') return -1;
if (b.tag === 'good_pass' && a.tag !== 'good_pass') return 1;
// 2. 如果都是商品券或都不是商品券,按照类型和折扣力度排序
if (a.tag === 'good_pass' && b.tag === 'good_pass') {
// 都是商品券,按照过期时间排序
return compareByExpireTime(a, b);
} else if (a.tag === 'product_discount_card' && b.tag === 'product_discount_card') {
// 都是折扣券,按照par_value排序(折扣越大越优先,即par_value越小越优先)
if (a.par_value !== b.par_value) {
var valueA = new Decimal(100).minus(a.par_value || 0);
var valueB = new Decimal(100).minus(b.par_value || 0);
return valueA.minus(valueB).toNumber();
}
// 相同折扣的情况下,按照过期时间排序
return compareByExpireTime(a, b);
}
// 3. 其他情况按照过期时间排序
return compareByExpireTime(a, b);
function compareByExpireTime(itemA, itemB) {
if (itemA.expire_time && itemB.expire_time) {
var timeA = new Date(itemA.expire_time).getTime();
var timeB = new Date(itemB.expire_time).getTime();
return timeA - timeB;
}
// 有过期时间的优先级高于永久的
return itemA.expire_time ? -1 : itemB.expire_time ? 1 : 0;
}
});
// const newProductList = [];
//
// productList.forEach(item => {
// const product = this.hooks.getProduct(item);
// if (product.quantity > 1) {
// for (let i = 1; i < product.quantity; i++) {
// newProductList.push(product)
// }
// } else {
// newProductList.push(item)
// }
// })
// 对productList按价格降序排序(用于应用优惠券时优先选择高价商品) 价格相同时使用quantity 排序
var sortedProductList = _toConsumableArray(productList).sort(function (a, b) {
var aProduct = _this3.hooks.getProduct(a);
var bProduct = _this3.hooks.getProduct(b);
var priceA = new Decimal(aProduct.price || '0');
var priceB = new Decimal(bProduct.price || '0');
if (priceA.toNumber() === priceB.toNumber()) {
if (aProduct.quantity === bProduct.quantity) {
var _bProduct$discount_li, _aProduct$discount_li;
return ((_bProduct$discount_li = bProduct.discount_list) === null || _bProduct$discount_li === void 0 ? void 0 : _bProduct$discount_li.length) - ((_aProduct$discount_li = aProduct.discount_list) === null || _aProduct$discount_li === void 0 ? void 0 : _aProduct$discount_li.length);
}
return aProduct.quantity - bProduct.quantity;
}
return priceB.toNumber() - priceA.toNumber();
});
// 标记已使用的优惠券
var usedDiscounts = new Map();
// 记录每个优惠券适用的商品ID
var discountApplicability = new Map();
// 记录每个优惠券适用的商品详细信息
var discountApplicableProducts = new Map();
// 初始化每个优惠券的适用性和可抵扣商品
addModeDiscount.forEach(function (discount) {
discountApplicability.set(discount.id, []);
discountApplicableProducts.set(discount.id, []);
});
// 处理后的商品列表(按排序后的顺序处理,记录优惠信息)
var processedProductsMap = new Map();
// 记录已应用优惠券的商品信息
var appliedDiscountProducts = new Map();
// 首先遍历所有商品和所有优惠券,确定每个优惠券的适用范围,包括isSelected为false的优惠券
sortedProductList.forEach(function (originProduct) {
var product = _this3.hooks.getProduct(originProduct);
addModeDiscount.forEach(function (discount) {
var _product$discount_lis, _product$discount_lis2;
var limitedData = discount === null || discount === void 0 ? void 0 : discount.limited_relation_product_data;
// 是符合折扣的商品
var isLimitedProduct = limitedData.type === 'product_all' || limitedData.product_ids && limitedData.product_ids.includes(product.id);
// 编辑的商品 使用了优惠券不可用
var isAvailableProduct = !(product !== null && product !== void 0 && product.booking_id && product !== null && product !== void 0 && (_product$discount_lis = product.discount_list) !== null && _product$discount_lis !== void 0 && _product$discount_lis.length && product !== null && product !== void 0 && (_product$discount_lis2 = product.discount_list) !== null && _product$discount_lis2 !== void 0 && _product$discount_lis2.every(function (discount) {
return discount.id && ['good_pass', 'discount_card', 'product_discount_card'].includes(discount.tag || discount.type);
}));
// 判断优惠券是否适用于该商品
if (isAvailableProduct && isLimitedProduct) {
var _discountApplicabilit;
// 记录此优惠券适用的商品
(_discountApplicabilit = discountApplicability.get(discount.id)) === null || _discountApplicabilit === void 0 || _discountApplicabilit.push(product.id);
// 记录可抵扣的商品详情
var applicableProducts = discountApplicableProducts.get(discount.id) || [];
applicableProducts.push({
amount: product.price,
type: discount.tag || discount.type,
tag: discount.tag || discount.type,
discount: {
resource_id: discount.id,
title: discount.format_title,
original_amount: product.origin_total,
pre_value: discount.par_value,
product_id: originProduct.id
},
num: product.num || 1
});
discountApplicableProducts.set(discount.id, applicableProducts);
}
});
});
console.log(sortedProductList, 'sortedProductListsortedProductList');
// 然后再处理应用哪些优惠券,此时只考虑filteredDiscountList中的优惠券
sortedProductList.forEach(function (originProduct, i) {
var _product$discount_lis3, _product$discount_lis4, _product$discount_lis5, _product$discount_lis6, _product$discount_lis7;
var product = _this3.hooks.getProduct(originProduct);
if (product !== null && product !== void 0 && product.booking_id && (_product$discount_lis3 = product.discount_list) !== null && _product$discount_lis3 !== void 0 && _product$discount_lis3.length && product !== null && product !== void 0 && (_product$discount_lis4 = product.discount_list) !== null && _product$discount_lis4 !== void 0 && _product$discount_lis4.every(function (discount) {
return discount.id && ['good_pass', 'discount_card', 'product_discount_card'].includes(discount.tag || discount.type);
})) {
processedProductsMap.set(product._id, [originProduct]);
return;
}
// 找到适用于此商品的所有优惠券,仅考虑isSelected不为false的优惠券
var applicableDiscounts = sortedDiscountList.filter(function (discount) {
// 如果商品价格为 0,其实不需要使用任何优惠券,直接 return true
if (Number(product.price) === 0 || !product.price) return false;
// 如果优惠券已被使用,则跳过
var targetUsedDiscounts = usedDiscounts.get(discount.id);
if (targetUsedDiscounts && (discount.tag || discount.type) === 'good_pass') return false;
var limitedData = discount.limited_relation_product_data;
// 判断优惠券是否适用于该商品
if (limitedData.type === 'product_all') {
return true;
} else if (limitedData.product_ids && limitedData.product_ids.includes(product.id)) {
return true;
}
return false;
});
// 选择第一个适用的优惠券(已经按过期时间排序)
var selectedDiscount = applicableDiscounts[0];
// 如果是手动折扣,则不适用优惠券
var isManualDiscount = typeof product.isManualDiscount === 'boolean' ? product.isManualDiscount : product.total != product.origin_total && (!((_product$discount_lis5 = product.discount_list) !== null && _product$discount_lis5 !== void 0 && _product$discount_lis5.length) || (product === null || product === void 0 || (_product$discount_lis6 = product.discount_list) === null || _product$discount_lis6 === void 0 || (_product$discount_lis7 = _product$discount_lis6.every) === null || _product$discount_lis7 === void 0 ? void 0 : _product$discount_lis7.call(_product$discount_lis6, function (item) {
return item.type === 'product';
})));
// 勾选时覆盖手动折扣
if (options !== null && options !== void 0 && options.discountId && product.discount_list.some(function (item) {
var _item$discount;
return ((_item$discount = item.discount) === null || _item$discount === void 0 ? void 0 : _item$discount.resource_id) === options.discountId;
})) {
isManualDiscount = false;
}
// 如果没有适用的优惠券,或者手动折扣,则不适用优惠券
if (applicableDiscounts.length === 0 || isManualDiscount) {
if (product.isClient) {
processedProductsMap.set(product._id, [_this3.hooks.setProduct(originProduct, _objectSpread(_objectSpread({}, isManualDiscount ? {} : {
origin_total: getProductOriginTotalPrice({
product: {
original_price: product.original_price
},
bundle: product.bundle,
options: product.options
}),
variant: originProduct._productInit.variant,
original_price: originProduct._productInit.original_price,
total: getProductTotalPrice({
product: {
price: product.price
},
bundle: product.bundle,
options: product.options
}),
price: product.price
}), {}, {
discount_list: []
}))]);
} else {
processedProductsMap.set(product._id, [_this3.hooks.setProduct(originProduct, _objectSpread(_objectSpread({}, isManualDiscount ? {} : {
_id: product._id.split('___')[0] + '___' + i,
total: product.origin_total || product.total,
price: product.price
}), {}, {
discount_list: []
}))]);
}
return;
}
if (applicableDiscounts.length && product.booking_id && typeof selectedDiscount.isManualSelect === 'undefined' && !(options !== null && options !== void 0 && options.scan) && !isEditModeAddNewProduct) {
return;
}
// 是否需要拆分
var isNeedSplit = (selectedDiscount.tag || selectedDiscount.type) === 'good_pass';
// 需要拆分出来的数量
var splitCount = isNeedSplit ? Math.min(product.quantity, applicableDiscounts.filter(function (item) {
return (item.tag || item.type) === 'good_pass';
}).length) : 1;
var arr = [];
if (splitCount < product.quantity && isNeedSplit) {
arr.push(_this3.hooks.setProduct(originProduct, {
discount_list: [],
quantity: product.quantity - splitCount,
_id: product._id.split('___')[0]
}));
}
var _loop = function _loop() {
var selectedDiscount = applicableDiscounts[_i];
// 标记优惠券为已使用
usedDiscounts.set(selectedDiscount.id, true);
// 记录实际应用了优惠券的商品信息
var appliedProducts = appliedDiscountProducts.get(selectedDiscount.id) || [];
var targetProductPrice = selectedDiscount.tag === 'good_pass' ? '0' : new Decimal(100).minus(selectedDiscount.par_value || 0).div(100).mul(new Decimal(product.price || 0)).toFixed(2);
var discountDetail = {
amount: selectedDiscount.tag === 'good_pass' ? product.price : new Decimal(product.price || 0).minus(new Decimal(targetProductPrice)).toNumber(),
type: selectedDiscount.tag === 'product_discount_card' ? 'discount_card' : selectedDiscount.tag,
discount: {
resource_id: selectedDiscount.id,
title: selectedDiscount.format_title,
original_amount: product.origin_total || product.price,
product_id: originProduct.id,
percent: selectedDiscount.par_value
},
num: product.num || 1
};
appliedProducts.push(discountDetail);
appliedDiscountProducts.set(selectedDiscount.id, appliedProducts);
// 记录应用了优惠券的商品
// 后续更新价格改为 getProductTotalPrice getProductOriginTotalPrice逻辑
if (product.isClient) {
var _originProduct$_produ;
var variant = (_originProduct$_produ = originProduct._productOrigin.variant) === null || _originProduct$_produ === void 0 ? void 0 : _originProduct$_produ.map(function (n) {
var _originProduct$_produ2;
if (n.id === ((_originProduct$_produ2 = originProduct._productOrigin) === null || _originProduct$_produ2 === void 0 ? void 0 : _originProduct$_produ2.product_variant_id)) {
n.original_price = n.price;
var _targetProductPrice = selectedDiscount.tag === 'good_pass' ? '0' : new Decimal(100).minus(selectedDiscount.par_value || 0).div(100).mul(new Decimal(n.price || 0)).toFixed(2);
n.price = _targetProductPrice;
}
return n;
});
arr.push(_this3.hooks.setProduct(originProduct, {
discount_list: [discountDetail],
price: new Decimal(targetProductPrice).toNumber(),
quantity: isNeedSplit ? 1 : product.quantity,
origin_total: getProductOriginTotalPrice({
product: {
original_price: targetProductPrice
},
bundle: product.bundle,
options: product.options
}),
variant: variant,
original_price: new Decimal(product.price).toNumber(),
total: getProductTotalPrice({
product: {
price: targetProductPrice
},
bundle: product.bundle,
options: product.options
})
}));
} else {
arr.push(_this3.hooks.setProduct(originProduct, {
discount_list: [discountDetail],
_id: product._id.split('___')[0] + "___" + selectedDiscount.id,
price: new Decimal(targetProductPrice).toNumber(),
quantity: isNeedSplit ? 1 : product.quantity,
total: new Decimal(product.origin_total || product.total || 0).minus(new Decimal(product.price || 0).minus(new Decimal(targetProductPrice))).toNumber(),
origin_total: product.origin_total || product.total
}));
}
};
for (var _i = 0; _i < splitCount; _i++) {
_loop();
}
console.log(arr, 'arrarrarr');
processedProductsMap.set(product._id, arr);
});
// 按原始顺序构建处理后的商品列表
var processedProductList = [];
productList.forEach(function (originProduct) {
var product = _this3.hooks.getProduct(originProduct);
var getDefaultProduct = function getDefaultProduct() {
if (product.isClient) {
return _this3.hooks.setProduct(originProduct, {
discount_list: [],
price: product.price,
origin_total: getProductOriginTotalPrice({
product: {
original_price: product.original_price
},
bundle: product.bundle,
options: product.options
}),
variant: originProduct._productInit.variant,
original_price: originProduct._productInit.original_price,
total: getProductTotalPrice({
product: {
price: product.price
},
bundle: product.bundle,
options: product.options
})
});
} else {
return _this3.hooks.setProduct(originProduct, {
discount_list: [],
total: product.total,
origin_total: product.origin_total,
price: product.price
});
}
};
var arr = processedProductsMap.get(product._id);
arr !== null && arr !== void 0 && arr.length ? processedProductList.push.apply(processedProductList, _toConsumableArray(arr)) : processedProductList.push(getDefaultProduct());
});
// 按原始顺序更新优惠券列表,标记已使用和可用的优惠券
var updatedDiscountList = addModeDiscount.map(function (discount) {
// 获取此优惠券适用的商品列表
var applicableProducts = discountApplicability.get(discount.id) || [];
// 获取此优惠券适用的商品详情
var applicableProductDetails = discountApplicableProducts.get(discount.id) || [];
// 获取此优惠券实际应用的商品详情
var appliedProductDetails = appliedDiscountProducts.get(discount.id) || [];
// 根据是否有适用商品决定isAvailable
var isAvailable = applicableProducts.length > 0;
// 如果此优惠券被明确设置为不选中,保持其状态,但正确设置isAvailable
if (typeof discount.isSelected === 'boolean' && discount.isSelected === false && discount.isManualSelect) {
return _objectSpread(_objectSpread({}, discount), {}, {
isSelected: false,
isAvailable: isAvailable,
// 正确设置可用性
applicableProductIds: applicableProducts,
// 添加可抵扣的商品详情
applicableProductDetails: applicableProductDetails,
// 添加实际抵扣的商品详情(对于未选中的优惠券,为空数组)
appliedProductDetails: []
});
}
if (usedDiscounts.get(discount.id)) {
return _objectSpread(_objectSpread({}, discount), {}, {
isSelected: true,
// 标记为可用,因为它已被应用
isAvailable: true,
// 记录适用的商品IDs
applicableProductIds: applicableProducts,
// 添加可抵扣的商品详情
applicableProductDetails: applicableProductDetails,
// 添加实际抵扣的商品详情
appliedProductDetails: appliedProductDetails
});
}
var isSelected = typeof discount.isSelected === 'boolean' ? discount.isSelected : undefined;
// 如果是可用的 并且没有手动标记 则设置为选中
if (isAvailable && appliedProductDetails.length && !discount.isManualSelect) {
isSelected = true;
} else if (!appliedProductDetails.length) {
isSelected = false;
}
return _objectSpread(_objectSpread({}, discount), {}, {
// 如果有适用的商品,标记为可用
isAvailable: isAvailable,
isSelected: isSelected,
// 记录适用的商品IDs
applicableProductIds: applicableProducts,
// 添加可抵扣的商品详情
applicableProductDetails: applicableProductDetails,
// 添加实际抵扣的商品详情(对于未使用的优惠券,为空数组)
appliedProductDetails: []
});
});
console.log(processedProductList, 'processedProductList');
return {
productList: processedProductList,
discountList: [].concat(editModeDiscount, _toConsumableArray(updatedDiscountList))
};
}
}, {
key: "destroy",
value: function () {
var _destroy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
this.core.effects.offByModuleDestroy(this.name);
_context3.next = 3;
return this.core.effects.emit(RulesHooks.OnDestroy, {});
case 3:
console.log('[Rules] 已销毁');
case 4:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
function destroy() {
return _destroy.apply(this, arguments);
}
return destroy;
}()
}, {
key: "clear",
value: function () {
var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
console.log('[Rules] clear');
case 1:
case "end":
return _context4.stop();
}
}, _callee4);
}));
function clear() {
return _clear.apply(this, arguments);
}
return clear;
}()
}]);
return RulesModule;
}(BaseModule);