@pisell/pisellos 2.1.170 → 2.1.172

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.js +1 -3
  3. package/dist/model/strategy/adapter/index.d.ts +0 -4
  4. package/dist/model/strategy/adapter/index.js +1 -5
  5. package/dist/model/strategy/adapter/promotion/evaluator.js +99 -26
  6. package/dist/model/strategy/adapter/promotion/index.js +0 -9
  7. package/dist/model/strategy/adapter/walletPass/evaluator.d.ts +2 -0
  8. package/dist/model/strategy/adapter/walletPass/evaluator.js +61 -8
  9. package/dist/model/strategy/adapter/walletPass/locales.js +12 -3
  10. package/dist/model/strategy/engine.d.ts +18 -5
  11. package/dist/model/strategy/engine.js +145 -45
  12. package/dist/model/strategy/type.d.ts +17 -0
  13. package/dist/model/strategy/type.js +4 -0
  14. package/dist/modules/Cart/types.d.ts +2 -0
  15. package/dist/modules/Cart/utils/cartProduct.js +56 -25
  16. package/dist/modules/Cart/utils/changePrice.js +9 -16
  17. package/dist/modules/Discount/index.d.ts +4 -13
  18. package/dist/modules/Discount/index.js +12 -124
  19. package/dist/modules/Discount/types.d.ts +18 -13
  20. package/dist/modules/Order/index.d.ts +1 -67
  21. package/dist/modules/Order/index.js +30 -918
  22. package/dist/modules/Order/types.d.ts +12 -176
  23. package/dist/modules/Order/types.js +0 -2
  24. package/dist/modules/Order/utils.d.ts +0 -118
  25. package/dist/modules/Order/utils.js +2 -586
  26. package/dist/modules/Payment/index.d.ts +2 -1
  27. package/dist/modules/Payment/index.js +10 -7
  28. package/dist/modules/Payment/utils.js +3 -0
  29. package/dist/modules/Payment/walletpass.d.ts +23 -0
  30. package/dist/modules/Payment/walletpass.js +191 -95
  31. package/dist/modules/Product/utils.js +2 -2
  32. package/dist/modules/ProductList/index.d.ts +2 -4
  33. package/dist/modules/ProductList/index.js +12 -24
  34. package/dist/modules/Rules/index.d.ts +9 -5
  35. package/dist/modules/Rules/index.js +669 -173
  36. package/dist/modules/Rules/types.d.ts +2 -0
  37. package/dist/modules/Schedule/getDateIsInSchedule.js +18 -16
  38. package/dist/modules/Schedule/utils.d.ts +1 -1
  39. package/dist/modules/Summary/types.d.ts +2 -0
  40. package/dist/modules/Summary/utils.d.ts +9 -3
  41. package/dist/modules/Summary/utils.js +57 -67
  42. package/dist/modules/index.d.ts +0 -4
  43. package/dist/modules/index.js +1 -5
  44. package/dist/plugins/window.d.ts +2 -0
  45. package/dist/solution/BookingByStep/index.d.ts +3 -2
  46. package/dist/solution/BookingByStep/index.js +43 -46
  47. package/dist/solution/BookingByStep/types.d.ts +1 -3
  48. package/dist/solution/BookingByStep/types.js +1 -5
  49. package/dist/solution/BookingByStep/utils/timeslots.d.ts +1 -3
  50. package/dist/solution/BookingByStep/utils/timeslots.js +12 -19
  51. package/dist/solution/Checkout/index.js +2 -0
  52. package/dist/solution/ShopDiscount/index.d.ts +2 -3
  53. package/dist/solution/ShopDiscount/index.js +60 -62
  54. package/dist/solution/ShopDiscount/types.d.ts +1 -1
  55. package/dist/solution/ShopDiscount/types.js +2 -1
  56. package/dist/solution/ShopDiscount/utils.js +26 -12
  57. package/dist/solution/index.d.ts +0 -2
  58. package/dist/solution/index.js +1 -3
  59. package/lib/index.d.ts +1 -1
  60. package/lib/index.js +3 -4
  61. package/lib/model/strategy/adapter/index.d.ts +0 -4
  62. package/lib/model/strategy/adapter/index.js +2 -13
  63. package/lib/model/strategy/adapter/promotion/evaluator.js +57 -8
  64. package/lib/model/strategy/adapter/walletPass/evaluator.d.ts +2 -0
  65. package/lib/model/strategy/adapter/walletPass/evaluator.js +34 -3
  66. package/lib/model/strategy/adapter/walletPass/locales.js +12 -3
  67. package/lib/model/strategy/engine.d.ts +18 -5
  68. package/lib/model/strategy/engine.js +85 -21
  69. package/lib/model/strategy/type.d.ts +17 -0
  70. package/lib/modules/Cart/types.d.ts +2 -0
  71. package/lib/modules/Cart/utils/cartProduct.js +39 -12
  72. package/lib/modules/Cart/utils/changePrice.js +9 -13
  73. package/lib/modules/Discount/index.d.ts +4 -13
  74. package/lib/modules/Discount/index.js +5 -76
  75. package/lib/modules/Discount/types.d.ts +18 -13
  76. package/lib/modules/Order/index.d.ts +1 -67
  77. package/lib/modules/Order/index.js +1 -525
  78. package/lib/modules/Order/types.d.ts +12 -176
  79. package/lib/modules/Order/utils.d.ts +0 -118
  80. package/lib/modules/Order/utils.js +2 -483
  81. package/lib/modules/Payment/index.d.ts +2 -1
  82. package/lib/modules/Payment/index.js +1 -0
  83. package/lib/modules/Payment/utils.js +3 -0
  84. package/lib/modules/Payment/walletpass.d.ts +23 -0
  85. package/lib/modules/Payment/walletpass.js +94 -17
  86. package/lib/modules/Product/utils.js +2 -2
  87. package/lib/modules/ProductList/index.d.ts +2 -4
  88. package/lib/modules/ProductList/index.js +39 -46
  89. package/lib/modules/Rules/index.d.ts +9 -5
  90. package/lib/modules/Rules/index.js +776 -292
  91. package/lib/modules/Rules/types.d.ts +2 -0
  92. package/lib/modules/Schedule/getDateIsInSchedule.js +11 -13
  93. package/lib/modules/Schedule/utils.d.ts +1 -1
  94. package/lib/modules/Summary/types.d.ts +2 -0
  95. package/lib/modules/Summary/utils.d.ts +9 -3
  96. package/lib/modules/Summary/utils.js +34 -45
  97. package/lib/modules/index.d.ts +0 -4
  98. package/lib/modules/index.js +1 -9
  99. package/lib/plugins/window.d.ts +2 -0
  100. package/lib/solution/BookingByStep/index.d.ts +3 -2
  101. package/lib/solution/BookingByStep/index.js +4 -6
  102. package/lib/solution/BookingByStep/types.d.ts +1 -3
  103. package/lib/solution/BookingByStep/types.js +0 -10
  104. package/lib/solution/BookingByStep/utils/timeslots.d.ts +1 -3
  105. package/lib/solution/BookingByStep/utils/timeslots.js +11 -19
  106. package/lib/solution/Checkout/index.js +2 -0
  107. package/lib/solution/ShopDiscount/index.d.ts +2 -3
  108. package/lib/solution/ShopDiscount/index.js +27 -22
  109. package/lib/solution/ShopDiscount/types.d.ts +1 -1
  110. package/lib/solution/ShopDiscount/utils.js +10 -6
  111. package/lib/solution/index.d.ts +0 -2
  112. package/lib/solution/index.js +1 -5
  113. package/package.json +2 -2
  114. package/dist/apis/picoding.d.ts +0 -0
  115. package/dist/apis/picoding.js +0 -1
  116. package/dist/model/strategy/adapter/dataVariant/adapter.d.ts +0 -50
  117. package/dist/model/strategy/adapter/dataVariant/adapter.js +0 -167
  118. package/dist/model/strategy/adapter/dataVariant/evaluator.d.ts +0 -89
  119. package/dist/model/strategy/adapter/dataVariant/evaluator.js +0 -867
  120. package/dist/model/strategy/adapter/dataVariant/examples.d.ts +0 -39
  121. package/dist/model/strategy/adapter/dataVariant/examples.js +0 -277
  122. package/dist/model/strategy/adapter/dataVariant/index.d.ts +0 -4
  123. package/dist/model/strategy/adapter/dataVariant/index.js +0 -4
  124. package/dist/model/strategy/adapter/dataVariant/type.d.ts +0 -149
  125. package/dist/model/strategy/adapter/dataVariant/type.js +0 -54
  126. package/dist/modules/OpenData/index.d.ts +0 -24
  127. package/dist/modules/OpenData/index.js +0 -173
  128. package/dist/modules/OpenData/types.d.ts +0 -73
  129. package/dist/modules/OpenData/types.js +0 -1
  130. package/dist/modules/OpenData/utils.d.ts +0 -2
  131. package/dist/modules/OpenData/utils.js +0 -75
  132. package/dist/modules/Quotation/index.d.ts +0 -48
  133. package/dist/modules/Quotation/index.js +0 -248
  134. package/dist/modules/Quotation/types.d.ts +0 -42
  135. package/dist/modules/Quotation/types.js +0 -1
  136. package/dist/modules/SalesSummary/index.d.ts +0 -63
  137. package/dist/modules/SalesSummary/index.js +0 -174
  138. package/dist/modules/SalesSummary/types.d.ts +0 -60
  139. package/dist/modules/SalesSummary/types.js +0 -1
  140. package/dist/modules/SalesSummary/utils.d.ts +0 -30
  141. package/dist/modules/SalesSummary/utils.js +0 -480
  142. package/dist/modules/ScanOrderLogger/index.d.ts +0 -23
  143. package/dist/modules/ScanOrderLogger/index.js +0 -174
  144. package/dist/modules/ScanOrderLogger/providers/feishu.d.ts +0 -2
  145. package/dist/modules/ScanOrderLogger/providers/feishu.js +0 -221
  146. package/dist/modules/ScanOrderLogger/providers/grafana.d.ts +0 -2
  147. package/dist/modules/ScanOrderLogger/providers/grafana.js +0 -50
  148. package/dist/modules/ScanOrderLogger/types.d.ts +0 -53
  149. package/dist/modules/ScanOrderLogger/types.js +0 -1
  150. package/dist/solution/ScanOrder/index.d.ts +0 -158
  151. package/dist/solution/ScanOrder/index.js +0 -3474
  152. package/dist/solution/ScanOrder/types.d.ts +0 -306
  153. package/dist/solution/ScanOrder/types.js +0 -35
  154. package/dist/solution/ScanOrder/utils.d.ts +0 -172
  155. package/dist/solution/ScanOrder/utils.js +0 -796
  156. package/dist/solution/VenueBooking/index.d.ts +0 -252
  157. package/dist/solution/VenueBooking/index.js +0 -3769
  158. package/dist/solution/VenueBooking/sales-section-4-annotated.json +0 -343
  159. package/dist/solution/VenueBooking/types.d.ts +0 -156
  160. package/dist/solution/VenueBooking/types.js +0 -22
  161. package/dist/solution/VenueBooking/utils/dateSummary.d.ts +0 -11
  162. package/dist/solution/VenueBooking/utils/dateSummary.js +0 -91
  163. package/dist/solution/VenueBooking/utils/resource.d.ts +0 -14
  164. package/dist/solution/VenueBooking/utils/resource.js +0 -131
  165. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +0 -32
  166. package/dist/solution/VenueBooking/utils/slotMerge.js +0 -233
  167. package/dist/solution/VenueBooking/utils/smartPricing.d.ts +0 -71
  168. package/dist/solution/VenueBooking/utils/smartPricing.js +0 -302
  169. package/dist/solution/VenueBooking/utils/timeSlot.d.ts +0 -34
  170. package/dist/solution/VenueBooking/utils/timeSlot.js +0 -458
  171. package/dist/solution/VenueBooking/utils.d.ts +0 -1
  172. package/dist/solution/VenueBooking/utils.js +0 -1
  173. package/lib/apis/picoding.d.ts +0 -0
  174. package/lib/apis/picoding.js +0 -0
  175. package/lib/model/strategy/adapter/dataVariant/adapter.d.ts +0 -50
  176. package/lib/model/strategy/adapter/dataVariant/adapter.js +0 -149
  177. package/lib/model/strategy/adapter/dataVariant/evaluator.d.ts +0 -89
  178. package/lib/model/strategy/adapter/dataVariant/evaluator.js +0 -666
  179. package/lib/model/strategy/adapter/dataVariant/examples.d.ts +0 -39
  180. package/lib/model/strategy/adapter/dataVariant/examples.js +0 -293
  181. package/lib/model/strategy/adapter/dataVariant/index.d.ts +0 -4
  182. package/lib/model/strategy/adapter/dataVariant/index.js +0 -38
  183. package/lib/model/strategy/adapter/dataVariant/type.d.ts +0 -149
  184. package/lib/model/strategy/adapter/dataVariant/type.js +0 -31
  185. package/lib/modules/OpenData/index.d.ts +0 -24
  186. package/lib/modules/OpenData/index.js +0 -119
  187. package/lib/modules/OpenData/types.d.ts +0 -73
  188. package/lib/modules/OpenData/types.js +0 -17
  189. package/lib/modules/OpenData/utils.d.ts +0 -2
  190. package/lib/modules/OpenData/utils.js +0 -111
  191. package/lib/modules/Quotation/index.d.ts +0 -48
  192. package/lib/modules/Quotation/index.js +0 -152
  193. package/lib/modules/Quotation/types.d.ts +0 -42
  194. package/lib/modules/Quotation/types.js +0 -17
  195. package/lib/modules/SalesSummary/index.d.ts +0 -63
  196. package/lib/modules/SalesSummary/index.js +0 -105
  197. package/lib/modules/SalesSummary/types.d.ts +0 -60
  198. package/lib/modules/SalesSummary/types.js +0 -17
  199. package/lib/modules/SalesSummary/utils.d.ts +0 -30
  200. package/lib/modules/SalesSummary/utils.js +0 -420
  201. package/lib/modules/ScanOrderLogger/index.d.ts +0 -23
  202. package/lib/modules/ScanOrderLogger/index.js +0 -147
  203. package/lib/modules/ScanOrderLogger/providers/feishu.d.ts +0 -2
  204. package/lib/modules/ScanOrderLogger/providers/feishu.js +0 -157
  205. package/lib/modules/ScanOrderLogger/providers/grafana.d.ts +0 -2
  206. package/lib/modules/ScanOrderLogger/providers/grafana.js +0 -52
  207. package/lib/modules/ScanOrderLogger/types.d.ts +0 -53
  208. package/lib/modules/ScanOrderLogger/types.js +0 -17
  209. package/lib/solution/ScanOrder/index.d.ts +0 -158
  210. package/lib/solution/ScanOrder/index.js +0 -2135
  211. package/lib/solution/ScanOrder/types.d.ts +0 -306
  212. package/lib/solution/ScanOrder/types.js +0 -36
  213. package/lib/solution/ScanOrder/utils.d.ts +0 -172
  214. package/lib/solution/ScanOrder/utils.js +0 -658
  215. package/lib/solution/VenueBooking/index.d.ts +0 -252
  216. package/lib/solution/VenueBooking/index.js +0 -2204
  217. package/lib/solution/VenueBooking/sales-section-4-annotated.json +0 -343
  218. package/lib/solution/VenueBooking/types.d.ts +0 -156
  219. package/lib/solution/VenueBooking/types.js +0 -45
  220. package/lib/solution/VenueBooking/utils/dateSummary.d.ts +0 -11
  221. package/lib/solution/VenueBooking/utils/dateSummary.js +0 -105
  222. package/lib/solution/VenueBooking/utils/resource.d.ts +0 -14
  223. package/lib/solution/VenueBooking/utils/resource.js +0 -92
  224. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +0 -32
  225. package/lib/solution/VenueBooking/utils/slotMerge.js +0 -236
  226. package/lib/solution/VenueBooking/utils/smartPricing.d.ts +0 -71
  227. package/lib/solution/VenueBooking/utils/smartPricing.js +0 -225
  228. package/lib/solution/VenueBooking/utils/timeSlot.d.ts +0 -34
  229. package/lib/solution/VenueBooking/utils/timeSlot.js +0 -343
  230. package/lib/solution/VenueBooking/utils.d.ts +0 -1
  231. package/lib/solution/VenueBooking/utils.js +0 -69
