@pisell/pisellos 2.2.177 → 2.2.179

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 (183) hide show
  1. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  2. package/dist/modules/Customer/index.d.ts +0 -6
  3. package/dist/modules/Customer/index.js +83 -129
  4. package/dist/modules/Customer/types.d.ts +0 -2
  5. package/dist/modules/Discount/index.d.ts +4 -2
  6. package/dist/modules/Discount/index.js +93 -8
  7. package/dist/modules/Discount/types.d.ts +7 -1
  8. package/dist/modules/Order/index.d.ts +18 -87
  9. package/dist/modules/Order/index.js +497 -1303
  10. package/dist/modules/Order/types.d.ts +19 -198
  11. package/dist/modules/Order/types.js +0 -31
  12. package/dist/modules/Order/utils.d.ts +1 -50
  13. package/dist/modules/Order/utils.js +32 -261
  14. package/dist/modules/Quotation/index.d.ts +1 -0
  15. package/dist/modules/Quotation/index.js +21 -23
  16. package/dist/modules/Rules/index.d.ts +0 -4
  17. package/dist/modules/Rules/index.js +10 -26
  18. package/dist/modules/SalesSummary/index.js +2 -4
  19. package/dist/modules/SalesSummary/utils.js +5 -18
  20. package/dist/modules/Schedule/index.js +2 -6
  21. package/dist/modules/index.d.ts +0 -1
  22. package/dist/modules/index.js +1 -2
  23. package/dist/server/index.js +29 -87
  24. package/dist/server/modules/order/index.d.ts +0 -23
  25. package/dist/server/modules/order/index.js +46 -123
  26. package/dist/server/modules/order/types.d.ts +2 -0
  27. package/dist/server/modules/order/utils/filterOrders.js +6 -20
  28. package/dist/server/modules/products/index.d.ts +1 -1
  29. package/dist/server/modules/products/index.js +113 -130
  30. package/dist/server/modules/schedule/index.js +6 -13
  31. package/dist/solution/BaseSales/index.d.ts +7 -89
  32. package/dist/solution/BaseSales/index.js +375 -1494
  33. package/dist/solution/BaseSales/types.d.ts +1 -67
  34. package/dist/solution/BaseSales/types.js +1 -3
  35. package/dist/solution/BaseSales/utils/parseSalesResponse.d.ts +1 -0
  36. package/dist/solution/BaseSales/utils/parseSalesResponse.js +1 -1
  37. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +16 -68
  38. package/dist/solution/BaseSales/utils.js +8 -46
  39. package/dist/solution/BookingByStep/index.d.ts +1 -1
  40. package/dist/solution/BookingTicket/index.d.ts +1 -133
  41. package/dist/solution/BookingTicket/index.js +175 -780
  42. package/dist/solution/BookingTicket/types.d.ts +0 -2
  43. package/dist/solution/BookingTicket/types.js +0 -3
  44. package/dist/solution/BookingTicket/utils/cartView.js +2 -4
  45. package/dist/solution/ScanOrder/index.d.ts +3 -9
  46. package/dist/solution/ScanOrder/index.js +128 -231
  47. package/dist/solution/ScanOrder/utils.js +8 -46
  48. package/dist/solution/ShopDiscount/index.d.ts +1 -0
  49. package/dist/solution/ShopDiscount/index.js +23 -18
  50. package/dist/solution/VenueBooking/index.d.ts +9 -5
  51. package/dist/solution/VenueBooking/index.js +55 -103
  52. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +0 -4
  53. package/dist/solution/VenueBooking/utils/slotMerge.js +0 -10
  54. package/lib/model/strategy/adapter/promotion/index.js +49 -0
  55. package/lib/modules/Customer/index.d.ts +0 -6
  56. package/lib/modules/Customer/index.js +11 -26
  57. package/lib/modules/Customer/types.d.ts +0 -2
  58. package/lib/modules/Discount/index.d.ts +4 -2
  59. package/lib/modules/Discount/index.js +63 -8
  60. package/lib/modules/Discount/types.d.ts +7 -1
  61. package/lib/modules/Order/index.d.ts +18 -87
  62. package/lib/modules/Order/index.js +146 -633
  63. package/lib/modules/Order/types.d.ts +19 -198
  64. package/lib/modules/Order/types.js +0 -1
  65. package/lib/modules/Order/utils.d.ts +1 -50
  66. package/lib/modules/Order/utils.js +22 -229
  67. package/lib/modules/Quotation/index.d.ts +1 -0
  68. package/lib/modules/Quotation/index.js +15 -18
  69. package/lib/modules/Rules/index.d.ts +0 -4
  70. package/lib/modules/Rules/index.js +14 -22
  71. package/lib/modules/SalesSummary/index.js +2 -4
  72. package/lib/modules/SalesSummary/utils.js +5 -18
  73. package/lib/modules/Schedule/index.js +1 -3
  74. package/lib/modules/index.d.ts +0 -1
  75. package/lib/modules/index.js +1 -3
  76. package/lib/server/index.js +4 -41
  77. package/lib/server/modules/order/index.d.ts +0 -23
  78. package/lib/server/modules/order/index.js +14 -46
  79. package/lib/server/modules/order/types.d.ts +2 -0
  80. package/lib/server/modules/order/utils/filterOrders.js +4 -12
  81. package/lib/server/modules/products/index.d.ts +1 -1
  82. package/lib/server/modules/products/index.js +20 -30
  83. package/lib/server/modules/schedule/index.js +1 -2
  84. package/lib/solution/BaseSales/index.d.ts +7 -89
  85. package/lib/solution/BaseSales/index.js +22 -736
  86. package/lib/solution/BaseSales/types.d.ts +1 -67
  87. package/lib/solution/BaseSales/types.js +1 -3
  88. package/lib/solution/BaseSales/utils/parseSalesResponse.d.ts +1 -0
  89. package/lib/solution/BaseSales/utils/parseSalesResponse.js +1 -0
  90. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +12 -71
  91. package/lib/solution/BaseSales/utils.js +6 -46
  92. package/lib/solution/BookingByStep/index.d.ts +1 -1
  93. package/lib/solution/BookingTicket/index.d.ts +1 -133
  94. package/lib/solution/BookingTicket/index.js +8 -352
  95. package/lib/solution/BookingTicket/types.d.ts +0 -2
  96. package/lib/solution/BookingTicket/types.js +0 -6
  97. package/lib/solution/BookingTicket/utils/cartView.js +2 -4
  98. package/lib/solution/ScanOrder/index.d.ts +3 -9
  99. package/lib/solution/ScanOrder/index.js +66 -147
  100. package/lib/solution/ScanOrder/utils.js +6 -46
  101. package/lib/solution/ShopDiscount/index.d.ts +1 -0
  102. package/lib/solution/ShopDiscount/index.js +4 -2
  103. package/lib/solution/VenueBooking/index.d.ts +9 -5
  104. package/lib/solution/VenueBooking/index.js +14 -50
  105. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +0 -4
  106. package/lib/solution/VenueBooking/utils/slotMerge.js +0 -10
  107. package/package.json +2 -2
  108. package/dist/modules/BookingContext/index.d.ts +0 -37
  109. package/dist/modules/BookingContext/index.js +0 -436
  110. package/dist/modules/BookingContext/types.d.ts +0 -102
  111. package/dist/modules/BookingContext/types.js +0 -51
  112. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +0 -16
  113. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +0 -193
  114. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +0 -8
  115. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +0 -137
  116. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +0 -75
  117. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.js +0 -215
  118. package/dist/modules/BookingContext/utils/flexible.d.ts +0 -28
  119. package/dist/modules/BookingContext/utils/flexible.js +0 -56
  120. package/dist/modules/BookingContext/utils/formatResourceList.d.ts +0 -8
  121. package/dist/modules/BookingContext/utils/formatResourceList.js +0 -38
  122. package/dist/modules/BookingContext/utils/index.d.ts +0 -11
  123. package/dist/modules/BookingContext/utils/index.js +0 -11
  124. package/dist/modules/BookingContext/utils/noResource.d.ts +0 -13
  125. package/dist/modules/BookingContext/utils/noResource.js +0 -77
  126. package/dist/modules/BookingContext/utils/productExtend.d.ts +0 -72
  127. package/dist/modules/BookingContext/utils/productExtend.js +0 -339
  128. package/dist/modules/BookingContext/utils/resourceErrors.d.ts +0 -41
  129. package/dist/modules/BookingContext/utils/resourceErrors.js +0 -74
  130. package/dist/modules/BookingContext/utils/resourceSelection.d.ts +0 -7
  131. package/dist/modules/BookingContext/utils/resourceSelection.js +0 -24
  132. package/dist/modules/BookingContext/utils/resources.d.ts +0 -80
  133. package/dist/modules/BookingContext/utils/resources.js +0 -486
  134. package/dist/modules/BookingContext/utils/serviceTimes.d.ts +0 -55
  135. package/dist/modules/BookingContext/utils/serviceTimes.js +0 -151
  136. package/dist/modules/BookingContext/utils/timeSlices.d.ts +0 -42
  137. package/dist/modules/BookingContext/utils/timeSlices.js +0 -100
  138. package/dist/modules/Order/utils/manualProductDiscount.d.ts +0 -106
  139. package/dist/modules/Order/utils/manualProductDiscount.js +0 -212
  140. package/dist/solution/BaseSales/utils/cartPromotion.d.ts +0 -275
  141. package/dist/solution/BaseSales/utils/cartPromotion.js +0 -1258
  142. package/dist/solution/BaseSales/utils/quotationPrice.d.ts +0 -7
  143. package/dist/solution/BaseSales/utils/quotationPrice.js +0 -237
  144. package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +0 -113
  145. package/dist/solution/BookingTicket/utils/addProductDecision.js +0 -346
  146. package/lib/modules/BookingContext/index.d.ts +0 -37
  147. package/lib/modules/BookingContext/index.js +0 -297
  148. package/lib/modules/BookingContext/types.d.ts +0 -102
  149. package/lib/modules/BookingContext/types.js +0 -34
  150. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +0 -16
  151. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +0 -207
  152. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +0 -8
  153. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +0 -141
  154. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +0 -75
  155. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.js +0 -198
  156. package/lib/modules/BookingContext/utils/flexible.d.ts +0 -28
  157. package/lib/modules/BookingContext/utils/flexible.js +0 -80
  158. package/lib/modules/BookingContext/utils/formatResourceList.d.ts +0 -8
  159. package/lib/modules/BookingContext/utils/formatResourceList.js +0 -50
  160. package/lib/modules/BookingContext/utils/index.d.ts +0 -11
  161. package/lib/modules/BookingContext/utils/index.js +0 -43
  162. package/lib/modules/BookingContext/utils/noResource.d.ts +0 -13
  163. package/lib/modules/BookingContext/utils/noResource.js +0 -90
  164. package/lib/modules/BookingContext/utils/productExtend.d.ts +0 -72
  165. package/lib/modules/BookingContext/utils/productExtend.js +0 -283
  166. package/lib/modules/BookingContext/utils/resourceErrors.d.ts +0 -41
  167. package/lib/modules/BookingContext/utils/resourceErrors.js +0 -80
  168. package/lib/modules/BookingContext/utils/resourceSelection.d.ts +0 -7
  169. package/lib/modules/BookingContext/utils/resourceSelection.js +0 -46
  170. package/lib/modules/BookingContext/utils/resources.d.ts +0 -80
  171. package/lib/modules/BookingContext/utils/resources.js +0 -377
  172. package/lib/modules/BookingContext/utils/serviceTimes.d.ts +0 -55
  173. package/lib/modules/BookingContext/utils/serviceTimes.js +0 -162
  174. package/lib/modules/BookingContext/utils/timeSlices.d.ts +0 -42
  175. package/lib/modules/BookingContext/utils/timeSlices.js +0 -124
  176. package/lib/modules/Order/utils/manualProductDiscount.d.ts +0 -106
  177. package/lib/modules/Order/utils/manualProductDiscount.js +0 -207
  178. package/lib/solution/BaseSales/utils/cartPromotion.d.ts +0 -275
  179. package/lib/solution/BaseSales/utils/cartPromotion.js +0 -836
  180. package/lib/solution/BaseSales/utils/quotationPrice.d.ts +0 -7
  181. package/lib/solution/BaseSales/utils/quotationPrice.js +0 -277
  182. package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +0 -113
  183. package/lib/solution/BookingTicket/utils/addProductDecision.js +0 -318
