@pisell/pisellos 0.0.569 → 0.10.2

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 (328) hide show
  1. package/dist/core/index.js +10 -6
  2. package/dist/index.d.ts +0 -1
  3. package/dist/index.js +0 -3
  4. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  5. package/dist/model/strategy/adapter/walletPass/evaluator.js +7 -5
  6. package/dist/model/strategy/adapter/walletPass/example.js +26 -3
  7. package/dist/model/strategy/adapter/walletPass/index.js +5 -5
  8. package/dist/model/strategy/adapter/walletPass/type.d.ts +0 -3
  9. package/dist/model/strategy/adapter/walletPass/utils.d.ts +0 -26
  10. package/dist/model/strategy/adapter/walletPass/utils.js +17 -92
  11. package/dist/model/strategy/strategy-example.js +19 -5
  12. package/dist/modules/BaseModule.d.ts +1 -1
  13. package/dist/modules/BaseModule.js +8 -10
  14. package/dist/modules/Cart/index.js +3 -0
  15. package/dist/modules/Cart/utils/cartProduct.js +1 -0
  16. package/dist/modules/Cart/utils/cartResource.js +0 -2
  17. package/dist/modules/Cart/utils/changePrice.js +9 -16
  18. package/dist/modules/Date/index.js +5 -1
  19. package/dist/modules/Discount/index.d.ts +0 -1
  20. package/dist/modules/Discount/index.js +7 -22
  21. package/dist/modules/Discount/types.d.ts +0 -1
  22. package/dist/modules/OpenData/index.js +2 -0
  23. package/dist/modules/Order/index.js +70 -40
  24. package/dist/modules/Payment/index.js +162 -97
  25. package/dist/modules/Payment/types.d.ts +4 -8
  26. package/dist/modules/Payment/walletpass.d.ts +0 -2
  27. package/dist/modules/Payment/walletpass.js +5 -4
  28. package/dist/modules/ProductList/index.d.ts +1 -1
  29. package/dist/modules/ProductList/index.js +3 -12
  30. package/dist/modules/ProductList/types.d.ts +0 -1
  31. package/dist/modules/Rules/index.js +126 -427
  32. package/dist/modules/SalesSummary/utils.js +1 -2
  33. package/dist/modules/Schedule/getDateIsInSchedule.js +0 -5
  34. package/dist/modules/Schedule/index.js +1 -0
  35. package/dist/modules/Schedule/utils.js +1 -0
  36. package/dist/modules/Step/index.js +1 -0
  37. package/dist/modules/Summary/utils.js +22 -43
  38. package/dist/plugins/request.js +4 -1
  39. package/dist/plugins/window.js +6 -2
  40. package/dist/server/index.js +129 -97
  41. package/dist/server/modules/menu/index.js +41 -32
  42. package/dist/server/modules/order/index.js +4 -2
  43. package/dist/server/modules/products/index.js +42 -24
  44. package/dist/server/modules/quotation/index.js +38 -29
  45. package/dist/server/modules/resource/index.js +4 -3
  46. package/dist/server/modules/schedule/index.js +35 -27
  47. package/dist/server/utils/product.js +1 -0
  48. package/dist/solution/BaseSales/index.js +41 -38
  49. package/dist/solution/BookingByStep/index.d.ts +1 -1
  50. package/dist/solution/BookingByStep/index.js +60 -11
  51. package/dist/solution/BookingByStep/utils/capacity.js +11 -1
  52. package/dist/solution/BookingByStep/utils/resources.js +3 -1
  53. package/dist/solution/BookingByStep/utils/timeslots.js +43 -2
  54. package/dist/solution/BookingTicket/index.d.ts +1 -1
  55. package/dist/solution/BookingTicket/index.js +2 -0
  56. package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +7 -6
  57. package/dist/solution/BookingTicket/utils/scan/handleScan.js +31 -25
  58. package/dist/solution/BookingTicket/utils/scan/index.js +10 -6
  59. package/dist/solution/BuyTickets/index.js +12 -9
  60. package/dist/solution/Checkout/index.js +252 -177
  61. package/dist/solution/Checkout/utils/index.js +16 -4
  62. package/dist/solution/RegisterAndLogin/index.js +76 -30
  63. package/dist/solution/ScanOrder/index.js +60 -50
  64. package/dist/solution/ShopDiscount/index.js +14 -15
  65. package/dist/solution/ShopDiscount/types.d.ts +4 -5
  66. package/dist/solution/ShopDiscount/utils.d.ts +0 -9
  67. package/dist/solution/ShopDiscount/utils.js +0 -9
  68. package/dist/solution/VenueBooking/index.d.ts +3 -31
  69. package/dist/solution/VenueBooking/index.js +496 -651
  70. package/dist/solution/VenueBooking/types.d.ts +1 -3
  71. package/dist/solution/VenueBooking/types.js +0 -1
  72. package/dist/solution/VenueBooking/utils/dateSummary.d.ts +2 -2
  73. package/dist/solution/VenueBooking/utils/dateSummary.js +25 -12
  74. package/dist/solution/VenueBooking/utils/timeSlot.d.ts +0 -2
  75. package/dist/solution/VenueBooking/utils/timeSlot.js +4 -9
  76. package/dist/types/index.d.ts +1 -1
  77. package/dist/utils/task.js +18 -15
  78. package/dist/utils/watch.js +1 -0
  79. package/lib/apis/picoding.js +0 -2
  80. package/lib/core/index.js +132 -130
  81. package/lib/effects/index.js +57 -46
  82. package/lib/index.d.ts +0 -1
  83. package/lib/index.js +50 -92
  84. package/lib/model/index.js +21 -14
  85. package/lib/model/strategy/adapter/dataVariant/adapter.js +50 -38
  86. package/lib/model/strategy/adapter/dataVariant/evaluator.js +236 -162
  87. package/lib/model/strategy/adapter/dataVariant/examples.js +237 -229
  88. package/lib/model/strategy/adapter/dataVariant/index.js +34 -39
  89. package/lib/model/strategy/adapter/dataVariant/type.js +28 -57
  90. package/lib/model/strategy/adapter/index.js +64 -100
  91. package/lib/model/strategy/adapter/itemRule/adapter.js +144 -156
  92. package/lib/model/strategy/adapter/itemRule/evaluator.js +48 -36
  93. package/lib/model/strategy/adapter/itemRule/examples.js +225 -295
  94. package/lib/model/strategy/adapter/itemRule/index.js +57 -83
  95. package/lib/model/strategy/adapter/itemRule/type.js +36 -97
  96. package/lib/model/strategy/adapter/promotion/adapter.js +63 -84
  97. package/lib/model/strategy/adapter/promotion/evaluator.js +231 -381
  98. package/lib/model/strategy/adapter/promotion/examples.js +159 -139
  99. package/lib/model/strategy/adapter/promotion/index.js +49 -1
  100. package/lib/model/strategy/adapter/promotion/type.js +35 -199
  101. package/lib/model/strategy/adapter/type.js +16 -4
  102. package/lib/model/strategy/adapter/walletPass/evaluator.js +152 -180
  103. package/lib/model/strategy/adapter/walletPass/example.js +190 -217
  104. package/lib/model/strategy/adapter/walletPass/index.js +51 -75
  105. package/lib/model/strategy/adapter/walletPass/locales.js +58 -36
  106. package/lib/model/strategy/adapter/walletPass/type.d.ts +0 -3
  107. package/lib/model/strategy/adapter/walletPass/type.js +16 -4
  108. package/lib/model/strategy/adapter/walletPass/utils.d.ts +0 -26
  109. package/lib/model/strategy/adapter/walletPass/utils.js +383 -678
  110. package/lib/model/strategy/engine.js +168 -270
  111. package/lib/model/strategy/index.js +34 -49
  112. package/lib/model/strategy/strategy-example.js +239 -243
  113. package/lib/model/strategy/type.js +40 -100
  114. package/lib/modules/Account/index.js +53 -39
  115. package/lib/modules/Account/types.js +33 -20
  116. package/lib/modules/AccountList/index.js +154 -116
  117. package/lib/modules/AccountList/types.js +31 -30
  118. package/lib/modules/AccountList/utils.js +30 -18
  119. package/lib/modules/BaseModule.d.ts +1 -1
  120. package/lib/modules/BaseModule.js +46 -25
  121. package/lib/modules/BookingContext/index.js +136 -158
  122. package/lib/modules/BookingContext/types.js +32 -46
  123. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +143 -131
  124. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +82 -75
  125. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.js +150 -170
  126. package/lib/modules/BookingContext/utils/flexible.js +55 -38
  127. package/lib/modules/BookingContext/utils/formatResourceList.js +34 -19
  128. package/lib/modules/BookingContext/utils/index.js +41 -124
  129. package/lib/modules/BookingContext/utils/noResource.js +70 -58
  130. package/lib/modules/BookingContext/utils/orderLineDisplay.js +41 -14
  131. package/lib/modules/BookingContext/utils/productExtend.js +155 -202
  132. package/lib/modules/BookingContext/utils/resourceErrors.js +53 -53
  133. package/lib/modules/BookingContext/utils/resourceSelection.js +41 -19
  134. package/lib/modules/BookingContext/utils/resources.js +167 -209
  135. package/lib/modules/BookingContext/utils/serviceTimes.js +116 -115
  136. package/lib/modules/BookingContext/utils/timeSlices.js +80 -70
  137. package/lib/modules/Cart/index.js +124 -170
  138. package/lib/modules/Cart/types.js +51 -46
  139. package/lib/modules/Cart/utils/cartAccount.js +39 -40
  140. package/lib/modules/Cart/utils/cartDate.js +61 -56
  141. package/lib/modules/Cart/utils/cartDiscount.js +33 -28
  142. package/lib/modules/Cart/utils/cartNote.js +32 -27
  143. package/lib/modules/Cart/utils/cartProduct.js +251 -321
  144. package/lib/modules/Cart/utils/cartRelationForms.js +35 -29
  145. package/lib/modules/Cart/utils/cartResource.js +78 -72
  146. package/lib/modules/Cart/utils/changePrice.js +50 -28
  147. package/lib/modules/Cart/utils/index.js +48 -106
  148. package/lib/modules/Customer/constants.js +34 -13
  149. package/lib/modules/Customer/index.js +169 -232
  150. package/lib/modules/Customer/types.js +35 -38
  151. package/lib/modules/Date/index.js +115 -116
  152. package/lib/modules/Date/types.js +28 -16
  153. package/lib/modules/Date/utils.js +123 -174
  154. package/lib/modules/Discount/index.d.ts +0 -1
  155. package/lib/modules/Discount/index.js +128 -130
  156. package/lib/modules/Discount/types.d.ts +0 -1
  157. package/lib/modules/Discount/types.js +31 -9
  158. package/lib/modules/Guests/index.js +56 -30
  159. package/lib/modules/Guests/types.js +33 -23
  160. package/lib/modules/Holder/index.js +189 -209
  161. package/lib/modules/Holder/types.js +16 -4
  162. package/lib/modules/Holder/utils.js +49 -20
  163. package/lib/modules/OpenData/index.js +76 -69
  164. package/lib/modules/OpenData/types.js +16 -4
  165. package/lib/modules/OpenData/utils.js +78 -44
  166. package/lib/modules/Order/index.js +1909 -1572
  167. package/lib/modules/Order/types.js +35 -78
  168. package/lib/modules/Order/utils/bundleDiscountHydration.js +74 -41
  169. package/lib/modules/Order/utils/manualProductDiscount.js +123 -124
  170. package/lib/modules/Order/utils/orderCollectionIdentity.js +210 -148
  171. package/lib/modules/Order/utils.js +634 -799
  172. package/lib/modules/Payment/cash.js +33 -20
  173. package/lib/modules/Payment/cashRecommendationAlgorithm.js +76 -145
  174. package/lib/modules/Payment/eftpos.js +30 -16
  175. package/lib/modules/Payment/index.js +378 -518
  176. package/lib/modules/Payment/mx51.js +0 -1
  177. package/lib/modules/Payment/types.d.ts +4 -8
  178. package/lib/modules/Payment/types.js +107 -216
  179. package/lib/modules/Payment/utils.js +48 -51
  180. package/lib/modules/Payment/walletpass.d.ts +0 -2
  181. package/lib/modules/Payment/walletpass.js +211 -226
  182. package/lib/modules/Product/index.js +46 -51
  183. package/lib/modules/Product/types.js +16 -4
  184. package/lib/modules/Product/utils.js +33 -32
  185. package/lib/modules/ProductList/index.d.ts +1 -1
  186. package/lib/modules/ProductList/index.js +117 -117
  187. package/lib/modules/ProductList/types.d.ts +0 -1
  188. package/lib/modules/ProductList/types.js +31 -9
  189. package/lib/modules/Quotation/index.js +100 -66
  190. package/lib/modules/Quotation/types.js +16 -4
  191. package/lib/modules/Resource/index.js +59 -27
  192. package/lib/modules/Resource/types.js +32 -22
  193. package/lib/modules/Resource/utils.js +38 -30
  194. package/lib/modules/ResourcePlanner/index.js +61 -60
  195. package/lib/modules/ResourcePlanner/planner.js +384 -346
  196. package/lib/modules/ResourcePlanner/types.js +16 -4
  197. package/lib/modules/Rules/index.js +903 -1475
  198. package/lib/modules/Rules/types.js +40 -17
  199. package/lib/modules/SalesSummary/index.js +90 -85
  200. package/lib/modules/SalesSummary/types.js +16 -4
  201. package/lib/modules/SalesSummary/utils.js +427 -351
  202. package/lib/modules/ScanOrderLogger/index.js +79 -59
  203. package/lib/modules/ScanOrderLogger/providers/feishu.js +78 -54
  204. package/lib/modules/ScanOrderLogger/providers/grafana.js +36 -13
  205. package/lib/modules/ScanOrderLogger/types.js +16 -4
  206. package/lib/modules/Schedule/getDateIsInSchedule.js +163 -339
  207. package/lib/modules/Schedule/index.js +114 -100
  208. package/lib/modules/Schedule/type.js +16 -4
  209. package/lib/modules/Schedule/types.js +16 -4
  210. package/lib/modules/Schedule/utils.js +291 -433
  211. package/lib/modules/Step/index.js +52 -40
  212. package/lib/modules/Step/tyeps.js +16 -4
  213. package/lib/modules/Summary/index.js +71 -66
  214. package/lib/modules/Summary/types.js +16 -4
  215. package/lib/modules/Summary/utils.js +418 -791
  216. package/lib/modules/SurchargeList/index.js +60 -46
  217. package/lib/modules/SurchargeList/types.js +16 -4
  218. package/lib/modules/index.js +63 -245
  219. package/lib/plugins/app.js +16 -4
  220. package/lib/plugins/index.js +25 -36
  221. package/lib/plugins/request.js +126 -137
  222. package/lib/plugins/shopStore.js +16 -4
  223. package/lib/plugins/user.js +16 -4
  224. package/lib/plugins/window.js +179 -171
  225. package/lib/server/index.js +2337 -2675
  226. package/lib/server/modules/floor-plan/index.js +123 -102
  227. package/lib/server/modules/floor-plan/types.js +30 -15
  228. package/lib/server/modules/index.js +68 -106
  229. package/lib/server/modules/menu/index.js +122 -146
  230. package/lib/server/modules/menu/types.js +31 -18
  231. package/lib/server/modules/order/index.js +642 -567
  232. package/lib/server/modules/order/types.js +32 -117
  233. package/lib/server/modules/order/utils/filterBookings.js +194 -219
  234. package/lib/server/modules/order/utils/filterOrders.js +92 -118
  235. package/lib/server/modules/payment/index.js +83 -59
  236. package/lib/server/modules/payment/types.js +16 -4
  237. package/lib/server/modules/products/index.js +459 -575
  238. package/lib/server/modules/products/types.js +34 -44
  239. package/lib/server/modules/quotation/index.js +172 -137
  240. package/lib/server/modules/quotation/types.js +31 -21
  241. package/lib/server/modules/resource/index.js +184 -213
  242. package/lib/server/modules/resource/types.js +33 -42
  243. package/lib/server/modules/schedule/index.js +123 -135
  244. package/lib/server/modules/schedule/types.js +21 -14
  245. package/lib/server/modules/schedule/utils.js +163 -334
  246. package/lib/server/types.js +16 -4
  247. package/lib/server/utils/index.js +23 -25
  248. package/lib/server/utils/product.js +139 -196
  249. package/lib/server/utils/schedule.js +41 -34
  250. package/lib/server/utils/small-ticket.js +456 -478
  251. package/lib/server/utils/time.js +49 -40
  252. package/lib/solution/BaseSales/index.js +1016 -850
  253. package/lib/solution/BaseSales/types.js +37 -41
  254. package/lib/solution/BaseSales/utils/cartPromotion.js +460 -611
  255. package/lib/solution/BaseSales/utils/parseSalesResponse.js +105 -85
  256. package/lib/solution/BaseSales/utils/quotationPrice.js +114 -56
  257. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +143 -102
  258. package/lib/solution/BaseSales/utils.js +140 -155
  259. package/lib/solution/BookingByStep/index.d.ts +1 -1
  260. package/lib/solution/BookingByStep/index.js +1340 -1530
  261. package/lib/solution/BookingByStep/types.js +99 -40
  262. package/lib/solution/BookingByStep/utils/capacity.js +160 -192
  263. package/lib/solution/BookingByStep/utils/products.js +52 -42
  264. package/lib/solution/BookingByStep/utils/resources.js +330 -527
  265. package/lib/solution/BookingByStep/utils/stock.js +44 -65
  266. package/lib/solution/BookingByStep/utils/timeslots.js +131 -129
  267. package/lib/solution/BookingTicket/index.d.ts +1 -1
  268. package/lib/solution/BookingTicket/index.js +459 -543
  269. package/lib/solution/BookingTicket/types.js +77 -99
  270. package/lib/solution/BookingTicket/utils/addProductDecision.js +184 -219
  271. package/lib/solution/BookingTicket/utils/addTimeAvailability.js +89 -58
  272. package/lib/solution/BookingTicket/utils/bookingStatus.js +78 -107
  273. package/lib/solution/BookingTicket/utils/cartView.js +94 -110
  274. package/lib/solution/BookingTicket/utils/exampleData.js +0 -185
  275. package/lib/solution/BookingTicket/utils/orderCustomer.js +41 -18
  276. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.js +86 -219
  277. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +93 -144
  278. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +91 -79
  279. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.js +41 -54
  280. package/lib/solution/BookingTicket/utils/scan/handleScan.js +81 -84
  281. package/lib/solution/BookingTicket/utils/scan/index.js +104 -98
  282. package/lib/solution/BookingTicket/utils/scan/scanCache.js +43 -90
  283. package/lib/solution/BookingTicket/utils/scan/scanProductValues.js +64 -52
  284. package/lib/solution/BookingTicket/utils/sessionCatalogStale.js +58 -56
  285. package/lib/solution/BuyTickets/index.js +70 -67
  286. package/lib/solution/BuyTickets/types.js +38 -22
  287. package/lib/solution/Checkout/index.js +1158 -1451
  288. package/lib/solution/Checkout/types.js +61 -91
  289. package/lib/solution/Checkout/utils/index.js +156 -228
  290. package/lib/solution/PlaceOrder/index.js +0 -55
  291. package/lib/solution/RegisterAndLogin/config.js +460 -493
  292. package/lib/solution/RegisterAndLogin/index.js +630 -633
  293. package/lib/solution/RegisterAndLogin/types.js +76 -189
  294. package/lib/solution/RegisterAndLogin/utils.js +125 -183
  295. package/lib/solution/Sales/index.js +320 -317
  296. package/lib/solution/Sales/types.js +33 -27
  297. package/lib/solution/ScanOrder/index.js +862 -831
  298. package/lib/solution/ScanOrder/types.js +34 -33
  299. package/lib/solution/ScanOrder/utils.js +371 -406
  300. package/lib/solution/ShopDiscount/index.js +233 -235
  301. package/lib/solution/ShopDiscount/types.d.ts +4 -5
  302. package/lib/solution/ShopDiscount/types.js +37 -15
  303. package/lib/solution/ShopDiscount/utils.d.ts +0 -9
  304. package/lib/solution/ShopDiscount/utils.js +172 -309
  305. package/lib/solution/UnifiedBookingSales/index.js +405 -379
  306. package/lib/solution/UnifiedBookingSales/types.js +31 -12
  307. package/lib/solution/VenueBooking/index.d.ts +3 -31
  308. package/lib/solution/VenueBooking/index.js +916 -967
  309. package/lib/solution/VenueBooking/types.d.ts +1 -3
  310. package/lib/solution/VenueBooking/types.js +39 -20
  311. package/lib/solution/VenueBooking/utils/dateSummary.d.ts +2 -2
  312. package/lib/solution/VenueBooking/utils/dateSummary.js +62 -25
  313. package/lib/solution/VenueBooking/utils/resource.js +54 -31
  314. package/lib/solution/VenueBooking/utils/slotMerge.js +107 -94
  315. package/lib/solution/VenueBooking/utils/timeSlot.d.ts +0 -2
  316. package/lib/solution/VenueBooking/utils/timeSlot.js +133 -138
  317. package/lib/solution/VenueBooking/utils.js +67 -130
  318. package/lib/solution/index.js +41 -124
  319. package/lib/store/createStore.js +29 -32
  320. package/lib/types/index.d.ts +1 -1
  321. package/lib/types/index.js +16 -4
  322. package/lib/utils/task.js +36 -36
  323. package/lib/utils/watch.js +47 -81
  324. package/package.json +2 -4
  325. package/dist/solution/VenueBooking/utils/smartPricing.d.ts +0 -70
  326. package/dist/solution/VenueBooking/utils/smartPricing.js +0 -233
  327. package/lib/solution/VenueBooking/utils/smartPricing.d.ts +0 -70
  328. package/lib/solution/VenueBooking/utils/smartPricing.js +0 -192
@@ -1,250 +1,312 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- var _exportNames = {
7
- BaseSalesImpl: true
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 });
8
10
  };
9
- exports.BaseSalesImpl = void 0;
10
- var _BaseModule = require("../../modules/BaseModule");
11
- var _types = require("./types");
12
- Object.keys(_types).forEach(function (key) {
13
- if (key === "default" || key === "__esModule") return;
14
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
15
- if (key in exports && exports[key] === _types[key]) return;
16
- Object.defineProperty(exports, key, {
17
- enumerable: true,
18
- get: function () {
19
- return _types[key];
20
- }
21
- });
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/BaseSales/index.ts
31
+ var BaseSales_exports = {};
32
+ __export(BaseSales_exports, {
33
+ BaseSalesImpl: () => BaseSalesImpl
22
34
  });
23
- var _Order = require("../../modules/Order");
24
- var _decimal = _interopRequireDefault(require("decimal.js"));
25
- var _lodashEs = require("lodash-es");
26
- var _types2 = require("../BookingByStep/types");
27
- var _utils = require("../../modules/Order/utils");
28
- var _orderCollectionIdentity = require("../../modules/Order/utils/orderCollectionIdentity");
29
- var _dayjs = _interopRequireDefault(require("dayjs"));
30
- var _Quotation = require("../../modules/Quotation");
31
- var _transformBaseProductToOrderProduct = require("./utils/transformBaseProductToOrderProduct");
32
- var _quotationPrice = require("./utils/quotationPrice");
33
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34
- const SERVER_ORDER_CHANGED_EVENT = 'order:onOrdersChanged';
35
+ module.exports = __toCommonJS(BaseSales_exports);
36
+ var import_BaseModule = require("../../modules/BaseModule");
37
+ var import_types = require("./types");
38
+ var import_Order = require("../../modules/Order");
39
+ var import_decimal = __toESM(require("decimal.js"));
40
+ var import_lodash_es = require("lodash-es");
41
+ var import_types2 = require("../BookingByStep/types");
42
+ var import_utils = require("../../modules/Order/utils");
43
+ var import_orderCollectionIdentity = require("../../modules/Order/utils/orderCollectionIdentity");
44
+ var import_dayjs = __toESM(require("dayjs"));
45
+ __reExport(BaseSales_exports, require("./types"), module.exports);
46
+ var import_Quotation = require("../../modules/Quotation");
47
+ var import_transformBaseProductToOrderProduct = require("./utils/transformBaseProductToOrderProduct");
48
+ var import_quotationPrice = require("./utils/quotationPrice");
49
+ var SERVER_ORDER_CHANGED_EVENT = "order:onOrdersChanged";
35
50
  function isBaseSalesManualProductDiscountProduct(product) {
36
- return product?.metadata?.is_manual_discount === true || product?.metadata?.is_manual_discount === 1 || (product?.discount_list || []).some(item => item?.type === 'product');
51
+ var _a, _b;
52
+ return ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a.is_manual_discount) === true || ((_b = product == null ? void 0 : product.metadata) == null ? void 0 : _b.is_manual_discount) === 1 || ((product == null ? void 0 : product.discount_list) || []).some((item) => (item == null ? void 0 : item.type) === "product");
37
53
  }
38
54
  function getBaseSalesProductUid(product) {
39
- const uid = product?.metadata?.unique_identification_number || product?.unique_identification_number;
40
- if (uid === undefined || uid === null || uid === '') return null;
55
+ var _a;
56
+ const uid = ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a.unique_identification_number) || (product == null ? void 0 : product.unique_identification_number);
57
+ if (uid === void 0 || uid === null || uid === "")
58
+ return null;
41
59
  return String(uid);
42
60
  }