@@ -1,2204 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/solution/VenueBooking/index.ts
31
- var VenueBooking_exports = {};
32
- __export(VenueBooking_exports, {
33
- VenueBookingImpl: () => VenueBookingImpl
34
- });
35
- module.exports = __toCommonJS(VenueBooking_exports);
36
- var import_BaseModule = require("../../modules/BaseModule");
37
- var import_types = require("./types");
38
- var import_utils = require("./utils");
39
- var import_types2 = require("../BookingByStep/types");
40
- var import_ProductList = require("../../modules/ProductList");
41
- var import_Date = require("../../modules/Date");
42
- var import_Schedule = require("../../modules/Schedule");
43
- var import_utils2 = require("../../modules/Schedule/utils");
44
- var import_Quotation = require("../../modules/Quotation");
45
- var import_OpenData = require("../../modules/OpenData");
46
- var import_types3 = require("../../modules/Account/types");
47
- var import_dayjs = __toESM(require("dayjs"));
48
- var import_itemRule = require("../../model/strategy/adapter/itemRule");
49
- var import_resource = require("./utils/resource");
50
- var import_timeSlot = require("./utils/timeSlot");
51
- var import_dateSummary = require("./utils/dateSummary");
52
- var import_slotMerge = require("./utils/slotMerge");
53
- var import_smartPricing = require("./utils/smartPricing");
54
- var import_utils3 = require("../../modules/Order/utils");
55
- var import_Order = require("../../modules/Order");
56
- var import_types4 = require("../RegisterAndLogin/types");
57
- var import_decimal = __toESM(require("decimal.js"));
58
- __reExport(VenueBooking_exports, require("./types"), module.exports);
59
- var OPEN_DATA_SECTION_CODES = [
60
- "basic",
61
- "fulfillment",
62
- "reservation",
63
- "sale",
64
- "menu",
65
- "availability",
66
- "workflow",
67
- "checkout"
68
- ];
69
- function cloneCustomDepositData(customDepositData) {
70
- if (!customDepositData || typeof customDepositData !== "object")
71
- return void 0;
72
- return {
73
- ...customDepositData,
74
- self_deposit_policy_ids: Array.isArray(customDepositData.self_deposit_policy_ids) ? [...customDepositData.self_deposit_policy_ids] : [],
75
- deposit_policy_ids: Array.isArray(customDepositData.deposit_policy_ids) ? [...customDepositData.deposit_policy_ids] : [],
76
- deposit_policy_data: Array.isArray(customDepositData.deposit_policy_data) ? [...customDepositData.deposit_policy_data] : []
77
- };
78
- }
79
- var _VenueBookingImpl = class extends import_BaseModule.BaseModule {
80
- constructor(name, version) {
81
- super(name, version);
82
- this.defaultName = "venueBooking";
83
- this.defaultVersion = "1.0.0";
84
- this.isSolution = true;
85
- this.initializeOptions = {};
86
- this.store = {
87
- entryContext: null,
88
- status: "idle",
89
- flow: {},
90
- error: null,
91
- products: void 0,
92
- rawResourceData: [],
93
- slotConfig: { ...import_types.DEFAULT_SLOT_CONFIG },
94
- itemRuleQuantityLimits: [],
95
- cartValidation: {
96
- passed: null,
97
- failures: []
98
- }
99
- };
100
- this.otherParams = {};
101
- this.baseSlotConfig = { ...import_types.DEFAULT_SLOT_CONFIG };
102
- this.itemRuleEvaluator = new import_itemRule.ItemRuleEvaluator();
103
- this.itemRuleConfigs = [];
104
- this.itemRuleConfigsPromise = null;
105
- this.itemRulePrefillApplied = false;
106
- this.itemRuleRuntimeConfig = {};
107
- this.resourceProductMap = /* @__PURE__ */ new Map();
108
- this.loginEffectDisposers = [];
109
- this.customerLoginRefreshInFlight = null;
110
- this.customerLoginRefreshIdInFlight = null;
111
- this.loadAllProductsInFlight = null;
112
- this.productsLoaded = false;
113
- this.loadOpenDataConfigInFlight = null;
114
- /** 按日期缓存 slot 智能定价 Map,避免同周重复 resolveProducts */
115
- this.slotPriceMapCache = /* @__PURE__ */ new Map();
116
- /** loadProducts 后缓存的全量商品(venue + addon),供分段算价复用 */
117
- this.smartPricingProductCatalog = [];
118
- }
119
- getLoggerContext() {
120
- return {
121
- cacheId: this.cacheId,
122
- solutionName: this.name,
123
- moduleName: "venueBooking"
124
- };
125
- }
126
- safeStringify(value) {
127
- try {
128
- return JSON.stringify(value);
129
- } catch {
130
- return void 0;
131
- }
132
- }
133
- pickErrorMessage(error) {
134
- var _a, _b, _c, _d;
135
- const candidates = [
136
- error.message,
137
- (_a = error.data) == null ? void 0 : _a.message,
138
- (_c = (_b = error.response) == null ? void 0 : _b.data) == null ? void 0 : _c.message,
139
- (_d = error.error) == null ? void 0 : _d.message
140
- ];
141
- for (const candidate of candidates) {
142
- if (typeof candidate === "string" && candidate.trim())
143
- return candidate;
144
- }
145
- return void 0;
146
- }
147
- serializeError(error) {
148
- if (error instanceof Error) {
149
- return {
150
- name: error.name,
151
- message: error.message,
152
- stack: error.stack
153
- };
154
- }
155
- if (error && typeof error === "object") {
156
- const raw = error;
157
- const message = this.pickErrorMessage(raw) || this.safeStringify(raw) || String(error);
158
- return {
159
- ...typeof raw.name === "string" ? { name: raw.name } : {},
160
- message,
161
- ..."code" in raw ? { code: raw.code } : {},
162
- ..."status" in raw ? { status: raw.status } : {},
163
- ...this.safeStringify(raw) ? { raw: this.safeStringify(raw) } : {}
164
- };
165
- }
166
- return {
167
- message: String(error)
168
- };
169
- }
170
- async addVenueBookingLog(params) {
171
- const payload = {
172
- cacheId: this.cacheId,
173
- ...params.payload || {}
174
- };
175
- const extra = {
176
- ...params.extra || {}
177
- };
178
- const logger = this.store.scanOrderLogger;
179
- if (!logger) {
180
- if ((params.level || "info") === "error") {
181
- console.error("[VenueBooking][log-fallback]", params.title, { payload, extra });
182
- } else {
183
- console.log("[VenueBooking][log-fallback]", params.title, { payload, extra });
184
- }
185
- return;
186
- }
187
- await logger.addLog({
188
- ...params,
189
- payload,
190
- extra
191
- });
192
- }
193
- /**
194
- * 临时线上排查日志:
195
- * - 仅对指定页面 cacheId 开启,避免影响其他页面
196
- * - 不 await,且吞掉日志上报异常,保证日志系统不会阻断登录/商品加载主流程
197
- */
198
- logPricingDiagnostics(title, payload = {}) {
199
- if (!this.isPricingDiagnosticsEnabled())
200
- return;
201
- void this.addVenueBookingLog({
202
- level: "info",
203
- title,
204
- payload
205
- }).catch((error) => {
206
- console.warn("[VenueBooking] pricing diagnostic log failed", error);
207
- });
208
- }
209
- isPricingDiagnosticsEnabled() {
210
- return String(this.cacheId || "") === _VenueBookingImpl.PRICING_DEBUG_CACHE_ID;
211
- }
212
- getAvailableWalletIdsForDiagnostics() {
213
- var _a, _b;
214
- try {
215
- return (_b = (_a = this.store.order) == null ? void 0 : _a.getAvailableWalletIds) == null ? void 0 : _b.call(_a);
216
- } catch (error) {
217
- return {
218
- readFailed: true,
219
- error: this.serializeError(error)
220
- };
221
- }
222
- }
223
- logMethodStart(method, payload = {}) {
224
- void this.addVenueBookingLog({
225
- level: "info",
226
- title: `[VenueBooking] ${method} start`,
227
- payload: {
228
- method,
229
- ...payload
230
- }
231
- });
232
- }
233
- logMethodSuccess(method, payload = {}) {
234
- void this.addVenueBookingLog({
235
- level: "info",
236
- title: `[VenueBooking] ${method} success`,
237
- payload: {
238
- method,
239
- ...payload
240
- }
241
- });
242
- }
243
- logMethodError(method, error, payload = {}) {
244
- void this.addVenueBookingLog({
245
- level: "error",
246
- title: `[VenueBooking] ${method} failed`,
247
- payload: {
248
- method,
249
- ...payload,
250
- error: this.serializeError(error)
251
- }
252
- });
253
- }
254
- async addLog(params) {
255
- await this.addVenueBookingLog({
256
- ...params,
257
- payload: {
258
- source: "ui-bridge",
259
- ...params.payload || {}
260
- }
261
- });
262
- }
263
- normalizeCustomerId(value) {
264
- const customerId = Number(value);
265
- if (!Number.isFinite(customerId) || customerId <= 0)
266
- return null;
267
- return customerId;
268
- }
269
- resolveCustomerIdFromLoginPayload(payload) {
270
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
271
- const candidates = [
272
- payload == null ? void 0 : payload.customerId,
273
- payload == null ? void 0 : payload.customer_id,
274
- payload == null ? void 0 : payload.id,
275
- (_a = payload == null ? void 0 : payload.user) == null ? void 0 : _a.customerId,
276
- (_b = payload == null ? void 0 : payload.user) == null ? void 0 : _b.customer_id,
277
- (_c = payload == null ? void 0 : payload.user) == null ? void 0 : _c.id,
278
- (_e = (_d = payload == null ? void 0 : payload.user) == null ? void 0 : _d._origin) == null ? void 0 : _e.customer_id,
279
- (_f = payload == null ? void 0 : payload.account) == null ? void 0 : _f.customerId,
280
- (_g = payload == null ? void 0 : payload.account) == null ? void 0 : _g.customer_id,
281
- (_h = payload == null ? void 0 : payload.account) == null ? void 0 : _h.id,
282
- (_i = payload == null ? void 0 : payload._origin) == null ? void 0 : _i.customer_id
283
- ];
284
- for (const candidate of candidates) {
285
- const customerId = this.normalizeCustomerId(candidate);
286
- if (customerId)
287
- return customerId;
288
- }
289
- return null;
290
- }
291
- clearLoginEffectListeners() {
292
- for (const dispose of this.loginEffectDisposers) {
293
- dispose();
294
- }
295
- this.loginEffectDisposers = [];
296
- }
297
- registerLoginEffect(event, callback) {
298
- var _a;
299
- const effects = (_a = this.core) == null ? void 0 : _a.effects;
300
- if (!(effects == null ? void 0 : effects.on))
301
- return;
302
- effects.on(event, callback);
303
- this.loginEffectDisposers.push(() => {
304
- if (typeof effects.off === "function") {
305
- effects.off(event, callback);
306
- }
307
- });
308
- }
309
- registerCustomerLoginListeners() {
310
- this.clearLoginEffectListeners();
311
- const createHandleLogin = () => async (payload) => {
312
- const customerId = this.resolveCustomerIdFromLoginPayload(payload);
313
- this.logPricingDiagnostics("[VenueBooking] customer login event received", {
314
- customerId,
315
- hasLoadAllProductsInFlight: !!this.loadAllProductsInFlight,
316
- productsLoaded: this.productsLoaded,
317
- smartPricingProductCatalogCount: this.smartPricingProductCatalog.length
318
- });
319
- if (!customerId) {
320
- this.logPricingDiagnostics(
321
- "[VenueBooking] customer login event skipped customerId not found in login payload"
322
- );
323
- return;
324
- }
325
- await this.refreshOrderMarketingAfterLogin({ customerId });
326
- };
327
- this.registerLoginEffect(_VenueBookingImpl.PISELL1_LOGIN_SUCCESS, createHandleLogin());
328
- this.registerLoginEffect(import_types3.AccountHooks.OnLogin, createHandleLogin());
329
- this.registerLoginEffect(import_types4.RegisterAndLoginHooks.onLoginSuccess, createHandleLogin());
330
- }
331
- async refreshOrderMarketingAfterLogin(params) {
332
- if (!this.store.order)
333
- throw new Error("order 模块未初始化");
334
- this.logPricingDiagnostics("[VenueBooking] refreshOrderMarketingAfterLogin entered", {
335
- customerId: params.customerId,
336
- hasCustomerLoginRefreshInFlight: !!this.customerLoginRefreshInFlight,
337
- customerLoginRefreshIdInFlight: this.customerLoginRefreshIdInFlight,
338
- hasLoadAllProductsInFlight: !!this.loadAllProductsInFlight,
339
- productsLoaded: this.productsLoaded,
340
- smartPricingProductCatalogCount: this.smartPricingProductCatalog.length,
341
- note: "This login refresh recalculates the loaded catalog and does not call loadAllProducts"
342
- });
343
- if (this.customerLoginRefreshInFlight) {
344
- if (this.customerLoginRefreshIdInFlight === params.customerId) {
345
- this.logPricingDiagnostics("[VenueBooking] customer login refresh reused", {
346
- customerId: params.customerId,
347
- reason: "same customer refresh is already in flight"
348
- });
349
- await this.customerLoginRefreshInFlight;
350
- return;
351
- }
352
- await this.customerLoginRefreshInFlight;
353
- }
354
- this.customerLoginRefreshIdInFlight = params.customerId;
355
- const refreshTask = (async () => {
356
- var _a, _b, _c;
357
- this.smartPricingCustomerId = params.customerId;
358
- await this.store.order.loadDiscountConfig({
359
- customerId: params.customerId
360
- });
361
- this.clearSlotPriceMapCache();
362
- this.recalculateOrderPricesFromSmartPricing();
363
- this.store.order.applyDiscount();
364
- this.normalizeDiscountedOrderPrices(
365
- this.store.order.getDiscountList()
366
- );
367
- await this.store.order.recalculateSummary({ createIfMissing: true });
368
- this.store.order.persistTempOrder();
369
- await this.refreshItemRuleQuantityLimits();
370
- await this.refreshCartValidationPassed();
371
- await ((_c = (_b = (_a = this.core) == null ? void 0 : _a.effects) == null ? void 0 : _b.emit) == null ? void 0 : _c.call(_b, import_types.VenueBookingHooks.onSmartPricingUpdated, {
372
- customerId: params.customerId
373
- }));
374
- })();
375
- this.customerLoginRefreshInFlight = refreshTask;
376
- try {
377
- await refreshTask;
378
- } catch (error) {
379
- throw error;
380
- } finally {
381
- if (this.customerLoginRefreshInFlight === refreshTask) {
382
- this.customerLoginRefreshInFlight = null;
383
- this.customerLoginRefreshIdInFlight = null;
384
- }
385
- }
386
- }
387
- async initialize(core, options = {}) {
388
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
389
- this.logMethodStart("initialize");
390
- this.core = core;
391
- this.initializeOptions = options || {};
392
- this.store = { ...this.store, ...options.store };
393
- this.smartPricingCustomerId = void 0;
394
- this.store.entryContext = ((_a = options.otherParams) == null ? void 0 : _a.entryContext) || this.store.entryContext;
395
- this.store.status = "initializing";
396
- this.store.error = null;
397
- this.store.rawResourceData = [];
398
- this.baseSlotConfig = {
399
- ...import_types.DEFAULT_SLOT_CONFIG,
400
- ...((_b = options.otherParams) == null ? void 0 : _b.slotConfig) || {}
401
- };
402
- this.store.slotConfig = { ...this.baseSlotConfig };
403
- this.otherParams = options.otherParams || {};
404
- this.cacheId = (_c = this.otherParams) == null ? void 0 : _c.cacheId;
405
- this.logPricingDiagnostics("[VenueBooking] initialize product loading state", {
406
- hasLoadAllProductsInFlight: !!this.loadAllProductsInFlight,
407
- productsLoaded: this.productsLoaded,
408
- smartPricingProductCatalogCount: this.smartPricingProductCatalog.length,
409
- note: "initialize currently does not reset the product loading state"
410
- });
411
- this.itemRuleRuntimeConfig = ((_d = this.otherParams) == null ? void 0 : _d.venueBookingItemRule) || ((_e = this.otherParams) == null ? void 0 : _e.itemRule) || {};
412
- this.itemRuleConfigs = [];
413
- this.itemRuleConfigsPromise = null;
414
- this.itemRulePrefillApplied = false;
415
- this.store.itemRuleQuantityLimits = [];
416
- this.store.cartValidation = {
417
- passed: null,
418
- failures: []
419
- };
420
- this.window = core.getPlugin("window");
421
- this.request = core.getPlugin("request");
422
- if (!this.window) {
423
- this.logMethodError("initialize", "window plugin missing");
424
- throw new Error("venueBooking解决方案需要 window 插件支持");
425
- }
426
- if (!this.request) {
427
- this.logMethodError("initialize", "request plugin missing");
428
- throw new Error("venueBooking解决方案需要 request 插件支持");
429
- }
430
- const baseModules = [
431
- "scanOrderLogger",
432
- "products",
433
- "order",
434
- "salesSummary"
435
- ];
436
- baseModules.forEach((step) => {
437
- var _a2, _b2, _c2, _d2, _e2, _f2;
438
- const targetModule = (0, import_types2.createModule)(step, this.name);
439
- if (targetModule) {
440
- this.store[step] = targetModule;
441
- const initialState = step === "salesSummary" ? {
442
- summary: ((_b2 = (_a2 = this.store.order) == null ? void 0 : _a2.getTempOrder()) == null ? void 0 : _b2.summary) || (0, import_utils.createEmptySummary)()
443
- } : {};
444
- const loggerProvider = ((_c2 = this.otherParams) == null ? void 0 : _c2.loggerProvider) || "feishu";
445
- const loggerConfig = ((_d2 = this.otherParams) == null ? void 0 : _d2.loggerConfig) || {
446
- feishu: {
447
- webhook: "https://open.feishu.cn/open-apis/bot/v2/hook/8f069b14-9d39-4728-8f78-b56f393bfde8",
448
- errorHook: "https://open.feishu.cn/open-apis/bot/v2/hook/bdefae5e-f233-4705-8688-946887d9543d"
449
- }
450
- };
451
- this.core.registerModule(targetModule, {
452
- initialState,
453
- otherParams: {
454
- ...this.otherParams,
455
- fatherModule: this.name,
456
- openCache: ((_e2 = this.otherParams) == null ? void 0 : _e2.cacheId) ? true : false,
457
- cacheId: (_f2 = this.otherParams) == null ? void 0 : _f2.cacheId,
458
- salesSummaryModuleName: `${this.name}_salesSummary`,
459
- provider: loggerProvider,
460
- providerConfig: loggerConfig,
461
- context: this.getLoggerContext()
462
- }
463
- });
464
- } else {
465
- this.logMethodError("initialize", `module ${step} missing`);
466
- throw new Error(`模块 ${step} 不存在`);
467
- }
468
- });
469
- const venueProductsModule = new import_ProductList.ProductList(`${this.name}_venueProducts`);
470
- this.store.venueProducts = venueProductsModule;
471
- this.core.registerModule(venueProductsModule, {
472
- otherParams: {
473
- ...this.otherParams,
474
- fatherModule: this.name
475
- }
476
- });
477
- const addonProductsModule = new import_ProductList.ProductList(`${this.name}_addonProducts`);
478
- this.store.addonProducts = addonProductsModule;
479
- this.core.registerModule(addonProductsModule, {
480
- otherParams: {
481
- ...this.otherParams,
482
- fatherModule: this.name
483
- }
484
- });
485
- const dateModule = new import_Date.DateModule(`${this.name}_date`);
486
- this.store.date = dateModule;
487
- this.core.registerModule(dateModule, {
488
- otherParams: {
489
- ...this.otherParams,
490
- fatherModule: this.name,
491
- cacheId: this.cacheId
492
- }
493
- });
494
- const scheduleModule = new import_Schedule.ScheduleModule(`${this.name}_schedule`);
495
- this.store.schedule = scheduleModule;
496
- this.core.registerModule(scheduleModule, {
497
- otherParams: {
498
- ...this.otherParams,
499
- fatherModule: this.name
500
- }
501
- });
502
- const quotationModule = new import_Quotation.QuotationModule(`${this.name}_quotation`);
503
- this.store.quotation = quotationModule;
504
- this.core.registerModule(quotationModule, {
505
- otherParams: {
506
- ...this.otherParams,
507
- fatherModule: this.name
508
- }
509
- });
510
- const openDataModule = new import_OpenData.OpenDataModule(`${this.name}_openData`);
511
- this.store.openData = openDataModule;
512
- this.core.registerModule(openDataModule, {
513
- otherParams: {
514
- ...this.otherParams,
515
- fatherModule: this.name,
516
- openCache: !!((_f = this.otherParams) == null ? void 0 : _f.cacheId),
517
- cacheId: (_g = this.otherParams) == null ? void 0 : _g.cacheId
518
- }
519
- });
520
- if (this.store.scanOrderLogger) {
521
- this.store.scanOrderLogger.setContext(this.getLoggerContext());
522
- }
523
- this.registerCustomerLoginListeners();
524
- console.log("[VenueBooking] 初始化开始");
525
- try {
526
- await ((_h = this.store.order) == null ? void 0 : _h.recalculateSummary({ createIfMissing: false }));
527
- (_i = this.store.order) == null ? void 0 : _i.persistTempOrder();
528
- await this.loadRuntimeConfigs();
529
- if (this.store.schedule) {
530
- await this.store.schedule.loadAllSchedule();
531
- }
532
- await this.refreshItemRuleQuantityLimits();
533
- this.store.status = "ready";
534
- console.log("[VenueBooking] 初始化完成");
535
- await this.core.effects.emit(import_types.VenueBookingHooks.onInited, {
536
- status: this.store.status
537
- });
538
- this.logMethodSuccess("initialize", {
539
- status: this.store.status
540
- });
541
- } catch (error) {
542
- this.store.status = "error";
543
- this.store.error = error instanceof Error ? error.message : "初始化失败";
544
- console.error("[VenueBooking] 初始化失败", error);
545
- this.logMethodError("initialize", error, {
546
- status: this.store.status
547
- });
548
- throw error;
549
- }
550
- }
551
- async destroy() {
552
- this.logMethodStart("destroy");
553
- this.clearLoginEffectListeners();
554
- await this.core.effects.emit(import_types.VenueBookingHooks.onDestroy, {});
555
- console.log("[VenueBooking] 已销毁");
556
- this.logMethodSuccess("destroy");
557
- }
558
- async retryInit() {
559
- this.logMethodStart("retryInit");
560
- console.log("[VenueBooking] retryInit 调用");
561
- await this.core.effects.emit(import_types.VenueBookingHooks.onRetryInit, {});
562
- try {
563
- await this.initialize(this.core, this.initializeOptions);
564
- this.logMethodSuccess("retryInit");
565
- } catch (error) {
566
- this.logMethodError("retryInit", error);
567
- throw error;
568
- }
569
- }
570
- async refresh() {
571
- this.logMethodStart("refresh");
572
- console.log("[VenueBooking] refresh 调用");
573
- try {
574
- this.store.status = "initializing";
575
- await this.loadRuntimeConfigs();
576
- await this.refreshItemRuleQuantityLimits();
577
- this.store.status = "ready";
578
- await this.core.effects.emit(import_types.VenueBookingHooks.onRefresh, {
579
- status: this.store.status
580
- });
581
- this.logMethodSuccess("refresh", {
582
- status: this.store.status
583
- });
584
- } catch (error) {
585
- this.logMethodError("refresh", error);
586
- throw error;
587
- }
588
- }
589
- // ─── 状态查询 ───
590
- getStatus() {
591
- return this.store.status;
592
- }
593
- getEntryContext() {
594
- return this.store.entryContext;
595
- }
596
- getItemRuleQuantityLimits() {
597
- return this.store.itemRuleQuantityLimits || [];
598
- }
599
- getCartValidationPassed() {
600
- var _a;
601
- return ((_a = this.store.cartValidation) == null ? void 0 : _a.passed) ?? null;
602
- }
603
- getCartValidation() {
604
- return this.store.cartValidation || { passed: null, failures: [] };
605
- }
606
- /** 清除 slot 价格分段缓存(商品重载 / 登录后 customerId 变化时调用) */
607
- clearSlotPriceMapCache() {
608
- this.slotPriceMapCache.clear();
609
- }
610
- /** 读取当前登录 customerId */
611
- resolveCustomerIdForSmartPricing() {
612
- var _a, _b, _c;
613
- if (this.smartPricingCustomerId)
614
- return this.smartPricingCustomerId;
615
- try {
616
- const userPlugin = (_a = this.core) == null ? void 0 : _a.getPlugin("user");
617
- const customerId = Number((_c = (_b = userPlugin == null ? void 0 : userPlugin.get) == null ? void 0 : _b.call(userPlugin)) == null ? void 0 : _c.id);
618
- return Number.isFinite(customerId) && customerId > 0 ? customerId : void 0;
619
- } catch {
620
- return void 0;
621
- }
622
- }
623
- resolveAvailableWalletIdsForSmartPricing() {
624
- var _a, _b, _c, _d, _e, _f, _g, _h;
625
- const orderWalletIds = (_b = (_a = this.store.order) == null ? void 0 : _a.getAvailableWalletIds) == null ? void 0 : _b.call(_a);
626
- const fallbackWalletIds = ((_c = this.otherParams) == null ? void 0 : _c.available_wallet_ids) || ((_d = this.otherParams) == null ? void 0 : _d.availableWalletIds) || ((_f = (_e = this.otherParams) == null ? void 0 : _e.strategy_context) == null ? void 0 : _f.available_wallet_ids) || ((_h = (_g = this.otherParams) == null ? void 0 : _g.strategy_context) == null ? void 0 : _h.availableWalletIds);
627
- const source = Array.isArray(orderWalletIds) && orderWalletIds.length ? orderWalletIds : fallbackWalletIds;
628
- if (!Array.isArray(source))
629
- return [];
630
- const ids = source.map((item) => Number(item)).filter((item) => Number.isFinite(item) && item > 0);
631
- return Array.from(new Set(ids));
632
- }
633
- /** 读取 schedule 全量列表,供智能定价 schedule_match 使用 */
634
- getScheduleListForSmartPricing() {
635
- var _a;
636
- const scheduleModule = this.store.schedule;
637
- const list = (_a = scheduleModule == null ? void 0 : scheduleModule.store) == null ? void 0 : _a.scheduleList;
638
- return Array.isArray(list) ? list : [];
639
- }
640
- /** 构建智能定价上下文,对齐 OS Server buildProductFormatterContext */
641
- buildSmartPricingContext(customerId) {
642
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
643
- const evaluator = (_b = (_a = this.core) == null ? void 0 : _a.context) == null ? void 0 : _b.dataVariantEvaluator;
644
- return {
645
- evaluator,
646
- scheduleList: this.getScheduleListForSmartPricing(),
647
- menuList: ((_c = this.otherParams) == null ? void 0 : _c.menuList) || ((_e = (_d = this.otherParams) == null ? void 0 : _d.openData) == null ? void 0 : _e.menuList) || [],
648
- customerId: customerId ?? this.resolveCustomerIdForSmartPricing(),
649
- availableWalletIds: this.resolveAvailableWalletIdsForSmartPricing(),
650
- channel: (_f = this.otherParams) == null ? void 0 : _f.channel,
651
- businessCode: (_g = this.otherParams) == null ? void 0 : _g.businessCode,
652
- orderType: ((_h = this.otherParams) == null ? void 0 : _h.orderType) || ((_i = this.otherParams) == null ? void 0 : _i.type),
653
- strategy_context: (_j = this.otherParams) == null ? void 0 : _j.strategy_context,
654
- ...this.isPricingDiagnosticsEnabled() ? {
655
- debugLog: (title, payload = {}) => this.logPricingDiagnostics(title, payload)
656
- } : {}
657
- };
658
- }
659
- /** venue + addon 全量商品,供智能定价评估 */
660
- getAllProductsForSmartPricing() {
661
- if (this.smartPricingProductCatalog.length) {
662
- return this.smartPricingProductCatalog;
663
- }
664
- const venueList = this.getVenueProducts();
665
- const addonList = this.getAddonProductsList();
666
- return [...venueList, ...addonList];
667
- }
668
- getSlotPriceMapCacheKey(date, context) {
669
- return [
670
- date,
671
- context.customerId ?? "",
672
- (context.availableWalletIds || []).join(","),
673
- context.channel ?? "",
674
- context.businessCode ?? ""
675
- ].join("|");
676
- }
677
- /**
678
- * 按 schedule 分段构建 slot 价格 Map,带实例级缓存。
679
- */
680
- buildSlotPriceMapForDate(date, config, productIds) {
681
- const context = this.buildSmartPricingContext();
682
- const cacheKey = this.getSlotPriceMapCacheKey(date, context);
683
- const cached = this.slotPriceMapCache.get(cacheKey);
684
- if (cached)
685
- return cached;
686
- const timeLabels = (0, import_timeSlot.generateTimeLabels)(config);
687
- const slotPriceMap = (0, import_smartPricing.buildSlotPriceMapByScheduleSegments)({
688
- products: this.getAllProductsForSmartPricing(),
689
- productIds,
690
- date,
691
- timeLabels,
692
- config,
693
- context
694
- });
695
- this.slotPriceMapCache.set(cacheKey, slotPriceMap);
696
- return slotPriceMap;
697
- }
698
- // ─── 场地商品 & 附加商品 ───
699
- async loadAllProducts() {
700
- this.logPricingDiagnostics("[VenueBooking] loadAllProducts called", {
701
- hasLoadAllProductsInFlight: !!this.loadAllProductsInFlight,
702
- productsLoaded: this.productsLoaded,
703
- smartPricingCustomerId: this.smartPricingCustomerId,
704
- smartPricingProductCatalogCount: this.smartPricingProductCatalog.length,
705
- venueProducts: !this.store.venueProducts,
706
- addonProducts: !this.store.addonProducts
707
- });
708
- if (this.loadAllProductsInFlight) {
709
- this.logPricingDiagnostics("[VenueBooking] loadAllProducts request skipped", {
710
- reason: "reusing existing loadAllProductsInFlight promise",
711
- productsLoaded: this.productsLoaded
712
- });
713
- return this.loadAllProductsInFlight;
714
- }
715
- this.logPricingDiagnostics("[VenueBooking] loadAllProducts request starting", {
716
- productsLoaded: this.productsLoaded,
717
- smartPricingCustomerId: this.smartPricingCustomerId
718
- });
719
- this.loadAllProductsInFlight = this._doLoadAllProducts().finally(() => {
720
- this.logPricingDiagnostics("[VenueBooking] loadAllProducts request settled", {
721
- productsLoaded: this.productsLoaded,
722
- smartPricingProductCatalogCount: this.smartPricingProductCatalog.length
723
- });
724
- this.loadAllProductsInFlight = null;
725
- });
726
- return this.loadAllProductsInFlight;
727
- }
728
- async _doLoadAllProducts() {
729
- var _a, _b, _c;
730
- this.logMethodStart("loadAllProducts");
731
- try {
732
- if (!this.store.venueProducts)
733
- throw new Error("venueProducts 模块未初始化");
734
- if (!this.store.addonProducts)
735
- throw new Error("addonProducts 模块未初始化");
736
- await this.loadOpenDataConfig();
737
- const associatedMenus = ((_b = (_a = this.otherParams) == null ? void 0 : _a.openData) == null ? void 0 : _b["menu.associated_menus"]) || [];
738
- if (!associatedMenus.length) {
739
- this.logMethodError("loadAllProducts", new Error("未获取到餐牌配置(menu.associated_menus),请检查 OpenData 配置"));
740
- throw new Error("未获取到餐牌配置(menu.associated_menus),请检查 OpenData 配置");
741
- }
742
- const menuListIds = associatedMenus.map((n) => Number(n.value));
743
- const allProducts = await this.store.venueProducts.loadProducts({
744
- menu_list_ids: menuListIds,
745
- cacheId: this.cacheId,
746
- schedule_date: (0, import_dayjs.default)().format("YYYY-MM-DD"),
747
- schedule_datetime: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss"),
748
- with_extra: ["dataVariants"]
749
- });
750
- const rawList = Array.isArray(allProducts) ? allProducts : [];
751
- let list = rawList;
752
- this.smartPricingProductCatalog = rawList.slice();
753
- const smartPricingContext = this.buildSmartPricingContext();
754
- list = (0, import_smartPricing.formatProductsWithDataVariant)(
755
- list,
756
- smartPricingContext,
757
- (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
758
- );
759
- if (this.isPricingDiagnosticsEnabled()) {
760
- this.logPricingDiagnostics("[VenueBooking] loadAllProducts smart pricing context", {
761
- smartPricingContext,
762
- rawList,
763
- list,
764
- otherParams: this.otherParams,
765
- availableWalletIds: this.getAvailableWalletIdsForDiagnostics()
766
- });
767
- }
768
- this.clearSlotPriceMapCache();
769
- const venueList = list.filter((p) => p.duration != null);
770
- const addonList = list.filter((p) => p.duration == null);
771
- const venueStore = (_c = this.store.venueProducts) == null ? void 0 : _c.store;
772
- if (venueStore) {
773
- venueStore.list = venueList.slice().sort((a, b) => Number(b.sort) - Number(a.sort));
774
- }
775
- this.store.addonProducts.addProduct(addonList);
776
- this.resourceProductMap = (0, import_resource.buildResourceProductMap)(venueList);
777
- this.productsLoaded = true;
778
- this.logMethodSuccess("loadAllProducts", {
779
- total: list.length,
780
- venueCount: venueList.length,
781
- addonCount: addonList.length,
782
- resourceCount: this.resourceProductMap.size
783
- });
784
- return { venueProducts: venueList, addonProducts: addonList };
785
- } catch (error) {
786
- this.logMethodError("loadAllProducts", error);
787
- throw error;
788
- }
789
- }
790
- async loadVenueProducts() {
791
- this.logPricingDiagnostics("[VenueBooking] loadVenueProducts called", {
792
- hasLoadAllProductsInFlight: !!this.loadAllProductsInFlight,
793
- productsLoaded: this.productsLoaded
794
- });
795
- const result = await this.loadAllProducts();
796
- return result.venueProducts;
797
- }
798
- async loadAddonProducts() {
799
- const result = await this.loadAllProducts();
800
- return result.addonProducts;
801
- }
802
- getVenueProducts() {
803
- var _a, _b;
804
- return ((_b = (_a = this.store.venueProducts) == null ? void 0 : _a.store) == null ? void 0 : _b.list) || [];
805
- }
806
- getAddonProductsList() {
807
- var _a, _b;
808
- return ((_b = (_a = this.store.addonProducts) == null ? void 0 : _a.store) == null ? void 0 : _b.list) || [];
809
- }
810
- // ─── 报价单 ───
811
- async loadQuotations(params) {
812
- this.logMethodStart("loadQuotations");
813
- try {
814
- if (!this.store.quotation)
815
- throw new Error("quotation 模块未初始化");
816
- await this.store.quotation.loadQuotations(params);
817
- this.logMethodSuccess("loadQuotations", {
818
- count: this.store.quotation.getQuotationList().length
819
- });
820
- } catch (error) {
821
- this.logMethodError("loadQuotations", error);
822
- throw error;
823
- }
824
- }
825
- // ─── 资源可用性 ───
826
- async fetchResourceAvailability(params) {
827
- this.logMethodStart("fetchResourceAvailability", params);
828
- try {
829
- const venueProducts = this.getVenueProducts();
830
- if (!venueProducts.length) {
831
- this.store.rawResourceData = [];
832
- this.logMethodSuccess("fetchResourceAvailability", { resourceCount: 0 });
833
- return;
834
- }
835
- const resourceIds = (0, import_resource.extractResourceIds)(venueProducts);
836
- if (!resourceIds.length) {
837
- this.store.rawResourceData = [];
838
- this.logMethodSuccess("fetchResourceAvailability", { resourceIds: [] });
839
- return;
840
- }
841
- const config = this.store.slotConfig;
842
- const crossDay = (0, import_timeSlot.isBusinessHoursCrossDay)(config);
843
- const effectiveEndDate = crossDay ? (0, import_dayjs.default)(params.endDate).add(1, "day").format("YYYY-MM-DD") : params.endDate;
844
- if (!this.store.date)
845
- throw new Error("date 模块未初始化");
846
- const res = await this.store.date.fetchResourceDates({
847
- query: {
848
- start_date: params.startDate,
849
- end_date: effectiveEndDate,
850
- resource_ids: resourceIds
851
- },
852
- useCache: false
853
- });
854
- const rawData = [];
855
- if ((res == null ? void 0 : res.data) && Array.isArray(res.data)) {
856
- for (const item of res.data) {
857
- rawData.push({
858
- resourceId: item.id,
859
- formId: item.form_id,
860
- times: Array.isArray(item.times) ? item.times : [],
861
- ...item
862
- });
863
- }
864
- }
865
- this.store.rawResourceData = rawData;
866
- for (const item of rawData) {
867
- const mappings = this.resourceProductMap.get(item.resourceId);
868
- if (!mappings)
869
- continue;
870
- for (const mapping of mappings) {
871
- if (item.main_field)
872
- mapping.resourceName = item.main_field;
873
- if (item.resource_form_id)
874
- mapping.formId = item.resource_form_id;
875
- }
876
- }
877
- this.logMethodSuccess("fetchResourceAvailability", {
878
- resourceCount: rawData.length,
879
- totalTimes: rawData.reduce((sum, r) => sum + r.times.length, 0)
880
- });
881
- } catch (error) {
882
- this.store.rawResourceData = [];
883
- this.logMethodError("fetchResourceAvailability", error);
884
- throw error;
885
- }
886
- }
887
- // ─── 日期概览 & 时间槽矩阵(纯计算,不发请求) ───
888
- getOperatingHoursScheduleIds() {
889
- var _a, _b;
890
- const openData = this.otherParams.openData || ((_b = (_a = this.store.openData) == null ? void 0 : _a.getOpenData) == null ? void 0 : _b.call(_a)) || null;
891
- const rawIds = openData == null ? void 0 : openData["availability.operating_hours"];
892
- if (!Array.isArray(rawIds))
893
- return [];
894
- return [...new Set(
895
- rawIds.map((id) => Number(id)).filter((id) => Number.isFinite(id) && id > 0).map((id) => Math.floor(id))
896
- )];
897
- }
898
- resolveSlotConfigForDate(date) {
899
- var _a;
900
- const nextSlotConfig = { ...this.baseSlotConfig };
901
- if (!date || !this.store.schedule)
902
- return nextSlotConfig;
903
- const operatingHoursScheduleIds = this.getOperatingHoursScheduleIds();
904
- if (!operatingHoursScheduleIds.length)
905
- return nextSlotConfig;
906
- const scheduleList = this.store.schedule.getScheduleListByIds(
907
- operatingHoursScheduleIds
908
- );
909
- if (!scheduleList.length)
910
- return nextSlotConfig;
911
- const timeRangeMap = (0, import_utils2.calcMinTimeMaxTimeBySchedules)(
912
- scheduleList,
913
- void 0,
914
- date
915
- );
916
- let earliestStart = null;
917
- let latestEnd = null;
918
- for (const schedule of scheduleList) {
919
- const dateRangeList = ((_a = timeRangeMap == null ? void 0 : timeRangeMap[schedule.id]) == null ? void 0 : _a.dateRangeFormat) || [];
920
- for (const range of dateRangeList) {
921
- const start = (0, import_dayjs.default)(range == null ? void 0 : range.start);
922
- const end = (0, import_dayjs.default)(range == null ? void 0 : range.end);
923
- if (!start.isValid() || !end.isValid())
924
- continue;
925
- if (!earliestStart || start.isBefore(earliestStart)) {
926
- earliestStart = start;
927
- }
928
- if (!latestEnd || end.isAfter(latestEnd)) {
929
- latestEnd = end;
930
- }
931
- }
932
- }
933
- if (!earliestStart || !latestEnd)
934
- return nextSlotConfig;
935
- return {
936
- ...nextSlotConfig,
937
- businessStartTime: earliestStart.format("HH:mm"),
938
- businessEndTime: latestEnd.format("HH:mm")
939
- };
940
- }
941
- syncOperatingHoursToSlotConfig(date) {
942
- const resolvedSlotConfig = this.resolveSlotConfigForDate(date);
943
- this.store.slotConfig = resolvedSlotConfig;
944
- return resolvedSlotConfig;
945
- }
946
- getDateRangeSummary(params) {
947
- return (0, import_dateSummary.buildDateRangeSummary)({
948
- startDate: params.startDate,
949
- endDate: params.endDate,
950
- config: this.baseSlotConfig,
951
- rawResources: this.store.rawResourceData,
952
- resourceProductMap: this.resourceProductMap,
953
- resolveConfig: (date) => this.resolveSlotConfigForDate(date),
954
- buildSlotPriceMap: (date, config, productIds) => this.buildSlotPriceMapForDate(date, config, productIds)
955
- });
956
- }
957
- getTimeSlotGrid(date) {
958
- const resolvedSlotConfig = this.syncOperatingHoursToSlotConfig(date);
959
- const productIds = [
960
- ...new Set(
961
- [...this.resourceProductMap.values()].flat().map((m) => m.productId)
962
- )
963
- ];
964
- const slotPriceMap = productIds.length ? this.buildSlotPriceMapForDate(date, resolvedSlotConfig, productIds) : void 0;
965
- return (0, import_timeSlot.buildTimeSlotGrid)({
966
- date,
967
- config: resolvedSlotConfig,
968
- rawResources: this.store.rawResourceData,
969
- resourceProductMap: this.resourceProductMap,
970
- slotPriceMap
971
- });
972
- }
973
- // ─── 时间槽订单操作 ───
974
- /**
975
- * 切换单个时段的选中状态(选中/取消)。
976
- * 内部自动处理连续时段的合并与拆分,订单是唯一真相源。
977
- *
978
- * slot.productId 指定当前操作针对的是该 resourceId 下的哪一个商品。
979
- * 同一资源下不同 productId 之间互相隔离,不会相互合并。
980
- */
981
- async toggleSlot(slot) {
982
- this.logMethodStart("toggleSlot", {
983
- resourceId: slot.resourceId,
984
- productId: slot.productId,
985
- startTime: slot.startTime
986
- });
987
- try {
988
- const mappings = this.resourceProductMap.get(slot.resourceId);
989
- if (!mappings || !mappings.length) {
990
- throw new Error(`未找到资源 ${slot.resourceId} 的商品映射`);
991
- }
992
- const mapping = mappings.find((m) => m.productId === slot.productId);
993
- if (!mapping) {
994
- throw new Error(`资源 ${slot.resourceId} 未关联商品 ${slot.productId}`);
995
- }
996
- if (!this.store.order)
997
- throw new Error("order 模块未初始化");
998
- const currentSlots = this.getSelectedSlotsForResourceProduct(
999
- slot.resourceId,
1000
- slot.productId
1001
- );
1002
- const existIndex = currentSlots.findIndex((s) => s.startTime === slot.startTime);
1003
- let nextSlots;
1004
- if (existIndex !== -1) {
1005
- nextSlots = currentSlots.filter((_, i) => i !== existIndex);
1006
- } else {
1007
- nextSlots = [...currentSlots, slot];
1008
- }
1009
- await this.reconcileOrderForResourceProduct(
1010
- slot.resourceId,
1011
- slot.productId,
1012
- nextSlots
1013
- );
1014
- const products = this.store.order.getOrderProducts();
1015
- await this.refreshItemRuleQuantityLimits();
1016
- await this.refreshCartValidationPassed();
1017
- this.logMethodSuccess("toggleSlot", {
1018
- action: existIndex !== -1 ? "remove" : "add",
1019
- resourceId: slot.resourceId,
1020
- productId: slot.productId,
1021
- slotCount: nextSlots.length
1022
- });
1023
- return products;
1024
- } catch (error) {
1025
- this.logMethodError("toggleSlot", error);
1026
- throw error;
1027
- }
1028
- }
1029
- /**
1030
- * 获取某资源当前选中的所有独立时段(从订单中解析)。
1031
- * 不传 productId 时返回该资源下所有商品的选中时段;传了则精确匹配。
1032
- */
1033
- getSelectedSlotsForResource(resourceId, productId) {
1034
- var _a;
1035
- const tempOrder = (_a = this.store.order) == null ? void 0 : _a.getTempOrder();
1036
- if (!tempOrder)
1037
- return [];
1038
- const venueProducts = tempOrder.products.filter((p) => {
1039
- var _a2, _b;
1040
- if (!((_a2 = p.metadata) == null ? void 0 : _a2.venue_booking))
1041
- return false;
1042
- if (String((_b = p.metadata) == null ? void 0 : _b.resource_id) !== String(resourceId))
1043
- return false;
1044
- if (productId != null && Number(p.product_id) !== Number(productId))
1045
- return false;
1046
- return true;
1047
- });
1048
- const slotDuration = this.store.slotConfig.slotDurationMinutes;
1049
- const slots = [];
1050
- for (const product of venueProducts) {
1051
- slots.push(
1052
- ...(0, import_slotMerge.expandMergedSlotToIndividual)(product, slotDuration).map((s) => ({
1053
- ...s,
1054
- productId: Number(product.product_id)
1055
- }))
1056
- );
1057
- }
1058
- return slots.sort((a, b) => a.startTime.localeCompare(b.startTime));
1059
- }
1060
- /** getSelectedSlotsForResource 的 (resourceId, productId) 精确版,内部使用。 */
1061
- getSelectedSlotsForResourceProduct(resourceId, productId) {
1062
- return this.getSelectedSlotsForResource(resourceId, productId);
1063
- }
1064
- /**
1065
- * 判断某个时段是否已选中。
1066
- * 不传 productId 时:只要该资源下任一商品在 startTime 被选中即返回 true;传了则精确匹配。
1067
- */
1068
- isSlotSelected(resourceId, startTime, productId) {
1069
- return this.getSelectedSlotsForResource(resourceId, productId).some((s) => s.startTime === startTime);
1070
- }
1071
- /**
1072
- * 判断指定 (resourceId, productId, startTime) 格子是否应因其它已选项而被禁用。
1073
- * 规则:
1074
- * 1) 同一 resourceId 下若已选了另一个 productId 的同 startTime → 禁用
1075
- * 2) 当前 resource 是组合资源:若其任一 child resource 在 startTime 被选中 → 禁用
1076
- * 3) 当前 resource 是某些组合资源的 child:若该组合资源在 startTime 被选中 → 禁用
1077
- * 4) 两个组合资源的 child 集合有交集,且对方在该 startTime 被选中 → 禁用
1078
- */
1079
- isSlotDisabledBySelection(params) {
1080
- const { resourceId, productId, startTime } = params;
1081
- const allSelected = this.getAllSelectedSlots();
1082
- const getSelectedAt = (resId) => {
1083
- const list = allSelected.get(resId) || [];
1084
- return list.filter((s) => s.startTime === startTime);
1085
- };
1086
- const sameResourceSelections = getSelectedAt(resourceId);
1087
- if (sameResourceSelections.some((s) => Number(s.productId) !== Number(productId))) {
1088
- return true;
1089
- }
1090
- const getCombinedChildIds = (resId) => {
1091
- const raw = this.store.rawResourceData.find(
1092
- (r) => String(r.resourceId) === String(resId)
1093
- );
1094
- const combined = raw == null ? void 0 : raw.combined_resource;
1095
- if (combined && combined.status === 1 && Array.isArray(combined.resource_ids)) {
1096
- return combined.resource_ids;
1097
- }
1098
- return [];
1099
- };
1100
- const currentChildIds = getCombinedChildIds(resourceId);
1101
- const currentIsCombined = currentChildIds.length > 0;
1102
- if (currentIsCombined) {
1103
- for (const childId of currentChildIds) {
1104
- if (getSelectedAt(childId).length > 0)
1105
- return true;
1106
- }
1107
- }
1108
- for (const [selectedResId, slots] of allSelected) {
1109
- if (!slots.some((s) => s.startTime === startTime))
1110
- continue;
1111
- if (String(selectedResId) === String(resourceId))
1112
- continue;
1113
- const selectedChildIds = getCombinedChildIds(selectedResId);
1114
- if (selectedChildIds.length === 0)
1115
- continue;
1116
- if (selectedChildIds.some((id) => String(id) === String(resourceId))) {
1117
- return true;
1118
- }
1119
- if (currentIsCombined) {
1120
- const intersect = selectedChildIds.some(
1121
- (id) => currentChildIds.some((cid) => String(cid) === String(id))
1122
- );
1123
- if (intersect)
1124
- return true;
1125
- }
1126
- }
1127
- return false;
1128
- }
1129
- /**
1130
- * 获取所有已选时段(按资源分组)。每个 slot 上带 productId,便于 UI 做 per-product 判定。
1131
- */
1132
- getAllSelectedSlots() {
1133
- var _a, _b;
1134
- const result = /* @__PURE__ */ new Map();
1135
- const tempOrder = (_a = this.store.order) == null ? void 0 : _a.getTempOrder();
1136
- if (!tempOrder)
1137
- return result;
1138
- const venueProducts = tempOrder.products.filter((p) => {
1139
- var _a2;
1140
- return (_a2 = p.metadata) == null ? void 0 : _a2.venue_booking;
1141
- });
1142
- const slotDuration = this.store.slotConfig.slotDurationMinutes;
1143
- for (const product of venueProducts) {
1144
- const resourceId = (_b = product.metadata) == null ? void 0 : _b.resource_id;
1145
- if (resourceId == null)
1146
- continue;
1147
- const productId = Number(product.product_id);
1148
- const existing = result.get(resourceId) || [];
1149
- existing.push(
1150
- ...(0, import_slotMerge.expandMergedSlotToIndividual)(product, slotDuration).map((s) => ({
1151
- ...s,
1152
- productId
1153
- }))
1154
- );
1155
- result.set(resourceId, existing);
1156
- }
1157
- for (const [key, slots] of result) {
1158
- result.set(key, slots.sort((a, b) => a.startTime.localeCompare(b.startTime)));
1159
- }
1160
- return result;
1161
- }
1162
- /**
1163
- * 对指定 (resourceId, productId) 的订单商品进行 reconcile:
1164
- * 清除旧商品 → 合并连续时段 → 重新写入。
1165
- * 同一场地下不同商品互不干扰,各自单独 reconcile。
1166
- */
1167
- async reconcileOrderForResourceProduct(resourceId, productId, slots) {
1168
- const mappings = this.resourceProductMap.get(resourceId);
1169
- if (!mappings || !mappings.length || !this.store.order)
1170
- return;
1171
- const mapping = mappings.find((m) => m.productId === productId);
1172
- if (!mapping)
1173
- return;
1174
- const tempOrder = this.store.order.ensureTempOrder();
1175
- const matchesCurrent = (meta, pid) => !!(meta == null ? void 0 : meta.venue_booking) && String(meta == null ? void 0 : meta.resource_id) === String(resourceId) && Number(pid) === Number(productId);
1176
- tempOrder.products = tempOrder.products.filter(
1177
- (p) => !matchesCurrent(p.metadata, p.product_id)
1178
- );
1179
- tempOrder.bookings = (tempOrder.bookings || []).filter(
1180
- (b) => {
1181
- var _a, _b, _c, _d;
1182
- if (!((_a = b.metadata) == null ? void 0 : _a.venue_booking))
1183
- return true;
1184
- if (String((_b = b.metadata) == null ? void 0 : _b.resource_id) !== String(resourceId))
1185
- return true;
1186
- const bookingProductId = ((_c = b.metadata) == null ? void 0 : _c.product_id) ?? ((_d = b == null ? void 0 : b.product) == null ? void 0 : _d.product_id);
1187
- if (bookingProductId == null)
1188
- return false;
1189
- return Number(bookingProductId) !== Number(productId);
1190
- }
1191
- );
1192
- if (!slots.length) {
1193
- this.store.order.applyDiscount();
1194
- await this.store.order.recalculateSummary({ createIfMissing: true });
1195
- this.store.order.persistTempOrder();
1196
- return;
1197
- }
1198
- const merged = (0, import_slotMerge.mergeConsecutiveSlots)(slots);
1199
- const rawResource = this.store.rawResourceData.find(
1200
- (r) => String(r.resourceId) === String(resourceId)
1201
- );
1202
- const childRawResources = this.getCombinedChildRawResources(rawResource);
1203
- const venueProduct = this.getVenueProducts().find((p) => p.id === mapping.productId);
1204
- tempOrder.bookings = tempOrder.bookings || [];
1205
- for (let i = 0; i < merged.length; i++) {
1206
- const group = merged[i];
1207
- const identityKey = (0, import_slotMerge.buildVenueIdentityKey)(resourceId, i);
1208
- const bookingUuid = (0, import_utils3.createUuidV4)();
1209
- const startMoment = (0, import_dayjs.default)(group.startTime, "YYYY-MM-DD HH:mm");
1210
- const endMoment = (0, import_dayjs.default)(group.endTime, "YYYY-MM-DD HH:mm");
1211
- const duration = endMoment.diff(startMoment, "minute");
1212
- const customDepositData = cloneCustomDepositData(venueProduct == null ? void 0 : venueProduct.custom_deposit_data);
1213
- const resourceEntry = {
1214
- relation_type: "form",
1215
- like_status: "common",
1216
- id: resourceId,
1217
- main_field: mapping.resourceName,
1218
- form_id: (rawResource == null ? void 0 : rawResource.form_id) ?? mapping.formId,
1219
- relation_id: resourceId,
1220
- capacity: 1,
1221
- metadata: (0, import_slotMerge.buildVenueResourceMetadata)({ mapping, rawResource })
1222
- };
1223
- if (childRawResources && childRawResources.length) {
1224
- resourceEntry.children = childRawResources.map((child) => ({
1225
- relation_type: "form",
1226
- like_status: "common",
1227
- id: child.resourceId,
1228
- main_field: child.main_field || "",
1229
- form_id: child.form_id ?? child.formId,
1230
- relation_id: child.resourceId,
1231
- capacity: child.capacity ?? 1,
1232
- metadata: {}
1233
- }));
1234
- }
1235
- tempOrder.products.push(
1236
- (0, import_utils.normalizeOrderProduct)({
1237
- product_id: mapping.productId,
1238
- product_variant_id: 0,
1239
- identity_key: identityKey,
1240
- num: 1,
1241
- selling_price: group.totalPrice,
1242
- original_price: group.totalPrice,
1243
- is_charge_tax: (venueProduct == null ? void 0 : venueProduct.is_charge_tax) ?? 0,
1244
- metadata: {
1245
- venue_booking: true,
1246
- resource_id: resourceId,
1247
- resource_form_id: mapping.formId,
1248
- resource_name: mapping.resourceName,
1249
- start_time: group.startTime,
1250
- end_time: group.endTime,
1251
- slot_count: group.slotCount,
1252
- booking_uid: bookingUuid,
1253
- price_breakdown: (0, import_slotMerge.buildPriceBreakdown)({
1254
- group,
1255
- productId: mapping.productId
1256
- })
1257
- },
1258
- _origin: {
1259
- name: mapping.productTitle,
1260
- cover: (venueProduct == null ? void 0 : venueProduct.cover) || "",
1261
- custom_deposit_data: customDepositData,
1262
- id: 0,
1263
- number: 1,
1264
- registration_type: "all",
1265
- relation_products: [],
1266
- is_all: false,
1267
- product: {
1268
- product_id: mapping.productId,
1269
- product_variant_id: 0,
1270
- num: 1,
1271
- product_bundle: [],
1272
- product_option_item: [],
1273
- discount_list: [],
1274
- custom_deposit_data: customDepositData,
1275
- metadata: {}
1276
- },
1277
- sub_type: "minutes",
1278
- duration,
1279
- like_status: "common",
1280
- resources: [resourceEntry],
1281
- schedule_id: 0,
1282
- select_date: startMoment.format("YYYY-MM-DD"),
1283
- start_date: startMoment.format("YYYY-MM-DD"),
1284
- start_time: startMoment.format("HH:mm"),
1285
- end_date: endMoment.format("YYYY-MM-DD"),
1286
- end_time: endMoment.format("HH:mm"),
1287
- metadata: {
1288
- venue_booking: true,
1289
- slot_count: group.slotCount
1290
- },
1291
- holder: null
1292
- }
1293
- })
1294
- );
1295
- const booking = (0, import_slotMerge.buildVenueBookingEntry)({
1296
- group,
1297
- resourceId,
1298
- mapping,
1299
- rawResource,
1300
- bookingUuid,
1301
- productUid: identityKey,
1302
- childResources: childRawResources
1303
- });
1304
- tempOrder.bookings.push(booking);
1305
- }
1306
- this.store.order.applyDiscount();
1307
- await this.store.order.recalculateSummary({ createIfMissing: true });
1308
- this.store.order.persistTempOrder();
1309
- }
1310
- /** 给定一个父 rawResource,返回其 combined_resource.resource_ids 对应的子 rawResource 列表。 */
1311
- getCombinedChildRawResources(rawResource) {
1312
- if (!rawResource)
1313
- return void 0;
1314
- const combined = rawResource.combined_resource;
1315
- if (!combined || combined.status !== 1 || !Array.isArray(combined.resource_ids) || !combined.resource_ids.length) {
1316
- return void 0;
1317
- }
1318
- const children = [];
1319
- for (const id of combined.resource_ids) {
1320
- const child = this.store.rawResourceData.find(
1321
- (r) => String(r.resourceId) === String(id)
1322
- );
1323
- if (child)
1324
- children.push(child);
1325
- }
1326
- return children.length ? children : void 0;
1327
- }
1328
- // ─── 配置 ───
1329
- setSlotConfig(config) {
1330
- this.baseSlotConfig = {
1331
- ...this.baseSlotConfig,
1332
- ...config
1333
- };
1334
- this.store.slotConfig = {
1335
- ...this.baseSlotConfig
1336
- };
1337
- }
1338
- getSlotConfig() {
1339
- return { ...this.store.slotConfig };
1340
- }
1341
- // ─── 日程 ───
1342
- async loadSchedules() {
1343
- this.logMethodStart("loadSchedules");
1344
- try {
1345
- if (!this.store.schedule)
1346
- throw new Error("schedule 模块未初始化");
1347
- await this.store.schedule.loadAllSchedule();
1348
- this.logMethodSuccess("loadSchedules");
1349
- } catch (error) {
1350
- this.logMethodError("loadSchedules", error);
1351
- throw error;
1352
- }
1353
- }
1354
- getScheduleListByIds(ids) {
1355
- if (!this.store.schedule)
1356
- return [];
1357
- return this.store.schedule.getScheduleListByIds(ids);
1358
- }
1359
- // ─── 临时订单操作(保留原有能力) ───
1360
- getTempOrder() {
1361
- var _a;
1362
- const result = ((_a = this.store.order) == null ? void 0 : _a.getTempOrder()) || null;
1363
- return result;
1364
- }
1365
- updateTempOrderNote(note) {
1366
- if (!this.store.order)
1367
- throw new Error("order 模块未初始化");
1368
- return this.store.order.updateTempOrderNote(note);
1369
- }
1370
- updateTempOrderContactsInfo(contactsInfo) {
1371
- if (!this.store.order)
1372
- throw new Error("order 模块未初始化");
1373
- return this.store.order.updateTempOrderContactsInfo(contactsInfo);
1374
- }
1375
- ensureTempOrder() {
1376
- if (!this.store.order)
1377
- throw new Error("order 模块未初始化");
1378
- return this.store.order.ensureTempOrder();
1379
- }
1380
- async onCustomerLogin(params) {
1381
- this.logMethodStart("onCustomerLogin", { customerId: params.customerId });
1382
- try {
1383
- await this.refreshOrderMarketingAfterLogin({
1384
- customerId: params.customerId
1385
- });
1386
- this.logMethodSuccess("onCustomerLogin", { customerId: params.customerId });
1387
- } catch (error) {
1388
- this.logMethodError("onCustomerLogin", error);
1389
- throw error;
1390
- }
1391
- }
1392
- recalculateOrderPricesFromSmartPricing() {
1393
- var _a, _b;
1394
- if (!this.store.order)
1395
- return;
1396
- const tempOrder = this.store.order.getTempOrder();
1397
- if (!((_a = tempOrder == null ? void 0 : tempOrder.products) == null ? void 0 : _a.length))
1398
- return;
1399
- const now = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
1400
- const catalog = this.getAllProductsForSmartPricing();
1401
- const context = this.buildSmartPricingContext();
1402
- for (const product of tempOrder.products) {
1403
- if ((_b = product.metadata) == null ? void 0 : _b.venue_booking) {
1404
- const mappings = this.resourceProductMap.get(product.metadata.resource_id);
1405
- if (!mappings || !mappings.length)
1406
- continue;
1407
- const mapping = mappings.find((m) => Number(m.productId) === Number(product.product_id)) || mappings[0];
1408
- if (!mapping)
1409
- continue;
1410
- const slots = (0, import_slotMerge.expandMergedSlotToIndividual)(
1411
- product,
1412
- this.store.slotConfig.slotDurationMinutes
1413
- );
1414
- const uniqueDates = [
1415
- ...new Set(slots.map((slot) => (0, import_dayjs.default)(slot.startTime).format("YYYY-MM-DD")))
1416
- ];
1417
- const slotPriceMaps = /* @__PURE__ */ new Map();
1418
- for (const slotDate of uniqueDates) {
1419
- slotPriceMaps.set(
1420
- slotDate,
1421
- this.buildSlotPriceMapForDate(slotDate, this.store.slotConfig, [mapping.productId])
1422
- );
1423
- }
1424
- const updatedSlots = slots.map((slot) => {
1425
- const slotDate = (0, import_dayjs.default)(slot.startTime).format("YYYY-MM-DD");
1426
- const slotPriceMap = slotPriceMaps.get(slotDate);
1427
- return {
1428
- ...slot,
1429
- productId: mapping.productId,
1430
- price: slotPriceMap ? (0, import_smartPricing.getSlotPriceFromMap)({
1431
- slotPriceMap,
1432
- productId: mapping.productId,
1433
- slotStartTime: slot.startTime,
1434
- fallbackPrice: mapping.price
1435
- }) : mapping.price
1436
- };
1437
- });
1438
- const merged = (0, import_slotMerge.mergeConsecutiveSlots)(updatedSlots);
1439
- if (merged.length === 1) {
1440
- this.resetProductPriceForSmartPricing({
1441
- product,
1442
- price: merged[0].totalPrice,
1443
- priceBreakdown: (0, import_slotMerge.buildPriceBreakdown)({
1444
- group: merged[0],
1445
- productId: mapping.productId
1446
- })
1447
- });
1448
- }
1449
- } else if (product.product_id != null) {
1450
- const smartPrice = (0, import_smartPricing.getPriceForProductAtDatetime)({
1451
- products: catalog,
1452
- context,
1453
- productId: Number(product.product_id),
1454
- datetime: now,
1455
- fallbackPrice: product.selling_price
1456
- });
1457
- this.resetProductPriceForSmartPricing({
1458
- product,
1459
- price: smartPrice
1460
- });
1461
- }
1462
- }
1463
- }
1464
- /**
1465
- * DataVariant 重算价格后,同步刷新订单展示、Rules 与 Summary 共用的价格口径。
1466
- * Rules 会在本轮结束后根据当前客户的 discountList 重新写入实际折扣。
1467
- */
1468
- resetProductPriceForSmartPricing(params) {
1469
- const { product, price, priceBreakdown } = params;
1470
- const metadata = product.metadata || {};
1471
- product.selling_price = price;
1472
- product.original_price = price;
1473
- product.discount_list = [];
1474
- product.metadata = {
1475
- ...metadata,
1476
- ...priceBreakdown ? { price_breakdown: priceBreakdown } : {},
1477
- source_product_price: price,
1478
- main_product_original_price: price,
1479
- main_product_selling_price: price,
1480
- price_schema_version: 2
1481
- };
1482
- }
1483
- async scanCode(code, customerId) {
1484
- this.logMethodStart("scanCode", { code });
1485
- try {
1486
- if (!this.store.order)
1487
- throw new Error("order 模块未初始化");
1488
- const result = await this.store.order.scanCode(code, customerId);
1489
- if (result.isAvailable) {
1490
- await this.store.order.recalculateSummary({ createIfMissing: true });
1491
- this.store.order.persistTempOrder();
1492
- }
1493
- this.logMethodSuccess("scanCode", { isAvailable: result.isAvailable });
1494
- return result;
1495
- } catch (error) {
1496
- this.logMethodError("scanCode", error);
1497
- throw error;
1498
- }
1499
- }
1500
- /** 获取当前折扣列表(包装 order.getDiscountList) */
1501
- getDiscountList() {
1502
- if (!this.store.order)
1503
- return [];
1504
- return this.store.order.getDiscountList();
1505
- }
1506
- /** 勾选/取消勾选某张折扣券,重新计算折扣并持久化 */
1507
- async setDiscountSelected(params) {
1508
- var _a, _b, _c, _d, _e;
1509
- this.logMethodStart("setDiscountSelected", params);
1510
- try {
1511
- if (!this.store.order)
1512
- throw new Error("order 模块未初始化");
1513
- const list = this.store.order.getDiscountList();
1514
- const beforeTarget = list.find((d) => d.id === params.discountId) || null;
1515
- const updated = list.map(
1516
- (d) => d.id === params.discountId ? {
1517
- ...d,
1518
- isSelected: params.isSelected,
1519
- isManualSelect: !params.isSelected
1520
- } : d
1521
- );
1522
- const updatedTarget = updated.find((d) => d.id === params.discountId) || null;
1523
- const tempOrder = this.store.order.ensureTempOrder();
1524
- const orderStore = this.store.order.store || {};
1525
- const discountModule = orderStore.discount;
1526
- const rulesModule = orderStore.rules;
1527
- const holders = ((_a = tempOrder.holder) == null ? void 0 : _a.form_record_id) ? [{ form_record_id: tempOrder.holder.form_record_id }] : [];
1528
- let nextDiscountList = updated;
1529
- await (discountModule == null ? void 0 : discountModule.setDiscountList(updated));
1530
- if (rulesModule) {
1531
- const result = rulesModule.calcDiscount(
1532
- {
1533
- productList: tempOrder.products,
1534
- discountList: updated,
1535
- holders,
1536
- isFormSubject: !!((_b = tempOrder.holder) == null ? void 0 : _b.type) && tempOrder.holder.type === "form"
1537
- },
1538
- {
1539
- discountId: params.discountId,
1540
- isSelected: params.isSelected
1541
- }
1542
- ) || { productList: tempOrder.products, discountList: updated };
1543
- if (result == null ? void 0 : result.productList) {
1544
- tempOrder.products = result.productList;
1545
- }
1546
- if (result == null ? void 0 : result.discountList) {
1547
- nextDiscountList = result.discountList;
1548
- if (!params.isSelected) {
1549
- const beforeSelectedIds = new Set(
1550
- updated.filter((d) => d.isSelected).map((d) => d.id)
1551
- );
1552
- for (const d of nextDiscountList) {
1553
- if (d.isSelected && !beforeSelectedIds.has(d.id)) {
1554
- d.isSelected = false;
1555
- }
1556
- }
1557
- }
1558
- }
1559
- }
1560
- this.normalizeDiscountedOrderPrices(nextDiscountList);
1561
- import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1562
- await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1563
- tempOrder.discount_list = (nextDiscountList || []).filter((d) => d.isSelected);
1564
- const afterApplyTarget = this.store.order.getDiscountList().find((d) => d.id === params.discountId) || null;
1565
- await this.store.order.recalculateSummary({ createIfMissing: true });
1566
- this.store.order.persistTempOrder();
1567
- const finalSummary = ((_c = this.store.order.getTempOrder()) == null ? void 0 : _c.summary) || null;
1568
- const finalProduct = ((_e = (_d = this.store.order.getTempOrder()) == null ? void 0 : _d.products) == null ? void 0 : _e[0]) || null;
1569
- this.logMethodSuccess("setDiscountSelected", params);
1570
- const finalTarget = this.store.order.getDiscountList().find((d) => d.id === params.discountId) || null;
1571
- return this.store.order.getDiscountList();
1572
- } catch (error) {
1573
- this.logMethodError("setDiscountSelected", error);
1574
- throw error;
1575
- }
1576
- }
1577
- /**
1578
- * 统一 VenueBooking 折扣后的订单行价。
1579
- *
1580
- * Rules 的 `discount_list.amount` 是已经按适用规则计算出的每件优惠额;它是这里唯一
1581
- * 的折扣金额来源。使用智能定价写入的 source_product_price 减去该金额,再同步
1582
- * selling_price 与 Summary 使用的 main_product_selling_price,避免 UI 的购物车行价、
1583
- * 小计和提交订单各自读取到不同的价格字段。
1584
- */
1585
- normalizeDiscountedOrderPrices(discountList) {
1586
- var _a;
1587
- const order = this.store.order;
1588
- if (!order)
1589
- return;
1590
- const tempOrder = order.ensureTempOrder();
1591
- const selectedResourceIds = new Set(
1592
- (discountList || []).filter((discount) => discount.isSelected).map((discount) => discount.id)
1593
- );
1594
- for (const product of tempOrder.products) {
1595
- if ((_a = product._origin) == null ? void 0 : _a.isManualDiscount)
1596
- continue;
1597
- product.discount_list = (product.discount_list || []).filter((detail) => {
1598
- var _a2;
1599
- const resourceId = ((_a2 = detail.discount) == null ? void 0 : _a2.resource_id) ?? detail.id;
1600
- return resourceId != null && selectedResourceIds.has(resourceId);
1601
- });
1602
- const totalPerUnitDiscount = (product.discount_list || []).reduce(
1603
- (total, detail) => total.plus(detail.amount || 0),
1604
- new import_decimal.default(0)
1605
- );
1606
- const metadata = product.metadata || (product.metadata = {});
1607
- const optionSum = (0, import_utils3.sumOptionUnitPrice)(product.product_option_item);
1608
- const sourcePrice = metadata.source_product_price ?? (metadata.main_product_original_price != null ? new import_decimal.default(Number(metadata.main_product_original_price) || 0).minus(optionSum).toFixed(2) : product.original_price ?? "0");
1609
- const nextSourceSellingPrice = import_decimal.default.max(
1610
- 0,
1611
- new import_decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount)
1612
- ).toDecimalPlaces(2).toString();
1613
- const nextMainSellingPrice = new import_decimal.default(Number(nextSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
1614
- metadata.main_product_selling_price = nextMainSellingPrice;
1615
- metadata.price_schema_version = 2;
1616
- product.selling_price = (0, import_utils3.composeLinePrice)({
1617
- mainPrice: nextMainSellingPrice,
1618
- bundle: product.product_bundle
1619
- });
1620
- }
1621
- }
1622
- async addNewOrder() {
1623
- this.logMethodStart("addNewOrder");
1624
- try {
1625
- if (!this.store.order)
1626
- throw new Error("order 模块未初始化");
1627
- const tempOrder = await this.store.order.addNewOrder();
1628
- this.logMethodSuccess("addNewOrder", {
1629
- productCount: tempOrder.products.length
1630
- });
1631
- return tempOrder;
1632
- } catch (error) {
1633
- this.logMethodError("addNewOrder", error);
1634
- throw error;
1635
- }
1636
- }
1637
- getOrderProducts() {
1638
- if (!this.store.order)
1639
- throw new Error("order 模块未初始化");
1640
- return this.store.order.getOrderProducts();
1641
- }
1642
- async getSummary() {
1643
- this.logMethodStart("getSummary");
1644
- try {
1645
- if (!this.store.order)
1646
- throw new Error("order 模块未初始化");
1647
- const summary = await this.store.order.getScanOrderSummary();
1648
- this.logMethodSuccess("getSummary", {
1649
- totalAmount: summary.total_amount
1650
- });
1651
- return summary;
1652
- } catch (error) {
1653
- this.logMethodError("getSummary", error);
1654
- throw error;
1655
- }
1656
- }
1657
- async submitOrder() {
1658
- var _a, _b, _c, _d, _e;
1659
- this.logMethodStart("submitOrder");
1660
- try {
1661
- await this.validateBeforeSubmitByItemRule();
1662
- if (!this.store.order) {
1663
- throw new Error("venueBooking解决方案需要 order 模块支持");
1664
- }
1665
- const result = await this.store.order.submitTempOrder({
1666
- cacheId: this.cacheId,
1667
- platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
1668
- businessCode: (_b = this.otherParams) == null ? void 0 : _b.businessCode,
1669
- channel: (_c = this.otherParams) == null ? void 0 : _c.channel,
1670
- type: (_d = this.otherParams) == null ? void 0 : _d.type
1671
- });
1672
- const tempOrder = this.store.order.getTempOrder();
1673
- this.logMethodSuccess("submitOrder", {
1674
- productCount: ((_e = tempOrder == null ? void 0 : tempOrder.products) == null ? void 0 : _e.length) || 0
1675
- });
1676
- return result;
1677
- } catch (error) {
1678
- this.logMethodError("submitOrder", error);
1679
- throw error;
1680
- }
1681
- }
1682
- /**
1683
- * 0 元订单免费领取(非定金场景)
1684
- * 与 appointment getFreeProduct 同接口:POST /pay/order/free-pay/:id
1685
- */
1686
- async submitFreeOrder(id) {
1687
- this.logMethodStart("submitFreeOrder", { id });
1688
- try {
1689
- if (!id) {
1690
- throw new Error("订单 ID 不能为空");
1691
- }
1692
- const res = await this.request.post(`/pay/order/free-pay/${id}`);
1693
- this.logMethodSuccess("submitFreeOrder", { id, status: res == null ? void 0 : res.status });
1694
- return res;
1695
- } catch (error) {
1696
- this.logMethodError("submitFreeOrder", error);
1697
- throw error;
1698
- }
1699
- }
1700
- async addProductToOrder(product) {
1701
- var _a, _b;
1702
- this.logMethodStart("addProductToOrder", {
1703
- product_id: product.product_id,
1704
- product_variant_id: product.product_variant_id
1705
- });
1706
- try {
1707
- if (!this.store.order)
1708
- throw new Error("order 模块未初始化");
1709
- if (!((_a = product.metadata) == null ? void 0 : _a.venue_booking) && product.product_id != null) {
1710
- const smartPrice = (0, import_smartPricing.getPriceForProductAtDatetime)({
1711
- products: this.getAllProductsForSmartPricing(),
1712
- context: this.buildSmartPricingContext(),
1713
- productId: Number(product.product_id),
1714
- datetime: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss"),
1715
- fallbackPrice: product.selling_price
1716
- });
1717
- product.selling_price = smartPrice;
1718
- product.original_price = smartPrice;
1719
- } else if (product.selling_price != null && !((_b = product.metadata) == null ? void 0 : _b.venue_booking)) {
1720
- product.original_price = product.selling_price;
1721
- }
1722
- const products = await this.store.order.addProductToOrder(product);
1723
- await this.refreshItemRuleQuantityLimits();
1724
- await this.refreshCartValidationPassed();
1725
- this.logMethodSuccess("addProductToOrder", {
1726
- productCount: products.length
1727
- });
1728
- return products;
1729
- } catch (error) {
1730
- this.logMethodError("addProductToOrder", error);
1731
- throw error;
1732
- }
1733
- }
1734
- async updateProductInOrder(params) {
1735
- this.logMethodStart("updateProductInOrder", {
1736
- product_id: params.product_id,
1737
- product_variant_id: params.product_variant_id
1738
- });
1739
- try {
1740
- if (!this.store.order)
1741
- throw new Error("order 模块未初始化");
1742
- const products = await this.store.order.updateProductInOrder(params);
1743
- await this.refreshItemRuleQuantityLimits();
1744
- await this.refreshCartValidationPassed();
1745
- this.logMethodSuccess("updateProductInOrder", {
1746
- productCount: products.length
1747
- });
1748
- return products;
1749
- } catch (error) {
1750
- this.logMethodError("updateProductInOrder", error);
1751
- throw error;
1752
- }
1753
- }
1754
- async removeProductFromOrder(identity) {
1755
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
1756
- this.logMethodStart("removeProductFromOrder", {
1757
- product_id: identity.product_id,
1758
- product_variant_id: identity.product_variant_id
1759
- });
1760
- try {
1761
- if (!this.store.order)
1762
- throw new Error("order 模块未初始化");
1763
- const tempOrder = ((_b = (_a = this.store.order).getTempOrder) == null ? void 0 : _b.call(_a)) || ((_d = (_c = this.store.order).ensureTempOrder) == null ? void 0 : _d.call(_c));
1764
- const products = await this.store.order.removeProductFromOrder(identity);
1765
- if ((_e = tempOrder == null ? void 0 : tempOrder.bookings) == null ? void 0 : _e.length) {
1766
- const venueProductUids = /* @__PURE__ */ new Set();
1767
- const venueBookingUids = /* @__PURE__ */ new Set();
1768
- for (const product of tempOrder.products || []) {
1769
- if (!((_f = product == null ? void 0 : product.metadata) == null ? void 0 : _f.venue_booking))
1770
- continue;
1771
- if (product.identity_key)
1772
- venueProductUids.add(String(product.identity_key));
1773
- if ((_g = product.metadata) == null ? void 0 : _g.booking_uid) {
1774
- venueBookingUids.add(String(product.metadata.booking_uid));
1775
- }
1776
- }
1777
- const beforeBookingCount = ((_h = tempOrder.bookings) == null ? void 0 : _h.length) || 0;
1778
- tempOrder.bookings = (tempOrder.bookings || []).filter((booking) => {
1779
- var _a2, _b2;
1780
- if (!((_a2 = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a2.venue_booking))
1781
- return true;
1782
- if (booking.product_uid) {
1783
- return venueProductUids.has(String(booking.product_uid));
1784
- }
1785
- const bookingUid = (_b2 = booking.metadata) == null ? void 0 : _b2.unique_identification_number;
1786
- if (bookingUid)
1787
- return venueBookingUids.has(String(bookingUid));
1788
- return true;
1789
- });
1790
- if ((((_i = tempOrder.bookings) == null ? void 0 : _i.length) || 0) !== beforeBookingCount) {
1791
- (_k = (_j = this.store.order).persistTempOrder) == null ? void 0 : _k.call(_j);
1792
- }
1793
- }
1794
- await this.refreshItemRuleQuantityLimits();
1795
- await this.refreshCartValidationPassed();
1796
- this.logMethodSuccess("removeProductFromOrder", {
1797
- productCount: products.length
1798
- });
1799
- return products;
1800
- } catch (error) {
1801
- this.logMethodError("removeProductFromOrder", error);
1802
- throw error;
1803
- }
1804
- }
1805
- async getProductList() {
1806
- if (this.productsLoaded) {
1807
- this.logPricingDiagnostics("[VenueBooking] getProductList loadAllProducts skipped", {
1808
- reason: "productsLoaded is true",
1809
- addonProductCount: this.getAddonProductsList().length,
1810
- smartPricingProductCatalogCount: this.smartPricingProductCatalog.length
1811
- });
1812
- return (0, import_utils.attachItemRuleLimitsToTopLevelProducts)(
1813
- this.getAddonProductsList(),
1814
- this.store.itemRuleQuantityLimits || []
1815
- );
1816
- }
1817
- const result = await this.loadAllProducts();
1818
- return (0, import_utils.attachItemRuleLimitsToTopLevelProducts)(
1819
- result.addonProducts,
1820
- this.store.itemRuleQuantityLimits || []
1821
- );
1822
- }
1823
- // ─── ItemRule 引擎 ───
1824
- async loadOpenDataConfig() {
1825
- if (!this.store.openData)
1826
- throw new Error("openData 模块未初始化");
1827
- const lastFetchedAt = this.store.openData.getLastFetchedAt();
1828
- const cachedData = this.store.openData.getOpenData();
1829
- if (cachedData && lastFetchedAt && Date.now() - lastFetchedAt < _VenueBookingImpl.OPEN_DATA_CACHE_TTL) {
1830
- this.otherParams.openData = cachedData;
1831
- return cachedData;
1832
- }
1833
- if (this.loadOpenDataConfigInFlight)
1834
- return await this.loadOpenDataConfigInFlight;
1835
- this.loadOpenDataConfigInFlight = this.store.openData.fetchOpenData({
1836
- scope: "board",
1837
- target: "venue_booking+online_store",
1838
- section_code: [...OPEN_DATA_SECTION_CODES]
1839
- });
1840
- try {
1841
- const openDataConfig = await this.loadOpenDataConfigInFlight;
1842
- this.otherParams.openData = openDataConfig;
1843
- return openDataConfig;
1844
- } finally {
1845
- this.loadOpenDataConfigInFlight = null;
1846
- }
1847
- }
1848
- async loadRuntimeConfigs() {
1849
- await this.loadOpenDataConfig();
1850
- const itemRuleConfigs = await this.ensureItemRuleConfigsLoaded();
1851
- this.logMethodSuccess("loadRuntimeConfigs", {
1852
- itemRuleCount: itemRuleConfigs.length
1853
- });
1854
- return { itemRuleConfigs };
1855
- }
1856
- async fetchItemRuleConfigsByModelIds(strategyModelIds) {
1857
- this.logMethodStart("fetchItemRuleConfigsByModelIds", { strategyModelIds });
1858
- if (!strategyModelIds.length)
1859
- return [];
1860
- try {
1861
- const result = await this.request.get("/promotion", {
1862
- skip: 1,
1863
- num: 99,
1864
- status: "active",
1865
- ids: strategyModelIds
1866
- });
1867
- let configs = [];
1868
- if (result.code === 200) {
1869
- configs = result.data.list.map((item) => item.metadata);
1870
- }
1871
- this.logMethodSuccess("fetchItemRuleConfigsByModelIds", {
1872
- strategyModelIds,
1873
- strategyCount: configs.length
1874
- });
1875
- return configs;
1876
- } catch (error) {
1877
- this.logMethodError("fetchItemRuleConfigsByModelIds", error, { strategyModelIds });
1878
- return [];
1879
- }
1880
- }
1881
- async buildPrefillProductSourceMap() {
1882
- const sourceMap = /* @__PURE__ */ new Map();
1883
- try {
1884
- const productList = await this.getProductList();
1885
- if (!Array.isArray(productList))
1886
- return sourceMap;
1887
- const visited = /* @__PURE__ */ new Set();
1888
- const collectFromValue = (value) => {
1889
- if (!value || typeof value !== "object")
1890
- return;
1891
- if (visited.has(value))
1892
- return;
1893
- visited.add(value);
1894
- if (Array.isArray(value)) {
1895
- for (const item of value)
1896
- collectFromValue(item);
1897
- return;
1898
- }
1899
- const node = value;
1900
- const rawProductId = node.product_id ?? node.id;
1901
- const productId = Number(rawProductId);
1902
- if (Number.isFinite(productId) && productId > 0) {
1903
- const productVariantId = Number(node.product_variant_id ?? node.variant_id ?? 0);
1904
- const normalizedVariantId = Number.isNaN(productVariantId) ? 0 : productVariantId;
1905
- const key = (0, import_utils.buildProductKey)(productId, normalizedVariantId);
1906
- if (!sourceMap.has(key))
1907
- sourceMap.set(key, node);
1908
- }
1909
- for (const childValue of Object.values(node)) {
1910
- if (childValue && typeof childValue === "object")
1911
- collectFromValue(childValue);
1912
- }
1913
- };
1914
- collectFromValue(productList);
1915
- } catch (error) {
1916
- this.logMethodError("buildPrefillProductSourceMap", error);
1917
- }
1918
- return sourceMap;
1919
- }
1920
- getItemRuleRuntimeConfig() {
1921
- return this.itemRuleRuntimeConfig || {};
1922
- }
1923
- async ensureItemRuleConfigsLoaded() {
1924
- if (this.itemRuleConfigs.length > 0)
1925
- return this.itemRuleConfigs;
1926
- if (this.itemRuleConfigsPromise)
1927
- return this.itemRuleConfigsPromise;
1928
- this.itemRuleConfigsPromise = (async () => {
1929
- const runtimeConfig = this.getItemRuleRuntimeConfig();
1930
- const staticConfigs = (0, import_utils.normalizeItemRuleStrategies)(runtimeConfig.strategyConfigs);
1931
- if (staticConfigs.length > 0) {
1932
- this.itemRuleConfigs = staticConfigs;
1933
- this.itemRuleEvaluator.setStrategyConfigs(staticConfigs);
1934
- return this.itemRuleConfigs;
1935
- }
1936
- this.itemRuleConfigs = [];
1937
- this.itemRuleEvaluator.setStrategyConfigs([]);
1938
- return this.itemRuleConfigs;
1939
- })();
1940
- return await this.itemRuleConfigsPromise;
1941
- }
1942
- async refreshItemRuleQuantityLimits() {
1943
- try {
1944
- const strategyConfigs = await this.ensureItemRuleConfigsLoaded();
1945
- if (!strategyConfigs.length) {
1946
- this.store.itemRuleQuantityLimits = [];
1947
- return [];
1948
- }
1949
- const businessData = (0, import_utils.buildItemRuleBusinessData)({
1950
- tempOrder: this.ensureTempOrder(),
1951
- runtimeConfig: this.getItemRuleRuntimeConfig(),
1952
- itemRuleConfigs: this.itemRuleConfigs
1953
- });
1954
- const limits = this.itemRuleEvaluator.getQuantityLimits(businessData);
1955
- this.store.itemRuleQuantityLimits = limits;
1956
- this.logMethodSuccess("refreshItemRuleQuantityLimits", { limitCount: limits.length });
1957
- return limits;
1958
- } catch (error) {
1959
- this.store.itemRuleQuantityLimits = [];
1960
- this.logMethodError("refreshItemRuleQuantityLimits", error);
1961
- return [];
1962
- }
1963
- }
1964
- async applyPrefillByItemRule() {
1965
- var _a;
1966
- if (this.itemRulePrefillApplied)
1967
- return;
1968
- if (!this.store.order)
1969
- return;
1970
- const strategyConfigs = await this.ensureItemRuleConfigsLoaded();
1971
- if (!strategyConfigs.length)
1972
- return;
1973
- const businessData = (0, import_utils.buildItemRuleBusinessData)({
1974
- tempOrder: this.ensureTempOrder(),
1975
- runtimeConfig: this.getItemRuleRuntimeConfig(),
1976
- itemRuleConfigs: this.itemRuleConfigs
1977
- });
1978
- const prefillItems = this.itemRuleEvaluator.getPrefillItems(businessData);
1979
- if (!prefillItems.length) {
1980
- this.itemRulePrefillApplied = true;
1981
- return;
1982
- }
1983
- const productSourceMap = await this.buildPrefillProductSourceMap();
1984
- const tempOrder = this.ensureTempOrder();
1985
- let hasChanges = false;
1986
- for (const prefillItem of prefillItems) {
1987
- const productId = Number(prefillItem.product_id);
1988
- const productVariantId = Number(prefillItem.product_variant_id ?? 0);
1989
- const targetQuantity = (0, import_utils.toNonNegativeInt)(prefillItem.quantity);
1990
- if (!Number.isFinite(productId) || targetQuantity <= 0)
1991
- continue;
1992
- if (Number.isNaN(productVariantId))
1993
- continue;
1994
- const sourceItem = productSourceMap.get((0, import_utils.buildProductKey)(productId, productVariantId)) || productSourceMap.get((0, import_utils.buildProductKey)(productId, 0)) || null;
1995
- const productIndex = (0, import_utils.getProductIdentityIndex)(tempOrder.products, {
1996
- product_id: productId,
1997
- product_variant_id: productVariantId
1998
- });
1999
- if (productIndex === -1) {
2000
- const sellingPrice = (0, import_utils.toPriceString)((sourceItem == null ? void 0 : sourceItem.price) ?? (sourceItem == null ? void 0 : sourceItem.selling_price), "0.00");
2001
- tempOrder.products.push(
2002
- (0, import_utils.normalizeOrderProduct)({
2003
- product_id: productId,
2004
- product_variant_id: productVariantId,
2005
- num: targetQuantity,
2006
- selling_price: sellingPrice,
2007
- original_price: sellingPrice,
2008
- metadata: { item_rule_prefill: true, item_rule_id: prefillItem.ruleId },
2009
- _origin: { ...sourceItem || {}, item_rule_prefill: true, item_rule_id: prefillItem.ruleId }
2010
- })
2011
- );
2012
- hasChanges = true;
2013
- continue;
2014
- }
2015
- const targetProduct = tempOrder.products[productIndex];
2016
- const existedQuantity = (0, import_utils.toNonNegativeInt)(targetProduct.num);
2017
- const delta = targetQuantity - existedQuantity;
2018
- const nextProduct = {
2019
- ...targetProduct,
2020
- ...delta > 0 ? { num: (0, import_utils.getSafeProductNum)(existedQuantity + delta) } : {},
2021
- metadata: { ...targetProduct.metadata || {}, item_rule_prefill: true, item_rule_id: prefillItem.ruleId },
2022
- _origin: sourceItem ? { ...targetProduct._origin || {}, ...sourceItem } : targetProduct._origin
2023
- };
2024
- if (delta > 0 || Boolean(sourceItem && (!targetProduct._origin || ((_a = targetProduct._origin) == null ? void 0 : _a.price) !== (sourceItem == null ? void 0 : sourceItem.price)))) {
2025
- tempOrder.products[productIndex] = nextProduct;
2026
- hasChanges = true;
2027
- }
2028
- }
2029
- if (hasChanges) {
2030
- this.store.order.applyDiscount();
2031
- await this.store.order.recalculateSummary({ createIfMissing: true });
2032
- this.store.order.persistTempOrder();
2033
- }
2034
- await this.refreshItemRuleQuantityLimits();
2035
- this.itemRulePrefillApplied = true;
2036
- this.logMethodSuccess("applyPrefillByItemRule", {
2037
- prefillCount: prefillItems.length,
2038
- hasChanges
2039
- });
2040
- }
2041
- async applyItemRulePrefill() {
2042
- this.logMethodStart("applyItemRulePrefill");
2043
- await this.applyPrefillByItemRule();
2044
- await this.refreshItemRuleQuantityLimits();
2045
- await this.refreshCartValidationPassed();
2046
- }
2047
- async evaluateCartValidationByItemRule() {
2048
- const strategyConfigs = await this.ensureItemRuleConfigsLoaded();
2049
- if (!strategyConfigs.length)
2050
- return { passed: true, failures: [] };
2051
- const businessData = (0, import_utils.buildItemRuleBusinessData)({
2052
- tempOrder: this.ensureTempOrder(),
2053
- runtimeConfig: this.getItemRuleRuntimeConfig(),
2054
- itemRuleConfigs: this.itemRuleConfigs
2055
- });
2056
- return this.itemRuleEvaluator.validateCart(businessData);
2057
- }
2058
- async validateBeforeSubmitByItemRule() {
2059
- const validationResult = await this.evaluateCartValidationByItemRule();
2060
- if (validationResult.passed)
2061
- return;
2062
- const firstFailure = validationResult.failures[0];
2063
- const errorMessage = (firstFailure == null ? void 0 : firstFailure.validationMessage) || "当前购物车未满足商品规则,请调整后再提交";
2064
- const error = new Error(String(errorMessage));
2065
- error.failures = validationResult.failures;
2066
- throw error;
2067
- }
2068
- async refreshCartValidationPassed() {
2069
- const previous = this.store.cartValidation || { passed: null, failures: [] };
2070
- let nextState = {
2071
- passed: null,
2072
- failures: []
2073
- };
2074
- try {
2075
- const validationResult = await this.evaluateCartValidationByItemRule();
2076
- nextState = {
2077
- passed: validationResult.passed,
2078
- failures: validationResult.failures || []
2079
- };
2080
- } catch {
2081
- nextState = { passed: false, failures: [] };
2082
- }
2083
- this.store.cartValidation = nextState;
2084
- const changed = previous.passed !== nextState.passed || previous.failures !== nextState.failures;
2085
- if (changed) {
2086
- await this.core.effects.emit(import_types.VenueBookingHooks.onCartValidationChanged, {
2087
- cartValidation: nextState,
2088
- cartValidationPassed: nextState.passed
2089
- });
2090
- }
2091
- return nextState.passed;
2092
- }
2093
- async setItemRuleRuntimeConfig(config = {}) {
2094
- var _a, _b;
2095
- this.logMethodStart("setItemRuleRuntimeConfig");
2096
- this.itemRuleRuntimeConfig = {
2097
- ...this.itemRuleRuntimeConfig,
2098
- ...config,
2099
- pax: { ...((_a = this.itemRuleRuntimeConfig) == null ? void 0 : _a.pax) || {}, ...(config == null ? void 0 : config.pax) || {} },
2100
- custom: { ...((_b = this.itemRuleRuntimeConfig) == null ? void 0 : _b.custom) || {}, ...(config == null ? void 0 : config.custom) || {} }
2101
- };
2102
- if ("strategyConfigs" in config) {
2103
- this.itemRuleConfigs = [];
2104
- this.itemRuleConfigsPromise = null;
2105
- this.itemRuleEvaluator.setStrategyConfigs([]);
2106
- }
2107
- this.itemRulePrefillApplied = false;
2108
- await this.refreshItemRuleQuantityLimits();
2109
- await this.refreshCartValidationPassed();
2110
- this.logMethodSuccess("setItemRuleRuntimeConfig", {
2111
- strategyCount: Array.isArray(this.itemRuleRuntimeConfig.strategyConfigs) ? this.itemRuleRuntimeConfig.strategyConfigs.length : 0
2112
- });
2113
- }
2114
- getOtherParams() {
2115
- return this.otherParams;
2116
- }
2117
- getUIStateBucketKey() {
2118
- if (!this.cacheId)
2119
- return null;
2120
- return `${_VenueBookingImpl.UI_STATE_KEY_PREFIX}${this.cacheId}`;
2121
- }
2122
- readUIStateBucket() {
2123
- var _a;
2124
- const key = this.getUIStateBucketKey();
2125
- if (!key || !((_a = this.window) == null ? void 0 : _a.sessionStorage))
2126
- return {};
2127
- try {
2128
- const raw = this.window.sessionStorage.getItem(key) || "{}";
2129
- const parsed = JSON.parse(raw);
2130
- return parsed && typeof parsed === "object" ? parsed : {};
2131
- } catch {
2132
- return {};
2133
- }
2134
- }
2135
- writeUIStateBucket(bucket) {
2136
- var _a;
2137
- const key = this.getUIStateBucketKey();
2138
- if (!key || !((_a = this.window) == null ? void 0 : _a.sessionStorage))
2139
- return;
2140
- this.window.sessionStorage.setItem(key, JSON.stringify(bucket));
2141
- }
2142
- setUIState(key, value) {
2143
- if (!this.getUIStateBucketKey())
2144
- return;
2145
- const bucket = this.readUIStateBucket();
2146
- bucket[key] = value;
2147
- this.writeUIStateBucket(bucket);
2148
- }
2149
- getUIState(key) {
2150
- if (!this.getUIStateBucketKey())
2151
- return void 0;
2152
- const bucket = this.readUIStateBucket();
2153
- return bucket[key];
2154
- }
2155
- deleteUIState(key) {
2156
- if (!this.getUIStateBucketKey())
2157
- return;
2158
- const bucket = this.readUIStateBucket();
2159
- if (key in bucket) {
2160
- delete bucket[key];
2161
- this.writeUIStateBucket(bucket);
2162
- }
2163
- }
2164
- setBookingHolder(bookingUid, holder) {
2165
- var _a;
2166
- const order = this.getTempOrder();
2167
- const booking = (_a = order == null ? void 0 : order.bookings) == null ? void 0 : _a.find((b) => {
2168
- var _a2;
2169
- return ((_a2 = b.metadata) == null ? void 0 : _a2.unique_identification_number) === bookingUid;
2170
- });
2171
- if (booking) {
2172
- booking.holder = holder;
2173
- }
2174
- }
2175
- // ─── OpenData 可用性 ───
2176
- async checkOpenDataAvailability() {
2177
- if (!this.store.openData)
2178
- throw new Error("openData 模块未初始化");
2179
- await this.loadOpenDataConfig();
2180
- return this.store.openData.checkAvailability(this.store.schedule);
2181
- }
2182
- async setOtherParams(params, { cover = false } = {}) {
2183
- if (cover) {
2184
- this.otherParams = params;
2185
- } else {
2186
- this.otherParams = { ...this.otherParams, ...params };
2187
- }
2188
- }
2189
- };
2190
- var VenueBookingImpl = _VenueBookingImpl;
2191
- VenueBookingImpl.PRICING_DEBUG_CACHE_ID = "031596279011848516";
2192
- VenueBookingImpl.OPEN_DATA_CACHE_TTL = 5 * 60 * 1e3;
2193
- VenueBookingImpl.PISELL1_LOGIN_SUCCESS = "pisell1.login.success";
2194
- // ─── UI 状态缓存(按 cacheId 分桶,sessionStorage) ───
2195
- //
2196
- // 用于物料层持久化 UI 层面的轻量状态(如当前步骤、登录回跳意图等)。
2197
- // 桶键:pisell.venueBooking.uiState:<cacheId>;内部以 JSON object 形式存储多个字段。
2198
- // 无 cacheId 时所有方法自动降级为 no-op,上层不用判空。
2199
- VenueBookingImpl.UI_STATE_KEY_PREFIX = "pisell.venueBooking.uiState:";
2200
- // Annotate the CommonJS export names for ESM import in node:
2201
- 0 && (module.exports = {
2202
- VenueBookingImpl,
2203
- ...require("./types")
2204
- });