@@ -37,9 +37,7 @@ var import_types = require("./types");
37
37
  var import_utils = require("./utils");
38
38
  var import_utils2 = require("../Product/utils");
39
39
  var import_dayjs = __toESM(require("dayjs"));
40
- var import_cartPromotion = require("../../solution/BaseSales/utils/cartPromotion");
41
40
  var import_utils3 = require("../../solution/ScanOrder/utils");
42
- var import_manualProductDiscount = require("./utils/manualProductDiscount");
43
41
  var import_Discount = require("../Discount");
44
42
  var import_Rules = require("../Rules");
45
43
  var import_types2 = require("../Rules/types");
@@ -51,17 +49,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
51
49
  super(name || "order", version);
52
50
  this.defaultName = "order";
53
51
  this.defaultVersion = "1.0.0";
54
- // ─── 促销/赠品 ────────────────────────────────────
55
- /** 评估器引用;由 SalesSdkProvider 注入,未注入时 applyPromotion 静默跳过 */
56
- this.promotionEvaluator = null;
57
- /** 赠品选择 resolver;由 SDK host bridge 注入 */
58
- this.giftSelectResolver = null;
59
- /** applyPromotion 递归保护 flag(写路径同步调 applyPromotion,禁止重入) */
60
- this.isApplyingPromotion = false;
61
- /** 最近一次 applyPromotion 的未满足促销提示 */
62
- this.lastUnfulfilledPromotions = [];
63
- /** 最近一次 applyPromotion 的赠品操作 diff(debug / SDK 读取使用) */
64
- this.lastGiftActions = null;
65
52
  }