43
61
  function preserveManualProductDiscountProducts(previousProducts, nextProducts) {
44
- const previousByUid = new Map();
62
+ const previousByUid = /* @__PURE__ */ new Map();
45
63
  (previousProducts || []).forEach((product, index) => {
46
64
  const uid = getBaseSalesProductUid(product);
47
- if (uid) previousByUid.set(uid, product);
65
+ if (uid)
66
+ previousByUid.set(uid, product);
48
67
  previousByUid.set(`__index__:${index}`, product);
49
68
  });
50
69
  return (nextProducts || []).map((product, index) => {
51
70
  const uid = getBaseSalesProductUid(product);
52
- const previous = (uid ? previousByUid.get(uid) : undefined) || previousByUid.get(`__index__:${index}`);
71
+ const previous = (uid ? previousByUid.get(uid) : void 0) || previousByUid.get(`__index__:${index}`);
53
72
  return previous && isBaseSalesManualProductDiscountProduct(previous) ? previous : product;
54
73
  });
55
74
  }
56
75
  function isBaseSalesHistoricalDiscountEntry(discount) {
57
- return Boolean(discount?.isEditMode || discount?.isDisabled || discount?.order_discount_id != null);
76
+ return Boolean(
77
+ (discount == null ? void 0 : discount.isEditMode) || (discount == null ? void 0 : discount.isDisabled) || (discount == null ? void 0 : discount.order_discount_id) != null
78
+ );
58
79
  }
