UNPKG

@pisell/pisellos

Version:

一个可扩展的前端模块化SDK框架,支持插件系统

792 lines (730 loc) 155 kB
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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _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 { UnavailableReason } from "./types"; import { uniqueById, getDiscountAmount, getDiscountListAmountTotal, getDiscountListAmount, filterDiscountListByBookingTime } from "../../solution/ShopDiscount/utils"; import { getProductOriginTotalPrice, getProductTotalPrice } from "../Cart/utils"; import Decimal from 'decimal.js'; import { isBoolean } from 'lodash-es'; import dayjs from 'dayjs'; import { isOrderLevelFixedAmountDiscount } from "../../solution/ShopDiscount/utils"; import { calculateOrderLevelDiscountAllocation } from "../../solution/ShopDiscount/utils"; 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), "window", void 0); // WindowPlugin 实例 _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; this.window = core.getPlugin('window'); case 4: 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("".concat(this.name, ":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; } }, { key: "getWalletPassEvaluator", value: function getWalletPassEvaluator() { var _this$window$getWalle, _this$window; return (_this$window$getWalle = (_this$window = this.window).getWalletPassEvaluator) === null || _this$window$getWalle === void 0 ? void 0 : _this$window$getWalle.call(_this$window); } // 商品不需要holder,则不需要判断,直接返回true,商品需要holder但是还没填写,那么暂时不使用带有holder的券,直到填写才去匹配 }, { key: "checkHolderMatch", value: function checkHolderMatch(discount, product, holders) { var _discount$holder; // 非表单类型 holder 视为匹配 if (((_discount$holder = discount.holder) === null || _discount$holder === void 0 ? void 0 : _discount$holder.holder_type) !== 'form') return true; // 主预约holder, 目前(20251124)默认只考虑单个holder的情况 var orderHolderId = Array.isArray(holders) && holders.length > 0 ? holders[0].form_record_id : undefined; var productHolderId = Array.isArray(product.holder_id) ? product.holder_id[0] : product.holder_id; // 商品不需要选holder,则不对比holder,直接返回true, if (!product.isNeedHolder) return true; // 商品需要holder,但父预约及商品都无holder,返回false if (!orderHolderId && !productHolderId) return false; // 最终直接匹配 holder 是否相同 return (productHolderId || orderHolderId) === discount.holder.holder_id; } // 判断discountList 是否可以对当前productList生效 }, { key: "isDiscountListAvailable", value: function isDiscountListAvailable(_ref) { var _this2 = this; var oldDiscountList = _ref.oldDiscountList, newDiscountList = _ref.newDiscountList, productList = _ref.productList, orderTotalAmount = _ref.orderTotalAmount, holders = _ref.holders, isFormSubject = _ref.isFormSubject; // 首先检查是否有新的优惠券可应用 if (!newDiscountList || newDiscountList.length === 0) { return { isAvailable: false, discountList: oldDiscountList, productList: productList }; } // 编辑商品已有商品券 if (productList.every(function (item) { var _product$discount_lis; var product = _this2.hooks.getProduct(item); return product.booking_id && (((_product$discount_lis = product.discount_list) === null || _product$discount_lis === void 0 ? void 0 : _product$discount_lis.length) || (newDiscountList[0].tag === 'good_pass' ? product.price == 0 : product.total == 0)); })) { return { isAvailable: false, discountList: oldDiscountList, productList: productList, unavailableReason: UnavailableReason.AlreadyUsed }; } // 合并新旧折扣列表,并计算折扣结果,注意,如果旧折扣里有 isEditMode 为 true 的优惠券,则不合并 // 保留之前扫码得到的商品券(isScan: true) var filteredOldDiscountList = oldDiscountList.filter(function (discount) { return !discount.isEditMode && (discount.tag !== 'good_pass' || discount.isScan); }); var mergedDiscountList = uniqueById([].concat(_toConsumableArray(filteredOldDiscountList), _toConsumableArray(newDiscountList))); var result = this.calcDiscount({ discountList: mergedDiscountList, productList: _toConsumableArray(productList), holders: holders, orderTotalAmount: orderTotalAmount, isFormSubject: isFormSubject }, { 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, bundle = _this2$hooks$getProdu.bundle; var allDiscountList = _toConsumableArray(discount_list || []); (bundle || []).forEach(function (item) { allDiscountList.push.apply(allDiscountList, _toConsumableArray((item === null || item === void 0 ? void 0 : item.discount_list) || [])); }); if (allDiscountList && allDiscountList.length > 0) { // 检查是否有使用新折扣的情况 var usedNewDiscount = allDiscountList.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; } } }); // 如果券不可用,判断不可用原因 var unavailableReason; if (!hasApplicableDiscount) { unavailableReason = this.getUnavailableReason(newDiscountList, productList); } return { isAvailable: hasApplicableDiscount, discountList: hasApplicableDiscount ? result.discountList : oldDiscountList, productList: hasApplicableDiscount ? result.productList : productList, unavailableReason: unavailableReason }; } }, { key: "filterDiscountListByType", value: function filterDiscountListByType(discountList, type) { return (discountList || []).filter(function (item) { return item.type === type || item.tag === type; }); } // 获取券不可用的原因 }, { key: "getUnavailableReason", value: function getUnavailableReason(discountList, productList) { // 检查时间限制 var _iterator = _createForOfIteratorHelper(discountList), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var discount = _step.value; var _iterator3 = _createForOfIteratorHelper(productList), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var item = _step3.value; var product = this.hooks.getProduct(item); var bookingTime = ((product === null || product === void 0 ? void 0 : product.startDate) || dayjs()).format('YYYY-MM-DD HH:mm:ss'); var filteredList = filterDiscountListByBookingTime([discount], bookingTime); if (filteredList.length === 0) { return UnavailableReason.TimeLimit; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } } // 检查商品适用性 } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var _iterator2 = _createForOfIteratorHelper(discountList), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var _discount = _step2.value; var limitedData = _discount.limited_relation_product_data; var hasApplicableProduct = false; var _iterator4 = _createForOfIteratorHelper(productList), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var _limitedData$product_; var _item = _step4.value; var _product = this.hooks.getProduct(_item); if (limitedData.type === 'product_all') { hasApplicableProduct = true; break; } else if ((_limitedData$product_ = limitedData.product_ids) !== null && _limitedData$product_ !== void 0 && _limitedData$product_.includes(_product.id)) { hasApplicableProduct = true; break; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } if (!hasApplicableProduct) { return UnavailableReason.ProductNotApplicable; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return UnavailableReason.Unknown; } }, { key: "calcDiscount", value: function calcDiscount(_ref2, options) { var _this3 = this; var discountList = _ref2.discountList, productList = _ref2.productList, holders = _ref2.holders, isFormSubject = _ref2.isFormSubject, orderTotalAmount = _ref2.orderTotalAmount; var editModeDiscount = []; var addModeDiscount = []; discountList.forEach(function (discount) { if (discount.isEditMode) { editModeDiscount.push(discount); } else { addModeDiscount.push(discount); } }); // 🔥 检查 editModeDiscount 中是否有订单级别的折扣,如果有则禁用 addModeDiscount 中相同 product_id 的折扣卡 var editModeOrderLevelProductIds = new Set(); editModeDiscount.forEach(function (discount) { var _discount$discount2; if (((_discount$discount2 = discount.discount) === null || _discount$discount2 === void 0 ? void 0 : _discount$discount2.discount_calculation_mode) === 'order_level') { var _discount$discount3; editModeOrderLevelProductIds.add(discount === null || discount === void 0 || (_discount$discount3 = discount.discount) === null || _discount$discount3 === void 0 ? void 0 : _discount$discount3.discount_product_id); } }); // 如果存在订单级别的编辑模式折扣,禁用 addModeDiscount 中相同 product_id 的折扣卡 if (editModeOrderLevelProductIds.size > 0) { addModeDiscount.forEach(function (discount) { if (editModeOrderLevelProductIds.has(discount.product_id)) { discount.isDisabled = true; } }); } // 过滤掉手动取消false的优惠券,但仅用于应用优惠逻辑 var filteredDiscountList = addModeDiscount.filter(function (discount) { return !discount.isManualSelect; }); // 🔥 扁平化商品列表:将 bundle 子商品展开为虚拟商品 var flattenProductsWithBundle = function flattenProductsWithBundle(productList) { var flattened = []; productList.forEach(function (originProduct) { var product = _this3.hooks.getProduct(originProduct); // 1. 添加主商品 flattened.push({ type: 'main', originProduct: originProduct, product: product, price: Number(product.price || 0), id: product.id, _id: product._id, parentId: product._id, quantity: product.quantity, num: product.num, booking_id: product.booking_id }); // 2. 展开 bundle 子商品 if (product.bundle && Array.isArray(product.bundle) && product.bundle.length > 0) { product.bundle.forEach(function (bundleItem, bundleIndex) { flattened.push({ type: 'bundle', originProduct: originProduct, parentProduct: product, bundleItem: bundleItem, bundleIndex: bundleIndex, // 虚拟商品属性 price: Number(bundleItem.price || 0), id: bundleItem._bundle_product_id, // 🔥 使用 _bundle_product_id _id: "".concat(product._id, "_bundle_").concat(bundleIndex), parentId: product._id, num: bundleItem.num || 1, quantity: bundleItem.num || 1, total: new Decimal(bundleItem.price || 0).mul(bundleItem.num || 1).toNumber(), origin_total: new Decimal(bundleItem.price || 0).mul(bundleItem.num || 1).toNumber(), original_price: bundleItem.original_price, // 继承主商品属性 booking_id: bundleItem.booking_id, discount_list: bundleItem.discount_list || [] }); }); } }); return flattened; }; // 优惠力度排序,传进来的数据里可能有商品券,也可能有优惠券 // 新的优先级排序规则(从高到低): // 1. 带有Holder的商品券(metadata?.holder?.type === 'custom' && tag === 'good_pass') // 2. 带有Holder的商品级折扣卡(metadata?.holder?.type === 'custom' && tag === 'product_discount_card' && discount_calculation_mode !== 'order_level') // 3. 带有Holder的订单级折扣卡(metadata?.holder?.type === 'custom' && tag === 'product_discount_card' && discount_calculation_mode === 'order_level') // 4. Customer商品券(metadata?.holder?.type !== 'custom' && tag === 'good_pass') // 5. Customer商品级折扣卡(metadata?.holder?.type !== 'custom' && tag === 'product_discount_card' && discount_calculation_mode !== 'order_level') // 6. Customer订单级固定金额折扣(metadata?.holder?.type !== 'custom' && tag === 'product_discount_card' && discount_calculation_mode === 'order_level') // 同一优先级内部:固定金额优先于百分比,金额/折扣力度越大越优先,最后按过期时间排序 var sortedDiscountList = _toConsumableArray(filteredDiscountList).sort(function (a, b) { // 辅助函数:判断是否是带有Holder的优惠券 var isHolderDiscount = function isHolderDiscount(discount) { var _discount$metadata; return ((_discount$metadata = discount.metadata) === null || _discount$metadata === void 0 || (_discount$metadata = _discount$metadata.holder) === null || _discount$metadata === void 0 ? void 0 : _discount$metadata.type) === 'custom'; }; // 辅助函数:判断是否是商品券 var isGoodPass = function isGoodPass(discount) { return discount.tag === 'good_pass'; }; // 辅助函数:判断是否是订单级折扣卡 var isOrderLevelDiscount = function isOrderLevelDiscount(discount) { var _discount$metadata2; return discount.tag === 'product_discount_card' && ((_discount$metadata2 = discount.metadata) === null || _discount$metadata2 === void 0 ? void 0 : _discount$metadata2.discount_calculation_mode) === 'order_level'; }; // 辅助函数:判断是否是商品级折扣卡 var isItemLevelDiscount = function isItemLevelDiscount(discount) { var _discount$metadata3; return discount.tag === 'product_discount_card' && ((_discount$metadata3 = discount.metadata) === null || _discount$metadata3 === void 0 ? void 0 : _discount$metadata3.discount_calculation_mode) !== 'order_level'; }; // 辅助函数:获取优先级(数字越小优先级越高) var getPriority = function getPriority(discount) { var isHolder = isHolderDiscount(discount); if (isHolder) { if (isGoodPass(discount)) return 1; // 带有Holder的商品券 if (isItemLevelDiscount(discount)) return 2; // 带有Holder的商品级折扣卡 if (isOrderLevelDiscount(discount)) return 3; // 带有Holder的订单级折扣卡 } else { if (isGoodPass(discount)) return 4; // Customer商品券 if (isItemLevelDiscount(discount)) return 5; // Customer商品级折扣卡 if (isOrderLevelDiscount(discount)) return 6; // Customer订单级固定金额折扣 } return 7; // 其他情况 }; // 辅助函数:按过期时间比较 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; } // 辅助函数:同类型折扣卡内部排序(固定金额优先于百分比,金额/折扣力度排序) function compareDiscountCardValue(itemA, itemB) { var _itemA$metadata, _itemB$metadata; var typeA = ((_itemA$metadata = itemA.metadata) === null || _itemA$metadata === void 0 ? void 0 : _itemA$metadata.discount_card_type) || 'percent'; var typeB = ((_itemB$metadata = itemB.metadata) === null || _itemB$metadata === void 0 ? void 0 : _itemB$metadata.discount_card_type) || 'percent'; // 1. 固定金额优先于百分比 if (typeA === 'fixed_amount' && typeB === 'percent') return -1; if (typeA === 'percent' && typeB === 'fixed_amount') return 1; // 2. 都是固定金额时,金额越大越优先 if (typeA === 'fixed_amount' && typeB === 'fixed_amount') { if (itemA.par_value !== itemB.par_value) { var valueA = new Decimal(itemA.par_value || 0); var valueB = new Decimal(itemB.par_value || 0); return valueB.minus(valueA).toNumber(); // 金额大的在前 } } // 3. 都是百分比时,折扣越大越优先(par_value越大越优先) if (typeA === 'percent' && typeB === 'percent') { if (itemA.par_value !== itemB.par_value) { var _valueA = new Decimal(100).minus(itemA.par_value || 0); var _valueB = new Decimal(100).minus(itemB.par_value || 0); return _valueA.minus(_valueB).toNumber(); // 折扣大的在前 } } return 0; } // 1. 先按优先级排序 var priorityA = getPriority(a); var priorityB = getPriority(b); if (priorityA !== priorityB) { return priorityA - priorityB; } // 2. 同一优先级内部排序 // 如果是商品券(优先级1或4),按过期时间排序 if (isGoodPass(a) && isGoodPass(b)) { return compareByExpireTime(a, b); } // 如果是折扣卡(优先级2、3、5、6),按折扣力度排序,然后按过期时间 if (a.tag === 'product_discount_card' && b.tag === 'product_discount_card') { var valueCompare = compareDiscountCardValue(a, b); if (valueCompare !== 0) return valueCompare; return compareByExpireTime(a, b); } // 3. 其他情况按照过期时间排序 return compareByExpireTime(a, b); }); // 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) // } // }) // 🔥 扁平化商品列表(包含主商品和bundle子商品) var flattenedList = flattenProductsWithBundle(productList); // 识别出来是不是在编辑的界面里又新增了商品 // 这种情况下,如果有可用的优惠券,也会自动勾选上 var isEditModeAddNewProduct = flattenedList.find(function (n) { return n.booking_id; }) && flattenedList.find(function (n) { return !n.booking_id; }); // 对扁平化后的列表按价格降序排序(用于应用优惠券时优先选择高价商品) var sortedFlattenedList = flattenedList.sort(function (a, b) { var _ref3, _a$original_price, _ref4, _b$original_price; // 子商品优先使用 original_price,主商品使用 price var priceA = new Decimal(a.type === 'bundle' ? (_ref3 = (_a$original_price = a.original_price) !== null && _a$original_price !== void 0 ? _a$original_price : a.price) !== null && _ref3 !== void 0 ? _ref3 : '0' : a.price || '0'); var priceB = new Decimal(b.type === 'bundle' ? (_ref4 = (_b$original_price = b.original_price) !== null && _b$original_price !== void 0 ? _b$original_price : b.price) !== null && _ref4 !== void 0 ? _ref4 : '0' : b.price || '0'); if (priceA.equals(priceB)) { // 价格相同时,主商品优先 if (a.type !== b.type) { return a.type === 'main' ? -1 : 1; } // 都是主商品时,按原有逻辑排序 if (a.type === 'main' && b.type === 'main') { if (a.product.quantity === b.product.quantity) { var _b$product$discount_l, _a$product$discount_l; return (((_b$product$discount_l = b.product.discount_list) === null || _b$product$discount_l === void 0 ? void 0 : _b$product$discount_l.length) || 0) - (((_a$product$discount_l = a.product.discount_list) === null || _a$product$discount_l === void 0 ? void 0 : _a$product$discount_l.length) || 0); } return a.product.quantity - b.product.quantity; } // 都是bundle时,按数量排序 if (a.type === 'bundle' && b.type === 'bundle') { return (a.num || 1) - (b.num || 1); } } return priceB.minus(priceA).toNumber(); }); // 🔥 为每个折扣卡/商品券执行策略检查并附加config var evaluator = this.getWalletPassEvaluator(); if (evaluator) { addModeDiscount.forEach(function (discount) { var discountType = discount.tag || discount.type; // 只对 good_pass 和 discount_card 类型执行策略检查 if (['good_pass', 'discount_card', 'product_discount_card'].includes(discountType)) { var _discount$limited_rel, _discount$limited_rel2; // 转换 discount 为 Voucher 格式 var voucher = { id: discount.id, amount: Number(discount.par_value || 0), balance: Number(discount.balance || 0), type: discountType, product_id: discount.product_id, unified_available_status: 1, available_product_type: (_discount$limited_rel = discount.limited_relation_product_data) === null || _discount$limited_rel === void 0 ? void 0 : _discount$limited_rel.type, available_product_ids: (_discount$limited_rel2 = discount.limited_relation_product_data) === null || _discount$limited_rel2 === void 0 ? void 0 : _discount$limited_rel2.product_ids }; // 转换 sortedFlattenedList 为 Product 格式 var productsForEvaluate = sortedFlattenedList.map(function (item) { return { product_id: item.id, price: item.price || 0, quantity: item.quantity || item.num || 1, selling_price: item.price || 0 }; }); // 调用策略检查 var result = evaluator.checkVoucherAvailability({ orderTotalAmount: orderTotalAmount, products: productsForEvaluate, vouchers: [voucher] }); // 将 config 附加到 discount 对象 if (result.isAvailable) { discount.config = _objectSpread(_objectSpread({}, result.config), {}, { isAvailable: true }); } else { discount.config = { isAvailable: false }; } } }); } /** // 对productList按价格降序排序(用于应用优惠券时优先选择高价商品) 价格相同时使用quantity 排序 const sortedProductList = [...productList].sort((a, b) => { const aProduct = this.hooks.getProduct(a); const bProduct = this.hooks.getProduct(b); const priceA = new Decimal((aProduct.price as string) || '0'); const priceB = new Decimal((bProduct.price as string) || '0'); if (priceA.toNumber() === priceB.toNumber()) { if (aProduct.quantity === bProduct.quantity) { return bProduct.discount_list?.length - aProduct.discount_list?.length; } return aProduct.quantity - bProduct.quantity; } return priceB.toNumber() - priceA.toNumber(); }); */ // 标记已使用的优惠券 var usedDiscounts = new Map(); // 🔥 统计每个 product_id(商品券商品id)已使用的数量,用于 maxUsagePerOrder 限制 var usedProductIdCounts = new Map(); // 🔥 统计每张折扣卡的 applicableProductLimit 已使用次数(跨商品全局计数) var usedDiscountCardLimitCounts = new Map(); // 🔥 预先将 editModeDiscount 中的折扣卡计入 applicableProductLimit 已使用次数 editModeDiscount.forEach(function (discount) { var discountType = discount.tag || discount.type; if (['discount_card', 'product_discount_card'].includes(discountType)) { var _discount$metadata4; var currentCount = usedDiscountCardLimitCounts.get(discount.id) || 0; usedDiscountCardLimitCounts.set(discount.id, currentCount + (((_discount$metadata4 = discount.metadata) === null || _discount$metadata4 === void 0 ? void 0 : _discount$metadata4.num) || 1)); } }); // 记录每个优惠券适用的商品ID var discountApplicability = new Map(); // 记录每个优惠券适用的商品详细信息 var discountApplicableProducts = new Map(); // 初始化每个优惠券的适用性和可抵扣商品 addModeDiscount.forEach(function (discount) { discountApplicability.set(discount.id, []); discountApplicableProducts.set(discount.id, []); }); // 预处理 order_level 固定金额折扣卡的分摊信息 // Map<discountId, Map<productId, { discountAmount, difference }>> var orderLevelDiscountAllocations = new Map(); // 第一步:收集所有被勾选的 order_level 折扣卡及其适用商品 // Map<discountId, Set<flatItemId>> - 记录每个折扣卡适用的商品 var orderLevelDiscountApplicableItems = new Map(); // Map<flatItemId, Set<discountId>> - 记录每个商品可以被哪些折扣卡使用 var itemApplicableDiscounts = new Map(); // 辅助函数:检查商品是否对某个折扣卡可用 var checkItemApplicableForDiscount = function checkItemApplicableForDiscount(flatItem, discount) { var _product2, _product3, _product4, _flatItem$bundleItem, _flatItem$bundleItem2, _product5; var product; if (flatItem.type === 'main') { product = flatItem.product; } else { var _flatItem$parentProdu; product = { _id: flatItem._id, id: flatItem.id, price: flatItem.price, quantity: flatItem.quantity, num: flatItem.num, booking_id: flatItem.booking_id, discount_list: flatItem.discount_list || [], startDate: (_flatItem$parentProdu = flatItem.parentProduct) === null || _flatItem$parentProdu === void 0 ? void 0 : _flatItem$parentProdu.startDate }; } // 编辑的商品使用了优惠券不可用 var isAvailableProduct = flatItem.type === 'main' ? !((_product2 = product) !== null && _product2 !== void 0 && _product2.booking_id && (_product3 = product) !== null && _product3 !== void 0 && (_product3 = _product3.discount_list) !== null && _product3 !== void 0 && _product3.length && (_product4 = product) !== null && _product4 !== void 0 && (_product4 = _product4.discount_list) !== null && _product4 !== void 0 && _product4.every(function (d) { return d.id && ['good_pass', 'discount_card', 'product_discount_card'].includes(d.tag || d.type); })) : !(flatItem !== null && flatItem !== void 0 && flatItem.booking_id && !!(flatItem !== null && flatItem !== void 0 && (_flatItem$bundleItem = flatItem.bundleItem) !== null && _flatItem$bundleItem !== void 0 && (_flatItem$bundleItem = _flatItem$bundleItem.discount_list) !== null && _flatItem$bundleItem !== void 0 && _flatItem$bundleItem.length) && flatItem !== null && flatItem !== void 0 && (_flatItem$bundleItem2 = flatItem.bundleItem) !== null && _flatItem$bundleItem2 !== void 0 && (_flatItem$bundleItem2 = _flatItem$bundleItem2.discount_list) !== null && _flatItem$bundleItem2 !== void 0 && _flatItem$bundleItem2.every(function (d) { return d.id; })); if (!isAvailableProduct) { return false; } // vouchersApplicable 为 false 的商品不参与订单级别折扣均摊 if (isBoolean(product.vouchersApplicable) && !product.vouchersApplicable) { return false; } // 商品价格为0时不可用 if (Number(product.price) <= 0 || !product.price) { return false; } var limitedData = discount.limited_relation_product_data; // 时间限制检查 var timeLimit = !!filterDiscountListByBookingTime([discount], (((_product5 = product) === null || _product5 === void 0 ? void 0 : _product5.startDate) || dayjs()).format('YYYY-MM-DD HH:mm:ss')).length; if (!timeLimit) { return false; } // 判断商品是否适用 var isLimitedProduct = false; if (limitedData.type === 'product_all') { var _limitedData$exclude_; // 全品类,但需要检查是否被排除 if (limitedData.filter === 1 && (_limitedData$exclude_ = limitedData.exclude_product_ids) !== null && _limitedData$exclude_ !== void 0 && _limitedData$exclude_.includes(product.id)) { isLimitedProduct = false; } else { isLimitedProduct = true; } } else if (limitedData.product_ids && limitedData.product_ids.includes(product.id)) { isLimitedProduct = true; } // 套餐规则检查 var isBundleAvailable = _this3.checkPackageSubItemUsageRules(discount, flatItem); return isLimitedProduct && isBundleAvailable; }; // 收集所有被勾选的 order_level 折扣卡及其适用商品 var selectedOrderLevelDiscounts = sortedDiscountList.filter(function (discount) { return isOrderLevelFixedAmountDiscount(discount) && discount.isSelected !== false; }); // 遍历所有被勾选的 order_level 折扣卡,建立双向映射 selectedOrderLevelDiscounts.forEach(function (discount) { var applicableItemIds = new Set(); sortedFlattenedList.forEach(function (flatItem) { if (checkItemApplicableForDiscount(flatItem, discount)) { applicableItemIds.add(flatItem._id); // 记录商品可以被哪些折扣卡使用 if (!itemApplicableDiscounts.has(flatItem._id)) { itemApplicableDiscounts.set(flatItem._id, new Set()); } itemApplicableDiscounts.get(flatItem._id).add(discount.id); } }); orderLevelDiscountApplicableItems.set(discount.id, applicableItemIds); }); // 专属折扣卡定义:限定了特定商品(product_ids),而不是全品类(product_all)的折扣卡 // 如果专属折扣卡被勾选,它适用的商品会被占用,其他折扣卡均摊时应排除这些商品 // Map<flatItemId, discountId> - 记录被占用的商品及其对应的折扣卡 var occupiedItems = new Map(); // 按排序顺序遍历折扣卡,判断哪些是专属折扣卡 selectedOrderLevelDiscounts.forEach(function (discount) { var limitedData = discount.limited_relation_product_data; // 判断是否是专属折扣卡(只能用于特定商品,而不是全品类) var isExclusiveDiscount = limitedData.type !== 'product_all'; if (isExclusiveDiscount) { // 专属折扣卡:它适用的所有商品都会被它占用 var applicableItems = orderLevelDiscountApplicableItems.get(discount.id); if (applicableItems) { applicableItems.forEach(function (itemId) { // 如果商品还没被占用,则标记为被当前折扣卡占用 if (!occupiedItems.has(itemId)) { occupiedItems.set(itemId, discount.id); } }); } } }); console.log('occupiedItems', occupiedItems, 'orderLevelDiscountApplicableItems', orderLevelDiscountApplicableItems); // 🔥 第三步:识别 order_level 折扣卡并预计算分摊(排除被其他专属折扣卡占用的商品) sortedDiscountList.forEach(function (discount) { if (!isOrderLevelFixedAmountDiscount(discount)) { return; } // 收集该折扣卡适用的商品(排除被其他专属折扣卡占用的商品) var applicableProducts = []; sortedFlattenedList.forEach(function (flatItem) { var _flatItem$parentProdu2, _flatItem$parentProdu3, _product$price, _ref5, _flatItem$original_pr; // 🔥 检查该商品是否被其他专属折扣卡占用 var occupyingDiscountId = occupiedItems.get(flatItem._id); if (occupyingDiscountId !== undefined && occupyingDiscountId !== discount.id) { // 该商品被其他专属折扣卡占用,跳过 return; } if (!checkItemApplicableForDiscount(flatItem, discount)) { re