@pisell/pisellos 2.3.74 → 2.3.76

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 (283) hide show
  1. package/dist/core/index.js +6 -10
  2. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  3. package/dist/model/strategy/adapter/walletPass/example.js +3 -26
  4. package/dist/model/strategy/strategy-example.js +5 -19
  5. package/dist/modules/Cart/index.js +0 -3
  6. package/dist/modules/Cart/utils/cartProduct.js +0 -1
  7. package/dist/modules/Date/index.js +1 -5
  8. package/dist/modules/Discount/index.js +2 -4
  9. package/dist/modules/OpenData/index.js +0 -2
  10. package/dist/modules/Order/index.d.ts +1 -1
  11. package/dist/modules/Order/index.js +75 -91
  12. package/dist/modules/Order/types.d.ts +3 -1
  13. package/dist/modules/Payment/index.js +97 -162
  14. package/dist/modules/Rules/index.js +1 -4
  15. package/dist/modules/Schedule/index.js +0 -1
  16. package/dist/modules/Schedule/utils.js +0 -1
  17. package/dist/modules/Step/index.js +0 -1
  18. package/dist/plugins/request.js +1 -4
  19. package/dist/plugins/window.js +2 -6
  20. package/dist/server/index.js +97 -129
  21. package/dist/server/modules/menu/index.js +32 -41
  22. package/dist/server/modules/order/index.js +2 -4
  23. package/dist/server/modules/products/index.js +24 -42
  24. package/dist/server/modules/quotation/index.js +29 -38
  25. package/dist/server/modules/resource/index.js +3 -4
  26. package/dist/server/modules/schedule/index.js +27 -35
  27. package/dist/server/utils/product.js +0 -1
  28. package/dist/solution/BaseSales/index.js +100 -72
  29. package/dist/solution/BaseSales/utils/cartPromotion.d.ts +5 -0
  30. package/dist/solution/BaseSales/utils/cartPromotion.js +15 -6
  31. package/dist/solution/BookingByStep/index.js +7 -59
  32. package/dist/solution/BookingByStep/utils/capacity.js +1 -11
  33. package/dist/solution/BookingByStep/utils/resources.js +1 -3
  34. package/dist/solution/BookingByStep/utils/timeslots.js +2 -43
  35. package/dist/solution/BookingTicket/index.js +0 -2
  36. package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +6 -7
  37. package/dist/solution/BookingTicket/utils/scan/handleScan.js +25 -31
  38. package/dist/solution/BookingTicket/utils/scan/index.js +6 -10
  39. package/dist/solution/BuyTickets/index.js +9 -12
  40. package/dist/solution/Checkout/index.js +177 -252
  41. package/dist/solution/Checkout/utils/index.js +4 -16
  42. package/dist/solution/RegisterAndLogin/index.js +30 -76
  43. package/dist/solution/ScanOrder/index.js +50 -60
  44. package/dist/solution/ShopDiscount/index.js +2 -7
  45. package/dist/solution/VenueBooking/index.js +45 -55
  46. package/dist/utils/task.js +15 -18
  47. package/dist/utils/watch.js +0 -1
  48. package/lib/apis/picoding.js +2 -0
  49. package/lib/core/index.js +134 -134
  50. package/lib/effects/index.js +46 -57
  51. package/lib/index.js +82 -49
  52. package/lib/model/index.js +14 -21
  53. package/lib/model/strategy/adapter/dataVariant/adapter.js +38 -50
  54. package/lib/model/strategy/adapter/dataVariant/evaluator.js +162 -236
  55. package/lib/model/strategy/adapter/dataVariant/examples.js +229 -237
  56. package/lib/model/strategy/adapter/dataVariant/index.js +39 -34
  57. package/lib/model/strategy/adapter/dataVariant/type.js +57 -28
  58. package/lib/model/strategy/adapter/index.js +100 -64
  59. package/lib/model/strategy/adapter/itemRule/adapter.js +156 -144
  60. package/lib/model/strategy/adapter/itemRule/evaluator.js +36 -48
  61. package/lib/model/strategy/adapter/itemRule/examples.js +295 -225
  62. package/lib/model/strategy/adapter/itemRule/index.js +83 -57
  63. package/lib/model/strategy/adapter/itemRule/type.js +97 -36
  64. package/lib/model/strategy/adapter/promotion/adapter.js +91 -69
  65. package/lib/model/strategy/adapter/promotion/evaluator.js +444 -310
  66. package/lib/model/strategy/adapter/promotion/examples.js +222 -234
  67. package/lib/model/strategy/adapter/promotion/index.js +1 -0
  68. package/lib/model/strategy/adapter/promotion/type.js +243 -36
  69. package/lib/model/strategy/adapter/type.js +4 -16
  70. package/lib/model/strategy/adapter/walletPass/evaluator.js +180 -150
  71. package/lib/model/strategy/adapter/walletPass/example.js +217 -190
  72. package/lib/model/strategy/adapter/walletPass/index.js +75 -51
  73. package/lib/model/strategy/adapter/walletPass/locales.js +36 -58
  74. package/lib/model/strategy/adapter/walletPass/type.js +4 -16
  75. package/lib/model/strategy/adapter/walletPass/utils.js +588 -378
  76. package/lib/model/strategy/engine.js +270 -168
  77. package/lib/model/strategy/index.js +49 -34
  78. package/lib/model/strategy/strategy-example.js +243 -239
  79. package/lib/model/strategy/type.js +100 -40
  80. package/lib/modules/Account/index.js +39 -53
  81. package/lib/modules/Account/types.js +20 -33
  82. package/lib/modules/AccountList/index.js +116 -154
  83. package/lib/modules/AccountList/types.js +30 -31
  84. package/lib/modules/AccountList/utils.js +18 -30
  85. package/lib/modules/BaseModule.js +23 -42
  86. package/lib/modules/BookingContext/index.js +158 -136
  87. package/lib/modules/BookingContext/types.js +46 -32
  88. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +138 -146
  89. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +78 -83
  90. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.js +170 -150
  91. package/lib/modules/BookingContext/utils/flexible.js +38 -55
  92. package/lib/modules/BookingContext/utils/formatResourceList.js +19 -34
  93. package/lib/modules/BookingContext/utils/index.js +124 -41
  94. package/lib/modules/BookingContext/utils/noResource.js +58 -70
  95. package/lib/modules/BookingContext/utils/orderLineDisplay.js +14 -41
  96. package/lib/modules/BookingContext/utils/productExtend.js +202 -155
  97. package/lib/modules/BookingContext/utils/resourceErrors.js +53 -53
  98. package/lib/modules/BookingContext/utils/resourceSelection.js +19 -41
  99. package/lib/modules/BookingContext/utils/resources.js +209 -167
  100. package/lib/modules/BookingContext/utils/serviceTimes.js +115 -116
  101. package/lib/modules/BookingContext/utils/timeSlices.js +76 -86
  102. package/lib/modules/Cart/index.js +170 -124
  103. package/lib/modules/Cart/types.js +46 -51
  104. package/lib/modules/Cart/utils/cartAccount.js +40 -39
  105. package/lib/modules/Cart/utils/cartDate.js +56 -61
  106. package/lib/modules/Cart/utils/cartDiscount.js +28 -33
  107. package/lib/modules/Cart/utils/cartNote.js +27 -32
  108. package/lib/modules/Cart/utils/cartProduct.js +321 -251
  109. package/lib/modules/Cart/utils/cartRelationForms.js +29 -35
  110. package/lib/modules/Cart/utils/cartResource.js +70 -78
  111. package/lib/modules/Cart/utils/changePrice.js +22 -50
  112. package/lib/modules/Cart/utils/index.js +106 -48
  113. package/lib/modules/Customer/constants.js +13 -34
  114. package/lib/modules/Customer/index.js +235 -172
  115. package/lib/modules/Customer/types.js +38 -35
  116. package/lib/modules/Date/index.js +116 -115
  117. package/lib/modules/Date/types.js +16 -28
  118. package/lib/modules/Date/utils.js +174 -123
  119. package/lib/modules/Discount/index.js +122 -127
  120. package/lib/modules/Discount/types.js +9 -31
  121. package/lib/modules/Guests/index.js +30 -56
  122. package/lib/modules/Guests/types.js +23 -33
  123. package/lib/modules/Holder/index.js +209 -189
  124. package/lib/modules/Holder/types.js +4 -16
  125. package/lib/modules/Holder/utils.js +20 -49
  126. package/lib/modules/OpenData/index.js +70 -76
  127. package/lib/modules/OpenData/types.js +4 -16
  128. package/lib/modules/OpenData/utils.js +44 -78
  129. package/lib/modules/Order/index.d.ts +1 -1
  130. package/lib/modules/Order/index.js +1733 -2121
  131. package/lib/modules/Order/payment-utils.js +77 -120
  132. package/lib/modules/Order/types.d.ts +3 -1
  133. package/lib/modules/Order/types.js +88 -35
  134. package/lib/modules/Order/utils/bundleDiscountHydration.js +41 -74
  135. package/lib/modules/Order/utils/discountProductLineIdentity.js +142 -100
  136. package/lib/modules/Order/utils/manualProductDiscount.js +124 -123
  137. package/lib/modules/Order/utils/orderCollectionIdentity.js +184 -244
  138. package/lib/modules/Order/utils.js +814 -647
  139. package/lib/modules/Payment/cash.js +20 -33
  140. package/lib/modules/Payment/cashRecommendationAlgorithm.js +145 -76
  141. package/lib/modules/Payment/eftpos.js +16 -30
  142. package/lib/modules/Payment/index.js +532 -399
  143. package/lib/modules/Payment/mx51.js +1 -0
  144. package/lib/modules/Payment/types.js +230 -108
  145. package/lib/modules/Payment/utils.js +52 -51
  146. package/lib/modules/Payment/walletpass.js +485 -660
  147. package/lib/modules/Product/index.js +51 -46
  148. package/lib/modules/Product/types.js +4 -16
  149. package/lib/modules/Product/utils.js +32 -33
  150. package/lib/modules/ProductList/index.js +113 -123
  151. package/lib/modules/ProductList/types.js +9 -31
  152. package/lib/modules/Quotation/index.js +81 -118
  153. package/lib/modules/Quotation/types.js +4 -16
  154. package/lib/modules/Resource/index.js +27 -59
  155. package/lib/modules/Resource/types.js +22 -32
  156. package/lib/modules/Resource/utils.js +30 -38
  157. package/lib/modules/ResourcePlanner/index.js +25 -23
  158. package/lib/modules/ResourcePlanner/localClock.js +54 -119
  159. package/lib/modules/ResourcePlanner/planner.js +589 -770
  160. package/lib/modules/ResourcePlanner/types.js +10 -29
  161. package/lib/modules/Rules/index.js +1218 -959
  162. package/lib/modules/Rules/types.js +17 -40
  163. package/lib/modules/SalesSummary/index.js +85 -90
  164. package/lib/modules/SalesSummary/types.js +4 -16
  165. package/lib/modules/SalesSummary/utils.js +355 -430
  166. package/lib/modules/ScanOrderLogger/index.js +59 -79
  167. package/lib/modules/ScanOrderLogger/providers/feishu.js +54 -78
  168. package/lib/modules/ScanOrderLogger/providers/grafana.js +13 -36
  169. package/lib/modules/ScanOrderLogger/types.js +4 -16
  170. package/lib/modules/Schedule/getDateIsInSchedule.js +334 -163
  171. package/lib/modules/Schedule/index.js +100 -114
  172. package/lib/modules/Schedule/type.js +4 -16
  173. package/lib/modules/Schedule/types.js +4 -16
  174. package/lib/modules/Schedule/utils.js +433 -291
  175. package/lib/modules/Step/index.js +40 -52
  176. package/lib/modules/Step/tyeps.js +4 -16
  177. package/lib/modules/Summary/index.js +66 -71
  178. package/lib/modules/Summary/types.js +4 -16
  179. package/lib/modules/Summary/utils.js +773 -418
  180. package/lib/modules/SurchargeList/index.js +46 -60
  181. package/lib/modules/SurchargeList/types.js +4 -16
  182. package/lib/modules/index.js +245 -63
  183. package/lib/plugins/app.js +4 -16
  184. package/lib/plugins/index.js +36 -25
  185. package/lib/plugins/request.js +137 -126
  186. package/lib/plugins/shopStore.js +4 -16
  187. package/lib/plugins/user.js +4 -16
  188. package/lib/plugins/window.js +171 -179
  189. package/lib/server/index.js +3050 -2665
  190. package/lib/server/modules/floor-plan/index.js +118 -134
  191. package/lib/server/modules/floor-plan/types.js +15 -30
  192. package/lib/server/modules/index.js +106 -68
  193. package/lib/server/modules/menu/index.js +142 -122
  194. package/lib/server/modules/menu/types.js +18 -31
  195. package/lib/server/modules/order/index.js +784 -1002
  196. package/lib/server/modules/order/types.js +122 -33
  197. package/lib/server/modules/order/utils/filterBookings.js +219 -194
  198. package/lib/server/modules/order/utils/filterOrders.js +118 -92
  199. package/lib/server/modules/payment/index.js +59 -83
  200. package/lib/server/modules/payment/types.js +4 -16
  201. package/lib/server/modules/products/index.js +583 -471
  202. package/lib/server/modules/products/types.js +44 -34
  203. package/lib/server/modules/quotation/index.js +137 -172
  204. package/lib/server/modules/quotation/types.js +21 -31
  205. package/lib/server/modules/resource/index.js +220 -186
  206. package/lib/server/modules/resource/types.js +42 -33
  207. package/lib/server/modules/schedule/index.js +135 -123
  208. package/lib/server/modules/schedule/types.js +14 -21
  209. package/lib/server/modules/schedule/utils.js +334 -163
  210. package/lib/server/types.js +4 -16
  211. package/lib/server/utils/index.js +25 -23
  212. package/lib/server/utils/product.js +196 -139
  213. package/lib/server/utils/schedule.js +34 -41
  214. package/lib/server/utils/small-ticket.js +479 -456
  215. package/lib/server/utils/time.js +40 -49
  216. package/lib/solution/BaseSales/index.js +1220 -1412
  217. package/lib/solution/BaseSales/types.js +42 -38
  218. package/lib/solution/BaseSales/utils/cartPromotion.d.ts +5 -0
  219. package/lib/solution/BaseSales/utils/cartPromotion.js +652 -498
  220. package/lib/solution/BaseSales/utils/parseSalesResponse.js +85 -105
  221. package/lib/solution/BaseSales/utils/quotationPrice.js +56 -114
  222. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +108 -145
  223. package/lib/solution/BaseSales/utils.js +158 -143
  224. package/lib/solution/BookingByStep/index.js +1527 -1340
  225. package/lib/solution/BookingByStep/types.js +40 -99
  226. package/lib/solution/BookingByStep/utils/capacity.js +192 -160
  227. package/lib/solution/BookingByStep/utils/products.js +42 -52
  228. package/lib/solution/BookingByStep/utils/resources.js +527 -330
  229. package/lib/solution/BookingByStep/utils/stock.js +65 -44
  230. package/lib/solution/BookingByStep/utils/timeslots.js +129 -131
  231. package/lib/solution/BookingTicket/index.js +607 -522
  232. package/lib/solution/BookingTicket/types.js +99 -77
  233. package/lib/solution/BookingTicket/utils/addProductDecision.js +226 -189
  234. package/lib/solution/BookingTicket/utils/addTimeAvailability.js +58 -89
  235. package/lib/solution/BookingTicket/utils/bookingStatus.js +107 -78
  236. package/lib/solution/BookingTicket/utils/cartView.js +114 -99
  237. package/lib/solution/BookingTicket/utils/exampleData.js +185 -0
  238. package/lib/solution/BookingTicket/utils/orderCustomer.js +18 -41
  239. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.js +219 -86
  240. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +168 -116
  241. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +79 -91
  242. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.js +54 -41
  243. package/lib/solution/BookingTicket/utils/scan/handleScan.js +84 -81
  244. package/lib/solution/BookingTicket/utils/scan/index.js +98 -104
  245. package/lib/solution/BookingTicket/utils/scan/scanCache.js +90 -43
  246. package/lib/solution/BookingTicket/utils/scan/scanProductValues.js +52 -64
  247. package/lib/solution/BookingTicket/utils/sessionCatalogStale.js +56 -58
  248. package/lib/solution/BookingTicket/utils/weighingProductSku.js +34 -48
  249. package/lib/solution/BuyTickets/index.js +67 -70
  250. package/lib/solution/BuyTickets/types.js +22 -38
  251. package/lib/solution/Checkout/index.js +1451 -1158
  252. package/lib/solution/Checkout/types.js +91 -61
  253. package/lib/solution/Checkout/utils/index.js +228 -156
  254. package/lib/solution/PlaceOrder/index.js +55 -0
  255. package/lib/solution/RegisterAndLogin/config.js +493 -460
  256. package/lib/solution/RegisterAndLogin/index.js +633 -630
  257. package/lib/solution/RegisterAndLogin/types.js +189 -76
  258. package/lib/solution/RegisterAndLogin/utils.js +183 -125
  259. package/lib/solution/Sales/index.js +328 -324
  260. package/lib/solution/Sales/types.js +27 -33
  261. package/lib/solution/ScanOrder/index.js +832 -864
  262. package/lib/solution/ScanOrder/types.js +33 -34
  263. package/lib/solution/ScanOrder/utils.js +409 -374
  264. package/lib/solution/ShopDiscount/index.js +226 -232
  265. package/lib/solution/ShopDiscount/types.js +15 -37
  266. package/lib/solution/ShopDiscount/utils.js +300 -172
  267. package/lib/solution/UnifiedBookingSales/index.js +1035 -1201
  268. package/lib/solution/UnifiedBookingSales/remoteOccupancyCache.js +99 -159
  269. package/lib/solution/UnifiedBookingSales/types.js +10 -32
  270. package/lib/solution/VenueBooking/index.js +811 -879
  271. package/lib/solution/VenueBooking/types.js +19 -39
  272. package/lib/solution/VenueBooking/utils/dateSummary.js +27 -56
  273. package/lib/solution/VenueBooking/utils/resource.js +31 -54
  274. package/lib/solution/VenueBooking/utils/slotMerge.js +94 -107
  275. package/lib/solution/VenueBooking/utils/timeSlot.js +132 -132
  276. package/lib/solution/VenueBooking/utils.js +130 -67
  277. package/lib/solution/index.js +124 -41
  278. package/lib/store/createStore.js +32 -29
  279. package/lib/types/index.js +4 -16
  280. package/lib/utils/payment-number.js +26 -46
  281. package/lib/utils/task.js +36 -36
  282. package/lib/utils/watch.js +81 -47
  283. package/package.json +2 -1
