UNPKG

@pisell/pisellos

Version:

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

830 lines (820 loc) 248 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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } 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 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 { createModule } from "./types"; import { formatProductToCartItem, createCartItemOrigin, getUniqueId, handleVariantProduct, formatDateToCartItem, formatAccountToCartItem } from "../../modules/Cart/utils"; import { getAvailableProductResources, isSessionProduct } from "./utils/products"; import { getResourcesByProduct, getTimeSlicesByResource, getTimeSlicesByResources, getIsUsableByTimeItem, getOthersSelectedResources, getOthersCartSelectedResources, filterScheduleByDateRange, checkSessionProductLeadTime, sortCombinedResources, filterResourcesByFormItem, checkTwoResourcesIntersection, isConflict } from "./utils/resources"; import dayjs from 'dayjs'; import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'; import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'; dayjs.extend(isSameOrBefore); dayjs.extend(isSameOrAfter); import { getResourcesMap } from "../../modules/Resource/utils"; import { cloneDeep } from 'lodash-es'; import { calcCalendarDataByScheduleResult, calcMinTimeMaxTimeBySchedules, getAllSortedDateRanges } from "../../modules/Schedule/utils"; import { handleAvailableDateByResource } from "../../modules/Date/utils"; import { areAllNormalProducts, isNormalProduct } from "../../modules/Product/utils"; import { calculateResourceAvailableTime, filterConditionTimeSlots, findFastestAvailableResource } from "./utils/timeslots"; import { updateAllCartItemPrice } from "../../modules/Cart/utils/changePrice"; import { getCapacityInfoByCartItem, checkSubResourcesCapacity, checkResourceCanUseByCapacity, getResourcesIdsByProduct, checkTimeSlotCapacity } from "./utils/capacity"; import { checkProductStock } from "./utils/stock"; export var BookingByStepImpl = /*#__PURE__*/function (_BaseModule) { _inherits(BookingByStepImpl, _BaseModule); var _super = _createSuper(BookingByStepImpl); function BookingByStepImpl() { var _this; _classCallCheck(this, BookingByStepImpl); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _super.call.apply(_super, [this].concat(args)); _defineProperty(_assertThisInitialized(_this), "defaultName", 'bookingByStep'); _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), "shopStore", void 0); _defineProperty(_assertThisInitialized(_this), "store", void 0); _defineProperty(_assertThisInitialized(_this), "otherParams", {}); _defineProperty(_assertThisInitialized(_this), "cacheId", void 0); _defineProperty(_assertThisInitialized(_this), "otherData", {}); // 提供给 UI 层的临时数据存储,会进缓存 _defineProperty(_assertThisInitialized(_this), "platform", void 0); return _this; } _createClass(BookingByStepImpl, [{ key: "initialize", value: // 平台类型,用于判断是 PC / H5 function () { var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) { var _this$otherParams, _this$otherParams2, _this$otherParams3, _this2 = this; var targetCacheData, sessionData, _data$this$otherParam, data, moduleArr; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: this.core = core; this.store = options.store || {}; this.otherParams = options.otherParams || {}; console.log('[BookingByStep] 初始化完成'); // 获取依赖的插件 this.request = core.getPlugin('request'); this.window = core.getPlugin('window'); this.shopStore = core.getPlugin('shopStore'); if (this.request) { _context.next = 9; break; } throw new Error('bookingByStep解决方案需要 request 插件支持'); case 9: if (this.shopStore) { _context.next = 11; break; } throw new Error('SummaryModule 需要 shopStore 插件支持'); case 11: // 如果有传 cacheid,默认需要收集上面这些模块里用户操作选中的数据 // 并且在上面 registerModule 的时候,读取 sessionStroage 里的数据,塞进默认值 targetCacheData = {}; this.cacheId = (_this$otherParams = this.otherParams) === null || _this$otherParams === void 0 ? void 0 : _this$otherParams.cacheId; this.platform = (_this$otherParams2 = this.otherParams) === null || _this$otherParams2 === void 0 ? void 0 : _this$otherParams2.platform; if ((_this$otherParams3 = this.otherParams) !== null && _this$otherParams3 !== void 0 && _this$otherParams3.cacheId) { sessionData = this.window.sessionStorage.getItem(this.name); if (sessionData) { data = JSON.parse(sessionData); // 匹配 cacheid,如果匹配不到,直接把 sessionData 清掉即可 // 如果匹配到了,则把 sessionData 里的数据按模块塞到 store 里去 targetCacheData = data[this.otherParams.cacheId]; this.otherData = ((_data$this$otherParam = data[this.otherParams.cacheId]) === null || _data$this$otherParam === void 0 || (_data$this$otherParam = _data$this$otherParam[this.name]) === null || _data$this$otherParam === void 0 ? void 0 : _data$this$otherParam['otherData']) || {}; } } moduleArr = ['accountList', 'cart', 'schedule', 'summary', 'step', 'products', 'date', 'order']; moduleArr.forEach(function (step) { var targetModule = createModule(step, _this2.name); if (targetModule) { var _targetCacheData, _this2$otherParams, _this2$otherParams2; _this2.store[step] = targetModule; _this2.core.registerModule(targetModule, { initialState: (_targetCacheData = targetCacheData) === null || _targetCacheData === void 0 ? void 0 : _targetCacheData[targetModule.name], otherParams: _objectSpread(_objectSpread({}, _this2.otherParams), {}, { fatherModule: _this2.name, openCache: (_this2$otherParams = _this2.otherParams) !== null && _this2$otherParams !== void 0 && _this2$otherParams.cacheId ? true : false, cacheId: (_this2$otherParams2 = _this2.otherParams) === null || _this2$otherParams2 === void 0 ? void 0 : _this2$otherParams2.cacheId }) }); } else { throw new Error("\u6A21\u5757 ".concat(step, " \u4E0D\u5B58\u5728")); } }); this.store.schedule.loadAllSchedule(); this.core.effects.emit("".concat(this.name, ":onInited"), {}); case 19: case "end": return _context.stop(); } }, _callee, this); })); function initialize(_x, _x2) { return _initialize.apply(this, arguments); } return initialize; }() // 初始化step }, { key: "initStep", value: function initStep(stepList) { this.store.step.init(stepList); } }, { key: "getCurrentStep", value: function getCurrentStep() { return { index: this.store.step.getCurrentStepIndex(), step: this.store.step.getCurrentStep() }; } // step: 下一个 }, { key: "next", value: function next() { this.store.step.nextStep(); } // step: 上一个 }, { key: "back", value: function back() { this.store.step.prevStep(); } // 跳转到指定步骤 }, { key: "gotoStep", value: function gotoStep(index) { this.store.step.gotoStep(index); } // 获取所有step }, { key: "getStepList", value: function getStepList() { return this.store.step.getStepList(); } /** * 添加step */ }, { key: "addStep", value: function addStep(step, key) { this.store.step.addStep(step, key); } /** * 删除step */ }, { key: "removeStep", value: function removeStep(key) { this.store.step.removeStep(key); } /** * 更新step */ }, { key: "updateStep", value: function updateStep(key, step) { this.store.step.updateStep(key, step); } /** * * 加载商品,然后导到商品列表里去 * @param {({ * category_ids?: number[]; * product_ids?: number[]; * collection?: number | string[]; * schedule_date?: string; * })} { * category_ids = [], * product_ids = [], * collection = [], * schedule_date, * } * @return {*} * @memberof BookingByStepImpl */ }, { key: "loadProducts", value: (function () { var _loadProducts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref) { var _ref$category_ids, category_ids, _ref$product_ids, product_ids, _ref$collection, collection, schedule_date, res; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _ref$category_ids = _ref.category_ids, category_ids = _ref$category_ids === void 0 ? [] : _ref$category_ids, _ref$product_ids = _ref.product_ids, product_ids = _ref$product_ids === void 0 ? [] : _ref$product_ids, _ref$collection = _ref.collection, collection = _ref$collection === void 0 ? [] : _ref$collection, schedule_date = _ref.schedule_date; _context2.next = 3; return this.store.products.loadProducts({ category_ids: category_ids, product_ids: product_ids, collection: collection, schedule_date: schedule_date, cacheId: this.cacheId }); case 3: res = _context2.sent; // 预拉取当天的资源数据 this.getAvailableDate({ startDate: schedule_date || dayjs().format('YYYY-MM-DD'), endDate: schedule_date || dayjs().format('YYYY-MM-DD'), products: _toConsumableArray(res) }); return _context2.abrupt("return", res); case 6: case "end": return _context2.stop(); } }, _callee2, this); })); function loadProducts(_x3) { return _loadProducts.apply(this, arguments); } return loadProducts; }() /** * 通过 schedule 来读取商品,适用于 session 类商品 * * @param {{ * date: string; * product_ids?: number[]; * category_ids?: number[]; * }} { * date, * product_ids = [], * category_ids = [], * } * @return {*} * @memberof BookingByStepImpl */ ) }, { key: "loadProductByScheduleDate", value: (function () { var _loadProductByScheduleDate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref2) { var _schedule$product_ids; var date, _ref2$product_ids, product_ids, _ref2$category_ids, category_ids, scheduleList, newProductIds, schedule, otherProductsIds, allProductIds, res; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: date = _ref2.date, _ref2$product_ids = _ref2.product_ids, product_ids = _ref2$product_ids === void 0 ? [] : _ref2$product_ids, _ref2$category_ids = _ref2.category_ids, category_ids = _ref2$category_ids === void 0 ? [] : _ref2$category_ids; scheduleList = this.store.schedule.getAvailabilityScheduleDateList(); // 缓存下这次选择的结果,如果是先选日期再选 duration 类商品,后面用得到 this.setDateRange([{ date: date, status: 'available', week: '', weekNum: 0 }, { date: date, status: 'available', week: '', weekNum: 0 }]); newProductIds = []; // const scheduleIds = scheduleList // .filter((n) => n.date === date) // .flatMap((n) => n.schedule_id) // .filter((n) => n !== null && n !== undefined); // 如果外面没传 product_ids,尝试从对应 schedule 里拿 product_ids // if (!product_ids?.length) { // const schedule = scheduleList.find((n) => n.date === date); // if (schedule && schedule.product_ids?.length) { // product_ids = schedule.product_ids; // } // } // V2接口修改后,只能从schedule 接口里拿数据,不可以从外面拿,外面给的是装修数据 schedule = scheduleList.find(function (n) { return n.date === date; }); if (schedule && (_schedule$product_ids = schedule.product_ids) !== null && _schedule$product_ids !== void 0 && _schedule$product_ids.length) { newProductIds = schedule.product_ids; } // 尝试去拿schedule 里的 other_product_ids 和 product_ids 拼在一起去重 otherProductsIds = this.store.schedule.getOtherProductsIds() || []; allProductIds = [].concat(_toConsumableArray(newProductIds), _toConsumableArray(otherProductsIds)).filter(function (n, index, self) { return self.indexOf(n) === index; }); _context3.next = 10; return this.loadProducts({ product_ids: allProductIds, category_ids: category_ids, schedule_date: date }); case 10: res = _context3.sent; return _context3.abrupt("return", res); case 12: case "end": return _context3.stop(); } }, _callee3, this); })); function loadProductByScheduleDate(_x4) { return _loadProductByScheduleDate.apply(this, arguments); } return loadProductByScheduleDate; }() /** * 更新完商品数据、切换日期、或者在较后的流程里登录了,检测当前购物车里是否有商品,如果有,则需要更新购物车里的商品价格 * * @param {string} date * @memberof BookingByStepImpl */ ) }, { key: "updateQuotationPriceAndCart", value: (function () { var _updateQuotationPriceAndCart = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(date) { var _this3 = this; var cartItems, userPlugin, customer_id, _userPlugin$get, res; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: cartItems = this.store.cart.getItems(); if (!cartItems.length) { _context4.next = 11; break; } userPlugin = this.core.getPlugin('user'); customer_id = undefined; try { customer_id = userPlugin === null || userPlugin === void 0 || (_userPlugin$get = userPlugin.get()) === null || _userPlugin$get === void 0 ? void 0 : _userPlugin$get.id; } catch (error) { console.error(error); } _context4.next = 7; return this.store.products.loadProductsPrice({ ids: cartItems.map(function (n) { return n.id; }), schedule_date: date, customer_id: customer_id }); case 7: res = _context4.sent; _context4.next = 10; return updateAllCartItemPrice(cartItems, res, function (id) { return _this3.store.products.getProduct(id); }, function (params) { return _this3.store.cart.updateItem(params); }, function (params) { return _this3.store.cart.updateItemInitInfo(params); }); case 10: this.core.effects.emit("".concat(this.store.cart.name, ":onUpdateQuotationPrice"), {}); case 11: case "end": return _context4.stop(); } }, _callee4, this); })); function updateQuotationPriceAndCart(_x5) { return _updateQuotationPriceAndCart.apply(this, arguments); } return updateQuotationPriceAndCart; }() /** * ui 层提供日期的起始范围,返回一个起始范围内日期的可用情况 * 适用于先选日期的流程,确定日期是否可用 * 已知问题:如果挂接的商品的资源不可用,后端是不会计算的 * * @param {LoadScheduleAvailableDateParams} { * startDate, * endDate, * custom_page_id, * channel, * } * @memberof BookingByStepImpl */ ) }, { key: "loadScheduleAvailableDate", value: (function () { var _loadScheduleAvailableDate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref3) { var startDate, endDate, custom_page_id, channel; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: startDate = _ref3.startDate, endDate = _ref3.endDate, custom_page_id = _ref3.custom_page_id, channel = _ref3.channel; _context5.next = 3; return this.store.schedule.loadScheduleAvailableDate({ startDate: startDate, endDate: endDate, custom_page_id: custom_page_id, channel: channel }); case 3: return _context5.abrupt("return", _context5.sent); case 4: case "end": return _context5.stop(); } }, _callee5, this); })); function loadScheduleAvailableDate(_x6) { return _loadScheduleAvailableDate.apply(this, arguments); } return loadScheduleAvailableDate; }() // 添加单个账户或者 guest ) }, { key: "addAccount", value: function () { var _addAccount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(account, extra) { var accountModules, newAccount; return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: if (!((extra === null || extra === void 0 ? void 0 : extra.type) === 'holder')) { _context6.next = 5; break; } _context6.next = 3; return this.store.accountList.addHolderAccounts({ holders: [account], customerId: extra.customerId, type: 'unshift' }); case 3: accountModules = _context6.sent; return _context6.abrupt("return", accountModules[0].getAccount()); case 5: _context6.next = 7; return this.store.accountList.addAccount(account); case 7: newAccount = _context6.sent; return _context6.abrupt("return", newAccount.getAccount()); case 9: case "end": return _context6.stop(); } }, _callee6, this); })); function addAccount(_x7, _x8) { return _addAccount.apply(this, arguments); } return addAccount; }() // 添加账户或者 guest }, { key: "addAccounts", value: function () { var _addAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(accounts, extra) { var res, _iterator, _step, account, accountModule, accountData; return _regeneratorRuntime().wrap(function _callee7$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: if (!((extra === null || extra === void 0 ? void 0 : extra.type) === 'holder')) { _context7.next = 3; break; } this.store.accountList.addHolderAccounts({ holders: accounts, customerId: extra.customerId, type: 'unshift' }); return _context7.abrupt("return"); case 3: res = []; _iterator = _createForOfIteratorHelper(accounts); _context7.prev = 5; _iterator.s(); case 7: if ((_step = _iterator.n()).done) { _context7.next = 16; break; } account = _step.value; _context7.next = 11; return this.store.accountList.addAccount(account); case 11: accountModule = _context7.sent; accountData = accountModule.getAccount(); if (accountData) { res.push(accountData); } case 14: _context7.next = 7; break; case 16: _context7.next = 21; break; case 18: _context7.prev = 18; _context7.t0 = _context7["catch"](5); _iterator.e(_context7.t0); case 21: _context7.prev = 21; _iterator.f(); return _context7.finish(21); case 24: return _context7.abrupt("return", res); case 25: case "end": return _context7.stop(); } }, _callee7, this, [[5, 18, 21, 24]]); })); function addAccounts(_x9, _x10) { return _addAccounts.apply(this, arguments); } return addAccounts; }() // 获取所有账户 }, { key: "getAccounts", value: function () { var _getAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() { var accounts; return _regeneratorRuntime().wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { case 0: accounts = this.store.accountList.getAccounts(); return _context8.abrupt("return", accounts.map(function (account) { return account.getAccount(); })); case 2: case "end": return _context8.stop(); } }, _callee8, this); })); function getAccounts() { return _getAccounts.apply(this, arguments); } return getAccounts; }() }, { key: "checkHasLoginAccount", value: function checkHasLoginAccount() { var accounts = this.store.accountList.getAccounts(); return accounts.some(function (account) { return account.getLoginStatus(); }); } }, { key: "setActiveAccount", value: function setActiveAccount(id) { this.store.accountList.setActiveAccount(id); } }, { key: "getActiveAccount", value: function getActiveAccount() { var activeAccount = this.store.accountList.getActiveAccount(); var account = activeAccount === null || activeAccount === void 0 ? void 0 : activeAccount.getAccount(); return account === null ? undefined : account; } }, { key: "removeAccount", value: function removeAccount(id) { this.store.accountList.removeAccount(id); // 还需要把对应账号的商品给她删了 this.clearCartByAccount(id); } /** * 获取holder类型账户列表 * @param params */ }, { key: "fetchHolderAccountsAsync", value: (function () { var _fetchHolderAccountsAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(params) { var cartItems, _this$store$date$getD, date, normalProductCartItem; return _regeneratorRuntime().wrap(function _callee9$(_context9) { while (1) switch (_context9.prev = _context9.next) { case 0: cartItems = this.store.cart.getItems(); if (cartItems.length) { date = (_this$store$date$getD = this.store.date.getDateRange()) === null || _this$store$date$getD === void 0 || (_this$store$date$getD = _this$store$date$getD[0]) === null || _this$store$date$getD === void 0 ? void 0 : _this$store$date$getD.date; if (!date) { // 如果没有日期,则应该是 session 类先选商品的流程,直接从购物车里拿 start_date // 不能从购物车里第一个找时间,而是找到购物车里第一个有 start_date 的时间 normalProductCartItem = cartItems.find(function (n) { return !isNormalProduct(n._productOrigin); }); date = (normalProductCartItem === null || normalProductCartItem === void 0 ? void 0 : normalProductCartItem.start_date) || ''; } this.updateQuotationPriceAndCart(date); } return _context9.abrupt("return", this.store.accountList.fetchHolderAccounts(params)); case 3: case "end": return _context9.stop(); } }, _callee9, this); })); function fetchHolderAccountsAsync(_x11) { return _fetchHolderAccountsAsync.apply(this, arguments); } return fetchHolderAccountsAsync; }() // 设置日期范围,注入到日期模块中 ) }, { key: "setDateRange", value: function () { var _setDateRange = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(dateRange) { return _regeneratorRuntime().wrap(function _callee10$(_context10) { while (1) switch (_context10.prev = _context10.next) { case 0: this.store.date.setDateRange(dateRange); // 日期数据变更后,如果购物车里有数据,需要更新购物车里的报价单的价格 if (dateRange.length && this.store.cart.getItems().length) { this.updateQuotationPriceAndCart(dateRange[0].date); } case 2: case "end": return _context10.stop(); } }, _callee10, this); })); function setDateRange(_x12) { return _setDateRange.apply(this, arguments); } return setDateRange; }() }, { key: "clearDateRange", value: function clearDateRange() { this.store.date.clearDateRange(); } // 获取日期模块里选中的日期 }, { key: "getDateRange", value: function () { var _getDateRange = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() { return _regeneratorRuntime().wrap(function _callee11$(_context11) { while (1) switch (_context11.prev = _context11.next) { case 0: return _context11.abrupt("return", this.store.date.getDateRange()); case 1: case "end": return _context11.stop(); } }, _callee11, this); })); function getDateRange() { return _getDateRange.apply(this, arguments); } return getDateRange; }() }, { key: "getCart", value: function getCart() { return this.store.cart.getItems(); } // 获取商品/服务的可用日期 }, { key: "getAvailableDate", value: function () { var _getAvailableDate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() { var _this4 = this, _dateRange$, _dateRange$2, _dateRange$3; var params, products, startDate, endDate, type, _params$useCache, useCache, tempProducts, _this$store$currentPr, dateRange, tempStartDate, tempEndDate, _ref4, resourceIds, rules, resourcesMap, res, _args12 = arguments; return _regeneratorRuntime().wrap(function _callee12$(_context12) { while (1) switch (_context12.prev = _context12.next) { case 0: params = _args12.length > 0 && _args12[0] !== undefined ? _args12[0] : {}; // 开始日期如果小于今天,直接以今天当做开始日期 products = params.products, startDate = params.startDate, endDate = params.endDate, type = params.type, _params$useCache = params.useCache, useCache = _params$useCache === void 0 ? true : _params$useCache; // 前端传递的 startDate,可能是今天之前的,如果 startDate 小于今天 且 endDate 小于或等于今天,需要把 startDate 置为今天 if (dayjs(startDate).isBefore(dayjs(), 'day') && (dayjs(endDate).isAfter(dayjs(), 'day') || dayjs(endDate).isSame(dayjs(), 'day'))) { startDate = dayjs().format('YYYY-MM-DD'); } tempProducts = products || this.store.cart.getItems().map(function (p) { return p._productOrigin; }); if (tempProducts.length) { tempProducts.forEach(function (p) { if (p !== null && p !== void 0 && p['schedule.ids']) { var scheduleData = _this4.getScheduleDataByIds(p['schedule.ids']); p['_schedule'] = scheduleData; } }); } // 如果当前打开了某个的商品详情弹窗,则应该默认用这个商品 if (this.store.currentProduct) { tempProducts = [_objectSpread(_objectSpread({}, this.store.currentProduct), {}, { _schedule: (_this$store$currentPr = this.store.currentProductMeta) === null || _this$store$currentPr === void 0 ? void 0 : _this$store$currentPr['schedule'] })]; } dateRange = this.store.date.getDateRange(); tempStartDate = startDate || (dateRange === null || dateRange === void 0 || (_dateRange$ = dateRange[0]) === null || _dateRange$ === void 0 ? void 0 : _dateRange$.date); tempEndDate = endDate || (dateRange === null || dateRange === void 0 || (_dateRange$2 = dateRange[1]) === null || _dateRange$2 === void 0 ? void 0 : _dateRange$2.date) || (dateRange === null || dateRange === void 0 || (_dateRange$3 = dateRange[0]) === null || _dateRange$3 === void 0 ? void 0 : _dateRange$3.date); if (tempProducts.length) { _context12.next = 11; break; } return _context12.abrupt("return", []); case 11: // 在这里需要把能收集到的数据都收集上来,拼装好给 date 模块去查询 _ref4 = getAvailableProductResources(tempProducts) || {}, resourceIds = _ref4.resourceIds, rules = _ref4.rules, resourcesMap = _ref4.resourcesMap; this.otherParams.currentResourcesMap = resourcesMap; _context12.next = 15; return this.store.date.getResourceDates({ url: params.url, query: { start_date: tempStartDate, end_date: tempEndDate, resource_ids: resourceIds }, rules: rules, type: type, useCache: useCache }); case 15: res = _context12.sent; return _context12.abrupt("return", res); case 17: case "end": return _context12.stop(); } }, _callee12, this); })); function getAvailableDate() { return _getAvailableDate.apply(this, arguments); } return getAvailableDate; }() /** * 获取购物车汇总信息 */ }, { key: "getSummary", value: (function () { var _getSummary = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() { var cartItems, summary; return _regeneratorRuntime().wrap(function _callee13$(_context13) { while (1) switch (_context13.prev = _context13.next) { case 0: cartItems = this.store.cart.getItems(); _context13.next = 3; return this.store.summary.getSummary(cartItems); case 3: summary = _context13.sent; return _context13.abrupt("return", summary); case 5: case "end": return _context13.stop(); } }, _callee13, this); })); function getSummary() { return _getSummary.apply(this, arguments); } return getSummary; }() /** * 获取协议 */ ) }, { key: "getProtocol", value: (function () { var _getProtocol = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mar