@pisell/pisellos 0.0.491 → 0.0.493

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 (165) hide show
  1. package/dist/apis/picoding.d.ts +0 -0
  2. package/dist/apis/picoding.js +1 -0
  3. package/dist/model/strategy/adapter/index.d.ts +2 -0
  4. package/dist/model/strategy/adapter/index.js +3 -1
  5. package/dist/model/strategy/adapter/itemRule/adapter.d.ts +59 -0
  6. package/dist/model/strategy/adapter/itemRule/adapter.js +439 -0
  7. package/dist/model/strategy/adapter/itemRule/evaluator.d.ts +43 -0
  8. package/dist/model/strategy/adapter/itemRule/evaluator.js +169 -0
  9. package/dist/model/strategy/adapter/itemRule/examples.d.ts +64 -0
  10. package/dist/model/strategy/adapter/itemRule/examples.js +315 -0
  11. package/dist/model/strategy/adapter/itemRule/index.d.ts +5 -0
  12. package/dist/model/strategy/adapter/itemRule/index.js +5 -0
  13. package/dist/model/strategy/adapter/itemRule/type.d.ts +206 -0
  14. package/dist/model/strategy/adapter/itemRule/type.js +101 -0
  15. package/dist/model/strategy/adapter/walletPass/utils.js +2 -2
  16. package/dist/modules/OpenData/index.d.ts +23 -0
  17. package/dist/modules/OpenData/index.js +167 -0
  18. package/dist/modules/OpenData/types.d.ts +73 -0
  19. package/dist/modules/OpenData/types.js +1 -0
  20. package/dist/modules/OpenData/utils.d.ts +2 -0
  21. package/dist/modules/OpenData/utils.js +75 -0
  22. package/dist/modules/Order/index.d.ts +54 -2
  23. package/dist/modules/Order/index.js +717 -27
  24. package/dist/modules/Order/types.d.ts +144 -12
  25. package/dist/modules/Order/utils.d.ts +25 -0
  26. package/dist/modules/Order/utils.js +214 -1
  27. package/dist/modules/Product/index.d.ts +1 -1
  28. package/dist/modules/Product/utils.js +2 -2
  29. package/dist/modules/ProductList/index.d.ts +1 -1
  30. package/dist/modules/ProductList/index.js +3 -1
  31. package/dist/modules/Quotation/index.d.ts +40 -0
  32. package/dist/modules/Quotation/index.js +212 -0
  33. package/dist/modules/Quotation/types.d.ts +42 -0
  34. package/dist/modules/Quotation/types.js +1 -0
  35. package/dist/modules/SalesSummary/index.d.ts +63 -0
  36. package/dist/modules/SalesSummary/index.js +174 -0
  37. package/dist/modules/SalesSummary/types.d.ts +59 -0
  38. package/dist/modules/SalesSummary/types.js +1 -0
  39. package/dist/modules/SalesSummary/utils.d.ts +30 -0
  40. package/dist/modules/SalesSummary/utils.js +506 -0
  41. package/dist/modules/ScanOrderLogger/index.d.ts +21 -0
  42. package/dist/modules/ScanOrderLogger/index.js +161 -0
  43. package/dist/modules/ScanOrderLogger/providers/feishu.d.ts +2 -0
  44. package/dist/modules/ScanOrderLogger/providers/feishu.js +95 -0
  45. package/dist/modules/ScanOrderLogger/providers/grafana.d.ts +2 -0
  46. package/dist/modules/ScanOrderLogger/providers/grafana.js +50 -0
  47. package/dist/modules/ScanOrderLogger/types.d.ts +46 -0
  48. package/dist/modules/ScanOrderLogger/types.js +1 -0
  49. package/dist/modules/Summary/utils.d.ts +3 -3
  50. package/dist/modules/Summary/utils.js +4 -4
  51. package/dist/modules/index.d.ts +4 -0
  52. package/dist/modules/index.js +5 -1
  53. package/dist/solution/BookingByStep/index.d.ts +1 -1
  54. package/dist/solution/BookingByStep/index.js +44 -42
  55. package/dist/solution/BookingByStep/types.d.ts +3 -1
  56. package/dist/solution/BookingByStep/types.js +5 -1
  57. package/dist/solution/BookingByStep/utils/timeslots.d.ts +3 -1
  58. package/dist/solution/BookingByStep/utils/timeslots.js +19 -12
  59. package/dist/solution/BookingTicket/index.d.ts +1 -1
  60. package/dist/solution/ScanOrder/index.d.ts +90 -0
  61. package/dist/solution/ScanOrder/index.js +1853 -0
  62. package/dist/solution/ScanOrder/types.d.ts +210 -0
  63. package/dist/solution/ScanOrder/types.js +16 -0
  64. package/dist/solution/ScanOrder/utils.d.ts +93 -0
  65. package/dist/solution/ScanOrder/utils.js +378 -0
  66. package/dist/solution/VenueBooking/index.d.ts +159 -0
  67. package/dist/solution/VenueBooking/index.js +2773 -0
  68. package/dist/solution/VenueBooking/sales-section-4-annotated.json +343 -0
  69. package/dist/solution/VenueBooking/types.d.ts +123 -0
  70. package/dist/solution/VenueBooking/types.js +21 -0
  71. package/dist/solution/VenueBooking/utils/dateSummary.d.ts +10 -0
  72. package/dist/solution/VenueBooking/utils/dateSummary.js +102 -0
  73. package/dist/solution/VenueBooking/utils/resource.d.ts +4 -0
  74. package/dist/solution/VenueBooking/utils/resource.js +94 -0
  75. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +18 -0
  76. package/dist/solution/VenueBooking/utils/slotMerge.js +128 -0
  77. package/dist/solution/VenueBooking/utils/timeSlot.d.ts +32 -0
  78. package/dist/solution/VenueBooking/utils/timeSlot.js +256 -0
  79. package/dist/solution/VenueBooking/utils.d.ts +1 -0
  80. package/dist/solution/VenueBooking/utils.js +1 -0
  81. package/dist/solution/index.d.ts +2 -0
  82. package/dist/solution/index.js +3 -1
  83. package/lib/apis/picoding.d.ts +0 -0
  84. package/lib/apis/picoding.js +0 -0
  85. package/lib/model/strategy/adapter/index.d.ts +2 -0
  86. package/lib/model/strategy/adapter/index.js +6 -0
  87. package/lib/model/strategy/adapter/itemRule/adapter.d.ts +59 -0
  88. package/lib/model/strategy/adapter/itemRule/adapter.js +338 -0
  89. package/lib/model/strategy/adapter/itemRule/evaluator.d.ts +43 -0
  90. package/lib/model/strategy/adapter/itemRule/evaluator.js +124 -0
  91. package/lib/model/strategy/adapter/itemRule/examples.d.ts +64 -0
  92. package/lib/model/strategy/adapter/itemRule/examples.js +269 -0
  93. package/lib/model/strategy/adapter/itemRule/index.d.ts +5 -0
  94. package/lib/model/strategy/adapter/itemRule/index.js +58 -0
  95. package/lib/model/strategy/adapter/itemRule/type.d.ts +206 -0
  96. package/lib/model/strategy/adapter/itemRule/type.js +46 -0
  97. package/lib/model/strategy/adapter/walletPass/utils.js +2 -2
  98. package/lib/modules/OpenData/index.d.ts +23 -0
  99. package/lib/modules/OpenData/index.js +116 -0
  100. package/lib/modules/OpenData/types.d.ts +73 -0
  101. package/lib/modules/OpenData/types.js +17 -0
  102. package/lib/modules/OpenData/utils.d.ts +2 -0
  103. package/lib/modules/OpenData/utils.js +111 -0
  104. package/lib/modules/Order/index.d.ts +54 -2
  105. package/lib/modules/Order/index.js +389 -1
  106. package/lib/modules/Order/types.d.ts +144 -12
  107. package/lib/modules/Order/utils.d.ts +25 -0
  108. package/lib/modules/Order/utils.js +217 -0
  109. package/lib/modules/Product/index.d.ts +1 -1
  110. package/lib/modules/Product/utils.js +2 -2
  111. package/lib/modules/ProductList/index.d.ts +1 -1
  112. package/lib/modules/ProductList/index.js +2 -1
  113. package/lib/modules/Quotation/index.d.ts +40 -0
  114. package/lib/modules/Quotation/index.js +128 -0
  115. package/lib/modules/Quotation/types.d.ts +42 -0
  116. package/lib/modules/Quotation/types.js +17 -0
  117. package/lib/modules/SalesSummary/index.d.ts +63 -0
  118. package/lib/modules/SalesSummary/index.js +105 -0
  119. package/lib/modules/SalesSummary/types.d.ts +59 -0
  120. package/lib/modules/SalesSummary/types.js +17 -0
  121. package/lib/modules/SalesSummary/utils.d.ts +30 -0
  122. package/lib/modules/SalesSummary/utils.js +445 -0
  123. package/lib/modules/ScanOrderLogger/index.d.ts +21 -0
  124. package/lib/modules/ScanOrderLogger/index.js +135 -0
  125. package/lib/modules/ScanOrderLogger/providers/feishu.d.ts +2 -0
  126. package/lib/modules/ScanOrderLogger/providers/feishu.js +82 -0
  127. package/lib/modules/ScanOrderLogger/providers/grafana.d.ts +2 -0
  128. package/lib/modules/ScanOrderLogger/providers/grafana.js +52 -0
  129. package/lib/modules/ScanOrderLogger/types.d.ts +46 -0
  130. package/lib/modules/ScanOrderLogger/types.js +17 -0
  131. package/lib/modules/Summary/utils.d.ts +3 -3
  132. package/lib/modules/Summary/utils.js +4 -4
  133. package/lib/modules/index.d.ts +4 -0
  134. package/lib/modules/index.js +9 -1
  135. package/lib/solution/BookingByStep/index.d.ts +1 -1
  136. package/lib/solution/BookingByStep/index.js +4 -2
  137. package/lib/solution/BookingByStep/types.d.ts +3 -1
  138. package/lib/solution/BookingByStep/types.js +10 -0
  139. package/lib/solution/BookingByStep/utils/timeslots.d.ts +3 -1
  140. package/lib/solution/BookingByStep/utils/timeslots.js +19 -11
  141. package/lib/solution/BookingTicket/index.d.ts +1 -1
  142. package/lib/solution/ScanOrder/index.d.ts +90 -0
  143. package/lib/solution/ScanOrder/index.js +1071 -0
  144. package/lib/solution/ScanOrder/types.d.ts +210 -0
  145. package/lib/solution/ScanOrder/types.js +36 -0
  146. package/lib/solution/ScanOrder/utils.d.ts +93 -0
  147. package/lib/solution/ScanOrder/utils.js +342 -0
  148. package/lib/solution/VenueBooking/index.d.ts +159 -0
  149. package/lib/solution/VenueBooking/index.js +1508 -0
  150. package/lib/solution/VenueBooking/sales-section-4-annotated.json +343 -0
  151. package/lib/solution/VenueBooking/types.d.ts +123 -0
  152. package/lib/solution/VenueBooking/types.js +44 -0
  153. package/lib/solution/VenueBooking/utils/dateSummary.d.ts +10 -0
  154. package/lib/solution/VenueBooking/utils/dateSummary.js +101 -0
  155. package/lib/solution/VenueBooking/utils/resource.d.ts +4 -0
  156. package/lib/solution/VenueBooking/utils/resource.js +80 -0
  157. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +18 -0
  158. package/lib/solution/VenueBooking/utils/slotMerge.js +156 -0
  159. package/lib/solution/VenueBooking/utils/timeSlot.d.ts +32 -0
  160. package/lib/solution/VenueBooking/utils/timeSlot.js +200 -0
  161. package/lib/solution/VenueBooking/utils.d.ts +1 -0
  162. package/lib/solution/VenueBooking/utils.js +69 -0
  163. package/lib/solution/index.d.ts +2 -0
  164. package/lib/solution/index.js +5 -1
  165. package/package.json +1 -1