59
- const BASE_SALES_PERSISTENT_ID_FIELD_BY_KIND = {
60
- product: 'order_detail_id',
61
- booking: 'schedule_event_id',
62
- payment: 'order_payment_id'
80
+ var BASE_SALES_PERSISTENT_ID_FIELD_BY_KIND = {
81
+ product: "order_detail_id",
82
+ booking: "schedule_event_id",
83
+ payment: "order_payment_id"
63
84
  };
64
85
  function getBaseSalesOrderCollectionKind(key) {
65
- if (key === 'products') return 'product';
66
- if (key === 'bookings') return 'booking';
67
- if (key === 'payments' || key === 'payment') return 'payment';
86
+ if (key === "products")
87
+ return "product";
88
+ if (key === "bookings")
89
+ return "booking";
90
+ if (key === "payments" || key === "payment")
91
+ return "payment";
68
92
  return null;
69
93
  }
70
94
  function isSameBaseSalesOrderRecord(left, right) {
71
- if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false;
72
- const leftIdentities = new Set([left.order_id, left.id, left.external_sale_number, left.order_number].filter(value => value !== undefined && value !== null && value !== '').map(String));
73
- if (leftIdentities.size === 0) return false;
74
- return [right.order_id, right.id, right.external_sale_number, right.order_number].some(value => value !== undefined && value !== null && value !== '' && leftIdentities.has(String(value)));
95
+ if (!left || !right || typeof left !== "object" || typeof right !== "object")
96
+ return false;
97
+ const leftIdentities = new Set(
98
+ [left.order_id, left.id, left.external_sale_number, left.order_number].filter((value) => value !== void 0 && value !== null && value !== "").map(String)
99
+ );
100
+ if (leftIdentities.size === 0)
101
+ return false;
102
+ return [right.order_id, right.id, right.external_sale_number, right.order_number].some(
103
+ (value) => value !== void 0 && value !== null && value !== "" && leftIdentities.has(String(value))
104
+ );
75
105
  }
76
106
  function isBaseSalesBlankValue(value) {
77
- return value === undefined || value === null || value === '';
107
+ return value === void 0 || value === null || value === "";
78
108
  }
79
109
  function mergeBaseSalesProductSnapshotFields(currentItem, loadedItem) {
80
- const mergedItem = (0, _lodashEs.cloneDeep)(loadedItem);
81
- if (isBaseSalesBlankValue(mergedItem.product_cover) && !isBaseSalesBlankValue(currentItem?.product_cover)) {
110
+ var _a, _b, _c;
111
+ const mergedItem = (0, import_lodash_es.cloneDeep)(loadedItem);
112
+ if (isBaseSalesBlankValue(mergedItem.product_cover) && !isBaseSalesBlankValue(currentItem == null ? void 0 : currentItem.product_cover)) {
82
113
  mergedItem.product_cover = currentItem.product_cover;
83
114
  }
84
- const currentHolderConfig = currentItem?.metadata?.holder_config;
85
- if ((mergedItem.metadata?.holder_config === undefined || mergedItem.metadata?.holder_config === null) && currentHolderConfig !== undefined && currentHolderConfig !== null) {
115
+ const currentHolderConfig = (_a = currentItem == null ? void 0 : currentItem.metadata) == null ? void 0 : _a.holder_config;
116
+ if ((((_b = mergedItem.metadata) == null ? void 0 : _b.holder_config) === void 0 || ((_c = mergedItem.metadata) == null ? void 0 : _c.holder_config) === null) && currentHolderConfig !== void 0 && currentHolderConfig !== null) {
86
117
  mergedItem.metadata = {
87
- ...(mergedItem.metadata || {}),
118
+ ...mergedItem.metadata || {},
88
119
  holder_config: currentHolderConfig
89
120
  };
90
121
  }
91
122
  return mergedItem;
92
123
  }
93
124
  function mergeBaseSalesCollectionItem(kind, currentItem, incomingItem, uidRemaps) {
94
- const currentReferenceUid = (0, _orderCollectionIdentity.getOrderCollectionReferenceUid)(kind, currentItem);
95
- const incomingReferenceUid = (0, _orderCollectionIdentity.getOrderCollectionReferenceUid)(kind, incomingItem);
96
- const identityMergedItem = (0, _orderCollectionIdentity.mergeOrderCollectionItems)(kind, currentItem, incomingItem);
97
- const mergedUid = (0, _orderCollectionIdentity.getOrderCollectionUid)(kind, identityMergedItem);
125
+ const currentReferenceUid = (0, import_orderCollectionIdentity.getOrderCollectionReferenceUid)(kind, currentItem);
126
+ const incomingReferenceUid = (0, import_orderCollectionIdentity.getOrderCollectionReferenceUid)(kind, incomingItem);
127
+ const identityMergedItem = (0, import_orderCollectionIdentity.mergeOrderCollectionItems)(
128
+ kind,
129
+ currentItem,
130
+ incomingItem
131
+ );
132
+ const mergedUid = (0, import_orderCollectionIdentity.getOrderCollectionUid)(kind, identityMergedItem);
98
133
  if (mergedUid) {
99
- for (const from of new Set([currentReferenceUid, incomingReferenceUid])) {
100
- if (!from || from === mergedUid) continue;
134
+ for (const from of /* @__PURE__ */ new Set([currentReferenceUid, incomingReferenceUid])) {
135
+ if (!from || from === mergedUid)
136
+ continue;
101
137
  uidRemaps.push({
102
138
  kind,
103
139
  from,
104
140
  to: mergedUid,
105
- persistentId: (0, _orderCollectionIdentity.getOrderCollectionPersistentId)(kind, incomingItem) || (0, _orderCollectionIdentity.getOrderCollectionPersistentId)(kind, currentItem)
141
+ persistentId: (0, import_orderCollectionIdentity.getOrderCollectionPersistentId)(kind, incomingItem) || (0, import_orderCollectionIdentity.getOrderCollectionPersistentId)(kind, currentItem)
106
142
  });
107
143
  }
108
144
  }
109
- const mergedItem = mergedUid ? (0, _orderCollectionIdentity.setOrderCollectionUid)(kind, incomingItem, mergedUid) : (0, _lodashEs.cloneDeep)(incomingItem);
145
+ const mergedItem = mergedUid ? (0, import_orderCollectionIdentity.setOrderCollectionUid)(kind, incomingItem, mergedUid) : (0, import_lodash_es.cloneDeep)(incomingItem);
110
146
  const persistentIdField = BASE_SALES_PERSISTENT_ID_FIELD_BY_KIND[kind];
111
147
  if (isBaseSalesBlankValue(mergedItem[persistentIdField]) && !isBaseSalesBlankValue(identityMergedItem[persistentIdField])) {
112
148
  mergedItem[persistentIdField] = identityMergedItem[persistentIdField];
113
149
  }
114
- return kind === 'product' ? mergeBaseSalesProductSnapshotFields(currentItem, mergedItem) : mergedItem;
150
+ return kind === "product" ? mergeBaseSalesProductSnapshotFields(currentItem, mergedItem) : mergedItem;
115
151
  }
116
152
  function mergeBaseSalesOrderCollection(kind, currentValue, incomingValue, strategy, uidRemaps) {
117
- const currentItems = (0, _orderCollectionIdentity.normalizeOrderCollection)(kind, currentValue, {
153
+ const currentItems = (0, import_orderCollectionIdentity.normalizeOrderCollection)(kind, currentValue, {
118
154
  ensureUid: false
119
155
  }).items;
120
- const incomingItems = (0, _orderCollectionIdentity.normalizeOrderCollection)(kind, incomingValue, {
156
+ const incomingItems = (0, import_orderCollectionIdentity.normalizeOrderCollection)(kind, incomingValue, {
121
157
  ensureUid: false
122
158
  }).items;
123
- if (strategy === 'authoritative-incoming') {
124
- const result = (0, _lodashEs.cloneDeep)(incomingItems);
125
- currentItems.forEach(currentItem => {
126
- const incomingIndex = result.findIndex(incomingItem => (0, _orderCollectionIdentity.isSameOrderCollectionItem)(kind, currentItem, incomingItem));
159
+ if (strategy === "authoritative-incoming") {
160
+ const result2 = (0, import_lodash_es.cloneDeep)(incomingItems);
161
+ currentItems.forEach((currentItem) => {
162
+ const incomingIndex = result2.findIndex(
163
+ (incomingItem) => (0, import_orderCollectionIdentity.isSameOrderCollectionItem)(kind, currentItem, incomingItem)
164
+ );
127
165
  if (incomingIndex !== -1) {
128
- result[incomingIndex] = mergeBaseSalesCollectionItem(kind, currentItem, result[incomingIndex], uidRemaps);
166
+ result2[incomingIndex] = mergeBaseSalesCollectionItem(
167
+ kind,
168
+ currentItem,
169
+ result2[incomingIndex],
170
+ uidRemaps
171
+ );
129
172
  return;
130
173
  }
131
-
132
- // 完整服务端快照负责已落库行;仅保留尚未提交的本地新行。
133
- if (!(0, _orderCollectionIdentity.getOrderCollectionPersistentId)(kind, currentItem)) {
134
- result.push((0, _lodashEs.cloneDeep)(currentItem));
174
+ if (!(0, import_orderCollectionIdentity.getOrderCollectionPersistentId)(kind, currentItem)) {
175
+ result2.push((0, import_lodash_es.cloneDeep)(currentItem));
135
176
  }
136
177
  });
137
- return result;
178
+ return result2;
138
179
  }
139
- const result = (0, _lodashEs.cloneDeep)(currentItems);
140
- incomingItems.forEach(incomingItem => {
141
- const currentIndex = result.findIndex(currentItem => (0, _orderCollectionIdentity.isSameOrderCollectionItem)(kind, currentItem, incomingItem));
180
+ const result = (0, import_lodash_es.cloneDeep)(currentItems);
181
+ incomingItems.forEach((incomingItem) => {
182
+ const currentIndex = result.findIndex(
183
+ (currentItem) => (0, import_orderCollectionIdentity.isSameOrderCollectionItem)(kind, currentItem, incomingItem)
184
+ );
142
185
  if (currentIndex !== -1) {
143
- result[currentIndex] = mergeBaseSalesCollectionItem(kind, result[currentIndex], incomingItem, uidRemaps);
186
+ result[currentIndex] = mergeBaseSalesCollectionItem(
187
+ kind,
188
+ result[currentIndex],
189
+ incomingItem,
190
+ uidRemaps
191
+ );
144
192
  return;
145
193
  }
146
- result.push((0, _lodashEs.cloneDeep)(incomingItem));
194
+ result.push((0, import_lodash_es.cloneDeep)(incomingItem));
147
195
  });
148
196
  return result;
149
197
  }
150
198
  function normalizeBaseSalesRecordCollections(sourceRecord, options) {
151
- const normalizedRecord = (0, _orderCollectionIdentity.normalizeOrderCollections)((0, _lodashEs.cloneDeep)(sourceRecord || {}), options).order;
152
-
153
- // 兼容旧调用方偶尔使用的单数 payment 字段。
199
+ const normalizedRecord = (0, import_orderCollectionIdentity.normalizeOrderCollections)(
200
+ (0, import_lodash_es.cloneDeep)(sourceRecord || {}),
201
+ options
202
+ ).order;
154
203
  if (Array.isArray(normalizedRecord.payment)) {
155
- normalizedRecord.payment = (0, _orderCollectionIdentity.normalizeOrderCollection)('payment', normalizedRecord.payment, options).items;
204
+ normalizedRecord.payment = (0, import_orderCollectionIdentity.normalizeOrderCollection)(
205
+ "payment",
206
+ normalizedRecord.payment,
207
+ options
208
+ ).items;
156
209
  }
157
210
  return normalizedRecord;
158
211
  }
159
212
  function mergeSalesDetailRecordWithTempOrder(currentTempOrder, loadedRecord, strategy) {
160
- const normalizedLoadedRecord = normalizeBaseSalesRecordCollections(loadedRecord || {}, {
161
- ensureUid: false
162
- });
213
+ const normalizedLoadedRecord = normalizeBaseSalesRecordCollections(
214
+ loadedRecord || {},
215
+ { ensureUid: false }
216
+ );
163
217
  if (!currentTempOrder) {
164
218
  return normalizeBaseSalesRecordCollections(normalizedLoadedRecord);
165
219
  }
166
- const normalizedCurrentTempOrder = normalizeBaseSalesRecordCollections(currentTempOrder, {
167
- ensureUid: false
168
- });
220
+ const normalizedCurrentTempOrder = normalizeBaseSalesRecordCollections(
221
+ currentTempOrder,
222
+ { ensureUid: false }
223
+ );
169
224
  const uidRemaps = [];
170
- const mergedRecord = (0, _lodashEs.mergeWith)(normalizedCurrentTempOrder, normalizedLoadedRecord, (currentValue, loadedValue, key) => {
171
- const collectionKind = getBaseSalesOrderCollectionKind(key);
172
- if (collectionKind && Array.isArray(loadedValue)) {
173
- return mergeBaseSalesOrderCollection(collectionKind, Array.isArray(currentValue) ? currentValue : [], loadedValue, strategy, uidRemaps);
174
- }
175
- if (Array.isArray(currentValue) && Array.isArray(loadedValue)) {
176
- return [...(0, _lodashEs.cloneDeep)(currentValue), ...(0, _lodashEs.cloneDeep)(loadedValue)];
177
- }
178
- if (Array.isArray(loadedValue)) return (0, _lodashEs.cloneDeep)(loadedValue);
179
- if (Array.isArray(currentValue) && loadedValue === undefined) {
180
- return (0, _lodashEs.cloneDeep)(currentValue);
225
+ const mergedRecord = (0, import_lodash_es.mergeWith)(
226
+ normalizedCurrentTempOrder,
227
+ normalizedLoadedRecord,
228
+ (currentValue, loadedValue, key) => {
229
+ const collectionKind = getBaseSalesOrderCollectionKind(key);
230
+ if (collectionKind && Array.isArray(loadedValue)) {
231
+ return mergeBaseSalesOrderCollection(
232
+ collectionKind,
233
+ Array.isArray(currentValue) ? currentValue : [],
234
+ loadedValue,
235
+ strategy,
236
+ uidRemaps
237
+ );
238
+ }
239
+ if (Array.isArray(currentValue) && Array.isArray(loadedValue)) {
240
+ return [
241
+ ...(0, import_lodash_es.cloneDeep)(currentValue),
242
+ ...(0, import_lodash_es.cloneDeep)(loadedValue)
243
+ ];
244
+ }
245
+ if (Array.isArray(loadedValue))
246
+ return (0, import_lodash_es.cloneDeep)(loadedValue);
247
+ if (Array.isArray(currentValue) && loadedValue === void 0) {
248
+ return (0, import_lodash_es.cloneDeep)(currentValue);
249
+ }
250
+ return void 0;
181
251
  }
182
- return undefined;
183
- });
252
+ );
184
253
  delete mergedRecord.request_unique_idempotency_token;
185
- return normalizeBaseSalesRecordCollections((0, _orderCollectionIdentity.applyOrderCollectionUidRemaps)(mergedRecord, uidRemaps));
254
+ return normalizeBaseSalesRecordCollections(
255
+ (0, import_orderCollectionIdentity.applyOrderCollectionUidRemaps)(mergedRecord, uidRemaps)
256
+ );
186
257
  }
187
- class BaseSalesImpl extends _BaseModule.BaseModule {
188
- defaultName = 'baseSales';
189
- defaultVersion = '1.0.0';
190
- isSolution = true;
191
- initializeOptions = {};
192
- logger; // LoggerManager 实例
193
- appPlugin;
194
- store = {
195
- order: undefined
196
- };
197
- otherParams = {};
198
- cacheId;
199
- /**
200
- * window / request 暴露为 public:现存外部工具(如 BookingTicket Scan)通过
201
- * `solution.window` / `solution.request` 直接访问插件,保持原有契约不破坏。
202
- */
203
- window;
204
- request;
205
-
206
- // 当前缓存中已加载的最新 SalesDetail;只读 getter 走它对外暴露详情数据。
207
- currentSalesDetail = null;
208
- discountConfigCacheKey = null;
209
- hasManualDiscountSelection = false;
210
- reusedSharedSubModuleNames = new Set();
211
- paymentMethodsCache = [];
212
- queuedAutoPaymentSync = false;
213
- autoPaymentSyncFlushing = false;
214
- autoPaymentSyncTimer = null;
215
- salesDetailLoadInFlightCount = 0;
216
- salesDetailLoadSequence = 0;
217
- salesDetailHydrateQueue = Promise.resolve();
218
- serverOrderChangeUnsubscribe = null;
219
- serverOrderChangeHydrateInFlight = null;
220
- queuedServerOrderChanges = [];
221
- serverOrderChangeSyncEnabled = false;
258
+ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
222
259
  constructor(name, version) {
223
260
  super(name, version);
261
+ this.defaultName = "baseSales";
262
+ this.defaultVersion = "1.0.0";
263
+ this.isSolution = true;
264
+ this.initializeOptions = {};
265
+ this.store = {
266
+ order: void 0
267
+ };
268
+ this.otherParams = {};
269
+ // 当前缓存中已加载的最新 SalesDetail;只读 getter 走它对外暴露详情数据。
270
+ this.currentSalesDetail = null;
271
+ this.discountConfigCacheKey = null;
272
+ this.hasManualDiscountSelection = false;
273
+ this.reusedSharedSubModuleNames = /* @__PURE__ */ new Set();
274
+ this.paymentMethodsCache = [];
275
+ this.queuedAutoPaymentSync = false;
276
+ this.autoPaymentSyncFlushing = false;
277
+ this.autoPaymentSyncTimer = null;
278
+ this.salesDetailLoadInFlightCount = 0;
279
+ this.salesDetailLoadSequence = 0;
280
+ this.salesDetailHydrateQueue = Promise.resolve();
281
+ this.serverOrderChangeUnsubscribe = null;
282
+ this.serverOrderChangeHydrateInFlight = null;
283
+ this.queuedServerOrderChanges = [];
284
+ this.serverOrderChangeSyncEnabled = false;
224
285
  }
225
-
226
286
  /**
227
287
  * 子类可覆盖此方法以追加/收敛要注册的子模块。
228
288
  * 默认包含通用销售模块:products / order / salesSummary / schedule / payment / quotation。
229
289
  */
230
290
  getRegisteredModuleNames() {
231
- return ['products', 'order', 'salesSummary', 'schedule', 'payment', 'quotation'];
291
+ return ["products", "order", "salesSummary", "schedule", "payment", "quotation"];
232
292
  }
233
293
  getReusableSharedSubModule(moduleName) {
234
- if (moduleName !== 'schedule' && moduleName !== 'quotation') return null;
235
- return this.core?.getModule?.(moduleName) || null;
294
+ var _a, _b;
295
+ if (moduleName !== "schedule" && moduleName !== "quotation")
296
+ return null;
297
+ return ((_b = (_a = this.core) == null ? void 0 : _a.getModule) == null ? void 0 : _b.call(_a, moduleName)) || null;
236
298
  }
237
299
  isScheduleListLoaded(scheduleModule) {
238
- if (!scheduleModule) return false;
239
- if (typeof scheduleModule.isScheduleListLoaded === 'function') {
300
+ if (!scheduleModule)
301
+ return false;
302
+ if (typeof scheduleModule.isScheduleListLoaded === "function") {
240
303
  return scheduleModule.isScheduleListLoaded();
241
304
  }
242
- if (typeof scheduleModule.getScheduleList === 'function') {
305
+ if (typeof scheduleModule.getScheduleList === "function") {
243
306
  return Array.isArray(scheduleModule.getScheduleList());
244
307
  }
245
308
  return false;
246
309
  }
247
-
248
310
  /**
249
311
  * 记录信息日志
250
312
  */
@@ -252,13 +314,12 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
252
314
  if (this.logger) {
253
315
  const tempOrder = this.getTempOrder();
254
316
  this.logger.addLog({
255
- type: 'info',
256
- title: `[BaseSales] ${tempOrder?.order_id} ${tempOrder?.external_sale_number} ${title}`,
317
+ type: "info",
318
+ title: `[BaseSales] ${tempOrder == null ? void 0 : tempOrder.order_id} ${tempOrder == null ? void 0 : tempOrder.external_sale_number} ${title}`,
257
319
  metadata: metadata || {}
258
320
  });
259
321
  }
260
322
  }
261
-
262
323
  /**
263
324
  * 记录警告日志
264
325
  */
@@ -266,13 +327,12 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
266
327
  if (this.logger) {
267
328
  const tempOrder = this.getTempOrder();
268
329
  this.logger.addLog({
269
- type: 'warning',
270
- title: `[BaseSales] ${tempOrder?.order_id} ${tempOrder?.external_sale_number} ${title}`,
330
+ type: "warning",
331
+ title: `[BaseSales] ${tempOrder == null ? void 0 : tempOrder.order_id} ${tempOrder == null ? void 0 : tempOrder.external_sale_number} ${title}`,
271
332
  metadata: metadata || {}
272
333
  });
273
334
  }
274
335
  }
275
-
276
336
  /**
277
337
  * 记录错误日志
278
338
  */
@@ -280,24 +340,31 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
280
340
  if (this.logger) {
281
341
  const tempOrder = this.getTempOrder();
282
342
  this.logger.addLog({
283
- type: 'error',
284
- title: `[BaseSales] ${tempOrder?.order_id} ${tempOrder?.external_sale_number} ${title}`,
343
+ type: "error",
344
+ title: `[BaseSales] ${tempOrder == null ? void 0 : tempOrder.order_id} ${tempOrder == null ? void 0 : tempOrder.external_sale_number} ${title}`,
285
345
  metadata: metadata || {}
286
346
  });
287
347
  }
288
348
  }
289
349
  isCurrentSalesOrderRecord(order) {
290
- const currentTempOrder = this.store.order?.getTempOrder?.();
291
- const currentRecords = [currentTempOrder, this.currentSalesDetail].filter(Boolean);
292
- return currentRecords.some(record => isSameBaseSalesOrderRecord(record, order));
350
+ var _a, _b;
351
+ const currentTempOrder = (_b = (_a = this.store.order) == null ? void 0 : _a.getTempOrder) == null ? void 0 : _b.call(_a);
352
+ const currentRecords = [
353
+ currentTempOrder,
354
+ this.currentSalesDetail
355
+ ].filter(Boolean);
356
+ return currentRecords.some((record) => isSameBaseSalesOrderRecord(record, order));
293
357
  }
294
358
  setServerOrderChangeSyncEnabled(enabled) {
295
359
  this.serverOrderChangeSyncEnabled = enabled;
296
- if (!enabled) this.queuedServerOrderChanges = [];
360
+ if (!enabled)
361
+ this.queuedServerOrderChanges = [];
297
362
  }
298
363
  queueLatestServerOrderChange(order) {
299
- const snapshot = (0, _lodashEs.cloneDeep)(order);
300
- const existingIndex = this.queuedServerOrderChanges.findIndex(queued => isSameBaseSalesOrderRecord(queued, snapshot));
364
+ const snapshot = (0, import_lodash_es.cloneDeep)(order);
365
+ const existingIndex = this.queuedServerOrderChanges.findIndex(
366
+ (queued) => isSameBaseSalesOrderRecord(queued, snapshot)
367
+ );
301
368
  if (existingIndex >= 0) {
302
369
  this.queuedServerOrderChanges[existingIndex] = snapshot;
303
370
  return;
@@ -305,40 +372,46 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
305
372
  this.queuedServerOrderChanges.push(snapshot);
306
373
  }
307
374
  async drainQueuedServerOrderChanges() {
308
- if (!this.serverOrderChangeSyncEnabled || this.salesDetailLoadInFlightCount > 0 || this.serverOrderChangeHydrateInFlight || this.queuedServerOrderChanges.length === 0) return;
375
+ if (!this.serverOrderChangeSyncEnabled || this.salesDetailLoadInFlightCount > 0 || this.serverOrderChangeHydrateInFlight || this.queuedServerOrderChanges.length === 0)
376
+ return;
309
377
  const changedOrders = this.queuedServerOrderChanges;
310
378
  this.queuedServerOrderChanges = [];
311
- await this.syncCurrentSalesDetailFromServerOrderChange({
312
- changedOrders
313
- });
379
+ await this.syncCurrentSalesDetailFromServerOrderChange({ changedOrders });
314
380
  }
315
381
  async syncCurrentSalesDetailFromServerOrderChange(payload) {
316
- const changedOrders = Array.isArray(payload) ? payload : Array.isArray(payload?.changedOrders) ? payload.changedOrders : payload?.data && typeof payload.data === 'object' ? [payload.data] : [];
317
- if (!this.serverOrderChangeSyncEnabled) return;
318
-
319
- // 显式详情加载期间 current 可能仍是上一单,先按订单身份 latest-only 缓存;
320
- // load 完成后再用新的 current 过滤,避免恰好到达的最新支付快照丢失。
382
+ const changedOrders = Array.isArray(payload) ? payload : Array.isArray(payload == null ? void 0 : payload.changedOrders) ? payload.changedOrders : (payload == null ? void 0 : payload.data) && typeof payload.data === "object" ? [payload.data] : [];
383
+ if (!this.serverOrderChangeSyncEnabled)
384
+ return;
321
385
  if (this.salesDetailLoadInFlightCount > 0) {
322
- changedOrders.forEach(order => this.queueLatestServerOrderChange(order));
386
+ changedOrders.forEach(
387
+ (order) => this.queueLatestServerOrderChange(order)
388
+ );
323
389
  return;
324
390
  }
325
- const changedOrder = changedOrders.find(order => this.isCurrentSalesOrderRecord(order));
326
- if (!changedOrder) return;
391
+ const changedOrder = changedOrders.find(
392
+ (order) => this.isCurrentSalesOrderRecord(order)
393
+ );
394
+ if (!changedOrder)
395
+ return;
327
396
  if (this.serverOrderChangeHydrateInFlight) {
328
397
  this.queueLatestServerOrderChange(changedOrder);
329
398
  return;
330
399
  }
331
- if (!this.store.order) return;
400
+ if (!this.store.order)
401
+ return;
332
402
  this.serverOrderChangeHydrateInFlight = (async () => {
333
- const currentTempOrder = this.store.order.getTempOrder?.();
334
- const record = mergeSalesDetailRecordWithTempOrder(currentTempOrder, changedOrder, 'authoritative-incoming');
403
+ var _a, _b;
404
+ const currentTempOrder = (_b = (_a = this.store.order).getTempOrder) == null ? void 0 : _b.call(_a);
405
+ const record = mergeSalesDetailRecordWithTempOrder(
406
+ currentTempOrder,
407
+ changedOrder,
408
+ "authoritative-incoming"
409
+ );
335
410
  const sales = await this.store.order.hydrateTempOrderFromRecord(record, {
336
411
  recalcOnHydrate: false
337
412
  });
338
413
  this.currentSalesDetail = sales;
339
- await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, {
340
- sales
341
- });
414
+ await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, { sales });
342
415
  })();
343
416
  try {
344
417
  await this.serverOrderChangeHydrateInFlight;
@@ -348,12 +421,14 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
348
421
  }
349
422
  }
350
423
  registerServerOrderChangeSync() {
351
- this.serverOrderChangeUnsubscribe?.();
352
- const effects = this.core?.effects;
353
- if (!effects || typeof effects.on !== 'function') return;
354
- this.serverOrderChangeUnsubscribe = effects.on(SERVER_ORDER_CHANGED_EVENT, payload => {
355
- return this.syncCurrentSalesDetailFromServerOrderChange(payload).catch(error => {
356
- this.logError('sync sales detail from server order change failed', {
424
+ var _a, _b;
425
+ (_a = this.serverOrderChangeUnsubscribe) == null ? void 0 : _a.call(this);
426
+ const effects = (_b = this.core) == null ? void 0 : _b.effects;
427
+ if (!effects || typeof effects.on !== "function")
428
+ return;
429
+ this.serverOrderChangeUnsubscribe = effects.on(SERVER_ORDER_CHANGED_EVENT, (payload) => {
430
+ return this.syncCurrentSalesDetailFromServerOrderChange(payload).catch((error) => {
431
+ this.logError("sync sales detail from server order change failed", {
357
432
  error: error instanceof Error ? error.message : String(error)
358
433
  });
359
434
  });
@@ -363,54 +438,54 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
363
438
  let hydratedSales = null;
364
439
  let skippedBeforeHydrate = false;
365
440
  const hydrateTask = async () => {
366
- // 网络返回顺序可能倒置;只有当前最新显式加载可以进入共享 tempOrder。
367
441
  if (loadSequence !== this.salesDetailLoadSequence) {
368
442
  skippedBeforeHydrate = true;
369
443
  return;
370
444
  }
371
- if (!this.store.order) throw new Error('order 模块未初始化');
445
+ if (!this.store.order)
446
+ throw new Error("order 模块未初始化");
372
447
  const sales = await this.store.order.hydrateTempOrderFromRecord(record, {
373
448
  recalcOnHydrate: false
374
449
  });
375
450
  hydratedSales = sales;
376
-
377
- // hydrate 期间可能又发起了更新请求;后续任务已串行排队,将负责最终状态。
378
- if (loadSequence !== this.salesDetailLoadSequence) return;
451
+ if (loadSequence !== this.salesDetailLoadSequence)
452
+ return;
379
453
  this.currentSalesDetail = sales;
380
- await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, {
381
- sales
382
- });
454
+ await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, { sales });
383
455
  };
384
456
  const queuedTask = this.salesDetailHydrateQueue.then(hydrateTask, hydrateTask);
385
- this.salesDetailHydrateQueue = queuedTask.then(() => undefined, () => undefined);
457
+ this.salesDetailHydrateQueue = queuedTask.then(
458
+ () => void 0,
459
+ () => void 0
460
+ );
386
461
  await queuedTask;
387
- if (skippedBeforeHydrate) return record;
462
+ if (skippedBeforeHydrate)
463
+ return record;
388
464
  return hydratedSales || this.currentSalesDetail || record;
389
465
  }
390
466
  hydrateOrderPaymentNames(payments) {
391
- if (!payments.length) return [];
467
+ if (!payments.length)
468
+ return [];
392
469
  if (!this.paymentMethodsCache.length) {
393
- return payments.map(payment => ({
394
- ...payment
395
- }));
470
+ return payments.map((payment) => ({ ...payment }));
396
471
  }
397
- const paymentMethodById = new Map();
398
- const paymentMethodByCode = new Map();
399
- this.paymentMethodsCache.forEach(method => {
400
- if (method?.id !== undefined && method?.id !== null) {
472
+ const paymentMethodById = /* @__PURE__ */ new Map();
473
+ const paymentMethodByCode = /* @__PURE__ */ new Map();
474
+ this.paymentMethodsCache.forEach((method) => {
475
+ if ((method == null ? void 0 : method.id) !== void 0 && (method == null ? void 0 : method.id) !== null) {
401
476
  paymentMethodById.set(String(method.id), method);
402
477
  }
403
- if (method?.code) {
478
+ if (method == null ? void 0 : method.code) {
404
479
  paymentMethodByCode.set(String(method.code), method);
405
480
  }
406
481
  });
407
- return payments.map(payment => {
408
- const nextPayment = {
409
- ...payment
410
- };
411
- if (nextPayment.name) return nextPayment;
482
+ return payments.map((payment) => {
483
+ const nextPayment = { ...payment };
484
+ if (nextPayment.name)
485
+ return nextPayment;
412
486
  const paymentMethod = paymentMethodById.get(String(nextPayment.custom_payment_id)) || paymentMethodByCode.get(String(nextPayment.code));
413
- if (!paymentMethod?.name) return nextPayment;
487
+ if (!(paymentMethod == null ? void 0 : paymentMethod.name))
488
+ return nextPayment;
414
489
  return {
415
490
  ...nextPayment,
416
491
  name: paymentMethod.name
@@ -421,103 +496,120 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
421
496
  return this.store.payment;
422
497
  }
423
498
  getCurrentOrderCustomerId() {
424
- const tempOrder = this.store.order?.getTempOrder?.();
425
- const customerId = tempOrder?.customer_id;
426
- if (customerId === null || customerId === undefined) return undefined;
499
+ var _a, _b;
500
+ const tempOrder = (_b = (_a = this.store.order) == null ? void 0 : _a.getTempOrder) == null ? void 0 : _b.call(_a);
501
+ const customerId = tempOrder == null ? void 0 : tempOrder.customer_id;
502
+ if (customerId === null || customerId === void 0)
503
+ return void 0;
427
504
  return customerId;
428
505
  }
429
506
  normalizePriceContextCustomerId(customerId) {
430
- if (customerId === undefined || customerId === null || customerId === '') return null;
507
+ if (customerId === void 0 || customerId === null || customerId === "")
508
+ return null;
431
509
  return String(customerId);
432
510
  }
433
511
  applyQuotationScheduleResolver(quotation) {
434
512
  const scheduleModule = this.store.schedule;
435
- if (!scheduleModule) return;
436
- const scheduleById = new Map();
437
- const scheduleList = typeof scheduleModule.getScheduleList === 'function' ? scheduleModule.getScheduleList() : [];
513
+ if (!scheduleModule)
514
+ return;
515
+ const scheduleById = /* @__PURE__ */ new Map();
516
+ const scheduleList = typeof scheduleModule.getScheduleList === "function" ? scheduleModule.getScheduleList() : [];
438
517
  if (Array.isArray(scheduleList)) {
439
- scheduleList.forEach(schedule => {
440
- if (schedule?.id !== undefined && schedule?.id !== null) {
518
+ scheduleList.forEach((schedule) => {
519
+ if ((schedule == null ? void 0 : schedule.id) !== void 0 && (schedule == null ? void 0 : schedule.id) !== null) {
441
520
  scheduleById.set(String(schedule.id), schedule);
442
521
  }
443
522
  });
444
523
  }
445
- quotation.setScheduleResolver(id => {
524
+ quotation.setScheduleResolver((id) => {
525
+ var _a, _b;
446
526
  const scheduleId = String(id);
447
- if (scheduleById.has(scheduleId)) return scheduleById.get(scheduleId);
448
- const schedules = scheduleModule.getScheduleListByIds?.([id]) || scheduleModule.getScheduleByIds?.([id]) || [];
449
- if (schedules[0]) scheduleById.set(scheduleId, schedules[0]);
527
+ if (scheduleById.has(scheduleId))
528
+ return scheduleById.get(scheduleId);
529
+ const schedules = ((_a = scheduleModule.getScheduleListByIds) == null ? void 0 : _a.call(scheduleModule, [id])) || ((_b = scheduleModule.getScheduleByIds) == null ? void 0 : _b.call(scheduleModule, [id])) || [];
530
+ if (schedules[0])
531
+ scheduleById.set(scheduleId, schedules[0]);
450
532
  return schedules[0];
451
533
  });
452
534
  }
453
535
  async loadQuotationForPriceQuery(params) {
454
- if (!params.quotation) return;
536
+ var _a;
537
+ if (!params.quotation)
538
+ return;
455
539
  this.applyQuotationScheduleResolver(params.quotation);
456
540
  await params.quotation.loadQuotations({
457
- channel: params.channel || this.otherParams?.channel,
541
+ channel: params.channel || ((_a = this.otherParams) == null ? void 0 : _a.channel),
458
542
  customer_id: params.customer_id
459
543
  });
460
544
  }
461
545
  getPriceQueryProductId(product) {
462
- const productId = Number(product?.product_id ?? product?.id);
463
- if (!Number.isFinite(productId)) return null;
546
+ const productId = Number((product == null ? void 0 : product.product_id) ?? (product == null ? void 0 : product.id));
547
+ if (!Number.isFinite(productId))
548
+ return null;
464
549
  return productId;
465
550
  }
466
551
  getPriceQuerySchedule(params) {
467
552
  const booking = params.booking || {};
468
- if (typeof booking.start_date === 'string' && booking.start_date.trim()) {
553
+ if (typeof booking.start_date === "string" && booking.start_date.trim()) {
469
554
  const scheduleDate = booking.start_date.trim();
470
- const startTime = typeof booking.start_time === 'string' && booking.start_time.trim() ? booking.start_time.trim() : '00:00:00';
471
- const datetime = (0, _dayjs.default)(`${scheduleDate} ${startTime}`);
555
+ const startTime = typeof booking.start_time === "string" && booking.start_time.trim() ? booking.start_time.trim() : "00:00:00";
556
+ const datetime = (0, import_dayjs.default)(`${scheduleDate} ${startTime}`);
472
557
  return {
473
558
  schedule_date: scheduleDate,
474
- schedule_datetime: datetime.isValid() ? datetime.format('YYYY-MM-DD HH:mm:ss') : `${scheduleDate} ${startTime}`
559
+ schedule_datetime: datetime.isValid() ? datetime.format("YYYY-MM-DD HH:mm:ss") : `${scheduleDate} ${startTime}`
475
560
  };
476
561
  }
477
- if (typeof params.datetime === 'string' && params.datetime.trim()) {
478
- const datetime = (0, _dayjs.default)(params.datetime.trim());
562
+ if (typeof params.datetime === "string" && params.datetime.trim()) {
563
+ const datetime = (0, import_dayjs.default)(params.datetime.trim());
479
564
  if (datetime.isValid()) {
480
565
  return {
481
- schedule_date: datetime.format('YYYY-MM-DD'),
482
- schedule_datetime: datetime.format('YYYY-MM-DD HH:mm:ss')
566
+ schedule_date: datetime.format("YYYY-MM-DD"),
567
+ schedule_datetime: datetime.format("YYYY-MM-DD HH:mm:ss")
483
568
  };
484
569
  }
485
570
  }
486
- const now = (0, _dayjs.default)();
571
+ const now = (0, import_dayjs.default)();
487
572
  return {
488
- schedule_date: now.format('YYYY-MM-DD'),
489
- schedule_datetime: now.format('YYYY-MM-DD HH:mm:ss')
573
+ schedule_date: now.format("YYYY-MM-DD"),
574
+ schedule_datetime: now.format("YYYY-MM-DD HH:mm:ss")
490
575
  };
491
576
  }
492
577
  async loadProductsForPriceQuery(params) {
493
- const ids = Array.from(new Set(params.ids.filter(id => Number.isFinite(id))));
494
- const productsById = new Map();
495
- if (!ids.length || !this.request) return productsById;
578
+ var _a, _b;
579
+ const ids = Array.from(new Set(
580
+ params.ids.filter((id) => Number.isFinite(id))
581
+ ));
582
+ const productsById = /* @__PURE__ */ new Map();
583
+ if (!ids.length || !this.request)
584
+ return productsById;
496
585
  try {
497
- const response = await this.request.post('/product/query', {
586
+ const response = await this.request.post("/product/query", {
498
587
  ids,
499
588
  open_quotation: 1,
500
589
  open_bundle: 1,
501
- status: 'published',
590
+ status: "published",
502
591
  num: 1,
503
592
  skip: 1,
504
593
  customer_id: params.customerId,
505
594
  schedule_date: params.schedule.schedule_date,
506
595
  schedule_datetime: params.schedule.schedule_datetime,
507
- application_code: params.channel || this.otherParams?.channel
596
+ application_code: params.channel || ((_a = this.otherParams) == null ? void 0 : _a.channel)
508
597
  }, {
509
598
  osServer: true,
510
- customToast: () => {}
599
+ customToast: () => {
600
+ }
511
601
  });
512
- const list = response?.data?.list || response?.list || [];
513
- if (!Array.isArray(list)) return productsById;
514
- list.forEach(item => {
515
- const productId = Number(item?.id ?? item?.product_id);
516
- if (Number.isFinite(productId)) productsById.set(productId, item);
602
+ const list = ((_b = response == null ? void 0 : response.data) == null ? void 0 : _b.list) || (response == null ? void 0 : response.list) || [];
603
+ if (!Array.isArray(list))
604
+ return productsById;
605
+ list.forEach((item) => {
606
+ const productId = Number((item == null ? void 0 : item.id) ?? (item == null ? void 0 : item.product_id));
607
+ if (Number.isFinite(productId))
608
+ productsById.set(productId, item);
517
609
  });
518
610
  return productsById;
519
611
  } catch (error) {
520
- this.logWarning('loadProductsForPriceQuery: 商品批量重查失败,使用入参 fallback', {
612
+ this.logWarning("loadProductsForPriceQuery: 商品批量重查失败,使用入参 fallback", {
521
613
  ids,
522
614
  error: error instanceof Error ? error.message : String(error)
523
615
  });
@@ -527,7 +619,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
527
619
  async loadProductForPriceQuery(params, customerId) {
528
620
  const product = params.product || {};
529
621
  const productId = this.getPriceQueryProductId(product);
530
- if (productId === null || !this.request) return null;
622
+ if (productId === null || !this.request)
623
+ return null;
531
624
  const schedule = this.getPriceQuerySchedule(params);
532
625
  const productsById = await this.loadProductsForPriceQuery({
533
626
  ids: [productId],
@@ -538,30 +631,34 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
538
631
  return productsById.get(productId) || null;
539
632
  }
540
633
  getAuthoritativeBundleItems(product) {
541
- if (Array.isArray(product?.product_bundle)) return product.product_bundle;
542
- const groups = Array.isArray(product?.bundle_group) ? product.bundle_group : Array.isArray(product?.bundleGroup) ? product.bundleGroup : [];
543
- return groups.flatMap(group => {
544
- const items = Array.isArray(group?.bundle_item) ? group.bundle_item : Array.isArray(group?.bundleItem) ? group.bundleItem : [];
545
- return items.map(item => ({
634
+ if (Array.isArray(product == null ? void 0 : product.product_bundle))
635
+ return product.product_bundle;
636
+ const groups = Array.isArray(product == null ? void 0 : product.bundle_group) ? product.bundle_group : Array.isArray(product == null ? void 0 : product.bundleGroup) ? product.bundleGroup : [];
637
+ return groups.flatMap((group) => {
638
+ const items = Array.isArray(group == null ? void 0 : group.bundle_item) ? group.bundle_item : Array.isArray(group == null ? void 0 : group.bundleItem) ? group.bundleItem : [];
639
+ return items.map((item) => ({
546
640
  ...item,
547
- group_id: item?.group_id ?? group?.id,
548
- bundle_group_id: item?.bundle_group_id ?? item?.group_id ?? group?.id
641
+ group_id: (item == null ? void 0 : item.group_id) ?? (group == null ? void 0 : group.id),
642
+ bundle_group_id: (item == null ? void 0 : item.bundle_group_id) ?? (item == null ? void 0 : item.group_id) ?? (group == null ? void 0 : group.id)
549
643
  }));
550
644
  });
551
645
  }
552
646
  findAuthoritativeBundleItem(bundle, candidates) {
553
647
  const bundleId = bundle.bundle_id ?? bundle.id;
554
648
  if (bundleId != null) {
555
- const matchedById = candidates.find(item => String(item?.bundle_id ?? item?.id) === String(bundleId));
556
- if (matchedById) return matchedById;
649
+ const matchedById = candidates.find((item) => String((item == null ? void 0 : item.bundle_id) ?? (item == null ? void 0 : item.id)) === String(bundleId));
650
+ if (matchedById)
651
+ return matchedById;
557
652
  }
558
653
  const productId = bundle.bundle_product_id ?? bundle._bundle_product_id;
559
654
  const groupId = bundle.bundle_group_id ?? bundle.group_id;
560
- return candidates.find(item => {
561
- const itemProductId = item?.bundle_product_id ?? item?._bundle_product_id;
562
- const itemGroupId = item?.bundle_group_id ?? item?.group_id;
563
- if (productId == null || String(itemProductId) !== String(productId)) return false;
564
- if (groupId == null) return true;
655
+ return candidates.find((item) => {
656
+ const itemProductId = (item == null ? void 0 : item.bundle_product_id) ?? (item == null ? void 0 : item._bundle_product_id);
657
+ const itemGroupId = (item == null ? void 0 : item.bundle_group_id) ?? (item == null ? void 0 : item.group_id);
658
+ if (productId == null || String(itemProductId) !== String(productId))
659
+ return false;
660
+ if (groupId == null)
661
+ return true;
565
662
  return String(itemGroupId) === String(groupId);
566
663
  }) || null;
567
664
  }
@@ -569,19 +666,21 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
569
666
  return bundle.price ?? bundle.bundle_selling_price ?? bundle.custom_price ?? bundle.product_price ?? bundle.base_price;
570
667
  }
571
668
  mergeProductForPriceQuery(product, authoritativeProduct) {
572
- if (!authoritativeProduct) return product;
669
+ if (!authoritativeProduct)
670
+ return product;
573
671
  const selectedBundles = Array.isArray(product.product_bundle) ? product.product_bundle : [];
574
672
  const authoritativeBundles = this.getAuthoritativeBundleItems(authoritativeProduct);
575
- const productBundle = selectedBundles.map(bundle => {
673
+ const productBundle = selectedBundles.map((bundle) => {
576
674
  const authoritativeBundle = this.findAuthoritativeBundleItem(bundle, authoritativeBundles);
577
- const unitPrice = authoritativeBundle ? this.getAuthoritativeBundleUnitPrice(authoritativeBundle) : undefined;
578
- if (unitPrice === undefined || unitPrice === null || unitPrice === '') return bundle;
675
+ const unitPrice = authoritativeBundle ? this.getAuthoritativeBundleUnitPrice(authoritativeBundle) : void 0;
676
+ if (unitPrice === void 0 || unitPrice === null || unitPrice === "")
677
+ return bundle;
579
678
  return {
580
679
  ...bundle,
581
680
  price: unitPrice,
582
681
  bundle_selling_price: unitPrice,
583
- base_price: authoritativeBundle?.base_price ?? bundle.base_price,
584
- product_price: authoritativeBundle?.product_price ?? bundle.product_price
682
+ base_price: (authoritativeBundle == null ? void 0 : authoritativeBundle.base_price) ?? bundle.base_price,
683
+ product_price: (authoritativeBundle == null ? void 0 : authoritativeBundle.product_price) ?? bundle.product_price
585
684
  };
586
685
  });
587
686
  return {
@@ -593,9 +692,9 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
593
692
  num: product.num ?? product.quantity ?? authoritativeProduct.num,
594
693
  quantity: product.quantity ?? product.num ?? authoritativeProduct.quantity,
595
694
  product_sku: (() => {
596
- const authoritativeSku = (0, _utils.ensureProductSku)(authoritativeProduct);
597
- const productSku = (0, _utils.ensureProductSku)(product);
598
- const hasProductSku = product.product_sku && typeof product.product_sku === 'object';
695
+ const authoritativeSku = (0, import_utils.ensureProductSku)(authoritativeProduct);
696
+ const productSku = (0, import_utils.ensureProductSku)(product);
697
+ const hasProductSku = product.product_sku && typeof product.product_sku === "object";
599
698
  return {
600
699
  ...authoritativeSku,
601
700
  ...productSku,
@@ -607,30 +706,30 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
607
706
  };
608
707
  }
609
708
  getSubmitOrderSalesChannel() {
610
- return this.otherParams?.channel;
709
+ var _a;
710
+ return (_a = this.otherParams) == null ? void 0 : _a.channel;
611
711
  }
612
-
613
712
  /**
614
713
  * 工厂入口:根据子模块名实例化对应模块。
615
714
  * 默认使用 BookingByStep 公共 `createModule`。子类若需引入额外类型(如 customer),
616
715
  * 可覆盖此方法并把未识别的 name 委托给 `super.createSubModule(name)`。
617
716
  */
618
717
  createSubModule(moduleName) {
619
- if (moduleName === 'quotation') {
620
- return new _Quotation.QuotationModule(`${this.name}_quotation`);
718
+ if (moduleName === "quotation") {
719
+ return new import_Quotation.QuotationModule(`${this.name}_quotation`);
621
720
  }
622
- return (0, _types2.createModule)(moduleName, this.name);
721
+ return (0, import_types2.createModule)(moduleName, this.name);
623
722
  }
624
723
  getSubModuleHooks(moduleName) {
724
+ var _a, _b;
625
725
  const optionHooks = this.initializeOptions.hooks || {};
626
726
  const otherHooks = this.otherParams.hooks || {};
627
- if (moduleName === 'order') {
727
+ if (moduleName === "order") {
628
728
  const directOrderHooks = optionHooks;
629
- return optionHooks.order || this.otherParams.order?.hooks || otherHooks.order || (directOrderHooks.onBeforeMergeProductToOrder ? directOrderHooks : undefined);
729
+ return optionHooks.order || ((_a = this.otherParams.order) == null ? void 0 : _a.hooks) || otherHooks.order || (directOrderHooks.onBeforeMergeProductToOrder ? directOrderHooks : void 0);
630
730
  }
631
- return optionHooks[moduleName] || this.otherParams[moduleName]?.hooks || otherHooks[moduleName];
731
+ return optionHooks[moduleName] || ((_b = this.otherParams[moduleName]) == null ? void 0 : _b.hooks) || otherHooks[moduleName];
632
732
  }
633
-
634
733
  /**
635
734
  * 构造传给 BaseSales 子模块的完整运行态参数,保证初始化和后续同步语义一致。
636
735
  *
@@ -647,41 +746,41 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
647
746
  cacheId: this.cacheId
648
747
  };
649
748
  }
650
-
651
749
  /**
652
750
  * 将父级 otherParams 的变更显式同步给已注册的子模块。
653
751
  *
654
752
  * @example
655
753
  * await this.syncOtherParamsToSubModules({ channel: 'pos' });
656
754
  */
657
- async syncOtherParamsToSubModules(changedParams, {
658
- cover = false
659
- } = {}) {
755
+ async syncOtherParamsToSubModules(changedParams, { cover = false } = {}) {
660
756
  const nextSubModuleOtherParams = this.buildSubModuleOtherParams();
661
- await Promise.all(Object.entries(this.store).map(async ([moduleName, subModule]) => {
662
- if (this.reusedSharedSubModuleNames.has(moduleName)) {
663
- return;
664
- }
665
- const targetModule = subModule;
666
- if (!targetModule || typeof targetModule.updateOtherParams !== 'function') {
667
- return;
668
- }
669
- await targetModule.updateOtherParams(nextSubModuleOtherParams, {
670
- changedParams,
671
- cover
672
- });
673
- }));
757
+ await Promise.all(
758
+ Object.entries(this.store).map(async ([moduleName, subModule]) => {
759
+ if (this.reusedSharedSubModuleNames.has(moduleName)) {
760
+ return;
761
+ }
762
+ const targetModule = subModule;
763
+ if (!targetModule || typeof targetModule.updateOtherParams !== "function") {
764
+ return;
765
+ }
766
+ await targetModule.updateOtherParams(nextSubModuleOtherParams, {
767
+ changedParams,
768
+ cover
769
+ });
770
+ })
771
+ );
674
772
  }
675
-
676
773
  /**
677
774
  * 读取 sessionStorage[this.name][cacheId],作为子模块 initialState 的来源。
678
775
  * sessionStorage 损坏时静默忽略,按空状态注册。
679
776
  */
680
777
  readSessionCacheData() {
681
- if (!this.cacheId || !this.window) return {};
778
+ if (!this.cacheId || !this.window)
779
+ return {};
682
780
  try {
683
781
  const sessionData = this.window.sessionStorage.getItem(this.name);
684
- if (!sessionData) return {};
782
+ if (!sessionData)
783
+ return {};
685
784
  const data = JSON.parse(sessionData);
686
785
  return data && data[this.cacheId] || {};
687
786
  } catch {
@@ -689,41 +788,43 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
689
788
  }
690
789
  }
691
790
  getAppData(key) {
692
- const getData = this.appPlugin.getData?.();
693
- if (typeof getData === 'function') return getData(key);
791
+ var _a, _b, _c, _d, _e, _f;
792
+ const getData = (_b = (_a = this.appPlugin).getData) == null ? void 0 : _b.call(_a);
793
+ if (typeof getData === "function")
794
+ return getData(key);
694
795
  const app = this.appPlugin.getApp();
695
- const coreData = app?.models?.getStore?.().getDataByModel?.('core', 'core');
696
- return coreData?.[key];
796
+ const coreData = (_f = (_d = (_c = app == null ? void 0 : app.models) == null ? void 0 : _c.getStore) == null ? void 0 : (_e = _d.call(_c)).getDataByModel) == null ? void 0 : _f.call(_e, "core", "core");
797
+ return coreData == null ? void 0 : coreData[key];
697
798
  }
698
799
  syncAppDataToTempOrder(tempOrder) {
699
- const isPriceIncludeTax = this.getAppData('is_price_include_tax');
700
- const taxCountryCode = this.getAppData('tax_country_code');
701
- const currencyCode = this.getAppData('shop_currency_code');
702
- const currencySymbol = this.getAppData('shop_symbol');
800
+ const isPriceIncludeTax = this.getAppData("is_price_include_tax");
801
+ const taxCountryCode = this.getAppData("tax_country_code");
802
+ const currencyCode = this.getAppData("shop_currency_code");
803
+ const currencySymbol = this.getAppData("shop_symbol");
703
804
  let isChanged = false;
704
- if (isPriceIncludeTax !== undefined) {
805
+ if (isPriceIncludeTax !== void 0) {
705
806
  const nextIsPriceIncludeTax = Number(isPriceIncludeTax);
706
807
  if ((nextIsPriceIncludeTax === 0 || nextIsPriceIncludeTax === 1) && tempOrder.is_price_include_tax !== nextIsPriceIncludeTax) {
707
808
  tempOrder.is_price_include_tax = nextIsPriceIncludeTax;
708
809
  isChanged = true;
709
810
  }
710
811
  }
711
- if (taxCountryCode !== undefined) {
712
- const nextTaxCountryCode = String(taxCountryCode || '');
812
+ if (taxCountryCode !== void 0) {
813
+ const nextTaxCountryCode = String(taxCountryCode || "");
713
814
  if (tempOrder.tax_country_code !== nextTaxCountryCode) {
714
815
  tempOrder.tax_country_code = nextTaxCountryCode;
715
816
  isChanged = true;
716
817
  }
717
818
  }
718
- if (currencyCode !== undefined) {
719
- const nextCurrencyCode = String(currencyCode || '');
819
+ if (currencyCode !== void 0) {
820
+ const nextCurrencyCode = String(currencyCode || "");
720
821
  if (tempOrder.currency_code !== nextCurrencyCode) {
721
822
  tempOrder.currency_code = nextCurrencyCode;
722
823
  isChanged = true;
723
824
  }
724
825
  }
725
- if (currencySymbol !== undefined) {
726
- const nextCurrencySymbol = String(currencySymbol || '');
826
+ if (currencySymbol !== void 0) {
827
+ const nextCurrencySymbol = String(currencySymbol || "");
727
828
  if (tempOrder.currency_symbol !== nextCurrencySymbol) {
728
829
  tempOrder.currency_symbol = nextCurrencySymbol;
729
830
  isChanged = true;
@@ -732,25 +833,22 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
732
833
  return isChanged;
733
834
  }
734
835
  async initialize(core, options = {}) {
836
+ var _a, _b, _c, _d;
735
837
  this.core = core;
736
838
  this.initializeOptions = options || {};
737
- // this.store = { ...this.store, ...(options.store as Partial<BaseSalesState>) };
738
839
  this.otherParams = options.otherParams || {};
739
- this.cacheId = this.otherParams?.cacheId;
840
+ this.cacheId = (_a = this.otherParams) == null ? void 0 : _a.cacheId;
740
841
  this.reusedSharedSubModuleNames.clear();
741
- this.window = core.getPlugin('window');
742
- this.request = core.getPlugin('request');
743
-
744
- // 获取 logger 实例
745
- this.appPlugin = core.getPlugin('app');
842
+ this.window = core.getPlugin("window");
843
+ this.request = core.getPlugin("request");
844
+ this.appPlugin = core.getPlugin("app");
746
845
  if (!this.appPlugin) {
747
- // throw new Error('Checkout 解决方案需要 app 插件支持');
748
846
  }
749
- const app = this.appPlugin?.getApp?.();
750
- this.logger = app?.logger;
847
+ const app = (_c = (_b = this.appPlugin) == null ? void 0 : _b.getApp) == null ? void 0 : _c.call(_b);
848
+ this.logger = app == null ? void 0 : app.logger;
751
849
  const targetCacheData = this.readSessionCacheData();
752
850
  const moduleNames = this.getRegisteredModuleNames();
753
- moduleNames.forEach(step => {
851
+ moduleNames.forEach((step) => {
754
852
  const reusedModule = this.getReusableSharedSubModule(step);
755
853
  if (reusedModule) {
756
854
  this.store[step] = reusedModule;
@@ -764,30 +862,32 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
764
862
  const hooks = this.getSubModuleHooks(step);
765
863
  this.store[step] = targetModule;
766
864
  this.core.registerModule(targetModule, {
767
- initialState: targetCacheData?.[targetModule.name] || {},
768
- ...(hooks ? {
769
- hooks
770
- } : {}),
865
+ initialState: (targetCacheData == null ? void 0 : targetCacheData[targetModule.name]) || {},
866
+ ...hooks ? { hooks } : {},
771
867
  otherParams: this.buildSubModuleOtherParams()
772
868
  });
773
869
  });
774
870
  if (this.store.schedule && !this.isScheduleListLoaded(this.store.schedule)) {
775
871
  await this.store.schedule.loadAllSchedule();
776
872
  }
777
- if (this.store.order && typeof this.otherParams?.enableTempOrderPersist === 'boolean') {
778
- this.store.order.setEnableTempOrderPersist(this.otherParams.enableTempOrderPersist);
873
+ if (this.store.order && typeof ((_d = this.otherParams) == null ? void 0 : _d.enableTempOrderPersist) === "boolean") {
874
+ this.store.order.setEnableTempOrderPersist(
875
+ this.otherParams.enableTempOrderPersist
876
+ );
779
877
  }
780
878
  await this.getPaymentMethodsAsync();
781
879
  this.registerServerOrderChangeSync();
782
880
  this.core.effects.emit(`${this.name}:onInited`, {});
783
881
  }
784
882
  async destroy() {
785
- this.serverOrderChangeUnsubscribe?.();
883
+ var _a;
884
+ (_a = this.serverOrderChangeUnsubscribe) == null ? void 0 : _a.call(this);
786
885
  this.serverOrderChangeUnsubscribe = null;
787
- Object.keys(this.store).forEach(key => {
788
- if (this.reusedSharedSubModuleNames.has(key)) return;
886
+ Object.keys(this.store).forEach((key) => {
887
+ if (this.reusedSharedSubModuleNames.has(key))
888
+ return;
789
889
  const sub = this.store[key];
790
- if (sub && typeof sub.destroy === 'function') {
890
+ if (sub && typeof sub.destroy === "function") {
791
891
  try {
792
892
  sub.destroy();
793
893
  } catch (error) {
@@ -801,7 +901,6 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
801
901
  await this.core.effects.emit(`${this.name}:onDestroy`, {});
802
902
  super.destroy();
803
903
  }
804
-
805
904
  /**
806
905
  * 加载销售订单到统一 tempOrder 工作区。
807
906
  * 统一通过 OrderModule 的 sales detail lookup 加载订单详情。
@@ -810,128 +909,142 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
810
909
  * (比如把 `sales.customer` 写入 CustomerModule、emit 业务 hook 等)。
811
910
  */
812
911
  async loadSalesDetail(orderIdOrParams) {
813
- if (!this.store.order) throw new Error('order 模块未初始化');
912
+ if (!this.store.order)
913
+ throw new Error("order 模块未初始化");
814
914
  const loadSequence = ++this.salesDetailLoadSequence;
815
915
  this.salesDetailLoadInFlightCount += 1;
816
916
  try {
817
- const params = typeof orderIdOrParams === 'object' ? orderIdOrParams : {
818
- orderId: orderIdOrParams
819
- };
917
+ const params = typeof orderIdOrParams === "object" ? orderIdOrParams : { orderId: orderIdOrParams };
820
918
  const externalSaleNumber = params.externalSaleNumber || params.external_sale_number;
821
919
  const preloadedSalesDetail = params.preloadedSalesDetail;
822
- const lookup = params.orderId ?? externalSaleNumber ?? params.orderNumber ?? preloadedSalesDetail?.order_id ?? preloadedSalesDetail?.external_sale_number ?? preloadedSalesDetail?.order_number;
823
- if (!preloadedSalesDetail && (lookup === undefined || lookup === null || lookup === '')) {
824
- throw new Error('加载销售详情需要 orderId、externalSaleNumber 或 orderNumber');
920
+ const lookup = params.orderId ?? externalSaleNumber ?? params.orderNumber ?? (preloadedSalesDetail == null ? void 0 : preloadedSalesDetail.order_id) ?? (preloadedSalesDetail == null ? void 0 : preloadedSalesDetail.external_sale_number) ?? (preloadedSalesDetail == null ? void 0 : preloadedSalesDetail.order_number);
921
+ if (!preloadedSalesDetail && (lookup === void 0 || lookup === null || lookup === "")) {
922
+ throw new Error("加载销售详情需要 orderId、externalSaleNumber 或 orderNumber");
825
923
  }
826
- // GlobalSearch 等调用方已拿到完整详情时,直接进入查询成功后的 hydrate 流程,避免按 id 二次请求。
827
- const loadedRecord = preloadedSalesDetail ?? (await this.store.order.getSalesOrderByLookup({
924
+ const loadedRecord = preloadedSalesDetail ?? await this.store.order.getSalesOrderByLookup({
828
925
  lookup,
829
926
  forceRemote: params.forceRemote
830
- }));
927
+ });
831
928
  if (!preloadedSalesDetail && (!loadedRecord || loadedRecord.code !== 200)) {
832
929
  const message = loadedRecord && (loadedRecord.message || loadedRecord.msg) || `加载销售详情失败: ${lookup}`;
833
930
  throw new Error(message);
834
931
  }
835
932
  const remoteRecord = preloadedSalesDetail ?? loadedRecord.data;
836
933
  const currentTempOrder = params.merge ? this.store.order.getTempOrder() : null;
837
- const record = params.merge ? mergeSalesDetailRecordWithTempOrder(currentTempOrder, remoteRecord, 'preserve-local') : remoteRecord;
934
+ const record = params.merge ? mergeSalesDetailRecordWithTempOrder(
935
+ currentTempOrder,
936
+ remoteRecord,
937
+ "preserve-local"
938
+ ) : remoteRecord;
838
939
  return await this.hydrateLatestLoadedSalesDetail(record, loadSequence);
839
940
  } finally {
840
- this.salesDetailLoadInFlightCount = Math.max(0, this.salesDetailLoadInFlightCount - 1);
941
+ this.salesDetailLoadInFlightCount = Math.max(
942
+ 0,
943
+ this.salesDetailLoadInFlightCount - 1
944
+ );
841
945
  if (this.salesDetailLoadInFlightCount === 0) {
842
946
  try {
843
947
  await this.drainQueuedServerOrderChanges();
844
948
  } catch (error) {
845
- this.logError('drain queued server order changes failed', {
949
+ this.logError("drain queued server order changes failed", {
846
950
  error: error instanceof Error ? error.message : String(error)
847
951
  });
848
952
  }
849
953
  }
850
954
  }
851
955
  }
852
-
853
956
  /** 获取当前已加载的销售详情(只读快照)。未加载过则返回 null。 */
854
957
  getSalesOrder() {
855
958
  return this.currentSalesDetail;
856
959
  }
857
-
858
960
  /** 获取销售详情顶部业务字段(订单号/状态/金额等通用字段集合)。 */
859
961
  getOrderHeader() {
860
- if (!this.currentSalesDetail) return null;
962
+ if (!this.currentSalesDetail)
963
+ return null;
861
964
  return this.currentSalesDetail.header || this.currentSalesDetail;
862
965
  }
863
-
864
966
  /** 获取所有 booking(含 root + children),按服务端原始顺序输出。 */
865
967
  getBookings() {
866
- return this.currentSalesDetail?.bookings || [];
968
+ var _a;
969
+ return ((_a = this.currentSalesDetail) == null ? void 0 : _a.bookings) || [];
867
970
  }
868
-
869
971
  /** 获取根 booking(is_next === 0 / is_root === 1),多个时取第一个。 */
870
972
  getRootBooking() {
871
- if (!this.currentSalesDetail) return null;
872
- if (this.currentSalesDetail.rootBooking) return this.currentSalesDetail.rootBooking;
973
+ if (!this.currentSalesDetail)
974
+ return null;
975
+ if (this.currentSalesDetail.rootBooking)
976
+ return this.currentSalesDetail.rootBooking;
873
977
  const bookings = this.currentSalesDetail.bookings || [];
874
- return bookings.find(booking => {
875
- const parentId = booking?.parent_id;
876
- return parentId === 0 || parentId === null || parentId === undefined;
978
+ return bookings.find((booking) => {
979
+ const parentId = booking == null ? void 0 : booking.parent_id;
980
+ return parentId === 0 || parentId === null || parentId === void 0;
877
981
  }) || null;
878
982
  }
879
-
880
983
  /** 按 product_uid 反查 booking 列表(用于商品行 ↔ booking 映射)。 */
881
984
  getChildBookingsByProductUid(productUid) {
882
- if (!this.currentSalesDetail || !productUid) return [];
883
- const indexed = this.currentSalesDetail.bookingsByProductUid?.[productUid];
884
- if (indexed) return indexed;
885
- return (this.currentSalesDetail.bookings || []).filter(booking => {
886
- const uid = booking?.product_uid || booking?.metadata?.product_uid;
887
- return String(uid || '') === String(productUid);
985
+ var _a;
986
+ if (!this.currentSalesDetail || !productUid)
987
+ return [];
988
+ const indexed = (_a = this.currentSalesDetail.bookingsByProductUid) == null ? void 0 : _a[productUid];
989
+ if (indexed)
990
+ return indexed;
991
+ return (this.currentSalesDetail.bookings || []).filter((booking) => {
992
+ var _a2;
993
+ const uid = (booking == null ? void 0 : booking.product_uid) || ((_a2 = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a2.product_uid);
994
+ return String(uid || "") === String(productUid);
888
995
  });
889
996
  }
890
-
891
997
  /** 获取支付列表(已支付/退款等明细)。 */
892
998
  getPayments() {
893
- return this.currentSalesDetail?.payments || [];
999
+ var _a;
1000
+ return ((_a = this.currentSalesDetail) == null ? void 0 : _a.payments) || [];
894
1001
  }
895
-
896
1002
  /** 获取附加费用(运费/服务费/税费等)。 */
897
1003
  getSurcharges() {
898
- return this.currentSalesDetail?.surcharges || [];
1004
+ var _a;
1005
+ return ((_a = this.currentSalesDetail) == null ? void 0 : _a.surcharges) || [];
899
1006
  }
900
1007
  getTempOrder() {
901
- const result = this.store.order?.getTempOrder() || null;
1008
+ var _a;
1009
+ const result = ((_a = this.store.order) == null ? void 0 : _a.getTempOrder()) || null;
902
1010
  return result;
903
1011
  }
904
1012
  async replaceTempOrder(tempOrder) {
905
- if (!this.store.order) throw new Error('order 模块未初始化');
1013
+ if (!this.store.order)
1014
+ throw new Error("order 模块未初始化");
906
1015
  const nextTempOrder = await this.store.order.replaceTempOrder(tempOrder);
907
- await this.effectsEmit('onTempOrderReplaced', {
908
- tempOrder: nextTempOrder
909
- });
1016
+ await this.effectsEmit("onTempOrderReplaced", { tempOrder: nextTempOrder });
910
1017
  return nextTempOrder;
911
1018
  }
912
1019
  getOrderIdentity() {
913
- if (!this.store.order) return null;
1020
+ if (!this.store.order)
1021
+ return null;
914
1022
  return this.store.order.getOrderIdentity();
915
1023
  }
916
1024
  getOrderSnapshot() {
917
- if (!this.store.order) return null;
1025
+ if (!this.store.order)
1026
+ return null;
918
1027
  return this.store.order.getOrderSnapshot();
919
1028
  }
920
1029
  getOrderSyncState() {
921
- if (!this.store.order) return 'local';
1030
+ if (!this.store.order)
1031
+ return "local";
922
1032
  return this.store.order.getOrderSyncState();
923
1033
  }
924
1034
  getOrderAmountSnapshot() {
925
- if (!this.store.order) return null;
1035
+ if (!this.store.order)
1036
+ return null;
926
1037
  return this.store.order.getOrderAmountSnapshot();
927
1038
  }
928
1039
  getTempOrderNote() {
929
- if (!this.store.order) return '';
1040
+ if (!this.store.order)
1041
+ return "";
930
1042
  return this.store.order.getTempOrderNote();
931
1043
  }
932
1044
  updateTempOrderNote(note, sync = false) {
933
1045
  try {
934
- if (!this.store.order) throw new Error('order 模块未初始化');
1046
+ if (!this.store.order)
1047
+ throw new Error("order 模块未初始化");
935
1048
  const result = this.store.order.updateTempOrderNote(note, sync);
936
1049
  return result;
937
1050
  } catch (error) {
@@ -939,42 +1052,47 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
939
1052
  }
940
1053
  }
941
1054
  updateRemoteOrderNote(orderId, note) {
942
- if (!this.store.order) throw new Error('order 模块未初始化');
1055
+ if (!this.store.order)
1056
+ throw new Error("order 模块未初始化");
943
1057
  this.store.order.syncTempOrderNoteToRemote(orderId, note);
944
1058
  }
945
1059
  updateTempOrderShopDiscount(amount) {
946
- if (!this.store.order) throw new Error('order 模块未初始化');
1060
+ if (!this.store.order)
1061
+ throw new Error("order 模块未初始化");
947
1062
  return this.store.order.updateTempOrderShopDiscount(amount);
948
1063
  }
949
1064
  updateTempOrderDepositAmount(amount) {
950
- if (!this.store.order) throw new Error('order 模块未初始化');
1065
+ if (!this.store.order)
1066
+ throw new Error("order 模块未初始化");
951
1067
  return this.store.order.updateTempOrderDepositAmount(amount);
952
1068
  }
953
1069
  updateTempOrderContactsInfo(contactsInfo) {
954
- if (!this.store.order) throw new Error('order 模块未初始化');
1070
+ if (!this.store.order)
1071
+ throw new Error("order 模块未初始化");
955
1072
  return this.store.order.updateTempOrderContactsInfo(contactsInfo);
956
1073
  }
957
-
958
1074
  /** @deprecated OrderModule 不再负责 tempOrder localStorage 持久化。 */
959
1075
  setEnableTempOrderPersist(enabled) {
960
- if (!this.store.order) throw new Error('order 模块未初始化');
1076
+ if (!this.store.order)
1077
+ throw new Error("order 模块未初始化");
961
1078
  this.store.order.setEnableTempOrderPersist(enabled);
962
1079
  }
963
-
964
1080
  /** 是否允许 saveDraft 写入 IndexedDB 草稿。 */
965
1081
  isTempOrderPersistEnabled() {
966
- if (!this.store.order) return false;
1082
+ if (!this.store.order)
1083
+ return false;
967
1084
  return this.store.order.isTempOrderPersistEnabled();
968
1085
  }
969
1086
  ensureTempOrder() {
970
- if (!this.store.order) throw new Error('order 模块未初始化');
1087
+ if (!this.store.order)
1088
+ throw new Error("order 模块未初始化");
971
1089
  return this.store.order.ensureTempOrder();
972
1090
  }
973
-
974
1091
  // 主动创建临时订单;若已存在则直接返回已有订单
975
1092
  async addNewOrder() {
976
1093
  try {
977
- if (!this.store.order) throw new Error('order 模块未初始化');
1094
+ if (!this.store.order)
1095
+ throw new Error("order 模块未初始化");
978
1096
  const tempOrder = await this.store.order.addNewOrder();
979
1097
  if (this.syncAppDataToTempOrder(tempOrder) && this.isTempOrderPersistEnabled()) {
980
1098
  this.store.order.persistTempOrder();
@@ -986,25 +1104,22 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
986
1104
  }
987
1105
  }
988
1106
  async saveDraft() {
989
- if (!this.store.order) throw new Error('order 模块未初始化');
1107
+ if (!this.store.order)
1108
+ throw new Error("order 模块未初始化");
990
1109
  return this.store.order.saveDraft();
991
1110
  }
992
-
993
1111
  // 重置 tempOrder 与与上一单强相关的运行态(resource/entryPaxNumber/enabledReservationRuleProducts),
994
1112
  // 适用于从支付页通过 react-router 跳回继续下单时清理残留数据
995
1113
  async restoreOrder() {
996
1114
  try {
997
1115
  if (!this.store.order) {
998
- throw new Error('scanOrder 解决方案需要 order 模块支持');
1116
+ throw new Error("scanOrder 解决方案需要 order 模块支持");
999
1117
  }
1000
- // this.store.resource = null;
1001
1118
  const tempOrder = this.store.order.restoreOrder();
1002
1119
  this.currentSalesDetail = null;
1003
1120
  this.discountConfigCacheKey = null;
1004
1121
  this.hasManualDiscountSelection = false;
1005
- await this.effectsEmit('onTempOrderReplaced', {
1006
- tempOrder
1007
- });
1122
+ await this.effectsEmit("onTempOrderReplaced", { tempOrder });
1008
1123
  if (this.syncAppDataToTempOrder(tempOrder) && this.isTempOrderPersistEnabled()) {
1009
1124
  this.store.order.persistTempOrder();
1010
1125
  await this.store.order.saveDraft();
@@ -1014,14 +1129,14 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1014
1129
  throw error;
1015
1130
  }
1016
1131
  }
1017
-
1018
1132
  /**
1019
1133
  * 仅清空 tempOrder 购物车行(products / bookings / discount_list)。
1020
1134
  * 同步清空内存中的 salesDetail 商品/预约视图,避免编辑态仍读到旧 bookings。
1021
1135
  */
1022
1136
  async clearOrderCartLines() {
1023
1137
  try {
1024
- if (!this.store.order) throw new Error('order 模块未初始化');
1138
+ if (!this.store.order)
1139
+ throw new Error("order 模块未初始化");
1025
1140
  const tempOrder = await this.store.order.clearOrderCartLines();
1026
1141
  if (this.currentSalesDetail) {
1027
1142
  this.currentSalesDetail = {
@@ -1033,9 +1148,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1033
1148
  discount_list: []
1034
1149
  };
1035
1150
  }
1036
- await this.effectsEmit('onTempOrderReplaced', {
1037
- tempOrder
1038
- });
1151
+ await this.effectsEmit("onTempOrderReplaced", { tempOrder });
1039
1152
  if (this.syncAppDataToTempOrder(tempOrder) && this.isTempOrderPersistEnabled()) {
1040
1153
  this.store.order.persistTempOrder();
1041
1154
  await this.store.order.saveDraft();
@@ -1046,13 +1159,15 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1046
1159
  }
1047
1160
  }
1048
1161
  getOrderProducts() {
1049
- if (!this.store.order) throw new Error('order 模块未初始化');
1162
+ if (!this.store.order)
1163
+ throw new Error("order 模块未初始化");
1050
1164
  const products = this.store.order.getOrderProducts();
1051
1165
  return products;
1052
1166
  }
1053
1167
  async getSummary() {
1054
1168
  try {
1055
- if (!this.store.order) throw new Error('order 模块未初始化');
1169
+ if (!this.store.order)
1170
+ throw new Error("order 模块未初始化");
1056
1171
  const summary = await this.store.order.getOrderSummary();
1057
1172
  return summary;
1058
1173
  } catch (error) {
@@ -1061,18 +1176,21 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1061
1176
  }
1062
1177
  getHistoricalProductDiscountList(products) {
1063
1178
  const historyDiscountList = [];
1064
- products.forEach(item => {
1065
- if (!this.isPersistedOrderProduct(item)) return;
1066
- (item.discount_list || []).forEach(discount => {
1067
- const discountId = discount.discount?.resource_id || discount.id;
1068
- if (!discountId || !['good_pass', 'discount_card'].includes(discount.type)) return;
1179
+ products.forEach((item) => {
1180
+ if (!this.isPersistedOrderProduct(item))
1181
+ return;
1182
+ (item.discount_list || []).forEach((discount) => {
1183
+ var _a, _b, _c, _d, _e, _f;
1184
+ const discountId = ((_a = discount.discount) == null ? void 0 : _a.resource_id) || discount.id;
1185
+ if (!discountId || !["good_pass", "discount_card"].includes(discount.type))
1186
+ return;
1069
1187
  const quantity = item.quantity || item.num || item.product_quantity || 1;
1070
- const savedAmount = new _decimal.default(discount.amount || 0).times(quantity).plus(discount?.metadata?.product_discount_difference || 0);
1071
- const index = historyDiscountList.findIndex(n => n.id === discountId);
1188
+ const savedAmount = new import_decimal.default(discount.amount || 0).times(quantity).plus(((_b = discount == null ? void 0 : discount.metadata) == null ? void 0 : _b.product_discount_difference) || 0);
1189
+ const index = historyDiscountList.findIndex((n) => n.id === discountId);
1072
1190
  if (index !== -1) {
1073
1191
  historyDiscountList[index] = {
1074
1192
  ...historyDiscountList[index],
1075
- amount: new _decimal.default(historyDiscountList[index].amount || 0).plus(discount.amount || 0).toNumber(),
1193
+ amount: new import_decimal.default(historyDiscountList[index].amount || 0).plus(discount.amount || 0).toNumber(),
1076
1194
  savedAmount: savedAmount.plus(historyDiscountList[index].savedAmount || 0).toNumber()
1077
1195
  };
1078
1196
  return;
@@ -1081,15 +1199,15 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1081
1199
  ...discount,
1082
1200
  id: discountId,
1083
1201
  tag: discount.tag || discount.type,
1084
- name: discount.name || discount.discount?.title?.auto,
1085
- format_title: discount.discount?.title || discount.format_title,
1202
+ name: discount.name || ((_d = (_c = discount.discount) == null ? void 0 : _c.title) == null ? void 0 : _d.auto),
1203
+ format_title: ((_e = discount.discount) == null ? void 0 : _e.title) || discount.format_title,
1086
1204
  isEditMode: true,
1087
1205
  limited_relation_product_data: {},
1088
1206
  savedAmount: savedAmount.toNumber(),
1089
1207
  isAvailable: true,
1090
1208
  isDisabled: true,
1091
1209
  isSelected: true,
1092
- product_id: discount.discount?.product_id || discount.product_id
1210
+ product_id: ((_f = discount.discount) == null ? void 0 : _f.product_id) || discount.product_id
1093
1211
  });
1094
1212
  });
1095
1213
  });
@@ -1097,38 +1215,57 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1097
1215
  }
1098
1216
  isPersistedOrderProduct(product) {
1099
1217
  const orderDetailId = product.order_detail_id ?? product.orderDetailId;
1100
- if (orderDetailId !== undefined && orderDetailId !== null && orderDetailId !== '') {
1218
+ if (orderDetailId !== void 0 && orderDetailId !== null && orderDetailId !== "") {
1101
1219
  return true;
1102
1220
  }
1103
1221
  const bookingId = product.booking_id ?? product.bookingId;
1104
- return bookingId !== undefined && bookingId !== null && bookingId !== '';
1222
+ return bookingId !== void 0 && bookingId !== null && bookingId !== "";
1105
1223
  }
1106
1224
  mergeHistoricalDiscountList(discountList, products) {
1107
1225
  const historyDiscountList = this.getHistoricalProductDiscountList(products);
1108
- const historyIds = new Set(historyDiscountList.map(discount => discount.id));
1109
- return [...historyDiscountList, ...(discountList || []).filter(discount => {
1110
- if (!historyIds.has(discount.id)) return true;
1111
- return !isBaseSalesHistoricalDiscountEntry(discount);
1112
- })];
1226
+ const historyIds = new Set(historyDiscountList.map((discount) => discount.id));
1227
+ return [
1228
+ ...historyDiscountList,
1229
+ ...(discountList || []).filter((discount) => {
1230
+ if (!historyIds.has(discount.id))
1231
+ return true;
1232
+ return !isBaseSalesHistoricalDiscountEntry(discount);
1233
+ })
1234
+ ];
1113
1235
  }
1114
1236
  shouldSkipAutoApplyFetchedDiscountsInEditMode(params) {
1115
- if (params.discountAction !== 'edit') return false;
1116
- if (!params.products.length) return false;
1117
- const hasDraftProduct = params.products.some(product => !this.isPersistedOrderProduct(product));
1118
- if (hasDraftProduct) return false;
1119
- const hasSelectedDiscount = params.currentDiscountList.some(discount => discount.isSelected || discount.isEditMode || discount.isManualSelect);
1120
- if (hasSelectedDiscount) return false;
1121
- return !params.nextDiscountList.some(discount => discount.isSelected || discount.isEditMode || discount.isManualSelect);
1237
+ if (params.discountAction !== "edit")
1238
+ return false;
1239
+ if (!params.products.length)
1240
+ return false;
1241
+ const hasDraftProduct = params.products.some((product) => !this.isPersistedOrderProduct(product));
1242
+ if (hasDraftProduct)
1243
+ return false;
1244
+ const hasSelectedDiscount = params.currentDiscountList.some(
1245
+ (discount) => discount.isSelected || discount.isEditMode || discount.isManualSelect
1246
+ );
1247
+ if (hasSelectedDiscount)
1248
+ return false;
1249
+ return !params.nextDiscountList.some(
1250
+ (discount) => discount.isSelected || discount.isEditMode || discount.isManualSelect
1251
+ );
1122
1252
  }
1123
1253
  mergeCurrentDiscountSelectionState(discountList, currentDiscountList) {
1124
- if (!currentDiscountList.length) return discountList;
1125
- const currentDiscountMap = new Map();
1126
- currentDiscountList.forEach(discount => {
1127
- currentDiscountMap.set(`${discount.id}:${isBaseSalesHistoricalDiscountEntry(discount) ? 'historical' : 'runtime'}`, discount);
1254
+ if (!currentDiscountList.length)
1255
+ return discountList;
1256
+ const currentDiscountMap = /* @__PURE__ */ new Map();
1257
+ currentDiscountList.forEach((discount) => {
1258
+ currentDiscountMap.set(
1259
+ `${discount.id}:${isBaseSalesHistoricalDiscountEntry(discount) ? "historical" : "runtime"}`,
1260
+ discount
1261
+ );
1128
1262
  });
1129
- return discountList.map(discount => {
1130
- const currentDiscount = currentDiscountMap.get(`${discount.id}:${isBaseSalesHistoricalDiscountEntry(discount) ? 'historical' : 'runtime'}`);
1131
- if (!currentDiscount) return discount;
1263
+ return discountList.map((discount) => {
1264
+ const currentDiscount = currentDiscountMap.get(
1265
+ `${discount.id}:${isBaseSalesHistoricalDiscountEntry(discount) ? "historical" : "runtime"}`
1266
+ );
1267
+ if (!currentDiscount)
1268
+ return discount;
1132
1269
  if (currentDiscount.isManualSelect) {
1133
1270
  return {
1134
1271
  ...discount,
@@ -1147,18 +1284,26 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1147
1284
  });
1148
1285
  }
1149
1286
  async loadDiscountConfig(params) {
1150
- if (!this.store.order) throw new Error('order 模块未初始化');
1287
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
1288
+ if (!this.store.order)
1289
+ throw new Error("order 模块未初始化");
1151
1290
  const tempOrder = this.store.order.ensureTempOrder();
1152
1291
  const orderStore = this.store.order.store || {};
1153
1292
  const discountModule = orderStore.discount;
1154
1293
  const rulesModule = orderStore.rules;
1155
- const orderId = tempOrder.order_id || this.getOrderIdentity?.()?.orderId;
1156
- const customerId = Number(params?.customerId || tempOrder.customer_id || tempOrder.customer?.id || tempOrder._extend?.customerSnapshot?.id || tempOrder._extend?.customerSnapshot?.customer_id || 0);
1157
- const currentDiscountList = discountModule?.getDiscountList?.() || [];
1158
- const originalDiscountList = discountModule?.getOriginalDiscountList?.() || [];
1159
- const hasManualDiscountSelection = this.hasManualDiscountSelection || currentDiscountList.some(discount => discount.isManualSelect);
1160
- const discountAction = params?.action || (orderId ? 'edit' : 'create');
1161
- const discountConfigCacheKey = [customerId, discountAction, Number(orderId) || 0].join(':');
1294
+ const orderId = tempOrder.order_id || ((_b = (_a = this.getOrderIdentity) == null ? void 0 : _a.call(this)) == null ? void 0 : _b.orderId);
1295
+ const customerId = Number(
1296
+ (params == null ? void 0 : params.customerId) || tempOrder.customer_id || ((_c = tempOrder.customer) == null ? void 0 : _c.id) || ((_e = (_d = tempOrder._extend) == null ? void 0 : _d.customerSnapshot) == null ? void 0 : _e.id) || ((_g = (_f = tempOrder._extend) == null ? void 0 : _f.customerSnapshot) == null ? void 0 : _g.customer_id) || 0
1297
+ );
1298
+ const currentDiscountList = ((_h = discountModule == null ? void 0 : discountModule.getDiscountList) == null ? void 0 : _h.call(discountModule)) || [];
1299
+ const originalDiscountList = ((_i = discountModule == null ? void 0 : discountModule.getOriginalDiscountList) == null ? void 0 : _i.call(discountModule)) || [];
1300
+ const hasManualDiscountSelection = this.hasManualDiscountSelection || currentDiscountList.some((discount) => discount.isManualSelect);
1301
+ const discountAction = (params == null ? void 0 : params.action) || (orderId ? "edit" : "create");
1302
+ const discountConfigCacheKey = [
1303
+ customerId,
1304
+ discountAction,
1305
+ Number(orderId) || 0
1306
+ ].join(":");
1162
1307
  let preparedDiscountList = [];
1163
1308
  if (customerId && customerId !== 1) {
1164
1309
  if (this.discountConfigCacheKey === discountConfigCacheKey) {
@@ -1167,11 +1312,11 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1167
1312
  preparedDiscountList = await this.store.order.loadDiscountConfig({
1168
1313
  customerId,
1169
1314
  action: discountAction,
1170
- orderId: Number(orderId) || undefined,
1315
+ orderId: Number(orderId) || void 0,
1171
1316
  apply: false
1172
1317
  });
1173
1318
  this.discountConfigCacheKey = discountConfigCacheKey;
1174
- await discountModule?.setOriginalDiscountList?.(preparedDiscountList);
1319
+ await ((_j = discountModule == null ? void 0 : discountModule.setOriginalDiscountList) == null ? void 0 : _j.call(discountModule, preparedDiscountList));
1175
1320
  }
1176
1321
  }
1177
1322
  if (hasManualDiscountSelection && currentDiscountList.length) {
@@ -1181,9 +1326,15 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1181
1326
  availableWalletIds: this.getAvailableWalletIds()
1182
1327
  };
1183
1328
  }
1184
- let nextDiscountList = this.mergeHistoricalDiscountList(preparedDiscountList || discountModule?.getDiscountList?.() || [], tempOrder.products || []);
1185
- nextDiscountList = this.mergeCurrentDiscountSelectionState(nextDiscountList, currentDiscountList);
1186
- await discountModule?.setDiscountList(nextDiscountList);
1329
+ let nextDiscountList = this.mergeHistoricalDiscountList(
1330
+ preparedDiscountList || ((_k = discountModule == null ? void 0 : discountModule.getDiscountList) == null ? void 0 : _k.call(discountModule)) || [],
1331
+ tempOrder.products || []
1332
+ );
1333
+ nextDiscountList = this.mergeCurrentDiscountSelectionState(
1334
+ nextDiscountList,
1335
+ currentDiscountList
1336
+ );
1337
+ await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1187
1338
  const shouldSkipAutoApplyFetchedDiscounts = this.shouldSkipAutoApplyFetchedDiscountsInEditMode({
1188
1339
  discountAction,
1189
1340
  products: tempOrder.products || [],
@@ -1191,11 +1342,9 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1191
1342
  nextDiscountList
1192
1343
  });
1193
1344
  if (shouldSkipAutoApplyFetchedDiscounts) {
1194
- const summary = await this.store.order.recalculateSummary({
1195
- createIfMissing: true
1196
- });
1345
+ const summary2 = await this.store.order.recalculateSummary({ createIfMissing: true });
1197
1346
  this.store.order.persistTempOrder();
1198
- await this.effectsEmit('onDiscountApplied', {
1347
+ await this.effectsEmit("onDiscountApplied", {
1199
1348
  productList: tempOrder.products || [],
1200
1349
  discountList: nextDiscountList,
1201
1350
  selectedDiscountList: tempOrder.discount_list || [],
@@ -1208,50 +1357,56 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1208
1357
  };
1209
1358
  }
1210
1359
  if (rulesModule) {
1211
- const orderTotalAmount = Number(orderStore.summary?.total_amount || 0);
1360
+ const orderTotalAmount = Number(((_l = orderStore.summary) == null ? void 0 : _l.total_amount) || 0);
1361
+ console.log("[BaseSales.applyDiscountConfig.calcDiscount]");
1212
1362
  const result = rulesModule.calcDiscount({
1213
1363
  productList: tempOrder.products,
1214
1364
  discountList: nextDiscountList,
1215
1365
  holders: [],
1216
- isFormSubject: product => (0, _utils.resolveIsFormSubject)(tempOrder, product),
1366
+ isFormSubject: (product) => (0, import_utils.resolveIsFormSubject)(tempOrder, product),
1217
1367
  orderTotalAmount
1218
- }) || {
1219
- productList: tempOrder.products,
1220
- discountList: nextDiscountList
1221
- };
1368
+ }) || { productList: tempOrder.products, discountList: nextDiscountList };
1222
1369
  if (result.productList) {
1223
- tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
1370
+ tempOrder.products = preserveManualProductDiscountProducts(
1371
+ tempOrder.products,
1372
+ result.productList
1373
+ );
1224
1374
  }
1225
1375
  for (const product of tempOrder.products || []) {
1226
- const productUid = product.metadata?.unique_identification_number;
1227
- const runtimeOrigin = productUid ? tempOrder._extend?.productsByUid?.[productUid]?.origin : undefined;
1228
- if (runtimeOrigin?.isManualDiscount || isBaseSalesManualProductDiscountProduct(product)) continue;
1229
- const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + Number(pd.amount || 0), 0);
1230
- const optionSum = (0, _utils.sumOptionUnitPrice)((0, _utils.getProductSkuOptions)(product));
1231
- const sourcePrice = product.metadata?.source_product_price ?? (product.metadata?.main_product_original_price != null ? new _decimal.default(Number(product.metadata.main_product_original_price) || 0).minus(optionSum).toFixed(2) : product.original_price ?? '0');
1232
- const newSourceSellingPrice = new _decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
1233
- const newMainSellingPrice = new _decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
1376
+ const productUid = (_m = product.metadata) == null ? void 0 : _m.unique_identification_number;
1377
+ const runtimeOrigin = productUid ? (_p = (_o = (_n = tempOrder._extend) == null ? void 0 : _n.productsByUid) == null ? void 0 : _o[productUid]) == null ? void 0 : _p.origin : void 0;
1378
+ if ((runtimeOrigin == null ? void 0 : runtimeOrigin.isManualDiscount) || isBaseSalesManualProductDiscountProduct(product))
1379
+ continue;
1380
+ const totalPerUnitDiscount = (product.discount_list || []).reduce(
1381
+ (sum, pd) => sum + Number(pd.amount || 0),
1382
+ 0
1383
+ );
1384
+ const optionSum = (0, import_utils.sumOptionUnitPrice)((0, import_utils.getProductSkuOptions)(product));
1385
+ const sourcePrice = ((_q = product.metadata) == null ? void 0 : _q.source_product_price) ?? (((_r = product.metadata) == null ? void 0 : _r.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");
1386
+ const newSourceSellingPrice = new import_decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
1387
+ const newMainSellingPrice = new import_decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
1234
1388
  if (product.metadata) {
1235
1389
  product.metadata.main_product_selling_price = newMainSellingPrice;
1236
1390
  product.metadata.price_schema_version = 2;
1237
1391
  }
1238
- product.selling_price = (0, _utils.composeLinePrice)({
1392
+ product.selling_price = (0, import_utils.composeLinePrice)({
1239
1393
  mainPrice: newMainSellingPrice,
1240
1394
  bundle: product.product_bundle
1241
1395
  });
1242
1396
  }
1243
1397
  if (result.discountList) {
1244
- nextDiscountList = this.mergeHistoricalDiscountList(result.discountList, tempOrder.products || []);
1245
- _Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1246
- await discountModule?.setDiscountList(nextDiscountList);
1247
- tempOrder.discount_list = nextDiscountList.filter(discount => discount.isSelected);
1398
+ nextDiscountList = this.mergeHistoricalDiscountList(
1399
+ result.discountList,
1400
+ tempOrder.products || []
1401
+ );
1402
+ import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1403
+ await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1404
+ tempOrder.discount_list = nextDiscountList.filter((discount) => discount.isSelected);
1248
1405
  }
1249
1406
  }
1250
- const summary = await this.store.order.recalculateSummary({
1251
- createIfMissing: true
1252
- });
1407
+ const summary = await this.store.order.recalculateSummary({ createIfMissing: true });
1253
1408
  this.store.order.persistTempOrder();
1254
- await this.effectsEmit('onDiscountApplied', {
1409
+ await this.effectsEmit("onDiscountApplied", {
1255
1410
  productList: tempOrder.products || [],
1256
1411
  discountList: nextDiscountList,
1257
1412
  selectedDiscountList: tempOrder.discount_list || [],
@@ -1264,79 +1419,95 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1264
1419
  };
1265
1420
  }
1266
1421
  getAvailableWalletIds() {
1267
- if (!this.store.order?.getAvailableWalletIds) return [];
1422
+ var _a;
1423
+ if (!((_a = this.store.order) == null ? void 0 : _a.getAvailableWalletIds))
1424
+ return [];
1268
1425
  return this.store.order.getAvailableWalletIds();
1269
1426
  }
1270
1427
  async bestDiscount(cb) {
1271
- if (!this.store.order) throw new Error('order 模块未初始化');
1428
+ var _a, _b, _c;
1429
+ if (!this.store.order)
1430
+ throw new Error("order 模块未初始化");
1272
1431
  const tempOrder = this.store.order.ensureTempOrder();
1273
1432
  const orderStore = this.store.order.store || {};
1274
1433
  const discountModule = orderStore.discount;
1275
1434
  const rulesModule = orderStore.rules;
1276
- const originalDiscountList = discountModule?.getOriginalDiscountList?.() || this.getDiscountList();
1277
- const currentDiscountList = discountModule?.getDiscountList?.() || [];
1278
- let nextDiscountList = this.mergeHistoricalDiscountList(originalDiscountList || [], tempOrder.products || []);
1435
+ const originalDiscountList = ((_a = discountModule == null ? void 0 : discountModule.getOriginalDiscountList) == null ? void 0 : _a.call(discountModule)) || this.getDiscountList();
1436
+ const currentDiscountList = ((_b = discountModule == null ? void 0 : discountModule.getDiscountList) == null ? void 0 : _b.call(discountModule)) || [];
1437
+ let nextDiscountList = this.mergeHistoricalDiscountList(
1438
+ originalDiscountList || [],
1439
+ tempOrder.products || []
1440
+ );
1279
1441
  let result = {
1280
1442
  productList: tempOrder.products || [],
1281
1443
  discountList: nextDiscountList
1282
1444
  };
1283
- await discountModule?.setDiscountList(nextDiscountList);
1445
+ await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1284
1446
  if (rulesModule) {
1285
- const orderTotalAmount = Number(orderStore.summary?.total_amount || 0);
1447
+ const orderTotalAmount = Number(((_c = orderStore.summary) == null ? void 0 : _c.total_amount) || 0);
1448
+ console.log("[BaseSales.bestDiscount.calcDiscount]");
1286
1449
  result = rulesModule.calcDiscount({
1287
1450
  productList: tempOrder.products,
1288
1451
  discountList: nextDiscountList,
1289
1452
  holders: [],
1290
- isFormSubject: product => (0, _utils.resolveIsFormSubject)(tempOrder, product),
1453
+ isFormSubject: (product) => (0, import_utils.resolveIsFormSubject)(tempOrder, product),
1291
1454
  orderTotalAmount
1292
1455
  }) || result;
1293
1456
  if (result.productList) {
1294
- tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
1457
+ tempOrder.products = preserveManualProductDiscountProducts(
1458
+ tempOrder.products,
1459
+ result.productList
1460
+ );
1295
1461
  }
1296
1462
  if (result.discountList) {
1297
- nextDiscountList = this.mergeHistoricalDiscountList(result.discountList, tempOrder.products || []);
1298
- _Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1299
- await discountModule?.setDiscountList(nextDiscountList);
1300
- tempOrder.discount_list = nextDiscountList.filter(discount => discount.isSelected);
1463
+ nextDiscountList = this.mergeHistoricalDiscountList(
1464
+ result.discountList,
1465
+ tempOrder.products || []
1466
+ );
1467
+ import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1468
+ await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1469
+ tempOrder.discount_list = nextDiscountList.filter((discount) => discount.isSelected);
1301
1470
  result = {
1302
1471
  productList: tempOrder.products,
1303
1472
  discountList: nextDiscountList
1304
1473
  };
1305
1474
  }
1306
1475
  }
1307
- await this.store.order.recalculateSummary({
1308
- createIfMissing: true
1309
- });
1476
+ await this.store.order.recalculateSummary({ createIfMissing: true });
1310
1477
  this.store.order.persistTempOrder();
1311
- await this.effectsEmit('onDiscountApplied', {
1478
+ await this.effectsEmit("onDiscountApplied", {
1312
1479
  productList: tempOrder.products || [],
1313
1480
  discountList: nextDiscountList,
1314
1481
  selectedDiscountList: tempOrder.discount_list || [],
1315
1482
  tempOrder
1316
1483
  });
1317
- cb?.(result);
1484
+ cb == null ? void 0 : cb(result);
1318
1485
  return result;
1319
1486
  }
1320
1487
  getDiscountList() {
1321
- if (!this.store.order) return [];
1488
+ if (!this.store.order)
1489
+ return [];
1322
1490
  return this.store.order.getDiscountList();
1323
1491
  }
1324
-
1325
1492
  /** 读取 Discount 模块原始券列表(未经过 bookingTime 等过滤)。 */
1326
1493
  getOriginalDiscountList() {
1327
- if (!this.store.order) return [];
1328
- const discountModule = this.store.order.store?.discount;
1329
- return discountModule?.getOriginalDiscountList?.() || [];
1494
+ var _a, _b;
1495
+ if (!this.store.order)
1496
+ return [];
1497
+ const discountModule = (_a = this.store.order.store) == null ? void 0 : _a.discount;
1498
+ return ((_b = discountModule == null ? void 0 : discountModule.getOriginalDiscountList) == null ? void 0 : _b.call(discountModule)) || [];
1330
1499
  }
1331
-
1332
1500
  /**
1333
1501
  * 同步写入 Discount 模块的 discountList / originalDiscountList。
1334
1502
  * 供 Holder 补全等场景在 OS store 层更新 machinecode holder 字段。
1335
1503
  */
1336
1504
  async replaceDiscountStoreLists(params) {
1337
- if (!this.store.order) throw new Error('order 模块未初始化');
1338
- const discountModule = this.store.order.store?.discount;
1339
- if (!discountModule) return;
1505
+ var _a;
1506
+ if (!this.store.order)
1507
+ throw new Error("order 模块未初始化");
1508
+ const discountModule = (_a = this.store.order.store) == null ? void 0 : _a.discount;
1509
+ if (!discountModule)
1510
+ return;
1340
1511
  if (params.originalDiscountList) {
1341
1512
  await discountModule.setOriginalDiscountList(params.originalDiscountList);
1342
1513
  }
@@ -1344,15 +1515,14 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1344
1515
  }
1345
1516
  async scanPromotionCode(code, customerId) {
1346
1517
  try {
1347
- if (!this.store.order) throw new Error('order 模块未初始化');
1518
+ if (!this.store.order)
1519
+ throw new Error("order 模块未初始化");
1348
1520
  const raw = await this.store.order.scanCode(code, customerId);
1349
1521
  if (raw.isAvailable) {
1350
- await this.store.order.recalculateSummary({
1351
- createIfMissing: true
1352
- });
1522
+ await this.store.order.recalculateSummary({ createIfMissing: true });
1353
1523
  this.store.order.persistTempOrder();
1354
1524
  const tempOrder = this.store.order.ensureTempOrder();
1355
- await this.effectsEmit('onDiscountApplied', {
1525
+ await this.effectsEmit("onDiscountApplied", {
1356
1526
  productList: tempOrder.products || [],
1357
1527
  discountList: this.store.order.getDiscountList(),
1358
1528
  selectedDiscountList: tempOrder.discount_list || [],
@@ -1369,46 +1539,55 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1369
1539
  throw error;
1370
1540
  }
1371
1541
  }
1372
-
1373
1542
  // TODO 需要优化,这段逻辑太长了,里面应该有些历史遗留问题
1374
1543
  async setDiscountSelected(params) {
1544
+ var _a, _b, _c, _d, _e, _f, _g;
1375
1545
  try {
1376
- if (!this.store.order) throw new Error('order 模块未初始化');
1546
+ if (!this.store.order)
1547
+ throw new Error("order 模块未初始化");
1377
1548
  const list = this.store.order.getDiscountList();
1378
- const updated = list.map(d => d.id === params.discountId && !isBaseSalesHistoricalDiscountEntry(d) ? {
1379
- ...d,
1380
- isSelected: params.isSelected,
1381
- isManualSelect: !params.isSelected
1382
- } : d);
1549
+ const updated = list.map(
1550
+ (d) => d.id === params.discountId && !isBaseSalesHistoricalDiscountEntry(d) ? {
1551
+ ...d,
1552
+ isSelected: params.isSelected,
1553
+ isManualSelect: !params.isSelected
1554
+ } : d
1555
+ );
1383
1556
  this.hasManualDiscountSelection = true;
1384
1557
  const tempOrder = this.store.order.ensureTempOrder();
1385
1558
  const orderStore = this.store.order.store || {};
1386
1559
  const discountModule = orderStore.discount;
1387
1560
  const rulesModule = orderStore.rules;
1388
1561
  let nextDiscountList = updated;
1389
- await discountModule?.setDiscountList(updated);
1562
+ await (discountModule == null ? void 0 : discountModule.setDiscountList(updated));
1390
1563
  if (rulesModule) {
1391
- const orderTotalAmount = Number(orderStore.summary?.total_amount || 0);
1392
- const result = rulesModule.calcDiscount({
1393
- productList: tempOrder.products,
1394
- discountList: updated,
1395
- holders: [],
1396
- isFormSubject: product => (0, _utils.resolveIsFormSubject)(tempOrder, product),
1397
- orderTotalAmount
1398
- }, {
1399
- discountId: params.discountId,
1400
- isSelected: params.isSelected
1401
- }) || {
1402
- productList: tempOrder.products,
1403
- discountList: updated
1404
- };
1405
- if (result?.productList) {
1406
- tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
1564
+ const orderTotalAmount = Number(((_a = orderStore.summary) == null ? void 0 : _a.total_amount) || 0);
1565
+ console.log("[BaseSales.setDiscountSelected.calcDiscount]");
1566
+ const result = rulesModule.calcDiscount(
1567
+ {
1568
+ productList: tempOrder.products,
1569
+ discountList: updated,
1570
+ holders: [],
1571
+ isFormSubject: (product) => (0, import_utils.resolveIsFormSubject)(tempOrder, product),
1572
+ orderTotalAmount
1573
+ },
1574
+ {
1575
+ discountId: params.discountId,
1576
+ isSelected: params.isSelected
1577
+ }
1578
+ ) || { productList: tempOrder.products, discountList: updated };
1579
+ if (result == null ? void 0 : result.productList) {
1580
+ tempOrder.products = preserveManualProductDiscountProducts(
1581
+ tempOrder.products,
1582
+ result.productList
1583
+ );
1407
1584
  }
1408
- if (result?.discountList) {
1585
+ if (result == null ? void 0 : result.discountList) {
1409
1586
  nextDiscountList = result.discountList;
1410
1587
  if (!params.isSelected) {
1411
- const beforeSelectedIds = new Set(updated.filter(d => d.isSelected).map(d => d.id));
1588
+ const beforeSelectedIds = new Set(
1589
+ updated.filter((d) => d.isSelected).map((d) => d.id)
1590
+ );
1412
1591
  for (const d of nextDiscountList) {
1413
1592
  if (d.isSelected && !beforeSelectedIds.has(d.id)) {
1414
1593
  d.isSelected = false;
@@ -1419,57 +1598,58 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1419
1598
  }
1420
1599
  }
1421
1600
  }
1422
- const selectedResourceIds = new Set(nextDiscountList.filter(d => d.isSelected).map(d => d.id));
1423
- const filterSelectedDiscountDetails = discountList => (discountList || []).filter(pd => {
1424
- const rid = pd.discount?.resource_id ?? pd.id;
1601
+ const selectedResourceIds = new Set(
1602
+ nextDiscountList.filter((d) => d.isSelected).map((d) => d.id)
1603
+ );
1604
+ const filterSelectedDiscountDetails = (discountList) => (discountList || []).filter((pd) => {
1605
+ var _a2;
1606
+ const rid = ((_a2 = pd.discount) == null ? void 0 : _a2.resource_id) ?? pd.id;
1425
1607
  return rid != null && selectedResourceIds.has(rid);
1426
1608
  });
1427
1609
  for (const product of tempOrder.products) {
1428
- const productUid = product.metadata?.unique_identification_number;
1429
- const runtimeOrigin = productUid ? tempOrder._extend?.productsByUid?.[productUid]?.origin : undefined;
1430
- if (runtimeOrigin?.isManualDiscount || isBaseSalesManualProductDiscountProduct(product)) continue;
1610
+ const productUid = (_b = product.metadata) == null ? void 0 : _b.unique_identification_number;
1611
+ const runtimeOrigin = productUid ? (_e = (_d = (_c = tempOrder._extend) == null ? void 0 : _c.productsByUid) == null ? void 0 : _d[productUid]) == null ? void 0 : _e.origin : void 0;
1612
+ if ((runtimeOrigin == null ? void 0 : runtimeOrigin.isManualDiscount) || isBaseSalesManualProductDiscountProduct(product))
1613
+ continue;
1431
1614
  product.discount_list = filterSelectedDiscountDetails(product.discount_list);
1432
1615
  if (Array.isArray(product.product_bundle)) {
1433
- product.product_bundle = product.product_bundle.map(bundle => {
1434
- const nextBundleDiscountList = filterSelectedDiscountDetails(bundle?.discount_list);
1616
+ product.product_bundle = product.product_bundle.map((bundle) => {
1617
+ const nextBundleDiscountList = filterSelectedDiscountDetails(bundle == null ? void 0 : bundle.discount_list);
1435
1618
  const shouldRestoreBundlePrice = nextBundleDiscountList.length === 0;
1436
- const restoredBundlePrice = bundle?.original_price ?? bundle?.product_price ?? bundle?.price;
1619
+ const restoredBundlePrice = (bundle == null ? void 0 : bundle.original_price) ?? (bundle == null ? void 0 : bundle.product_price) ?? (bundle == null ? void 0 : bundle.price);
1437
1620
  return {
1438
1621
  ...bundle,
1439
- ...(shouldRestoreBundlePrice ? {
1622
+ ...shouldRestoreBundlePrice ? {
1440
1623
  price: restoredBundlePrice,
1441
1624
  bundle_selling_price: restoredBundlePrice
1442
- } : {}),
1625
+ } : {},
1443
1626
  discount_list: nextBundleDiscountList
1444
1627
  };
1445
1628
  });
1446
1629
  }
1447
-
1448
- // 券作用于 source(不含 option、不含 bundle);算出新 source 折后价后补回 options
1449
- // 写入含 option 的 main_product_selling_price,再合成 composite 回写 selling_price。
1450
- const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + (pd.amount || 0), 0);
1451
- // TODO 这块逻辑需要拿掉
1452
- const optionSum = (0, _utils.sumOptionUnitPrice)((0, _utils.getProductSkuOptions)(product));
1453
- const sourcePrice = product.metadata?.source_product_price ?? (product.metadata?.main_product_original_price != null ? new _decimal.default(Number(product.metadata.main_product_original_price) || 0).minus(optionSum).toFixed(2) : product.original_price ?? '0');
1454
- const newSourceSellingPrice = new _decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
1455
- const newMainSellingPrice = new _decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
1630
+ const totalPerUnitDiscount = (product.discount_list || []).reduce(
1631
+ (sum, pd) => sum + (pd.amount || 0),
1632
+ 0
1633
+ );
1634
+ const optionSum = (0, import_utils.sumOptionUnitPrice)((0, import_utils.getProductSkuOptions)(product));
1635
+ const sourcePrice = ((_f = product.metadata) == null ? void 0 : _f.source_product_price) ?? (((_g = product.metadata) == null ? void 0 : _g.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");
1636
+ const newSourceSellingPrice = new import_decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
1637
+ const newMainSellingPrice = new import_decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
1456
1638
  if (product.metadata) {
1457
1639
  product.metadata.main_product_selling_price = newMainSellingPrice;
1458
1640
  product.metadata.price_schema_version = 2;
1459
1641
  }
1460
- product.selling_price = (0, _utils.composeLinePrice)({
1642
+ product.selling_price = (0, import_utils.composeLinePrice)({
1461
1643
  mainPrice: newMainSellingPrice,
1462
1644
  bundle: product.product_bundle
1463
1645
  });
1464
1646
  }
1465
- _Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1466
- await discountModule?.setDiscountList(nextDiscountList);
1467
- tempOrder.discount_list = (nextDiscountList || []).filter(d => d.isSelected);
1468
- await this.store.order.recalculateSummary({
1469
- createIfMissing: true
1470
- });
1647
+ import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1648
+ await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1649
+ tempOrder.discount_list = (nextDiscountList || []).filter((d) => d.isSelected);
1650
+ await this.store.order.recalculateSummary({ createIfMissing: true });
1471
1651
  this.store.order.persistTempOrder();
1472
- this.effectsEmit('onDiscountApplied', {
1652
+ this.effectsEmit("onDiscountApplied", {
1473
1653
  productList: tempOrder.products,
1474
1654
  discountList: nextDiscountList,
1475
1655
  selectedDiscountList: tempOrder.discount_list,
@@ -1481,24 +1661,32 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1481
1661
  }
1482
1662
  async applyDiscountCalculationResult(result) {
1483
1663
  try {
1484
- if (!this.store.order) throw new Error('order 模块未初始化');
1485
- if (!result) return;
1664
+ if (!this.store.order)
1665
+ throw new Error("order 模块未初始化");
1666
+ if (!result)
1667
+ return;
1486
1668
  const tempOrder = this.store.order.ensureTempOrder();
1487
1669
  const orderStore = this.store.order.store || {};
1488
1670
  const discountModule = orderStore.discount;
1489
1671
  if (result.productList) {
1490
- tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
1672
+ tempOrder.products = preserveManualProductDiscountProducts(
1673
+ tempOrder.products,
1674
+ result.productList
1675
+ );
1491
1676
  }
1492
1677
  if (result.discountList) {
1493
- _Order.OrderModule.populateSavedAmounts(tempOrder.products, result.discountList);
1494
- await discountModule?.setDiscountList(result.discountList);
1495
- tempOrder.discount_list = result.discountList.filter(discount => discount.isSelected);
1678
+ import_Order.OrderModule.populateSavedAmounts(
1679
+ tempOrder.products,
1680
+ result.discountList
1681
+ );
1682
+ await (discountModule == null ? void 0 : discountModule.setDiscountList(result.discountList));
1683
+ tempOrder.discount_list = result.discountList.filter(
1684
+ (discount) => discount.isSelected
1685
+ );
1496
1686
  }
1497
- await this.store.order.recalculateSummary({
1498
- createIfMissing: true
1499
- });
1687
+ await this.store.order.recalculateSummary({ createIfMissing: true });
1500
1688
  this.store.order.persistTempOrder();
1501
- await this.effectsEmit('onDiscountApplied', {
1689
+ await this.effectsEmit("onDiscountApplied", {
1502
1690
  productList: tempOrder.products || [],
1503
1691
  discountList: result.discountList || [],
1504
1692
  selectedDiscountList: tempOrder.discount_list || [],
@@ -1509,10 +1697,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1509
1697
  }
1510
1698
  }
1511
1699
  async submitScanOrder(params) {
1512
- // Deprecated compatibility alias. New BaseSales callers should use submitSalesOrder.
1513
1700
  return this.submitSalesOrder(params);
1514
1701
  }
1515
-
1516
1702
  /**
1517
1703
  * 提交当前 Sales 订单。
1518
1704
  *
@@ -1520,97 +1706,74 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1520
1706
  * payments 会交给 OrderModule 统一映射为 Sales 协议支付项。
1521
1707
  */
1522
1708
  async submitSalesOrder(params) {
1709
+ var _a, _b, _c, _d;
1523
1710
  if (!this.store.order) {
1524
- throw new Error('BaseSales 解决方案需要 order 模块支持');
1711
+ throw new Error("BaseSales 解决方案需要 order 模块支持");
1525
1712
  }
1526
- // this.store.order.persistTempOrder();
1527
- const inferredPaymentStatus = this.getSubmitPaymentStatus(params?.paymentStatus);
1528
- const smallTicketDataFlag = params?.smallTicketDataFlag ?? this.getDefaultCheckoutSmallTicketDataFlag();
1713
+ const inferredPaymentStatus = this.getSubmitPaymentStatus(params == null ? void 0 : params.paymentStatus);
1714
+ const smallTicketDataFlag = (params == null ? void 0 : params.smallTicketDataFlag) ?? this.getDefaultCheckoutSmallTicketDataFlag();
1529
1715
  const submitParams = {
1530
1716
  cacheId: this.cacheId,
1531
- platform: this.otherParams?.platform,
1532
- businessCode: this.otherParams?.businessCode || this.otherParams?.business_code,
1717
+ platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
1718
+ businessCode: ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1533
1719
  channel: this.getSubmitOrderSalesChannel(),
1534
- type: this.otherParams?.type,
1720
+ type: (_d = this.otherParams) == null ? void 0 : _d.type,
1535
1721
  request_unique_idempotency_token: this.store.order.generateIdempotencyToken(),
1536
- ...(params?.payments !== undefined ? {
1537
- payments: params.payments
1538
- } : {}),
1539
- ...(inferredPaymentStatus !== undefined ? {
1540
- paymentStatus: inferredPaymentStatus
1541
- } : {}),
1542
- ...(smallTicketDataFlag !== undefined ? {
1543
- smallTicketDataFlag
1544
- } : {}),
1545
- ...(params?.confirmPendingVoucherPayments !== undefined ? {
1546
- confirmPendingVoucherPayments: params.confirmPendingVoucherPayments
1547
- } : {}),
1548
- ...(params?.enhancePayload !== undefined ? {
1549
- enhancePayload: params.enhancePayload
1550
- } : {})
1722
+ ...(params == null ? void 0 : params.payments) !== void 0 ? { payments: params.payments } : {},
1723
+ ...inferredPaymentStatus !== void 0 ? { paymentStatus: inferredPaymentStatus } : {},
1724
+ ...smallTicketDataFlag !== void 0 ? { smallTicketDataFlag } : {},
1725
+ ...(params == null ? void 0 : params.confirmPendingVoucherPayments) !== void 0 ? { confirmPendingVoucherPayments: params.confirmPendingVoucherPayments } : {},
1726
+ ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
1551
1727
  };
1552
1728
  return this.shouldUseCheckoutSyncTask() ? this.store.order.submitTempOrder(submitParams) : this.store.order.submitTempOrderAsync(submitParams);
1553
1729
  }
1554
1730
  async submitTempOrderAsync(params) {
1731
+ var _a, _b, _c, _d;
1555
1732
  if (!this.store.order) {
1556
- throw new Error('BaseSales 解决方案需要 order 模块支持');
1733
+ throw new Error("BaseSales 解决方案需要 order 模块支持");
1557
1734
  }
1558
- const inferredPaymentStatus = this.getSubmitPaymentStatus(params?.paymentStatus);
1559
- const smallTicketDataFlag = params?.smallTicketDataFlag ?? this.getDefaultCheckoutSmallTicketDataFlag();
1735
+ const inferredPaymentStatus = this.getSubmitPaymentStatus(params == null ? void 0 : params.paymentStatus);
1736
+ const smallTicketDataFlag = (params == null ? void 0 : params.smallTicketDataFlag) ?? this.getDefaultCheckoutSmallTicketDataFlag();
1560
1737
  const submitParams = {
1561
1738
  cacheId: this.cacheId,
1562
- platform: this.otherParams?.platform,
1563
- businessCode: this.otherParams?.businessCode || this.otherParams?.business_code,
1739
+ platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
1740
+ businessCode: ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1564
1741
  channel: this.getSubmitOrderSalesChannel(),
1565
- type: this.otherParams?.type,
1742
+ type: (_d = this.otherParams) == null ? void 0 : _d.type,
1566
1743
  request_unique_idempotency_token: this.store.order.generateIdempotencyToken(),
1567
- ...(params?.payments !== undefined ? {
1568
- payments: params.payments
1569
- } : {}),
1570
- ...(inferredPaymentStatus !== undefined ? {
1571
- paymentStatus: inferredPaymentStatus
1572
- } : {}),
1573
- ...(smallTicketDataFlag !== undefined ? {
1574
- smallTicketDataFlag
1575
- } : {}),
1576
- ...(params?.confirmPendingVoucherPayments !== undefined ? {
1577
- confirmPendingVoucherPayments: params.confirmPendingVoucherPayments
1578
- } : {}),
1579
- ...(params?.enhancePayload !== undefined ? {
1580
- enhancePayload: params.enhancePayload
1581
- } : {})
1744
+ ...(params == null ? void 0 : params.payments) !== void 0 ? { payments: params.payments } : {},
1745
+ ...inferredPaymentStatus !== void 0 ? { paymentStatus: inferredPaymentStatus } : {},
1746
+ ...smallTicketDataFlag !== void 0 ? { smallTicketDataFlag } : {},
1747
+ ...(params == null ? void 0 : params.confirmPendingVoucherPayments) !== void 0 ? { confirmPendingVoucherPayments: params.confirmPendingVoucherPayments } : {},
1748
+ ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
1582
1749
  };
1583
1750
  return this.store.order.submitTempOrderAsync(submitParams);
1584
1751
  }
1585
-
1586
1752
  /**
1587
1753
  * 默认保持 WebPOS 的本地待同步订单模式;需要云端确认后才算成功的渠道可覆盖此策略。
1588
1754
  * otherParams.checkoutSyncTaskEnabled 优先,便于同一 solution 按入口恢复旧行为。
1589
1755
  */
1590
1756
  shouldUseCheckoutSyncTask() {
1591
- const configured = this.otherParams?.checkoutSyncTaskEnabled;
1592
- return typeof configured === 'boolean' ? configured : true;
1757
+ var _a;
1758
+ const configured = (_a = this.otherParams) == null ? void 0 : _a.checkoutSyncTaskEnabled;
1759
+ return typeof configured === "boolean" ? configured : true;
1593
1760
  }
1594
-
1595
1761
  /** 可由特定 solution 为真实 checkout 补充默认收据数据请求。 */
1596
1762
  getDefaultCheckoutSmallTicketDataFlag() {
1597
- return undefined;
1763
+ return void 0;
1598
1764
  }
1599
1765
  async printLocalOrderReceipt(lookup) {
1766
+ var _a, _b, _c, _d, _e, _f, _g;
1600
1767
  if (!this.store.order) {
1601
- throw new Error('BaseSales 解决方案需要 order 模块支持');
1768
+ throw new Error("BaseSales 解决方案需要 order 模块支持");
1602
1769
  }
1603
- const hasLookup = lookup !== undefined && lookup !== null && lookup !== '';
1604
- const lookupPayload = typeof lookup === 'number' ? {
1605
- order_id: lookup
1606
- } : {
1607
- external_sale_number: lookup
1608
- };
1770
+ const hasLookup = lookup !== void 0 && lookup !== null && lookup !== "";
1771
+ const lookupPayload = typeof lookup === "number" ? { order_id: lookup } : { external_sale_number: lookup };
1609
1772
  const context = {
1610
- platform: this.otherParams?.platform,
1611
- businessCode: this.otherParams?.businessCode || this.otherParams?.business_code,
1773
+ platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
1774
+ businessCode: ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1612
1775
  channel: this.getSubmitOrderSalesChannel(),
1613
- type: this.otherParams?.type
1776
+ type: (_d = this.otherParams) == null ? void 0 : _d.type
1614
1777
  };
1615
1778
  const payload = hasLookup ? {
1616
1779
  ...lookupPayload,
@@ -1627,46 +1790,48 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1627
1790
  channel: context.channel,
1628
1791
  type: context.type
1629
1792
  });
1630
- const response = await this.request.post('/local/print-order', payload, {
1793
+ const response = await this.request.post("/local/print-order", payload, {
1631
1794
  osServer: true,
1632
- customToast: () => {}
1795
+ customToast: () => {
1796
+ }
1633
1797
  });
1634
1798
  if (!hasLookup) {
1635
- await this.store.order.applyLocalPrintOrderNumbers?.(response?.data?.order);
1799
+ await ((_g = (_f = this.store.order).applyLocalPrintOrderNumbers) == null ? void 0 : _g.call(_f, (_e = response == null ? void 0 : response.data) == null ? void 0 : _e.order));
1636
1800
  }
1637
1801
  return response;
1638
1802
  }
1639
1803
  getSubmitPaymentStatus(paymentStatus) {
1640
- if (paymentStatus !== undefined) return paymentStatus;
1641
- const amountSnapshot = this.store.order?.getOrderAmountSnapshot?.();
1642
- if (!amountSnapshot) return undefined;
1804
+ var _a, _b;
1805
+ if (paymentStatus !== void 0)
1806
+ return paymentStatus;
1807
+ const amountSnapshot = (_b = (_a = this.store.order) == null ? void 0 : _a.getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
1808
+ if (!amountSnapshot)
1809
+ return void 0;
1643
1810
  try {
1644
- return new _decimal.default(amountSnapshot.amountGap || 0).lte(0) ? 'paid' : undefined;
1811
+ return new import_decimal.default(amountSnapshot.amountGap || 0).lte(0) ? "paid" : void 0;
1645
1812
  } catch {
1646
- return undefined;
1813
+ return void 0;
1647
1814
  }
1648
1815
  }
1649
1816
  async syncPaymentsToOrder(params) {
1650
- if (!this.store.order) throw new Error('order 模块未初始化');
1651
- const businessCode = params.businessCode ?? this.otherParams?.businessCode ?? this.otherParams?.business_code;
1817
+ var _a, _b;
1818
+ if (!this.store.order)
1819
+ throw new Error("order 模块未初始化");
1820
+ const businessCode = params.businessCode ?? ((_a = this.otherParams) == null ? void 0 : _a.businessCode) ?? ((_b = this.otherParams) == null ? void 0 : _b.business_code);
1652
1821
  const channel = params.channel ?? this.getSubmitOrderSalesChannel();
1653
1822
  const syncParams = {
1654
1823
  ...params,
1655
1824
  checkoutSyncTaskEnabled: this.shouldUseCheckoutSyncTask(),
1656
- ...(businessCode !== undefined ? {
1657
- businessCode
1658
- } : {}),
1659
- ...(channel !== undefined ? {
1660
- channel
1661
- } : {})
1825
+ ...businessCode !== void 0 ? { businessCode } : {},
1826
+ ...channel !== void 0 ? { channel } : {}
1662
1827
  };
1663
1828
  const syncState = this.store.order.getOrderSyncState();
1664
- if (params.submitWhenPaid && syncState === 'submitting') {
1829
+ if (params.submitWhenPaid && syncState === "submitting") {
1665
1830
  this.queueLatestAutoPaymentSync();
1666
1831
  return this.store.order.syncPaymentsToOrder(syncParams);
1667
1832
  }
1668
1833
  const payments = params.payments || [];
1669
- await this.effectsEmit(_types.BaseSalesHookNames.onPaymentSyncStart, {
1834
+ await this.effectsEmit(import_types.BaseSalesHookNames.onPaymentSyncStart, {
1670
1835
  payments,
1671
1836
  params: syncParams,
1672
1837
  amountSnapshot: this.store.order.getOrderAmountSnapshot(),
@@ -1691,14 +1856,14 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1691
1856
  depositAmount: syncResult.depositAmount,
1692
1857
  orderExpectedAmount: syncResult.orderExpectedAmount
1693
1858
  };
1694
- await this.effectsEmit(_types.BaseSalesHookNames.onPaymentSyncEnd, syncPayload);
1859
+ await this.effectsEmit(import_types.BaseSalesHookNames.onPaymentSyncEnd, syncPayload);
1695
1860
  if (syncResult.isDepositFullyPaid && !syncResult.isOrderFullyPaid) {
1696
- await this.effectsEmit(_types.BaseSalesHookNames.onDepositPaymentSyncEnd, syncPayload);
1861
+ await this.effectsEmit(import_types.BaseSalesHookNames.onDepositPaymentSyncEnd, syncPayload);
1697
1862
  }
1698
1863
  this.scheduleQueuedAutoPaymentSyncFlush(0);
1699
1864
  return syncResult;
1700
1865
  } catch (error) {
1701
- await this.effectsEmit(_types.BaseSalesHookNames.onPaymentSyncEnd, {
1866
+ await this.effectsEmit(import_types.BaseSalesHookNames.onPaymentSyncEnd, {
1702
1867
  ok: false,
1703
1868
  error,
1704
1869
  payments: this.store.order.getOrderPayments(),
@@ -1710,41 +1875,46 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1710
1875
  throw error;
1711
1876
  }
1712
1877
  }
1713
-
1714
1878
  /** 读取当前 BaseSales 订单上下文中的 Sales 协议支付项。 */
1715
1879
  getOrderPayments() {
1716
- if (!this.store.order) return [];
1880
+ if (!this.store.order)
1881
+ return [];
1717
1882
  const payments = this.store.order.getOrderPayments();
1718
1883
  return this.hydrateOrderPaymentNames(payments);
1719
1884
  }
1720
-
1721
1885
  /** 覆盖当前订单支付项,内部由 OrderModule 清洗为 Sales 协议字段。 */
1722
1886
  setOrderPayments(payments) {
1723
- if (!this.store.order) throw new Error('order 模块未初始化');
1887
+ if (!this.store.order)
1888
+ throw new Error("order 模块未初始化");
1724
1889
  return this.store.order.setOrderPayments(payments);
1725
1890
  }
1726
1891
  getPaymentStatusForSync(payments) {
1727
1892
  const order = this.store.order;
1728
- if (!order) throw new Error('order 模块未初始化');
1893
+ if (!order)
1894
+ throw new Error("order 模块未初始化");
1729
1895
  const completion = order.getPaymentCompletion(payments);
1730
- return completion.isOrderFullyPaid ? 'paid' : 'partially_paid';
1896
+ return completion.isOrderFullyPaid ? "paid" : "partially_paid";
1731
1897
  }
1732
1898
  queueLatestAutoPaymentSync() {
1733
1899
  this.queuedAutoPaymentSync = true;
1734
1900
  this.scheduleQueuedAutoPaymentSyncFlush();
1735
1901
  }
1736
1902
  scheduleQueuedAutoPaymentSyncFlush(delay = 100) {
1737
- if (!this.queuedAutoPaymentSync) return;
1738
- if (this.autoPaymentSyncTimer) return;
1903
+ if (!this.queuedAutoPaymentSync)
1904
+ return;
1905
+ if (this.autoPaymentSyncTimer)
1906
+ return;
1739
1907
  this.autoPaymentSyncTimer = setTimeout(() => {
1740
1908
  this.autoPaymentSyncTimer = null;
1741
1909
  void this.flushQueuedAutoPaymentSync();
1742
1910
  }, delay);
1743
1911
  }
1744
1912
  async flushQueuedAutoPaymentSync() {
1745
- if (!this.store.order) return;
1746
- if (!this.queuedAutoPaymentSync || this.autoPaymentSyncFlushing) return;
1747
- if (this.store.order.getOrderSyncState() === 'submitting') {
1913
+ if (!this.store.order)
1914
+ return;
1915
+ if (!this.queuedAutoPaymentSync || this.autoPaymentSyncFlushing)
1916
+ return;
1917
+ if (this.store.order.getOrderSyncState() === "submitting") {
1748
1918
  this.scheduleQueuedAutoPaymentSyncFlush();
1749
1919
  return;
1750
1920
  }
@@ -1753,7 +1923,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1753
1923
  while (this.queuedAutoPaymentSync) {
1754
1924
  this.queuedAutoPaymentSync = false;
1755
1925
  const payments = this.store.order.getOrderPayments();
1756
- if (!payments.length) continue;
1926
+ if (!payments.length)
1927
+ continue;
1757
1928
  await this.syncPaymentsToOrder({
1758
1929
  payments,
1759
1930
  paymentStatus: this.getPaymentStatusForSync(payments),
@@ -1762,7 +1933,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1762
1933
  });
1763
1934
  }
1764
1935
  } catch (error) {
1765
- this.logError('queued auto sync payments failed', {
1936
+ this.logError("queued auto sync payments failed", {
1766
1937
  error: error instanceof Error ? error.message : String(error)
1767
1938
  });
1768
1939
  } finally {
@@ -1772,38 +1943,35 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1772
1943
  }
1773
1944
  }
1774
1945
  }
1775
-
1776
1946
  /** 追加单个支付项到当前订单。 */
1777
1947
  addOrderPayment(payment) {
1778
- if (!this.store.order) throw new Error('order 模块未初始化');
1948
+ var _a;
1949
+ if (!this.store.order)
1950
+ throw new Error("order 模块未初始化");
1779
1951
  const paymentRecord = payment;
1780
- const paymentAmount = new _decimal.default(paymentRecord.amount || 0);
1952
+ const paymentAmount = new import_decimal.default(paymentRecord.amount || 0);
1781
1953
  if (paymentAmount.isZero()) {
1782
- this.logWarning('addOrderPayment: 支付金额为 0,跳过添加支付项', {
1954
+ this.logWarning("addOrderPayment: 支付金额为 0,跳过添加支付项", {
1783
1955
  payment: paymentRecord
1784
1956
  });
1785
1957
  return this.store.order.getOrderPayments();
1786
1958
  }
1787
- const metadata = paymentRecord.metadata && typeof paymentRecord.metadata === 'object' ? {
1788
- ...paymentRecord.metadata
1789
- } : {};
1790
- const shopWalletPassId = this.otherParams?.shop_wallet_pass_id;
1791
- if (shopWalletPassId !== undefined && shopWalletPassId !== null) {
1959
+ const metadata = paymentRecord.metadata && typeof paymentRecord.metadata === "object" ? { ...paymentRecord.metadata } : {};
1960
+ const shopWalletPassId = (_a = this.otherParams) == null ? void 0 : _a.shop_wallet_pass_id;
1961
+ if (shopWalletPassId !== void 0 && shopWalletPassId !== null) {
1792
1962
  metadata.shop_wallet_pass_id = shopWalletPassId;
1793
1963
  }
1794
1964
  if (!metadata.unique_payment_number) {
1795
- metadata.unique_payment_number = (0, _utils.createUuidV4)();
1965
+ metadata.unique_payment_number = (0, import_utils.createUuidV4)();
1796
1966
  }
1797
- const paymentTimestamp = (0, _dayjs.default)().format('YYYY-MM-DD HH:mm:ss');
1967
+ const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
1798
1968
  const paymentTime = paymentRecord.payment_time ?? paymentTimestamp;
1799
1969
  const createdAt = paymentRecord.created_at ?? paymentTimestamp;
1800
- const serviceCharge = paymentRecord.service_charge && typeof paymentRecord.service_charge === 'object' ? paymentRecord.service_charge : null;
1801
- const calculatedServiceFee = serviceCharge ? new _decimal.default(paymentRecord.origin_amount ?? paymentRecord.amount ?? 0).times(serviceCharge.percentage || 0).plus(serviceCharge.amount || 0).toDecimalPlaces(2).toFixed(2) : undefined;
1970
+ const serviceCharge = paymentRecord.service_charge && typeof paymentRecord.service_charge === "object" ? paymentRecord.service_charge : null;
1971
+ const calculatedServiceFee = serviceCharge ? new import_decimal.default(paymentRecord.origin_amount ?? paymentRecord.amount ?? 0).times(serviceCharge.percentage || 0).plus(serviceCharge.amount || 0).toDecimalPlaces(2).toFixed(2) : void 0;
1802
1972
  const payments = this.store.order.addOrderPayment({
1803
1973
  ...paymentRecord,
1804
- ...(calculatedServiceFee !== undefined ? {
1805
- service_fee: calculatedServiceFee
1806
- } : {}),
1974
+ ...calculatedServiceFee !== void 0 ? { service_fee: calculatedServiceFee } : {},
1807
1975
  metadata,
1808
1976
  payment_time: paymentTime,
1809
1977
  created_at: createdAt
@@ -1811,7 +1979,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1811
1979
  const amountSnapshot = this.store.order.getOrderAmountSnapshot();
1812
1980
  const syncState = this.store.order.getOrderSyncState();
1813
1981
  if (amountSnapshot) {
1814
- if (syncState === 'submitting') {
1982
+ if (syncState === "submitting") {
1815
1983
  this.queueLatestAutoPaymentSync();
1816
1984
  return payments;
1817
1985
  }
@@ -1820,55 +1988,55 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1820
1988
  paymentStatus: this.getPaymentStatusForSync(payments),
1821
1989
  submitWhenPaid: true,
1822
1990
  smallTicketDataFlag: 1
1823
- }).catch(error => {
1824
- this.logError('auto sync payments failed', {
1991
+ }).catch((error) => {
1992
+ this.logError("auto sync payments failed", {
1825
1993
  error: error instanceof Error ? error.message : String(error)
1826
1994
  });
1827
1995
  });
1828
1996
  }
1829
1997
  return payments;
1830
1998
  }
1831
-
1832
1999
  /** 更新当前订单中的指定支付项。 */
1833
2000
  updateOrderPayment(paymentIdentity, updates) {
1834
- if (!this.store.order) throw new Error('order 模块未初始化');
2001
+ if (!this.store.order)
2002
+ throw new Error("order 模块未初始化");
1835
2003
  return this.store.order.updateOrderPayment(paymentIdentity, updates);
1836
2004
  }
1837
-
1838
2005
  /** 删除当前订单中的指定支付项。 */
1839
2006
  deleteOrderPayment(paymentIdentity) {
1840
- if (!this.store.order) throw new Error('order 模块未初始化');
2007
+ if (!this.store.order)
2008
+ throw new Error("order 模块未初始化");
1841
2009
  return this.store.order.deleteOrderPayment(paymentIdentity);
1842
2010
  }
1843
-
1844
2011
  /** 覆盖 wallet pass 支付项,同时保留普通支付项。 */
1845
2012
  updateVoucherOrderPayments(payments, options) {
1846
- if (!this.store.order) throw new Error('order 模块未初始化');
2013
+ if (!this.store.order)
2014
+ throw new Error("order 模块未初始化");
1847
2015
  return this.store.order.updateVoucherOrderPayments(payments, options);
1848
2016
  }
1849
2017
  confirmPendingVoucherPayments() {
1850
- if (!this.store.order) throw new Error('order 模块未初始化');
2018
+ if (!this.store.order)
2019
+ throw new Error("order 模块未初始化");
1851
2020
  return this.store.order.confirmPendingVoucherPayments();
1852
2021
  }
1853
2022
  discardPendingVoucherPayments() {
1854
- if (!this.store.order) throw new Error('order 模块未初始化');
2023
+ if (!this.store.order)
2024
+ throw new Error("order 模块未初始化");
1855
2025
  return this.store.order.discardPendingVoucherPayments();
1856
2026
  }
1857
2027
  getWalletProductList() {
1858
- const tempOrder = this.store.order?.getTempOrder();
1859
- if (!tempOrder?.products?.length) return [];
1860
- // 过滤出有 product_id的商品来,如果没有代表他是自定义商品,不需要参与 wallet
1861
- // debugger
1862
- // const products = tempOrder?.products?.filter(n => n.product_id)
1863
-
1864
- const walletProducts = tempOrder?.products.map(product => {
2028
+ var _a, _b;
2029
+ const tempOrder = (_a = this.store.order) == null ? void 0 : _a.getTempOrder();
2030
+ if (!((_b = tempOrder == null ? void 0 : tempOrder.products) == null ? void 0 : _b.length))
2031
+ return [];
2032
+ const walletProducts = tempOrder == null ? void 0 : tempOrder.products.map((product) => {
1865
2033
  const metadata = product.metadata || {};
1866
2034
  const rawHolderId = product.holder_id ?? metadata.holder_id;
1867
2035
  const holderIdValue = Array.isArray(rawHolderId) ? rawHolderId[0] : rawHolderId;
1868
- const holder_id = Number.isInteger(Number(holderIdValue)) ? Number(holderIdValue) : undefined;
2036
+ const holder_id = Number.isInteger(Number(holderIdValue)) ? Number(holderIdValue) : void 0;
1869
2037
  return {
1870
2038
  product_id: product.product_id || 0,
1871
- product_variant_id: String(product.product_variant_id ?? ''),
2039
+ product_variant_id: String(product.product_variant_id ?? ""),
1872
2040
  quantity: product.num || 1,
1873
2041
  is_price_include_tax: tempOrder.is_price_include_tax,
1874
2042
  is_charge_tax: product.is_charge_tax ?? 0,
@@ -1884,7 +2052,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1884
2052
  main_product_attached_bundle_surcharge_fee: metadata.main_product_attached_bundle_surcharge_fee,
1885
2053
  surcharge_rounding_remainder: metadata.surcharge_rounding_remainder
1886
2054
  },
1887
- product_bundle: (product.product_bundle || []).map(bundle => {
2055
+ product_bundle: (product.product_bundle || []).map((bundle) => {
1888
2056
  const bundleMetadata = bundle.metadata || {};
1889
2057
  return {
1890
2058
  is_price_include_tax: tempOrder.is_price_include_tax,
@@ -1911,11 +2079,13 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1911
2079
  return walletProducts;
1912
2080
  }
1913
2081
  async initWalletData(params) {
1914
- if (!this.store.order) throw new Error('order 模块未初始化');
1915
- if (!this.store.payment) throw new Error('payment 模块未初始化');
2082
+ if (!this.store.order)
2083
+ throw new Error("order 模块未初始化");
2084
+ if (!this.store.payment)
2085
+ throw new Error("payment 模块未初始化");
1916
2086
  const snapshot = this.store.order.getOrderSnapshot();
1917
- const tempOrder = snapshot?.tempOrder;
1918
- const amount = snapshot?.amount;
2087
+ const tempOrder = snapshot == null ? void 0 : snapshot.tempOrder;
2088
+ const amount = snapshot == null ? void 0 : snapshot.amount;
1919
2089
  if (!tempOrder || !amount) {
1920
2090
  return {
1921
2091
  walletRecommendList: [],
@@ -1926,7 +2096,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1926
2096
  };
1927
2097
  }
1928
2098
  const walletBusinessData = {
1929
- customer_id: tempOrder.customer_id ? Number(tempOrder.customer_id) : undefined,
2099
+ customer_id: tempOrder.customer_id ? Number(tempOrder.customer_id) : void 0,
1930
2100
  holder: tempOrder.holder,
1931
2101
  amountInfo: {
1932
2102
  totalAmount: amount.totalAmount,
@@ -1935,13 +2105,13 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1935
2105
  isDeposit: tempOrder.is_deposit
1936
2106
  },
1937
2107
  products: this.getWalletProductList(),
1938
- order_wait_pay_amount: params?.order_wait_pay_amount ?? Number(amount.amountGap || 0),
2108
+ order_wait_pay_amount: (params == null ? void 0 : params.order_wait_pay_amount) ?? Number(amount.amountGap || 0),
1939
2109
  is_price_include_tax: tempOrder.is_price_include_tax ?? this.otherParams.is_price_include_tax ?? 1,
1940
- ...(snapshot.identity.orderId ? {
1941
- payment_order_id: String(snapshot.identity.orderId)
1942
- } : {})
2110
+ ...snapshot.identity.orderId ? { payment_order_id: String(snapshot.identity.orderId) } : {}
1943
2111
  };
1944
- const result = await this.store.payment.wallet.initializeWalletDataFromBusinessAsync(walletBusinessData);
2112
+ const result = await this.store.payment.wallet.initializeWalletDataFromBusinessAsync(
2113
+ walletBusinessData
2114
+ );
1945
2115
  await this.core.effects.emit(`${this.name}:onWalletDataInitialized`, {
1946
2116
  orderId: snapshot.identity.orderId,
1947
2117
  customerId: walletBusinessData.customer_id,
@@ -1954,7 +2124,6 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1954
2124
  });
1955
2125
  return result;
1956
2126
  }
1957
-
1958
2127
  /**
1959
2128
  * 更新当前订单客户字段。
1960
2129
  *
@@ -1962,57 +2131,50 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1962
2131
  * 调用方通过 onCustomerChange 回调完成。
1963
2132
  */
1964
2133
  updateOrderCustomer(customer) {
1965
- if (!this.store.order) throw new Error('order 模块未初始化');
2134
+ if (!this.store.order)
2135
+ throw new Error("order 模块未初始化");
1966
2136
  const result = this.store.order.updateTempOrderCustomer(customer);
1967
- this.store.order.recalculateSummary({
1968
- createIfMissing: true
1969
- });
2137
+ this.store.order.recalculateSummary({ createIfMissing: true });
1970
2138
  this.store.order.persistTempOrder();
1971
2139
  return result;
1972
2140
  }
1973
-
1974
2141
  /** 获取可用支付方式列表,供 PaymentModal 渲染支付选项。 */
1975
2142
  async getPaymentMethodsAsync() {
1976
- // if (this.store.payment) {
1977
- // return this.store.payment.getPayMethodListAsync();
1978
- // }
1979
2143
  try {
1980
- const response = await this.request.get('/pay/custom-payment/all', {
2144
+ const response = await this.request.get("/pay/custom-payment/all", {
1981
2145
  filterPaymentMethods: true
1982
2146
  }, {
1983
2147
  osServer: true
1984
2148
  });
1985
- const paymentMethods = response?.data || [];
2149
+ const paymentMethods = (response == null ? void 0 : response.data) || [];
1986
2150
  this.paymentMethodsCache = Array.isArray(paymentMethods) ? [...paymentMethods] : [];
1987
2151
  return this.getPaymentMethods();
1988
2152
  } catch (error) {
1989
- this.logWarning('getPaymentMethodsAsync: 获取支付方式列表失败,使用缓存列表', {
2153
+ this.logWarning("getPaymentMethodsAsync: 获取支付方式列表失败,使用缓存列表", {
1990
2154
  error: error instanceof Error ? error.message : String(error)
1991
2155
  });
1992
2156
  return this.getPaymentMethods();
1993
2157
  }
1994
2158
  }
1995
-
1996
2159
  /** 同步读取初始化时缓存的支付方式列表。 */
1997
2160
  getPaymentMethods() {
1998
2161
  return [...this.paymentMethodsCache];
1999
2162
  }
2000
-
2001
2163
  /** 轻量舍入能力,供现金支付 UI 计算 rounding_amount。 */
2002
2164
  roundAmount(params) {
2003
- const amount = new _decimal.default(params.amount || 0);
2004
- const interval = new _decimal.default(params.interval || 0.05);
2005
- const rule = params.rule || 'standard_rounding';
2165
+ const amount = new import_decimal.default(params.amount || 0);
2166
+ const interval = new import_decimal.default(params.interval || 0.05);
2167
+ const rule = params.rule || "standard_rounding";
2006
2168
  const quotient = amount.div(interval);
2007
2169
  let roundedQuotient;
2008
- if (rule === 'always_up') {
2170
+ if (rule === "always_up") {
2009
2171
  roundedQuotient = quotient.ceil();
2010
- } else if (rule === 'always_down') {
2172
+ } else if (rule === "always_down") {
2011
2173
  roundedQuotient = quotient.floor();
2012
- } else if (rule === 'standard_down') {
2013
- roundedQuotient = quotient.toDecimalPlaces(0, _decimal.default.ROUND_HALF_DOWN);
2174
+ } else if (rule === "standard_down") {
2175
+ roundedQuotient = quotient.toDecimalPlaces(0, import_decimal.default.ROUND_HALF_DOWN);
2014
2176
  } else {
2015
- roundedQuotient = quotient.toDecimalPlaces(0, _decimal.default.ROUND_HALF_UP);
2177
+ roundedQuotient = quotient.toDecimalPlaces(0, import_decimal.default.ROUND_HALF_UP);
2016
2178
  }
2017
2179
  const roundedAmount = roundedQuotient.times(interval).toDecimalPlaces(2);
2018
2180
  return {
@@ -2021,7 +2183,6 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2021
2183
  roundingDifference: roundedAmount.minus(amount).toFixed(2)
2022
2184
  };
2023
2185
  }
2024
-
2025
2186
  /**
2026
2187
  * 发送支付链接。
2027
2188
  *
@@ -2029,15 +2190,17 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2029
2190
  * 只有成功拿到远端 order_id 后才调用 OrderModule 发送邮件。
2030
2191
  */
2031
2192
  async sendCustomerPayLink(params) {
2032
- if (!this.store.order) throw new Error('order 模块未初始化');
2193
+ var _a, _b;
2194
+ if (!this.store.order)
2195
+ throw new Error("order 模块未初始化");
2033
2196
  let orderIds = params.order_ids || params.orderIds || [];
2034
2197
  if (!orderIds.length || params.submitBeforeSend) {
2035
2198
  const submitResult = await this.submitSalesOrder({
2036
2199
  smallTicketDataFlag: 1
2037
2200
  });
2038
- const orderId = submitResult?.data?.order_id ?? submitResult?.order_id ?? submitResult?.data?.id ?? submitResult?.id;
2201
+ const orderId = ((_a = submitResult == null ? void 0 : submitResult.data) == null ? void 0 : _a.order_id) ?? (submitResult == null ? void 0 : submitResult.order_id) ?? ((_b = submitResult == null ? void 0 : submitResult.data) == null ? void 0 : _b.id) ?? (submitResult == null ? void 0 : submitResult.id);
2039
2202
  if (!orderId) {
2040
- throw new Error('本地订单提交云端失败,无法发送支付链接');
2203
+ throw new Error("本地订单提交云端失败,无法发送支付链接");
2041
2204
  }
2042
2205
  orderIds = [orderId];
2043
2206
  }
@@ -2048,7 +2211,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2048
2211
  });
2049
2212
  }
2050
2213
  transformBaseProductToOrderProduct(params) {
2051
- return (0, _transformBaseProductToOrderProduct.transformBaseProductToOrderProduct)(params);
2214
+ return (0, import_transformBaseProductToOrderProduct.transformBaseProductToOrderProduct)(params);
2052
2215
  }
2053
2216
  async calculateProductBookingPrice(params) {
2054
2217
  const quotation = this.store.quotation;
@@ -2060,34 +2223,36 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2060
2223
  customer_id: customerId,
2061
2224
  channel: params.channel
2062
2225
  });
2063
- return (0, _quotationPrice.calculateBaseSalesProductBookingPrice)({
2226
+ return (0, import_quotationPrice.calculateBaseSalesProductBookingPrice)({
2064
2227
  ...params,
2065
2228
  product,
2066
- fallback_price: authoritativeProduct ? undefined : params.fallback_price,
2229
+ fallback_price: authoritativeProduct ? void 0 : params.fallback_price,
2067
2230
  customer_id: customerId,
2068
2231
  quotation
2069
2232
  });
2070
2233
  }
2071
2234
  getQuotationCustomerScopeInfo() {
2072
2235
  const quotation = this.store.quotation;
2073
- if (quotation && typeof quotation.getQuotationCustomerScopeInfo === 'function') {
2236
+ if (quotation && typeof quotation.getQuotationCustomerScopeInfo === "function") {
2074
2237
  return quotation.getQuotationCustomerScopeInfo();
2075
2238
  }
2076
- const list = typeof quotation?.getQuotationList === 'function' ? quotation.getQuotationList() : [];
2077
- const customerById = new Map();
2078
- const quotationScopes = (Array.isArray(list) ? list : []).filter(item => Array.isArray(item?.customer) && item.customer.length > 0).map(item => {
2079
- const localSeen = new Set();
2080
- const customers = item.customer.filter(customer => {
2081
- const customerId = this.normalizePriceContextCustomerId(customer?.id);
2082
- if (!customerId || localSeen.has(customerId)) return false;
2239
+ const list = typeof (quotation == null ? void 0 : quotation.getQuotationList) === "function" ? quotation.getQuotationList() : [];
2240
+ const customerById = /* @__PURE__ */ new Map();
2241
+ const quotationScopes = (Array.isArray(list) ? list : []).filter((item) => Array.isArray(item == null ? void 0 : item.customer) && item.customer.length > 0).map((item) => {
2242
+ const localSeen = /* @__PURE__ */ new Set();
2243
+ const customers = item.customer.filter((customer) => {
2244
+ const customerId = this.normalizePriceContextCustomerId(customer == null ? void 0 : customer.id);
2245
+ if (!customerId || localSeen.has(customerId))
2246
+ return false;
2083
2247
  localSeen.add(customerId);
2084
- if (!customerById.has(customerId)) customerById.set(customerId, customer);
2248
+ if (!customerById.has(customerId))
2249
+ customerById.set(customerId, customer);
2085
2250
  return true;
2086
2251
  });
2087
2252
  return {
2088
2253
  quotationId: item.id,
2089
2254
  quotationName: item.name,
2090
- customerIds: customers.map(customer => String(customer.id)),
2255
+ customerIds: customers.map((customer) => String(customer.id)),
2091
2256
  customers
2092
2257
  };
2093
2258
  });
@@ -2102,7 +2267,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2102
2267
  }
2103
2268
  shouldRecalculateProductBookingPricesForContextChange(params) {
2104
2269
  const scopeInfo = this.getQuotationCustomerScopeInfo();
2105
- const scopedCustomerIds = new Set(scopeInfo.customerIds.map(id => String(id)));
2270
+ const scopedCustomerIds = new Set(scopeInfo.customerIds.map((id) => String(id)));
2106
2271
  const previousCustomerId = this.normalizePriceContextCustomerId(params.previousCustomerId);
2107
2272
  const nextCustomerId = this.normalizePriceContextCustomerId(params.nextCustomerId);
2108
2273
  const previousInScope = previousCustomerId ? scopedCustomerIds.has(previousCustomerId) : false;
@@ -2120,52 +2285,67 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2120
2285
  return shouldRecalculate;
2121
2286
  }
2122
2287
  async calculateProductBookingPrices(paramsList) {
2123
- if (!paramsList.length) return [];
2288
+ var _a, _b;
2289
+ if (!paramsList.length)
2290
+ return [];
2124
2291
  const quotation = this.store.quotation;
2125
- const customerId = paramsList[0]?.customer_id ?? this.getCurrentOrderCustomerId();
2126
- const productMapsByGroup = new Map();
2127
- const groups = new Map();
2128
- paramsList.forEach(params => {
2292
+ const customerId = ((_a = paramsList[0]) == null ? void 0 : _a.customer_id) ?? this.getCurrentOrderCustomerId();
2293
+ const productMapsByGroup = /* @__PURE__ */ new Map();
2294
+ const groups = /* @__PURE__ */ new Map();
2295
+ paramsList.forEach((params) => {
2296
+ var _a2;
2129
2297
  const product = params.product || {};
2130
2298
  const productId = this.getPriceQueryProductId(product);
2131
- if (productId === null) return;
2299
+ if (productId === null)
2300
+ return;
2132
2301
  const schedule = this.getPriceQuerySchedule(params);
2133
- const channel = params.channel || this.otherParams?.channel;
2134
- const groupKey = [schedule.schedule_date, schedule.schedule_datetime, channel || ''].join('|');
2302
+ const channel = params.channel || ((_a2 = this.otherParams) == null ? void 0 : _a2.channel);
2303
+ const groupKey = [
2304
+ schedule.schedule_date,
2305
+ schedule.schedule_datetime,
2306
+ channel || ""
2307
+ ].join("|");
2135
2308
  const group = groups.get(groupKey) || {
2136
- ids: new Set(),
2309
+ ids: /* @__PURE__ */ new Set(),
2137
2310
  schedule,
2138
2311
  channel
2139
2312
  };
2140
2313
  group.ids.add(productId);
2141
2314
  groups.set(groupKey, group);
2142
2315
  });
2143
- await Promise.all(Array.from(groups.entries()).map(async ([groupKey, group]) => {
2144
- const productsById = await this.loadProductsForPriceQuery({
2145
- ids: Array.from(group.ids),
2146
- schedule: group.schedule,
2147
- customerId,
2148
- channel: group.channel
2149
- });
2150
- productMapsByGroup.set(groupKey, productsById);
2151
- }));
2316
+ await Promise.all(
2317
+ Array.from(groups.entries()).map(async ([groupKey, group]) => {
2318
+ const productsById = await this.loadProductsForPriceQuery({
2319
+ ids: Array.from(group.ids),
2320
+ schedule: group.schedule,
2321
+ customerId,
2322
+ channel: group.channel
2323
+ });
2324
+ productMapsByGroup.set(groupKey, productsById);
2325
+ })
2326
+ );
2152
2327
  await this.loadQuotationForPriceQuery({
2153
2328
  quotation,
2154
2329
  customer_id: customerId,
2155
- channel: paramsList[0]?.channel
2330
+ channel: (_b = paramsList[0]) == null ? void 0 : _b.channel
2156
2331
  });
2157
- return paramsList.map(params => {
2332
+ return paramsList.map((params) => {
2333
+ var _a2, _b2;
2158
2334
  const productInput = params.product || {};
2159
2335
  const productId = this.getPriceQueryProductId(productInput);
2160
2336
  const schedule = this.getPriceQuerySchedule(params);
2161
- const channel = params.channel || this.otherParams?.channel;
2162
- const groupKey = [schedule.schedule_date, schedule.schedule_datetime, channel || ''].join('|');
2163
- const authoritativeProduct = productId === null ? null : productMapsByGroup.get(groupKey)?.get(productId) || null;
2337
+ const channel = params.channel || ((_a2 = this.otherParams) == null ? void 0 : _a2.channel);
2338
+ const groupKey = [
2339
+ schedule.schedule_date,
2340
+ schedule.schedule_datetime,
2341
+ channel || ""
2342
+ ].join("|");
2343
+ const authoritativeProduct = productId === null ? null : ((_b2 = productMapsByGroup.get(groupKey)) == null ? void 0 : _b2.get(productId)) || null;
2164
2344
  const product = this.mergeProductForPriceQuery(productInput, authoritativeProduct);
2165
- return (0, _quotationPrice.calculateBaseSalesProductBookingPrice)({
2345
+ return (0, import_quotationPrice.calculateBaseSalesProductBookingPrice)({
2166
2346
  ...params,
2167
2347
  product,
2168
- fallback_price: authoritativeProduct ? undefined : params.fallback_price,
2348
+ fallback_price: authoritativeProduct ? void 0 : params.fallback_price,
2169
2349
  customer_id: customerId,
2170
2350
  quotation
2171
2351
  });
@@ -2173,19 +2353,9 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2173
2353
  }
2174
2354
  async addProductToOrder(product, booking) {
2175
2355
  try {
2176
- if (!this.store.order) throw new Error('order 模块未初始化');
2356
+ if (!this.store.order)
2357
+ throw new Error("order 模块未初始化");
2177
2358
  const products = await this.store.order.addProductToOrder(product, booking);
2178
- // // 需要叠加
2179
- // if (this.hooks.onAddProductOverlay) {
2180
- // const res = this.hooks.onAddProductOverlay(是否叠加, product)
2181
- // if (!res) {
2182
- // 单独添加商品
2183
- // } else {
2184
- // 叠加
2185
- // }
2186
- // } else {
2187
- // 叠加
2188
- // }
2189
2359
  return products;
2190
2360
  } catch (error) {
2191
2361
  throw error;
@@ -2193,7 +2363,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2193
2363
  }
2194
2364
  async updateOrderProduct(params) {
2195
2365
  try {
2196
- if (!this.store.order) throw new Error('order 模块未初始化');
2366
+ if (!this.store.order)
2367
+ throw new Error("order 模块未初始化");
2197
2368
  const products = await this.store.order.updateOrderProduct(params);
2198
2369
  return products;
2199
2370
  } catch (error) {
@@ -2202,7 +2373,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2202
2373
  }
2203
2374
  async updateOrderProducts(paramsList) {
2204
2375
  try {
2205
- if (!this.store.order) throw new Error('order 模块未初始化');
2376
+ if (!this.store.order)
2377
+ throw new Error("order 模块未初始化");
2206
2378
  const products = await this.store.order.updateOrderProducts(paramsList);
2207
2379
  return products;
2208
2380
  } catch (error) {
@@ -2211,7 +2383,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2211
2383
  }
2212
2384
  async updateOrderProductQuantity(params) {
2213
2385
  try {
2214
- if (!this.store.order) throw new Error('order 模块未初始化');
2386
+ if (!this.store.order)
2387
+ throw new Error("order 模块未初始化");
2215
2388
  const products = await this.store.order.updateOrderProductQuantity(params);
2216
2389
  return products;
2217
2390
  } catch (error) {
@@ -2220,13 +2393,13 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2220
2393
  }
2221
2394
  updateOrderBooking(params) {
2222
2395
  try {
2223
- if (!this.store.order) throw new Error('order 模块未初始化');
2396
+ if (!this.store.order)
2397
+ throw new Error("order 模块未初始化");
2224
2398
  return this.store.order.updateOrderBooking(params);
2225
2399
  } catch (error) {
2226
2400
  throw error;
2227
2401
  }
2228
2402
  }
2229
-
2230
2403
  /**
2231
2404
  * 设置单行商品备注(与整单 `updateTempOrderNote` 区分)。
2232
2405
  * 多行同 SKU 时必须传入与删除/更新一致的 unique_identification_number。
@@ -2236,24 +2409,22 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2236
2409
  const params = {
2237
2410
  product_id: identity.product_id,
2238
2411
  product_variant_id: identity.product_variant_id,
2239
- updates: {
2240
- note: String(note || '')
2241
- }
2412
+ updates: { note: String(note || "") }
2242
2413
  };
2243
- if (identity.unique_identification_number !== undefined) {
2414
+ if (identity.unique_identification_number !== void 0) {
2244
2415
  params.unique_identification_number = identity.unique_identification_number;
2245
2416
  }
2246
- if (identity.product_sku !== undefined) {
2417
+ if (identity.product_sku !== void 0) {
2247
2418
  params.product_sku = identity.product_sku;
2248
2419
  }
2249
- if (identity.product_bundle !== undefined) params.product_bundle = identity.product_bundle;
2420
+ if (identity.product_bundle !== void 0)
2421
+ params.product_bundle = identity.product_bundle;
2250
2422
  const products = await this.updateOrderProduct(params);
2251
2423
  return products;
2252
2424
  } catch (error) {
2253
2425
  throw error;
2254
2426
  }
2255
2427
  }
2256
-
2257
2428
  /**
2258
2429
  * 批量删除购物车行,末尾仅一次促销重算。
2259
2430
  *
@@ -2262,7 +2433,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2262
2433
  */
2263
2434
  async removeProductsFromOrder(identities) {
2264
2435
  try {
2265
- if (!this.store.order) throw new Error('order 模块未初始化');
2436
+ if (!this.store.order)
2437
+ throw new Error("order 模块未初始化");
2266
2438
  return await this.store.order.removeProductsFromOrder(identities);
2267
2439
  } catch (error) {
2268
2440
  throw error;
@@ -2271,9 +2443,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2271
2443
  async removeProductFromOrder(identity) {
2272
2444
  return this.removeProductsFromOrder([identity]);
2273
2445
  }
2274
-
2275
2446
  // ─── 促销/赠品 透传(迁移自 booking usePromotion) ────────────────
2276
-
2277
2447
  /**
2278
2448
  * 注入促销评估器到底层 OrderModule。
2279
2449
  *
@@ -2281,10 +2451,10 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2281
2451
  * solution.setPromotionEvaluator(appHelper.utils.promotionEvaluator);
2282
2452
  */
2283
2453
  setPromotionEvaluator(evaluator) {
2284
- if (!this.store.order) throw new Error('order 模块未初始化');
2454
+ if (!this.store.order)
2455
+ throw new Error("order 模块未初始化");
2285
2456
  this.store.order.setPromotionEvaluator(evaluator);
2286
2457
  }
2287
-
2288
2458
  /**
2289
2459
  * 注入赠品选择 resolver。UI 层(SalesSdk)通过 bridge 提供。
2290
2460
  *
@@ -2292,10 +2462,10 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2292
2462
  * solution.setGiftSelectResolver(async (ctx) => bridge.request(ctx));
2293
2463
  */
2294
2464
  setGiftSelectResolver(resolver) {
2295
- if (!this.store.order) throw new Error('order 模块未初始化');
2465
+ if (!this.store.order)
2466
+ throw new Error("order 模块未初始化");
2296
2467
  this.store.order.setGiftSelectResolver(resolver);
2297
2468
  }
2298
-
2299
2469
  /**
2300
2470
  * 为商品目录追加促销标签,供 SalesSdkProductProvider 等商品列表入口复用。
2301
2471
  *
@@ -2303,40 +2473,40 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2303
2473
  * const products = solution.appendPromotionTags(catalogProducts);
2304
2474
  */
2305
2475
  appendPromotionTags(products) {
2306
- if (!this.store.order) throw new Error('order 模块未初始化');
2476
+ if (!this.store.order)
2477
+ throw new Error("order 模块未初始化");
2307
2478
  return this.store.order.appendPromotionTags(products);
2308
2479
  }
2309
-
2310
2480
  /**
2311
2481
  * 主动触发一次促销应用(一般写路径会自动触发,少数场景如客户切换后可手动调)。
2312
2482
  */
2313
2483
  async applyPromotion() {
2314
- if (!this.store.order) throw new Error('order 模块未初始化');
2484
+ if (!this.store.order)
2485
+ throw new Error("order 模块未初始化");
2315
2486
  await this.store.order.applyPromotion();
2316
2487
  }
2317
-
2318
2488
  /** 最近一次促销计算输出的未满足提示。 */
2319
2489
  getUnfulfilledPromotions() {
2320
- return this.store.order?.getUnfulfilledPromotions() || [];
2490
+ var _a;
2491
+ return ((_a = this.store.order) == null ? void 0 : _a.getUnfulfilledPromotions()) || [];
2321
2492
  }
2322
-
2323
2493
  /** 最近一次促销计算输出的赠品操作 diff。 */
2324
2494
  getLastGiftActions() {
2325
- return this.store.order?.getLastGiftActions() || null;
2495
+ var _a;
2496
+ return ((_a = this.store.order) == null ? void 0 : _a.getLastGiftActions()) || null;
2326
2497
  }
2327
-
2328
2498
  // 获取商品列表
2329
2499
  // TODO 需要跟 webpos 内的对齐一下
2330
2500
  async getProductList() {
2331
- // 可以直接通过配置里的 menu 读取
2332
- const menu_list_ids = this.otherParams?.dineInConfig?.['menu.associated_menus'].map(n => Number(n.value)) || [];
2501
+ var _a, _b, _c;
2502
+ const menu_list_ids = ((_b = (_a = this.otherParams) == null ? void 0 : _a.dineInConfig) == null ? void 0 : _b["menu.associated_menus"].map((n) => Number(n.value))) || [];
2333
2503
  try {
2334
- const res = await this.store.products?.loadProducts({
2504
+ const res = await ((_c = this.store.products) == null ? void 0 : _c.loadProducts({
2335
2505
  menu_list_ids,
2336
2506
  cacheId: this.cacheId,
2337
- schedule_date: (0, _dayjs.default)().format('YYYY-MM-DD'),
2338
- schedule_datetime: (0, _dayjs.default)().format('YYYY-MM-DD HH:mm:ss')
2339
- });
2507
+ schedule_date: (0, import_dayjs.default)().format("YYYY-MM-DD"),
2508
+ schedule_datetime: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
2509
+ }));
2340
2510
  return res;
2341
2511
  } catch (error) {
2342
2512
  throw error;
@@ -2345,23 +2515,19 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2345
2515
  getOtherParams() {
2346
2516
  return this.otherParams;
2347
2517
  }
2348
- async setOtherParams(params, {
2349
- cover = false
2350
- } = {}) {
2518
+ async setOtherParams(params, { cover = false } = {}) {
2519
+ var _a;
2351
2520
  if (cover) {
2352
- this.otherParams = {
2353
- ...params
2354
- };
2521
+ this.otherParams = { ...params };
2355
2522
  } else {
2356
- this.otherParams = {
2357
- ...this.otherParams,
2358
- ...params
2359
- };
2523
+ this.otherParams = { ...this.otherParams, ...params };
2360
2524
  }
2361
- this.cacheId = this.otherParams?.cacheId;
2362
- await this.syncOtherParamsToSubModules(params, {
2363
- cover
2364
- });
2525
+ this.cacheId = (_a = this.otherParams) == null ? void 0 : _a.cacheId;
2526
+ await this.syncOtherParamsToSubModules(params, { cover });
2365
2527
  }
2366
- }
2367
- exports.BaseSalesImpl = BaseSalesImpl;
2528
+ };
2529
+ // Annotate the CommonJS export names for ESM import in node:
2530
+ 0 && (module.exports = {
2531
+ BaseSalesImpl,
2532
+ ...require("./types")
2533
+ });