@@ -1,334 +1,275 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _exportNames = {
7
+ BaseSalesImpl: true
18
8
  };
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
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
+ });
34
22
  });
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_payment_utils = require("../../modules/Order/payment-utils");
44
- var import_payment_number = require("../../utils/payment-number");
45
- var import_orderCollectionIdentity = require("../../modules/Order/utils/orderCollectionIdentity");
46
- var import_dayjs = __toESM(require("dayjs"));
47
- __reExport(BaseSales_exports, require("./types"), module.exports);
48
- var import_Quotation = require("../../modules/Quotation");
49
- var import_transformBaseProductToOrderProduct = require("./utils/transformBaseProductToOrderProduct");
50
- var import_quotationPrice = require("./utils/quotationPrice");
51
- var SERVER_ORDER_CHANGED_EVENT = "order:onOrdersChanged";
52
- var WALLET_PAYMENT_CODE_BY_TAG = {
53
- product_voucher: "PRODUCTVOUCHER",
54
- gift_card: "GIFTCARD",
55
- point_card: "POINTCARD"
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 _paymentUtils = require("../../modules/Order/payment-utils");
29
+ var _paymentNumber = require("../../utils/payment-number");
30
+ var _orderCollectionIdentity = require("../../modules/Order/utils/orderCollectionIdentity");
31
+ var _dayjs = _interopRequireDefault(require("dayjs"));
32
+ var _Quotation = require("../../modules/Quotation");
33
+ var _transformBaseProductToOrderProduct = require("./utils/transformBaseProductToOrderProduct");
34
+ var _quotationPrice = require("./utils/quotationPrice");
35
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36
+ const SERVER_ORDER_CHANGED_EVENT = 'order:onOrdersChanged';
37
+ const WALLET_PAYMENT_CODE_BY_TAG = {
38
+ product_voucher: 'PRODUCTVOUCHER',
39
+ gift_card: 'GIFTCARD',
40
+ point_card: 'POINTCARD'
56
41
  };
57
42
  function getSharedWalletAssetId(asset) {
58
- return (asset == null ? void 0 : asset.id) ?? (asset == null ? void 0 : asset.voucher_id) ?? (asset == null ? void 0 : asset.code);
43
+ return asset?.id ?? asset?.voucher_id ?? asset?.code;
59
44
  }
60
45
  function getSharedWalletAssetAmount(asset) {
61
- const value = (asset == null ? void 0 : asset.edit_current_amount) ?? (asset == null ? void 0 : asset._available_max_amount) ?? ((asset == null ? void 0 : asset.tag) === "point_card" ? asset == null ? void 0 : asset.recommended_usage_amount : asset == null ? void 0 : asset.available_max_amount) ?? (asset == null ? void 0 : asset.actualDeduction) ?? (asset == null ? void 0 : asset.amount) ?? 0;
46
+ const value = asset?.edit_current_amount ?? asset?._available_max_amount ?? (asset?.tag === 'point_card' ? asset?.recommended_usage_amount : asset?.available_max_amount) ?? asset?.actualDeduction ?? asset?.amount ?? 0;
62
47
  const amount = Number(value);
63
48
  return Number.isFinite(amount) && amount > 0 ? amount : 0;
64
49
  }
65
50
  function isRejectedSalesSubmitResult(result) {
66
- var _a, _b;
67
- const candidates = [
68
- result,
69
- result == null ? void 0 : result.data,
70
- (_a = result == null ? void 0 : result.response) == null ? void 0 : _a.data,
71
- (_b = result == null ? void 0 : result.response) == null ? void 0 : _b.body
72
- ];
73
- return candidates.some((candidate) => {
74
- if (!candidate || typeof candidate !== "object")
75
- return false;
76
- if (candidate.code !== void 0 && candidate.code !== 200 && candidate.code !== "200") {
51
+ const candidates = [result, result?.data, result?.response?.data, result?.response?.body];
52
+ return candidates.some(candidate => {
53
+ if (!candidate || typeof candidate !== 'object') return false;
54
+ if (candidate.code !== undefined && candidate.code !== 200 && candidate.code !== '200') {
77
55
  return true;
78
56
  }
79
57
  const statusCode = Number(candidate.statusCode);
80
- if (Number.isFinite(statusCode) && statusCode >= 400)
81
- return true;
58
+ if (Number.isFinite(statusCode) && statusCode >= 400) return true;
82
59
  if (candidate.status === false || candidate.success === false || candidate.result === false) {
83
60
  return true;
84
61
  }
85
- return ["failed", "error"].includes(
86
- String(candidate.status || "").toLowerCase()
87
- );
62
+ return ['failed', 'error'].includes(String(candidate.status || '').toLowerCase());
88
63
  });
89
64
  }
90
65
  function getSalesSubmitErrorMessage(result, fallbackMessage) {
91
- var _a, _b;
92
- return (result == null ? void 0 : result.message) || (result == null ? void 0 : result.msg) || ((_a = result == null ? void 0 : result.data) == null ? void 0 : _a.message) || ((_b = result == null ? void 0 : result.data) == null ? void 0 : _b.msg) || fallbackMessage;
66
+ return result?.message || result?.msg || result?.data?.message || result?.data?.msg || fallbackMessage;
93
67
  }
94
68
  function toWalletFundValue(value) {
95
69
  try {
96
- return new import_decimal.default(value || 0).toDecimalPlaces(2).toFixed(2);
70
+ return new _decimal.default(value || 0).toDecimalPlaces(2).toFixed(2);
97
71
  } catch {
98
- return "0.00";
72
+ return '0.00';
99
73
  }
100
74
  }
101
75
  function subtractWalletFundValue(left, right) {
102
76
  try {
103
- return new import_decimal.default(left || 0).minus(right || 0).toDecimalPlaces(2).toFixed(2);
77
+ return new _decimal.default(left || 0).minus(right || 0).toDecimalPlaces(2).toFixed(2);
104
78
  } catch {
105
- return "0.00";
79
+ return '0.00';
106
80
  }
107
81
  }
108
82
  function getSharedWalletPassUseValue(params) {
109
- const { asset, amount, paymentMethod } = params;
110
- const configuredValue = Number(asset == null ? void 0 : asset.wallet_pass_use_value);
83
+ const {
84
+ asset,
85
+ amount,
86
+ paymentMethod
87
+ } = params;
88
+ const configuredValue = Number(asset?.wallet_pass_use_value);
111
89
  if (Number.isFinite(configuredValue) && configuredValue > 0) {
112
90
  return configuredValue;
113
91
  }
114
- const isPointCard = (asset == null ? void 0 : asset.tag) === "point_card" || paymentMethod.code === "POINTCARD";
115
- const usageUnit = asset == null ? void 0 : asset.wallet_pass_usage_unit;
116
- if (isPointCard && (usageUnit == null ? void 0 : usageUnit.points) && (usageUnit == null ? void 0 : usageUnit.price)) {
117
- return new import_decimal.default(amount).div(usageUnit.price).mul(usageUnit.points).toDecimalPlaces(2, import_decimal.default.ROUND_DOWN).toNumber();
92
+ const isPointCard = asset?.tag === 'point_card' || paymentMethod.code === 'POINTCARD';
93
+ const usageUnit = asset?.wallet_pass_usage_unit;
94
+ if (isPointCard && usageUnit?.points && usageUnit?.price) {
95
+ return new _decimal.default(amount).div(usageUnit.price).mul(usageUnit.points).toDecimalPlaces(2, _decimal.default.ROUND_DOWN).toNumber();
118
96
  }
119
97
  return amount;
120
98
  }
121
99
  function buildSharedWalletFundRecord(params) {
122
- const { asset, amount, paymentMethod } = params;
123
- const isPointCard = (asset == null ? void 0 : asset.tag) === "point_card" || paymentMethod.code === "POINTCARD";
124
- const usingBeforeValue = (asset == null ? void 0 : asset.balance_par_value) ?? (asset == null ? void 0 : asset.balance) ?? (asset == null ? void 0 : asset.using_before_value) ?? 0;
100
+ const {
101
+ asset,
102
+ amount,
103
+ paymentMethod
104
+ } = params;
105
+ const isPointCard = asset?.tag === 'point_card' || paymentMethod.code === 'POINTCARD';
106
+ const usingBeforeValue = asset?.balance_par_value ?? asset?.balance ?? asset?.using_before_value ?? 0;
125
107
  const walletPassUseValue = getSharedWalletPassUseValue(params);
126
108
  const usingValue = isPointCard ? walletPassUseValue : amount;
127
- const walletPassName = (asset == null ? void 0 : asset.wallet_pass_name) || (asset == null ? void 0 : asset.format_title) || (asset == null ? void 0 : asset.product_name) || (asset == null ? void 0 : asset.name) || paymentMethod.name;
109
+ const walletPassName = asset?.wallet_pass_name || asset?.format_title || asset?.product_name || asset?.name || paymentMethod.name;
128
110
  return {
129
- voucher_id: (asset == null ? void 0 : asset.voucher_id) ?? (asset == null ? void 0 : asset.id),
130
- wallet_pass_name: walletPassName && typeof walletPassName === "object" ? walletPassName : { default: walletPassName || "" },
131
- code: (asset == null ? void 0 : asset.code) || (asset == null ? void 0 : asset.tag),
132
- encoded: asset == null ? void 0 : asset.encoded,
111
+ voucher_id: asset?.voucher_id ?? asset?.id,
112
+ wallet_pass_name: walletPassName && typeof walletPassName === 'object' ? walletPassName : {
113
+ default: walletPassName || ''
114
+ },
115
+ code: asset?.code || asset?.tag,
116
+ encoded: asset?.encoded,
133
117
  using_before_value: toWalletFundValue(usingBeforeValue),
134
118
  using_after_value: subtractWalletFundValue(usingBeforeValue, usingValue)
135
119
  };
136
120
  }
137
121
  function isBaseSalesManualProductDiscountProduct(product) {
138
- var _a, _b;
139
- 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");
122
+ return product?.metadata?.is_manual_discount === true || product?.metadata?.is_manual_discount === 1 || (product?.discount_list || []).some(item => item?.type === 'product');
140
123
  }
141
124
  function getBaseSalesProductUid(product) {
142
- var _a;
143
- const uid = ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a.unique_identification_number) || (product == null ? void 0 : product.unique_identification_number);
144
- if (uid === void 0 || uid === null || uid === "")
145
- return null;
125
+ const uid = product?.metadata?.unique_identification_number || product?.unique_identification_number;
126
+ if (uid === undefined || uid === null || uid === '') return null;
146
127
  return String(uid);
147
128
  }
148
129
  function preserveManualProductDiscountProducts(previousProducts, nextProducts) {
149
- const previousByUid = /* @__PURE__ */ new Map();
130
+ const previousByUid = new Map();
150
131
  (previousProducts || []).forEach((product, index) => {
151
132
  const uid = getBaseSalesProductUid(product);
152
- if (uid)
153
- previousByUid.set(uid, product);
133
+ if (uid) previousByUid.set(uid, product);
154
134
  previousByUid.set(`__index__:${index}`, product);
155
135
  });
156
136
  return (nextProducts || []).map((product, index) => {
157
137
  const uid = getBaseSalesProductUid(product);
158
- const previous = (uid ? previousByUid.get(uid) : void 0) || previousByUid.get(`__index__:${index}`);
138
+ const previous = (uid ? previousByUid.get(uid) : undefined) || previousByUid.get(`__index__:${index}`);
159
139
  return previous && isBaseSalesManualProductDiscountProduct(previous) ? previous : product;
160
140
  });
161
141
  }
162
142
  function isBaseSalesHistoricalDiscountEntry(discount) {
163
- return Boolean(
164
- (discount == null ? void 0 : discount.isEditMode) || (discount == null ? void 0 : discount.isDisabled) || (discount == null ? void 0 : discount.order_discount_id) != null
165
- );
143
+ return Boolean(discount?.isEditMode || discount?.isDisabled || discount?.order_discount_id != null);
166
144
  }
167
145
  function getBaseSalesUniqueArrayMetadataKey(key) {
168
- if (key === "products" || key === "bookings")
169
- return "unique_identification_number";
146
+ if (key === 'products' || key === 'bookings') return 'unique_identification_number';
170
147
  return null;
171
148
  }
172
- var BASE_SALES_PERSISTENT_ID_FIELD_BY_KIND = {
173
- product: "order_detail_id",
174
- booking: "schedule_event_id",
175
- payment: "order_payment_id"
149
+ const BASE_SALES_PERSISTENT_ID_FIELD_BY_KIND = {
150
+ product: 'order_detail_id',
151
+ booking: 'schedule_event_id',
152
+ payment: 'order_payment_id'
176
153
  };
177
154
  function getBaseSalesOrderCollectionKind(key) {
178
- if (key === "products")
179
- return "product";
180
- if (key === "bookings")
181
- return "booking";
182
- if (key === "payments" || key === "payment")
183
- return "payment";
155
+ if (key === 'products') return 'product';
156
+ if (key === 'bookings') return 'booking';
157
+ if (key === 'payments' || key === 'payment') return 'payment';
184
158
  return null;
185
159
  }
186
160
  function isSameBaseSalesOrderRecord(left, right) {
187
- if (!left || !right || typeof left !== "object" || typeof right !== "object")
188
- return false;
189
- const leftIdentities = new Set(
190
- [left.order_id, left.id, left.external_sale_number, left.order_number].filter((value) => value !== void 0 && value !== null && value !== "").map(String)
191
- );
192
- if (leftIdentities.size === 0)
193
- return false;
194
- return [right.order_id, right.id, right.external_sale_number, right.order_number].some(
195
- (value) => value !== void 0 && value !== null && value !== "" && leftIdentities.has(String(value))
196
- );
161
+ if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false;
162
+ 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));
163
+ if (leftIdentities.size === 0) return false;
164
+ return [right.order_id, right.id, right.external_sale_number, right.order_number].some(value => value !== undefined && value !== null && value !== '' && leftIdentities.has(String(value)));
197
165
  }
198
166
  function isBaseSalesBlankValue(value) {
199
- return value === void 0 || value === null || value === "";
167
+ return value === undefined || value === null || value === '';
200
168
  }
201
169
  function mergeBaseSalesProductSnapshotFields(currentItem, loadedItem) {
202
- var _a, _b, _c;
203
- const mergedItem = (0, import_lodash_es.cloneDeep)(loadedItem);
204
- if (isBaseSalesBlankValue(mergedItem.product_cover) && !isBaseSalesBlankValue(currentItem == null ? void 0 : currentItem.product_cover)) {
170
+ const mergedItem = (0, _lodashEs.cloneDeep)(loadedItem);
171
+ if (isBaseSalesBlankValue(mergedItem.product_cover) && !isBaseSalesBlankValue(currentItem?.product_cover)) {
205
172
  mergedItem.product_cover = currentItem.product_cover;
206
173
  }
207
- const currentHolderConfig = (_a = currentItem == null ? void 0 : currentItem.metadata) == null ? void 0 : _a.holder_config;
208
- 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) {
174
+ const currentHolderConfig = currentItem?.metadata?.holder_config;
175
+ if ((mergedItem.metadata?.holder_config === undefined || mergedItem.metadata?.holder_config === null) && currentHolderConfig !== undefined && currentHolderConfig !== null) {
209
176
  mergedItem.metadata = {
210
- ...mergedItem.metadata || {},
177
+ ...(mergedItem.metadata || {}),
211
178
  holder_config: currentHolderConfig
212
179
  };
213
180
  }
214
181
  return mergedItem;
215
182
  }
216
183
  function mergeBaseSalesCollectionItem(kind, currentItem, incomingItem, uidRemaps) {
217
- const currentReferenceUid = (0, import_orderCollectionIdentity.getOrderCollectionReferenceUid)(kind, currentItem);
218
- const incomingReferenceUid = (0, import_orderCollectionIdentity.getOrderCollectionReferenceUid)(kind, incomingItem);
219
- const identityMergedItem = (0, import_orderCollectionIdentity.mergeOrderCollectionItems)(
220
- kind,
221
- currentItem,
222
- incomingItem
223
- );
224
- const mergedUid = (0, import_orderCollectionIdentity.getOrderCollectionUid)(kind, identityMergedItem);
184
+ const currentReferenceUid = (0, _orderCollectionIdentity.getOrderCollectionReferenceUid)(kind, currentItem);
185
+ const incomingReferenceUid = (0, _orderCollectionIdentity.getOrderCollectionReferenceUid)(kind, incomingItem);
186
+ const identityMergedItem = (0, _orderCollectionIdentity.mergeOrderCollectionItems)(kind, currentItem, incomingItem);
187
+ const mergedUid = (0, _orderCollectionIdentity.getOrderCollectionUid)(kind, identityMergedItem);
225
188
  if (mergedUid) {
226
- for (const from of /* @__PURE__ */ new Set([currentReferenceUid, incomingReferenceUid])) {
227
- if (!from || from === mergedUid)
228
- continue;
189
+ for (const from of new Set([currentReferenceUid, incomingReferenceUid])) {
190
+ if (!from || from === mergedUid) continue;
229
191
  uidRemaps.push({
230
192
  kind,
231
193
  from,
232
194
  to: mergedUid,
233
- persistentId: (0, import_orderCollectionIdentity.getOrderCollectionPersistentId)(kind, incomingItem) || (0, import_orderCollectionIdentity.getOrderCollectionPersistentId)(kind, currentItem)
195
+ persistentId: (0, _orderCollectionIdentity.getOrderCollectionPersistentId)(kind, incomingItem) || (0, _orderCollectionIdentity.getOrderCollectionPersistentId)(kind, currentItem)
234
196
  });
235
197
  }
236
198
  }
237
- const mergedItem = mergedUid ? (0, import_orderCollectionIdentity.setOrderCollectionUid)(kind, incomingItem, mergedUid) : (0, import_lodash_es.cloneDeep)(incomingItem);
199
+ const mergedItem = mergedUid ? (0, _orderCollectionIdentity.setOrderCollectionUid)(kind, incomingItem, mergedUid) : (0, _lodashEs.cloneDeep)(incomingItem);
238
200
  const persistentIdField = BASE_SALES_PERSISTENT_ID_FIELD_BY_KIND[kind];
239
201
  if (isBaseSalesBlankValue(mergedItem[persistentIdField]) && !isBaseSalesBlankValue(identityMergedItem[persistentIdField])) {
240
202
  mergedItem[persistentIdField] = identityMergedItem[persistentIdField];
241
203
  }
242
- return kind === "product" ? mergeBaseSalesProductSnapshotFields(currentItem, mergedItem) : mergedItem;
204
+ return kind === 'product' ? mergeBaseSalesProductSnapshotFields(currentItem, mergedItem) : mergedItem;
243
205
  }
244
206
  function mergeBaseSalesOrderCollection(kind, currentValue, incomingValue, strategy, uidRemaps) {
245
- if (kind === "payment") {
246
- return (0, import_payment_utils.mergeOrderPaymentListsByIdentity)(
247
- currentValue,
248
- incomingValue,
249
- strategy === "preserve-local" ? { preserveUnmatchedExisting: true } : {
250
- preserveUnmatchedExistingWhen: (payment) => (0, import_payment_utils.isIdentifiedPendingOrderPayment)(payment) || !(0, import_orderCollectionIdentity.getOrderCollectionPersistentId)("payment", payment)
251
- }
252
- );
207
+ if (kind === 'payment') {
208
+ return (0, _paymentUtils.mergeOrderPaymentListsByIdentity)(currentValue, incomingValue, strategy === 'preserve-local' ? {
209
+ preserveUnmatchedExisting: true
210
+ } : {
211
+ preserveUnmatchedExistingWhen: payment => (0, _paymentUtils.isIdentifiedPendingOrderPayment)(payment) || !(0, _orderCollectionIdentity.getOrderCollectionPersistentId)('payment', payment)
212
+ });
253
213
  }
254
- const currentItems = (0, import_orderCollectionIdentity.normalizeOrderCollection)(kind, currentValue, {
214
+ const currentItems = (0, _orderCollectionIdentity.normalizeOrderCollection)(kind, currentValue, {
255
215
  ensureUid: false
256
216
  }).items;
257
- const incomingItems = (0, import_orderCollectionIdentity.normalizeOrderCollection)(kind, incomingValue, {
217
+ const incomingItems = (0, _orderCollectionIdentity.normalizeOrderCollection)(kind, incomingValue, {
258
218
  ensureUid: false
259
219
  }).items;
260
- if (strategy === "authoritative-incoming") {
261
- const result2 = (0, import_lodash_es.cloneDeep)(incomingItems);
262
- currentItems.forEach((currentItem) => {
263
- const incomingIndex = result2.findIndex(
264
- (incomingItem) => (0, import_orderCollectionIdentity.isSameOrderCollectionItem)(kind, currentItem, incomingItem)
265
- );
220
+ if (strategy === 'authoritative-incoming') {
221
+ const result = (0, _lodashEs.cloneDeep)(incomingItems);
222
+ currentItems.forEach(currentItem => {
223
+ const incomingIndex = result.findIndex(incomingItem => (0, _orderCollectionIdentity.isSameOrderCollectionItem)(kind, currentItem, incomingItem));
266
224
  if (incomingIndex !== -1) {
267
- result2[incomingIndex] = mergeBaseSalesCollectionItem(
268
- kind,
269
- currentItem,
270
- result2[incomingIndex],
271
- uidRemaps
272
- );
225
+ result[incomingIndex] = mergeBaseSalesCollectionItem(kind, currentItem, result[incomingIndex], uidRemaps);
273
226
  return;
274
227
  }
275
- if (!(0, import_orderCollectionIdentity.getOrderCollectionPersistentId)(kind, currentItem)) {
276
- result2.push((0, import_lodash_es.cloneDeep)(currentItem));
228
+
229
+ // 完整服务端快照负责已落库行;仅保留尚未提交的本地新行。
230
+ if (!(0, _orderCollectionIdentity.getOrderCollectionPersistentId)(kind, currentItem)) {
231
+ result.push((0, _lodashEs.cloneDeep)(currentItem));
277
232
  }
278
233
  });
279
- return result2;
234
+ return result;
280
235
  }
281
- const result = (0, import_lodash_es.cloneDeep)(currentItems);
282
- incomingItems.forEach((incomingItem) => {
283
- const currentIndex = result.findIndex(
284
- (currentItem) => (0, import_orderCollectionIdentity.isSameOrderCollectionItem)(kind, currentItem, incomingItem)
285
- );
236
+ const result = (0, _lodashEs.cloneDeep)(currentItems);
237
+ incomingItems.forEach(incomingItem => {
238
+ const currentIndex = result.findIndex(currentItem => (0, _orderCollectionIdentity.isSameOrderCollectionItem)(kind, currentItem, incomingItem));
286
239
  if (currentIndex !== -1) {
287
- result[currentIndex] = mergeBaseSalesCollectionItem(
288
- kind,
289
- result[currentIndex],
290
- incomingItem,
291
- uidRemaps
292
- );
240
+ result[currentIndex] = mergeBaseSalesCollectionItem(kind, result[currentIndex], incomingItem, uidRemaps);
293
241
  return;
294
242
  }
295
- result.push((0, import_lodash_es.cloneDeep)(incomingItem));
243
+ result.push((0, _lodashEs.cloneDeep)(incomingItem));
296
244
  });
297
245
  return result;
298
246
  }
299
247
  function normalizeBaseSalesRecordCollections(sourceRecord, options) {
300
- const normalizedRecord = (0, import_orderCollectionIdentity.normalizeOrderCollections)(
301
- (0, import_lodash_es.cloneDeep)(sourceRecord || {}),
302
- options
303
- ).order;
248
+ const normalizedRecord = (0, _orderCollectionIdentity.normalizeOrderCollections)((0, _lodashEs.cloneDeep)(sourceRecord || {}), options).order;
249
+
250
+ // 兼容旧调用方偶尔使用的单数 payment 字段。
304
251
  if (Array.isArray(normalizedRecord.payment)) {
305
- normalizedRecord.payment = (0, import_orderCollectionIdentity.normalizeOrderCollection)(
306
- "payment",
307
- normalizedRecord.payment,
308
- options
309
- ).items;
252
+ normalizedRecord.payment = (0, _orderCollectionIdentity.normalizeOrderCollection)('payment', normalizedRecord.payment, options).items;
310
253
  }
311
254
  return normalizedRecord;
312
255
  }
313
256
  function getBaseSalesMetadataUid(item, metadataKey) {
314
- var _a;
315
- const uid = ((_a = item == null ? void 0 : item.metadata) == null ? void 0 : _a[metadataKey]) ?? (item == null ? void 0 : item[metadataKey]);
316
- if (uid === void 0 || uid === null || uid === "")
317
- return null;
257
+ const uid = item?.metadata?.[metadataKey] ?? item?.[metadataKey];
258
+ if (uid === undefined || uid === null || uid === '') return null;
318
259
  return String(uid);
319
260
  }
320
261
  function mergeBaseSalesUniqueArray(currentValue, loadedValue, metadataKey) {
321
262
  const result = [];
322
- const indexByUid = /* @__PURE__ */ new Map();
323
- const appendOrReplaceByUid = (item) => {
324
- const clonedItem = (0, import_lodash_es.cloneDeep)(item);
263
+ const indexByUid = new Map();
264
+ const appendOrReplaceByUid = item => {
265
+ const clonedItem = (0, _lodashEs.cloneDeep)(item);
325
266
  const uid = getBaseSalesMetadataUid(clonedItem, metadataKey);
326
267
  if (!uid) {
327
268
  result.push(clonedItem);
328
269
  return;
329
270
  }
330
271
  const existingIndex = indexByUid.get(uid);
331
- if (existingIndex !== void 0) {
272
+ if (existingIndex !== undefined) {
332
273
  result[existingIndex] = clonedItem;
333
274
  return;
334
275
  }
@@ -340,130 +281,142 @@ function mergeBaseSalesUniqueArray(currentValue, loadedValue, metadataKey) {
340
281
  return result;
341
282
  }
342
283
  function mergeSalesDetailRecordWithTempOrder(currentTempOrder, loadedRecord, strategy) {
343
- const normalizedLoadedRecord = normalizeBaseSalesRecordCollections(
344
- loadedRecord || {},
345
- { ensureUid: false }
346
- );
284
+ const normalizedLoadedRecord = normalizeBaseSalesRecordCollections(loadedRecord || {}, {
285
+ ensureUid: false
286
+ });
347
287
  if (!currentTempOrder) {
348
288
  return normalizeBaseSalesRecordCollections(normalizedLoadedRecord);
349
289
  }
350
- const normalizedCurrentTempOrder = normalizeBaseSalesRecordCollections(
351
- currentTempOrder,
352
- { ensureUid: false }
353
- );
290
+ const normalizedCurrentTempOrder = normalizeBaseSalesRecordCollections(currentTempOrder, {
291
+ ensureUid: false
292
+ });
354
293
  const uidRemaps = [];
355
- const mergedRecord = (0, import_lodash_es.mergeWith)(
356
- normalizedCurrentTempOrder,
357
- normalizedLoadedRecord,
358
- (currentValue, loadedValue, key) => {
359
- const collectionKind = getBaseSalesOrderCollectionKind(key);
360
- if (collectionKind && Array.isArray(loadedValue)) {
361
- return mergeBaseSalesOrderCollection(
362
- collectionKind,
363
- Array.isArray(currentValue) ? currentValue : [],
364
- loadedValue,
365
- strategy,
366
- uidRemaps
367
- );
368
- }
369
- if (Array.isArray(currentValue) && Array.isArray(loadedValue)) {
370
- if (key === "payments" || key === "payment") {
371
- return (0, import_payment_utils.mergeOrderPaymentListsByIdentity)(currentValue, loadedValue, {
372
- preserveUnmatchedExisting: true
373
- });
374
- }
375
- const metadataKey = getBaseSalesUniqueArrayMetadataKey(key);
376
- if (metadataKey) {
377
- return mergeBaseSalesUniqueArray(currentValue, loadedValue, metadataKey);
378
- }
379
- return [
380
- ...(0, import_lodash_es.cloneDeep)(currentValue),
381
- ...(0, import_lodash_es.cloneDeep)(loadedValue)
382
- ];
294
+ const mergedRecord = (0, _lodashEs.mergeWith)(normalizedCurrentTempOrder, normalizedLoadedRecord, (currentValue, loadedValue, key) => {
295
+ const collectionKind = getBaseSalesOrderCollectionKind(key);
296
+ if (collectionKind && Array.isArray(loadedValue)) {
297
+ return mergeBaseSalesOrderCollection(collectionKind, Array.isArray(currentValue) ? currentValue : [], loadedValue, strategy, uidRemaps);
298
+ }
299
+ if (Array.isArray(currentValue) && Array.isArray(loadedValue)) {
300
+ if (key === 'payments' || key === 'payment') {
301
+ return (0, _paymentUtils.mergeOrderPaymentListsByIdentity)(currentValue, loadedValue, {
302
+ preserveUnmatchedExisting: true
303
+ });
383
304
  }
384
- if (Array.isArray(loadedValue))
385
- return (0, import_lodash_es.cloneDeep)(loadedValue);
386
- if (Array.isArray(currentValue) && loadedValue === void 0) {
387
- return (0, import_lodash_es.cloneDeep)(currentValue);
305
+ const metadataKey = getBaseSalesUniqueArrayMetadataKey(key);
306
+ if (metadataKey) {
307
+ return mergeBaseSalesUniqueArray(currentValue, loadedValue, metadataKey);
388
308
  }
389
- return void 0;
309
+ return [...(0, _lodashEs.cloneDeep)(currentValue), ...(0, _lodashEs.cloneDeep)(loadedValue)];
390
310
  }
391
- );
311
+ if (Array.isArray(loadedValue)) return (0, _lodashEs.cloneDeep)(loadedValue);
312
+ if (Array.isArray(currentValue) && loadedValue === undefined) {
313
+ return (0, _lodashEs.cloneDeep)(currentValue);
314
+ }
315
+ return undefined;
316
+ });
392
317
  delete mergedRecord.request_unique_idempotency_token;
393
- return normalizeBaseSalesRecordCollections(
394
- (0, import_orderCollectionIdentity.applyOrderCollectionUidRemaps)(mergedRecord, uidRemaps)
395
- );
318
+ return normalizeBaseSalesRecordCollections((0, _orderCollectionIdentity.applyOrderCollectionUidRemaps)(mergedRecord, uidRemaps));
396
319
  }
397
320
  function filterPendingPaymentsFromLoadedSalesDetail(sourceRecord) {
398
- if (!sourceRecord || typeof sourceRecord !== "object")
399
- return sourceRecord;
400
- const record = { ...sourceRecord };
321
+ if (!sourceRecord || typeof sourceRecord !== 'object') return sourceRecord;
322
+ const record = {
323
+ ...sourceRecord
324
+ };
401
325
  if (Array.isArray(sourceRecord.payments)) {
402
- record.payments = sourceRecord.payments.filter((payment) => !(0, import_payment_utils.isPendingOrderPayment)(payment));
326
+ record.payments = sourceRecord.payments.filter(payment => !(0, _paymentUtils.isPendingOrderPayment)(payment));
403
327
  }
328
+ // 兼容少量历史详情数据使用的单数 payment 字段。
404
329
  if (Array.isArray(sourceRecord.payment)) {
405
- record.payment = sourceRecord.payment.filter((payment) => !(0, import_payment_utils.isPendingOrderPayment)(payment));
330
+ record.payment = sourceRecord.payment.filter(payment => !(0, _paymentUtils.isPendingOrderPayment)(payment));
406
331
  }
407
332
  return record;
408
333
  }
409
- var BaseSalesImpl = class extends import_BaseModule.BaseModule {
334
+
335
+ /**
336
+ * merge hydrate 不会统一给所有商品补 saved 标记,因此先只标记远端已保存商品。
337
+ * 当前 tempOrder 中尚未提交的本地商品会在 merge 后继续保持 current item 语义。
338
+ */
339
+ function markLoadedSalesDetailProductsAsSaved(sourceRecord) {
340
+ if (!sourceRecord || typeof sourceRecord !== 'object') return sourceRecord;
341
+ if (!Array.isArray(sourceRecord.products)) return sourceRecord;
342
+ return {
343
+ ...sourceRecord,
344
+ products: sourceRecord.products.map(product => ({
345
+ ...(product || {}),
346
+ metadata: {
347
+ ...(product?.metadata && typeof product.metadata === 'object' ? product.metadata : {}),
348
+ is_edit_for_runtime: true
349
+ }
350
+ }))
351
+ };
352
+ }
353
+ class BaseSalesImpl extends _BaseModule.BaseModule {
354
+ defaultName = 'baseSales';
355
+ defaultVersion = '1.0.0';
356
+ isSolution = true;
357
+ initializeOptions = {};
358
+ logger; // LoggerManager 实例
359
+ appPlugin;
360
+ store = {
361
+ order: undefined
362
+ };
363
+ otherParams = {};
364
+ cacheId;
365
+ /**
366
+ * 由已在初始化阶段解析过设备短号的业务解决方案写入。
367
+ * 未设置时,支付编号仍按原逻辑实时读取设备信息。
368
+ */
369
+ paymentNumberDevicePrefix = null;
370
+ /**
371
+ * window / request 暴露为 public:现存外部工具(如 BookingTicket Scan)通过
372
+ * `solution.window` / `solution.request` 直接访问插件,保持原有契约不破坏。
373
+ */
374
+ window;
375
+ request;
376
+
377
+ // 当前缓存中已加载的最新 SalesDetail;只读 getter 走它对外暴露详情数据。
378
+ currentSalesDetail = null;
379
+ discountConfigCacheKey = null;
380
+ hasManualDiscountSelection = false;
381
+ reusedSharedSubModuleNames = new Set();
382
+ paymentMethodsCache = [];
383
+ queuedAutoPaymentSync = false;
384
+ autoPaymentSyncFlushing = false;
385
+ autoPaymentSyncTimer = null;
386
+ salesDetailLoadInFlightCount = 0;
387
+ salesDetailLoadSequence = 0;
388
+ walletAssetsRefreshSequence = 0;
389
+ salesDetailHydrateQueue = Promise.resolve();
390
+ serverOrderChangeUnsubscribe = null;
391
+ serverOrderChangeHydrateInFlight = null;
392
+ queuedServerOrderChanges = [];
393
+ serverOrderChangeSyncEnabled = false;
410
394
  constructor(name, version) {
411
395
  super(name, version);
412
- this.defaultName = "baseSales";
413
- this.defaultVersion = "1.0.0";
414
- this.isSolution = true;
415
- this.initializeOptions = {};
416
- this.store = {
417
- order: void 0
418
- };
419
- this.otherParams = {};
420
- /**
421
- * 由已在初始化阶段解析过设备短号的业务解决方案写入。
422
- * 未设置时,支付编号仍按原逻辑实时读取设备信息。
423
- */
424
- this.paymentNumberDevicePrefix = null;
425
- // 当前缓存中已加载的最新 SalesDetail;只读 getter 走它对外暴露详情数据。
426
- this.currentSalesDetail = null;
427
- this.discountConfigCacheKey = null;
428
- this.hasManualDiscountSelection = false;
429
- this.reusedSharedSubModuleNames = /* @__PURE__ */ new Set();
430
- this.paymentMethodsCache = [];
431
- this.queuedAutoPaymentSync = false;
432
- this.autoPaymentSyncFlushing = false;
433
- this.autoPaymentSyncTimer = null;
434
- this.salesDetailLoadInFlightCount = 0;
435
- this.salesDetailLoadSequence = 0;
436
- this.walletAssetsRefreshSequence = 0;
437
- this.salesDetailHydrateQueue = Promise.resolve();
438
- this.serverOrderChangeUnsubscribe = null;
439
- this.serverOrderChangeHydrateInFlight = null;
440
- this.queuedServerOrderChanges = [];
441
- this.serverOrderChangeSyncEnabled = false;
442
396
  }
397
+
443
398
  /**
444
399
  * 子类可覆盖此方法以追加/收敛要注册的子模块。
445
400
  * 默认包含通用销售模块:products / order / salesSummary / schedule / payment / quotation。
446
401
  */
447
402
  getRegisteredModuleNames() {
448
- return ["products", "order", "salesSummary", "schedule", "payment", "quotation"];
403
+ return ['products', 'order', 'salesSummary', 'schedule', 'payment', 'quotation'];
449
404
  }
450
405
  getReusableSharedSubModule(moduleName) {
451
- var _a, _b;
452
- if (moduleName !== "schedule" && moduleName !== "quotation")
453
- return null;
454
- return ((_b = (_a = this.core) == null ? void 0 : _a.getModule) == null ? void 0 : _b.call(_a, moduleName)) || null;
406
+ if (moduleName !== 'schedule' && moduleName !== 'quotation') return null;
407
+ return this.core?.getModule?.(moduleName) || null;
455
408
  }
456
409
  isScheduleListLoaded(scheduleModule) {
457
- if (!scheduleModule)
458
- return false;
459
- if (typeof scheduleModule.isScheduleListLoaded === "function") {
410
+ if (!scheduleModule) return false;
411
+ if (typeof scheduleModule.isScheduleListLoaded === 'function') {
460
412
  return scheduleModule.isScheduleListLoaded();
461
413
  }
462
- if (typeof scheduleModule.getScheduleList === "function") {
414
+ if (typeof scheduleModule.getScheduleList === 'function') {
463
415
  return Array.isArray(scheduleModule.getScheduleList());
464
416
  }
465
417
  return false;
466
418
  }
419
+
467
420
  /**
468
421
  * 记录信息日志
469
422
  */
@@ -471,12 +424,13 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
471
424
  if (this.logger) {
472
425
  const tempOrder = this.getTempOrder();
473
426
  this.logger.addLog({
474
- type: "info",
475
- title: `[BaseSales] ${tempOrder == null ? void 0 : tempOrder.order_id} ${tempOrder == null ? void 0 : tempOrder.external_sale_number} ${title}`,
427
+ type: 'info',
428
+ title: `[BaseSales] ${tempOrder?.order_id} ${tempOrder?.external_sale_number} ${title}`,
476
429
  metadata: metadata || {}
477
430
  });
478
431
  }
479
432
  }
433
+
480
434
  /**
481
435
  * 记录警告日志
482
436
  */
@@ -484,12 +438,13 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
484
438
  if (this.logger) {
485
439
  const tempOrder = this.getTempOrder();
486
440
  this.logger.addLog({
487
- type: "warning",
488
- title: `[BaseSales] ${tempOrder == null ? void 0 : tempOrder.order_id} ${tempOrder == null ? void 0 : tempOrder.external_sale_number} ${title}`,
441
+ type: 'warning',
442
+ title: `[BaseSales] ${tempOrder?.order_id} ${tempOrder?.external_sale_number} ${title}`,
489
443
  metadata: metadata || {}
490
444
  });
491
445
  }
492
446
  }
447
+
493
448
  /**
494
449
  * 记录错误日志
495
450
  */
@@ -497,31 +452,24 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
497
452
  if (this.logger) {
498
453
  const tempOrder = this.getTempOrder();
499
454
  this.logger.addLog({
500
- type: "error",
501
- title: `[BaseSales] ${tempOrder == null ? void 0 : tempOrder.order_id} ${tempOrder == null ? void 0 : tempOrder.external_sale_number} ${title}`,
455
+ type: 'error',
456
+ title: `[BaseSales] ${tempOrder?.order_id} ${tempOrder?.external_sale_number} ${title}`,
502
457
  metadata: metadata || {}
503
458
  });
504
459
  }
505
460
  }
506
461
  isCurrentSalesOrderRecord(order) {
507
- var _a, _b;
508
- const currentTempOrder = (_b = (_a = this.store.order) == null ? void 0 : _a.getTempOrder) == null ? void 0 : _b.call(_a);
509
- const currentRecords = [
510
- currentTempOrder,
511
- this.currentSalesDetail
512
- ].filter(Boolean);
513
- return currentRecords.some((record) => isSameBaseSalesOrderRecord(record, order));
462
+ const currentTempOrder = this.store.order?.getTempOrder?.();
463
+ const currentRecords = [currentTempOrder, this.currentSalesDetail].filter(Boolean);
464
+ return currentRecords.some(record => isSameBaseSalesOrderRecord(record, order));
514
465
  }
515
466
  setServerOrderChangeSyncEnabled(enabled) {
516
467
  this.serverOrderChangeSyncEnabled = enabled;
517
- if (!enabled)
518
- this.queuedServerOrderChanges = [];
468
+ if (!enabled) this.queuedServerOrderChanges = [];
519
469
  }
520
470
  queueLatestServerOrderChange(order) {
521
- const snapshot = (0, import_lodash_es.cloneDeep)(order);
522
- const existingIndex = this.queuedServerOrderChanges.findIndex(
523
- (queued) => isSameBaseSalesOrderRecord(queued, snapshot)
524
- );
471
+ const snapshot = (0, _lodashEs.cloneDeep)(order);
472
+ const existingIndex = this.queuedServerOrderChanges.findIndex(queued => isSameBaseSalesOrderRecord(queued, snapshot));
525
473
  if (existingIndex >= 0) {
526
474
  this.queuedServerOrderChanges[existingIndex] = snapshot;
527
475
  return;
@@ -529,46 +477,40 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
529
477
  this.queuedServerOrderChanges.push(snapshot);
530
478
  }
531
479
  async drainQueuedServerOrderChanges() {
532
- if (!this.serverOrderChangeSyncEnabled || this.salesDetailLoadInFlightCount > 0 || this.serverOrderChangeHydrateInFlight || this.queuedServerOrderChanges.length === 0)
533
- return;
480
+ if (!this.serverOrderChangeSyncEnabled || this.salesDetailLoadInFlightCount > 0 || this.serverOrderChangeHydrateInFlight || this.queuedServerOrderChanges.length === 0) return;
534
481
  const changedOrders = this.queuedServerOrderChanges;
535
482
  this.queuedServerOrderChanges = [];
536
- await this.syncCurrentSalesDetailFromServerOrderChange({ changedOrders });
483
+ await this.syncCurrentSalesDetailFromServerOrderChange({
484
+ changedOrders
485
+ });
537
486
  }
538
487
  async syncCurrentSalesDetailFromServerOrderChange(payload) {
539
- 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] : [];
540
- if (!this.serverOrderChangeSyncEnabled)
541
- return;
488
+ const changedOrders = Array.isArray(payload) ? payload : Array.isArray(payload?.changedOrders) ? payload.changedOrders : payload?.data && typeof payload.data === 'object' ? [payload.data] : [];
489
+ if (!this.serverOrderChangeSyncEnabled) return;
490
+
491
+ // 显式详情加载期间 current 可能仍是上一单,先按订单身份 latest-only 缓存;
492
+ // load 完成后再用新的 current 过滤,避免恰好到达的最新支付快照丢失。
542
493
  if (this.salesDetailLoadInFlightCount > 0) {
543
- changedOrders.forEach(
544
- (order) => this.queueLatestServerOrderChange(order)
545
- );
494
+ changedOrders.forEach(order => this.queueLatestServerOrderChange(order));
546
495
  return;
547
496
  }
548
- const changedOrder = changedOrders.find(
549
- (order) => this.isCurrentSalesOrderRecord(order)
550
- );
551
- if (!changedOrder)
552
- return;
497
+ const changedOrder = changedOrders.find(order => this.isCurrentSalesOrderRecord(order));
498
+ if (!changedOrder) return;
553
499
  if (this.serverOrderChangeHydrateInFlight) {
554
500
  this.queueLatestServerOrderChange(changedOrder);
555
501
  return;
556
502
  }
557
- if (!this.store.order)
558
- return;
503
+ if (!this.store.order) return;
559
504
  this.serverOrderChangeHydrateInFlight = (async () => {
560
- var _a, _b;
561
- const currentTempOrder = (_b = (_a = this.store.order).getTempOrder) == null ? void 0 : _b.call(_a);
562
- const record = mergeSalesDetailRecordWithTempOrder(
563
- currentTempOrder,
564
- changedOrder,
565
- "authoritative-incoming"
566
- );
505
+ const currentTempOrder = this.store.order.getTempOrder?.();
506
+ const record = mergeSalesDetailRecordWithTempOrder(currentTempOrder, changedOrder, 'authoritative-incoming');
567
507
  const sales = await this.store.order.hydrateTempOrderFromRecord(record, {
568
508
  recalcOnHydrate: false
569
509
  });
570
510
  this.currentSalesDetail = sales;
571
- await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, { sales });
511
+ await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, {
512
+ sales
513
+ });
572
514
  })();
573
515
  try {
574
516
  await this.serverOrderChangeHydrateInFlight;
@@ -578,72 +520,81 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
578
520
  }
579
521
  }
580
522
  registerServerOrderChangeSync() {
581
- var _a, _b;
582
- (_a = this.serverOrderChangeUnsubscribe) == null ? void 0 : _a.call(this);
583
- const effects = (_b = this.core) == null ? void 0 : _b.effects;
584
- if (!effects || typeof effects.on !== "function")
585
- return;
586
- this.serverOrderChangeUnsubscribe = effects.on(SERVER_ORDER_CHANGED_EVENT, (payload) => {
587
- return this.syncCurrentSalesDetailFromServerOrderChange(payload).catch((error) => {
588
- this.logError("sync sales detail from server order change failed", {
523
+ this.serverOrderChangeUnsubscribe?.();
524
+ const effects = this.core?.effects;
525
+ if (!effects || typeof effects.on !== 'function') return;
526
+ this.serverOrderChangeUnsubscribe = effects.on(SERVER_ORDER_CHANGED_EVENT, payload => {
527
+ return this.syncCurrentSalesDetailFromServerOrderChange(payload).catch(error => {
528
+ this.logError('sync sales detail from server order change failed', {
589
529
  error: error instanceof Error ? error.message : String(error)
590
530
  });
591
531
  });
592
532
  });
593
533
  }
594
- async hydrateLatestLoadedSalesDetail(record, loadSequence, hydrateSource) {
534
+ async hydrateLatestLoadedSalesDetail(record, loadSequence, options) {
595
535
  let hydratedSales = null;
596
536
  let skippedBeforeHydrate = false;
597
537
  const hydrateTask = async () => {
538
+ // 网络返回顺序可能倒置;只有当前最新显式加载可以进入共享 tempOrder。
598
539
  if (loadSequence !== this.salesDetailLoadSequence) {
599
540
  skippedBeforeHydrate = true;
600
541
  return;
601
542
  }
602
- if (!this.store.order)
603
- throw new Error("order 模块未初始化");
604
- const sales = await this.store.order.hydrateTempOrderFromRecord(
605
- record,
606
- hydrateSource === "sessionStorage" ? { recalcOnHydrate: true, source: "sessionStorage" } : { recalcOnHydrate: false }
607
- );
543
+ if (!this.store.order) throw new Error('order 模块未初始化');
544
+ let hydrateOptions = {
545
+ recalcOnHydrate: false
546
+ };
547
+ if (options?.hydrateSource === 'sessionStorage') {
548
+ hydrateOptions = {
549
+ recalcOnHydrate: true,
550
+ source: 'sessionStorage'
551
+ };
552
+ } else if (options?.merge) {
553
+ hydrateOptions = {
554
+ recalcOnHydrate: true,
555
+ source: 'mergedSalesDetail'
556
+ };
557
+ }
558
+ const sales = await this.store.order.hydrateTempOrderFromRecord(record, hydrateOptions);
608
559
  hydratedSales = sales;
609
- if (loadSequence !== this.salesDetailLoadSequence)
610
- return;
560
+
561
+ // hydrate 期间可能又发起了更新请求;后续任务已串行排队,将负责最终状态。
562
+ if (loadSequence !== this.salesDetailLoadSequence) return;
611
563
  this.currentSalesDetail = sales;
612
- await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, { sales });
564
+ await this.core.effects.emit(`${this.name}:onSalesOrderLoaded`, {
565
+ sales
566
+ });
613
567
  };
614
568
  const queuedTask = this.salesDetailHydrateQueue.then(hydrateTask, hydrateTask);
615
- this.salesDetailHydrateQueue = queuedTask.then(
616
- () => void 0,
617
- () => void 0
618
- );
569
+ this.salesDetailHydrateQueue = queuedTask.then(() => undefined, () => undefined);
619
570
  await queuedTask;
620
- if (skippedBeforeHydrate)
621
- return record;
571
+ if (skippedBeforeHydrate) return record;
622
572
  return hydratedSales || this.currentSalesDetail || record;
623
573
  }
624
574
  hydrateOrderPaymentNames(payments) {
625
- if (!payments.length)
626
- return [];
575
+ if (!payments.length) return [];
627
576
  if (!this.paymentMethodsCache.length) {
628
- return payments.map((payment) => ({ ...payment }));
577
+ return payments.map(payment => ({
578
+ ...payment
579
+ }));
629
580
  }
630
- const paymentMethodById = /* @__PURE__ */ new Map();
631
- const paymentMethodByCode = /* @__PURE__ */ new Map();
632
- this.paymentMethodsCache.forEach((method) => {
633
- if ((method == null ? void 0 : method.id) !== void 0 && (method == null ? void 0 : method.id) !== null) {
581
+ const paymentMethodById = new Map();
582
+ const paymentMethodByCode = new Map();
583
+ this.paymentMethodsCache.forEach(method => {
584
+ if (method?.id !== undefined && method?.id !== null) {
634
585
  paymentMethodById.set(String(method.id), method);
635
586
  }
636
- if (method == null ? void 0 : method.code) {
587
+ if (method?.code) {
637
588
  paymentMethodByCode.set(String(method.code), method);
638
589
  }
639
590
  });
640
- return payments.map((payment) => {
641
- const nextPayment = { ...payment };
642
- if (nextPayment.name)
643
- return nextPayment;
591
+ return payments.map(payment => {
592
+ const nextPayment = {
593
+ ...payment
594
+ };
595
+ if (nextPayment.name) return nextPayment;
644
596
  const paymentMethod = paymentMethodById.get(String(nextPayment.custom_payment_id)) || paymentMethodByCode.get(String(nextPayment.code));
645
- if (!(paymentMethod == null ? void 0 : paymentMethod.name))
646
- return nextPayment;
597
+ if (!paymentMethod?.name) return nextPayment;
647
598
  return {
648
599
  ...nextPayment,
649
600
  name: paymentMethod.name
@@ -654,68 +605,58 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
654
605
  return this.store.payment;
655
606
  }
656
607
  getCurrentOrderCustomerId() {
657
- var _a, _b;
658
- const tempOrder = (_b = (_a = this.store.order) == null ? void 0 : _a.getTempOrder) == null ? void 0 : _b.call(_a);
659
- const customerId = tempOrder == null ? void 0 : tempOrder.customer_id;
660
- if (customerId === null || customerId === void 0)
661
- return void 0;
608
+ const tempOrder = this.store.order?.getTempOrder?.();
609
+ const customerId = tempOrder?.customer_id;
610
+ if (customerId === null || customerId === undefined) return undefined;
662
611
  return customerId;
663
612
  }
664
613
  normalizePriceContextCustomerId(customerId) {
665
- if (customerId === void 0 || customerId === null || customerId === "")
666
- return null;
614
+ if (customerId === undefined || customerId === null || customerId === '') return null;
667
615
  return String(customerId);
668
616
  }
669
617
  applyQuotationScheduleResolver(quotation) {
670
618
  const scheduleModule = this.store.schedule;
671
- if (!scheduleModule)
672
- return;
673
- const scheduleById = /* @__PURE__ */ new Map();
674
- const scheduleList = typeof scheduleModule.getScheduleList === "function" ? scheduleModule.getScheduleList() : [];
619
+ if (!scheduleModule) return;
620
+ const scheduleById = new Map();
621
+ const scheduleList = typeof scheduleModule.getScheduleList === 'function' ? scheduleModule.getScheduleList() : [];
675
622
  if (Array.isArray(scheduleList)) {
676
- scheduleList.forEach((schedule) => {
677
- if ((schedule == null ? void 0 : schedule.id) !== void 0 && (schedule == null ? void 0 : schedule.id) !== null) {
623
+ scheduleList.forEach(schedule => {
624
+ if (schedule?.id !== undefined && schedule?.id !== null) {
678
625
  scheduleById.set(String(schedule.id), schedule);
679
626
  }
680
627
  });
681
628
  }
682
- quotation.setScheduleResolver((id) => {
683
- var _a, _b;
629
+ quotation.setScheduleResolver(id => {
684
630
  const scheduleId = String(id);
685
- if (scheduleById.has(scheduleId))
686
- return scheduleById.get(scheduleId);
687
- const schedules = ((_a = scheduleModule.getScheduleListByIds) == null ? void 0 : _a.call(scheduleModule, [id])) || ((_b = scheduleModule.getScheduleByIds) == null ? void 0 : _b.call(scheduleModule, [id])) || [];
688
- if (schedules[0])
689
- scheduleById.set(scheduleId, schedules[0]);
631
+ if (scheduleById.has(scheduleId)) return scheduleById.get(scheduleId);
632
+ const schedules = scheduleModule.getScheduleListByIds?.([id]) || scheduleModule.getScheduleByIds?.([id]) || [];
633
+ if (schedules[0]) scheduleById.set(scheduleId, schedules[0]);
690
634
  return schedules[0];
691
635
  });
692
636
  }
693
637
  async loadQuotationForPriceQuery(params) {
694
- var _a;
695
- if (!params.quotation)
696
- return;
638
+ if (!params.quotation) return;
697
639
  this.applyQuotationScheduleResolver(params.quotation);
698
640
  await params.quotation.loadQuotations({
699
- channel: params.channel || ((_a = this.otherParams) == null ? void 0 : _a.channel),
641
+ channel: params.channel || this.otherParams?.channel,
700
642
  customer_id: params.customer_id
701
643
  });
702
644
  }
703
645
  getPriceQueryProductId(product) {
704
- const productId = Number((product == null ? void 0 : product.product_id) ?? (product == null ? void 0 : product.id));
705
- if (!Number.isFinite(productId))
706
- return null;
646
+ const productId = Number(product?.product_id ?? product?.id);
647
+ if (!Number.isFinite(productId)) return null;
707
648
  return productId;
708
649
  }
650
+
709
651
  /**
710
652
  * Change Time / customer reprice 必须沿用商品列表的渠道口径。
711
653
  * SalesSdk Provider 通常将渠道存为 platform,因此不能只读取 otherParams.channel。
712
654
  */
713
655
  getPriceQueryChannel(channel) {
714
- var _a, _b, _c;
715
- const strategyContext = ((_a = this.otherParams) == null ? void 0 : _a.strategy_context) && typeof this.otherParams.strategy_context === "object" ? this.otherParams.strategy_context : {};
716
- const value = channel ?? strategyContext.channel ?? ((_b = this.otherParams) == null ? void 0 : _b.channel) ?? ((_c = this.otherParams) == null ? void 0 : _c.platform);
717
- if (value === void 0 || value === null || String(value).trim() === "") {
718
- return void 0;
656
+ const strategyContext = this.otherParams?.strategy_context && typeof this.otherParams.strategy_context === 'object' ? this.otherParams.strategy_context : {};
657
+ const value = channel ?? strategyContext.channel ?? this.otherParams?.channel ?? this.otherParams?.platform;
658
+ if (value === undefined || value === null || String(value).trim() === '') {
659
+ return undefined;
719
660
  }
720
661
  return String(value).trim();
721
662
  }
@@ -724,14 +665,14 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
724
665
  * application_code 仅作为接口兼容字段,不能替代 channel / business_code。
725
666
  */
726
667
  getPriceQueryStrategyContext(channel) {
727
- var _a, _b, _c;
728
- const inherited = ((_a = this.otherParams) == null ? void 0 : _a.strategy_context) && typeof this.otherParams.strategy_context === "object" ? this.otherParams.strategy_context : {};
729
- const strategyContext = { ...inherited };
668
+ const inherited = this.otherParams?.strategy_context && typeof this.otherParams.strategy_context === 'object' ? this.otherParams.strategy_context : {};
669
+ const strategyContext = {
670
+ ...inherited
671
+ };
730
672
  const resolvedChannel = this.getPriceQueryChannel(channel);
731
- const businessCode = strategyContext.business_code ?? ((_b = this.otherParams) == null ? void 0 : _b.businessCode) ?? ((_c = this.otherParams) == null ? void 0 : _c.business_code);
732
- if (resolvedChannel)
733
- strategyContext.channel = resolvedChannel;
734
- if (businessCode !== void 0 && businessCode !== null && String(businessCode).trim() !== "") {
673
+ const businessCode = strategyContext.business_code ?? this.otherParams?.businessCode ?? this.otherParams?.business_code;
674
+ if (resolvedChannel) strategyContext.channel = resolvedChannel;
675
+ if (businessCode !== undefined && businessCode !== null && String(businessCode).trim() !== '') {
735
676
  strategyContext.business_code = String(businessCode).trim();
736
677
  }
737
678
  const availableWalletIds = this.getAvailableWalletIds();
@@ -740,11 +681,12 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
740
681
  }
741
682
  return strategyContext;
742
683
  }
684
+
743
685
  /**
744
686
  * 子类可在商品重报价前准备客户维度的策略上下文,例如等待 Wallet/优惠资产加载。
745
687
  */
746
- async prepareProductPriceQueryContext(_customerId) {
747
- }
688
+ async prepareProductPriceQueryContext(_customerId) {}
689
+
748
690
  /**
749
691
  * 默认保留 BaseSales 的 legacy quotation 行为;已由 /product/query 统一完成
750
692
  * 智能定价与报价合并的业务可在子类中覆盖,避免二次覆盖权威价格。
@@ -754,69 +696,64 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
754
696
  }
755
697
  getPriceQuerySchedule(params) {
756
698
  const booking = params.booking || {};
757
- if (typeof booking.start_date === "string" && booking.start_date.trim()) {
699
+ if (typeof booking.start_date === 'string' && booking.start_date.trim()) {
758
700
  const scheduleDate = booking.start_date.trim();
759
- const startTime = typeof booking.start_time === "string" && booking.start_time.trim() ? booking.start_time.trim() : "00:00:00";
760
- const datetime = (0, import_dayjs.default)(`${scheduleDate} ${startTime}`);
701
+ const startTime = typeof booking.start_time === 'string' && booking.start_time.trim() ? booking.start_time.trim() : '00:00:00';
702
+ const datetime = (0, _dayjs.default)(`${scheduleDate} ${startTime}`);
761
703
  return {
762
704
  schedule_date: scheduleDate,
763
- schedule_datetime: datetime.isValid() ? datetime.format("YYYY-MM-DD HH:mm:ss") : `${scheduleDate} ${startTime}`
705
+ schedule_datetime: datetime.isValid() ? datetime.format('YYYY-MM-DD HH:mm:ss') : `${scheduleDate} ${startTime}`
764
706
  };
765
707
  }
766
- if (typeof params.datetime === "string" && params.datetime.trim()) {
767
- const datetime = (0, import_dayjs.default)(params.datetime.trim());
708
+ if (typeof params.datetime === 'string' && params.datetime.trim()) {
709
+ const datetime = (0, _dayjs.default)(params.datetime.trim());
768
710
  if (datetime.isValid()) {
769
711
  return {
770
- schedule_date: datetime.format("YYYY-MM-DD"),
771
- schedule_datetime: datetime.format("YYYY-MM-DD HH:mm:ss")
712
+ schedule_date: datetime.format('YYYY-MM-DD'),
713
+ schedule_datetime: datetime.format('YYYY-MM-DD HH:mm:ss')
772
714
  };
773
715
  }
774
716
  }
775
- const now = (0, import_dayjs.default)();
717
+ const now = (0, _dayjs.default)();
776
718
  return {
777
- schedule_date: now.format("YYYY-MM-DD"),
778
- schedule_datetime: now.format("YYYY-MM-DD HH:mm:ss")
719
+ schedule_date: now.format('YYYY-MM-DD'),
720
+ schedule_datetime: now.format('YYYY-MM-DD HH:mm:ss')
779
721
  };
780
722
  }
781
723
  async loadProductsForPriceQuery(params) {
782
- var _a;
783
- const ids = Array.from(new Set(
784
- params.ids.filter((id) => Number.isFinite(id))
785
- ));
786
- const productsById = /* @__PURE__ */ new Map();
787
- if (!ids.length || !this.request)
788
- return productsById;
724
+ const ids = Array.from(new Set(params.ids.filter(id => Number.isFinite(id))));
725
+ const productsById = new Map();
726
+ if (!ids.length || !this.request) return productsById;
789
727
  const channel = this.getPriceQueryChannel(params.channel);
790
728
  const strategyContext = this.getPriceQueryStrategyContext(channel);
791
729
  try {
792
- const response = await this.request.post("/product/query", {
730
+ const response = await this.request.post('/product/query', {
793
731
  ids,
794
732
  open_quotation: 1,
795
733
  open_bundle: 1,
796
- status: "published",
734
+ status: 'published',
797
735
  num: 1,
798
736
  skip: 1,
799
737
  customer_id: params.customerId,
800
738
  schedule_date: params.schedule.schedule_date,
801
739
  schedule_datetime: params.schedule.schedule_datetime,
802
740
  application_code: channel,
803
- ...Object.keys(strategyContext).length ? { strategy_context: strategyContext } : {}
741
+ ...(Object.keys(strategyContext).length ? {
742
+ strategy_context: strategyContext
743
+ } : {})
804
744
  }, {
805
745
  osServer: true,
806
- customToast: () => {
807
- }
746
+ customToast: () => {}
808
747
  });
809
- const list = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.list) || (response == null ? void 0 : response.list) || [];
810
- if (!Array.isArray(list))
811
- return productsById;
812
- list.forEach((item) => {
813
- const productId = Number((item == null ? void 0 : item.id) ?? (item == null ? void 0 : item.product_id));
814
- if (Number.isFinite(productId))
815
- productsById.set(productId, item);
748
+ const list = response?.data?.list || response?.list || [];
749
+ if (!Array.isArray(list)) return productsById;
750
+ list.forEach(item => {
751
+ const productId = Number(item?.id ?? item?.product_id);
752
+ if (Number.isFinite(productId)) productsById.set(productId, item);
816
753
  });
817
754
  return productsById;
818
755
  } catch (error) {
819
- this.logWarning("loadProductsForPriceQuery: 商品批量重查失败,使用入参 fallback", {
756
+ this.logWarning('loadProductsForPriceQuery: 商品批量重查失败,使用入参 fallback', {
820
757
  ids,
821
758
  error: error instanceof Error ? error.message : String(error)
822
759
  });
@@ -826,8 +763,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
826
763
  async loadProductForPriceQuery(params, customerId) {
827
764
  const product = params.product || {};
828
765
  const productId = this.getPriceQueryProductId(product);
829
- if (productId === null || !this.request)
830
- return null;
766
+ if (productId === null || !this.request) return null;
831
767
  const schedule = this.getPriceQuerySchedule(params);
832
768
  const productsById = await this.loadProductsForPriceQuery({
833
769
  ids: [productId],
@@ -838,34 +774,30 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
838
774
  return productsById.get(productId) || null;
839
775
  }
840
776
  getAuthoritativeBundleItems(product) {
841
- if (Array.isArray(product == null ? void 0 : product.product_bundle))
842
- return product.product_bundle;
843
- const groups = Array.isArray(product == null ? void 0 : product.bundle_group) ? product.bundle_group : Array.isArray(product == null ? void 0 : product.bundleGroup) ? product.bundleGroup : [];
844
- return groups.flatMap((group) => {
845
- const items = Array.isArray(group == null ? void 0 : group.bundle_item) ? group.bundle_item : Array.isArray(group == null ? void 0 : group.bundleItem) ? group.bundleItem : [];
846
- return items.map((item) => ({
777
+ if (Array.isArray(product?.product_bundle)) return product.product_bundle;
778
+ const groups = Array.isArray(product?.bundle_group) ? product.bundle_group : Array.isArray(product?.bundleGroup) ? product.bundleGroup : [];
779
+ return groups.flatMap(group => {
780
+ const items = Array.isArray(group?.bundle_item) ? group.bundle_item : Array.isArray(group?.bundleItem) ? group.bundleItem : [];
781
+ return items.map(item => ({
847
782
  ...item,
848
- group_id: (item == null ? void 0 : item.group_id) ?? (group == null ? void 0 : group.id),
849
- bundle_group_id: (item == null ? void 0 : item.bundle_group_id) ?? (item == null ? void 0 : item.group_id) ?? (group == null ? void 0 : group.id)
783
+ group_id: item?.group_id ?? group?.id,
784
+ bundle_group_id: item?.bundle_group_id ?? item?.group_id ?? group?.id
850
785
  }));
851
786
  });
852
787
  }
853
788
  findAuthoritativeBundleItem(bundle, candidates) {
854
789
  const bundleId = bundle.bundle_id ?? bundle.id;
855
790
  if (bundleId != null) {
856
- const matchedById = candidates.find((item) => String((item == null ? void 0 : item.bundle_id) ?? (item == null ? void 0 : item.id)) === String(bundleId));
857
- if (matchedById)
858
- return matchedById;
791
+ const matchedById = candidates.find(item => String(item?.bundle_id ?? item?.id) === String(bundleId));
792
+ if (matchedById) return matchedById;
859
793
  }
860
794
  const productId = bundle.bundle_product_id ?? bundle._bundle_product_id;
861
795
  const groupId = bundle.bundle_group_id ?? bundle.group_id;
862
- return candidates.find((item) => {
863
- const itemProductId = (item == null ? void 0 : item.bundle_product_id) ?? (item == null ? void 0 : item._bundle_product_id);
864
- const itemGroupId = (item == null ? void 0 : item.bundle_group_id) ?? (item == null ? void 0 : item.group_id);
865
- if (productId == null || String(itemProductId) !== String(productId))
866
- return false;
867
- if (groupId == null)
868
- return true;
796
+ return candidates.find(item => {
797
+ const itemProductId = item?.bundle_product_id ?? item?._bundle_product_id;
798
+ const itemGroupId = item?.bundle_group_id ?? item?.group_id;
799
+ if (productId == null || String(itemProductId) !== String(productId)) return false;
800
+ if (groupId == null) return true;
869
801
  return String(itemGroupId) === String(groupId);
870
802
  }) || null;
871
803
  }
@@ -873,21 +805,19 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
873
805
  return bundle.price ?? bundle.bundle_selling_price ?? bundle.custom_price ?? bundle.product_price ?? bundle.base_price;
874
806
  }
875
807
  mergeProductForPriceQuery(product, authoritativeProduct) {
876
- if (!authoritativeProduct)
877
- return product;
808
+ if (!authoritativeProduct) return product;
878
809
  const selectedBundles = Array.isArray(product.product_bundle) ? product.product_bundle : [];
879
810
  const authoritativeBundles = this.getAuthoritativeBundleItems(authoritativeProduct);
880
- const productBundle = selectedBundles.map((bundle) => {
811
+ const productBundle = selectedBundles.map(bundle => {
881
812
  const authoritativeBundle = this.findAuthoritativeBundleItem(bundle, authoritativeBundles);
882
- const unitPrice = authoritativeBundle ? this.getAuthoritativeBundleUnitPrice(authoritativeBundle) : void 0;
883
- if (unitPrice === void 0 || unitPrice === null || unitPrice === "")
884
- return bundle;
813
+ const unitPrice = authoritativeBundle ? this.getAuthoritativeBundleUnitPrice(authoritativeBundle) : undefined;
814
+ if (unitPrice === undefined || unitPrice === null || unitPrice === '') return bundle;
885
815
  return {
886
816
  ...bundle,
887
817
  price: unitPrice,
888
818
  bundle_selling_price: unitPrice,
889
- base_price: (authoritativeBundle == null ? void 0 : authoritativeBundle.base_price) ?? bundle.base_price,
890
- product_price: (authoritativeBundle == null ? void 0 : authoritativeBundle.product_price) ?? bundle.product_price
819
+ base_price: authoritativeBundle?.base_price ?? bundle.base_price,
820
+ product_price: authoritativeBundle?.product_price ?? bundle.product_price
891
821
  };
892
822
  });
893
823
  return {
@@ -899,9 +829,9 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
899
829
  num: product.num ?? product.quantity ?? authoritativeProduct.num,
900
830
  quantity: product.quantity ?? product.num ?? authoritativeProduct.quantity,
901
831
  product_sku: (() => {
902
- const authoritativeSku = (0, import_utils.ensureProductSku)(authoritativeProduct);
903
- const productSku = (0, import_utils.ensureProductSku)(product);
904
- const hasProductSku = product.product_sku && typeof product.product_sku === "object";
832
+ const authoritativeSku = (0, _utils.ensureProductSku)(authoritativeProduct);
833
+ const productSku = (0, _utils.ensureProductSku)(product);
834
+ const hasProductSku = product.product_sku && typeof product.product_sku === 'object';
905
835
  return {
906
836
  ...authoritativeSku,
907
837
  ...productSku,
@@ -913,30 +843,30 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
913
843
  };
914
844
  }
915
845
  getSubmitOrderSalesChannel() {
916
- var _a;
917
- return (_a = this.otherParams) == null ? void 0 : _a.channel;
846
+ return this.otherParams?.channel;
918
847
  }
848
+
919
849
  /**
920
850
  * 工厂入口:根据子模块名实例化对应模块。
921
851
  * 默认使用 BookingByStep 公共 `createModule`。子类若需引入额外类型(如 customer),
922
852
  * 可覆盖此方法并把未识别的 name 委托给 `super.createSubModule(name)`。
923
853
  */
924
854
  createSubModule(moduleName) {
925
- if (moduleName === "quotation") {
926
- return new import_Quotation.QuotationModule(`${this.name}_quotation`);
855
+ if (moduleName === 'quotation') {
856
+ return new _Quotation.QuotationModule(`${this.name}_quotation`);
927
857
  }
928
- return (0, import_types2.createModule)(moduleName, this.name);
858
+ return (0, _types2.createModule)(moduleName, this.name);
929
859
  }
930
860
  getSubModuleHooks(moduleName) {
931
- var _a, _b;
932
861
  const optionHooks = this.initializeOptions.hooks || {};
933
862
  const otherHooks = this.otherParams.hooks || {};
934
- if (moduleName === "order") {
863
+ if (moduleName === 'order') {
935
864
  const directOrderHooks = optionHooks;
936
- return optionHooks.order || ((_a = this.otherParams.order) == null ? void 0 : _a.hooks) || otherHooks.order || (directOrderHooks.onBeforeMergeProductToOrder ? directOrderHooks : void 0);
865
+ return optionHooks.order || this.otherParams.order?.hooks || otherHooks.order || (directOrderHooks.onBeforeMergeProductToOrder ? directOrderHooks : undefined);
937
866
  }
938
- return optionHooks[moduleName] || ((_b = this.otherParams[moduleName]) == null ? void 0 : _b.hooks) || otherHooks[moduleName];
867
+ return optionHooks[moduleName] || this.otherParams[moduleName]?.hooks || otherHooks[moduleName];
939
868
  }
869
+
940
870
  /**
941
871
  * 构造传给 BaseSales 子模块的完整运行态参数,保证初始化和后续同步语义一致。
942
872
  *
@@ -959,30 +889,32 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
959
889
  cacheId: this.cacheId
960
890
  };
961
891
  }
892
+
962
893
  /**
963
894
  * 将父级 otherParams 的变更显式同步给已注册的子模块。
964
895
  *
965
896
  * @example
966
897
  * await this.syncOtherParamsToSubModules({ channel: 'pos' });
967
898
  */
968
- async syncOtherParamsToSubModules(changedParams, { cover = false } = {}) {
969
- await Promise.all(
970
- Object.entries(this.store).map(async ([moduleName, subModule]) => {
971
- if (this.reusedSharedSubModuleNames.has(moduleName)) {
972
- return;
973
- }
974
- const targetModule = subModule;
975
- if (!targetModule || typeof targetModule.updateOtherParams !== "function") {
976
- return;
977
- }
978
- const nextSubModuleOtherParams = this.buildSubModuleOtherParams(moduleName);
979
- await targetModule.updateOtherParams(nextSubModuleOtherParams, {
980
- changedParams,
981
- cover
982
- });
983
- })
984
- );
899
+ async syncOtherParamsToSubModules(changedParams, {
900
+ cover = false
901
+ } = {}) {
902
+ await Promise.all(Object.entries(this.store).map(async ([moduleName, subModule]) => {
903
+ if (this.reusedSharedSubModuleNames.has(moduleName)) {
904
+ return;
905
+ }
906
+ const targetModule = subModule;
907
+ if (!targetModule || typeof targetModule.updateOtherParams !== 'function') {
908
+ return;
909
+ }
910
+ const nextSubModuleOtherParams = this.buildSubModuleOtherParams(moduleName);
911
+ await targetModule.updateOtherParams(nextSubModuleOtherParams, {
912
+ changedParams,
913
+ cover
914
+ });
915
+ }));
985
916
  }
917
+
986
918
  /**
987
919
  * 读取 sessionStorage[this.name][cacheId],作为子模块 initialState 的来源。
988
920
  * sessionStorage 损坏时静默忽略,按空状态注册。
@@ -994,8 +926,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
994
926
  }
995
927
  try {
996
928
  const sessionData = this.window.sessionStorage.getItem(this.name);
997
- if (!sessionData)
998
- return {};
929
+ if (!sessionData) return {};
999
930
  const data = JSON.parse(sessionData);
1000
931
  return data && data[cacheId] || {};
1001
932
  } catch {
@@ -1003,64 +934,61 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1003
934
  }
1004
935
  }
1005
936
  getAppData(key) {
1006
- var _a, _b, _c, _d, _e, _f;
1007
- const getData = (_b = (_a = this.appPlugin).getData) == null ? void 0 : _b.call(_a);
1008
- if (typeof getData === "function")
1009
- return getData(key);
937
+ const getData = this.appPlugin.getData?.();
938
+ if (typeof getData === 'function') return getData(key);
1010
939
  const app = this.appPlugin.getApp();
1011
- 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");
1012
- return coreData == null ? void 0 : coreData[key];
940
+ const coreData = app?.models?.getStore?.().getDataByModel?.('core', 'core');
941
+ return coreData?.[key];
1013
942
  }
943
+
1014
944
  /**
1015
945
  * 复用业务解决方案初始化时已解析的支付设备短号。
1016
946
  * 空值会清除缓存,使后续支付恢复实时读取设备信息的兼容路径。
1017
947
  */
1018
948
  setPaymentNumberDevicePrefix(prefix) {
1019
- const normalized = String(prefix ?? "").trim();
949
+ const normalized = String(prefix ?? '').trim();
1020
950
  this.paymentNumberDevicePrefix = normalized || null;
1021
951
  }
1022
952
  getPaymentNumberDevicePrefixSync() {
1023
- if (!this.appPlugin)
1024
- return "LOCAL";
1025
- return (0, import_payment_number.resolvePaymentNumberDevicePrefixFromDeviceId)((key) => this.getAppData(key));
953
+ if (!this.appPlugin) return 'LOCAL';
954
+ return (0, _paymentNumber.resolvePaymentNumberDevicePrefixFromDeviceId)(key => this.getAppData(key));
1026
955
  }
1027
956
  getPaymentNumberDevicePrefixAsync() {
1028
- if (!this.appPlugin)
1029
- return Promise.resolve("LOCAL");
957
+ if (!this.appPlugin) return Promise.resolve('LOCAL');
1030
958
  if (this.paymentNumberDevicePrefix) {
1031
959
  return Promise.resolve(this.paymentNumberDevicePrefix);
1032
960
  }
1033
- return (0, import_payment_number.resolvePaymentNumberDevicePrefix)((key) => this.getAppData(key));
961
+ return (0, _paymentNumber.resolvePaymentNumberDevicePrefix)(key => this.getAppData(key));
1034
962
  }
1035
963
  syncAppDataToTempOrder(tempOrder) {
1036
- const isPriceIncludeTax = this.getAppData("is_price_include_tax");
1037
- const taxCountryCode = this.getAppData("tax_country_code");
1038
- const currencyCode = this.getAppData("shop_currency_code");
1039
- const currencySymbol = this.getAppData("shop_symbol");
964
+ const isPriceIncludeTax = this.getAppData('is_price_include_tax');
965
+ const taxCountryCode = this.getAppData('tax_country_code');
966
+ const currencyCode = this.getAppData('shop_currency_code');
967
+ const currencySymbol = this.getAppData('shop_symbol');
1040
968
  let isChanged = false;
1041
- if (isPriceIncludeTax !== void 0) {
969
+ if (isPriceIncludeTax !== undefined) {
1042
970
  const nextIsPriceIncludeTax = Number(isPriceIncludeTax);
1043
971
  if ((nextIsPriceIncludeTax === 0 || nextIsPriceIncludeTax === 1) && tempOrder.is_price_include_tax !== nextIsPriceIncludeTax) {
1044
972
  tempOrder.is_price_include_tax = nextIsPriceIncludeTax;
1045
973
  isChanged = true;
1046
974
  }
1047
975
  }
1048
- if (taxCountryCode !== void 0) {
1049
- const nextTaxCountryCode = String(taxCountryCode || "");
976
+ if (taxCountryCode !== undefined) {
977
+ const nextTaxCountryCode = String(taxCountryCode || '');
1050
978
  if (tempOrder.tax_country_code !== nextTaxCountryCode) {
1051
979
  tempOrder.tax_country_code = nextTaxCountryCode;
1052
980
  isChanged = true;
1053
981
  }
1054
982
  }
1055
- if (currencyCode !== void 0) {
1056
- const nextCurrencyCode = String(currencyCode || "");
983
+ if (currencyCode !== undefined) {
984
+ const nextCurrencyCode = String(currencyCode || '');
1057
985
  if (tempOrder.currency_code !== nextCurrencyCode) {
1058
986
  tempOrder.currency_code = nextCurrencyCode;
1059
987
  isChanged = true;
1060
988
  }
1061
989
  }
1062
- if (currencySymbol !== void 0) {
1063
- const nextCurrencySymbol = String(currencySymbol || "");
990
+ if (currencySymbol !== undefined) {
991
+ const nextCurrencySymbol = String(currencySymbol || '');
1064
992
  if (tempOrder.currency_symbol !== nextCurrencySymbol) {
1065
993
  tempOrder.currency_symbol = nextCurrencySymbol;
1066
994
  isChanged = true;
@@ -1069,23 +997,26 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1069
997
  return isChanged;
1070
998
  }
1071
999
  async initialize(core, options = {}) {
1072
- var _a, _b, _c, _d;
1073
1000
  this.core = core;
1074
1001
  this.initializeOptions = options || {};
1075
1002
  this.paymentNumberDevicePrefix = null;
1003
+ // this.store = { ...this.store, ...(options.store as Partial<BaseSalesState>) };
1076
1004
  this.otherParams = options.otherParams || {};
1077
- this.cacheId = (_a = this.otherParams) == null ? void 0 : _a.cacheId;
1005
+ this.cacheId = this.otherParams?.cacheId;
1078
1006
  this.reusedSharedSubModuleNames.clear();
1079
- this.window = core.getPlugin("window");
1080
- this.request = core.getPlugin("request");
1081
- this.appPlugin = core.getPlugin("app");
1007
+ this.window = core.getPlugin('window');
1008
+ this.request = core.getPlugin('request');
1009
+
1010
+ // 获取 logger 实例
1011
+ this.appPlugin = core.getPlugin('app');
1082
1012
  if (!this.appPlugin) {
1013
+ // throw new Error('Checkout 解决方案需要 app 插件支持');
1083
1014
  }
1084
- const app = (_c = (_b = this.appPlugin) == null ? void 0 : _b.getApp) == null ? void 0 : _c.call(_b);
1085
- this.logger = app == null ? void 0 : app.logger;
1015
+ const app = this.appPlugin?.getApp?.();
1016
+ this.logger = app?.logger;
1086
1017
  const targetCacheData = this.readSessionCacheData();
1087
1018
  const moduleNames = this.getRegisteredModuleNames();
1088
- moduleNames.forEach((step) => {
1019
+ moduleNames.forEach(step => {
1089
1020
  const reusedModule = this.getReusableSharedSubModule(step);
1090
1021
  if (reusedModule) {
1091
1022
  this.store[step] = reusedModule;
@@ -1099,32 +1030,30 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1099
1030
  const hooks = this.getSubModuleHooks(step);
1100
1031
  this.store[step] = targetModule;
1101
1032
  this.core.registerModule(targetModule, {
1102
- initialState: this.shouldUseSessionStorageForSubModule(step) ? (targetCacheData == null ? void 0 : targetCacheData[targetModule.name]) || {} : {},
1103
- ...hooks ? { hooks } : {},
1033
+ initialState: this.shouldUseSessionStorageForSubModule(step) ? targetCacheData?.[targetModule.name] || {} : {},
1034
+ ...(hooks ? {
1035
+ hooks
1036
+ } : {}),
1104
1037
  otherParams: this.buildSubModuleOtherParams(step)
1105
1038
  });
1106
1039
  });
1107
1040
  if (this.store.schedule && !this.isScheduleListLoaded(this.store.schedule)) {
1108
1041
  await this.store.schedule.loadAllSchedule();
1109
1042
  }
1110
- if (this.store.order && typeof ((_d = this.otherParams) == null ? void 0 : _d.enableTempOrderPersist) === "boolean") {
1111
- this.store.order.setEnableTempOrderPersist(
1112
- this.otherParams.enableTempOrderPersist
1113
- );
1043
+ if (this.store.order && typeof this.otherParams?.enableTempOrderPersist === 'boolean') {
1044
+ this.store.order.setEnableTempOrderPersist(this.otherParams.enableTempOrderPersist);
1114
1045
  }
1115
1046
  await this.getPaymentMethodsAsync();
1116
1047
  this.registerServerOrderChangeSync();
1117
1048
  this.core.effects.emit(`${this.name}:onInited`, {});
1118
1049
  }
1119
1050
  async destroy() {
1120
- var _a;
1121
- (_a = this.serverOrderChangeUnsubscribe) == null ? void 0 : _a.call(this);
1051
+ this.serverOrderChangeUnsubscribe?.();
1122
1052
  this.serverOrderChangeUnsubscribe = null;
1123
- Object.keys(this.store).forEach((key) => {
1124
- if (this.reusedSharedSubModuleNames.has(key))
1125
- return;
1053
+ Object.keys(this.store).forEach(key => {
1054
+ if (this.reusedSharedSubModuleNames.has(key)) return;
1126
1055
  const sub = this.store[key];
1127
- if (sub && typeof sub.destroy === "function") {
1056
+ if (sub && typeof sub.destroy === 'function') {
1128
1057
  try {
1129
1058
  sub.destroy();
1130
1059
  } catch (error) {
@@ -1140,6 +1069,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1140
1069
  await this.core.effects.emit(`${this.name}:onDestroy`, {});
1141
1070
  super.destroy();
1142
1071
  }
1072
+
1143
1073
  /**
1144
1074
  * 加载销售订单到统一 tempOrder 工作区。
1145
1075
  * 统一通过 OrderModule 的 sales detail lookup 加载订单详情。
@@ -1148,149 +1078,136 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1148
1078
  * (比如把 `sales.customer` 写入 CustomerModule、emit 业务 hook 等)。
1149
1079
  */
1150
1080
  async loadSalesDetail(orderIdOrParams) {
1151
- if (!this.store.order)
1152
- throw new Error("order 模块未初始化");
1081
+ if (!this.store.order) throw new Error('order 模块未初始化');
1153
1082
  const loadSequence = ++this.salesDetailLoadSequence;
1154
1083
  this.salesDetailLoadInFlightCount += 1;
1155
1084
  try {
1156
- const params = typeof orderIdOrParams === "object" ? orderIdOrParams : { orderId: orderIdOrParams };
1085
+ const params = typeof orderIdOrParams === 'object' ? orderIdOrParams : {
1086
+ orderId: orderIdOrParams
1087
+ };
1157
1088
  const externalSaleNumber = params.externalSaleNumber || params.external_sale_number;
1158
1089
  const preloadedSalesDetail = params.preloadedSalesDetail;
1159
- 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);
1160
- if (!preloadedSalesDetail && (lookup === void 0 || lookup === null || lookup === "")) {
1161
- throw new Error("加载销售详情需要 orderId、externalSaleNumber 或 orderNumber");
1090
+ const lookup = params.orderId ?? externalSaleNumber ?? params.orderNumber ?? preloadedSalesDetail?.order_id ?? preloadedSalesDetail?.external_sale_number ?? preloadedSalesDetail?.order_number;
1091
+ if (!preloadedSalesDetail && (lookup === undefined || lookup === null || lookup === '')) {
1092
+ throw new Error('加载销售详情需要 orderId、externalSaleNumber 或 orderNumber');
1162
1093
  }
1163
- const loadedRecord = preloadedSalesDetail ?? await this.store.order.getSalesOrderByLookup({
1094
+ // GlobalSearch 等调用方已拿到完整详情时,直接进入查询成功后的 hydrate 流程,避免按 id 二次请求。
1095
+ const loadedRecord = preloadedSalesDetail ?? (await this.store.order.getSalesOrderByLookup({
1164
1096
  lookup,
1165
1097
  forceRemote: params.forceRemote
1166
- });
1098
+ }));
1167
1099
  if (!preloadedSalesDetail && (!loadedRecord || loadedRecord.code !== 200)) {
1168
1100
  const message = loadedRecord && (loadedRecord.message || loadedRecord.msg) || `加载销售详情失败: ${lookup}`;
1169
1101
  throw new Error(message);
1170
1102
  }
1171
1103
  const loadedSalesDetail = preloadedSalesDetail ?? loadedRecord.data;
1172
- const shouldFilterPendingPayments = params.hydrateSource !== "sessionStorage";
1104
+ // payment_pending 只存在于本地;远端详情需过滤,但会话快照必须完整恢复。
1105
+ const shouldFilterPendingPayments = params.hydrateSource !== 'sessionStorage';
1173
1106
  const remoteRecord = shouldFilterPendingPayments ? filterPendingPaymentsFromLoadedSalesDetail(loadedSalesDetail) : loadedSalesDetail;
1107
+ const mergeSourceRecord = params.merge ? markLoadedSalesDetailProductsAsSaved(remoteRecord) : remoteRecord;
1174
1108
  const currentTempOrder = params.merge ? this.store.order.getTempOrder() : null;
1175
- const mergedRecord = params.merge ? mergeSalesDetailRecordWithTempOrder(
1176
- currentTempOrder,
1177
- remoteRecord,
1178
- "preserve-local"
1179
- ) : remoteRecord;
1109
+ const mergedRecord = params.merge ? mergeSalesDetailRecordWithTempOrder(currentTempOrder, mergeSourceRecord, 'preserve-local') : mergeSourceRecord;
1180
1110
  const record = shouldFilterPendingPayments ? filterPendingPaymentsFromLoadedSalesDetail(mergedRecord) : mergedRecord;
1181
- return await this.hydrateLatestLoadedSalesDetail(
1182
- record,
1183
- loadSequence,
1184
- params.hydrateSource
1185
- );
1111
+ return await this.hydrateLatestLoadedSalesDetail(record, loadSequence, {
1112
+ hydrateSource: params.hydrateSource,
1113
+ merge: params.merge
1114
+ });
1186
1115
  } finally {
1187
- this.salesDetailLoadInFlightCount = Math.max(
1188
- 0,
1189
- this.salesDetailLoadInFlightCount - 1
1190
- );
1116
+ this.salesDetailLoadInFlightCount = Math.max(0, this.salesDetailLoadInFlightCount - 1);
1191
1117
  if (this.salesDetailLoadInFlightCount === 0) {
1192
1118
  try {
1193
1119
  await this.drainQueuedServerOrderChanges();
1194
1120
  } catch (error) {
1195
- this.logError("drain queued server order changes failed", {
1121
+ this.logError('drain queued server order changes failed', {
1196
1122
  error: error instanceof Error ? error.message : String(error)
1197
1123
  });
1198
1124
  }
1199
1125
  }
1200
1126
  }
1201
1127
  }
1128
+
1202
1129
  /** 获取当前已加载的销售详情(只读快照)。未加载过则返回 null。 */
1203
1130
  getSalesOrder() {
1204
1131
  return this.currentSalesDetail;
1205
1132
  }
1133
+
1206
1134
  /** 获取销售详情顶部业务字段(订单号/状态/金额等通用字段集合)。 */
1207
1135
  getOrderHeader() {
1208
- if (!this.currentSalesDetail)
1209
- return null;
1136
+ if (!this.currentSalesDetail) return null;
1210
1137
  return this.currentSalesDetail.header || this.currentSalesDetail;
1211
1138
  }
1139
+
1212
1140
  /** 获取所有 booking(含 root + children),按服务端原始顺序输出。 */
1213
1141
  getBookings() {
1214
- var _a;
1215
- return ((_a = this.currentSalesDetail) == null ? void 0 : _a.bookings) || [];
1142
+ return this.currentSalesDetail?.bookings || [];
1216
1143
  }
1144
+
1217
1145
  /** 获取根 booking(is_next === 0 / is_root === 1),多个时取第一个。 */
1218
1146
  getRootBooking() {
1219
- if (!this.currentSalesDetail)
1220
- return null;
1221
- if (this.currentSalesDetail.rootBooking)
1222
- return this.currentSalesDetail.rootBooking;
1147
+ if (!this.currentSalesDetail) return null;
1148
+ if (this.currentSalesDetail.rootBooking) return this.currentSalesDetail.rootBooking;
1223
1149
  const bookings = this.currentSalesDetail.bookings || [];
1224
- return bookings.find((booking) => {
1225
- const parentId = booking == null ? void 0 : booking.parent_id;
1226
- return parentId === 0 || parentId === null || parentId === void 0;
1150
+ return bookings.find(booking => {
1151
+ const parentId = booking?.parent_id;
1152
+ return parentId === 0 || parentId === null || parentId === undefined;
1227
1153
  }) || null;
1228
1154
  }
1155
+
1229
1156
  /** 按 product_uid 反查 booking 列表(用于商品行 ↔ booking 映射)。 */
1230
1157
  getChildBookingsByProductUid(productUid) {
1231
- var _a;
1232
- if (!this.currentSalesDetail || !productUid)
1233
- return [];
1234
- const indexed = (_a = this.currentSalesDetail.bookingsByProductUid) == null ? void 0 : _a[productUid];
1235
- if (indexed)
1236
- return indexed;
1237
- return (this.currentSalesDetail.bookings || []).filter((booking) => {
1238
- var _a2;
1239
- const uid = (booking == null ? void 0 : booking.product_uid) || ((_a2 = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a2.product_uid);
1240
- return String(uid || "") === String(productUid);
1158
+ if (!this.currentSalesDetail || !productUid) return [];
1159
+ const indexed = this.currentSalesDetail.bookingsByProductUid?.[productUid];
1160
+ if (indexed) return indexed;
1161
+ return (this.currentSalesDetail.bookings || []).filter(booking => {
1162
+ const uid = booking?.product_uid || booking?.metadata?.product_uid;
1163
+ return String(uid || '') === String(productUid);
1241
1164
  });
1242
1165
  }
1166
+
1243
1167
  /** 获取支付列表(已支付/退款等明细)。 */
1244
1168
  getPayments() {
1245
- var _a;
1246
- return ((_a = this.currentSalesDetail) == null ? void 0 : _a.payments) || [];
1169
+ return this.currentSalesDetail?.payments || [];
1247
1170
  }
1171
+
1248
1172
  /** 获取附加费用(运费/服务费/税费等)。 */
1249
1173
  getSurcharges() {
1250
- var _a;
1251
- return ((_a = this.currentSalesDetail) == null ? void 0 : _a.surcharges) || [];
1174
+ return this.currentSalesDetail?.surcharges || [];
1252
1175
  }
1253
1176
  getTempOrder() {
1254
- var _a;
1255
- const result = ((_a = this.store.order) == null ? void 0 : _a.getTempOrder()) || null;
1177
+ const result = this.store.order?.getTempOrder() || null;
1256
1178
  return result;
1257
1179
  }
1258
1180
  async replaceTempOrder(tempOrder, options) {
1259
- if (!this.store.order)
1260
- throw new Error("order 模块未初始化");
1181
+ if (!this.store.order) throw new Error('order 模块未初始化');
1261
1182
  const nextTempOrder = await this.store.order.replaceTempOrder(tempOrder, options);
1262
- await this.effectsEmit("onTempOrderReplaced", { tempOrder: nextTempOrder });
1183
+ await this.effectsEmit('onTempOrderReplaced', {
1184
+ tempOrder: nextTempOrder
1185
+ });
1263
1186
  return nextTempOrder;
1264
1187
  }
1265
1188
  getOrderIdentity() {
1266
- if (!this.store.order)
1267
- return null;
1189
+ if (!this.store.order) return null;
1268
1190
  return this.store.order.getOrderIdentity();
1269
1191
  }
1270
1192
  getOrderSnapshot() {
1271
- if (!this.store.order)
1272
- return null;
1193
+ if (!this.store.order) return null;
1273
1194
  return this.store.order.getOrderSnapshot();
1274
1195
  }
1275
1196
  getOrderSyncState() {
1276
- if (!this.store.order)
1277
- return "local";
1197
+ if (!this.store.order) return 'local';
1278
1198
  return this.store.order.getOrderSyncState();
1279
1199
  }
1280
1200
  getOrderAmountSnapshot() {
1281
- if (!this.store.order)
1282
- return null;
1201
+ if (!this.store.order) return null;
1283
1202
  return this.store.order.getOrderAmountSnapshot();
1284
1203
  }
1285
1204
  getTempOrderNote() {
1286
- if (!this.store.order)
1287
- return "";
1205
+ if (!this.store.order) return '';
1288
1206
  return this.store.order.getTempOrderNote();
1289
1207
  }
1290
1208
  updateTempOrderNote(note, sync = false) {
1291
1209
  try {
1292
- if (!this.store.order)
1293
- throw new Error("order 模块未初始化");
1210
+ if (!this.store.order) throw new Error('order 模块未初始化');
1294
1211
  const result = this.store.order.updateTempOrderNote(note, sync);
1295
1212
  return result;
1296
1213
  } catch (error) {
@@ -1298,47 +1215,42 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1298
1215
  }
1299
1216
  }
1300
1217
  updateRemoteOrderNote(orderId, note) {
1301
- if (!this.store.order)
1302
- throw new Error("order 模块未初始化");
1218
+ if (!this.store.order) throw new Error('order 模块未初始化');
1303
1219
  this.store.order.syncTempOrderNoteToRemote(orderId, note);
1304
1220
  }
1305
1221
  updateTempOrderShopDiscount(amount) {
1306
- if (!this.store.order)
1307
- throw new Error("order 模块未初始化");
1222
+ if (!this.store.order) throw new Error('order 模块未初始化');
1308
1223
  return this.store.order.updateTempOrderShopDiscount(amount);
1309
1224
  }
1310
1225
  updateTempOrderDepositAmount(amount) {
1311
- if (!this.store.order)
1312
- throw new Error("order 模块未初始化");
1226
+ if (!this.store.order) throw new Error('order 模块未初始化');
1313
1227
  return this.store.order.updateTempOrderDepositAmount(amount);
1314
1228
  }
1315
1229
  updateTempOrderContactsInfo(contactsInfo) {
1316
- if (!this.store.order)
1317
- throw new Error("order 模块未初始化");
1230
+ if (!this.store.order) throw new Error('order 模块未初始化');
1318
1231
  return this.store.order.updateTempOrderContactsInfo(contactsInfo);
1319
1232
  }
1233
+
1320
1234
  /** @deprecated OrderModule 不再负责 tempOrder localStorage 持久化。 */
1321
1235
  setEnableTempOrderPersist(enabled) {
1322
- if (!this.store.order)
1323
- throw new Error("order 模块未初始化");
1236
+ if (!this.store.order) throw new Error('order 模块未初始化');
1324
1237
  this.store.order.setEnableTempOrderPersist(enabled);
1325
1238
  }
1239
+
1326
1240
  /** 是否允许 saveDraft 写入 IndexedDB 草稿。 */
1327
1241
  isTempOrderPersistEnabled() {
1328
- if (!this.store.order)
1329
- return false;
1242
+ if (!this.store.order) return false;
1330
1243
  return this.store.order.isTempOrderPersistEnabled();
1331
1244
  }
1332
1245
  ensureTempOrder() {
1333
- if (!this.store.order)
1334
- throw new Error("order 模块未初始化");
1246
+ if (!this.store.order) throw new Error('order 模块未初始化');
1335
1247
  return this.store.order.ensureTempOrder();
1336
1248
  }
1249
+
1337
1250
  // 主动创建临时订单;若已存在则直接返回已有订单
1338
1251
  async addNewOrder() {
1339
1252
  try {
1340
- if (!this.store.order)
1341
- throw new Error("order 模块未初始化");
1253
+ if (!this.store.order) throw new Error('order 模块未初始化');
1342
1254
  const tempOrder = await this.store.order.addNewOrder();
1343
1255
  if (this.syncAppDataToTempOrder(tempOrder) && this.isTempOrderPersistEnabled()) {
1344
1256
  this.store.order.persistTempOrder();
@@ -1350,29 +1262,31 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1350
1262
  }
1351
1263
  }
1352
1264
  async saveDraft() {
1353
- if (!this.store.order)
1354
- throw new Error("order 模块未初始化");
1265
+ if (!this.store.order) throw new Error('order 模块未初始化');
1355
1266
  return this.store.order.saveDraft();
1356
1267
  }
1268
+
1357
1269
  // 重置 tempOrder 与与上一单强相关的运行态(resource/entryPaxNumber/enabledReservationRuleProducts),
1358
1270
  // 适用于从支付页通过 react-router 跳回继续下单时清理残留数据
1359
1271
  async restoreOrder() {
1360
- var _a;
1361
1272
  try {
1362
1273
  if (!this.store.order) {
1363
- throw new Error("scanOrder 解决方案需要 order 模块支持");
1274
+ throw new Error('scanOrder 解决方案需要 order 模块支持');
1364
1275
  }
1276
+ // this.store.resource = null;
1365
1277
  const tempOrder = this.store.order.restoreOrder();
1366
1278
  this.currentSalesDetail = null;
1367
1279
  this.discountConfigCacheKey = null;
1368
1280
  this.hasManualDiscountSelection = false;
1369
- const wallet = (_a = this.store.payment) == null ? void 0 : _a.wallet;
1281
+ const wallet = this.store.payment?.wallet;
1370
1282
  if (wallet) {
1371
1283
  this.walletAssetsRefreshSequence += 1;
1372
1284
  wallet.clearAllCache();
1373
1285
  await this.publishWalletAssetsState(wallet.getWalletAssetsState());
1374
1286
  }
1375
- await this.effectsEmit("onTempOrderReplaced", { tempOrder });
1287
+ await this.effectsEmit('onTempOrderReplaced', {
1288
+ tempOrder
1289
+ });
1376
1290
  if (this.syncAppDataToTempOrder(tempOrder) && this.isTempOrderPersistEnabled()) {
1377
1291
  this.store.order.persistTempOrder();
1378
1292
  await this.store.order.saveDraft();
@@ -1382,14 +1296,14 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1382
1296
  throw error;
1383
1297
  }
1384
1298
  }
1299
+
1385
1300
  /**
1386
1301
  * 仅清空 tempOrder 购物车行(products / bookings / discount_list)。
1387
1302
  * 同步清空内存中的 salesDetail 商品/预约视图,避免编辑态仍读到旧 bookings。
1388
1303
  */
1389
1304
  async clearOrderCartLines() {
1390
1305
  try {
1391
- if (!this.store.order)
1392
- throw new Error("order 模块未初始化");
1306
+ if (!this.store.order) throw new Error('order 模块未初始化');
1393
1307
  const tempOrder = await this.store.order.clearOrderCartLines();
1394
1308
  if (this.currentSalesDetail) {
1395
1309
  this.currentSalesDetail = {
@@ -1401,7 +1315,9 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1401
1315
  discount_list: []
1402
1316
  };
1403
1317
  }
1404
- await this.effectsEmit("onTempOrderReplaced", { tempOrder });
1318
+ await this.effectsEmit('onTempOrderReplaced', {
1319
+ tempOrder
1320
+ });
1405
1321
  if (this.syncAppDataToTempOrder(tempOrder) && this.isTempOrderPersistEnabled()) {
1406
1322
  this.store.order.persistTempOrder();
1407
1323
  await this.store.order.saveDraft();
@@ -1412,15 +1328,13 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1412
1328
  }
1413
1329
  }
1414
1330
  getOrderProducts() {
1415
- if (!this.store.order)
1416
- throw new Error("order 模块未初始化");
1331
+ if (!this.store.order) throw new Error('order 模块未初始化');
1417
1332
  const products = this.store.order.getOrderProducts();
1418
1333
  return products;
1419
1334
  }
1420
1335
  async getSummary() {
1421
1336
  try {
1422
- if (!this.store.order)
1423
- throw new Error("order 模块未初始化");
1337
+ if (!this.store.order) throw new Error('order 模块未初始化');
1424
1338
  const summary = await this.store.order.getOrderSummary();
1425
1339
  return summary;
1426
1340
  } catch (error) {
@@ -1429,21 +1343,18 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1429
1343
  }
1430
1344
  getHistoricalProductDiscountList(products) {
1431
1345
  const historyDiscountList = [];
1432
- products.forEach((item) => {
1433
- if (!this.isPersistedOrderProduct(item))
1434
- return;
1435
- (item.discount_list || []).forEach((discount) => {
1436
- var _a, _b, _c, _d, _e, _f;
1437
- const discountId = ((_a = discount.discount) == null ? void 0 : _a.resource_id) || discount.id;
1438
- if (!discountId || !["good_pass", "discount_card"].includes(discount.type))
1439
- return;
1346
+ products.forEach(item => {
1347
+ if (!this.isPersistedOrderProduct(item)) return;
1348
+ (item.discount_list || []).forEach(discount => {
1349
+ const discountId = discount.discount?.resource_id || discount.id;
1350
+ if (!discountId || !['good_pass', 'discount_card'].includes(discount.type)) return;
1440
1351
  const quantity = item.quantity || item.num || item.product_quantity || 1;
1441
- 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);
1442
- const index = historyDiscountList.findIndex((n) => n.id === discountId);
1352
+ const savedAmount = new _decimal.default(discount.amount || 0).times(quantity).plus(discount?.metadata?.product_discount_difference || 0);
1353
+ const index = historyDiscountList.findIndex(n => n.id === discountId);
1443
1354
  if (index !== -1) {
1444
1355
  historyDiscountList[index] = {
1445
1356
  ...historyDiscountList[index],
1446
- amount: new import_decimal.default(historyDiscountList[index].amount || 0).plus(discount.amount || 0).toNumber(),
1357
+ amount: new _decimal.default(historyDiscountList[index].amount || 0).plus(discount.amount || 0).toNumber(),
1447
1358
  savedAmount: savedAmount.plus(historyDiscountList[index].savedAmount || 0).toNumber()
1448
1359
  };
1449
1360
  return;
@@ -1452,15 +1363,15 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1452
1363
  ...discount,
1453
1364
  id: discountId,
1454
1365
  tag: discount.tag || discount.type,
1455
- name: discount.name || ((_d = (_c = discount.discount) == null ? void 0 : _c.title) == null ? void 0 : _d.auto),
1456
- format_title: ((_e = discount.discount) == null ? void 0 : _e.title) || discount.format_title,
1366
+ name: discount.name || discount.discount?.title?.auto,
1367
+ format_title: discount.discount?.title || discount.format_title,
1457
1368
  isEditMode: true,
1458
1369
  limited_relation_product_data: {},
1459
1370
  savedAmount: savedAmount.toNumber(),
1460
1371
  isAvailable: true,
1461
1372
  isDisabled: true,
1462
1373
  isSelected: true,
1463
- product_id: ((_f = discount.discount) == null ? void 0 : _f.product_id) || discount.product_id
1374
+ product_id: discount.discount?.product_id || discount.product_id
1464
1375
  });
1465
1376
  });
1466
1377
  });
@@ -1468,57 +1379,49 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1468
1379
  }
1469
1380
  isPersistedOrderProduct(product) {
1470
1381
  const orderDetailId = product.order_detail_id ?? product.orderDetailId;
1471
- if (orderDetailId !== void 0 && orderDetailId !== null && orderDetailId !== "") {
1382
+ if (orderDetailId !== undefined && orderDetailId !== null && orderDetailId !== '') {
1472
1383
  return true;
1473
1384
  }
1474
1385
  const bookingId = product.booking_id ?? product.bookingId;
1475
- return bookingId !== void 0 && bookingId !== null && bookingId !== "";
1386
+ return bookingId !== undefined && bookingId !== null && bookingId !== '';
1476
1387
  }
1477
1388
  mergeHistoricalDiscountList(discountList, products) {
1478
1389
  const historyDiscountList = this.getHistoricalProductDiscountList(products);
1479
- const historyIds = new Set(historyDiscountList.map((discount) => discount.id));
1480
- return [
1481
- ...historyDiscountList,
1482
- ...(discountList || []).filter((discount) => {
1483
- if (!historyIds.has(discount.id))
1484
- return true;
1485
- return !isBaseSalesHistoricalDiscountEntry(discount);
1486
- })
1487
- ];
1390
+ const historyIds = new Set(historyDiscountList.map(discount => discount.id));
1391
+ return [...historyDiscountList, ...(discountList || []).filter(discount => {
1392
+ if (!historyIds.has(discount.id)) return true;
1393
+ return !isBaseSalesHistoricalDiscountEntry(discount);
1394
+ })];
1488
1395
  }
1489
1396
  shouldSkipAutoApplyFetchedDiscountsInEditMode(params) {
1490
- if (params.discountAction !== "edit")
1491
- return false;
1492
- if (!params.products.length)
1493
- return false;
1494
- const hasDraftProduct = params.products.some((product) => !this.isPersistedOrderProduct(product));
1495
- if (hasDraftProduct)
1496
- return false;
1497
- const hasRuntimeDiscountSelection = params.currentDiscountList.some(
1498
- (discount) => !discount.isEditMode && (discount.isSelected || discount.isManualSelect)
1499
- );
1500
- if (hasRuntimeDiscountSelection)
1501
- return false;
1502
- return !params.nextDiscountList.some(
1503
- (discount) => !discount.isEditMode && (discount.isSelected || discount.isManualSelect)
1504
- );
1397
+ if (params.discountAction !== 'edit') return false;
1398
+ if (!params.products.length) return false;
1399
+ const hasDraftProduct = params.products.some(product => !this.isPersistedOrderProduct(product));
1400
+ if (hasDraftProduct) return false;
1401
+
1402
+ // 编辑详情 hydrate 时,商品行上的历史券卡会被还原为 isEditMode=true、
1403
+ // isSelected=true 的只读记录。它们表示“该折扣已在原订单结算”,不是用户在
1404
+ // 当前编辑会话中新做的选择,不能据此放行刚从 prepare/config 拉回来的折扣。
1405
+ // 否则后续 Rules.calcDiscount 会把没有 isManualSelect 标记的可用 runtime 卡
1406
+ // 当作自动候选,再次写入 tempOrder。这里只识别非 isEditMode 的 runtime 状态;
1407
+ // 新建单、编辑态新增商品以及用户本次明确选择/取消折扣的原有流程保持不变。
1408
+ const hasRuntimeDiscountSelection = params.currentDiscountList.some(discount => !discount.isEditMode && (discount.isSelected || discount.isManualSelect));
1409
+ if (hasRuntimeDiscountSelection) return false;
1410
+
1411
+ // nextDiscountList 已经合并了历史只读折扣与本次获取的 runtime 折扣,
1412
+ // 因此这里同样必须排除 isEditMode;只有 runtime 条目已有明确选择状态时,
1413
+ // 才允许继续进入折扣重算。
1414
+ return !params.nextDiscountList.some(discount => !discount.isEditMode && (discount.isSelected || discount.isManualSelect));
1505
1415
  }
1506
1416
  mergeCurrentDiscountSelectionState(discountList, currentDiscountList) {
1507
- if (!currentDiscountList.length)
1508
- return discountList;
1509
- const currentDiscountMap = /* @__PURE__ */ new Map();
1510
- currentDiscountList.forEach((discount) => {
1511
- currentDiscountMap.set(
1512
- `${discount.id}:${isBaseSalesHistoricalDiscountEntry(discount) ? "historical" : "runtime"}`,
1513
- discount
1514
- );
1417
+ if (!currentDiscountList.length) return discountList;
1418
+ const currentDiscountMap = new Map();
1419
+ currentDiscountList.forEach(discount => {
1420
+ currentDiscountMap.set(`${discount.id}:${isBaseSalesHistoricalDiscountEntry(discount) ? 'historical' : 'runtime'}`, discount);
1515
1421
  });
1516
- return discountList.map((discount) => {
1517
- const currentDiscount = currentDiscountMap.get(
1518
- `${discount.id}:${isBaseSalesHistoricalDiscountEntry(discount) ? "historical" : "runtime"}`
1519
- );
1520
- if (!currentDiscount)
1521
- return discount;
1422
+ return discountList.map(discount => {
1423
+ const currentDiscount = currentDiscountMap.get(`${discount.id}:${isBaseSalesHistoricalDiscountEntry(discount) ? 'historical' : 'runtime'}`);
1424
+ if (!currentDiscount) return discount;
1522
1425
  if (currentDiscount.isManualSelect) {
1523
1426
  return {
1524
1427
  ...discount,
@@ -1537,26 +1440,18 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1537
1440
  });
1538
1441
  }
1539
1442
  async loadDiscountConfig(params) {
1540
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
1541
- if (!this.store.order)
1542
- throw new Error("order 模块未初始化");
1443
+ if (!this.store.order) throw new Error('order 模块未初始化');
1543
1444
  const tempOrder = this.store.order.ensureTempOrder();
1544
1445
  const orderStore = this.store.order.store || {};
1545
1446
  const discountModule = orderStore.discount;
1546
1447
  const rulesModule = orderStore.rules;
1547
- const orderId = tempOrder.order_id || ((_b = (_a = this.getOrderIdentity) == null ? void 0 : _a.call(this)) == null ? void 0 : _b.orderId);
1548
- const customerId = Number(
1549
- (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
1550
- );
1551
- const currentDiscountList = ((_h = discountModule == null ? void 0 : discountModule.getDiscountList) == null ? void 0 : _h.call(discountModule)) || [];
1552
- const originalDiscountList = ((_i = discountModule == null ? void 0 : discountModule.getOriginalDiscountList) == null ? void 0 : _i.call(discountModule)) || [];
1553
- const hasManualDiscountSelection = this.hasManualDiscountSelection || currentDiscountList.some((discount) => discount.isManualSelect);
1554
- const discountAction = (params == null ? void 0 : params.action) || (orderId ? "edit" : "create");
1555
- const discountConfigCacheKey = [
1556
- customerId,
1557
- discountAction,
1558
- Number(orderId) || 0
1559
- ].join(":");
1448
+ const orderId = tempOrder.order_id || this.getOrderIdentity?.()?.orderId;
1449
+ const customerId = Number(params?.customerId || tempOrder.customer_id || tempOrder.customer?.id || tempOrder._extend?.customerSnapshot?.id || tempOrder._extend?.customerSnapshot?.customer_id || 0);
1450
+ const currentDiscountList = discountModule?.getDiscountList?.() || [];
1451
+ const originalDiscountList = discountModule?.getOriginalDiscountList?.() || [];
1452
+ const hasManualDiscountSelection = this.hasManualDiscountSelection || currentDiscountList.some(discount => discount.isManualSelect);
1453
+ const discountAction = params?.action || (orderId ? 'edit' : 'create');
1454
+ const discountConfigCacheKey = [customerId, discountAction, Number(orderId) || 0].join(':');
1560
1455
  let preparedDiscountList = [];
1561
1456
  if (customerId && customerId !== 1) {
1562
1457
  if (this.discountConfigCacheKey === discountConfigCacheKey) {
@@ -1565,11 +1460,11 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1565
1460
  preparedDiscountList = await this.store.order.loadDiscountConfig({
1566
1461
  customerId,
1567
1462
  action: discountAction,
1568
- orderId: Number(orderId) || void 0,
1463
+ orderId: Number(orderId) || undefined,
1569
1464
  apply: false
1570
1465
  });
1571
1466
  this.discountConfigCacheKey = discountConfigCacheKey;
1572
- await ((_j = discountModule == null ? void 0 : discountModule.setOriginalDiscountList) == null ? void 0 : _j.call(discountModule, preparedDiscountList));
1467
+ await discountModule?.setOriginalDiscountList?.(preparedDiscountList);
1573
1468
  }
1574
1469
  }
1575
1470
  if (hasManualDiscountSelection && currentDiscountList.length) {
@@ -1579,15 +1474,9 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1579
1474
  availableWalletIds: this.getAvailableWalletIds()
1580
1475
  };
1581
1476
  }
1582
- let nextDiscountList = this.mergeHistoricalDiscountList(
1583
- preparedDiscountList || ((_k = discountModule == null ? void 0 : discountModule.getDiscountList) == null ? void 0 : _k.call(discountModule)) || [],
1584
- tempOrder.products || []
1585
- );
1586
- nextDiscountList = this.mergeCurrentDiscountSelectionState(
1587
- nextDiscountList,
1588
- currentDiscountList
1589
- );
1590
- await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1477
+ let nextDiscountList = this.mergeHistoricalDiscountList(preparedDiscountList || discountModule?.getDiscountList?.() || [], tempOrder.products || []);
1478
+ nextDiscountList = this.mergeCurrentDiscountSelectionState(nextDiscountList, currentDiscountList);
1479
+ await discountModule?.setDiscountList(nextDiscountList);
1591
1480
  const shouldSkipAutoApplyFetchedDiscounts = this.shouldSkipAutoApplyFetchedDiscountsInEditMode({
1592
1481
  discountAction,
1593
1482
  products: tempOrder.products || [],
@@ -1595,9 +1484,11 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1595
1484
  nextDiscountList
1596
1485
  });
1597
1486
  if (shouldSkipAutoApplyFetchedDiscounts) {
1598
- const summary2 = await this.store.order.recalculateSummary({ createIfMissing: true });
1487
+ const summary = await this.store.order.recalculateSummary({
1488
+ createIfMissing: true
1489
+ });
1599
1490
  this.store.order.persistTempOrder();
1600
- await this.effectsEmit("onDiscountApplied", {
1491
+ await this.effectsEmit('onDiscountApplied', {
1601
1492
  productList: tempOrder.products || [],
1602
1493
  discountList: nextDiscountList,
1603
1494
  selectedDiscountList: tempOrder.discount_list || [],
@@ -1610,56 +1501,50 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1610
1501
  };
1611
1502
  }
1612
1503
  if (rulesModule) {
1613
- const orderTotalAmount = Number(((_l = orderStore.summary) == null ? void 0 : _l.total_amount) || 0);
1614
- console.log("[BaseSales.applyDiscountConfig.calcDiscount]");
1504
+ const orderTotalAmount = Number(orderStore.summary?.total_amount || 0);
1615
1505
  const result = rulesModule.calcDiscount({
1616
1506
  productList: tempOrder.products,
1617
1507
  discountList: nextDiscountList,
1618
1508
  holders: [],
1619
- isFormSubject: (product) => (0, import_utils.resolveIsFormSubject)(tempOrder, product),
1509
+ isFormSubject: product => (0, _utils.resolveIsFormSubject)(tempOrder, product),
1620
1510
  orderTotalAmount
1621
- }) || { productList: tempOrder.products, discountList: nextDiscountList };
1511
+ }) || {
1512
+ productList: tempOrder.products,
1513
+ discountList: nextDiscountList
1514
+ };
1622
1515
  if (result.productList) {
1623
- tempOrder.products = preserveManualProductDiscountProducts(
1624
- tempOrder.products,
1625
- result.productList
1626
- );
1516
+ tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
1627
1517
  }
1628
1518
  for (const product of tempOrder.products || []) {
1629
- const productUid = (_m = product.metadata) == null ? void 0 : _m.unique_identification_number;
1630
- 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;
1631
- if ((runtimeOrigin == null ? void 0 : runtimeOrigin.isManualDiscount) || isBaseSalesManualProductDiscountProduct(product))
1632
- continue;
1633
- const totalPerUnitDiscount = (product.discount_list || []).reduce(
1634
- (sum, pd) => sum + Number(pd.amount || 0),
1635
- 0
1636
- );
1637
- const optionSum = (0, import_utils.sumOptionUnitPrice)((0, import_utils.getProductSkuOptions)(product));
1638
- 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");
1639
- const newSourceSellingPrice = new import_decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
1640
- const newMainSellingPrice = new import_decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
1519
+ const productUid = product.metadata?.unique_identification_number;
1520
+ const runtimeOrigin = productUid ? tempOrder._extend?.productsByUid?.[productUid]?.origin : undefined;
1521
+ if (runtimeOrigin?.isManualDiscount || isBaseSalesManualProductDiscountProduct(product)) continue;
1522
+ const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + Number(pd.amount || 0), 0);
1523
+ const optionSum = (0, _utils.sumOptionUnitPrice)((0, _utils.getProductSkuOptions)(product));
1524
+ 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');
1525
+ const newSourceSellingPrice = new _decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
1526
+ const newMainSellingPrice = new _decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
1641
1527
  if (product.metadata) {
1642
1528
  product.metadata.main_product_selling_price = newMainSellingPrice;
1643
1529
  product.metadata.price_schema_version = 2;
1644
1530
  }
1645
- product.selling_price = (0, import_utils.composeLinePrice)({
1531
+ product.selling_price = (0, _utils.composeLinePrice)({
1646
1532
  mainPrice: newMainSellingPrice,
1647
1533
  bundle: product.product_bundle
1648
1534
  });
1649
1535
  }
1650
1536
  if (result.discountList) {
1651
- nextDiscountList = this.mergeHistoricalDiscountList(
1652
- result.discountList,
1653
- tempOrder.products || []
1654
- );
1655
- import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1656
- await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1657
- tempOrder.discount_list = nextDiscountList.filter((discount) => discount.isSelected);
1537
+ nextDiscountList = this.mergeHistoricalDiscountList(result.discountList, tempOrder.products || []);
1538
+ _Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1539
+ await discountModule?.setDiscountList(nextDiscountList);
1540
+ tempOrder.discount_list = nextDiscountList.filter(discount => discount.isSelected);
1658
1541
  }
1659
1542
  }
1660
- const summary = await this.store.order.recalculateSummary({ createIfMissing: true });
1543
+ const summary = await this.store.order.recalculateSummary({
1544
+ createIfMissing: true
1545
+ });
1661
1546
  this.store.order.persistTempOrder();
1662
- await this.effectsEmit("onDiscountApplied", {
1547
+ await this.effectsEmit('onDiscountApplied', {
1663
1548
  productList: tempOrder.products || [],
1664
1549
  discountList: nextDiscountList,
1665
1550
  selectedDiscountList: tempOrder.discount_list || [],
@@ -1672,95 +1557,79 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1672
1557
  };
1673
1558
  }
1674
1559
  getAvailableWalletIds() {
1675
- var _a;
1676
- if (!((_a = this.store.order) == null ? void 0 : _a.getAvailableWalletIds))
1677
- return [];
1560
+ if (!this.store.order?.getAvailableWalletIds) return [];
1678
1561
  return this.store.order.getAvailableWalletIds();
1679
1562
  }
1680
1563
  async bestDiscount(cb) {
1681
- var _a, _b, _c;
1682
- if (!this.store.order)
1683
- throw new Error("order 模块未初始化");
1564
+ if (!this.store.order) throw new Error('order 模块未初始化');
1684
1565
  const tempOrder = this.store.order.ensureTempOrder();
1685
1566
  const orderStore = this.store.order.store || {};
1686
1567
  const discountModule = orderStore.discount;
1687
1568
  const rulesModule = orderStore.rules;
1688
- const originalDiscountList = ((_a = discountModule == null ? void 0 : discountModule.getOriginalDiscountList) == null ? void 0 : _a.call(discountModule)) || this.getDiscountList();
1689
- const currentDiscountList = ((_b = discountModule == null ? void 0 : discountModule.getDiscountList) == null ? void 0 : _b.call(discountModule)) || [];
1690
- let nextDiscountList = this.mergeHistoricalDiscountList(
1691
- originalDiscountList || [],
1692
- tempOrder.products || []
1693
- );
1569
+ const originalDiscountList = discountModule?.getOriginalDiscountList?.() || this.getDiscountList();
1570
+ const currentDiscountList = discountModule?.getDiscountList?.() || [];
1571
+ let nextDiscountList = this.mergeHistoricalDiscountList(originalDiscountList || [], tempOrder.products || []);
1694
1572
  let result = {
1695
1573
  productList: tempOrder.products || [],
1696
1574
  discountList: nextDiscountList
1697
1575
  };
1698
- await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1576
+ await discountModule?.setDiscountList(nextDiscountList);
1699
1577
  if (rulesModule) {
1700
- const orderTotalAmount = Number(((_c = orderStore.summary) == null ? void 0 : _c.total_amount) || 0);
1701
- console.log("[BaseSales.bestDiscount.calcDiscount]");
1578
+ const orderTotalAmount = Number(orderStore.summary?.total_amount || 0);
1702
1579
  result = rulesModule.calcDiscount({
1703
1580
  productList: tempOrder.products,
1704
1581
  discountList: nextDiscountList,
1705
1582
  holders: [],
1706
- isFormSubject: (product) => (0, import_utils.resolveIsFormSubject)(tempOrder, product),
1583
+ isFormSubject: product => (0, _utils.resolveIsFormSubject)(tempOrder, product),
1707
1584
  orderTotalAmount
1708
1585
  }) || result;
1709
1586
  if (result.productList) {
1710
- tempOrder.products = preserveManualProductDiscountProducts(
1711
- tempOrder.products,
1712
- result.productList
1713
- );
1587
+ tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
1714
1588
  }
1715
1589
  if (result.discountList) {
1716
- nextDiscountList = this.mergeHistoricalDiscountList(
1717
- result.discountList,
1718
- tempOrder.products || []
1719
- );
1720
- import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1721
- await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1722
- tempOrder.discount_list = nextDiscountList.filter((discount) => discount.isSelected);
1590
+ nextDiscountList = this.mergeHistoricalDiscountList(result.discountList, tempOrder.products || []);
1591
+ _Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1592
+ await discountModule?.setDiscountList(nextDiscountList);
1593
+ tempOrder.discount_list = nextDiscountList.filter(discount => discount.isSelected);
1723
1594
  result = {
1724
1595
  productList: tempOrder.products,
1725
1596
  discountList: nextDiscountList
1726
1597
  };
1727
1598
  }
1728
1599
  }
1729
- await this.store.order.recalculateSummary({ createIfMissing: true });
1600
+ await this.store.order.recalculateSummary({
1601
+ createIfMissing: true
1602
+ });
1730
1603
  this.store.order.persistTempOrder();
1731
- await this.effectsEmit("onDiscountApplied", {
1604
+ await this.effectsEmit('onDiscountApplied', {
1732
1605
  productList: tempOrder.products || [],
1733
1606
  discountList: nextDiscountList,
1734
1607
  selectedDiscountList: tempOrder.discount_list || [],
1735
1608
  tempOrder
1736
1609
  });
1737
- cb == null ? void 0 : cb(result);
1610
+ cb?.(result);
1738
1611
  return result;
1739
1612
  }
1740
1613
  getDiscountList() {
1741
- if (!this.store.order)
1742
- return [];
1614
+ if (!this.store.order) return [];
1743
1615
  return this.store.order.getDiscountList();
1744
1616
  }
1617
+
1745
1618
  /** 读取 Discount 模块原始券列表(未经过 bookingTime 等过滤)。 */
1746
1619
  getOriginalDiscountList() {
1747
- var _a, _b;
1748
- if (!this.store.order)
1749
- return [];
1750
- const discountModule = (_a = this.store.order.store) == null ? void 0 : _a.discount;
1751
- return ((_b = discountModule == null ? void 0 : discountModule.getOriginalDiscountList) == null ? void 0 : _b.call(discountModule)) || [];
1620
+ if (!this.store.order) return [];
1621
+ const discountModule = this.store.order.store?.discount;
1622
+ return discountModule?.getOriginalDiscountList?.() || [];
1752
1623
  }
1624
+
1753
1625
  /**
1754
1626
  * 同步写入 Discount 模块的 discountList / originalDiscountList。
1755
1627
  * 供 Holder 补全等场景在 OS store 层更新 machinecode holder 字段。
1756
1628
  */
1757
1629
  async replaceDiscountStoreLists(params) {
1758
- var _a;
1759
- if (!this.store.order)
1760
- throw new Error("order 模块未初始化");
1761
- const discountModule = (_a = this.store.order.store) == null ? void 0 : _a.discount;
1762
- if (!discountModule)
1763
- return;
1630
+ if (!this.store.order) throw new Error('order 模块未初始化');
1631
+ const discountModule = this.store.order.store?.discount;
1632
+ if (!discountModule) return;
1764
1633
  if (params.originalDiscountList) {
1765
1634
  await discountModule.setOriginalDiscountList(params.originalDiscountList);
1766
1635
  }
@@ -1768,14 +1637,15 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1768
1637
  }
1769
1638
  async scanPromotionCode(code, customerId) {
1770
1639
  try {
1771
- if (!this.store.order)
1772
- throw new Error("order 模块未初始化");
1640
+ if (!this.store.order) throw new Error('order 模块未初始化');
1773
1641
  const raw = await this.store.order.scanCode(code, customerId);
1774
1642
  if (raw.isAvailable) {
1775
- await this.store.order.recalculateSummary({ createIfMissing: true });
1643
+ await this.store.order.recalculateSummary({
1644
+ createIfMissing: true
1645
+ });
1776
1646
  this.store.order.persistTempOrder();
1777
1647
  const tempOrder = this.store.order.ensureTempOrder();
1778
- await this.effectsEmit("onDiscountApplied", {
1648
+ await this.effectsEmit('onDiscountApplied', {
1779
1649
  productList: tempOrder.products || [],
1780
1650
  discountList: this.store.order.getDiscountList(),
1781
1651
  selectedDiscountList: tempOrder.discount_list || [],
@@ -1784,7 +1654,9 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1784
1654
  }
1785
1655
  return {
1786
1656
  isAvailable: raw.isAvailable,
1787
- ...raw.isAccepted !== void 0 ? { isAccepted: raw.isAccepted } : {},
1657
+ ...(raw.isAccepted !== undefined ? {
1658
+ isAccepted: raw.isAccepted
1659
+ } : {}),
1788
1660
  type: raw.type,
1789
1661
  unavailableReason: raw.unavailableReason,
1790
1662
  scannedDiscountList: raw.scannedDiscountList
@@ -1793,55 +1665,46 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1793
1665
  throw error;
1794
1666
  }
1795
1667
  }
1668
+
1796
1669
  // TODO 需要优化,这段逻辑太长了,里面应该有些历史遗留问题
1797
1670
  async setDiscountSelected(params) {
1798
- var _a, _b, _c, _d, _e, _f, _g;
1799
1671
  try {
1800
- if (!this.store.order)
1801
- throw new Error("order 模块未初始化");
1672
+ if (!this.store.order) throw new Error('order 模块未初始化');
1802
1673
  const list = this.store.order.getDiscountList();
1803
- const updated = list.map(
1804
- (d) => d.id === params.discountId && !isBaseSalesHistoricalDiscountEntry(d) ? {
1805
- ...d,
1806
- isSelected: params.isSelected,
1807
- isManualSelect: !params.isSelected
1808
- } : d
1809
- );
1674
+ const updated = list.map(d => d.id === params.discountId && !isBaseSalesHistoricalDiscountEntry(d) ? {
1675
+ ...d,
1676
+ isSelected: params.isSelected,
1677
+ isManualSelect: !params.isSelected
1678
+ } : d);
1810
1679
  this.hasManualDiscountSelection = true;
1811
1680
  const tempOrder = this.store.order.ensureTempOrder();
1812
1681
  const orderStore = this.store.order.store || {};
1813
1682
  const discountModule = orderStore.discount;
1814
1683
  const rulesModule = orderStore.rules;
1815
1684
  let nextDiscountList = updated;
1816
- await (discountModule == null ? void 0 : discountModule.setDiscountList(updated));
1685
+ await discountModule?.setDiscountList(updated);
1817
1686
  if (rulesModule) {
1818
- const orderTotalAmount = Number(((_a = orderStore.summary) == null ? void 0 : _a.total_amount) || 0);
1819
- console.log("[BaseSales.setDiscountSelected.calcDiscount]");
1820
- const result = rulesModule.calcDiscount(
1821
- {
1822
- productList: tempOrder.products,
1823
- discountList: updated,
1824
- holders: [],
1825
- isFormSubject: (product) => (0, import_utils.resolveIsFormSubject)(tempOrder, product),
1826
- orderTotalAmount
1827
- },
1828
- {
1829
- discountId: params.discountId,
1830
- isSelected: params.isSelected
1831
- }
1832
- ) || { productList: tempOrder.products, discountList: updated };
1833
- if (result == null ? void 0 : result.productList) {
1834
- tempOrder.products = preserveManualProductDiscountProducts(
1835
- tempOrder.products,
1836
- result.productList
1837
- );
1687
+ const orderTotalAmount = Number(orderStore.summary?.total_amount || 0);
1688
+ const result = rulesModule.calcDiscount({
1689
+ productList: tempOrder.products,
1690
+ discountList: updated,
1691
+ holders: [],
1692
+ isFormSubject: product => (0, _utils.resolveIsFormSubject)(tempOrder, product),
1693
+ orderTotalAmount
1694
+ }, {
1695
+ discountId: params.discountId,
1696
+ isSelected: params.isSelected
1697
+ }) || {
1698
+ productList: tempOrder.products,
1699
+ discountList: updated
1700
+ };
1701
+ if (result?.productList) {
1702
+ tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
1838
1703
  }
1839
- if (result == null ? void 0 : result.discountList) {
1704
+ if (result?.discountList) {
1840
1705
  nextDiscountList = result.discountList;
1841
1706
  if (!params.isSelected) {
1842
- const beforeSelectedIds = new Set(
1843
- updated.filter((d) => d.isSelected).map((d) => d.id)
1844
- );
1707
+ const beforeSelectedIds = new Set(updated.filter(d => d.isSelected).map(d => d.id));
1845
1708
  for (const d of nextDiscountList) {
1846
1709
  if (d.isSelected && !beforeSelectedIds.has(d.id)) {
1847
1710
  d.isSelected = false;
@@ -1852,58 +1715,57 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1852
1715
  }
1853
1716
  }
1854
1717
  }
1855
- const selectedResourceIds = new Set(
1856
- nextDiscountList.filter((d) => d.isSelected).map((d) => d.id)
1857
- );
1858
- const filterSelectedDiscountDetails = (discountList) => (discountList || []).filter((pd) => {
1859
- var _a2;
1860
- const rid = ((_a2 = pd.discount) == null ? void 0 : _a2.resource_id) ?? pd.id;
1718
+ const selectedResourceIds = new Set(nextDiscountList.filter(d => d.isSelected).map(d => d.id));
1719
+ const filterSelectedDiscountDetails = discountList => (discountList || []).filter(pd => {
1720
+ const rid = pd.discount?.resource_id ?? pd.id;
1861
1721
  return rid != null && selectedResourceIds.has(rid);
1862
1722
  });
1863
1723
  for (const product of tempOrder.products) {
1864
- const productUid = (_b = product.metadata) == null ? void 0 : _b.unique_identification_number;
1865
- 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;
1866
- if ((runtimeOrigin == null ? void 0 : runtimeOrigin.isManualDiscount) || isBaseSalesManualProductDiscountProduct(product))
1867
- continue;
1724
+ const productUid = product.metadata?.unique_identification_number;
1725
+ const runtimeOrigin = productUid ? tempOrder._extend?.productsByUid?.[productUid]?.origin : undefined;
1726
+ if (runtimeOrigin?.isManualDiscount || isBaseSalesManualProductDiscountProduct(product)) continue;
1868
1727
  product.discount_list = filterSelectedDiscountDetails(product.discount_list);
1869
1728
  if (Array.isArray(product.product_bundle)) {
1870
- product.product_bundle = product.product_bundle.map((bundle) => {
1871
- const nextBundleDiscountList = filterSelectedDiscountDetails(bundle == null ? void 0 : bundle.discount_list);
1729
+ product.product_bundle = product.product_bundle.map(bundle => {
1730
+ const nextBundleDiscountList = filterSelectedDiscountDetails(bundle?.discount_list);
1872
1731
  const shouldRestoreBundlePrice = nextBundleDiscountList.length === 0;
1873
- const restoredBundlePrice = (bundle == null ? void 0 : bundle.original_price) ?? (bundle == null ? void 0 : bundle.product_price) ?? (bundle == null ? void 0 : bundle.price);
1732
+ const restoredBundlePrice = bundle?.original_price ?? bundle?.product_price ?? bundle?.price;
1874
1733
  return {
1875
1734
  ...bundle,
1876
- ...shouldRestoreBundlePrice ? {
1735
+ ...(shouldRestoreBundlePrice ? {
1877
1736
  price: restoredBundlePrice,
1878
1737
  bundle_selling_price: restoredBundlePrice
1879
- } : {},
1738
+ } : {}),
1880
1739
  discount_list: nextBundleDiscountList
1881
1740
  };
1882
1741
  });
1883
1742
  }
1884
- const totalPerUnitDiscount = (product.discount_list || []).reduce(
1885
- (sum, pd) => sum + (pd.amount || 0),
1886
- 0
1887
- );
1888
- const optionSum = (0, import_utils.sumOptionUnitPrice)((0, import_utils.getProductSkuOptions)(product));
1889
- 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");
1890
- const newSourceSellingPrice = new import_decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
1891
- const newMainSellingPrice = new import_decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
1743
+
1744
+ // 券作用于 source(不含 option、不含 bundle);算出新 source 折后价后补回 options
1745
+ // 写入含 option 的 main_product_selling_price,再合成 composite 回写 selling_price。
1746
+ const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + (pd.amount || 0), 0);
1747
+ // TODO 这块逻辑需要拿掉
1748
+ const optionSum = (0, _utils.sumOptionUnitPrice)((0, _utils.getProductSkuOptions)(product));
1749
+ 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');
1750
+ const newSourceSellingPrice = new _decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
1751
+ const newMainSellingPrice = new _decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
1892
1752
  if (product.metadata) {
1893
1753
  product.metadata.main_product_selling_price = newMainSellingPrice;
1894
1754
  product.metadata.price_schema_version = 2;
1895
1755
  }
1896
- product.selling_price = (0, import_utils.composeLinePrice)({
1756
+ product.selling_price = (0, _utils.composeLinePrice)({
1897
1757
  mainPrice: newMainSellingPrice,
1898
1758
  bundle: product.product_bundle
1899
1759
  });
1900
1760
  }
1901
- import_Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1902
- await (discountModule == null ? void 0 : discountModule.setDiscountList(nextDiscountList));
1903
- tempOrder.discount_list = (nextDiscountList || []).filter((d) => d.isSelected);
1904
- await this.store.order.recalculateSummary({ createIfMissing: true });
1761
+ _Order.OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
1762
+ await discountModule?.setDiscountList(nextDiscountList);
1763
+ tempOrder.discount_list = (nextDiscountList || []).filter(d => d.isSelected);
1764
+ await this.store.order.recalculateSummary({
1765
+ createIfMissing: true
1766
+ });
1905
1767
  this.store.order.persistTempOrder();
1906
- this.effectsEmit("onDiscountApplied", {
1768
+ this.effectsEmit('onDiscountApplied', {
1907
1769
  productList: tempOrder.products,
1908
1770
  discountList: nextDiscountList,
1909
1771
  selectedDiscountList: tempOrder.discount_list,
@@ -1915,32 +1777,24 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1915
1777
  }
1916
1778
  async applyDiscountCalculationResult(result) {
1917
1779
  try {
1918
- if (!this.store.order)
1919
- throw new Error("order 模块未初始化");
1920
- if (!result)
1921
- return;
1780
+ if (!this.store.order) throw new Error('order 模块未初始化');
1781
+ if (!result) return;
1922
1782
  const tempOrder = this.store.order.ensureTempOrder();
1923
1783
  const orderStore = this.store.order.store || {};
1924
1784
  const discountModule = orderStore.discount;
1925
1785
  if (result.productList) {
1926
- tempOrder.products = preserveManualProductDiscountProducts(
1927
- tempOrder.products,
1928
- result.productList
1929
- );
1786
+ tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
1930
1787
  }
1931
1788
  if (result.discountList) {
1932
- import_Order.OrderModule.populateSavedAmounts(
1933
- tempOrder.products,
1934
- result.discountList
1935
- );
1936
- await (discountModule == null ? void 0 : discountModule.setDiscountList(result.discountList));
1937
- tempOrder.discount_list = result.discountList.filter(
1938
- (discount) => discount.isSelected
1939
- );
1940
- }
1941
- await this.store.order.recalculateSummary({ createIfMissing: true });
1789
+ _Order.OrderModule.populateSavedAmounts(tempOrder.products, result.discountList);
1790
+ await discountModule?.setDiscountList(result.discountList);
1791
+ tempOrder.discount_list = result.discountList.filter(discount => discount.isSelected);
1792
+ }
1793
+ await this.store.order.recalculateSummary({
1794
+ createIfMissing: true
1795
+ });
1942
1796
  this.store.order.persistTempOrder();
1943
- await this.effectsEmit("onDiscountApplied", {
1797
+ await this.effectsEmit('onDiscountApplied', {
1944
1798
  productList: tempOrder.products || [],
1945
1799
  discountList: result.discountList || [],
1946
1800
  selectedDiscountList: tempOrder.discount_list || [],
@@ -1951,8 +1805,10 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1951
1805
  }
1952
1806
  }
1953
1807
  async submitScanOrder(params) {
1808
+ // Deprecated compatibility alias. New BaseSales callers should use submitSalesOrder.
1954
1809
  return this.submitSalesOrder(params);
1955
1810
  }
1811
+
1956
1812
  /**
1957
1813
  * 提交当前 Sales 订单。
1958
1814
  *
@@ -1960,88 +1816,112 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1960
1816
  * payments 会交给 OrderModule 统一映射为 Sales 协议支付项。
1961
1817
  */
1962
1818
  async submitSalesOrder(params) {
1963
- var _a, _b, _c, _d;
1964
1819
  if (!this.store.order) {
1965
- throw new Error("BaseSales 解决方案需要 order 模块支持");
1820
+ throw new Error('BaseSales 解决方案需要 order 模块支持');
1966
1821
  }
1967
- const inferredPaymentStatus = this.getSubmitPaymentStatus(params == null ? void 0 : params.paymentStatus);
1968
- const smallTicketDataFlag = (params == null ? void 0 : params.smallTicketDataFlag) ?? this.getDefaultCheckoutSmallTicketDataFlag();
1822
+ // this.store.order.persistTempOrder();
1823
+ const inferredPaymentStatus = this.getSubmitPaymentStatus(params?.paymentStatus);
1824
+ const smallTicketDataFlag = params?.smallTicketDataFlag ?? this.getDefaultCheckoutSmallTicketDataFlag();
1969
1825
  const submitParams = {
1970
1826
  cacheId: this.cacheId,
1971
- platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
1972
- businessCode: ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1827
+ platform: this.otherParams?.platform,
1828
+ businessCode: this.otherParams?.businessCode || this.otherParams?.business_code,
1973
1829
  channel: this.getSubmitOrderSalesChannel(),
1974
- type: (_d = this.otherParams) == null ? void 0 : _d.type,
1830
+ type: this.otherParams?.type,
1975
1831
  request_unique_idempotency_token: this.store.order.generateIdempotencyToken(),
1976
- ...(params == null ? void 0 : params.payments) !== void 0 ? { payments: params.payments } : {},
1977
- ...inferredPaymentStatus !== void 0 ? { paymentStatus: inferredPaymentStatus } : {},
1978
- ...smallTicketDataFlag !== void 0 ? { smallTicketDataFlag } : {},
1979
- ...(params == null ? void 0 : params.confirmPendingVoucherPayments) !== void 0 ? { confirmPendingVoucherPayments: params.confirmPendingVoucherPayments } : {},
1980
- ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
1832
+ ...(params?.payments !== undefined ? {
1833
+ payments: params.payments
1834
+ } : {}),
1835
+ ...(inferredPaymentStatus !== undefined ? {
1836
+ paymentStatus: inferredPaymentStatus
1837
+ } : {}),
1838
+ ...(smallTicketDataFlag !== undefined ? {
1839
+ smallTicketDataFlag
1840
+ } : {}),
1841
+ ...(params?.confirmPendingVoucherPayments !== undefined ? {
1842
+ confirmPendingVoucherPayments: params.confirmPendingVoucherPayments
1843
+ } : {}),
1844
+ ...(params?.enhancePayload !== undefined ? {
1845
+ enhancePayload: params.enhancePayload
1846
+ } : {})
1981
1847
  };
1982
1848
  return this.shouldUseCheckoutSyncTask() ? this.store.order.submitTempOrder(submitParams) : this.store.order.submitTempOrderAsync(submitParams);
1983
1849
  }
1984
1850
  async saveSalesOrderDraft(params) {
1985
- var _a, _b, _c, _d;
1986
1851
  if (!this.store.order) {
1987
- throw new Error("BaseSales 解决方案需要 order 模块支持");
1852
+ throw new Error('BaseSales 解决方案需要 order 模块支持');
1988
1853
  }
1989
1854
  return this.store.order.saveTempOrderAsDraft({
1990
1855
  cacheId: this.cacheId,
1991
- platform: (params == null ? void 0 : params.platform) ?? ((_a = this.otherParams) == null ? void 0 : _a.platform),
1992
- businessCode: (params == null ? void 0 : params.businessCode) || ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1993
- channel: (params == null ? void 0 : params.channel) ?? this.getSubmitOrderSalesChannel(),
1994
- type: (params == null ? void 0 : params.type) ?? ((_d = this.otherParams) == null ? void 0 : _d.type),
1995
- ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
1856
+ platform: params?.platform ?? this.otherParams?.platform,
1857
+ businessCode: params?.businessCode || this.otherParams?.businessCode || this.otherParams?.business_code,
1858
+ channel: params?.channel ?? this.getSubmitOrderSalesChannel(),
1859
+ type: params?.type ?? this.otherParams?.type,
1860
+ ...(params?.enhancePayload !== undefined ? {
1861
+ enhancePayload: params.enhancePayload
1862
+ } : {})
1996
1863
  });
1997
1864
  }
1998
1865
  async submitTempOrderAsync(params) {
1999
- var _a, _b, _c, _d;
2000
1866
  if (!this.store.order) {
2001
- throw new Error("BaseSales 解决方案需要 order 模块支持");
1867
+ throw new Error('BaseSales 解决方案需要 order 模块支持');
2002
1868
  }
2003
- const inferredPaymentStatus = this.getSubmitPaymentStatus(params == null ? void 0 : params.paymentStatus);
2004
- const smallTicketDataFlag = (params == null ? void 0 : params.smallTicketDataFlag) ?? this.getDefaultCheckoutSmallTicketDataFlag();
1869
+ const inferredPaymentStatus = this.getSubmitPaymentStatus(params?.paymentStatus);
1870
+ const smallTicketDataFlag = params?.smallTicketDataFlag ?? this.getDefaultCheckoutSmallTicketDataFlag();
2005
1871
  const submitParams = {
2006
1872
  cacheId: this.cacheId,
2007
- platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
2008
- businessCode: ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1873
+ platform: this.otherParams?.platform,
1874
+ businessCode: this.otherParams?.businessCode || this.otherParams?.business_code,
2009
1875
  channel: this.getSubmitOrderSalesChannel(),
2010
- type: (_d = this.otherParams) == null ? void 0 : _d.type,
1876
+ type: this.otherParams?.type,
2011
1877
  request_unique_idempotency_token: this.store.order.generateIdempotencyToken(),
2012
- ...(params == null ? void 0 : params.payments) !== void 0 ? { payments: params.payments } : {},
2013
- ...inferredPaymentStatus !== void 0 ? { paymentStatus: inferredPaymentStatus } : {},
2014
- ...smallTicketDataFlag !== void 0 ? { smallTicketDataFlag } : {},
2015
- ...(params == null ? void 0 : params.confirmPendingVoucherPayments) !== void 0 ? { confirmPendingVoucherPayments: params.confirmPendingVoucherPayments } : {},
2016
- ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
1878
+ ...(params?.payments !== undefined ? {
1879
+ payments: params.payments
1880
+ } : {}),
1881
+ ...(inferredPaymentStatus !== undefined ? {
1882
+ paymentStatus: inferredPaymentStatus
1883
+ } : {}),
1884
+ ...(smallTicketDataFlag !== undefined ? {
1885
+ smallTicketDataFlag
1886
+ } : {}),
1887
+ ...(params?.confirmPendingVoucherPayments !== undefined ? {
1888
+ confirmPendingVoucherPayments: params.confirmPendingVoucherPayments
1889
+ } : {}),
1890
+ ...(params?.enhancePayload !== undefined ? {
1891
+ enhancePayload: params.enhancePayload
1892
+ } : {})
2017
1893
  };
2018
1894
  return this.store.order.submitTempOrderAsync(submitParams);
2019
1895
  }
1896
+
2020
1897
  /**
2021
1898
  * 默认保持 WebPOS 的本地待同步订单模式;需要云端确认后才算成功的渠道可覆盖此策略。
2022
1899
  * otherParams.checkoutSyncTaskEnabled 优先,便于同一 solution 按入口恢复旧行为。
2023
1900
  */
2024
1901
  shouldUseCheckoutSyncTask() {
2025
- var _a;
2026
- const configured = (_a = this.otherParams) == null ? void 0 : _a.checkoutSyncTaskEnabled;
2027
- return typeof configured === "boolean" ? configured : true;
1902
+ const configured = this.otherParams?.checkoutSyncTaskEnabled;
1903
+ return typeof configured === 'boolean' ? configured : true;
2028
1904
  }
1905
+
2029
1906
  /** 可由特定 solution 为真实 checkout 补充默认收据数据请求。 */
2030
1907
  getDefaultCheckoutSmallTicketDataFlag() {
2031
- return void 0;
1908
+ return undefined;
2032
1909
  }
2033
1910
  async printLocalOrderReceipt(lookup) {
2034
- var _a, _b, _c, _d, _e, _f, _g;
2035
1911
  if (!this.store.order) {
2036
- throw new Error("BaseSales 解决方案需要 order 模块支持");
1912
+ throw new Error('BaseSales 解决方案需要 order 模块支持');
2037
1913
  }
2038
- const hasLookup = lookup !== void 0 && lookup !== null && lookup !== "";
2039
- const lookupPayload = typeof lookup === "number" ? { order_id: lookup } : { external_sale_number: lookup };
1914
+ const hasLookup = lookup !== undefined && lookup !== null && lookup !== '';
1915
+ const lookupPayload = typeof lookup === 'number' ? {
1916
+ order_id: lookup
1917
+ } : {
1918
+ external_sale_number: lookup
1919
+ };
2040
1920
  const context = {
2041
- platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
2042
- businessCode: ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1921
+ platform: this.otherParams?.platform,
1922
+ businessCode: this.otherParams?.businessCode || this.otherParams?.business_code,
2043
1923
  channel: this.getSubmitOrderSalesChannel(),
2044
- type: (_d = this.otherParams) == null ? void 0 : _d.type
1924
+ type: this.otherParams?.type
2045
1925
  };
2046
1926
  const payload = hasLookup ? {
2047
1927
  ...lookupPayload,
@@ -2058,48 +1938,46 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2058
1938
  channel: context.channel,
2059
1939
  type: context.type
2060
1940
  });
2061
- const response = await this.request.post("/local/print-order", payload, {
1941
+ const response = await this.request.post('/local/print-order', payload, {
2062
1942
  osServer: true,
2063
- customToast: () => {
2064
- }
1943
+ customToast: () => {}
2065
1944
  });
2066
1945
  if (!hasLookup) {
2067
- 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));
1946
+ await this.store.order.applyLocalPrintOrderNumbers?.(response?.data?.order);
2068
1947
  }
2069
1948
  return response;
2070
1949
  }
2071
1950
  getSubmitPaymentStatus(paymentStatus) {
2072
- var _a, _b;
2073
- if (paymentStatus !== void 0)
2074
- return paymentStatus;
2075
- const amountSnapshot = (_b = (_a = this.store.order) == null ? void 0 : _a.getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2076
- if (!amountSnapshot)
2077
- return void 0;
1951
+ if (paymentStatus !== undefined) return paymentStatus;
1952
+ const amountSnapshot = this.store.order?.getOrderAmountSnapshot?.();
1953
+ if (!amountSnapshot) return undefined;
2078
1954
  try {
2079
- return new import_decimal.default(amountSnapshot.amountGap || 0).lte(0) ? "paid" : void 0;
1955
+ return new _decimal.default(amountSnapshot.amountGap || 0).lte(0) ? 'paid' : undefined;
2080
1956
  } catch {
2081
- return void 0;
1957
+ return undefined;
2082
1958
  }
2083
1959
  }
2084
1960
  async syncPaymentsToOrder(params) {
2085
- var _a, _b;
2086
- if (!this.store.order)
2087
- throw new Error("order 模块未初始化");
2088
- const businessCode = params.businessCode ?? ((_a = this.otherParams) == null ? void 0 : _a.businessCode) ?? ((_b = this.otherParams) == null ? void 0 : _b.business_code);
1961
+ if (!this.store.order) throw new Error('order 模块未初始化');
1962
+ const businessCode = params.businessCode ?? this.otherParams?.businessCode ?? this.otherParams?.business_code;
2089
1963
  const channel = params.channel ?? this.getSubmitOrderSalesChannel();
2090
1964
  const syncParams = {
2091
1965
  ...params,
2092
1966
  checkoutSyncTaskEnabled: this.shouldUseCheckoutSyncTask(),
2093
- ...businessCode !== void 0 ? { businessCode } : {},
2094
- ...channel !== void 0 ? { channel } : {}
1967
+ ...(businessCode !== undefined ? {
1968
+ businessCode
1969
+ } : {}),
1970
+ ...(channel !== undefined ? {
1971
+ channel
1972
+ } : {})
2095
1973
  };
2096
1974
  const syncState = this.store.order.getOrderSyncState();
2097
- if (params.submitWhenPaid && syncState === "submitting") {
1975
+ if (params.submitWhenPaid && syncState === 'submitting') {
2098
1976
  this.queueLatestAutoPaymentSync();
2099
1977
  return this.store.order.syncPaymentsToOrder(syncParams);
2100
1978
  }
2101
1979
  const payments = params.payments || [];
2102
- await this.effectsEmit(import_types.BaseSalesHookNames.onPaymentSyncStart, {
1980
+ await this.effectsEmit(_types.BaseSalesHookNames.onPaymentSyncStart, {
2103
1981
  payments,
2104
1982
  params: syncParams,
2105
1983
  amountSnapshot: this.store.order.getOrderAmountSnapshot(),
@@ -2124,14 +2002,14 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2124
2002
  depositAmount: syncResult.depositAmount,
2125
2003
  orderExpectedAmount: syncResult.orderExpectedAmount
2126
2004
  };
2127
- await this.effectsEmit(import_types.BaseSalesHookNames.onPaymentSyncEnd, syncPayload);
2005
+ await this.effectsEmit(_types.BaseSalesHookNames.onPaymentSyncEnd, syncPayload);
2128
2006
  if (syncResult.isDepositFullyPaid && !syncResult.isOrderFullyPaid) {
2129
- await this.effectsEmit(import_types.BaseSalesHookNames.onDepositPaymentSyncEnd, syncPayload);
2007
+ await this.effectsEmit(_types.BaseSalesHookNames.onDepositPaymentSyncEnd, syncPayload);
2130
2008
  }
2131
2009
  this.scheduleQueuedAutoPaymentSyncFlush(0);
2132
2010
  return syncResult;
2133
2011
  } catch (error) {
2134
- await this.effectsEmit(import_types.BaseSalesHookNames.onPaymentSyncEnd, {
2012
+ await this.effectsEmit(_types.BaseSalesHookNames.onPaymentSyncEnd, {
2135
2013
  ok: false,
2136
2014
  error,
2137
2015
  payments: this.store.order.getOrderPayments(),
@@ -2143,46 +2021,41 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2143
2021
  throw error;
2144
2022
  }
2145
2023
  }
2024
+
2146
2025
  /** 读取当前 BaseSales 订单上下文中的 Sales 协议支付项。 */
2147
2026
  getOrderPayments() {
2148
- if (!this.store.order)
2149
- return [];
2027
+ if (!this.store.order) return [];
2150
2028
  const payments = this.store.order.getOrderPayments();
2151
2029
  return this.hydrateOrderPaymentNames(payments);
2152
2030
  }
2031
+
2153
2032
  /** 覆盖当前订单支付项,内部由 OrderModule 清洗为 Sales 协议字段。 */
2154
2033
  setOrderPayments(payments) {
2155
- if (!this.store.order)
2156
- throw new Error("order 模块未初始化");
2034
+ if (!this.store.order) throw new Error('order 模块未初始化');
2157
2035
  return this.store.order.setOrderPayments(payments);
2158
2036
  }
2159
2037
  getPaymentStatusForSync(payments) {
2160
2038
  const order = this.store.order;
2161
- if (!order)
2162
- throw new Error("order 模块未初始化");
2039
+ if (!order) throw new Error('order 模块未初始化');
2163
2040
  const completion = order.getPaymentCompletion(payments);
2164
- return completion.isOrderFullyPaid ? "paid" : "partially_paid";
2041
+ return completion.isOrderFullyPaid ? 'paid' : 'partially_paid';
2165
2042
  }
2166
2043
  queueLatestAutoPaymentSync() {
2167
2044
  this.queuedAutoPaymentSync = true;
2168
2045
  this.scheduleQueuedAutoPaymentSyncFlush();
2169
2046
  }
2170
2047
  scheduleQueuedAutoPaymentSyncFlush(delay = 100) {
2171
- if (!this.queuedAutoPaymentSync)
2172
- return;
2173
- if (this.autoPaymentSyncTimer)
2174
- return;
2048
+ if (!this.queuedAutoPaymentSync) return;
2049
+ if (this.autoPaymentSyncTimer) return;
2175
2050
  this.autoPaymentSyncTimer = setTimeout(() => {
2176
2051
  this.autoPaymentSyncTimer = null;
2177
2052
  void this.flushQueuedAutoPaymentSync();
2178
2053
  }, delay);
2179
2054
  }
2180
2055
  async flushQueuedAutoPaymentSync() {
2181
- if (!this.store.order)
2182
- return;
2183
- if (!this.queuedAutoPaymentSync || this.autoPaymentSyncFlushing)
2184
- return;
2185
- if (this.store.order.getOrderSyncState() === "submitting") {
2056
+ if (!this.store.order) return;
2057
+ if (!this.queuedAutoPaymentSync || this.autoPaymentSyncFlushing) return;
2058
+ if (this.store.order.getOrderSyncState() === 'submitting') {
2186
2059
  this.scheduleQueuedAutoPaymentSyncFlush();
2187
2060
  return;
2188
2061
  }
@@ -2191,8 +2064,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2191
2064
  while (this.queuedAutoPaymentSync) {
2192
2065
  this.queuedAutoPaymentSync = false;
2193
2066
  const payments = this.store.order.getOrderPayments();
2194
- if (!payments.length)
2195
- continue;
2067
+ if (!payments.length) continue;
2196
2068
  await this.syncPaymentsToOrder({
2197
2069
  payments,
2198
2070
  paymentStatus: this.getPaymentStatusForSync(payments),
@@ -2201,7 +2073,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2201
2073
  });
2202
2074
  }
2203
2075
  } catch (error) {
2204
- this.logError("queued auto sync payments failed", {
2076
+ this.logError('queued auto sync payments failed', {
2205
2077
  error: error instanceof Error ? error.message : String(error)
2206
2078
  });
2207
2079
  } finally {
@@ -2211,69 +2083,64 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2211
2083
  }
2212
2084
  }
2213
2085
  }
2086
+
2214
2087
  /**
2215
2088
  * 同步兼容入口。无法等待 IoT 短号时,按调用当下的 device_id 或 LOCAL 生成。
2216
2089
  */
2217
2090
  addOrderPayment(payment) {
2218
- const hasPaymentNumber = String(
2219
- payment.payment_number || ""
2220
- ).trim() !== "";
2221
- return this.addOrderPaymentWithDevicePrefix(
2222
- payment,
2223
- hasPaymentNumber ? "LOCAL" : this.getPaymentNumberDevicePrefixSync()
2224
- );
2091
+ const hasPaymentNumber = String(payment.payment_number || '').trim() !== '';
2092
+ return this.addOrderPaymentWithDevicePrefix(payment, hasPaymentNumber ? 'LOCAL' : this.getPaymentNumberDevicePrefixSync());
2225
2093
  }
2094
+
2226
2095
  /**
2227
2096
  * 创建新支付项时优先使用业务解决方案初始化阶段缓存的设备短号;
2228
2097
  * 未缓存的通用 BaseSales 保持实时读取设备信息的兼容语义。
2229
2098
  */
2230
2099
  async addOrderPaymentAsync(payment) {
2231
2100
  const paymentRecord = payment;
2232
- const hasPaymentNumber = String(paymentRecord.payment_number || "").trim() !== "";
2233
- const devicePrefix = hasPaymentNumber ? "LOCAL" : await this.getPaymentNumberDevicePrefixAsync();
2101
+ const hasPaymentNumber = String(paymentRecord.payment_number || '').trim() !== '';
2102
+ const devicePrefix = hasPaymentNumber ? 'LOCAL' : await this.getPaymentNumberDevicePrefixAsync();
2234
2103
  return this.addOrderPaymentWithDevicePrefix(payment, devicePrefix);
2235
2104
  }
2236
2105
  addOrderPaymentWithDevicePrefix(payment, devicePrefix) {
2237
- var _a;
2238
- if (!this.store.order)
2239
- throw new Error("order 模块未初始化");
2106
+ if (!this.store.order) throw new Error('order 模块未初始化');
2240
2107
  const paymentRecord = payment;
2241
- const paymentAmount = new import_decimal.default(paymentRecord.amount || 0);
2108
+ const paymentAmount = new _decimal.default(paymentRecord.amount || 0);
2242
2109
  if (paymentAmount.isZero()) {
2243
- this.logWarning("addOrderPayment: 支付金额为 0,跳过添加支付项", {
2110
+ this.logWarning('addOrderPayment: 支付金额为 0,跳过添加支付项', {
2244
2111
  payment: paymentRecord
2245
2112
  });
2246
2113
  return this.store.order.getOrderPayments();
2247
2114
  }
2248
- const metadata = paymentRecord.metadata && typeof paymentRecord.metadata === "object" ? { ...paymentRecord.metadata } : {};
2249
- const shopWalletPassId = (_a = this.otherParams) == null ? void 0 : _a.shop_wallet_pass_id;
2250
- if (shopWalletPassId !== void 0 && shopWalletPassId !== null) {
2115
+ const metadata = paymentRecord.metadata && typeof paymentRecord.metadata === 'object' ? {
2116
+ ...paymentRecord.metadata
2117
+ } : {};
2118
+ const shopWalletPassId = this.otherParams?.shop_wallet_pass_id;
2119
+ if (shopWalletPassId !== undefined && shopWalletPassId !== null) {
2251
2120
  metadata.shop_wallet_pass_id = shopWalletPassId;
2252
2121
  }
2253
- const normalizedPaymentRecord = (0, import_payment_utils.ensureOrderPaymentNumber)(
2254
- paymentRecord,
2255
- devicePrefix,
2256
- import_utils.createUuidV4
2257
- );
2258
- const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
2122
+ const normalizedPaymentRecord = (0, _paymentUtils.ensureOrderPaymentNumber)(paymentRecord, devicePrefix, _utils.createUuidV4);
2123
+ const paymentTimestamp = (0, _dayjs.default)().format('YYYY-MM-DD HH:mm:ss');
2259
2124
  const paymentTime = paymentRecord.payment_time ?? paymentTimestamp;
2260
2125
  const createdAt = paymentRecord.created_at ?? paymentTimestamp;
2261
- const serviceCharge = paymentRecord.service_charge && typeof paymentRecord.service_charge === "object" ? paymentRecord.service_charge : null;
2262
- 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;
2126
+ const serviceCharge = paymentRecord.service_charge && typeof paymentRecord.service_charge === 'object' ? paymentRecord.service_charge : null;
2127
+ 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;
2263
2128
  const payments = this.store.order.addOrderPayment({
2264
2129
  ...normalizedPaymentRecord,
2265
- ...calculatedServiceFee !== void 0 ? { service_fee: calculatedServiceFee } : {},
2130
+ ...(calculatedServiceFee !== undefined ? {
2131
+ service_fee: calculatedServiceFee
2132
+ } : {}),
2266
2133
  metadata,
2267
2134
  payment_time: paymentTime,
2268
2135
  created_at: createdAt
2269
2136
  });
2270
- if (paymentRecord.status === "payment_pending") {
2137
+ if (paymentRecord.status === 'payment_pending') {
2271
2138
  return payments;
2272
2139
  }
2273
2140
  const amountSnapshot = this.store.order.getOrderAmountSnapshot();
2274
2141
  const syncState = this.store.order.getOrderSyncState();
2275
2142
  if (amountSnapshot) {
2276
- if (syncState === "submitting") {
2143
+ if (syncState === 'submitting') {
2277
2144
  this.queueLatestAutoPaymentSync();
2278
2145
  return payments;
2279
2146
  }
@@ -2282,31 +2149,26 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2282
2149
  paymentStatus: this.getPaymentStatusForSync(payments),
2283
2150
  submitWhenPaid: true,
2284
2151
  smallTicketDataFlag: 1
2285
- }).catch((error) => {
2286
- this.logError("auto sync payments failed", {
2152
+ }).catch(error => {
2153
+ this.logError('auto sync payments failed', {
2287
2154
  error: error instanceof Error ? error.message : String(error)
2288
2155
  });
2289
2156
  });
2290
2157
  }
2291
2158
  return payments;
2292
2159
  }
2160
+
2293
2161
  /** 更新当前订单中的指定支付项。 */
2294
2162
  async updateOrderPayment(paymentIdentity, updates, options = {}) {
2295
- var _a, _b, _c;
2296
- if (!this.store.order)
2297
- throw new Error("order 模块未初始化");
2298
- const matchMode = options.matchBy === "compat" || options.matchBy === "legacy" ? "compat" : "payment_number";
2299
- const previousMatch = (0, import_payment_utils.resolveOrderPaymentIdentity)(
2300
- this.store.order.getOrderPayments(),
2301
- paymentIdentity,
2302
- matchMode
2303
- );
2304
- const previousPayment = previousMatch == null ? void 0 : previousMatch.payment;
2305
- if ((previousPayment == null ? void 0 : previousPayment.status) === "paid" && !options.applyUpdatesWhenPaid) {
2163
+ if (!this.store.order) throw new Error('order 模块未初始化');
2164
+ const matchMode = options.matchBy === 'compat' || options.matchBy === 'legacy' ? 'compat' : 'payment_number';
2165
+ const previousMatch = (0, _paymentUtils.resolveOrderPaymentIdentity)(this.store.order.getOrderPayments(), paymentIdentity, matchMode);
2166
+ const previousPayment = previousMatch?.payment;
2167
+ if (previousPayment?.status === 'paid' && !options.applyUpdatesWhenPaid) {
2306
2168
  const currentPayments = this.store.order.getOrderPayments();
2307
- let syncResult2;
2169
+ let syncResult;
2308
2170
  if (options.submitWhenPaid && options.forceSubmitIfPaid) {
2309
- syncResult2 = await this.syncPaymentsToOrder({
2171
+ syncResult = await this.syncPaymentsToOrder({
2310
2172
  payments: currentPayments,
2311
2173
  paymentStatus: this.getPaymentStatusForSync(currentPayments),
2312
2174
  submitWhenPaid: true,
@@ -2317,8 +2179,10 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2317
2179
  updated: false,
2318
2180
  payment: previousPayment,
2319
2181
  payments: currentPayments,
2320
- summary: ((_a = this.store.order.getOrderAmountSnapshot()) == null ? void 0 : _a.summary) || null,
2321
- ...syncResult2 !== void 0 ? { syncResult: syncResult2 } : {}
2182
+ summary: this.store.order.getOrderAmountSnapshot()?.summary || null,
2183
+ ...(syncResult !== undefined ? {
2184
+ syncResult
2185
+ } : {})
2322
2186
  };
2323
2187
  }
2324
2188
  const result = await this.store.order.updateOrderPayment(paymentIdentity, updates, {
@@ -2331,18 +2195,15 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2331
2195
  draftResult = await this.saveSalesOrderDraft();
2332
2196
  } catch (error) {
2333
2197
  draftError = error;
2334
- this.logError("updateOrderPayment: 保存支付草稿失败", {
2198
+ this.logError('updateOrderPayment: 保存支付草稿失败', {
2335
2199
  paymentIdentity,
2336
2200
  error: error instanceof Error ? error.message : String(error)
2337
2201
  });
2338
- if (!options.submitWhenPaid)
2339
- throw error;
2202
+ if (!options.submitWhenPaid) throw error;
2340
2203
  }
2341
2204
  }
2342
- const becamePaid = (previousPayment == null ? void 0 : previousPayment.status) !== "paid" && ((_b = result.payment) == null ? void 0 : _b.status) === "paid";
2343
- const shouldSubmit = Boolean(
2344
- options.submitWhenPaid && ((_c = result.payment) == null ? void 0 : _c.status) === "paid" && (becamePaid || options.forceSubmitIfPaid)
2345
- );
2205
+ const becamePaid = previousPayment?.status !== 'paid' && result.payment?.status === 'paid';
2206
+ const shouldSubmit = Boolean(options.submitWhenPaid && result.payment?.status === 'paid' && (becamePaid || options.forceSubmitIfPaid));
2346
2207
  let syncResult;
2347
2208
  if (shouldSubmit) {
2348
2209
  syncResult = await this.syncPaymentsToOrder({
@@ -2354,60 +2215,62 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2354
2215
  }
2355
2216
  return {
2356
2217
  ...result,
2357
- ...draftResult !== void 0 ? { draftResult } : {},
2358
- ...draftError !== void 0 ? { draftError } : {},
2359
- ...syncResult !== void 0 ? { syncResult } : {}
2218
+ ...(draftResult !== undefined ? {
2219
+ draftResult
2220
+ } : {}),
2221
+ ...(draftError !== undefined ? {
2222
+ draftError
2223
+ } : {}),
2224
+ ...(syncResult !== undefined ? {
2225
+ syncResult
2226
+ } : {})
2360
2227
  };
2361
2228
  }
2229
+
2362
2230
  /** 删除当前订单中的指定支付项。 */
2363
2231
  deleteOrderPayment(paymentIdentity) {
2364
- if (!this.store.order)
2365
- throw new Error("order 模块未初始化");
2232
+ if (!this.store.order) throw new Error('order 模块未初始化');
2366
2233
  return this.store.order.deleteOrderPayment(paymentIdentity);
2367
2234
  }
2235
+
2368
2236
  /** 覆盖 wallet pass 支付项,同时保留普通支付项。 */
2369
2237
  updateVoucherOrderPayments(payments, options) {
2370
- if (!this.store.order)
2371
- throw new Error("order 模块未初始化");
2238
+ if (!this.store.order) throw new Error('order 模块未初始化');
2372
2239
  return this.store.order.updateVoucherOrderPayments(payments, options);
2373
2240
  }
2374
2241
  async updateVoucherOrderPaymentsAsync(payments, options) {
2375
- if (!this.store.order)
2376
- throw new Error("order 模块未初始化");
2242
+ if (!this.store.order) throw new Error('order 模块未初始化');
2377
2243
  return this.store.order.updateVoucherOrderPaymentsAsync(payments, options);
2378
2244
  }
2379
2245
  confirmPendingVoucherPayments() {
2380
- if (!this.store.order)
2381
- throw new Error("order 模块未初始化");
2246
+ if (!this.store.order) throw new Error('order 模块未初始化');
2382
2247
  const payments = this.store.order.confirmPendingVoucherPayments();
2383
2248
  if (this.store.payment) {
2384
2249
  const committed = this.getCommittedWalletAssets();
2385
- const state = this.store.payment.wallet.setCommittedWalletAssets(
2386
- committed.ids,
2387
- committed.assets
2388
- );
2250
+ const state = this.store.payment.wallet.setCommittedWalletAssets(committed.ids, committed.assets);
2389
2251
  void this.publishWalletAssetsState(state);
2390
2252
  }
2391
2253
  return payments;
2392
2254
  }
2393
2255
  discardPendingVoucherPayments() {
2394
- if (!this.store.order)
2395
- throw new Error("order 模块未初始化");
2256
+ if (!this.store.order) throw new Error('order 模块未初始化');
2396
2257
  return this.store.order.discardPendingVoucherPayments();
2397
2258
  }
2398
2259
  getWalletProductList() {
2399
- var _a, _b;
2400
- const tempOrder = (_a = this.store.order) == null ? void 0 : _a.getTempOrder();
2401
- if (!((_b = tempOrder == null ? void 0 : tempOrder.products) == null ? void 0 : _b.length))
2402
- return [];
2403
- const walletProducts = tempOrder == null ? void 0 : tempOrder.products.map((product) => {
2260
+ const tempOrder = this.store.order?.getTempOrder();
2261
+ if (!tempOrder?.products?.length) return [];
2262
+ // 过滤出有 product_id的商品来,如果没有代表他是自定义商品,不需要参与 wallet
2263
+ // debugger
2264
+ // const products = tempOrder?.products?.filter(n => n.product_id)
2265
+
2266
+ const walletProducts = tempOrder?.products.map(product => {
2404
2267
  const metadata = product.metadata || {};
2405
2268
  const rawHolderId = product.holder_id ?? metadata.holder_id;
2406
2269
  const holderIdValue = Array.isArray(rawHolderId) ? rawHolderId[0] : rawHolderId;
2407
- const holder_id = Number.isInteger(Number(holderIdValue)) ? Number(holderIdValue) : void 0;
2270
+ const holder_id = Number.isInteger(Number(holderIdValue)) ? Number(holderIdValue) : undefined;
2408
2271
  return {
2409
2272
  product_id: product.product_id || 0,
2410
- product_variant_id: String(product.product_variant_id ?? ""),
2273
+ product_variant_id: String(product.product_variant_id ?? ''),
2411
2274
  quantity: product.num || 1,
2412
2275
  is_price_include_tax: tempOrder.is_price_include_tax,
2413
2276
  is_charge_tax: product.is_charge_tax ?? 0,
@@ -2423,7 +2286,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2423
2286
  main_product_attached_bundle_surcharge_fee: metadata.main_product_attached_bundle_surcharge_fee,
2424
2287
  surcharge_rounding_remainder: metadata.surcharge_rounding_remainder
2425
2288
  },
2426
- product_bundle: (product.product_bundle || []).map((bundle) => {
2289
+ product_bundle: (product.product_bundle || []).map(bundle => {
2427
2290
  const bundleMetadata = bundle.metadata || {};
2428
2291
  return {
2429
2292
  is_price_include_tax: tempOrder.is_price_include_tax,
@@ -2450,14 +2313,12 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2450
2313
  return walletProducts;
2451
2314
  }
2452
2315
  buildWalletInitBusinessData(params) {
2453
- var _a;
2454
- const snapshot = (_a = this.store.order) == null ? void 0 : _a.getOrderSnapshot();
2455
- const tempOrder = snapshot == null ? void 0 : snapshot.tempOrder;
2456
- const amount = snapshot == null ? void 0 : snapshot.amount;
2457
- if (!tempOrder || !amount)
2458
- return null;
2316
+ const snapshot = this.store.order?.getOrderSnapshot();
2317
+ const tempOrder = snapshot?.tempOrder;
2318
+ const amount = snapshot?.amount;
2319
+ if (!tempOrder || !amount) return null;
2459
2320
  return {
2460
- customer_id: tempOrder.customer_id ? Number(tempOrder.customer_id) : void 0,
2321
+ customer_id: tempOrder.customer_id ? Number(tempOrder.customer_id) : undefined,
2461
2322
  holder: tempOrder.holder,
2462
2323
  amountInfo: {
2463
2324
  totalAmount: amount.totalAmount,
@@ -2466,17 +2327,16 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2466
2327
  isDeposit: tempOrder.is_deposit
2467
2328
  },
2468
2329
  products: this.getWalletProductList(),
2469
- order_wait_pay_amount: (params == null ? void 0 : params.order_wait_pay_amount) ?? Number(amount.amountGap || 0),
2330
+ order_wait_pay_amount: params?.order_wait_pay_amount ?? Number(amount.amountGap || 0),
2470
2331
  is_price_include_tax: tempOrder.is_price_include_tax ?? this.otherParams.is_price_include_tax ?? 1,
2471
- ...snapshot.identity.orderId ? { payment_order_id: String(snapshot.identity.orderId) } : {}
2332
+ ...(snapshot.identity.orderId ? {
2333
+ payment_order_id: String(snapshot.identity.orderId)
2334
+ } : {})
2472
2335
  };
2473
2336
  }
2474
2337
  async initWalletData(params) {
2475
- var _a;
2476
- if (!this.store.order)
2477
- throw new Error("order 模块未初始化");
2478
- if (!this.store.payment)
2479
- throw new Error("payment 模块未初始化");
2338
+ if (!this.store.order) throw new Error('order 模块未初始化');
2339
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2480
2340
  const snapshot = this.store.order.getOrderSnapshot();
2481
2341
  const walletBusinessData = this.buildWalletInitBusinessData(params);
2482
2342
  if (!walletBusinessData) {
@@ -2488,11 +2348,9 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2488
2348
  products: []
2489
2349
  };
2490
2350
  }
2491
- const result = await this.store.payment.wallet.initializeWalletDataFromBusinessAsync(
2492
- walletBusinessData
2493
- );
2351
+ const result = await this.store.payment.wallet.initializeWalletDataFromBusinessAsync(walletBusinessData);
2494
2352
  await this.core.effects.emit(`${this.name}:onWalletDataInitialized`, {
2495
- orderId: (_a = snapshot == null ? void 0 : snapshot.identity) == null ? void 0 : _a.orderId,
2353
+ orderId: snapshot?.identity?.orderId,
2496
2354
  customerId: walletBusinessData.customer_id,
2497
2355
  walletBusinessData: {
2498
2356
  customer_id: walletBusinessData.customer_id,
@@ -2504,26 +2362,22 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2504
2362
  return result;
2505
2363
  }
2506
2364
  getCommittedWalletAssets() {
2507
- var _a, _b;
2508
- const payments = ((_b = (_a = this.store.order) == null ? void 0 : _a.getOrderPayments) == null ? void 0 : _b.call(_a)) || [];
2509
- const committed = payments.filter((payment) => {
2510
- const voucherId = payment == null ? void 0 : payment.voucher_id;
2511
- if (voucherId === void 0 || voucherId === null || voucherId === 0) {
2365
+ const payments = this.store.order?.getOrderPayments?.() || [];
2366
+ const committed = payments.filter(payment => {
2367
+ const voucherId = payment?.voucher_id;
2368
+ if (voucherId === undefined || voucherId === null || voucherId === 0) {
2512
2369
  return false;
2513
2370
  }
2514
- return (payment == null ? void 0 : payment.status) === "paid" || (payment == null ? void 0 : payment.isSynced) === true || (payment == null ? void 0 : payment.order_payment_id) !== void 0 && (payment == null ? void 0 : payment.order_payment_id) !== null && (payment == null ? void 0 : payment.order_payment_id) !== "";
2371
+ return payment?.status === 'paid' || payment?.isSynced === true || payment?.order_payment_id !== undefined && payment?.order_payment_id !== null && payment?.order_payment_id !== '';
2515
2372
  });
2516
2373
  return {
2517
- ids: committed.map((payment) => payment.voucher_id),
2518
- assets: committed.map((payment) => {
2519
- var _a2;
2520
- const fundRecord = (payment == null ? void 0 : payment.fund_record) || {};
2374
+ ids: committed.map(payment => payment.voucher_id),
2375
+ assets: committed.map(payment => {
2376
+ const fundRecord = payment?.fund_record || {};
2521
2377
  const walletPassName = fundRecord.wallet_pass_name;
2522
- const title = walletPassName && typeof walletPassName === "object" ? walletPassName.default || Object.values(walletPassName)[0] : walletPassName;
2523
- const code = String((payment == null ? void 0 : payment.code) || "").toUpperCase();
2524
- const tag = ((_a2 = Object.entries(WALLET_PAYMENT_CODE_BY_TAG).find(
2525
- ([, paymentCode]) => paymentCode === code
2526
- )) == null ? void 0 : _a2[0]) || fundRecord.tag;
2378
+ const title = walletPassName && typeof walletPassName === 'object' ? walletPassName.default || Object.values(walletPassName)[0] : walletPassName;
2379
+ const code = String(payment?.code || '').toUpperCase();
2380
+ const tag = Object.entries(WALLET_PAYMENT_CODE_BY_TAG).find(([, paymentCode]) => paymentCode === code)?.[0] || fundRecord.tag;
2527
2381
  return {
2528
2382
  id: payment.voucher_id,
2529
2383
  voucher_id: payment.voucher_id,
@@ -2541,34 +2395,25 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2541
2395
  };
2542
2396
  }
2543
2397
  async publishWalletAssetsState(state) {
2544
- await this.effectsEmit(import_types.BaseSalesHookNames.onWalletAssetsStateChanged, {
2398
+ await this.effectsEmit(_types.BaseSalesHookNames.onWalletAssetsStateChanged, {
2545
2399
  state
2546
2400
  });
2547
2401
  return state;
2548
2402
  }
2549
2403
  async syncSelectedWalletAssets(state) {
2550
2404
  if (!this.store.order || !this.store.payment) {
2551
- throw new Error("订单或支付模块未初始化");
2405
+ throw new Error('订单或支付模块未初始化');
2552
2406
  }
2553
2407
  let paymentMethods = this.getPaymentMethods();
2554
2408
  if (!paymentMethods.length && state.selectedItems.length) {
2555
2409
  paymentMethods = await this.getPaymentMethodsAsync();
2556
2410
  }
2557
- const methodByCode = new Map(
2558
- paymentMethods.map((method) => [String(method.code || "").toUpperCase(), method])
2559
- );
2560
- const preparePayments = this.store.payment.wallet.formatWalletPassList2PreparePayments(
2561
- state.selectedItems
2562
- );
2563
- const selectedAssetById = new Map(
2564
- state.selectedItems.map((asset) => [
2565
- String(getSharedWalletAssetId(asset)),
2566
- asset
2567
- ])
2568
- );
2569
- const voucherPayments = preparePayments.flatMap((item) => {
2411
+ const methodByCode = new Map(paymentMethods.map(method => [String(method.code || '').toUpperCase(), method]));
2412
+ const preparePayments = this.store.payment.wallet.formatWalletPassList2PreparePayments(state.selectedItems);
2413
+ const selectedAssetById = new Map(state.selectedItems.map(asset => [String(getSharedWalletAssetId(asset)), asset]));
2414
+ const voucherPayments = preparePayments.flatMap(item => {
2570
2415
  const asset = selectedAssetById.get(String(item.voucher_id));
2571
- const paymentCode = WALLET_PAYMENT_CODE_BY_TAG[String(item.tag || (asset == null ? void 0 : asset.tag) || "")] || String(item.tag || (asset == null ? void 0 : asset.tag) || "").toUpperCase();
2416
+ const paymentCode = WALLET_PAYMENT_CODE_BY_TAG[String(item.tag || asset?.tag || '')] || String(item.tag || asset?.tag || '').toUpperCase();
2572
2417
  const paymentMethod = methodByCode.get(paymentCode);
2573
2418
  const formattedAmount = Number(item.amount);
2574
2419
  const amount = Number.isFinite(formattedAmount) && formattedAmount > 0 ? formattedAmount : getSharedWalletAssetAmount(asset);
@@ -2580,105 +2425,105 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2580
2425
  amount,
2581
2426
  paymentMethod
2582
2427
  });
2583
- return [
2584
- {
2585
- amount: amount.toFixed(2),
2586
- code: paymentMethod.code,
2587
- custom_payment_id: paymentMethod.id,
2588
- name: paymentMethod.name,
2589
- type: paymentMethod.type,
2590
- voucher_id: item.voucher_id,
2591
- wallet_pass_usage_unit: item.wallet_pass_usage_unit,
2592
- wallet_pass_use_value: walletPassUseValue,
2593
- fund_record: buildSharedWalletFundRecord({
2594
- asset,
2595
- amount,
2596
- paymentMethod
2597
- })
2598
- }
2599
- ];
2428
+ return [{
2429
+ amount: amount.toFixed(2),
2430
+ code: paymentMethod.code,
2431
+ custom_payment_id: paymentMethod.id,
2432
+ name: paymentMethod.name,
2433
+ type: paymentMethod.type,
2434
+ voucher_id: item.voucher_id,
2435
+ wallet_pass_usage_unit: item.wallet_pass_usage_unit,
2436
+ wallet_pass_use_value: walletPassUseValue,
2437
+ fund_record: buildSharedWalletFundRecord({
2438
+ asset,
2439
+ amount,
2440
+ paymentMethod
2441
+ })
2442
+ }];
2600
2443
  });
2601
2444
  const payments = this.updateVoucherOrderPayments(voucherPayments, {
2602
- status: "payment_pending"
2445
+ status: 'payment_pending'
2446
+ });
2447
+ await this.store.order.recalculateSummary({
2448
+ createIfMissing: true
2603
2449
  });
2604
- await this.store.order.recalculateSummary({ createIfMissing: true });
2605
2450
  return payments;
2606
2451
  }
2452
+
2607
2453
  /** 读取购物车与 Shared Checkout 共用的钱包资产状态。 */
2608
2454
  getWalletAssetsState() {
2609
- if (!this.store.payment)
2610
- throw new Error("payment 模块未初始化");
2455
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2611
2456
  return this.store.payment.wallet.getWalletAssetsState();
2612
2457
  }
2458
+
2613
2459
  /** 导出 Shared Checkout 跨运行时恢复所需的钱包状态与搜索缓存。 */
2614
2460
  exportWalletAssetsSnapshot() {
2615
- if (!this.store.payment)
2616
- throw new Error("payment 模块未初始化");
2461
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2617
2462
  return this.store.payment.wallet.exportWalletAssetsSnapshot();
2618
2463
  }
2464
+
2619
2465
  /** 配置仅影响 Wallet Assets,不改变 Promotion/Voucher 选择流程。 */
2620
2466
  configureWalletAssetsBehavior(options) {
2621
- if (!this.store.payment)
2622
- throw new Error("payment 模块未初始化");
2467
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2623
2468
  this.store.payment.wallet.configureWalletAssetsBehavior(options);
2624
2469
  }
2470
+
2625
2471
  /**
2626
2472
  * 恢复 Shared Checkout 钱包快照,并把选择重新同步为订单 pending payment。
2627
2473
  */
2628
2474
  async importWalletAssetsSnapshot(snapshot) {
2629
- if (!this.store.payment)
2630
- throw new Error("payment 模块未初始化");
2475
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2631
2476
  const state = this.store.payment.wallet.importWalletAssetsSnapshot(snapshot);
2632
2477
  await this.syncSelectedWalletAssets(state);
2633
2478
  return this.publishWalletAssetsState(state);
2634
2479
  }
2480
+
2635
2481
  /**
2636
2482
  * 基于当前订单快照刷新钱包资产。商品变化保留并重验选择;客户变化强制清空。
2637
2483
  */
2638
2484
  async refreshWalletAssets(params) {
2639
- if (!this.store.order)
2640
- throw new Error("order 模块未初始化");
2641
- if (!this.store.payment)
2642
- throw new Error("payment 模块未初始化");
2485
+ if (!this.store.order) throw new Error('order 模块未初始化');
2486
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2643
2487
  const refreshSequence = ++this.walletAssetsRefreshSequence;
2644
2488
  const wallet = this.store.payment.wallet;
2645
2489
  const businessData = this.buildWalletInitBusinessData(params);
2646
2490
  if (!businessData) {
2647
2491
  wallet.clearAllCache();
2648
2492
  const emptyState = wallet.getWalletAssetsState();
2649
- this.updateVoucherOrderPayments([], { status: "payment_pending" });
2493
+ this.updateVoucherOrderPayments([], {
2494
+ status: 'payment_pending'
2495
+ });
2650
2496
  return this.publishWalletAssetsState(emptyState);
2651
2497
  }
2652
2498
  const previousState = wallet.getWalletAssetsState();
2653
- const hasPreviousWalletContext = previousState.status !== "idle" || previousState.items.length > 0 || previousState.selectedIds.length > 0 || previousState.customerId !== void 0;
2654
- const customerChanged = hasPreviousWalletContext && String(previousState.customerId ?? "") !== String(businessData.customer_id ?? "");
2499
+ const hasPreviousWalletContext = previousState.status !== 'idle' || previousState.items.length > 0 || previousState.selectedIds.length > 0 || previousState.customerId !== undefined;
2500
+ const customerChanged = hasPreviousWalletContext && String(previousState.customerId ?? '') !== String(businessData.customer_id ?? '');
2655
2501
  if (customerChanged) {
2656
2502
  const clearedState = wallet.clearWalletAssetSelection();
2657
- this.updateVoucherOrderPayments([], { status: "payment_pending" });
2503
+ this.updateVoucherOrderPayments([], {
2504
+ status: 'payment_pending'
2505
+ });
2658
2506
  await this.publishWalletAssetsState(clearedState);
2659
2507
  }
2660
- const refreshTask = wallet.refreshWalletAssetsFromBusinessAsync(
2661
- businessData,
2662
- {
2663
- preserveSelection: (params == null ? void 0 : params.preserveSelection) !== false && !customerChanged
2664
- }
2665
- );
2508
+ const refreshTask = wallet.refreshWalletAssetsFromBusinessAsync(businessData, {
2509
+ preserveSelection: params?.preserveSelection !== false && !customerChanged
2510
+ });
2666
2511
  await this.publishWalletAssetsState(wallet.getWalletAssetsState());
2667
2512
  let state = await refreshTask;
2668
2513
  if (refreshSequence !== this.walletAssetsRefreshSequence) {
2669
2514
  return wallet.getWalletAssetsState();
2670
2515
  }
2671
- if (state.status !== "error") {
2516
+ if (state.status !== 'error') {
2672
2517
  const committed = this.getCommittedWalletAssets();
2673
2518
  state = wallet.setCommittedWalletAssets(committed.ids, committed.assets);
2674
2519
  }
2675
2520
  await this.syncSelectedWalletAssets(state);
2676
2521
  return this.publishWalletAssetsState(state);
2677
2522
  }
2523
+
2678
2524
  /** 选择或取消单张钱包资产,并立即同步 pending wallet payments。 */
2679
2525
  async selectWalletAsset(params) {
2680
- if (!this.store.payment)
2681
- throw new Error("payment 模块未初始化");
2526
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2682
2527
  const state = this.store.payment.wallet.selectWalletAsset(params.assetId, {
2683
2528
  selected: params.selected,
2684
2529
  source: params.source
@@ -2686,41 +2531,40 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2686
2531
  await this.syncSelectedWalletAssets(state);
2687
2532
  return this.publishWalletAssetsState(state);
2688
2533
  }
2534
+
2689
2535
  /** 更新已选钱包资产的手动使用金额,并同步 pending payment。 */
2690
2536
  async updateWalletAssetAmount(params) {
2691
- if (!this.store.payment)
2692
- throw new Error("payment 模块未初始化");
2693
- const state = this.store.payment.wallet.updateWalletAssetAmount(
2694
- params.assetId,
2695
- params.amount
2696
- );
2537
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2538
+ const state = this.store.payment.wallet.updateWalletAssetAmount(params.assetId, params.amount);
2697
2539
  await this.syncSelectedWalletAssets(state);
2698
2540
  return this.publishWalletAssetsState(state);
2699
2541
  }
2542
+
2700
2543
  /** 扫码精确查券;仅可用资产会被自动选中。 */
2701
2544
  async scanWalletAsset(code) {
2702
- if (!this.store.payment)
2703
- throw new Error("payment 模块未初始化");
2545
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2704
2546
  const wallet = this.store.payment.wallet;
2547
+ // 扫码可能早于后台 Wallet 刷新,搜索参数必须以当前订单为准。
2705
2548
  const businessData = this.buildWalletInitBusinessData();
2706
2549
  if (businessData) {
2707
2550
  wallet.generateWalletParams(businessData);
2708
2551
  }
2709
2552
  const result = await wallet.scanWalletAssetAsync(code);
2710
- if (result.type === "normalCode") {
2553
+ if (result.type === 'normalCode') {
2711
2554
  await this.syncSelectedWalletAssets(result.state);
2712
2555
  await this.publishWalletAssetsState(result.state);
2713
2556
  }
2714
2557
  return result;
2715
2558
  }
2559
+
2716
2560
  /** 清空全部未确认钱包选择,已支付钱包项由 Order 模块继续保留。 */
2717
2561
  async clearWalletAssetSelection() {
2718
- if (!this.store.payment)
2719
- throw new Error("payment 模块未初始化");
2562
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2720
2563
  const state = this.store.payment.wallet.clearWalletAssetSelection();
2721
2564
  await this.syncSelectedWalletAssets(state);
2722
2565
  return this.publishWalletAssetsState(state);
2723
2566
  }
2567
+
2724
2568
  /**
2725
2569
  * 更新当前订单客户字段。
2726
2570
  *
@@ -2728,46 +2572,50 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2728
2572
  * 调用方通过 onCustomerChange 回调完成。
2729
2573
  */
2730
2574
  updateOrderCustomer(customer) {
2731
- if (!this.store.order)
2732
- throw new Error("order 模块未初始化");
2575
+ if (!this.store.order) throw new Error('order 模块未初始化');
2733
2576
  const result = this.store.order.updateTempOrderCustomer(customer);
2734
- this.store.order.recalculateSummary({ createIfMissing: true });
2577
+ this.store.order.recalculateSummary({
2578
+ createIfMissing: true
2579
+ });
2735
2580
  this.store.order.persistTempOrder();
2736
2581
  return result;
2737
2582
  }
2583
+
2738
2584
  /** 获取可用支付方式列表,供 PaymentModal 渲染支付选项。 */
2739
2585
  async getPaymentMethodsAsync() {
2586
+ // if (this.store.payment) {
2587
+ // return this.store.payment.getPayMethodListAsync();
2588
+ // }
2740
2589
  try {
2741
- const response = await this.request.get("/pay/custom-payment/all", {
2590
+ const response = await this.request.get('/pay/custom-payment/all', {
2742
2591
  filterPaymentMethods: true
2743
2592
  }, {
2744
2593
  osServer: true
2745
2594
  });
2746
- const paymentMethods = (response == null ? void 0 : response.data) || [];
2595
+ const paymentMethods = response?.data || [];
2747
2596
  this.paymentMethodsCache = Array.isArray(paymentMethods) ? [...paymentMethods] : [];
2748
2597
  return this.getPaymentMethods();
2749
2598
  } catch (error) {
2750
- this.logWarning("getPaymentMethodsAsync: 获取支付方式列表失败,使用缓存列表", {
2599
+ this.logWarning('getPaymentMethodsAsync: 获取支付方式列表失败,使用缓存列表', {
2751
2600
  error: error instanceof Error ? error.message : String(error)
2752
2601
  });
2753
2602
  return this.getPaymentMethods();
2754
2603
  }
2755
2604
  }
2605
+
2756
2606
  /** 同步读取初始化时缓存的支付方式列表。 */
2757
2607
  getPaymentMethods() {
2758
2608
  return [...this.paymentMethodsCache];
2759
2609
  }
2760
2610
  findCashPaymentMethod(paymentMethods) {
2761
- return paymentMethods.find((method) => {
2762
- const identifiers = [method == null ? void 0 : method.code, method == null ? void 0 : method.type, method == null ? void 0 : method.tag].map(
2763
- (value) => String(value || "").toUpperCase()
2764
- );
2765
- return identifiers.includes("CASHMANUAL") && (method == null ? void 0 : method.enabled) !== false && (method == null ? void 0 : method.enable) !== false;
2611
+ return paymentMethods.find(method => {
2612
+ const identifiers = [method?.code, method?.type, method?.tag].map(value => String(value || '').toUpperCase());
2613
+ return identifiers.includes('CASHMANUAL') && method?.enabled !== false && method?.enable !== false;
2766
2614
  });
2767
2615
  }
2768
- getPendingWalletPaymentAmount(payments = ((_b) => (_b = ((_a) => (_a = this.store.order) == null ? void 0 : _a.getOrderPayments)()) == null ? void 0 : _b.call(_a))() || []) {
2616
+ getPendingWalletPaymentAmount(payments = this.store.order?.getOrderPayments?.() || []) {
2769
2617
  return payments.reduce((total, payment) => {
2770
- if ((payment == null ? void 0 : payment.status) !== "payment_pending" || (payment == null ? void 0 : payment.voucher_id) === void 0 || Number(payment.voucher_id) === 0) {
2618
+ if (payment?.status !== 'payment_pending' || payment?.voucher_id === undefined || Number(payment.voucher_id) === 0) {
2771
2619
  return total;
2772
2620
  }
2773
2621
  try {
@@ -2775,26 +2623,22 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2775
2623
  } catch {
2776
2624
  return total;
2777
2625
  }
2778
- }, new import_decimal.default(0));
2626
+ }, new _decimal.default(0));
2779
2627
  }
2628
+
2780
2629
  /** 读取现金 action 所需的支付方式、待付金额和快捷金额。 */
2781
2630
  async getCashPaymentConfig() {
2782
- var _a, _b, _c, _d, _e, _f;
2783
- if (!this.store.payment)
2784
- throw new Error("payment 模块未初始化");
2631
+ if (!this.store.payment) throw new Error('payment 模块未初始化');
2785
2632
  let paymentMethods = this.getPaymentMethods();
2786
2633
  let paymentMethod = this.findCashPaymentMethod(paymentMethods);
2787
2634
  if (!paymentMethod) {
2788
2635
  paymentMethods = await this.getPaymentMethodsAsync();
2789
2636
  paymentMethod = this.findCashPaymentMethod(paymentMethods);
2790
2637
  }
2791
- const amountSnapshot = (_b = (_a = this.store.order) == null ? void 0 : _a.getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2638
+ const amountSnapshot = this.store.order?.getOrderAmountSnapshot?.();
2792
2639
  const pendingWalletAmount = this.getPendingWalletPaymentAmount();
2793
- const amountDue = import_decimal.default.max(
2794
- new import_decimal.default((amountSnapshot == null ? void 0 : amountSnapshot.amountGap) || 0).minus(pendingWalletAmount),
2795
- 0
2796
- ).toDecimalPlaces(2).toNumber();
2797
- const currency = ((_e = (_d = (_c = this.store.order) == null ? void 0 : _c.getTempOrder) == null ? void 0 : _d.call(_c)) == null ? void 0 : _e.currency_code) || ((_f = this.otherParams) == null ? void 0 : _f.currency) || "USD";
2640
+ const amountDue = _decimal.default.max(new _decimal.default(amountSnapshot?.amountGap || 0).minus(pendingWalletAmount), 0).toDecimalPlaces(2).toNumber();
2641
+ const currency = this.store.order?.getTempOrder?.()?.currency_code || this.otherParams?.currency || 'USD';
2798
2642
  const recommendedAmounts = amountDue > 0 ? this.store.payment.cash.getRecommendedAmount(amountDue, currency) : [];
2799
2643
  return {
2800
2644
  available: Boolean(paymentMethod && amountDue > 0),
@@ -2803,6 +2647,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2803
2647
  recommendedAmounts
2804
2648
  };
2805
2649
  }
2650
+
2806
2651
  /**
2807
2652
  * 确认足额覆盖订单的 pending Wallet 支付并提交订单。
2808
2653
  *
@@ -2810,23 +2655,18 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2810
2655
  * 才同步 Wallet committed 状态。失败时恢复调用前 payments,允许用户重试。
2811
2656
  */
2812
2657
  async confirmWalletPayment() {
2813
- var _a, _b, _c, _d, _e;
2814
- if (!this.store.order)
2815
- throw new Error("order 模块未初始化");
2816
- const beforePayments = (0, import_lodash_es.cloneDeep)(this.store.order.getOrderPayments());
2658
+ if (!this.store.order) throw new Error('order 模块未初始化');
2659
+ const beforePayments = (0, _lodashEs.cloneDeep)(this.store.order.getOrderPayments());
2817
2660
  const pendingWalletAmount = this.getPendingWalletPaymentAmount(beforePayments);
2818
2661
  if (pendingWalletAmount.lte(0)) {
2819
- throw new Error("当前订单没有待确认的 Wallet 支付");
2662
+ throw new Error('当前订单没有待确认的 Wallet 支付');
2820
2663
  }
2821
- const amountSnapshot = (_b = (_a = this.store.order).getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2822
- const effectiveAmountDue = import_decimal.default.max(
2823
- new import_decimal.default((amountSnapshot == null ? void 0 : amountSnapshot.amountGap) || 0).minus(pendingWalletAmount),
2824
- 0
2825
- );
2664
+ const amountSnapshot = this.store.order.getOrderAmountSnapshot?.();
2665
+ const effectiveAmountDue = _decimal.default.max(new _decimal.default(amountSnapshot?.amountGap || 0).minus(pendingWalletAmount), 0);
2826
2666
  if (effectiveAmountDue.gt(0.01)) {
2827
- throw new Error("Wallet 支付尚未覆盖全部待支付金额");
2667
+ throw new Error('Wallet 支付尚未覆盖全部待支付金额');
2828
2668
  }
2829
- const beforePaymentStatus = (_c = this.store.order.getTempOrder()) == null ? void 0 : _c.payment_status;
2669
+ const beforePaymentStatus = this.store.order.getTempOrder()?.payment_status;
2830
2670
  let submitResult;
2831
2671
  try {
2832
2672
  submitResult = await this.submitSalesOrder({
@@ -2834,80 +2674,74 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2834
2674
  confirmPendingVoucherPayments: true
2835
2675
  });
2836
2676
  if (isRejectedSalesSubmitResult(submitResult)) {
2837
- throw new Error(
2838
- getSalesSubmitErrorMessage(submitResult, "Wallet 支付确认失败")
2839
- );
2677
+ throw new Error(getSalesSubmitErrorMessage(submitResult, 'Wallet 支付确认失败'));
2840
2678
  }
2841
2679
  } catch (error) {
2842
2680
  this.store.order.setOrderPayments(beforePayments);
2843
2681
  const restoredTempOrder = this.store.order.getTempOrder();
2844
- if (restoredTempOrder && beforePaymentStatus !== void 0) {
2682
+ if (restoredTempOrder && beforePaymentStatus !== undefined) {
2845
2683
  restoredTempOrder.payment_status = beforePaymentStatus;
2846
2684
  this.store.order.persistTempOrder();
2847
2685
  }
2848
- await this.store.order.recalculateSummary({ createIfMissing: true });
2686
+ await this.store.order.recalculateSummary({
2687
+ createIfMissing: true
2688
+ });
2849
2689
  throw error;
2850
2690
  }
2851
2691
  if (this.store.payment) {
2852
2692
  try {
2853
2693
  const committed = this.getCommittedWalletAssets();
2854
- const walletState = this.store.payment.wallet.setCommittedWalletAssets(
2855
- committed.ids,
2856
- committed.assets
2857
- );
2694
+ const walletState = this.store.payment.wallet.setCommittedWalletAssets(committed.ids, committed.assets);
2858
2695
  await this.publishWalletAssetsState(walletState);
2859
2696
  } catch (error) {
2860
- this.logWarning("confirmWalletPayment: Wallet committed 状态同步失败", {
2697
+ this.logWarning('confirmWalletPayment: Wallet committed 状态同步失败', {
2861
2698
  error: error instanceof Error ? error.message : String(error)
2862
2699
  });
2863
2700
  }
2864
2701
  }
2865
- const latestAmountSnapshot = (_e = (_d = this.store.order).getOrderAmountSnapshot) == null ? void 0 : _e.call(_d);
2702
+ const latestAmountSnapshot = this.store.order.getOrderAmountSnapshot?.();
2866
2703
  return {
2867
2704
  submitResult,
2868
2705
  payments: this.store.order.getOrderPayments(),
2869
- isOrderFullyPaid: new import_decimal.default(
2870
- (latestAmountSnapshot == null ? void 0 : latestAmountSnapshot.amountGap) || 0
2871
- ).lte(0)
2706
+ isOrderFullyPaid: new _decimal.default(latestAmountSnapshot?.amountGap || 0).lte(0)
2872
2707
  };
2873
2708
  }
2709
+
2874
2710
  /**
2875
2711
  * 购物车现金直付:写入现金记录并等待支付同步完成。
2876
2712
  * 同步失败会恢复调用前 payments(包含 Wallet pending 状态)。
2877
2713
  */
2878
2714
  async payCash(params) {
2879
- var _a, _b, _c, _d, _e, _f;
2880
- if (!this.store.order)
2881
- throw new Error("order 模块未初始化");
2715
+ if (!this.store.order) throw new Error('order 模块未初始化');
2882
2716
  const amount = Number(params.amount || 0);
2883
2717
  if (!Number.isFinite(amount) || amount <= 0) {
2884
- throw new Error("现金支付金额必须大于 0");
2718
+ throw new Error('现金支付金额必须大于 0');
2885
2719
  }
2886
2720
  const config = await this.getCashPaymentConfig();
2887
2721
  const paymentMethod = config.paymentMethod;
2888
- if (!paymentMethod)
2889
- throw new Error("未找到可用的 CASHMANUAL 支付方式");
2890
- if (config.amountDue <= 0)
2891
- throw new Error("当前订单没有待支付金额");
2722
+ if (!paymentMethod) throw new Error('未找到可用的 CASHMANUAL 支付方式');
2723
+ if (config.amountDue <= 0) throw new Error('当前订单没有待支付金额');
2892
2724
  const roundingAmount = Number(params.roundingAmount || 0);
2893
- const effectivePaymentAmount = new import_decimal.default(amount).minus(roundingAmount);
2894
- if (effectivePaymentAmount.gt(new import_decimal.default(config.amountDue).plus(0.01))) {
2895
- throw new Error("现金支付金额超过当前待支付金额");
2896
- }
2897
- const beforePayments = (0, import_lodash_es.cloneDeep)(this.store.order.getOrderPayments());
2898
- const beforePaymentStatus = (_a = this.store.order.getTempOrder()) == null ? void 0 : _a.payment_status;
2899
- const uniquePaymentNumber = (0, import_utils.createUuidV4)();
2900
- const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
2725
+ const effectivePaymentAmount = new _decimal.default(amount).minus(roundingAmount);
2726
+ if (effectivePaymentAmount.gt(new _decimal.default(config.amountDue).plus(0.01))) {
2727
+ throw new Error('现金支付金额超过当前待支付金额');
2728
+ }
2729
+ const beforePayments = (0, _lodashEs.cloneDeep)(this.store.order.getOrderPayments());
2730
+ const beforePaymentStatus = this.store.order.getTempOrder()?.payment_status;
2731
+ const uniquePaymentNumber = (0, _utils.createUuidV4)();
2732
+ const paymentTimestamp = (0, _dayjs.default)().format('YYYY-MM-DD HH:mm:ss');
2901
2733
  const actualPaidAmount = Number(params.actualPaidAmount ?? amount);
2902
2734
  const changeAmount = Number(params.changeAmount || 0);
2903
- const shopWalletPassId = (_b = this.otherParams) == null ? void 0 : _b.shop_wallet_pass_id;
2735
+ const shopWalletPassId = this.otherParams?.shop_wallet_pass_id;
2904
2736
  if (!Number.isFinite(actualPaidAmount) || actualPaidAmount + 0.01 < amount) {
2905
- throw new Error("顾客实收现金不能小于支付金额");
2737
+ throw new Error('顾客实收现金不能小于支付金额');
2906
2738
  }
2907
- (_f = (_e = (_d = (_c = this.window) == null ? void 0 : _c.interaction) == null ? void 0 : _d.utils) == null ? void 0 : _e.postMessageToApp) == null ? void 0 : _f.call(_e, {
2908
- module: "till",
2909
- key: "open_till",
2910
- data: { type: "cash" }
2739
+ this.window?.interaction?.utils?.postMessageToApp?.({
2740
+ module: 'till',
2741
+ key: 'open_till',
2742
+ data: {
2743
+ type: 'cash'
2744
+ }
2911
2745
  });
2912
2746
  const payments = this.store.order.addOrderPayment({
2913
2747
  amount: amount.toFixed(2),
@@ -2919,19 +2753,16 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2919
2753
  rounding_amount: roundingAmount.toFixed(2),
2920
2754
  metadata: {
2921
2755
  unique_payment_number: uniquePaymentNumber,
2922
- ...shopWalletPassId !== void 0 && shopWalletPassId !== null ? { shop_wallet_pass_id: shopWalletPassId } : {},
2756
+ ...(shopWalletPassId !== undefined && shopWalletPassId !== null ? {
2757
+ shop_wallet_pass_id: shopWalletPassId
2758
+ } : {}),
2923
2759
  actual_paid_amount: Number.isFinite(actualPaidAmount) ? actualPaidAmount : amount,
2924
2760
  change_given_amount: Number.isFinite(changeAmount) ? changeAmount : 0
2925
2761
  },
2926
2762
  payment_time: paymentTimestamp,
2927
2763
  created_at: paymentTimestamp
2928
2764
  });
2929
- const payment = payments.find(
2930
- (item) => {
2931
- var _a2;
2932
- return ((_a2 = item == null ? void 0 : item.metadata) == null ? void 0 : _a2.unique_payment_number) === uniquePaymentNumber;
2933
- }
2934
- );
2765
+ const payment = payments.find(item => item?.metadata?.unique_payment_number === uniquePaymentNumber);
2935
2766
  try {
2936
2767
  const syncResult = await this.syncPaymentsToOrder({
2937
2768
  payments,
@@ -2940,35 +2771,33 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2940
2771
  confirmPendingVoucherPayments: true
2941
2772
  });
2942
2773
  if (isRejectedSalesSubmitResult(syncResult.submitResult)) {
2943
- throw new Error(
2944
- getSalesSubmitErrorMessage(syncResult.submitResult, "订单提交失败")
2945
- );
2774
+ throw new Error(getSalesSubmitErrorMessage(syncResult.submitResult, '订单提交失败'));
2946
2775
  }
2947
2776
  if (this.store.payment) {
2948
2777
  const committed = this.getCommittedWalletAssets();
2949
- const walletState = this.store.payment.wallet.setCommittedWalletAssets(
2950
- committed.ids,
2951
- committed.assets
2952
- );
2778
+ const walletState = this.store.payment.wallet.setCommittedWalletAssets(committed.ids, committed.assets);
2953
2779
  await this.publishWalletAssetsState(walletState);
2954
2780
  }
2955
2781
  return {
2956
2782
  payment: payment || {},
2957
2783
  payments: this.store.order.getOrderPayments(),
2958
- syncResult,
2784
+ syncResult: syncResult,
2959
2785
  isOrderFullyPaid: syncResult.isOrderFullyPaid
2960
2786
  };
2961
2787
  } catch (error) {
2962
2788
  this.store.order.setOrderPayments(beforePayments);
2963
2789
  const restoredTempOrder = this.store.order.getTempOrder();
2964
- if (restoredTempOrder && beforePaymentStatus !== void 0) {
2790
+ if (restoredTempOrder && beforePaymentStatus !== undefined) {
2965
2791
  restoredTempOrder.payment_status = beforePaymentStatus;
2966
2792
  this.store.order.persistTempOrder();
2967
2793
  }
2968
- await this.store.order.recalculateSummary({ createIfMissing: true });
2794
+ await this.store.order.recalculateSummary({
2795
+ createIfMissing: true
2796
+ });
2969
2797
  throw error;
2970
2798
  }
2971
2799
  }
2800
+
2972
2801
  /**
2973
2802
  * 提交一次已由支付设备确认成功的非 Wallet 支付。
2974
2803
  *
@@ -2977,19 +2806,17 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2977
2806
  * 调用前的 payments 与 payment_status,便于 UI 安全解锁并重试。
2978
2807
  */
2979
2808
  async commitPaymentMethodPayment(params) {
2980
- var _a, _b, _c, _d;
2981
- if (!this.store.order)
2982
- throw new Error("order 模块未初始化");
2809
+ if (!this.store.order) throw new Error('order 模块未初始化');
2983
2810
  const amount = Number(params.amount || 0);
2984
2811
  if (!Number.isFinite(amount) || amount <= 0) {
2985
- throw new Error("支付金额必须大于 0");
2812
+ throw new Error('支付金额必须大于 0');
2986
2813
  }
2987
2814
  let paymentMethods = this.getPaymentMethods();
2988
2815
  const findPaymentMethod = () => {
2989
- const methodCode = String(params.paymentMethodCode || "").toUpperCase();
2990
- return paymentMethods.find((method) => {
2991
- const idMatched = params.paymentMethodId !== void 0 && String(method.id) === String(params.paymentMethodId);
2992
- const codeMatched = Boolean(methodCode) && String(method.code || "").toUpperCase() === methodCode;
2816
+ const methodCode = String(params.paymentMethodCode || '').toUpperCase();
2817
+ return paymentMethods.find(method => {
2818
+ const idMatched = params.paymentMethodId !== undefined && String(method.id) === String(params.paymentMethodId);
2819
+ const codeMatched = Boolean(methodCode) && String(method.code || '').toUpperCase() === methodCode;
2993
2820
  return (idMatched || codeMatched) && method.enabled !== false && method.enable !== false;
2994
2821
  });
2995
2822
  };
@@ -2999,54 +2826,49 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2999
2826
  paymentMethod = findPaymentMethod();
3000
2827
  }
3001
2828
  if (!paymentMethod) {
3002
- throw new Error(
3003
- `未找到可用的支付方式:${params.paymentMethodCode || params.paymentMethodId || ""}`
3004
- );
2829
+ throw new Error(`未找到可用的支付方式:${params.paymentMethodCode || params.paymentMethodId || ''}`);
3005
2830
  }
3006
- const amountSnapshot = (_b = (_a = this.store.order).getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2831
+ const amountSnapshot = this.store.order.getOrderAmountSnapshot?.();
3007
2832
  const pendingWalletAmount = this.getPendingWalletPaymentAmount();
3008
- const amountDue = import_decimal.default.max(
3009
- new import_decimal.default((amountSnapshot == null ? void 0 : amountSnapshot.amountGap) || 0).minus(pendingWalletAmount),
3010
- 0
3011
- );
3012
- if (amountDue.lte(0))
3013
- throw new Error("当前订单没有待支付金额");
3014
- if (new import_decimal.default(amount).gt(amountDue.plus(0.01))) {
3015
- throw new Error("支付金额超过当前待支付金额");
3016
- }
3017
- const beforePayments = (0, import_lodash_es.cloneDeep)(this.store.order.getOrderPayments());
3018
- const beforePaymentStatus = (_c = this.store.order.getTempOrder()) == null ? void 0 : _c.payment_status;
3019
- const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
2833
+ const amountDue = _decimal.default.max(new _decimal.default(amountSnapshot?.amountGap || 0).minus(pendingWalletAmount), 0);
2834
+ if (amountDue.lte(0)) throw new Error('当前订单没有待支付金额');
2835
+ if (new _decimal.default(amount).gt(amountDue.plus(0.01))) {
2836
+ throw new Error('支付金额超过当前待支付金额');
2837
+ }
2838
+ const beforePayments = (0, _lodashEs.cloneDeep)(this.store.order.getOrderPayments());
2839
+ const beforePaymentStatus = this.store.order.getTempOrder()?.payment_status;
2840
+ const paymentTimestamp = (0, _dayjs.default)().format('YYYY-MM-DD HH:mm:ss');
3020
2841
  const metadata = {
3021
- ...params.metadata || {},
3022
- unique_payment_number: ((_d = params.metadata) == null ? void 0 : _d.unique_payment_number) || (0, import_utils.createUuidV4)()
2842
+ ...(params.metadata || {}),
2843
+ unique_payment_number: params.metadata?.unique_payment_number || (0, _utils.createUuidV4)()
3023
2844
  };
3024
2845
  const serviceCharge = params.serviceCharge ? {
3025
2846
  amount: String(params.serviceCharge.amount || 0),
3026
2847
  percentage: String(params.serviceCharge.percentage || 0)
3027
- } : void 0;
3028
- const serviceFee = serviceCharge ? new import_decimal.default(params.originAmount ?? amount).times(serviceCharge.percentage || 0).plus(serviceCharge.amount || 0).toDecimalPlaces(2).toFixed(2) : void 0;
2848
+ } : undefined;
2849
+ const serviceFee = serviceCharge ? new _decimal.default(params.originAmount ?? amount).times(serviceCharge.percentage || 0).plus(serviceCharge.amount || 0).toDecimalPlaces(2).toFixed(2) : undefined;
3029
2850
  const payments = this.store.order.addOrderPayment({
3030
- ...params.paymentData || {},
2851
+ ...(params.paymentData || {}),
3031
2852
  amount: amount.toFixed(2),
3032
- ...params.originAmount !== void 0 ? { origin_amount: Number(params.originAmount).toFixed(2) } : {},
2853
+ ...(params.originAmount !== undefined ? {
2854
+ origin_amount: Number(params.originAmount).toFixed(2)
2855
+ } : {}),
3033
2856
  code: paymentMethod.code,
3034
2857
  custom_payment_id: paymentMethod.id,
3035
2858
  name: paymentMethod.name,
3036
2859
  custom_payment_type: paymentMethod.type,
3037
2860
  voucher_id: 0,
3038
- ...serviceCharge ? { service_charge: serviceCharge } : {},
3039
- ...serviceFee !== void 0 ? { service_fee: serviceFee } : {},
2861
+ ...(serviceCharge ? {
2862
+ service_charge: serviceCharge
2863
+ } : {}),
2864
+ ...(serviceFee !== undefined ? {
2865
+ service_fee: serviceFee
2866
+ } : {}),
3040
2867
  metadata,
3041
2868
  payment_time: paymentTimestamp,
3042
2869
  created_at: paymentTimestamp
3043
2870
  });
3044
- const payment = payments.find(
3045
- (item) => {
3046
- var _a2;
3047
- return ((_a2 = item == null ? void 0 : item.metadata) == null ? void 0 : _a2.unique_payment_number) === metadata.unique_payment_number;
3048
- }
3049
- );
2871
+ const payment = payments.find(item => item?.metadata?.unique_payment_number === metadata.unique_payment_number);
3050
2872
  try {
3051
2873
  const syncResult = await this.syncPaymentsToOrder({
3052
2874
  payments,
@@ -3055,35 +2877,33 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3055
2877
  confirmPendingVoucherPayments: true
3056
2878
  });
3057
2879
  if (isRejectedSalesSubmitResult(syncResult.submitResult)) {
3058
- throw new Error(
3059
- getSalesSubmitErrorMessage(syncResult.submitResult, "订单提交失败")
3060
- );
2880
+ throw new Error(getSalesSubmitErrorMessage(syncResult.submitResult, '订单提交失败'));
3061
2881
  }
3062
2882
  if (this.store.payment) {
3063
2883
  const committed = this.getCommittedWalletAssets();
3064
- const walletState = this.store.payment.wallet.setCommittedWalletAssets(
3065
- committed.ids,
3066
- committed.assets
3067
- );
2884
+ const walletState = this.store.payment.wallet.setCommittedWalletAssets(committed.ids, committed.assets);
3068
2885
  await this.publishWalletAssetsState(walletState);
3069
2886
  }
3070
2887
  return {
3071
2888
  payment: payment || {},
3072
2889
  payments: this.store.order.getOrderPayments(),
3073
- syncResult,
2890
+ syncResult: syncResult,
3074
2891
  isOrderFullyPaid: syncResult.isOrderFullyPaid
3075
2892
  };
3076
2893
  } catch (error) {
3077
2894
  this.store.order.setOrderPayments(beforePayments);
3078
2895
  const restoredTempOrder = this.store.order.getTempOrder();
3079
- if (restoredTempOrder && beforePaymentStatus !== void 0) {
2896
+ if (restoredTempOrder && beforePaymentStatus !== undefined) {
3080
2897
  restoredTempOrder.payment_status = beforePaymentStatus;
3081
2898
  this.store.order.persistTempOrder();
3082
2899
  }
3083
- await this.store.order.recalculateSummary({ createIfMissing: true });
2900
+ await this.store.order.recalculateSummary({
2901
+ createIfMissing: true
2902
+ });
3084
2903
  throw error;
3085
2904
  }
3086
2905
  }
2906
+
3087
2907
  /**
3088
2908
  * 按当前店铺的现金舍入配置计算金额,供现金支付 UI 使用。
3089
2909
  *
@@ -3091,27 +2911,21 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3091
2911
  * otherParams.order_rounding_setting,金额算法统一由 PaymentModule 维护。
3092
2912
  */
3093
2913
  async roundAmount(params) {
3094
- var _a, _b, _c;
3095
2914
  const amount = params.amount;
3096
- const cashManualPayment = this.paymentMethodsCache.find(
3097
- (paymentMethod) => paymentMethod.code === "CASHMANUAL"
3098
- );
3099
- if (!((_a = cashManualPayment == null ? void 0 : cashManualPayment.metadata) == null ? void 0 : _a.order_rounding_switch)) {
2915
+ const cashManualPayment = this.paymentMethodsCache.find(paymentMethod => paymentMethod.code === 'CASHMANUAL');
2916
+ if (!cashManualPayment?.metadata?.order_rounding_switch) {
3100
2917
  return {
3101
2918
  originalAmount: amount.toString(),
3102
2919
  roundedAmount: amount.toString(),
3103
- roundingDifference: "0.00"
2920
+ roundingDifference: '0.00'
3104
2921
  };
3105
2922
  }
3106
2923
  if (!this.payment) {
3107
- throw new Error("payment 模块未初始化");
2924
+ throw new Error('payment 模块未初始化');
3108
2925
  }
3109
- return this.payment.roundAmountAsync(
3110
- amount,
3111
- (_b = this.otherParams.order_rounding_setting) == null ? void 0 : _b.interval,
3112
- (_c = this.otherParams.order_rounding_setting) == null ? void 0 : _c.type
3113
- );
2926
+ return this.payment.roundAmountAsync(amount, this.otherParams.order_rounding_setting?.interval, this.otherParams.order_rounding_setting?.type);
3114
2927
  }
2928
+
3115
2929
  /**
3116
2930
  * 发送支付链接。
3117
2931
  *
@@ -3119,17 +2933,15 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3119
2933
  * 只有成功拿到远端 order_id 后才调用 OrderModule 发送邮件。
3120
2934
  */
3121
2935
  async sendCustomerPayLink(params) {
3122
- var _a, _b;
3123
- if (!this.store.order)
3124
- throw new Error("order 模块未初始化");
2936
+ if (!this.store.order) throw new Error('order 模块未初始化');
3125
2937
  let orderIds = params.order_ids || params.orderIds || [];
3126
2938
  if (!orderIds.length || params.submitBeforeSend) {
3127
2939
  const submitResult = await this.submitSalesOrder({
3128
2940
  smallTicketDataFlag: 1
3129
2941
  });
3130
- 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);
2942
+ const orderId = submitResult?.data?.order_id ?? submitResult?.order_id ?? submitResult?.data?.id ?? submitResult?.id;
3131
2943
  if (!orderId) {
3132
- throw new Error("本地订单提交云端失败,无法发送支付链接");
2944
+ throw new Error('本地订单提交云端失败,无法发送支付链接');
3133
2945
  }
3134
2946
  orderIds = [orderId];
3135
2947
  }
@@ -3140,7 +2952,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3140
2952
  });
3141
2953
  }
3142
2954
  transformBaseProductToOrderProduct(params) {
3143
- return (0, import_transformBaseProductToOrderProduct.transformBaseProductToOrderProduct)(params);
2955
+ return (0, _transformBaseProductToOrderProduct.transformBaseProductToOrderProduct)(params);
3144
2956
  }
3145
2957
  async calculateProductBookingPrice(params) {
3146
2958
  const quotation = this.store.quotation;
@@ -3153,36 +2965,34 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3153
2965
  customer_id: customerId,
3154
2966
  channel: params.channel
3155
2967
  });
3156
- return (0, import_quotationPrice.calculateBaseSalesProductBookingPrice)({
2968
+ return (0, _quotationPrice.calculateBaseSalesProductBookingPrice)({
3157
2969
  ...params,
3158
2970
  product,
3159
- fallback_price: authoritativeProduct ? void 0 : params.fallback_price,
2971
+ fallback_price: authoritativeProduct ? undefined : params.fallback_price,
3160
2972
  customer_id: customerId,
3161
- quotation: authoritativeProduct && this.preferAuthoritativeProductQueryPrice() ? void 0 : quotation
2973
+ quotation: authoritativeProduct && this.preferAuthoritativeProductQueryPrice() ? undefined : quotation
3162
2974
  });
3163
2975
  }
3164
2976
  getQuotationCustomerScopeInfo() {
3165
2977
  const quotation = this.store.quotation;
3166
- if (quotation && typeof quotation.getQuotationCustomerScopeInfo === "function") {
2978
+ if (quotation && typeof quotation.getQuotationCustomerScopeInfo === 'function') {
3167
2979
  return quotation.getQuotationCustomerScopeInfo();
3168
2980
  }
3169
- const list = typeof (quotation == null ? void 0 : quotation.getQuotationList) === "function" ? quotation.getQuotationList() : [];
3170
- const customerById = /* @__PURE__ */ new Map();
3171
- const quotationScopes = (Array.isArray(list) ? list : []).filter((item) => Array.isArray(item == null ? void 0 : item.customer) && item.customer.length > 0).map((item) => {
3172
- const localSeen = /* @__PURE__ */ new Set();
3173
- const customers = item.customer.filter((customer) => {
3174
- const customerId = this.normalizePriceContextCustomerId(customer == null ? void 0 : customer.id);
3175
- if (!customerId || localSeen.has(customerId))
3176
- return false;
2981
+ const list = typeof quotation?.getQuotationList === 'function' ? quotation.getQuotationList() : [];
2982
+ const customerById = new Map();
2983
+ const quotationScopes = (Array.isArray(list) ? list : []).filter(item => Array.isArray(item?.customer) && item.customer.length > 0).map(item => {
2984
+ const localSeen = new Set();
2985
+ const customers = item.customer.filter(customer => {
2986
+ const customerId = this.normalizePriceContextCustomerId(customer?.id);
2987
+ if (!customerId || localSeen.has(customerId)) return false;
3177
2988
  localSeen.add(customerId);
3178
- if (!customerById.has(customerId))
3179
- customerById.set(customerId, customer);
2989
+ if (!customerById.has(customerId)) customerById.set(customerId, customer);
3180
2990
  return true;
3181
2991
  });
3182
2992
  return {
3183
2993
  quotationId: item.id,
3184
2994
  quotationName: item.name,
3185
- customerIds: customers.map((customer) => String(customer.id)),
2995
+ customerIds: customers.map(customer => String(customer.id)),
3186
2996
  customers
3187
2997
  };
3188
2998
  });
@@ -3196,9 +3006,8 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3196
3006
  };
3197
3007
  }
3198
3008
  hasSmartPricingStrategies() {
3199
- var _a, _b;
3200
- const evaluator = (_b = (_a = this.core) == null ? void 0 : _a.context) == null ? void 0 : _b.dataVariantEvaluator;
3201
- if (!evaluator || typeof evaluator.getStrategyConfigs !== "function") {
3009
+ const evaluator = this.core?.context?.dataVariantEvaluator;
3010
+ if (!evaluator || typeof evaluator.getStrategyConfigs !== 'function') {
3202
3011
  return false;
3203
3012
  }
3204
3013
  const configs = evaluator.getStrategyConfigs();
@@ -3206,7 +3015,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3206
3015
  }
3207
3016
  shouldRecalculateProductBookingPricesForContextChange(params) {
3208
3017
  const scopeInfo = this.getQuotationCustomerScopeInfo();
3209
- const scopedCustomerIds = new Set(scopeInfo.customerIds.map((id) => String(id)));
3018
+ const scopedCustomerIds = new Set(scopeInfo.customerIds.map(id => String(id)));
3210
3019
  const previousCustomerId = this.normalizePriceContextCustomerId(params.previousCustomerId);
3211
3020
  const nextCustomerId = this.normalizePriceContextCustomerId(params.nextCustomerId);
3212
3021
  if (this.hasSmartPricingStrategies()) {
@@ -3227,78 +3036,73 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3227
3036
  return shouldRecalculate;
3228
3037
  }
3229
3038
  async calculateProductBookingPrices(paramsList) {
3230
- var _a, _b;
3231
- if (!paramsList.length)
3232
- return [];
3039
+ if (!paramsList.length) return [];
3233
3040
  const quotation = this.store.quotation;
3234
- const customerId = ((_a = paramsList[0]) == null ? void 0 : _a.customer_id) ?? this.getCurrentOrderCustomerId();
3041
+ const customerId = paramsList[0]?.customer_id ?? this.getCurrentOrderCustomerId();
3235
3042
  await this.prepareProductPriceQueryContext(customerId);
3236
- const productMapsByGroup = /* @__PURE__ */ new Map();
3237
- const groups = /* @__PURE__ */ new Map();
3238
- paramsList.forEach((params) => {
3239
- var _a2;
3043
+ const productMapsByGroup = new Map();
3044
+ const groups = new Map();
3045
+ paramsList.forEach(params => {
3240
3046
  const product = params.product || {};
3241
3047
  const productId = this.getPriceQueryProductId(product);
3242
- if (productId === null)
3243
- return;
3048
+ if (productId === null) return;
3244
3049
  const schedule = this.getPriceQuerySchedule(params);
3245
- const channel = params.channel || ((_a2 = this.otherParams) == null ? void 0 : _a2.channel);
3246
- const groupKey = [
3247
- schedule.schedule_date,
3248
- schedule.schedule_datetime,
3249
- channel || ""
3250
- ].join("|");
3050
+ const channel = params.channel || this.otherParams?.channel;
3051
+ const groupKey = [schedule.schedule_date, schedule.schedule_datetime, channel || ''].join('|');
3251
3052
  const group = groups.get(groupKey) || {
3252
- ids: /* @__PURE__ */ new Set(),
3053
+ ids: new Set(),
3253
3054
  schedule,
3254
3055
  channel
3255
3056
  };
3256
3057
  group.ids.add(productId);
3257
3058
  groups.set(groupKey, group);
3258
3059
  });
3259
- await Promise.all(
3260
- Array.from(groups.entries()).map(async ([groupKey, group]) => {
3261
- const productsById = await this.loadProductsForPriceQuery({
3262
- ids: Array.from(group.ids),
3263
- schedule: group.schedule,
3264
- customerId,
3265
- channel: group.channel
3266
- });
3267
- productMapsByGroup.set(groupKey, productsById);
3268
- })
3269
- );
3060
+ await Promise.all(Array.from(groups.entries()).map(async ([groupKey, group]) => {
3061
+ const productsById = await this.loadProductsForPriceQuery({
3062
+ ids: Array.from(group.ids),
3063
+ schedule: group.schedule,
3064
+ customerId,
3065
+ channel: group.channel
3066
+ });
3067
+ productMapsByGroup.set(groupKey, productsById);
3068
+ }));
3270
3069
  await this.loadQuotationForPriceQuery({
3271
3070
  quotation,
3272
3071
  customer_id: customerId,
3273
- channel: (_b = paramsList[0]) == null ? void 0 : _b.channel
3072
+ channel: paramsList[0]?.channel
3274
3073
  });
3275
- return paramsList.map((params) => {
3276
- var _a2, _b2;
3074
+ return paramsList.map(params => {
3277
3075
  const productInput = params.product || {};
3278
3076
  const productId = this.getPriceQueryProductId(productInput);
3279
3077
  const schedule = this.getPriceQuerySchedule(params);
3280
- const channel = params.channel || ((_a2 = this.otherParams) == null ? void 0 : _a2.channel);
3281
- const groupKey = [
3282
- schedule.schedule_date,
3283
- schedule.schedule_datetime,
3284
- channel || ""
3285
- ].join("|");
3286
- const authoritativeProduct = productId === null ? null : ((_b2 = productMapsByGroup.get(groupKey)) == null ? void 0 : _b2.get(productId)) || null;
3078
+ const channel = params.channel || this.otherParams?.channel;
3079
+ const groupKey = [schedule.schedule_date, schedule.schedule_datetime, channel || ''].join('|');
3080
+ const authoritativeProduct = productId === null ? null : productMapsByGroup.get(groupKey)?.get(productId) || null;
3287
3081
  const product = this.mergeProductForPriceQuery(productInput, authoritativeProduct);
3288
- return (0, import_quotationPrice.calculateBaseSalesProductBookingPrice)({
3082
+ return (0, _quotationPrice.calculateBaseSalesProductBookingPrice)({
3289
3083
  ...params,
3290
3084
  product,
3291
- fallback_price: authoritativeProduct ? void 0 : params.fallback_price,
3085
+ fallback_price: authoritativeProduct ? undefined : params.fallback_price,
3292
3086
  customer_id: customerId,
3293
- quotation: authoritativeProduct && this.preferAuthoritativeProductQueryPrice() ? void 0 : quotation
3087
+ quotation: authoritativeProduct && this.preferAuthoritativeProductQueryPrice() ? undefined : quotation
3294
3088
  });
3295
3089
  });
3296
3090
  }
3297
3091
  async addProductToOrder(product, booking, options) {
3298
3092
  try {
3299
- if (!this.store.order)
3300
- throw new Error("order 模块未初始化");
3093
+ if (!this.store.order) throw new Error('order 模块未初始化');
3301
3094
  const products = await this.store.order.addProductToOrder(product, booking, options);
3095
+ // // 需要叠加
3096
+ // if (this.hooks.onAddProductOverlay) {
3097
+ // const res = this.hooks.onAddProductOverlay(是否叠加, product)
3098
+ // if (!res) {
3099
+ // 单独添加商品
3100
+ // } else {
3101
+ // 叠加
3102
+ // }
3103
+ // } else {
3104
+ // 叠加
3105
+ // }
3302
3106
  return products;
3303
3107
  } catch (error) {
3304
3108
  throw error;
@@ -3306,8 +3110,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3306
3110
  }
3307
3111
  async updateOrderProduct(params) {
3308
3112
  try {
3309
- if (!this.store.order)
3310
- throw new Error("order 模块未初始化");
3113
+ if (!this.store.order) throw new Error('order 模块未初始化');
3311
3114
  const products = await this.store.order.updateOrderProduct(params);
3312
3115
  return products;
3313
3116
  } catch (error) {
@@ -3316,8 +3119,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3316
3119
  }
3317
3120
  async updateOrderProducts(paramsList) {
3318
3121
  try {
3319
- if (!this.store.order)
3320
- throw new Error("order 模块未初始化");
3122
+ if (!this.store.order) throw new Error('order 模块未初始化');
3321
3123
  const products = await this.store.order.updateOrderProducts(paramsList);
3322
3124
  return products;
3323
3125
  } catch (error) {
@@ -3326,8 +3128,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3326
3128
  }
3327
3129
  async updateOrderProductQuantity(params) {
3328
3130
  try {
3329
- if (!this.store.order)
3330
- throw new Error("order 模块未初始化");
3131
+ if (!this.store.order) throw new Error('order 模块未初始化');
3331
3132
  const products = await this.store.order.updateOrderProductQuantity(params);
3332
3133
  return products;
3333
3134
  } catch (error) {
@@ -3336,13 +3137,13 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3336
3137
  }
3337
3138
  updateOrderBooking(params) {
3338
3139
  try {
3339
- if (!this.store.order)
3340
- throw new Error("order 模块未初始化");
3140
+ if (!this.store.order) throw new Error('order 模块未初始化');
3341
3141
  return this.store.order.updateOrderBooking(params);
3342
3142
  } catch (error) {
3343
3143
  throw error;
3344
3144
  }
3345
3145
  }
3146
+
3346
3147
  /**
3347
3148
  * 设置单行商品备注(与整单 `updateTempOrderNote` 区分)。
3348
3149
  * 多行同 SKU 时必须传入与删除/更新一致的 unique_identification_number。
@@ -3352,22 +3153,24 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3352
3153
  const params = {
3353
3154
  product_id: identity.product_id,
3354
3155
  product_variant_id: identity.product_variant_id,
3355
- updates: { note: String(note || "") }
3156
+ updates: {
3157
+ note: String(note || '')
3158
+ }
3356
3159
  };
3357
- if (identity.unique_identification_number !== void 0) {
3160
+ if (identity.unique_identification_number !== undefined) {
3358
3161
  params.unique_identification_number = identity.unique_identification_number;
3359
3162
  }
3360
- if (identity.product_sku !== void 0) {
3163
+ if (identity.product_sku !== undefined) {
3361
3164
  params.product_sku = identity.product_sku;
3362
3165
  }
3363
- if (identity.product_bundle !== void 0)
3364
- params.product_bundle = identity.product_bundle;
3166
+ if (identity.product_bundle !== undefined) params.product_bundle = identity.product_bundle;
3365
3167
  const products = await this.updateOrderProduct(params);
3366
3168
  return products;
3367
3169
  } catch (error) {
3368
3170
  throw error;
3369
3171
  }
3370
3172
  }
3173
+
3371
3174
  /**
3372
3175
  * 批量删除购物车行,末尾仅一次促销重算。
3373
3176
  *
@@ -3376,8 +3179,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3376
3179
  */
3377
3180
  async removeProductsFromOrder(identities, options) {
3378
3181
  try {
3379
- if (!this.store.order)
3380
- throw new Error("order 模块未初始化");
3182
+ if (!this.store.order) throw new Error('order 模块未初始化');
3381
3183
  return await this.store.order.removeProductsFromOrder(identities, options);
3382
3184
  } catch (error) {
3383
3185
  throw error;
@@ -3386,7 +3188,9 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3386
3188
  async removeProductFromOrder(identity, options) {
3387
3189
  return this.removeProductsFromOrder([identity], options);
3388
3190
  }
3191
+
3389
3192
  // ─── 促销/赠品 透传(迁移自 booking usePromotion) ────────────────
3193
+
3390
3194
  /**
3391
3195
  * 注入促销评估器到底层 OrderModule。
3392
3196
  *
@@ -3394,10 +3198,10 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3394
3198
  * solution.setPromotionEvaluator(appHelper.utils.promotionEvaluator);
3395
3199
  */
3396
3200
  setPromotionEvaluator(evaluator) {
3397
- if (!this.store.order)
3398
- throw new Error("order 模块未初始化");
3201
+ if (!this.store.order) throw new Error('order 模块未初始化');
3399
3202
  this.store.order.setPromotionEvaluator(evaluator);
3400
3203
  }
3204
+
3401
3205
  /**
3402
3206
  * 注入赠品选择 resolver。UI 层(SalesSdk)通过 bridge 提供。
3403
3207
  *
@@ -3405,10 +3209,10 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3405
3209
  * solution.setGiftSelectResolver(async (ctx) => bridge.request(ctx));
3406
3210
  */
3407
3211
  setGiftSelectResolver(resolver) {
3408
- if (!this.store.order)
3409
- throw new Error("order 模块未初始化");
3212
+ if (!this.store.order) throw new Error('order 模块未初始化');
3410
3213
  this.store.order.setGiftSelectResolver(resolver);
3411
3214
  }
3215
+
3412
3216
  /**
3413
3217
  * 为商品目录追加促销标签,供 SalesSdkProductProvider 等商品列表入口复用。
3414
3218
  *
@@ -3416,40 +3220,40 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3416
3220
  * const products = solution.appendPromotionTags(catalogProducts);
3417
3221
  */
3418
3222
  appendPromotionTags(products) {
3419
- if (!this.store.order)
3420
- throw new Error("order 模块未初始化");
3223
+ if (!this.store.order) throw new Error('order 模块未初始化');
3421
3224
  return this.store.order.appendPromotionTags(products);
3422
3225
  }
3226
+
3423
3227
  /**
3424
3228
  * 主动触发一次促销应用(一般写路径会自动触发,少数场景如客户切换后可手动调)。
3425
3229
  */
3426
3230
  async applyPromotion() {
3427
- if (!this.store.order)
3428
- throw new Error("order 模块未初始化");
3231
+ if (!this.store.order) throw new Error('order 模块未初始化');
3429
3232
  await this.store.order.applyPromotion();
3430
3233
  }
3234
+
3431
3235
  /** 最近一次促销计算输出的未满足提示。 */
3432
3236
  getUnfulfilledPromotions() {
3433
- var _a;
3434
- return ((_a = this.store.order) == null ? void 0 : _a.getUnfulfilledPromotions()) || [];
3237
+ return this.store.order?.getUnfulfilledPromotions() || [];
3435
3238
  }
3239
+
3436
3240
  /** 最近一次促销计算输出的赠品操作 diff。 */
3437
3241
  getLastGiftActions() {
3438
- var _a;
3439
- return ((_a = this.store.order) == null ? void 0 : _a.getLastGiftActions()) || null;
3242
+ return this.store.order?.getLastGiftActions() || null;
3440
3243
  }
3244
+
3441
3245
  // 获取商品列表
3442
3246
  // TODO 需要跟 webpos 内的对齐一下
3443
3247
  async getProductList() {
3444
- var _a, _b, _c;
3445
- 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))) || [];
3248
+ // 可以直接通过配置里的 menu 读取
3249
+ const menu_list_ids = this.otherParams?.dineInConfig?.['menu.associated_menus'].map(n => Number(n.value)) || [];
3446
3250
  try {
3447
- const res = await ((_c = this.store.products) == null ? void 0 : _c.loadProducts({
3251
+ const res = await this.store.products?.loadProducts({
3448
3252
  menu_list_ids,
3449
3253
  cacheId: this.cacheId,
3450
- schedule_date: (0, import_dayjs.default)().format("YYYY-MM-DD"),
3451
- schedule_datetime: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
3452
- }));
3254
+ schedule_date: (0, _dayjs.default)().format('YYYY-MM-DD'),
3255
+ schedule_datetime: (0, _dayjs.default)().format('YYYY-MM-DD HH:mm:ss')
3256
+ });
3453
3257
  return res;
3454
3258
  } catch (error) {
3455
3259
  throw error;
@@ -3458,19 +3262,23 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
3458
3262
  getOtherParams() {
3459
3263
  return this.otherParams;
3460
3264
  }
3461
- async setOtherParams(params, { cover = false } = {}) {
3462
- var _a;
3265
+ async setOtherParams(params, {
3266
+ cover = false
3267
+ } = {}) {
3463
3268
  if (cover) {
3464
- this.otherParams = { ...params };
3269
+ this.otherParams = {
3270
+ ...params
3271
+ };
3465
3272
  } else {
3466
- this.otherParams = { ...this.otherParams, ...params };
3273
+ this.otherParams = {
3274
+ ...this.otherParams,
3275
+ ...params
3276
+ };
3467
3277
  }
3468
- this.cacheId = (_a = this.otherParams) == null ? void 0 : _a.cacheId;
3469
- await this.syncOtherParamsToSubModules(params, { cover });
3278
+ this.cacheId = this.otherParams?.cacheId;
3279
+ await this.syncOtherParamsToSubModules(params, {
3280
+ cover
3281
+ });
3470
3282
  }
3471
- };
3472
- // Annotate the CommonJS export names for ESM import in node:
3473
- 0 && (module.exports = {
3474
- BaseSalesImpl,
3475
- ...require("./types")
3476
- });
3283
+ }
3284
+ exports.BaseSalesImpl = BaseSalesImpl;