66
53
  /**
67
54
  * Populate `savedAmount` on each discount based on product-level discount details.
@@ -88,27 +75,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
88
75
  d.savedAmount = d.isSelected && key != null && savedMap.has(key) ? savedMap.get(key).toNumber() : 0;
89
76
  }
90
77
  }
91
- applyProductDiscountPrices(products) {
92
- return (products || []).map((product) => {
93
- var _a, _b, _c;
94
- if ((_a = product.metadata) == null ? void 0 : _a.is_manual_discount)
95
- return product;
96
- const totalPerUnitDiscount = (0, import_utils.resolveEffectivePerUnitDiscount)(product);
97
- const optionSum = (0, import_utils.sumOptionUnitPrice)(product.product_option_item);
98
- const sourcePrice = ((_b = product.metadata) == null ? void 0 : _b.source_product_price) ?? (((_c = product.metadata) == null ? void 0 : _c.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");
99
- const newSourceSellingPrice = new import_decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
100
- const newMainSellingPrice = new import_decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
101
- if (product.metadata) {
102
- product.metadata.main_product_selling_price = newMainSellingPrice;
103
- product.metadata.price_schema_version = 2;
104
- }
105
- product.selling_price = (0, import_utils.composeLinePrice)({
106
- mainPrice: newMainSellingPrice,
107
- bundle: product.product_bundle
108
- });
109
- return product;
110
- });
111
- }
112
78
  async initialize(core, options) {
113
79
  var _a, _b, _c;
114
80
  this.core = core;
@@ -135,6 +101,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
135
101
  this.orderHooks = options.hooks || ((_b = otherParams.order) == null ? void 0 : _b.hooks) || ((_c = otherParams.hooks) == null ? void 0 : _c.order);
136
102
  this.otherParams = otherParams;
137
103
  this.registerDiscountModules(options);
104
+ this.restoreTempOrderFromStorage();
138
105
  this.logInfo("OrderModule initialized successfully");
139
106
  }
140
107
  /**
@@ -207,25 +174,21 @@ var OrderModule = class extends import_BaseModule.BaseModule {
207
174
  }
208
175
  // ─── Discount: 公共 API ───
209
176
  async loadDiscountConfig(params) {
210
- var _a, _b, _c, _d, _e, _f;
211
- const orderId = params.orderId || ((_a = this.store.tempOrder) == null ? void 0 : _a.order_id) || void 0;
212
- const discountList = await ((_b = this.store.discount) == null ? void 0 : _b.loadPrepareConfig({
177
+ var _a, _b, _c, _d;
178
+ const discountList = await ((_a = this.store.discount) == null ? void 0 : _a.loadPrepareConfig({
213
179
  customer_id: params.customerId,
214
- action: params.action || (orderId ? "edit" : "create"),
180
+ action: params.action || "create",
215
181
  with_good_pass: 1,
216
182
  with_discount_card: 1,
217
183
  with_wallet_pass_holder: 1,
218
- request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
219
- ...orderId ? { order_id: orderId } : {}
184
+ request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
220
185
  }));
221
186
  if (discountList) {
222
- await ((_c = this.store.discount) == null ? void 0 : _c.setOriginalDiscountList(discountList));
223
- await ((_d = this.store.discount) == null ? void 0 : _d.setDiscountList(discountList));
187
+ (_b = this.store.discount) == null ? void 0 : _b.setDiscountList(discountList);
224
188
  }
225
- if (params.apply !== false && ((_f = (_e = this.store.tempOrder) == null ? void 0 : _e.products) == null ? void 0 : _f.length)) {
189
+ if ((_d = (_c = this.store.tempOrder) == null ? void 0 : _c.products) == null ? void 0 : _d.length) {
226
190
  this.applyDiscount();
227
191
  }
228
- return this.getDiscountList();
229
192
  }
230
193
  getDiscountList() {
231
194
  var _a;
@@ -233,14 +196,14 @@ var OrderModule = class extends import_BaseModule.BaseModule {
233
196
  }
234
197
  async scanCode(code, customerId) {
235
198
  var _a, _b, _c, _d, _e;
236
- const resultDiscountList = await ((_a = this.store.discount) == null ? void 0 : _a.batchSearch(code, { customerId })) || [];
199
+ const resultDiscountWithReason = await ((_a = this.store.discount) == null ? void 0 : _a.batchSearch(code, { customerId })) || { discountList: [], unavailableReasonKey: null };
200
+ const { discountList: resultDiscountList, unavailableReasonKey } = resultDiscountWithReason;
237
201
  const rulesModule = this.store.rules;
238
202
  if (!rulesModule) {
239
203
  return {
240
204
  type: "clientCalc",
241
205
  isAvailable: false,
242
206
  discountList: this.getDiscountList(),
243
- scannedDiscountList: resultDiscountList,
244
207
  unavailableReason: import_types2.UnavailableReason.Unknown
245
208
  };
246
209
  }
@@ -249,7 +212,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
249
212
  type: "server",
250
213
  isAvailable: false,
251
214
  discountList: this.getDiscountList(),
252
- scannedDiscountList: resultDiscountList
215
+ unavailableReasonKey
253
216
  };
254
217
  }
255
218
  const withScanList = resultDiscountList.map((item) => ({
@@ -261,8 +224,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
261
224
  return {
262
225
  type: "clientCalc",
263
226
  isAvailable: true,
264
- discountList: this.getDiscountList(),
265
- scannedDiscountList: resultDiscountList
227
+ discountList: this.getDiscountList()
266
228
  };
267
229
  }
268
230
  const tempOrder = this.store.tempOrder;
@@ -283,7 +245,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
283
245
  type: "clientCalc",
284
246
  isAvailable: isAvailable || false,
285
247
  discountList: newDiscountList || this.getDiscountList(),
286
- scannedDiscountList: resultDiscountList,
287
248
  unavailableReason
288
249
  };
289
250
  }
@@ -292,7 +253,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
292
253
  const tempOrder = this.store.tempOrder;
293
254
  if (!tempOrder)
294
255
  return;
295
- delete tempOrder.discount_list;
296
256
  const rulesModule = this.store.rules;
297
257
  if (!rulesModule)
298
258
  return;
@@ -306,17 +266,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
306
266
  orderTotalAmount: Number(((_d = this.store.summary) == null ? void 0 : _d.total_amount) || 0)
307
267
  });
308
268
  if (result == null ? void 0 : result.productList) {
309
- tempOrder.products = this.applyProductDiscountPrices(
310
- (result.productList || []).map((product) => ({
311
- ...product,
312
- discount_list: (0, import_utils.normalizeOrderProductDiscountList)(
313
- (0, import_manualProductDiscount.syncManualProductDiscountProductNum)(
314
- product.discount_list,
315
- product.num
316
- )
317
- )
318
- }))
319
- );
269
+ tempOrder.products = result.productList;
320
270
  }
321
271
  if (result == null ? void 0 : result.discountList) {
322
272
  OrderModule.populateSavedAmounts(
@@ -324,178 +274,80 @@ var OrderModule = class extends import_BaseModule.BaseModule {
324
274
  result.discountList
325
275
  );
326
276
  (_e = this.store.discount) == null ? void 0 : _e.setDiscountList(result.discountList);
277
+ tempOrder.discount_list = result.discountList.filter(
278
+ (d) => d.isSelected
279
+ );
327
280
  }
328
281
  }
329
- // ─── 促销/赠品 ──────────────────────────────────────
330
- /**
331
- * 注入促销评估器。
332
- *
333
- * @example
334
- * order.setPromotionEvaluator(appHelper.utils.promotionEvaluator);
335
- */
336
- setPromotionEvaluator(evaluator) {
337
- this.promotionEvaluator = evaluator || null;
338
- }
339
- /**
340
- * 注入赠品选择 resolver。OS 需要补赠品时会 await 调用 resolver;缺省时跳过新增并 console.warn。
341
- *
342
- * @example
343
- * order.setGiftSelectResolver(async (ctx) => {
344
- * // SDK 内部决定弹窗 or 自动选第一项,返回完整 OrderProduct[]
345
- * return giftSelectBridge.request(ctx);
346
- * });
347
- */
348
- setGiftSelectResolver(resolver) {
349
- this.giftSelectResolver = resolver || null;
282
+ // ─── TempOrder: 初始化入口 ───
283
+ initTempOrder(params) {
284
+ if (params.cacheId !== void 0)
285
+ this.cacheId = params.cacheId;
286
+ if (params.salesSummaryModuleName !== void 0)
287
+ this.salesSummaryModuleName = params.salesSummaryModuleName;
288
+ this.restoreTempOrderFromStorage();
350
289
  }
351
- /**
352
- * 为商品目录追加促销标签,供上层 Sales 门面复用。
353
- *
354
- * @example
355
- * const products = order.appendPromotionTags(catalogProducts);
356
- */
357
- appendPromotionTags(products) {
358
- return (0, import_cartPromotion.appendPromotionTags)(products, this.promotionEvaluator);
290
+ // ─── TempOrder: localStorage 持久化 ───
291
+ getTempOrderStorageKey() {
292
+ if (!this.cacheId)
293
+ return null;
294
+ return `scanOrder:tempOrder:${this.cacheId}`;
359
295
  }
360
- /**
361
- * 应用购物车促销:计算 → 差异化赠品 → 写回 tempOrder.products → emit onPromotionApplied。
362
- *
363
- * 调用时机:写路径(add/update/remove/clear/setCustomer)末尾自动触发;外部一般无需手动调。
364
- *
365
- * 关键约束:
366
- * - 不调用任何公开 CRUD API(如 removeProductFromOrder),全部内部 mutate tempOrder.products,避免事件风暴;
367
- * - 用 `isApplyingPromotion` 防递归;
368
- * - 多选项赠品依赖 giftSelectResolver,未注入则跳过且 console.warn;
369
- * - 不主动调用 applyDiscount / recalculateSummary,调用方负责跟进。
370
- */
371
- async applyPromotion() {
372
- if (this.isApplyingPromotion)
296
+ restoreTempOrderFromStorage() {
297
+ var _a, _b;
298
+ const key = this.getTempOrderStorageKey();
299
+ if (!key)
373
300
  return;
374
- if (!this.promotionEvaluator)
301
+ if (!this.window)
375
302
  return;
376
- const tempOrder = this.store.tempOrder;
377
- if (!tempOrder)
303
+ const cachedData = this.window.localStorage.getItem(key);
304
+ if (!cachedData)
378
305
  return;
379
- this.isApplyingPromotion = true;
380
306
  try {
381
- const result = (0, import_cartPromotion.processCartPromotion)(
382
- tempOrder.products,
383
- this.promotionEvaluator
384
- );
385
- if (result.giftActions.toRemove.length > 0) {
386
- const removeSet = new Set(result.giftActions.toRemove.map(String));
387
- result.products = result.products.filter((p) => {
388
- const uid = (0, import_cartPromotion.getOrderProductUid)(p);
389
- return uid ? !removeSet.has(String(uid)) : true;
390
- });
307
+ const parsedData = JSON.parse(cachedData);
308
+ if (!(0, import_utils.isTempOrder)(parsedData)) {
309
+ this.window.localStorage.removeItem(key);
310
+ return;
391
311
  }
392
- for (const reduce of result.giftActions.toReduce) {
393
- for (const item of reduce.items) {
394
- const product = result.products.find(
395
- (p) => (0, import_cartPromotion.getOrderProductUid)(p) === item.uid
396
- );
397
- if (product) {
398
- product.num = item.newQuantity;
312
+ if (Array.isArray(parsedData.products)) {
313
+ for (let i = 0; i < parsedData.products.length; i++) {
314
+ const p = parsedData.products[i];
315
+ if (!p || typeof p !== "object")
316
+ continue;
317
+ if (!Array.isArray(p.product_option_item)) {
318
+ p.product_option_item = [];
399
319
  }
400
- }
401
- }
402
- if (result.giftActions.toAdd.length > 0) {
403
- if (!this.giftSelectResolver) {
404
- if (result.giftActions.toAdd.some((g) => g.giftOptions.length > 1)) {
405
- console.warn(
406
- "[OrderModule] giftSelectResolver not set, skip applying gifts",
407
- result.giftActions.toAdd
408
- );
409
- } else {
410
- console.warn(
411
- "[OrderModule] giftSelectResolver not set, skip applying single-option gifts",
412
- result.giftActions.toAdd
413
- );
414
- }
415
- } else {
416
- for (const addAction of result.giftActions.toAdd) {
417
- if (addAction.giftOptions.length === 1) {
418
- const sameStrategy = result.products.find(
419
- (p) => {
420
- var _a, _b;
421
- return ((_b = (_a = p.metadata) == null ? void 0 : _a._giftInfo) == null ? void 0 : _b.strategyId) === addAction.strategyId;
422
- }
423
- );
424
- if (sameStrategy) {
425
- sameStrategy.num = (Number(sameStrategy.num) || 0) + (addAction.giftCount || 1);
426
- continue;
427
- }
428
- }
429
- try {
430
- const giftProducts = await this.giftSelectResolver({
431
- strategyId: addAction.strategyId,
432
- strategyName: addAction.strategyName,
433
- giftCount: addAction.giftCount,
434
- giftOptions: addAction.giftOptions,
435
- sourceProductIds: addAction.sourceProductIds
436
- });
437
- if (Array.isArray(giftProducts) && giftProducts.length > 0) {
438
- for (const gp of giftProducts) {
439
- if (!gp)
440
- continue;
441
- result.products.push(gp);
442
- }
443
- }
444
- } catch (error) {
445
- console.warn(
446
- "[OrderModule] giftSelectResolver rejected, skip add gift",
447
- addAction.strategyId,
448
- error
449
- );
450
- }
320
+ if (!Array.isArray(p.product_bundle)) {
321
+ p.product_bundle = [];
451
322
  }
323
+ const row = p;
324
+ parsedData.products[i] = (0, import_utils3.normalizeOrderProduct)(row);
452
325
  }
453
326
  }
454
- tempOrder.products = result.products;
455
- this.lastUnfulfilledPromotions = result.unfulfilledPromotions;
456
- this.lastGiftActions = result.giftActions;
457
- const payload = {
458
- unfulfilledPromotions: result.unfulfilledPromotions,
459
- giftActions: result.giftActions,
460
- gifts: result.gifts.map((g) => ({
461
- strategyId: g.strategyId,
462
- strategyName: g.strategyName,
463
- giftCount: g.giftCount,
464
- giftOptions: g.giftOptions
465
- })),
466
- products: tempOrder.products
467
- };
468
- this.effectsEmit("onPromotionApplied", payload);
469
- } catch (error) {
470
- console.error("[OrderModule] applyPromotion failed", error);
471
- } finally {
472
- this.isApplyingPromotion = false;
327
+ const parsedRecord = parsedData;
328
+ this.store.summary = parsedRecord.summary || (0, import_utils.createEmptySummary)();
329
+ delete parsedData.summary;
330
+ if (parsedRecord.lastOrderInfo) {
331
+ this.store.lastOrderInfo = parsedRecord.lastOrderInfo;
332
+ delete parsedData.lastOrderInfo;
333
+ }
334
+ if (!parsedData._extend || typeof parsedData._extend !== "object") {
335
+ parsedData._extend = { productsByUid: {} };
336
+ } else if (!parsedData._extend.productsByUid) {
337
+ parsedData._extend.productsByUid = {};
338
+ }
339
+ this.store.tempOrder = parsedData;
340
+ } catch {
341
+ (_b = (_a = this.window) == null ? void 0 : _a.localStorage) == null ? void 0 : _b.removeItem(key);
473
342
  }
474
343
  }
475
- /** 最近一次 applyPromotion 输出的未满足促销列表 */
476
- getUnfulfilledPromotions() {
477
- return this.lastUnfulfilledPromotions;
478
- }
479
- /** 最近一次 applyPromotion 输出的赠品操作 diff */
480
- getLastGiftActions() {
481
- return this.lastGiftActions;
482
- }
483
- // ─── TempOrder: 初始化入口 ───
484
- initTempOrder(params) {
485
- if (params.cacheId !== void 0)
486
- this.cacheId = params.cacheId;
487
- if (params.salesSummaryModuleName !== void 0)
488
- this.salesSummaryModuleName = params.salesSummaryModuleName;
489
- }
490
- /** @deprecated OrderModule 不再负责 tempOrder localStorage 持久化。 */
491
- setEnableTempOrderPersist(_enabled) {
492
- }
493
- /** @deprecated OrderModule 不再负责 tempOrder localStorage 持久化。 */
494
- isTempOrderPersistEnabled() {
495
- return false;
496
- }
497
- /** @deprecated OrderModule 不再负责 tempOrder localStorage 持久化;草稿保存请使用 IndexedDB saveDraft。 */
498
344
  persistTempOrder() {
345
+ const key = this.getTempOrderStorageKey();
346
+ if (!key || !this.store.tempOrder)
347
+ return;
348
+ if (!this.window)
349
+ return;
350
+ this.window.localStorage.setItem(key, JSON.stringify(this.store.tempOrder));
499
351
  }
500
352
  // ─── TempOrder: 创建 & 获取 ───
501
353
  createDefaultTempOrderInstance() {
@@ -539,14 +391,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
539
391
  }
540
392
  return tempOrder.request_unique_idempotency_token;
541
393
  }
542
- buildPaymentSyncIdempotencyToken(tempOrder, payments) {
543
- const baseToken = this.ensureRequestUniqueIdempotencyToken(tempOrder);
544
- const paidPaymentsCount = (payments || []).filter((payment) => {
545
- return String((payment == null ? void 0 : payment.status) || "").toLowerCase() === "paid";
546
- }).length;
547
- const paidCount = paidPaymentsCount > 0 ? paidPaymentsCount : payments.length;
548
- return `${baseToken}_payment_${paidCount}`;
549
- }
550
394
  hasLocalDatabase() {
551
395
  return !!this.dbManager;
552
396
  }
@@ -649,9 +493,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
649
493
  });
650
494
  }
651
495
  }
652
- saveDraftInBackground() {
653
- void this.saveDraft();
654
- }
655
496
  async hydrateTempOrderFromLocalRecord(record) {
656
497
  return this.hydrateTempOrderFromRecord(record);
657
498
  }
@@ -696,39 +537,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
696
537
  const fixedAmount = new import_decimal.default(serviceCharge.amount || 0);
697
538
  return new import_decimal.default(payment.amount || 0).times(percentage).plus(fixedAmount);
698
539
  }
699
- formatSummaryMetadataMoney(value) {
700
- if (value === void 0 || value === null || value === "")
701
- return void 0;
702
- if (value instanceof import_decimal.default)
703
- return value.toFixed(2);
704
- return new import_decimal.default(String(value || 0)).toFixed(2);
705
- }
706
- syncSummaryProductMetadata(products) {
707
- const moneyKeys = [
708
- "main_product_attached_bundle_surcharge_fee",
709
- "main_product_attached_bundle_tax_fee",
710
- "surcharge_rounding_remainder",
711
- "tax_fee_rounding_remainder"
712
- ];
713
- for (const product of products || []) {
714
- const productRecord = product;
715
- const metadata = productRecord.metadata && typeof productRecord.metadata === "object" ? { ...productRecord.metadata } : {};
716
- let hasMetadataPatch = false;
717
- for (const key of moneyKeys) {
718
- const value = this.formatSummaryMetadataMoney(productRecord[key]);
719
- if (value === void 0)
720
- continue;
721
- metadata[key] = value;
722
- hasMetadataPatch = true;
723
- }
724
- if (Array.isArray(productRecord.relation_surcharge_ids)) {
725
- metadata.relation_surcharge_ids = productRecord.relation_surcharge_ids;
726
- hasMetadataPatch = true;
727
- }
728
- if (hasMetadataPatch)
729
- productRecord.metadata = metadata;
730
- }
731
- }
732
540
  getPaymentTargetAmount() {
733
541
  const tempOrder = this.ensureTempOrder();
734
542
  const summary = this.store.summary || (0, import_utils.createEmptySummary)();
@@ -751,43 +559,17 @@ var OrderModule = class extends import_BaseModule.BaseModule {
751
559
  return newOrder;
752
560
  }
753
561
  restoreOrder() {
754
- var _a, _b;
755
562
  const freshTempOrder = this.createDefaultTempOrderInstance();
756
563
  this.ensureExternalSaleNumber(freshTempOrder);
757
564
  this.store.tempOrder = freshTempOrder;
758
565
  this.store.summary = (0, import_utils.createEmptySummary)();
759
566
  this.store.lastOrderInfo = void 0;
760
- this.store.syncState = void 0;
761
- void ((_a = this.store.discount) == null ? void 0 : _a.setOriginalDiscountList([]));
762
- void ((_b = this.store.discount) == null ? void 0 : _b.setDiscountList([]));
763
567
  this.persistTempOrder();
764
568
  return freshTempOrder;
765
569
  }
766
570
  getTempOrder() {
767
571
  return this.store.tempOrder;
768
572
  }
769
- async replaceTempOrder(tempOrder, options) {
770
- if (!(0, import_utils.isTempOrder)(tempOrder)) {
771
- throw new Error("无效的 tempOrder 数据");
772
- }
773
- const nextTempOrder = this.normalizeTempOrderForRuntime(
774
- (0, import_lodash_es.cloneDeep)(tempOrder),
775
- { ensureIdentity: false }
776
- );
777
- this.store.tempOrder = nextTempOrder;
778
- if ((options == null ? void 0 : options.recalculateSummary) !== false) {
779
- await this.recalculateSummary({ createIfMissing: false });
780
- } else {
781
- this.store.summary = (0, import_utils.createEmptySummary)();
782
- }
783
- if ((options == null ? void 0 : options.persist) !== false) {
784
- this.persistTempOrder();
785
- }
786
- if (options == null ? void 0 : options.saveDraft) {
787
- await this.saveDraft();
788
- }
789
- return nextTempOrder;
790
- }
791
573
  getOrderIdentity() {
792
574
  var _a;
793
575
  const tempOrder = this.store.tempOrder;
@@ -936,33 +718,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
936
718
  }
937
719
  };
938
720
  }
939
- getBookingUniqueIdentificationNumber(booking) {
940
- var _a;
941
- const uid = (_a = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a.unique_identification_number;
942
- if (uid === void 0 || uid === null || uid === "")
943
- return null;
944
- return String(uid);
945
- }
946
- findBookingIndexByUniqueIdentificationNumber(tempOrder, uniqueIdentificationNumber) {
947
- return (tempOrder.bookings || []).findIndex((booking) => {
948
- return this.getBookingUniqueIdentificationNumber(booking) === uniqueIdentificationNumber;
949
- });
950
- }
951
- removeLinkedBookingsForProduct(tempOrder, product) {
952
- var _a, _b;
953
- const productUid = ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a.unique_identification_number) || (product == null ? void 0 : product.unique_identification_number);
954
- const bookingUid = (product == null ? void 0 : product.booking_uid) || ((_b = product == null ? void 0 : product.metadata) == null ? void 0 : _b.booking_uid);
955
- if (!productUid && !bookingUid)
956
- return;
957
- tempOrder.bookings = (tempOrder.bookings || []).filter((booking) => {
958
- const currentBookingUid = this.getBookingUniqueIdentificationNumber(booking);
959
- if (bookingUid && currentBookingUid === String(bookingUid))
960
- return false;
961
- if (productUid && String((booking == null ? void 0 : booking.product_uid) || "") === String(productUid))
962
- return false;
963
- return true;
964
- });
965
- }
966
721
  // ─── TempOrder: 金额汇总 ───
967
722
  getSalesSummary() {
968
723
  if (!this.salesSummaryModuleName)
@@ -995,7 +750,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
995
750
  isPriceIncludeTax: tempOrder.is_price_include_tax,
996
751
  shopDiscount: tempOrder.shop_discount
997
752
  });
