@pisell/pisellos 2.3.74 → 2.3.75

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