@@ -0,0 +1,1508 @@
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_Quotation = require("../../modules/Quotation");
44
+ var import_OpenData = require("../../modules/OpenData");
45
+ var import_types3 = require("../../modules/Account/types");
46
+ var import_dayjs = __toESM(require("dayjs"));
47
+ var import_itemRule = require("../../model/strategy/adapter/itemRule");
48
+ var import_resource = require("./utils/resource");
49
+ var import_timeSlot = require("./utils/timeSlot");
50
+ var import_dateSummary = require("./utils/dateSummary");
51
+ var import_slotMerge = require("./utils/slotMerge");
52
+ var import_utils2 = require("../../modules/Order/utils");
53
+ var import_types4 = require("../RegisterAndLogin/types");
54
+ __reExport(VenueBooking_exports, require("./types"), module.exports);
55
+ var OPEN_DATA_SECTION_CODES = [
56
+ "basic",
57
+ "fulfillment",
58
+ "reservation",
59
+ "sale",
60
+ "menu",
61
+ "availability",
62
+ "workflow"
63
+ ];
64
+ function cloneCustomDepositData(customDepositData) {
65
+ if (!customDepositData || typeof customDepositData !== "object")
66
+ return void 0;
67
+ return {
68
+ ...customDepositData,
69
+ self_deposit_policy_ids: Array.isArray(customDepositData.self_deposit_policy_ids) ? [...customDepositData.self_deposit_policy_ids] : [],
70
+ deposit_policy_ids: Array.isArray(customDepositData.deposit_policy_ids) ? [...customDepositData.deposit_policy_ids] : [],
71
+ deposit_policy_data: Array.isArray(customDepositData.deposit_policy_data) ? [...customDepositData.deposit_policy_data] : []
72
+ };
73
+ }
74
+ var VenueBookingImpl = class extends import_BaseModule.BaseModule {
75
+ constructor(name, version) {
76
+ super(name, version);
77
+ this.defaultName = "venueBooking";
78
+ this.defaultVersion = "1.0.0";
79
+ this.isSolution = true;
80
+ this.initializeOptions = {};
81
+ this.store = {
82
+ entryContext: null,
83
+ status: "idle",
84
+ flow: {},
85
+ error: null,
86
+ products: void 0,
87
+ rawResourceData: [],
88
+ slotConfig: { ...import_types.DEFAULT_SLOT_CONFIG },
89
+ itemRuleQuantityLimits: [],
90
+ cartValidation: {
91
+ passed: null,
92
+ failures: []
93
+ }
94
+ };
95
+ this.otherParams = {};
96
+ this.itemRuleEvaluator = new import_itemRule.ItemRuleEvaluator();
97
+ this.itemRuleConfigs = [];
98
+ this.itemRuleConfigsPromise = null;
99
+ this.itemRulePrefillApplied = false;
100
+ this.itemRuleRuntimeConfig = {};
101
+ this.resourceProductMap = /* @__PURE__ */ new Map();
102
+ this.loginEffectDisposers = [];
103
+ this.customerLoginRefreshInFlight = null;
104
+ this.customerLoginRefreshIdInFlight = null;
105
+ }
106
+ getLoggerContext() {
107
+ return {
108
+ cacheId: this.cacheId,
109
+ solutionName: this.name,
110
+ moduleName: "venueBooking"
111
+ };
112
+ }
113
+ serializeError(error) {
114
+ if (error instanceof Error) {
115
+ return {
116
+ name: error.name,
117
+ message: error.message,
118
+ stack: error.stack
119
+ };
120
+ }
121
+ return {
122
+ message: String(error)
123
+ };
124
+ }
125
+ async addVenueBookingLog(params) {
126
+ const payload = {
127
+ cacheId: this.cacheId,
128
+ ...params.payload || {}
129
+ };
130
+ const extra = {
131
+ ...params.extra || {}
132
+ };
133
+ const logger = this.store.scanOrderLogger;
134
+ if (!logger) {
135
+ if ((params.level || "info") === "error") {
136
+ console.error("[VenueBooking][log-fallback]", params.title, { payload, extra });
137
+ } else {
138
+ console.log("[VenueBooking][log-fallback]", params.title, { payload, extra });
139
+ }
140
+ return;
141
+ }
142
+ await logger.addLog({
143
+ ...params,
144
+ payload,
145
+ extra
146
+ });
147
+ }
148
+ logMethodStart(method, payload = {}) {
149
+ void this.addVenueBookingLog({
150
+ level: "info",
151
+ title: `[VenueBooking] ${method} start`,
152
+ payload: {
153
+ method,
154
+ ...payload
155
+ }
156
+ });
157
+ }
158
+ logMethodSuccess(method, payload = {}) {
159
+ void this.addVenueBookingLog({
160
+ level: "info",
161
+ title: `[VenueBooking] ${method} success`,
162
+ payload: {
163
+ method,
164
+ ...payload
165
+ }
166
+ });
167
+ }
168
+ logMethodError(method, error, payload = {}) {
169
+ void this.addVenueBookingLog({
170
+ level: "error",
171
+ title: `[VenueBooking] ${method} failed`,
172
+ payload: {
173
+ method,
174
+ ...payload,
175
+ error: this.serializeError(error)
176
+ }
177
+ });
178
+ }
179
+ async addLog(params) {
180
+ await this.addVenueBookingLog({
181
+ ...params,
182
+ payload: {
183
+ source: "ui-bridge",
184
+ ...params.payload || {}
185
+ }
186
+ });
187
+ }
188
+ normalizeCustomerId(value) {
189
+ const customerId = Number(value);
190
+ if (!Number.isFinite(customerId) || customerId <= 0)
191
+ return null;
192
+ return customerId;
193
+ }
194
+ resolveCustomerIdFromLoginPayload(payload) {
195
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
196
+ const candidates = [
197
+ payload == null ? void 0 : payload.customerId,
198
+ payload == null ? void 0 : payload.customer_id,
199
+ payload == null ? void 0 : payload.id,
200
+ (_a = payload == null ? void 0 : payload.user) == null ? void 0 : _a.customerId,
201
+ (_b = payload == null ? void 0 : payload.user) == null ? void 0 : _b.customer_id,
202
+ (_c = payload == null ? void 0 : payload.user) == null ? void 0 : _c.id,
203
+ (_e = (_d = payload == null ? void 0 : payload.user) == null ? void 0 : _d._origin) == null ? void 0 : _e.customer_id,
204
+ (_f = payload == null ? void 0 : payload.account) == null ? void 0 : _f.customerId,
205
+ (_g = payload == null ? void 0 : payload.account) == null ? void 0 : _g.customer_id,
206
+ (_h = payload == null ? void 0 : payload.account) == null ? void 0 : _h.id,
207
+ (_i = payload == null ? void 0 : payload._origin) == null ? void 0 : _i.customer_id
208
+ ];
209
+ for (const candidate of candidates) {
210
+ const customerId = this.normalizeCustomerId(candidate);
211
+ if (customerId)
212
+ return customerId;
213
+ }
214
+ return null;
215
+ }
216
+ clearLoginEffectListeners() {
217
+ for (const dispose of this.loginEffectDisposers) {
218
+ dispose();
219
+ }
220
+ this.loginEffectDisposers = [];
221
+ }
222
+ registerLoginEffect(event, callback) {
223
+ var _a;
224
+ const effects = (_a = this.core) == null ? void 0 : _a.effects;
225
+ if (!(effects == null ? void 0 : effects.on))
226
+ return;
227
+ effects.on(event, callback);
228
+ this.loginEffectDisposers.push(() => {
229
+ if (typeof effects.off === "function") {
230
+ effects.off(event, callback);
231
+ }
232
+ });
233
+ }
234
+ registerCustomerLoginListeners() {
235
+ var _a, _b, _c, _d;
236
+ this.clearLoginEffectListeners();
237
+ const accountModule = (_a = this.core) == null ? void 0 : _a.getModule("account");
238
+ const registerAndLoginModule = (_b = this.core) == null ? void 0 : _b.getModule("registerAndLogin");
239
+ const currentAccount = ((_c = accountModule == null ? void 0 : accountModule.getCurrentAccount) == null ? void 0 : _c.call(accountModule)) || ((_d = accountModule == null ? void 0 : accountModule.getAccount) == null ? void 0 : _d.call(accountModule)) || null;
240
+ const createHandleLogin = (eventName) => async (payload) => {
241
+ const customerId = this.resolveCustomerIdFromLoginPayload(payload);
242
+ if (!customerId)
243
+ return;
244
+ await this.refreshOrderMarketingAfterLogin({ customerId });
245
+ };
246
+ this.registerLoginEffect(import_types3.AccountHooks.OnLogin, createHandleLogin(import_types3.AccountHooks.OnLogin));
247
+ this.registerLoginEffect(import_types4.RegisterAndLoginHooks.onLoginSuccess, createHandleLogin(import_types4.RegisterAndLoginHooks.onLoginSuccess));
248
+ }
249
+ async refreshOrderMarketingAfterLogin(params) {
250
+ if (!this.store.order)
251
+ throw new Error("order 模块未初始化");
252
+ if (this.customerLoginRefreshInFlight) {
253
+ if (this.customerLoginRefreshIdInFlight === params.customerId) {
254
+ await this.customerLoginRefreshInFlight;
255
+ return;
256
+ }
257
+ await this.customerLoginRefreshInFlight;
258
+ }
259
+ this.customerLoginRefreshIdInFlight = params.customerId;
260
+ const refreshTask = (async () => {
261
+ var _a;
262
+ if (this.store.quotation) {
263
+ await this.store.quotation.loadQuotations({
264
+ channel: (_a = this.otherParams) == null ? void 0 : _a.channel
265
+ });
266
+ }
267
+ this.recalculateOrderPricesFromQuotation();
268
+ await this.store.order.loadDiscountConfig({
269
+ customerId: params.customerId
270
+ });
271
+ await this.store.order.recalculateSummary({ createIfMissing: true });
272
+ this.store.order.persistTempOrder();
273
+ await this.refreshItemRuleQuantityLimits();
274
+ await this.refreshCartValidationPassed();
275
+ })();
276
+ this.customerLoginRefreshInFlight = refreshTask;
277
+ try {
278
+ await refreshTask;
279
+ } catch (error) {
280
+ throw error;
281
+ } finally {
282
+ if (this.customerLoginRefreshInFlight === refreshTask) {
283
+ this.customerLoginRefreshInFlight = null;
284
+ this.customerLoginRefreshIdInFlight = null;
285
+ }
286
+ }
287
+ }
288
+ async initialize(core, options = {}) {
289
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
290
+ this.logMethodStart("initialize");
291
+ this.core = core;
292
+ this.initializeOptions = options || {};
293
+ this.store = { ...this.store, ...options.store };
294
+ this.store.entryContext = ((_a = options.otherParams) == null ? void 0 : _a.entryContext) || this.store.entryContext;
295
+ this.store.status = "initializing";
296
+ this.store.error = null;
297
+ this.store.rawResourceData = [];
298
+ this.store.slotConfig = {
299
+ ...import_types.DEFAULT_SLOT_CONFIG,
300
+ ...((_b = options.otherParams) == null ? void 0 : _b.slotConfig) || {}
301
+ };
302
+ this.otherParams = options.otherParams || {};
303
+ this.cacheId = (_c = this.otherParams) == null ? void 0 : _c.cacheId;
304
+ this.itemRuleRuntimeConfig = ((_d = this.otherParams) == null ? void 0 : _d.venueBookingItemRule) || ((_e = this.otherParams) == null ? void 0 : _e.itemRule) || {};
305
+ this.itemRuleConfigs = [];
306
+ this.itemRuleConfigsPromise = null;
307
+ this.itemRulePrefillApplied = false;
308
+ this.store.itemRuleQuantityLimits = [];
309
+ this.store.cartValidation = {
310
+ passed: null,
311
+ failures: []
312
+ };
313
+ this.window = core.getPlugin("window");
314
+ this.request = core.getPlugin("request");
315
+ if (!this.window) {
316
+ this.logMethodError("initialize", "window plugin missing");
317
+ throw new Error("venueBooking解决方案需要 window 插件支持");
318
+ }
319
+ if (!this.request) {
320
+ this.logMethodError("initialize", "request plugin missing");
321
+ throw new Error("venueBooking解决方案需要 request 插件支持");
322
+ }
323
+ const baseModules = [
324
+ "scanOrderLogger",
325
+ "products",
326
+ "order",
327
+ "salesSummary"
328
+ ];
329
+ baseModules.forEach((step) => {
330
+ var _a2, _b2, _c2, _d2, _e2, _f2;
331
+ const targetModule = (0, import_types2.createModule)(step, this.name);
332
+ if (targetModule) {
333
+ this.store[step] = targetModule;
334
+ const initialState = step === "salesSummary" ? {
335
+ summary: ((_b2 = (_a2 = this.store.order) == null ? void 0 : _a2.getTempOrder()) == null ? void 0 : _b2.summary) || (0, import_utils.createEmptySummary)()
336
+ } : {};
337
+ const loggerProvider = ((_c2 = this.otherParams) == null ? void 0 : _c2.loggerProvider) || "feishu";
338
+ const loggerConfig = ((_d2 = this.otherParams) == null ? void 0 : _d2.loggerConfig) || {
339
+ feishu: {}
340
+ };
341
+ this.core.registerModule(targetModule, {
342
+ initialState,
343
+ otherParams: {
344
+ ...this.otherParams,
345
+ fatherModule: this.name,
346
+ openCache: ((_e2 = this.otherParams) == null ? void 0 : _e2.cacheId) ? true : false,
347
+ cacheId: (_f2 = this.otherParams) == null ? void 0 : _f2.cacheId,
348
+ salesSummaryModuleName: `${this.name}_salesSummary`,
349
+ provider: loggerProvider,
350
+ providerConfig: loggerConfig,
351
+ context: this.getLoggerContext()
352
+ }
353
+ });
354
+ } else {
355
+ this.logMethodError("initialize", `module ${step} missing`);
356
+ throw new Error(`模块 ${step} 不存在`);
357
+ }
358
+ });
359
+ const venueProductsModule = new import_ProductList.ProductList(`${this.name}_venueProducts`);
360
+ this.store.venueProducts = venueProductsModule;
361
+ this.core.registerModule(venueProductsModule, {
362
+ otherParams: {
363
+ ...this.otherParams,
364
+ fatherModule: this.name
365
+ }
366
+ });
367
+ const addonProductsModule = new import_ProductList.ProductList(`${this.name}_addonProducts`);
368
+ this.store.addonProducts = addonProductsModule;
369
+ this.core.registerModule(addonProductsModule, {
370
+ otherParams: {
371
+ ...this.otherParams,
372
+ fatherModule: this.name
373
+ }
374
+ });
375
+ const dateModule = new import_Date.DateModule(`${this.name}_date`);
376
+ this.store.date = dateModule;
377
+ this.core.registerModule(dateModule, {
378
+ otherParams: {
379
+ ...this.otherParams,
380
+ fatherModule: this.name,
381
+ cacheId: this.cacheId
382
+ }
383
+ });
384
+ const scheduleModule = new import_Schedule.ScheduleModule(`${this.name}_schedule`);
385
+ this.store.schedule = scheduleModule;
386
+ this.core.registerModule(scheduleModule, {
387
+ otherParams: {
388
+ ...this.otherParams,
389
+ fatherModule: this.name
390
+ }
391
+ });
392
+ const quotationModule = new import_Quotation.QuotationModule(`${this.name}_quotation`);
393
+ this.store.quotation = quotationModule;
394
+ this.core.registerModule(quotationModule, {
395
+ otherParams: {
396
+ ...this.otherParams,
397
+ fatherModule: this.name
398
+ }
399
+ });
400
+ const openDataModule = new import_OpenData.OpenDataModule(`${this.name}_openData`);
401
+ this.store.openData = openDataModule;
402
+ this.core.registerModule(openDataModule, {
403
+ otherParams: {
404
+ ...this.otherParams,
405
+ fatherModule: this.name,
406
+ openCache: !!((_f = this.otherParams) == null ? void 0 : _f.cacheId),
407
+ cacheId: (_g = this.otherParams) == null ? void 0 : _g.cacheId
408
+ }
409
+ });
410
+ if (this.store.scanOrderLogger) {
411
+ this.store.scanOrderLogger.setContext(this.getLoggerContext());
412
+ }
413
+ this.registerCustomerLoginListeners();
414
+ console.log("[VenueBooking] 初始化开始");
415
+ try {
416
+ await ((_h = this.store.order) == null ? void 0 : _h.recalculateSummary({ createIfMissing: false }));
417
+ (_i = this.store.order) == null ? void 0 : _i.persistTempOrder();
418
+ await this.loadRuntimeConfigs();
419
+ await this.refreshItemRuleQuantityLimits();
420
+ this.store.status = "ready";
421
+ console.log("[VenueBooking] 初始化完成");
422
+ await this.core.effects.emit(import_types.VenueBookingHooks.onInited, {
423
+ status: this.store.status
424
+ });
425
+ this.logMethodSuccess("initialize", {
426
+ status: this.store.status
427
+ });
428
+ } catch (error) {
429
+ this.store.status = "error";
430
+ this.store.error = error instanceof Error ? error.message : "初始化失败";
431
+ console.error("[VenueBooking] 初始化失败", error);
432
+ this.logMethodError("initialize", error, {
433
+ status: this.store.status
434
+ });
435
+ throw error;
436
+ }
437
+ }
438
+ async destroy() {
439
+ this.logMethodStart("destroy");
440
+ this.clearLoginEffectListeners();
441
+ await this.core.effects.emit(import_types.VenueBookingHooks.onDestroy, {});
442
+ console.log("[VenueBooking] 已销毁");
443
+ this.logMethodSuccess("destroy");
444
+ }
445
+ async retryInit() {
446
+ this.logMethodStart("retryInit");
447
+ console.log("[VenueBooking] retryInit 调用");
448
+ await this.core.effects.emit(import_types.VenueBookingHooks.onRetryInit, {});
449
+ try {
450
+ await this.initialize(this.core, this.initializeOptions);
451
+ this.logMethodSuccess("retryInit");
452
+ } catch (error) {
453
+ this.logMethodError("retryInit", error);
454
+ throw error;
455
+ }
456
+ }
457
+ async refresh() {
458
+ this.logMethodStart("refresh");
459
+ console.log("[VenueBooking] refresh 调用");
460
+ try {
461
+ this.store.status = "initializing";
462
+ await this.loadRuntimeConfigs();
463
+ await this.refreshItemRuleQuantityLimits();
464
+ this.store.status = "ready";
465
+ await this.core.effects.emit(import_types.VenueBookingHooks.onRefresh, {
466
+ status: this.store.status
467
+ });
468
+ this.logMethodSuccess("refresh", {
469
+ status: this.store.status
470
+ });
471
+ } catch (error) {
472
+ this.logMethodError("refresh", error);
473
+ throw error;
474
+ }
475
+ }
476
+ // ─── 状态查询 ───
477
+ getStatus() {
478
+ return this.store.status;
479
+ }
480
+ getEntryContext() {
481
+ return this.store.entryContext;
482
+ }
483
+ getItemRuleQuantityLimits() {
484
+ return this.store.itemRuleQuantityLimits || [];
485
+ }
486
+ getCartValidationPassed() {
487
+ var _a;
488
+ return ((_a = this.store.cartValidation) == null ? void 0 : _a.passed) ?? null;
489
+ }
490
+ getCartValidation() {
491
+ return this.store.cartValidation || { passed: null, failures: [] };
492
+ }
493
+ // ─── 场地商品 & 附加商品 ───
494
+ async loadVenueProducts(params) {
495
+ this.logMethodStart("loadVenueProducts", { productIds: params.productIds });
496
+ try {
497
+ if (!this.store.venueProducts)
498
+ throw new Error("venueProducts 模块未初始化");
499
+ const res = await this.store.venueProducts.loadProducts({
500
+ product_ids: params.productIds,
501
+ cacheId: this.cacheId,
502
+ schedule_date: (0, import_dayjs.default)().format("YYYY-MM-DD"),
503
+ schedule_datetime: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
504
+ });
505
+ const products = Array.isArray(res) ? res : [];
506
+ this.resourceProductMap = (0, import_resource.buildResourceProductMap)(products);
507
+ this.logMethodSuccess("loadVenueProducts", {
508
+ productCount: products.length,
509
+ resourceCount: this.resourceProductMap.size
510
+ });
511
+ return products;
512
+ } catch (error) {
513
+ this.logMethodError("loadVenueProducts", error);
514
+ throw error;
515
+ }
516
+ }
517
+ async loadAddonProducts(params) {
518
+ this.logMethodStart("loadAddonProducts");
519
+ try {
520
+ if (!this.store.addonProducts)
521
+ throw new Error("addonProducts 模块未初始化");
522
+ const res = await this.store.addonProducts.loadProducts({
523
+ category_ids: params.categoryIds || [],
524
+ product_ids: params.productIds || [],
525
+ collection: (params.collectionIds || []).map(String),
526
+ cacheId: this.cacheId,
527
+ schedule_date: (0, import_dayjs.default)().format("YYYY-MM-DD"),
528
+ schedule_datetime: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
529
+ });
530
+ const products = Array.isArray(res) ? res : [];
531
+ this.logMethodSuccess("loadAddonProducts", {
532
+ productCount: products.length
533
+ });
534
+ return products;
535
+ } catch (error) {
536
+ this.logMethodError("loadAddonProducts", error);
537
+ throw error;
538
+ }
539
+ }
540
+ getVenueProducts() {
541
+ var _a, _b;
542
+ return ((_b = (_a = this.store.venueProducts) == null ? void 0 : _a.store) == null ? void 0 : _b.list) || [];
543
+ }
544
+ getAddonProductsList() {
545
+ var _a, _b;
546
+ return ((_b = (_a = this.store.addonProducts) == null ? void 0 : _a.store) == null ? void 0 : _b.list) || [];
547
+ }
548
+ // ─── 报价单 ───
549
+ async loadQuotations(params) {
550
+ this.logMethodStart("loadQuotations");
551
+ try {
552
+ if (!this.store.quotation)
553
+ throw new Error("quotation 模块未初始化");
554
+ await this.store.quotation.loadQuotations(params);
555
+ this.logMethodSuccess("loadQuotations", {
556
+ count: this.store.quotation.getQuotationList().length
557
+ });
558
+ } catch (error) {
559
+ this.logMethodError("loadQuotations", error);
560
+ throw error;
561
+ }
562
+ }
563
+ // ─── 资源可用性 ───
564
+ async fetchResourceAvailability(params) {
565
+ this.logMethodStart("fetchResourceAvailability", params);
566
+ try {
567
+ const venueProducts = this.getVenueProducts();
568
+ if (!venueProducts.length) {
569
+ this.store.rawResourceData = [];
570
+ this.logMethodSuccess("fetchResourceAvailability", { resourceCount: 0 });
571
+ return;
572
+ }
573
+ const resourceIds = (0, import_resource.extractResourceIds)(venueProducts);
574
+ if (!resourceIds.length) {
575
+ this.store.rawResourceData = [];
576
+ this.logMethodSuccess("fetchResourceAvailability", { resourceIds: [] });
577
+ return;
578
+ }
579
+ const config = this.store.slotConfig;
580
+ const crossDay = (0, import_timeSlot.isBusinessHoursCrossDay)(config);
581
+ const effectiveEndDate = crossDay ? (0, import_dayjs.default)(params.endDate).add(1, "day").format("YYYY-MM-DD") : params.endDate;
582
+ if (!this.store.date)
583
+ throw new Error("date 模块未初始化");
584
+ const res = await this.store.date.fetchResourceDates({
585
+ query: {
586
+ start_date: params.startDate,
587
+ end_date: effectiveEndDate,
588
+ resource_ids: resourceIds
589
+ },
590
+ useCache: false
591
+ });
592
+ const rawData = [];
593
+ if ((res == null ? void 0 : res.data) && Array.isArray(res.data)) {
594
+ for (const item of res.data) {
595
+ rawData.push({
596
+ resourceId: item.id,
597
+ formId: item.form_id,
598
+ times: Array.isArray(item.times) ? item.times : [],
599
+ ...item
600
+ });
601
+ }
602
+ }
603
+ this.store.rawResourceData = rawData;
604
+ for (const item of rawData) {
605
+ const mapping = this.resourceProductMap.get(item.resourceId);
606
+ if (mapping && item.main_field) {
607
+ mapping.resourceName = item.main_field;
608
+ }
609
+ if (mapping && item.resource_form_id) {
610
+ mapping.formId = item.resource_form_id;
611
+ }
612
+ }
613
+ this.logMethodSuccess("fetchResourceAvailability", {
614
+ resourceCount: rawData.length,
615
+ totalTimes: rawData.reduce((sum, r) => sum + r.times.length, 0)
616
+ });
617
+ } catch (error) {
618
+ this.store.rawResourceData = [];
619
+ this.logMethodError("fetchResourceAvailability", error);
620
+ throw error;
621
+ }
622
+ }
623
+ // ─── 日期概览 & 时间槽矩阵(纯计算,不发请求) ───
624
+ getDateRangeSummary(params) {
625
+ return (0, import_dateSummary.buildDateRangeSummary)({
626
+ startDate: params.startDate,
627
+ endDate: params.endDate,
628
+ config: this.store.slotConfig,
629
+ rawResources: this.store.rawResourceData,
630
+ resourceProductMap: this.resourceProductMap,
631
+ quotationModule: this.store.quotation
632
+ });
633
+ }
634
+ getTimeSlotGrid(date) {
635
+ let quotationPriceMap;
636
+ if (this.store.quotation) {
637
+ const productIds = [...new Set([...this.resourceProductMap.values()].map((m) => m.productId))];
638
+ const timeLabels = (0, import_timeSlot.generateTimeLabels)(this.store.slotConfig);
639
+ const timePoints = timeLabels.map((label) => `${date} ${label}`);
640
+ quotationPriceMap = this.store.quotation.buildProductPriceMap({ productIds, timePoints });
641
+ }
642
+ return (0, import_timeSlot.buildTimeSlotGrid)({
643
+ date,
644
+ config: this.store.slotConfig,
645
+ rawResources: this.store.rawResourceData,
646
+ resourceProductMap: this.resourceProductMap,
647
+ quotationPriceMap
648
+ });
649
+ }
650
+ // ─── 时间槽订单操作 ───
651
+ /**
652
+ * 切换单个时段的选中状态(选中/取消)。
653
+ * 内部自动处理连续时段的合并与拆分,订单是唯一真相源。
654
+ */
655
+ async toggleSlot(slot) {
656
+ this.logMethodStart("toggleSlot", {
657
+ resourceId: slot.resourceId,
658
+ startTime: slot.startTime
659
+ });
660
+ try {
661
+ const mapping = this.resourceProductMap.get(slot.resourceId);
662
+ if (!mapping)
663
+ throw new Error(`未找到资源 ${slot.resourceId} 的商品映射`);
664
+ if (!this.store.order)
665
+ throw new Error("order 模块未初始化");
666
+ const currentSlots = this.getSelectedSlotsForResource(slot.resourceId);
667
+ const existIndex = currentSlots.findIndex((s) => s.startTime === slot.startTime);
668
+ let nextSlots;
669
+ if (existIndex !== -1) {
670
+ nextSlots = currentSlots.filter((_, i) => i !== existIndex);
671
+ } else {
672
+ nextSlots = [...currentSlots, slot];
673
+ }
674
+ await this.reconcileOrderForResource(slot.resourceId, nextSlots);
675
+ const products = this.store.order.getOrderProducts();
676
+ await this.refreshItemRuleQuantityLimits();
677
+ await this.refreshCartValidationPassed();
678
+ this.logMethodSuccess("toggleSlot", {
679
+ action: existIndex !== -1 ? "remove" : "add",
680
+ resourceId: slot.resourceId,
681
+ slotCount: nextSlots.length
682
+ });
683
+ return products;
684
+ } catch (error) {
685
+ this.logMethodError("toggleSlot", error);
686
+ throw error;
687
+ }
688
+ }
689
+ /**
690
+ * 获取某资源当前选中的所有独立时段(从订单中解析)。
691
+ */
692
+ getSelectedSlotsForResource(resourceId) {
693
+ var _a;
694
+ const tempOrder = (_a = this.store.order) == null ? void 0 : _a.getTempOrder();
695
+ if (!tempOrder)
696
+ return [];
697
+ const venueProducts = tempOrder.products.filter(
698
+ (p) => {
699
+ var _a2, _b;
700
+ return ((_a2 = p.metadata) == null ? void 0 : _a2.venue_booking) && String((_b = p.metadata) == null ? void 0 : _b.resource_id) === String(resourceId);
701
+ }
702
+ );
703
+ const slotDuration = this.store.slotConfig.slotDurationMinutes;
704
+ const slots = [];
705
+ for (const product of venueProducts) {
706
+ slots.push(...(0, import_slotMerge.expandMergedSlotToIndividual)(product, slotDuration));
707
+ }
708
+ return slots.sort((a, b) => a.startTime.localeCompare(b.startTime));
709
+ }
710
+ /**
711
+ * 判断某个时段是否已选中。
712
+ */
713
+ isSlotSelected(resourceId, startTime) {
714
+ return this.getSelectedSlotsForResource(resourceId).some((s) => s.startTime === startTime);
715
+ }
716
+ /**
717
+ * 获取所有已选时段(按资源分组)。
718
+ */
719
+ getAllSelectedSlots() {
720
+ var _a, _b;
721
+ const result = /* @__PURE__ */ new Map();
722
+ const tempOrder = (_a = this.store.order) == null ? void 0 : _a.getTempOrder();
723
+ if (!tempOrder)
724
+ return result;
725
+ const venueProducts = tempOrder.products.filter((p) => {
726
+ var _a2;
727
+ return (_a2 = p.metadata) == null ? void 0 : _a2.venue_booking;
728
+ });
729
+ const slotDuration = this.store.slotConfig.slotDurationMinutes;
730
+ for (const product of venueProducts) {
731
+ const resourceId = (_b = product.metadata) == null ? void 0 : _b.resource_id;
732
+ if (resourceId == null)
733
+ continue;
734
+ const existing = result.get(resourceId) || [];
735
+ existing.push(...(0, import_slotMerge.expandMergedSlotToIndividual)(product, slotDuration));
736
+ result.set(resourceId, existing);
737
+ }
738
+ for (const [key, slots] of result) {
739
+ result.set(key, slots.sort((a, b) => a.startTime.localeCompare(b.startTime)));
740
+ }
741
+ return result;
742
+ }
743
+ /**
744
+ * 对指定资源的订单商品进行 reconcile:
745
+ * 清除旧商品 → 合并连续时段 → 重新写入。
746
+ */
747
+ async reconcileOrderForResource(resourceId, slots) {
748
+ const mapping = this.resourceProductMap.get(resourceId);
749
+ if (!mapping || !this.store.order)
750
+ return;
751
+ const tempOrder = this.store.order.ensureTempOrder();
752
+ tempOrder.products = tempOrder.products.filter(
753
+ (p) => {
754
+ var _a, _b;
755
+ return !(((_a = p.metadata) == null ? void 0 : _a.venue_booking) && String((_b = p.metadata) == null ? void 0 : _b.resource_id) === String(resourceId));
756
+ }
757
+ );
758
+ tempOrder.bookings = (tempOrder.bookings || []).filter(
759
+ (b) => {
760
+ var _a, _b;
761
+ return !(((_a = b.metadata) == null ? void 0 : _a.venue_booking) && String((_b = b.metadata) == null ? void 0 : _b.resource_id) === String(resourceId));
762
+ }
763
+ );
764
+ if (!slots.length) {
765
+ this.store.order.applyDiscount();
766
+ await this.store.order.recalculateSummary({ createIfMissing: true });
767
+ this.store.order.persistTempOrder();
768
+ return;
769
+ }
770
+ const merged = (0, import_slotMerge.mergeConsecutiveSlots)(slots);
771
+ const rawResource = this.store.rawResourceData.find(
772
+ (r) => String(r.resourceId) === String(resourceId)
773
+ );
774
+ const venueProduct = this.getVenueProducts().find((p) => p.id === mapping.productId);
775
+ tempOrder.bookings = tempOrder.bookings || [];
776
+ for (let i = 0; i < merged.length; i++) {
777
+ const group = merged[i];
778
+ const identityKey = (0, import_slotMerge.buildVenueIdentityKey)(resourceId, i);
779
+ const bookingUuid = (0, import_utils2.createUuidV4)();
780
+ const startMoment = (0, import_dayjs.default)(group.startTime, "YYYY-MM-DD HH:mm");
781
+ const endMoment = (0, import_dayjs.default)(group.endTime, "YYYY-MM-DD HH:mm");
782
+ const duration = endMoment.diff(startMoment, "minute");
783
+ const customDepositData = cloneCustomDepositData(venueProduct == null ? void 0 : venueProduct.custom_deposit_data);
784
+ tempOrder.products.push(
785
+ (0, import_utils.normalizeOrderProduct)({
786
+ product_id: mapping.productId,
787
+ product_variant_id: 0,
788
+ identity_key: identityKey,
789
+ num: 1,
790
+ selling_price: group.totalPrice,
791
+ original_price: group.totalPrice,
792
+ payment_price: group.totalPrice,
793
+ is_charge_tax: (venueProduct == null ? void 0 : venueProduct.is_charge_tax) ?? 0,
794
+ metadata: {
795
+ venue_booking: true,
796
+ resource_id: resourceId,
797
+ resource_form_id: mapping.formId,
798
+ resource_name: mapping.resourceName,
799
+ start_time: group.startTime,
800
+ end_time: group.endTime,
801
+ slot_count: group.slotCount,
802
+ booking_uid: bookingUuid
803
+ },
804
+ _origin: {
805
+ name: mapping.productTitle,
806
+ cover: (venueProduct == null ? void 0 : venueProduct.cover) || "",
807
+ custom_deposit_data: customDepositData,
808
+ id: 0,
809
+ number: 1,
810
+ registration_type: "all",
811
+ relation_products: [],
812
+ is_all: false,
813
+ product: {
814
+ product_id: mapping.productId,
815
+ product_variant_id: 0,
816
+ num: 1,
817
+ product_bundle: [],
818
+ product_option_item: [],
819
+ discount_list: [],
820
+ custom_deposit_data: customDepositData,
821
+ metadata: {}
822
+ },
823
+ sub_type: "minutes",
824
+ duration,
825
+ like_status: "common",
826
+ resources: [{
827
+ relation_type: "form",
828
+ like_status: "common",
829
+ id: resourceId,
830
+ main_field: mapping.resourceName,
831
+ form_id: (rawResource == null ? void 0 : rawResource.form_id) ?? mapping.formId,
832
+ relation_id: resourceId,
833
+ capacity: (rawResource == null ? void 0 : rawResource.capacity) ?? 0,
834
+ metadata: {}
835
+ }],
836
+ schedule_id: 0,
837
+ select_date: startMoment.format("YYYY-MM-DD"),
838
+ start_date: startMoment.format("YYYY-MM-DD"),
839
+ start_time: startMoment.format("HH:mm"),
840
+ end_date: endMoment.format("YYYY-MM-DD"),
841
+ end_time: endMoment.format("HH:mm"),
842
+ metadata: {
843
+ venue_booking: true,
844
+ slot_count: group.slotCount
845
+ },
846
+ holder: null
847
+ }
848
+ })
849
+ );
850
+ const booking = (0, import_slotMerge.buildVenueBookingEntry)({
851
+ group,
852
+ resourceId,
853
+ mapping,
854
+ rawResource,
855
+ bookingUuid,
856
+ productUid: identityKey
857
+ });
858
+ tempOrder.bookings.push(booking);
859
+ }
860
+ this.store.order.applyDiscount();
861
+ await this.store.order.recalculateSummary({ createIfMissing: true });
862
+ this.store.order.persistTempOrder();
863
+ }
864
+ // ─── 配置 ───
865
+ setSlotConfig(config) {
866
+ this.store.slotConfig = {
867
+ ...this.store.slotConfig,
868
+ ...config
869
+ };
870
+ }
871
+ getSlotConfig() {
872
+ return { ...this.store.slotConfig };
873
+ }
874
+ // ─── 日程 ───
875
+ async loadSchedules() {
876
+ this.logMethodStart("loadSchedules");
877
+ try {
878
+ if (!this.store.schedule)
879
+ throw new Error("schedule 模块未初始化");
880
+ await this.store.schedule.loadAllSchedule();
881
+ this.logMethodSuccess("loadSchedules");
882
+ } catch (error) {
883
+ this.logMethodError("loadSchedules", error);
884
+ throw error;
885
+ }
886
+ }
887
+ getScheduleListByIds(ids) {
888
+ if (!this.store.schedule)
889
+ return [];
890
+ return this.store.schedule.getScheduleListByIds(ids);
891
+ }
892
+ // ─── 临时订单操作(保留原有能力) ───
893
+ getTempOrder() {
894
+ var _a;
895
+ const result = ((_a = this.store.order) == null ? void 0 : _a.getTempOrder()) || null;
896
+ return result;
897
+ }
898
+ updateTempOrderNote(note) {
899
+ if (!this.store.order)
900
+ throw new Error("order 模块未初始化");
901
+ return this.store.order.updateTempOrderNote(note);
902
+ }
903
+ updateTempOrderContactsInfo(contactsInfo) {
904
+ if (!this.store.order)
905
+ throw new Error("order 模块未初始化");
906
+ return this.store.order.updateTempOrderContactsInfo(contactsInfo);
907
+ }
908
+ ensureTempOrder() {
909
+ if (!this.store.order)
910
+ throw new Error("order 模块未初始化");
911
+ return this.store.order.ensureTempOrder();
912
+ }
913
+ async onCustomerLogin(params) {
914
+ this.logMethodStart("onCustomerLogin", { customerId: params.customerId });
915
+ try {
916
+ await this.refreshOrderMarketingAfterLogin({
917
+ customerId: params.customerId
918
+ });
919
+ this.logMethodSuccess("onCustomerLogin", { customerId: params.customerId });
920
+ } catch (error) {
921
+ this.logMethodError("onCustomerLogin", error);
922
+ throw error;
923
+ }
924
+ }
925
+ recalculateOrderPricesFromQuotation() {
926
+ var _a, _b;
927
+ if (!this.store.order || !this.store.quotation)
928
+ return;
929
+ const tempOrder = this.store.order.getTempOrder();
930
+ if (!((_a = tempOrder == null ? void 0 : tempOrder.products) == null ? void 0 : _a.length))
931
+ return;
932
+ const now = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
933
+ for (const product of tempOrder.products) {
934
+ if ((_b = product.metadata) == null ? void 0 : _b.venue_booking) {
935
+ const mapping = this.resourceProductMap.get(product.metadata.resource_id);
936
+ if (!mapping)
937
+ continue;
938
+ const slots = (0, import_slotMerge.expandMergedSlotToIndividual)(
939
+ product,
940
+ this.store.slotConfig.slotDurationMinutes
941
+ );
942
+ const updatedSlots = slots.map((slot) => ({
943
+ ...slot,
944
+ price: this.store.quotation.getPriceForProduct({
945
+ productId: mapping.productId,
946
+ datetime: slot.startTime
947
+ }) ?? mapping.price
948
+ }));
949
+ const merged = (0, import_slotMerge.mergeConsecutiveSlots)(updatedSlots);
950
+ if (merged.length === 1) {
951
+ product.selling_price = merged[0].totalPrice;
952
+ product.original_price = merged[0].totalPrice;
953
+ product.payment_price = merged[0].totalPrice;
954
+ }
955
+ } else if (product.product_id != null) {
956
+ const quotationPrice = this.store.quotation.getPriceForProduct({
957
+ productId: product.product_id,
958
+ variantId: product.product_variant_id ?? void 0,
959
+ datetime: now
960
+ });
961
+ if (quotationPrice !== null) {
962
+ product.selling_price = quotationPrice;
963
+ product.original_price = quotationPrice;
964
+ product.payment_price = quotationPrice;
965
+ }
966
+ }
967
+ }
968
+ }
969
+ async scanCode(code, customerId) {
970
+ this.logMethodStart("scanCode", { code });
971
+ try {
972
+ if (!this.store.order)
973
+ throw new Error("order 模块未初始化");
974
+ const result = await this.store.order.scanCode(code, customerId);
975
+ if (result.isAvailable) {
976
+ await this.store.order.recalculateSummary({ createIfMissing: true });
977
+ this.store.order.persistTempOrder();
978
+ }
979
+ this.logMethodSuccess("scanCode", { isAvailable: result.isAvailable });
980
+ return result;
981
+ } catch (error) {
982
+ this.logMethodError("scanCode", error);
983
+ throw error;
984
+ }
985
+ }
986
+ /** 获取当前折扣列表(包装 order.getDiscountList) */
987
+ getDiscountList() {
988
+ if (!this.store.order)
989
+ return [];
990
+ return this.store.order.getDiscountList();
991
+ }
992
+ /** 勾选/取消勾选某张折扣券,重新计算折扣并持久化 */
993
+ async setDiscountSelected(params) {
994
+ var _a, _b, _c, _d, _e;
995
+ this.logMethodStart("setDiscountSelected", params);
996
+ try {
997
+ if (!this.store.order)
998
+ throw new Error("order 模块未初始化");
999
+ const list = this.store.order.getDiscountList();
1000
+ const beforeTarget = list.find((d) => d.id === params.discountId) || null;
1001
+ const updated = list.map(
1002
+ (d) => d.id === params.discountId ? {
1003
+ ...d,
1004
+ isSelected: params.isSelected,
1005
+ isManualSelect: !params.isSelected
1006
+ } : d
1007
+ );
1008
+ const updatedTarget = updated.find((d) => d.id === params.discountId) || null;
1009
+ const tempOrder = this.store.order.ensureTempOrder();
1010
+ const orderStore = this.store.order.store || {};
1011
+ const discountModule = orderStore.discount;
1012
+ const rulesModule = orderStore.rules;
1013
+ const holders = ((_a = tempOrder.holder) == null ? void 0 : _a.form_record_id) ? [{ form_record_id: tempOrder.holder.form_record_id }] : [];
1014
+ let nextDiscountList = updated;
1015
+ await (discountModule == null ? void 0 : discountModule.setDiscountList(updated));
1016
+ if (rulesModule) {
1017
+ const result = rulesModule.calcDiscount(
1018
+ {
1019
+ productList: tempOrder.products,
1020
+ discountList: updated,
1021
+ holders,
1022
+ isFormSubject: !!((_b = tempOrder.holder) == null ? void 0 : _b.type) && tempOrder.holder.type === "form"
1023
+ },
1024
+ {
1025
+ discountId: params.discountId,
1026
+ isSelected: params.isSelected
1027
+ }
1028
+ ) || { productList: tempOrder.products, discountList: updated };
1029
+ if (result == null ? void 0 : result.productList) {
1030
+ tempOrder.products = result.productList;
1031
+ }
1032
+ if (result == null ? void 0 : result.discountList) {
1033
+ nextDiscountList = result.discountList;
1034
+ await (discountModule == null ? void 0 : discountModule.setDiscountList(result.discountList));
1035
+ }
1036
+ }
1037
+ tempOrder.discount_list = (nextDiscountList || []).filter((d) => d.isSelected);
1038
+ const afterApplyTarget = this.store.order.getDiscountList().find((d) => d.id === params.discountId) || null;
1039
+ await this.store.order.recalculateSummary({ createIfMissing: true });
1040
+ this.store.order.persistTempOrder();
1041
+ const finalSummary = ((_c = this.store.order.getTempOrder()) == null ? void 0 : _c.summary) || null;
1042
+ const finalProduct = ((_e = (_d = this.store.order.getTempOrder()) == null ? void 0 : _d.products) == null ? void 0 : _e[0]) || null;
1043
+ this.logMethodSuccess("setDiscountSelected", params);
1044
+ const finalTarget = this.store.order.getDiscountList().find((d) => d.id === params.discountId) || null;
1045
+ return this.store.order.getDiscountList();
1046
+ } catch (error) {
1047
+ this.logMethodError("setDiscountSelected", error);
1048
+ throw error;
1049
+ }
1050
+ }
1051
+ async addNewOrder() {
1052
+ this.logMethodStart("addNewOrder");
1053
+ try {
1054
+ if (!this.store.order)
1055
+ throw new Error("order 模块未初始化");
1056
+ const tempOrder = await this.store.order.addNewOrder();
1057
+ this.logMethodSuccess("addNewOrder", {
1058
+ productCount: tempOrder.products.length
1059
+ });
1060
+ return tempOrder;
1061
+ } catch (error) {
1062
+ this.logMethodError("addNewOrder", error);
1063
+ throw error;
1064
+ }
1065
+ }
1066
+ getOrderProducts() {
1067
+ if (!this.store.order)
1068
+ throw new Error("order 模块未初始化");
1069
+ return this.store.order.getOrderProducts();
1070
+ }
1071
+ async getSummary() {
1072
+ this.logMethodStart("getSummary");
1073
+ try {
1074
+ if (!this.store.order)
1075
+ throw new Error("order 模块未初始化");
1076
+ const summary = await this.store.order.getScanOrderSummary();
1077
+ this.logMethodSuccess("getSummary", {
1078
+ totalAmount: summary.total_amount
1079
+ });
1080
+ return summary;
1081
+ } catch (error) {
1082
+ this.logMethodError("getSummary", error);
1083
+ throw error;
1084
+ }
1085
+ }
1086
+ async submitOrder() {
1087
+ var _a;
1088
+ this.logMethodStart("submitOrder");
1089
+ try {
1090
+ await this.validateBeforeSubmitByItemRule();
1091
+ if (!this.store.order) {
1092
+ throw new Error("venueBooking解决方案需要 order 模块支持");
1093
+ }
1094
+ const result = await this.store.order.submitTempOrder({
1095
+ cacheId: this.cacheId
1096
+ });
1097
+ const tempOrder = this.store.order.getTempOrder();
1098
+ this.logMethodSuccess("submitOrder", {
1099
+ productCount: ((_a = tempOrder == null ? void 0 : tempOrder.products) == null ? void 0 : _a.length) || 0
1100
+ });
1101
+ return result;
1102
+ } catch (error) {
1103
+ this.logMethodError("submitOrder", error);
1104
+ throw error;
1105
+ }
1106
+ }
1107
+ async addProductToOrder(product) {
1108
+ var _a;
1109
+ this.logMethodStart("addProductToOrder", {
1110
+ product_id: product.product_id,
1111
+ product_variant_id: product.product_variant_id
1112
+ });
1113
+ try {
1114
+ if (!this.store.order)
1115
+ throw new Error("order 模块未初始化");
1116
+ if (!((_a = product.metadata) == null ? void 0 : _a.venue_booking) && this.store.quotation && product.product_id != null) {
1117
+ const quotationPrice = this.store.quotation.getPriceForProduct({
1118
+ productId: product.product_id,
1119
+ variantId: product.product_variant_id ?? void 0,
1120
+ datetime: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
1121
+ });
1122
+ if (quotationPrice !== null) {
1123
+ product.selling_price = quotationPrice;
1124
+ product.original_price = quotationPrice;
1125
+ product.payment_price = quotationPrice;
1126
+ }
1127
+ }
1128
+ const products = await this.store.order.addProductToOrder(product);
1129
+ await this.refreshItemRuleQuantityLimits();
1130
+ await this.refreshCartValidationPassed();
1131
+ this.logMethodSuccess("addProductToOrder", {
1132
+ productCount: products.length
1133
+ });
1134
+ return products;
1135
+ } catch (error) {
1136
+ this.logMethodError("addProductToOrder", error);
1137
+ throw error;
1138
+ }
1139
+ }
1140
+ async updateProductInOrder(params) {
1141
+ this.logMethodStart("updateProductInOrder", {
1142
+ product_id: params.product_id,
1143
+ product_variant_id: params.product_variant_id
1144
+ });
1145
+ try {
1146
+ if (!this.store.order)
1147
+ throw new Error("order 模块未初始化");
1148
+ const products = await this.store.order.updateProductInOrder(params);
1149
+ await this.refreshItemRuleQuantityLimits();
1150
+ await this.refreshCartValidationPassed();
1151
+ this.logMethodSuccess("updateProductInOrder", {
1152
+ productCount: products.length
1153
+ });
1154
+ return products;
1155
+ } catch (error) {
1156
+ this.logMethodError("updateProductInOrder", error);
1157
+ throw error;
1158
+ }
1159
+ }
1160
+ async removeProductFromOrder(identity) {
1161
+ this.logMethodStart("removeProductFromOrder", {
1162
+ product_id: identity.product_id,
1163
+ product_variant_id: identity.product_variant_id
1164
+ });
1165
+ try {
1166
+ if (!this.store.order)
1167
+ throw new Error("order 模块未初始化");
1168
+ const products = await this.store.order.removeProductFromOrder(identity);
1169
+ await this.refreshItemRuleQuantityLimits();
1170
+ await this.refreshCartValidationPassed();
1171
+ this.logMethodSuccess("removeProductFromOrder", {
1172
+ productCount: products.length
1173
+ });
1174
+ return products;
1175
+ } catch (error) {
1176
+ this.logMethodError("removeProductFromOrder", error);
1177
+ throw error;
1178
+ }
1179
+ }
1180
+ async getProductList() {
1181
+ var _a, _b, _c, _d, _e, _f, _g;
1182
+ this.logMethodStart("getProductList");
1183
+ const cachedList = (_b = (_a = this.store.products) == null ? void 0 : _a.store) == null ? void 0 : _b.list;
1184
+ if (Array.isArray(cachedList) && cachedList.length > 0) {
1185
+ const formattedRes = (0, import_utils.attachItemRuleLimitsToTopLevelProducts)(
1186
+ cachedList,
1187
+ this.store.itemRuleQuantityLimits || []
1188
+ );
1189
+ this.logMethodSuccess("getProductList", { fromCache: true });
1190
+ return formattedRes;
1191
+ }
1192
+ const menuListIds = ((_c = this.otherParams) == null ? void 0 : _c.menuListIds) || ((_f = (_e = (_d = this.otherParams) == null ? void 0 : _d.dineInConfig) == null ? void 0 : _e["menu.associated_menus"]) == null ? void 0 : _f.map((n) => Number(n.value))) || [];
1193
+ try {
1194
+ const res = await ((_g = this.store.products) == null ? void 0 : _g.loadProducts({
1195
+ menu_list_ids: menuListIds,
1196
+ cacheId: this.cacheId,
1197
+ schedule_date: (0, import_dayjs.default)().format("YYYY-MM-DD"),
1198
+ schedule_datetime: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
1199
+ }));
1200
+ const formattedRes = (0, import_utils.attachItemRuleLimitsToTopLevelProducts)(
1201
+ res,
1202
+ this.store.itemRuleQuantityLimits || []
1203
+ );
1204
+ this.logMethodSuccess("getProductList", {
1205
+ menuCount: menuListIds.length
1206
+ });
1207
+ return formattedRes;
1208
+ } catch (error) {
1209
+ this.logMethodError("getProductList", error);
1210
+ throw error;
1211
+ }
1212
+ }
1213
+ // ─── ItemRule 引擎 ───
1214
+ async loadOpenDataConfig() {
1215
+ if (!this.store.openData)
1216
+ throw new Error("openData 模块未初始化");
1217
+ const openDataConfig = await this.store.openData.fetchOpenData({
1218
+ scope: "board",
1219
+ target: "venue_booking+online_store",
1220
+ section_code: [...OPEN_DATA_SECTION_CODES]
1221
+ });
1222
+ this.otherParams.dineInConfig = openDataConfig;
1223
+ return openDataConfig;
1224
+ }
1225
+ async loadRuntimeConfigs() {
1226
+ await this.loadOpenDataConfig();
1227
+ const itemRuleConfigs = await this.ensureItemRuleConfigsLoaded();
1228
+ this.logMethodSuccess("loadRuntimeConfigs", {
1229
+ itemRuleCount: itemRuleConfigs.length
1230
+ });
1231
+ return { itemRuleConfigs };
1232
+ }
1233
+ async fetchItemRuleConfigsByModelIds(strategyModelIds) {
1234
+ this.logMethodStart("fetchItemRuleConfigsByModelIds", { strategyModelIds });
1235
+ if (!strategyModelIds.length)
1236
+ return [];
1237
+ try {
1238
+ const result = await this.request.get("/promotion", {
1239
+ skip: 1,
1240
+ num: 99,
1241
+ status: "active",
1242
+ ids: strategyModelIds
1243
+ });
1244
+ let configs = [];
1245
+ if (result.code === 200) {
1246
+ configs = result.data.list.map((item) => item.metadata);
1247
+ }
1248
+ this.logMethodSuccess("fetchItemRuleConfigsByModelIds", {
1249
+ strategyModelIds,
1250
+ strategyCount: configs.length
1251
+ });
1252
+ return configs;
1253
+ } catch (error) {
1254
+ this.logMethodError("fetchItemRuleConfigsByModelIds", error, { strategyModelIds });
1255
+ return [];
1256
+ }
1257
+ }
1258
+ async buildPrefillProductSourceMap() {
1259
+ const sourceMap = /* @__PURE__ */ new Map();
1260
+ try {
1261
+ const productList = await this.getProductList();
1262
+ if (!Array.isArray(productList))
1263
+ return sourceMap;
1264
+ const visited = /* @__PURE__ */ new Set();
1265
+ const collectFromValue = (value) => {
1266
+ if (!value || typeof value !== "object")
1267
+ return;
1268
+ if (visited.has(value))
1269
+ return;
1270
+ visited.add(value);
1271
+ if (Array.isArray(value)) {
1272
+ for (const item of value)
1273
+ collectFromValue(item);
1274
+ return;
1275
+ }
1276
+ const node = value;
1277
+ const rawProductId = node.product_id ?? node.id;
1278
+ const productId = Number(rawProductId);
1279
+ if (Number.isFinite(productId) && productId > 0) {
1280
+ const productVariantId = Number(node.product_variant_id ?? node.variant_id ?? 0);
1281
+ const normalizedVariantId = Number.isNaN(productVariantId) ? 0 : productVariantId;
1282
+ const key = (0, import_utils.buildProductKey)(productId, normalizedVariantId);
1283
+ if (!sourceMap.has(key))
1284
+ sourceMap.set(key, node);
1285
+ }
1286
+ for (const childValue of Object.values(node)) {
1287
+ if (childValue && typeof childValue === "object")
1288
+ collectFromValue(childValue);
1289
+ }
1290
+ };
1291
+ collectFromValue(productList);
1292
+ } catch (error) {
1293
+ this.logMethodError("buildPrefillProductSourceMap", error);
1294
+ }
1295
+ return sourceMap;
1296
+ }
1297
+ getItemRuleRuntimeConfig() {
1298
+ return this.itemRuleRuntimeConfig || {};
1299
+ }
1300
+ async ensureItemRuleConfigsLoaded() {
1301
+ if (this.itemRuleConfigs.length > 0)
1302
+ return this.itemRuleConfigs;
1303
+ if (this.itemRuleConfigsPromise)
1304
+ return this.itemRuleConfigsPromise;
1305
+ this.itemRuleConfigsPromise = (async () => {
1306
+ const runtimeConfig = this.getItemRuleRuntimeConfig();
1307
+ const staticConfigs = (0, import_utils.normalizeItemRuleStrategies)(runtimeConfig.strategyConfigs);
1308
+ if (staticConfigs.length > 0) {
1309
+ this.itemRuleConfigs = staticConfigs;
1310
+ this.itemRuleEvaluator.setStrategyConfigs(staticConfigs);
1311
+ return this.itemRuleConfigs;
1312
+ }
1313
+ this.itemRuleConfigs = [];
1314
+ this.itemRuleEvaluator.setStrategyConfigs([]);
1315
+ return this.itemRuleConfigs;
1316
+ })();
1317
+ return await this.itemRuleConfigsPromise;
1318
+ }
1319
+ async refreshItemRuleQuantityLimits() {
1320
+ try {
1321
+ const strategyConfigs = await this.ensureItemRuleConfigsLoaded();
1322
+ if (!strategyConfigs.length) {
1323
+ this.store.itemRuleQuantityLimits = [];
1324
+ return [];
1325
+ }
1326
+ const businessData = (0, import_utils.buildItemRuleBusinessData)({
1327
+ tempOrder: this.ensureTempOrder(),
1328
+ runtimeConfig: this.getItemRuleRuntimeConfig(),
1329
+ itemRuleConfigs: this.itemRuleConfigs
1330
+ });
1331
+ const limits = this.itemRuleEvaluator.getQuantityLimits(businessData);
1332
+ this.store.itemRuleQuantityLimits = limits;
1333
+ this.logMethodSuccess("refreshItemRuleQuantityLimits", { limitCount: limits.length });
1334
+ return limits;
1335
+ } catch (error) {
1336
+ this.store.itemRuleQuantityLimits = [];
1337
+ this.logMethodError("refreshItemRuleQuantityLimits", error);
1338
+ return [];
1339
+ }
1340
+ }
1341
+ async applyPrefillByItemRule() {
1342
+ var _a;
1343
+ if (this.itemRulePrefillApplied)
1344
+ return;
1345
+ if (!this.store.order)
1346
+ return;
1347
+ const strategyConfigs = await this.ensureItemRuleConfigsLoaded();
1348
+ if (!strategyConfigs.length)
1349
+ return;
1350
+ const businessData = (0, import_utils.buildItemRuleBusinessData)({
1351
+ tempOrder: this.ensureTempOrder(),
1352
+ runtimeConfig: this.getItemRuleRuntimeConfig(),
1353
+ itemRuleConfigs: this.itemRuleConfigs
1354
+ });
1355
+ const prefillItems = this.itemRuleEvaluator.getPrefillItems(businessData);
1356
+ if (!prefillItems.length) {
1357
+ this.itemRulePrefillApplied = true;
1358
+ return;
1359
+ }
1360
+ const productSourceMap = await this.buildPrefillProductSourceMap();
1361
+ const tempOrder = this.ensureTempOrder();
1362
+ let hasChanges = false;
1363
+ for (const prefillItem of prefillItems) {
1364
+ const productId = Number(prefillItem.product_id);
1365
+ const productVariantId = Number(prefillItem.product_variant_id ?? 0);
1366
+ const targetQuantity = (0, import_utils.toNonNegativeInt)(prefillItem.quantity);
1367
+ if (!Number.isFinite(productId) || targetQuantity <= 0)
1368
+ continue;
1369
+ if (Number.isNaN(productVariantId))
1370
+ continue;
1371
+ const sourceItem = productSourceMap.get((0, import_utils.buildProductKey)(productId, productVariantId)) || productSourceMap.get((0, import_utils.buildProductKey)(productId, 0)) || null;
1372
+ const productIndex = (0, import_utils.getProductIdentityIndex)(tempOrder.products, {
1373
+ product_id: productId,
1374
+ product_variant_id: productVariantId
1375
+ });
1376
+ if (productIndex === -1) {
1377
+ const sellingPrice = (0, import_utils.toPriceString)((sourceItem == null ? void 0 : sourceItem.price) ?? (sourceItem == null ? void 0 : sourceItem.selling_price), "0.00");
1378
+ const originalPrice = (0, import_utils.toPriceString)((sourceItem == null ? void 0 : sourceItem.original_price) ?? (sourceItem == null ? void 0 : sourceItem.price) ?? sellingPrice, sellingPrice);
1379
+ const paymentPrice = (0, import_utils.toPriceString)((sourceItem == null ? void 0 : sourceItem.payment_price) ?? (sourceItem == null ? void 0 : sourceItem.price) ?? sellingPrice, sellingPrice);
1380
+ tempOrder.products.push(
1381
+ (0, import_utils.normalizeOrderProduct)({
1382
+ product_id: productId,
1383
+ product_variant_id: productVariantId,
1384
+ num: targetQuantity,
1385
+ selling_price: sellingPrice,
1386
+ original_price: originalPrice,
1387
+ payment_price: paymentPrice,
1388
+ metadata: { item_rule_prefill: true, item_rule_id: prefillItem.ruleId },
1389
+ _origin: { ...sourceItem || {}, item_rule_prefill: true, item_rule_id: prefillItem.ruleId }
1390
+ })
1391
+ );
1392
+ hasChanges = true;
1393
+ continue;
1394
+ }
1395
+ const targetProduct = tempOrder.products[productIndex];
1396
+ const existedQuantity = (0, import_utils.toNonNegativeInt)(targetProduct.num);
1397
+ const delta = targetQuantity - existedQuantity;
1398
+ const nextProduct = {
1399
+ ...targetProduct,
1400
+ ...delta > 0 ? { num: (0, import_utils.getSafeProductNum)(existedQuantity + delta) } : {},
1401
+ metadata: { ...targetProduct.metadata || {}, item_rule_prefill: true, item_rule_id: prefillItem.ruleId },
1402
+ _origin: sourceItem ? { ...targetProduct._origin || {}, ...sourceItem } : targetProduct._origin
1403
+ };
1404
+ if (delta > 0 || Boolean(sourceItem && (!targetProduct._origin || ((_a = targetProduct._origin) == null ? void 0 : _a.price) !== (sourceItem == null ? void 0 : sourceItem.price)))) {
1405
+ tempOrder.products[productIndex] = nextProduct;
1406
+ hasChanges = true;
1407
+ }
1408
+ }
1409
+ if (hasChanges) {
1410
+ await this.store.order.recalculateSummary({ createIfMissing: true });
1411
+ this.store.order.persistTempOrder();
1412
+ }
1413
+ await this.refreshItemRuleQuantityLimits();
1414
+ this.itemRulePrefillApplied = true;
1415
+ this.logMethodSuccess("applyPrefillByItemRule", {
1416
+ prefillCount: prefillItems.length,
1417
+ hasChanges
1418
+ });
1419
+ }
1420
+ async applyItemRulePrefill() {
1421
+ this.logMethodStart("applyItemRulePrefill");
1422
+ await this.applyPrefillByItemRule();
1423
+ await this.refreshItemRuleQuantityLimits();
1424
+ await this.refreshCartValidationPassed();
1425
+ }
1426
+ async evaluateCartValidationByItemRule() {
1427
+ const strategyConfigs = await this.ensureItemRuleConfigsLoaded();
1428
+ if (!strategyConfigs.length)
1429
+ return { passed: true, failures: [] };
1430
+ const businessData = (0, import_utils.buildItemRuleBusinessData)({
1431
+ tempOrder: this.ensureTempOrder(),
1432
+ runtimeConfig: this.getItemRuleRuntimeConfig(),
1433
+ itemRuleConfigs: this.itemRuleConfigs
1434
+ });
1435
+ return this.itemRuleEvaluator.validateCart(businessData);
1436
+ }
1437
+ async validateBeforeSubmitByItemRule() {
1438
+ const validationResult = await this.evaluateCartValidationByItemRule();
1439
+ if (validationResult.passed)
1440
+ return;
1441
+ const firstFailure = validationResult.failures[0];
1442
+ const errorMessage = (firstFailure == null ? void 0 : firstFailure.validationMessage) || "当前购物车未满足商品规则,请调整后再提交";
1443
+ const error = new Error(String(errorMessage));
1444
+ error.failures = validationResult.failures;
1445
+ throw error;
1446
+ }
1447
+ async refreshCartValidationPassed() {
1448
+ const previous = this.store.cartValidation || { passed: null, failures: [] };
1449
+ let nextState = {
1450
+ passed: null,
1451
+ failures: []
1452
+ };
1453
+ try {
1454
+ const validationResult = await this.evaluateCartValidationByItemRule();
1455
+ nextState = {
1456
+ passed: validationResult.passed,
1457
+ failures: validationResult.failures || []
1458
+ };
1459
+ } catch {
1460
+ nextState = { passed: false, failures: [] };
1461
+ }
1462
+ this.store.cartValidation = nextState;
1463
+ const changed = previous.passed !== nextState.passed || previous.failures !== nextState.failures;
1464
+ if (changed) {
1465
+ await this.core.effects.emit(import_types.VenueBookingHooks.onCartValidationChanged, {
1466
+ cartValidation: nextState,
1467
+ cartValidationPassed: nextState.passed
1468
+ });
1469
+ }
1470
+ return nextState.passed;
1471
+ }
1472
+ async setItemRuleRuntimeConfig(config = {}) {
1473
+ var _a, _b;
1474
+ this.logMethodStart("setItemRuleRuntimeConfig");
1475
+ this.itemRuleRuntimeConfig = {
1476
+ ...this.itemRuleRuntimeConfig,
1477
+ ...config,
1478
+ pax: { ...((_a = this.itemRuleRuntimeConfig) == null ? void 0 : _a.pax) || {}, ...(config == null ? void 0 : config.pax) || {} },
1479
+ custom: { ...((_b = this.itemRuleRuntimeConfig) == null ? void 0 : _b.custom) || {}, ...(config == null ? void 0 : config.custom) || {} }
1480
+ };
1481
+ if ("strategyConfigs" in config) {
1482
+ this.itemRuleConfigs = [];
1483
+ this.itemRuleConfigsPromise = null;
1484
+ this.itemRuleEvaluator.setStrategyConfigs([]);
1485
+ }
1486
+ this.itemRulePrefillApplied = false;
1487
+ await this.refreshItemRuleQuantityLimits();
1488
+ await this.refreshCartValidationPassed();
1489
+ this.logMethodSuccess("setItemRuleRuntimeConfig", {
1490
+ strategyCount: Array.isArray(this.itemRuleRuntimeConfig.strategyConfigs) ? this.itemRuleRuntimeConfig.strategyConfigs.length : 0
1491
+ });
1492
+ }
1493
+ getOtherParams() {
1494
+ return this.otherParams;
1495
+ }
1496
+ // ─── OpenData 可用性 ───
1497
+ async checkOpenDataAvailability() {
1498
+ if (!this.store.openData)
1499
+ throw new Error("openData 模块未初始化");
1500
+ await this.loadOpenDataConfig();
1501
+ return this.store.openData.checkAvailability(this.store.schedule);
1502
+ }
1503
+ };
1504
+ // Annotate the CommonJS export names for ESM import in node:
1505
+ 0 && (module.exports = {
1506
+ VenueBookingImpl,
1507
+ ...require("./types")
1508
+ });