@pisell/pisellos 3.0.89 → 3.0.91

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