998
- this.syncSummaryProductMetadata(tempOrder.products || []);
999
753
  const summary = {
1000
754
  ...salesSummaryResult,
1001
755
  total_refund_amount: existedSummary.total_refund_amount || "0.00",
@@ -1023,22 +777,13 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1023
777
  this.persistTempOrder();
1024
778
  return summary;
1025
779
  }
1026
- updateTempOrderNote(note, sync = false) {
780
+ // ─── TempOrder: 备注 ───
781
+ updateTempOrderNote(note) {
1027
782
  const tempOrder = this.ensureTempOrder();
1028
783
  tempOrder.note = String(note || "");
1029
784
  this.persistTempOrder();
1030
- if (sync) {
1031
- const orderId = tempOrder.order_id;
1032
- if (!orderId)
1033
- return tempOrder.note;
1034
- return this.syncTempOrderNoteToRemote(orderId, tempOrder.note);
1035
- }
1036
785
  return tempOrder.note;
1037
786
  }
1038
- async syncTempOrderNoteToRemote(orderId, note) {
1039
- await this.request.put(`/order/order/${orderId}/note`, { note });
1040
- return note;
1041
- }
1042
787
  getTempOrderNote() {
1043
788
  var _a;
1044
789
  return ((_a = this.store.tempOrder) == null ? void 0 : _a.note) || "";
@@ -1062,29 +807,10 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1062
807
  this.persistTempOrder();
1063
808
  return tempOrder.contacts_info;
1064
809
  }
1065
- buildTempOrderCustomer(params) {
1066
- if (!params.customerId)
1067
- return null;
1068
- const source = params.source ? (0, import_lodash_es.cloneDeep)(params.source) : {};
1069
- const name = source.name ?? source.display_name ?? source.customerName ?? source.customer_name ?? params.customerName;
1070
- const customerName = source.customer_name ?? source.customerName ?? source.display_name ?? source.name ?? params.customerName;
1071
- return {
1072
- ...source,
1073
- id: source.id ?? params.customerId,
1074
- customer_id: source.customer_id ?? params.customerId,
1075
- name: String(name || ""),
1076
- customer_name: String(customerName || ""),
1077
- country_calling_code: String(
1078
- source.country_calling_code ?? source.countryCallingCode ?? params.countryCallingCode
1079
- ),
1080
- phone: String(source.phone ?? params.phone),
1081
- email: String(source.email ?? params.email)
1082
- };
1083
- }
1084
810
  /**
1085
811
  * 更新当前 tempOrder 的客户协议字段。
1086
812
  *
1087
- * PaymentModal 只需要修改订单里的客户事实;如果外部还有客户模块需要同步,
813
+ * PaymentModal 只需要修改订单里的客户字段;如果外部还有客户模块需要同步,
1088
814
  * 应由调用方通过回调处理,不能把外部 UI 状态写进 tempOrder。
1089
815
  */
1090
816
  updateTempOrderCustomer(customer) {
@@ -1098,14 +824,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1098
824
  );
1099
825
  tempOrder.phone = String(customer.phone || "");
1100
826
  tempOrder.email = String(customer.email || "");
1101
- tempOrder.customer = this.buildTempOrderCustomer({
1102
- source: customer,
1103
- customerId: tempOrder.customer_id,
1104
- customerName: tempOrder.customer_name,
1105
- countryCallingCode: tempOrder.country_calling_code,
1106
- phone: tempOrder.phone,
1107
- email: tempOrder.email
1108
- });
1109
827
  this.persistTempOrder();
1110
828
  return {
1111
829
  customerId: tempOrder.customer_id,
@@ -1120,20 +838,11 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1120
838
  return;
1121
839
  }
1122
840
  const tempOrder = this.ensureTempOrder();
1123
- const previousCustomerId = tempOrder.customer_id ?? null;
1124
841
  tempOrder.customer_id = patch.customer_id || patch.id || null;
1125
842
  tempOrder.customer_name = String(patch.customer_name || "");
1126
843
  tempOrder.country_calling_code = String(patch.country_calling_code || "");
1127
844
  tempOrder.phone = String(patch.phone || "");
1128
845
  tempOrder.email = String(patch.email || "");
1129
- tempOrder.customer = this.buildTempOrderCustomer({
1130
- source: snapshot || null,
1131
- customerId: tempOrder.customer_id,
1132
- customerName: tempOrder.customer_name,
1133
- countryCallingCode: tempOrder.country_calling_code,
1134
- phone: tempOrder.phone,
1135
- email: tempOrder.email
1136
- });
1137
846
  if (snapshot !== void 0) {
1138
847
  const extend = this.ensureExtend(tempOrder);
1139
848
  if (snapshot === null)
@@ -1141,17 +850,12 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1141
850
  else
1142
851
  extend.customerSnapshot = (0, import_lodash_es.cloneDeep)(snapshot);
1143
852
  }
1144
- const nextCustomerId = tempOrder.customer_id ?? null;
1145
- if (String(previousCustomerId ?? "") !== String(nextCustomerId ?? "")) {
1146
- (0, import_utils.clearTempOrderHolderAssignments)(tempOrder);
1147
- }
1148
853
  this.persistTempOrder();
1149
- this.saveDraftInBackground();
1150
854
  this.emitOrderCustomerChange();
1151
855
  }
1152
856
  getOrderCustomer() {
1153
857
  const tempOrder = this.store.tempOrder;
1154
- if (!tempOrder || !tempOrder.customer_id) {
858
+ if (!tempOrder || tempOrder.customer_id === null || tempOrder.customer_id === void 0) {
1155
859
  return null;
1156
860
  }
1157
861
  return {
@@ -1169,17 +873,14 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1169
873
  }
1170
874
  clearOrderCustomer() {
1171
875
  const tempOrder = this.ensureTempOrder();
1172
- (0, import_utils.clearTempOrderHolderAssignments)(tempOrder);
1173
876
  tempOrder.customer_id = null;
1174
877
  tempOrder.customer_name = "";
1175
878
  tempOrder.country_calling_code = "";
1176
879
  tempOrder.phone = "";
1177
880
  tempOrder.email = "";
1178
- tempOrder.customer = null;
1179
881
  if (tempOrder._extend)
1180
882
  delete tempOrder._extend.customerSnapshot;
1181
883
  this.persistTempOrder();
1182
- this.saveDraftInBackground();
1183
884
  this.core.effects.emit(import_types.OrderHooks.OnOrderCustomerChange, null);
1184
885
  }
1185
886
  emitOrderCustomerChange() {
@@ -1219,23 +920,10 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1219
920
  }
1220
921
  /** 追加单个支付项,并立即持久化当前 tempOrder。 */
1221
922
  addOrderPayment(payment) {
1222
- this.logInfo("addOrderPayment", {
1223
- payment
1224
- });
1225
923
  const tempOrder = this.ensureTempOrder();
1226
- const paymentRecord = payment;
1227
- const mapped = (0, import_utils.mapPaymentItemsToOrderPayments)([{
1228
- ...paymentRecord,
1229
- status: paymentRecord.status ?? "paid",
1230
- origin_amount: paymentRecord.origin_amount ?? paymentRecord.amount ?? "0.00"
1231
- }]);
924
+ const mapped = (0, import_utils.mapPaymentItemsToOrderPayments)([payment]);
1232
925
  tempOrder.payments = [...tempOrder.payments || [], ...mapped];
1233
926
  this.persistTempOrder();
1234
- void this.recalculateSummary({ createIfMissing: true }).catch((error) => {
1235
- this.logError("recalculate summary after addOrderPayment failed", {
1236
- error: error instanceof Error ? error.message : String(error)
1237
- });
1238
- });
1239
927
  return tempOrder.payments;
1240
928
  }
1241
929
  /**
@@ -1338,9 +1026,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1338
1026
  productToAdd.product_bundle
1339
1027
  );
1340
1028
  const normalizedIncoming = (0, import_utils3.normalizeOrderProduct)(productToAdd);
1341
- normalizedIncoming.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
1342
- normalizedIncoming.discount_list
1343
- );
1344
1029
  const hasIncomingGoodPass = this.hasGoodPassDiscount(
1345
1030
  normalizedIncoming
1346
1031
  );
@@ -1397,9 +1082,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1397
1082
  unique_identification_number: targetUid
1398
1083
  }
1399
1084
  });
1400
- normalizedProduct.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
1401
- normalizedProduct.discount_list
1402
- );
1403
1085
  tempOrder.products[matchedIndex] = {
1404
1086
  ...targetProduct,
1405
1087
  ...normalizedProduct,
@@ -1422,7 +1104,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1422
1104
  if (linked) {
1423
1105
  tempOrder.bookings = [...tempOrder.bookings || [], linked.booking];
1424
1106
  }
1425
- await this.applyPromotion();
1426
1107
  this.applyDiscount();
1427
1108
  await this.recalculateSummary({ createIfMissing: true });
1428
1109
  this.persistTempOrder();
@@ -1446,17 +1127,15 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1446
1127
  (item) => (item == null ? void 0 : item.type) === "good_pass" || (item == null ? void 0 : item.tag) === "good_pass"
1447
1128
  );
1448
1129
  }
1449
- async updateOrderProduct(params) {
1450
- var _a, _b, _c, _d, _e, _f, _g;
1130
+ async updateProductInOrder(params) {
1131
+ var _a, _b, _c, _d, _e;
1451
1132
  const {
1452
1133
  product_id,
1453
1134
  product_variant_id,
1454
1135
  updates,
1455
1136
  unique_identification_number,
1456
- identity_key,
1457
1137
  product_option_item,
1458
- product_bundle,
1459
- booking
1138
+ product_bundle
1460
1139
  } = params;
1461
1140
  const tempOrder = this.ensureTempOrder();
1462
1141
  const identityLookup = {
@@ -1465,30 +1144,12 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1465
1144
  };
1466
1145
  if (unique_identification_number !== void 0) {
1467
1146
  identityLookup.unique_identification_number = unique_identification_number;
1468
- if (identity_key === void 0) {
1469
- identityLookup.identity_key = unique_identification_number;
1470
- }
1471
- }
1472
- if (identity_key !== void 0) {
1473
- identityLookup.identity_key = identity_key;
1474
1147
  }
1475
1148
  if (product_option_item !== void 0)
1476
1149
  identityLookup.product_option_item = product_option_item;
1477
1150
  if (product_bundle !== void 0)
1478
1151
  identityLookup.product_bundle = product_bundle;
1479
- let productIndex = -1;
1480
- if (unique_identification_number !== void 0) {
1481
- const targetUid = String(unique_identification_number);
1482
- productIndex = tempOrder.products.findIndex((item) => {
1483
- var _a2;
1484
- return String(
1485
- ((_a2 = item.metadata) == null ? void 0 : _a2.unique_identification_number) || item.unique_identification_number || ""
1486
- ) === targetUid;
1487
- });
1488
- }
1489
- if (productIndex === -1) {
1490
- productIndex = (0, import_utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
1491
- }
1152
+ const productIndex = (0, import_utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
1492
1153
  if (productIndex === -1) {
1493
1154
  throw new Error("[Order] 目标商品不存在,无法更新");
1494
1155
  }
@@ -1515,178 +1176,28 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1515
1176
  delete nextProduct.metadata.main_product_original_price;
1516
1177
  delete nextProduct.metadata.price_schema_version;
1517
1178
  }
1518
- let normalizedProduct = (0, import_utils3.normalizeOrderProduct)(nextProduct);
1519
- normalizedProduct.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
1520
- normalizedProduct.discount_list
1521
- );
1522
- if (booking) {
1523
- const productUid = String(
1524
- ((_e = normalizedProduct.metadata) == null ? void 0 : _e.unique_identification_number) || ((_f = targetProduct.metadata) == null ? void 0 : _f.unique_identification_number) || unique_identification_number || (0, import_utils.createUuidV4)()
1525
- );
1526
- normalizedProduct.metadata = {
1527
- ...normalizedProduct.metadata || {},
1528
- unique_identification_number: productUid
1529
- };
1530
- const linked = this.createLinkedProductAndBooking({
1531
- product: {
1532
- ...normalizedProduct,
1533
- unique_identification_number: productUid
1534
- },
1535
- booking
1536
- });
1537
- this.removeLinkedBookingsForProduct(tempOrder, targetProduct);
1538
- normalizedProduct = {
1539
- ...normalizedProduct,
1540
- booking_uid: linked.bookingUid,
1541
- metadata: {
1542
- ...normalizedProduct.metadata || {},
1543
- booking_uid: linked.bookingUid,
1544
- unique_identification_number: productUid
1545
- }
1546
- };
1547
- tempOrder.bookings = [...tempOrder.bookings || [], linked.booking];
1548
- }
1549
- tempOrder.products[productIndex] = normalizedProduct;
1179
+ tempOrder.products[productIndex] = (0, import_utils3.normalizeOrderProduct)(nextProduct);
1550
1180
  this.captureProductRuntime(
1551
1181
  tempOrder,
1552
1182
  updates,
1553
1183
  tempOrder.products[productIndex],
1554
- (_g = tempOrder.products[productIndex].metadata) == null ? void 0 : _g.unique_identification_number
1184
+ (_e = tempOrder.products[productIndex].metadata) == null ? void 0 : _e.unique_identification_number
1555
1185
  );
1556
- await this.applyPromotion();
1557
1186
  this.applyDiscount();
1558
1187
  await this.recalculateSummary({ createIfMissing: true });
1559
1188
  this.persistTempOrder();
1560
1189
  return tempOrder.products;
1561
1190
  }
1562
- async updateOrderProductQuantity(params) {
1563
- var _a;
1564
- const {
1565
- product_id,
1566
- product_variant_id,
1567
- num,
1568
- unique_identification_number,
1569
- identity_key,
1570
- product_option_item,
1571
- product_bundle
1572
- } = params;
1573
- const tempOrder = this.ensureTempOrder();
1574
- const identityLookup = {
1575
- product_id,
1576
- product_variant_id
1577
- };
1578
- if (unique_identification_number !== void 0) {
1579
- identityLookup.unique_identification_number = unique_identification_number;
1580
- if (identity_key === void 0) {
1581
- identityLookup.identity_key = unique_identification_number;
1582
- }
1583
- }
1584
- if (identity_key !== void 0)
1585
- identityLookup.identity_key = identity_key;
1586
- if (product_option_item !== void 0)
1587
- identityLookup.product_option_item = product_option_item;
1588
- if (product_bundle !== void 0)
1589
- identityLookup.product_bundle = product_bundle;
1590
- let productIndex = -1;
1591
- if (unique_identification_number !== void 0) {
1592
- const targetUid = String(unique_identification_number);
1593
- productIndex = tempOrder.products.findIndex((item) => {
1594
- var _a2;
1595
- return String(
1596
- ((_a2 = item.metadata) == null ? void 0 : _a2.unique_identification_number) || item.unique_identification_number || ""
1597
- ) === targetUid;
1598
- });
1599
- }
1600
- if (productIndex === -1) {
1601
- productIndex = (0, import_utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
1602
- }
1603
- if (productIndex === -1) {
1604
- throw new Error("[Order] 目标商品不存在,无法更新数量");
1605
- }
1606
- const targetProduct = tempOrder.products[productIndex];
1607
- const normalizedProduct = (0, import_utils3.normalizeOrderProduct)({
1608
- ...targetProduct,
1609
- num: (0, import_utils3.getSafeProductNum)(num),
1610
- metadata: {
1611
- ...targetProduct.metadata || {},
1612
- unique_identification_number: ((_a = targetProduct.metadata) == null ? void 0 : _a.unique_identification_number) || unique_identification_number
1613
- }
1614
- });
1615
- normalizedProduct.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
1616
- normalizedProduct.discount_list
1617
- );
1618
- tempOrder.products[productIndex] = normalizedProduct;
1619
- await this.applyPromotion();
1620
- this.applyDiscount();
1621
- await this.recalculateSummary({ createIfMissing: true });
1622
- this.persistTempOrder();
1623
- return tempOrder.products;
1624
- }
1625
- updateOrderBooking(params) {
1626
- const { unique_identification_number, updates } = params;
1627
- const tempOrder = this.ensureTempOrder();
1628
- const bookingUid = String(unique_identification_number || "");
1629
- const bookingIndex = this.findBookingIndexByUniqueIdentificationNumber(
1630
- tempOrder,
1631
- bookingUid
1632
- );
1633
- if (!bookingUid || bookingIndex === -1) {
1634
- throw new Error("[Order] 目标 booking 不存在,无法更新");
1635
- }
1636
- const targetBooking = tempOrder.bookings[bookingIndex] || {};
1637
- const nextBooking = {
1638
- ...targetBooking,
1639
- ...updates,
1640
- metadata: {
1641
- ...targetBooking.metadata || {},
1642
- ...updates.metadata || {},
1643
- unique_identification_number: bookingUid
1644
- }
1645
- };
1646
- nextBooking.is_all = (0, import_utils.normalizeBookingIsAll)(nextBooking);
1647
- nextBooking.sub_type = (0, import_utils.normalizeBookingSubType)(nextBooking);
1648
- tempOrder.bookings[bookingIndex] = nextBooking;
1649
- this.persistTempOrder();
1650
- return tempOrder.bookings;
1651
- }
1652
1191
  async removeProductFromOrder(identity) {
1653
1192
  const tempOrder = this.ensureTempOrder();
1654
- const removedProducts = [];
1655
- tempOrder.products = tempOrder.products.filter((item) => {
1656
- const shouldRemove = (0, import_utils3.isIdentityMatch)(item, identity);
1657
- if (shouldRemove)
1658
- removedProducts.push(item);
1659
- return !shouldRemove;
1660
- });
1661
- for (const product of removedProducts) {
1662
- this.removeLinkedBookingsForProduct(tempOrder, product);
1663
- }
1664
- await this.applyPromotion();
1193
+ tempOrder.products = tempOrder.products.filter(
1194
+ (item) => !(0, import_utils3.isIdentityMatch)(item, identity)
1195
+ );
1665
1196
  this.applyDiscount();
1666
1197
  await this.recalculateSummary({ createIfMissing: true });
1667
1198
  this.persistTempOrder();
1668
1199
  return tempOrder.products;
1669
1200
  }
1670
- /**
1671
- * 仅清空购物车行(products / bookings),不重置整单。
1672
- * 用于「仅清空商品」;客户、备注、支付等协议字段保持不变。
1673
- */
1674
- async clearOrderCartLines() {
1675
- const tempOrder = this.ensureTempOrder();
1676
- tempOrder.products = [];
1677
- tempOrder.bookings = [];
1678
- if (tempOrder._extend && typeof tempOrder._extend === "object") {
1679
- tempOrder._extend = {
1680
- ...tempOrder._extend,
1681
- productsByUid: {}
1682
- };
1683
- }
1684
- await this.applyPromotion();
1685
- this.applyDiscount();
1686
- await this.recalculateSummary({ createIfMissing: true });
1687
- this.persistTempOrder();
1688
- return tempOrder;
1689
- }
1690
1201
  // ─── TempOrder: 提交 ───
1691
1202
  /**
1692
1203
  * 提交当前 Sales tempOrder。
@@ -1713,8 +1224,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1713
1224
  ...hasPaymentStatusOverride ? { payment_status: params == null ? void 0 : params.paymentStatus } : {},
1714
1225
  ...hasSmallTicketDataFlagOverride ? { small_ticket_data_flag: params == null ? void 0 : params.smallTicketDataFlag } : {}
1715
1226
  };
1716
- const enhancedPayload = (params == null ? void 0 : params.enhancePayload) ? params.enhancePayload(nextPayload, ctx) : nextPayload;
1717
- return enhancedPayload;
1227
+ return (params == null ? void 0 : params.enhancePayload) ? params.enhancePayload(nextPayload, ctx) : nextPayload;
1718
1228
  } : void 0;
1719
1229
  const payload = (0, import_utils.buildSubmitPayload)({
1720
1230
  tempOrder,
@@ -1731,7 +1241,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1731
1241
  this.logInfo("submitTempOrder calling sales checkout", {
1732
1242
  orderId: payload.order_id,
1733
1243
  externalSaleNumber: payload.external_sale_number,
1734
- requestUniqueIdempotencyToken: payload.request_unique_idempotency_token,
1735
1244
  paymentStatus: payload.payment_status,
1736
1245
  paymentsCount: ((_b = payload.payments) == null ? void 0 : _b.length) || 0,
1737
1246
  smallTicketDataFlag: payload.small_ticket_data_flag
@@ -1818,37 +1327,21 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1818
1327
  const mappedPayments = (0, import_utils.mapPaymentItemsToOrderPayments)(
1819
1328
  params.payments || []
1820
1329
  );
1821
- const paymentTotal = this.calculatePaymentTotal(mappedPayments);
1822
- const targetAmount = this.getPaymentTargetAmount();
1823
- const isFullyPaid = targetAmount.lte(0) ? false : paymentTotal.gte(targetAmount);
1824
- const paymentStatus = isFullyPaid ? params.paymentStatus || "paid" : "partially_paid";
1825
1330
  tempOrder.payments = mappedPayments;
1826
- tempOrder.payment_status = paymentStatus;
1331
+ if (params.paymentStatus)
1332
+ tempOrder.payment_status = params.paymentStatus;
1827
1333
  this.persistTempOrder();
1828
1334
  await this.saveDraft();
1829
- if (!params.submitWhenPaid) {
1830
- return { isFullyPaid };
1831
- }
1832
- if (this.store.syncState === "submitting") {
1335
+ const paymentTotal = this.calculatePaymentTotal(mappedPayments);
1336
+ const targetAmount = this.getPaymentTargetAmount();
1337
+ const isFullyPaid = targetAmount.lte(0) ? false : paymentTotal.gte(targetAmount);
1338
+ if (!isFullyPaid || !params.submitWhenPaid) {
1833
1339
  return { isFullyPaid };
1834
1340
  }
1835
- this.store.syncState = "submitting";
1836
- const paymentSyncIdempotencyToken = this.buildPaymentSyncIdempotencyToken(
1837
- tempOrder,
1838
- mappedPayments
1839
- );
1840
1341
  const submitResult = await this.submitTempOrder({
1841
1342
  payments: mappedPayments,
1842
- paymentStatus,
1843
- smallTicketDataFlag: params.smallTicketDataFlag,
1844
- channel: params.channel,
1845
- enhancePayload: (payload) => {
1846
- const nextPayload = {
1847
- ...payload,
1848
- request_unique_idempotency_token: paymentSyncIdempotencyToken
1849
- };
1850
- return nextPayload;
1851
- }
1343
+ paymentStatus: params.paymentStatus || "paid",
1344
+ smallTicketDataFlag: params.smallTicketDataFlag
1852
1345
  });
1853
1346
  return { isFullyPaid, submitResult };
1854
1347
  }
@@ -2148,36 +1641,53 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2148
1641
  */
2149
1642
  async hydrateTempOrderFromRecord(record, options) {
2150
1643
  const raw = record && typeof record === "object" && record.data && record.order_id == null ? record.data : record || {};
2151
- const nextTempOrder = this.normalizeTempOrderForRuntime(raw, {
2152
- ensureIdentity: true
2153
- });
2154
- this.store.tempOrder = nextTempOrder;
2155
- this.store.summary = raw.summary && typeof raw.summary === "object" ? { ...(0, import_utils.createEmptySummary)(), ...raw.summary } : (0, import_utils.createEmptySummary)();
2156
- this.store.lastOrderInfo = raw.lastOrderInfo || raw;
2157
- if (options == null ? void 0 : options.recalcOnHydrate) {
2158
- await this.recalculateSummary({ createIfMissing: false });
2159
- }
2160
- this.persistTempOrder();
2161
- return nextTempOrder;
2162
- }
2163
- normalizeTempOrderForRuntime(raw, options) {
1644
+ const defaults = this.createDefaultTempOrderInstance();
2164
1645
  const nextTempOrder = {
2165
- ...this.createDefaultTempOrderInstance(),
2166
- ...raw || {}
1646
+ ...defaults
2167
1647
  };
2168
- delete nextTempOrder.summary;
2169
- delete nextTempOrder.lastOrderInfo;
2170
- delete nextTempOrder.discount_list;
2171
- delete nextTempOrder.shop_id;
2172
- delete nextTempOrder.create_date;
2173
- delete nextTempOrder.total_amount;
2174
- delete nextTempOrder.expect_amount;
2175
- delete nextTempOrder.paid_amount;
2176
- delete nextTempOrder.shop_note;
2177
- delete nextTempOrder.start_time;
2178
- delete nextTempOrder.tax_fee;
2179
- delete nextTempOrder.total_refund_amount;
2180
- delete nextTempOrder.holder_id;
1648
+ const TEMP_ORDER_KEYS = [
1649
+ "order_id",
1650
+ "external_sale_number",
1651
+ "order_number",
1652
+ "shop_order_number",
1653
+ "shop_full_order_number",
1654
+ "type",
1655
+ "business_code",
1656
+ "platform",
1657
+ "sales_channel",
1658
+ "order_sales_channel",
1659
+ "status",
1660
+ "payment_status",
1661
+ "shipping_status",
1662
+ "customer_id",
1663
+ "customer_name",
1664
+ "country_calling_code",
1665
+ "phone",
1666
+ "email",
1667
+ "customer",
1668
+ "is_price_include_tax",
1669
+ "tax_title",
1670
+ "tax_country_code",
1671
+ "currency_code",
1672
+ "currency_symbol",
1673
+ "currency_format",
1674
+ "is_deposit",
1675
+ "deposit_amount",
1676
+ "shop_discount",
1677
+ "surcharge_fee",
1678
+ "note",
1679
+ "buzzer",
1680
+ "delivery_type",
1681
+ "table_number",
1682
+ "schedule_date",
1683
+ "created_at",
1684
+ "request_unique_idempotency_token"
1685
+ ];
1686
+ TEMP_ORDER_KEYS.forEach((key) => {
1687
+ if (raw[key] !== void 0) {
1688
+ nextTempOrder[key] = raw[key];
1689
+ }
1690
+ });
2181
1691
  nextTempOrder.metadata = raw.metadata && typeof raw.metadata === "object" ? { ...raw.metadata } : {};
2182
1692
  nextTempOrder.holder = raw.holder && typeof raw.holder === "object" ? { ...raw.holder } : null;
2183
1693
  nextTempOrder.products = Array.isArray(raw.products) ? raw.products.map((p) => this.normalizeHydratedOrderProduct(p)) : [];
@@ -2188,6 +1698,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2188
1698
  })) : [];
2189
1699
  nextTempOrder.payments = Array.isArray(raw.payments) ? raw.payments.map((p) => ({ ...p || {} })) : [];
2190
1700
  nextTempOrder.surcharges = Array.isArray(raw.surcharges) ? raw.surcharges.map((s) => ({ ...s || {} })) : [];
1701
+ nextTempOrder.discount_list = Array.isArray(raw.discount_list) ? raw.discount_list.map((d) => ({ ...d || {} })) : [];
2191
1702
  nextTempOrder.relation_forms = Array.isArray(raw.relation_forms) ? raw.relation_forms.map((f) => ({ ...f || {} })) : [];
2192
1703
  nextTempOrder.contacts = Array.isArray(raw.contacts) ? raw.contacts.map((c) => ({ ...c || {} })) : [];
2193
1704
  nextTempOrder.contacts_info = raw.contacts_info && typeof raw.contacts_info === "object" && !Array.isArray(raw.contacts_info) ? { ...raw.contacts_info } : null;
@@ -2195,9 +1706,14 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2195
1706
  ...raw._extend,
2196
1707
  productsByUid: raw._extend.productsByUid || {}
2197
1708
  } : { productsByUid: {} };
2198
- if ((options == null ? void 0 : options.ensureIdentity) !== false) {
2199
- this.ensureExternalSaleNumber(nextTempOrder);
1709
+ this.ensureExternalSaleNumber(nextTempOrder);
1710
+ this.store.tempOrder = nextTempOrder;
1711
+ this.store.summary = raw.summary && typeof raw.summary === "object" ? { ...(0, import_utils.createEmptySummary)(), ...raw.summary } : (0, import_utils.createEmptySummary)();
1712
+ this.store.lastOrderInfo = raw.lastOrderInfo || raw;
1713
+ if (options == null ? void 0 : options.recalcOnHydrate) {
1714
+ await this.recalculateSummary({ createIfMissing: false });
2200
1715
  }
1716
+ this.persistTempOrder();
2201
1717
  return nextTempOrder;
2202
1718
  }
2203
1719
  normalizeHydratedOrderProduct(product) {
@@ -2216,9 +1732,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2216
1732
  row.metadata.unique_identification_number = (0, import_utils.createUuidV4)();
2217
1733
  }
2218
1734
  const normalized = (0, import_utils3.normalizeOrderProduct)(row);
2219
- normalized.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
2220
- normalized.discount_list
2221
- );
2222
1735
  const result = {
2223
1736
  ...row,
2224
1737
  ...normalized,