@pisell/pisellos 2.3.39 → 2.3.41

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 (226) hide show
  1. package/dist/core/index.d.ts +2 -0
  2. package/dist/core/index.js +7 -0
  3. package/dist/model/strategy/adapter/promotion/adapter.d.ts +4 -0
  4. package/dist/model/strategy/adapter/promotion/adapter.js +23 -0
  5. package/dist/model/strategy/adapter/promotion/evaluator.d.ts +17 -0
  6. package/dist/model/strategy/adapter/promotion/evaluator.js +279 -6
  7. package/dist/model/strategy/adapter/promotion/examples.d.ts +86 -0
  8. package/dist/model/strategy/adapter/promotion/examples.js +99 -0
  9. package/dist/model/strategy/adapter/promotion/index.d.ts +1 -1
  10. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  11. package/dist/model/strategy/adapter/promotion/type.d.ts +90 -2
  12. package/dist/model/strategy/adapter/promotion/type.js +45 -0
  13. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +5 -3
  14. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +6 -3
  15. package/dist/modules/Discount/index.d.ts +0 -1
  16. package/dist/modules/Discount/index.js +11 -40
  17. package/dist/modules/Discount/types.d.ts +0 -1
  18. package/dist/modules/OpenData/index.d.ts +2 -0
  19. package/dist/modules/OpenData/index.js +10 -2
  20. package/dist/modules/Order/index.d.ts +29 -12
  21. package/dist/modules/Order/index.js +750 -509
  22. package/dist/modules/Order/payment-utils.d.ts +26 -0
  23. package/dist/modules/Order/payment-utils.js +225 -0
  24. package/dist/modules/Order/types.d.ts +33 -10
  25. package/dist/modules/Order/utils/orderCollectionIdentity.js +7 -2
  26. package/dist/modules/Order/utils.d.ts +0 -10
  27. package/dist/modules/Order/utils.js +13 -41
  28. package/dist/modules/Payment/index.d.ts +2 -0
  29. package/dist/modules/Payment/index.js +79 -50
  30. package/dist/modules/Payment/types.d.ts +99 -28
  31. package/dist/modules/Payment/types.js +20 -3
  32. package/dist/modules/Payment/walletpass.d.ts +25 -1
  33. package/dist/modules/Payment/walletpass.js +707 -157
  34. package/dist/modules/Product/types.d.ts +0 -1
  35. package/dist/modules/ProductList/index.js +14 -33
  36. package/dist/modules/Quotation/index.d.ts +1 -1
  37. package/dist/modules/Quotation/index.js +2 -2
  38. package/dist/modules/Rules/index.d.ts +1 -0
  39. package/dist/modules/Rules/index.js +89 -96
  40. package/dist/modules/SalesSummary/index.js +13 -12
  41. package/dist/modules/ScanOrderLogger/index.d.ts +0 -2
  42. package/dist/modules/ScanOrderLogger/index.js +2 -15
  43. package/dist/modules/ScanOrderLogger/providers/feishu.js +27 -45
  44. package/dist/modules/ScanOrderLogger/types.d.ts +0 -1
  45. package/dist/modules/Schedule/index.d.ts +1 -3
  46. package/dist/modules/Schedule/index.js +16 -21
  47. package/dist/modules/Summary/utils.js +13 -38
  48. package/dist/modules/index.d.ts +0 -2
  49. package/dist/modules/index.js +1 -3
  50. package/dist/plugins/window.d.ts +0 -1
  51. package/dist/server/index.d.ts +16 -14
  52. package/dist/server/index.js +1925 -1143
  53. package/dist/server/modules/order/index.d.ts +54 -4
  54. package/dist/server/modules/order/index.js +1600 -700
  55. package/dist/server/modules/order/types.d.ts +11 -3
  56. package/dist/server/modules/order/types.js +1 -1
  57. package/dist/solution/BaseSales/index.d.ts +109 -20
  58. package/dist/solution/BaseSales/index.js +1800 -480
  59. package/dist/solution/BaseSales/types.d.ts +52 -0
  60. package/dist/solution/BaseSales/types.js +2 -1
  61. package/dist/solution/BaseSales/utils/cartPromotion.d.ts +3 -1
  62. package/dist/solution/BaseSales/utils/cartPromotion.js +90 -31
  63. package/dist/solution/BaseSales/utils/parseSalesResponse.d.ts +6 -1
  64. package/dist/solution/BookingByStep/index.d.ts +2 -17
  65. package/dist/solution/BookingByStep/index.js +215 -294
  66. package/dist/solution/BookingByStep/types.d.ts +1 -2
  67. package/dist/solution/BookingByStep/types.js +1 -3
  68. package/dist/solution/BookingByStep/utils/capacity.js +1 -17
  69. package/dist/solution/BookingByStep/utils/timeslots.d.ts +1 -3
  70. package/dist/solution/BookingByStep/utils/timeslots.js +12 -19
  71. package/dist/solution/BookingTicket/index.d.ts +7 -3
  72. package/dist/solution/BookingTicket/index.js +132 -49
  73. package/dist/solution/BookingTicket/utils/addProductDecision.js +6 -0
  74. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +8 -0
  75. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +172 -82
  76. package/dist/solution/BookingTicket/utils/weighingProductSku.d.ts +5 -0
  77. package/dist/solution/BookingTicket/utils/weighingProductSku.js +45 -0
  78. package/dist/solution/Sales/index.d.ts +1 -0
  79. package/dist/solution/Sales/index.js +10 -2
  80. package/dist/solution/ScanOrder/index.d.ts +14 -26
  81. package/dist/solution/ScanOrder/index.js +756 -1148
  82. package/dist/solution/ScanOrder/types.d.ts +1 -21
  83. package/dist/solution/ScanOrder/utils.d.ts +0 -8
  84. package/dist/solution/ScanOrder/utils.js +25 -66
  85. package/dist/solution/ShopDiscount/index.d.ts +0 -1
  86. package/dist/solution/ShopDiscount/index.js +87 -125
  87. package/dist/solution/VenueBooking/index.d.ts +11 -39
  88. package/dist/solution/VenueBooking/index.js +860 -1176
  89. package/dist/solution/VenueBooking/types.d.ts +0 -3
  90. package/dist/solution/VenueBooking/utils/resource.js +0 -1
  91. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +4 -4
  92. package/dist/solution/VenueBooking/utils/slotMerge.js +5 -10
  93. package/dist/solution/index.d.ts +0 -1
  94. package/dist/solution/index.js +1 -2
  95. package/dist/types/index.d.ts +1 -1
  96. package/dist/utils/payment-number.d.ts +9 -0
  97. package/dist/utils/payment-number.js +69 -0
  98. package/lib/core/index.d.ts +2 -0
  99. package/lib/core/index.js +4 -0
  100. package/lib/model/strategy/adapter/promotion/adapter.d.ts +4 -0
  101. package/lib/model/strategy/adapter/promotion/adapter.js +20 -0
  102. package/lib/model/strategy/adapter/promotion/evaluator.d.ts +17 -0
  103. package/lib/model/strategy/adapter/promotion/evaluator.js +235 -0
  104. package/lib/model/strategy/adapter/promotion/examples.d.ts +86 -0
  105. package/lib/model/strategy/adapter/promotion/examples.js +91 -0
  106. package/lib/model/strategy/adapter/promotion/index.d.ts +1 -1
  107. package/lib/model/strategy/adapter/promotion/index.js +51 -0
  108. package/lib/model/strategy/adapter/promotion/type.d.ts +90 -2
  109. package/lib/model/strategy/adapter/promotion/type.js +2 -0
  110. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +2 -1
  111. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +2 -1
  112. package/lib/modules/Discount/index.d.ts +0 -1
  113. package/lib/modules/Discount/index.js +0 -9
  114. package/lib/modules/Discount/types.d.ts +0 -1
  115. package/lib/modules/OpenData/index.d.ts +2 -0
  116. package/lib/modules/OpenData/index.js +6 -1
  117. package/lib/modules/Order/index.d.ts +29 -12
  118. package/lib/modules/Order/index.js +196 -86
  119. package/lib/modules/Order/payment-utils.d.ts +26 -0
  120. package/lib/modules/Order/payment-utils.js +224 -0
  121. package/lib/modules/Order/types.d.ts +33 -10
  122. package/lib/modules/Order/utils/orderCollectionIdentity.js +3 -0
  123. package/lib/modules/Order/utils.d.ts +0 -10
  124. package/lib/modules/Order/utils.js +16 -40
  125. package/lib/modules/Payment/index.d.ts +2 -0
  126. package/lib/modules/Payment/index.js +34 -13
  127. package/lib/modules/Payment/types.d.ts +99 -28
  128. package/lib/modules/Payment/types.js +4 -3
  129. package/lib/modules/Payment/walletpass.d.ts +25 -1
  130. package/lib/modules/Payment/walletpass.js +470 -21
  131. package/lib/modules/Product/types.d.ts +0 -1
  132. package/lib/modules/ProductList/index.js +31 -40
  133. package/lib/modules/Quotation/index.d.ts +1 -1
  134. package/lib/modules/Quotation/index.js +2 -2
  135. package/lib/modules/Rules/index.d.ts +1 -0
  136. package/lib/modules/Rules/index.js +47 -40
  137. package/lib/modules/SalesSummary/index.js +7 -6
  138. package/lib/modules/ScanOrderLogger/index.d.ts +0 -2
  139. package/lib/modules/ScanOrderLogger/index.js +1 -13
  140. package/lib/modules/ScanOrderLogger/providers/feishu.js +6 -15
  141. package/lib/modules/ScanOrderLogger/types.d.ts +0 -1
  142. package/lib/modules/Schedule/index.d.ts +1 -3
  143. package/lib/modules/Schedule/index.js +8 -10
  144. package/lib/modules/Summary/utils.js +1 -21
  145. package/lib/modules/index.d.ts +0 -2
  146. package/lib/modules/index.js +1 -5
  147. package/lib/plugins/window.d.ts +0 -1
  148. package/lib/server/index.d.ts +16 -14
  149. package/lib/server/index.js +675 -83
  150. package/lib/server/modules/order/index.d.ts +54 -4
  151. package/lib/server/modules/order/index.js +679 -66
  152. package/lib/server/modules/order/types.d.ts +11 -3
  153. package/lib/solution/BaseSales/index.d.ts +109 -20
  154. package/lib/solution/BaseSales/index.js +883 -70
  155. package/lib/solution/BaseSales/types.d.ts +52 -0
  156. package/lib/solution/BaseSales/types.js +2 -1
  157. package/lib/solution/BaseSales/utils/cartPromotion.d.ts +3 -1
  158. package/lib/solution/BaseSales/utils/cartPromotion.js +63 -12
  159. package/lib/solution/BaseSales/utils/parseSalesResponse.d.ts +6 -1
  160. package/lib/solution/BookingByStep/index.d.ts +2 -17
  161. package/lib/solution/BookingByStep/index.js +18 -60
  162. package/lib/solution/BookingByStep/types.d.ts +1 -2
  163. package/lib/solution/BookingByStep/types.js +0 -5
  164. package/lib/solution/BookingByStep/utils/capacity.js +1 -20
  165. package/lib/solution/BookingByStep/utils/timeslots.d.ts +1 -3
  166. package/lib/solution/BookingByStep/utils/timeslots.js +11 -19
  167. package/lib/solution/BookingTicket/index.d.ts +7 -3
  168. package/lib/solution/BookingTicket/index.js +62 -9
  169. package/lib/solution/BookingTicket/utils/addProductDecision.js +4 -0
  170. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +8 -0
  171. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +36 -4
  172. package/lib/solution/BookingTicket/utils/weighingProductSku.d.ts +5 -0
  173. package/lib/solution/BookingTicket/utils/weighingProductSku.js +63 -0
  174. package/lib/solution/Sales/index.d.ts +1 -0
  175. package/lib/solution/Sales/index.js +5 -3
  176. package/lib/solution/ScanOrder/index.d.ts +14 -26
  177. package/lib/solution/ScanOrder/index.js +190 -449
  178. package/lib/solution/ScanOrder/types.d.ts +1 -21
  179. package/lib/solution/ScanOrder/utils.d.ts +0 -8
  180. package/lib/solution/ScanOrder/utils.js +0 -31
  181. package/lib/solution/ShopDiscount/index.d.ts +0 -1
  182. package/lib/solution/ShopDiscount/index.js +0 -14
  183. package/lib/solution/VenueBooking/index.d.ts +11 -39
  184. package/lib/solution/VenueBooking/index.js +123 -328
  185. package/lib/solution/VenueBooking/types.d.ts +0 -3
  186. package/lib/solution/VenueBooking/utils/resource.js +0 -1
  187. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +4 -4
  188. package/lib/solution/VenueBooking/utils/slotMerge.js +4 -6
  189. package/lib/solution/index.d.ts +0 -1
  190. package/lib/solution/index.js +1 -3
  191. package/lib/types/index.d.ts +1 -1
  192. package/lib/utils/payment-number.d.ts +9 -0
  193. package/lib/utils/payment-number.js +64 -0
  194. package/package.json +1 -1
  195. package/dist/modules/Holder/index.d.ts +0 -48
  196. package/dist/modules/Holder/index.js +0 -640
  197. package/dist/modules/Holder/types.d.ts +0 -123
  198. package/dist/modules/Holder/types.js +0 -1
  199. package/dist/modules/Holder/utils.d.ts +0 -13
  200. package/dist/modules/Holder/utils.js +0 -34
  201. package/dist/modules/ResourcePlanner/index.d.ts +0 -24
  202. package/dist/modules/ResourcePlanner/index.js +0 -181
  203. package/dist/modules/ResourcePlanner/planner.d.ts +0 -14
  204. package/dist/modules/ResourcePlanner/planner.js +0 -1069
  205. package/dist/modules/ResourcePlanner/types.d.ts +0 -227
  206. package/dist/modules/ResourcePlanner/types.js +0 -1
  207. package/dist/solution/UnifiedBookingSales/index.d.ts +0 -183
  208. package/dist/solution/UnifiedBookingSales/index.js +0 -1871
  209. package/dist/solution/UnifiedBookingSales/types.d.ts +0 -143
  210. package/dist/solution/UnifiedBookingSales/types.js +0 -11
  211. package/lib/modules/Holder/index.d.ts +0 -48
  212. package/lib/modules/Holder/index.js +0 -402
  213. package/lib/modules/Holder/types.d.ts +0 -123
  214. package/lib/modules/Holder/types.js +0 -17
  215. package/lib/modules/Holder/utils.d.ts +0 -13
  216. package/lib/modules/Holder/utils.js +0 -71
  217. package/lib/modules/ResourcePlanner/index.d.ts +0 -24
  218. package/lib/modules/ResourcePlanner/index.js +0 -148
  219. package/lib/modules/ResourcePlanner/planner.d.ts +0 -14
  220. package/lib/modules/ResourcePlanner/planner.js +0 -933
  221. package/lib/modules/ResourcePlanner/types.d.ts +0 -227
  222. package/lib/modules/ResourcePlanner/types.js +0 -17
  223. package/lib/solution/UnifiedBookingSales/index.d.ts +0 -183
  224. package/lib/solution/UnifiedBookingSales/index.js +0 -1076
  225. package/lib/solution/UnifiedBookingSales/types.d.ts +0 -143
  226. package/lib/solution/UnifiedBookingSales/types.js +0 -33
@@ -40,6 +40,8 @@ var import_decimal = __toESM(require("decimal.js"));
40
40
  var import_lodash_es = require("lodash-es");
41
41
  var import_types2 = require("../BookingByStep/types");
42
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");
43
45
  var import_orderCollectionIdentity = require("../../modules/Order/utils/orderCollectionIdentity");
44
46
  var import_dayjs = __toESM(require("dayjs"));
45
47
  __reExport(BaseSales_exports, require("./types"), module.exports);
@@ -47,6 +49,88 @@ var import_Quotation = require("../../modules/Quotation");
47
49
  var import_transformBaseProductToOrderProduct = require("./utils/transformBaseProductToOrderProduct");
48
50
  var import_quotationPrice = require("./utils/quotationPrice");
49
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"
56
+ };
57
+ function getSharedWalletAssetId(asset) {
58
+ return (asset == null ? void 0 : asset.id) ?? (asset == null ? void 0 : asset.voucher_id) ?? (asset == null ? void 0 : asset.code);
59
+ }
60
+ 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;
62
+ const amount = Number(value);
63
+ return Number.isFinite(amount) && amount > 0 ? amount : 0;
64
+ }
65
+ 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
+ const responseCode = Number(candidate.code ?? candidate.statusCode);
77
+ if (Number.isFinite(responseCode) && responseCode >= 400)
78
+ return true;
79
+ if (candidate.status === false || candidate.success === false || candidate.result === false) {
80
+ return true;
81
+ }
82
+ return ["failed", "error"].includes(
83
+ String(candidate.status || "").toLowerCase()
84
+ );
85
+ });
86
+ }
87
+ function getSalesSubmitErrorMessage(result) {
88
+ var _a, _b;
89
+ 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) || "Wallet 支付确认失败";
90
+ }
91
+ function toWalletFundValue(value) {
92
+ try {
93
+ return new import_decimal.default(value || 0).toDecimalPlaces(2).toFixed(2);
94
+ } catch {
95
+ return "0.00";
96
+ }
97
+ }
98
+ function subtractWalletFundValue(left, right) {
99
+ try {
100
+ return new import_decimal.default(left || 0).minus(right || 0).toDecimalPlaces(2).toFixed(2);
101
+ } catch {
102
+ return "0.00";
103
+ }
104
+ }
105
+ function getSharedWalletPassUseValue(params) {
106
+ const { asset, amount, paymentMethod } = params;
107
+ const configuredValue = Number(asset == null ? void 0 : asset.wallet_pass_use_value);
108
+ if (Number.isFinite(configuredValue) && configuredValue > 0) {
109
+ return configuredValue;
110
+ }
111
+ const isPointCard = (asset == null ? void 0 : asset.tag) === "point_card" || paymentMethod.code === "POINTCARD";
112
+ const usageUnit = asset == null ? void 0 : asset.wallet_pass_usage_unit;
113
+ if (isPointCard && (usageUnit == null ? void 0 : usageUnit.points) && (usageUnit == null ? void 0 : usageUnit.price)) {
114
+ return new import_decimal.default(amount).div(usageUnit.price).mul(usageUnit.points).toDecimalPlaces(2, import_decimal.default.ROUND_DOWN).toNumber();
115
+ }
116
+ return amount;
117
+ }
118
+ function buildSharedWalletFundRecord(params) {
119
+ const { asset, amount, paymentMethod } = params;
120
+ const isPointCard = (asset == null ? void 0 : asset.tag) === "point_card" || paymentMethod.code === "POINTCARD";
121
+ 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;
122
+ const walletPassUseValue = getSharedWalletPassUseValue(params);
123
+ const usingValue = isPointCard ? walletPassUseValue : amount;
124
+ 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;
125
+ return {
126
+ voucher_id: (asset == null ? void 0 : asset.voucher_id) ?? (asset == null ? void 0 : asset.id),
127
+ wallet_pass_name: walletPassName && typeof walletPassName === "object" ? walletPassName : { default: walletPassName || "" },
128
+ code: (asset == null ? void 0 : asset.code) || (asset == null ? void 0 : asset.tag),
129
+ encoded: asset == null ? void 0 : asset.encoded,
130
+ using_before_value: toWalletFundValue(usingBeforeValue),
131
+ using_after_value: subtractWalletFundValue(usingBeforeValue, usingValue)
132
+ };
133
+ }
50
134
  function isBaseSalesManualProductDiscountProduct(product) {
51
135
  var _a, _b;
52
136
  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");
@@ -77,6 +161,11 @@ function isBaseSalesHistoricalDiscountEntry(discount) {
77
161
  (discount == null ? void 0 : discount.isEditMode) || (discount == null ? void 0 : discount.isDisabled) || (discount == null ? void 0 : discount.order_discount_id) != null
78
162
  );
79
163
  }
164
+ function getBaseSalesUniqueArrayMetadataKey(key) {
165
+ if (key === "products" || key === "bookings")
166
+ return "unique_identification_number";
167
+ return null;
168
+ }
80
169
  var BASE_SALES_PERSISTENT_ID_FIELD_BY_KIND = {
81
170
  product: "order_detail_id",
82
171
  booking: "schedule_event_id",
@@ -150,6 +239,15 @@ function mergeBaseSalesCollectionItem(kind, currentItem, incomingItem, uidRemaps
150
239
  return kind === "product" ? mergeBaseSalesProductSnapshotFields(currentItem, mergedItem) : mergedItem;
151
240
  }
152
241
  function mergeBaseSalesOrderCollection(kind, currentValue, incomingValue, strategy, uidRemaps) {
242
+ if (kind === "payment") {
243
+ return (0, import_payment_utils.mergeOrderPaymentListsByIdentity)(
244
+ currentValue,
245
+ incomingValue,
246
+ strategy === "preserve-local" ? { preserveUnmatchedExisting: true } : {
247
+ preserveUnmatchedExistingWhen: (payment) => (0, import_payment_utils.isIdentifiedPendingOrderPayment)(payment) || !(0, import_orderCollectionIdentity.getOrderCollectionPersistentId)("payment", payment)
248
+ }
249
+ );
250
+ }
153
251
  const currentItems = (0, import_orderCollectionIdentity.normalizeOrderCollection)(kind, currentValue, {
154
252
  ensureUid: false
155
253
  }).items;
@@ -209,6 +307,35 @@ function normalizeBaseSalesRecordCollections(sourceRecord, options) {
209
307
  }
210
308
  return normalizedRecord;
211
309
  }
310
+ function getBaseSalesMetadataUid(item, metadataKey) {
311
+ var _a;
312
+ const uid = ((_a = item == null ? void 0 : item.metadata) == null ? void 0 : _a[metadataKey]) ?? (item == null ? void 0 : item[metadataKey]);
313
+ if (uid === void 0 || uid === null || uid === "")
314
+ return null;
315
+ return String(uid);
316
+ }
317
+ function mergeBaseSalesUniqueArray(currentValue, loadedValue, metadataKey) {
318
+ const result = [];
319
+ const indexByUid = /* @__PURE__ */ new Map();
320
+ const appendOrReplaceByUid = (item) => {
321
+ const clonedItem = (0, import_lodash_es.cloneDeep)(item);
322
+ const uid = getBaseSalesMetadataUid(clonedItem, metadataKey);
323
+ if (!uid) {
324
+ result.push(clonedItem);
325
+ return;
326
+ }
327
+ const existingIndex = indexByUid.get(uid);
328
+ if (existingIndex !== void 0) {
329
+ result[existingIndex] = clonedItem;
330
+ return;
331
+ }
332
+ indexByUid.set(uid, result.length);
333
+ result.push(clonedItem);
334
+ };
335
+ currentValue.forEach(appendOrReplaceByUid);
336
+ loadedValue.forEach(appendOrReplaceByUid);
337
+ return result;
338
+ }
212
339
  function mergeSalesDetailRecordWithTempOrder(currentTempOrder, loadedRecord, strategy) {
213
340
  const normalizedLoadedRecord = normalizeBaseSalesRecordCollections(
214
341
  loadedRecord || {},
@@ -237,6 +364,15 @@ function mergeSalesDetailRecordWithTempOrder(currentTempOrder, loadedRecord, str
237
364
  );
238
365
  }
239
366
  if (Array.isArray(currentValue) && Array.isArray(loadedValue)) {
367
+ if (key === "payments" || key === "payment") {
368
+ return (0, import_payment_utils.mergeOrderPaymentListsByIdentity)(currentValue, loadedValue, {
369
+ preserveUnmatchedExisting: true
370
+ });
371
+ }
372
+ const metadataKey = getBaseSalesUniqueArrayMetadataKey(key);
373
+ if (metadataKey) {
374
+ return mergeBaseSalesUniqueArray(currentValue, loadedValue, metadataKey);
375
+ }
240
376
  return [
241
377
  ...(0, import_lodash_es.cloneDeep)(currentValue),
242
378
  ...(0, import_lodash_es.cloneDeep)(loadedValue)
@@ -255,6 +391,18 @@ function mergeSalesDetailRecordWithTempOrder(currentTempOrder, loadedRecord, str
255
391
  (0, import_orderCollectionIdentity.applyOrderCollectionUidRemaps)(mergedRecord, uidRemaps)
256
392
  );
257
393
  }
394
+ function filterPendingPaymentsFromLoadedSalesDetail(sourceRecord) {
395
+ if (!sourceRecord || typeof sourceRecord !== "object")
396
+ return sourceRecord;
397
+ const record = { ...sourceRecord };
398
+ if (Array.isArray(sourceRecord.payments)) {
399
+ record.payments = sourceRecord.payments.filter((payment) => !(0, import_payment_utils.isPendingOrderPayment)(payment));
400
+ }
401
+ if (Array.isArray(sourceRecord.payment)) {
402
+ record.payment = sourceRecord.payment.filter((payment) => !(0, import_payment_utils.isPendingOrderPayment)(payment));
403
+ }
404
+ return record;
405
+ }
258
406
  var BaseSalesImpl = class extends import_BaseModule.BaseModule {
259
407
  constructor(name, version) {
260
408
  super(name, version);
@@ -266,6 +414,11 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
266
414
  order: void 0
267
415
  };
268
416
  this.otherParams = {};
417
+ /**
418
+ * 由已在初始化阶段解析过设备短号的业务解决方案写入。
419
+ * 未设置时,支付编号仍按原逻辑实时读取设备信息。
420
+ */
421
+ this.paymentNumberDevicePrefix = null;
269
422
  // 当前缓存中已加载的最新 SalesDetail;只读 getter 走它对外暴露详情数据。
270
423
  this.currentSalesDetail = null;
271
424
  this.discountConfigCacheKey = null;
@@ -277,6 +430,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
277
430
  this.autoPaymentSyncTimer = null;
278
431
  this.salesDetailLoadInFlightCount = 0;
279
432
  this.salesDetailLoadSequence = 0;
433
+ this.walletAssetsRefreshSequence = 0;
280
434
  this.salesDetailHydrateQueue = Promise.resolve();
281
435
  this.serverOrderChangeUnsubscribe = null;
282
436
  this.serverOrderChangeHydrateInFlight = null;
@@ -796,6 +950,27 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
796
950
  const coreData = (_f = (_d = (_c = app == null ? void 0 : app.models) == null ? void 0 : _c.getStore) == null ? void 0 : (_e = _d.call(_c)).getDataByModel) == null ? void 0 : _f.call(_e, "core", "core");
797
951
  return coreData == null ? void 0 : coreData[key];
798
952
  }
953
+ /**
954
+ * 复用业务解决方案初始化时已解析的支付设备短号。
955
+ * 空值会清除缓存,使后续支付恢复实时读取设备信息的兼容路径。
956
+ */
957
+ setPaymentNumberDevicePrefix(prefix) {
958
+ const normalized = String(prefix ?? "").trim();
959
+ this.paymentNumberDevicePrefix = normalized || null;
960
+ }
961
+ getPaymentNumberDevicePrefixSync() {
962
+ if (!this.appPlugin)
963
+ return "LOCAL";
964
+ return (0, import_payment_number.resolvePaymentNumberDevicePrefixFromDeviceId)((key) => this.getAppData(key));
965
+ }
966
+ getPaymentNumberDevicePrefixAsync() {
967
+ if (!this.appPlugin)
968
+ return Promise.resolve("LOCAL");
969
+ if (this.paymentNumberDevicePrefix) {
970
+ return Promise.resolve(this.paymentNumberDevicePrefix);
971
+ }
972
+ return (0, import_payment_number.resolvePaymentNumberDevicePrefix)((key) => this.getAppData(key));
973
+ }
799
974
  syncAppDataToTempOrder(tempOrder) {
800
975
  const isPriceIncludeTax = this.getAppData("is_price_include_tax");
801
976
  const taxCountryCode = this.getAppData("tax_country_code");
@@ -833,9 +1008,10 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
833
1008
  return isChanged;
834
1009
  }
835
1010
  async initialize(core, options = {}) {
836
- var _a, _b, _c, _d;
1011
+ var _a, _b;
837
1012
  this.core = core;
838
1013
  this.initializeOptions = options || {};
1014
+ this.paymentNumberDevicePrefix = null;
839
1015
  this.otherParams = options.otherParams || {};
840
1016
  this.cacheId = (_a = this.otherParams) == null ? void 0 : _a.cacheId;
841
1017
  this.reusedSharedSubModuleNames.clear();
@@ -843,9 +1019,10 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
843
1019
  this.request = core.getPlugin("request");
844
1020
  this.appPlugin = core.getPlugin("app");
845
1021
  if (!this.appPlugin) {
1022
+ throw new Error("Checkout 解决方案需要 app 插件支持");
846
1023
  }
847
- const app = (_c = (_b = this.appPlugin) == null ? void 0 : _b.getApp) == null ? void 0 : _c.call(_b);
848
- this.logger = app == null ? void 0 : app.logger;
1024
+ const app = this.appPlugin.getApp();
1025
+ this.logger = app.logger;
849
1026
  const targetCacheData = this.readSessionCacheData();
850
1027
  const moduleNames = this.getRegisteredModuleNames();
851
1028
  moduleNames.forEach((step) => {
@@ -870,7 +1047,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
870
1047
  if (this.store.schedule && !this.isScheduleListLoaded(this.store.schedule)) {
871
1048
  await this.store.schedule.loadAllSchedule();
872
1049
  }
873
- if (this.store.order && typeof ((_d = this.otherParams) == null ? void 0 : _d.enableTempOrderPersist) === "boolean") {
1050
+ if (this.store.order && typeof ((_b = this.otherParams) == null ? void 0 : _b.enableTempOrderPersist) === "boolean") {
874
1051
  this.store.order.setEnableTempOrderPersist(
875
1052
  this.otherParams.enableTempOrderPersist
876
1053
  );
@@ -896,8 +1073,10 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
896
1073
  }
897
1074
  });
898
1075
  this.currentSalesDetail = null;
1076
+ this.paymentNumberDevicePrefix = null;
899
1077
  this.queuedServerOrderChanges = [];
900
1078
  this.salesDetailLoadSequence += 1;
1079
+ this.walletAssetsRefreshSequence += 1;
901
1080
  await this.core.effects.emit(`${this.name}:onDestroy`, {});
902
1081
  super.destroy();
903
1082
  }
@@ -929,13 +1108,16 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
929
1108
  const message = loadedRecord && (loadedRecord.message || loadedRecord.msg) || `加载销售详情失败: ${lookup}`;
930
1109
  throw new Error(message);
931
1110
  }
932
- const remoteRecord = preloadedSalesDetail ?? loadedRecord.data;
1111
+ const remoteRecord = filterPendingPaymentsFromLoadedSalesDetail(
1112
+ preloadedSalesDetail ?? loadedRecord.data
1113
+ );
933
1114
  const currentTempOrder = params.merge ? this.store.order.getTempOrder() : null;
934
- const record = params.merge ? mergeSalesDetailRecordWithTempOrder(
1115
+ const mergedRecord = params.merge ? mergeSalesDetailRecordWithTempOrder(
935
1116
  currentTempOrder,
936
1117
  remoteRecord,
937
1118
  "preserve-local"
938
1119
  ) : remoteRecord;
1120
+ const record = filterPendingPaymentsFromLoadedSalesDetail(mergedRecord);
939
1121
  return await this.hydrateLatestLoadedSalesDetail(record, loadSequence);
940
1122
  } finally {
941
1123
  this.salesDetailLoadInFlightCount = Math.max(
@@ -1111,6 +1293,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1111
1293
  // 重置 tempOrder 与与上一单强相关的运行态(resource/entryPaxNumber/enabledReservationRuleProducts),
1112
1294
  // 适用于从支付页通过 react-router 跳回继续下单时清理残留数据
1113
1295
  async restoreOrder() {
1296
+ var _a;
1114
1297
  try {
1115
1298
  if (!this.store.order) {
1116
1299
  throw new Error("scanOrder 解决方案需要 order 模块支持");
@@ -1119,6 +1302,12 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1119
1302
  this.currentSalesDetail = null;
1120
1303
  this.discountConfigCacheKey = null;
1121
1304
  this.hasManualDiscountSelection = false;
1305
+ const wallet = (_a = this.store.payment) == null ? void 0 : _a.wallet;
1306
+ if (wallet) {
1307
+ this.walletAssetsRefreshSequence += 1;
1308
+ wallet.clearAllCache();
1309
+ await this.publishWalletAssetsState(wallet.getWalletAssetsState());
1310
+ }
1122
1311
  await this.effectsEmit("onTempOrderReplaced", { tempOrder });
1123
1312
  if (this.syncAppDataToTempOrder(tempOrder) && this.isTempOrderPersistEnabled()) {
1124
1313
  this.store.order.persistTempOrder();
@@ -1711,7 +1900,6 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1711
1900
  throw new Error("BaseSales 解决方案需要 order 模块支持");
1712
1901
  }
1713
1902
  const inferredPaymentStatus = this.getSubmitPaymentStatus(params == null ? void 0 : params.paymentStatus);
1714
- const smallTicketDataFlag = (params == null ? void 0 : params.smallTicketDataFlag) ?? this.getDefaultCheckoutSmallTicketDataFlag();
1715
1903
  const submitParams = {
1716
1904
  cacheId: this.cacheId,
1717
1905
  platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
@@ -1721,11 +1909,25 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1721
1909
  request_unique_idempotency_token: this.store.order.generateIdempotencyToken(),
1722
1910
  ...(params == null ? void 0 : params.payments) !== void 0 ? { payments: params.payments } : {},
1723
1911
  ...inferredPaymentStatus !== void 0 ? { paymentStatus: inferredPaymentStatus } : {},
1724
- ...smallTicketDataFlag !== void 0 ? { smallTicketDataFlag } : {},
1912
+ ...(params == null ? void 0 : params.smallTicketDataFlag) !== void 0 ? { smallTicketDataFlag: params.smallTicketDataFlag } : {},
1725
1913
  ...(params == null ? void 0 : params.confirmPendingVoucherPayments) !== void 0 ? { confirmPendingVoucherPayments: params.confirmPendingVoucherPayments } : {},
1726
1914
  ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
1727
1915
  };
1728
- return this.shouldUseCheckoutSyncTask() ? this.store.order.submitTempOrder(submitParams) : this.store.order.submitTempOrderAsync(submitParams);
1916
+ return this.store.order.submitTempOrder(submitParams);
1917
+ }
1918
+ async saveSalesOrderDraft(params) {
1919
+ var _a, _b, _c, _d;
1920
+ if (!this.store.order) {
1921
+ throw new Error("BaseSales 解决方案需要 order 模块支持");
1922
+ }
1923
+ return this.store.order.saveTempOrderAsDraft({
1924
+ cacheId: this.cacheId,
1925
+ platform: (params == null ? void 0 : params.platform) ?? ((_a = this.otherParams) == null ? void 0 : _a.platform),
1926
+ businessCode: (params == null ? void 0 : params.businessCode) || ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1927
+ channel: (params == null ? void 0 : params.channel) ?? this.getSubmitOrderSalesChannel(),
1928
+ type: (params == null ? void 0 : params.type) ?? ((_d = this.otherParams) == null ? void 0 : _d.type),
1929
+ ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
1930
+ });
1729
1931
  }
1730
1932
  async submitTempOrderAsync(params) {
1731
1933
  var _a, _b, _c, _d;
@@ -1733,35 +1935,20 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1733
1935
  throw new Error("BaseSales 解决方案需要 order 模块支持");
1734
1936
  }
1735
1937
  const inferredPaymentStatus = this.getSubmitPaymentStatus(params == null ? void 0 : params.paymentStatus);
1736
- const smallTicketDataFlag = (params == null ? void 0 : params.smallTicketDataFlag) ?? this.getDefaultCheckoutSmallTicketDataFlag();
1737
1938
  const submitParams = {
1738
1939
  cacheId: this.cacheId,
1739
1940
  platform: (_a = this.otherParams) == null ? void 0 : _a.platform,
1740
1941
  businessCode: ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1741
1942
  channel: this.getSubmitOrderSalesChannel(),
1742
1943
  type: (_d = this.otherParams) == null ? void 0 : _d.type,
1743
- request_unique_idempotency_token: this.store.order.generateIdempotencyToken(),
1744
1944
  ...(params == null ? void 0 : params.payments) !== void 0 ? { payments: params.payments } : {},
1745
1945
  ...inferredPaymentStatus !== void 0 ? { paymentStatus: inferredPaymentStatus } : {},
1746
- ...smallTicketDataFlag !== void 0 ? { smallTicketDataFlag } : {},
1946
+ ...(params == null ? void 0 : params.smallTicketDataFlag) !== void 0 ? { smallTicketDataFlag: params.smallTicketDataFlag } : {},
1747
1947
  ...(params == null ? void 0 : params.confirmPendingVoucherPayments) !== void 0 ? { confirmPendingVoucherPayments: params.confirmPendingVoucherPayments } : {},
1748
1948
  ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
1749
1949
  };
1750
1950
  return this.store.order.submitTempOrderAsync(submitParams);
1751
1951
  }
1752
- /**
1753
- * 默认保持 WebPOS 的本地待同步订单模式;需要云端确认后才算成功的渠道可覆盖此策略。
1754
- * otherParams.checkoutSyncTaskEnabled 优先,便于同一 solution 按入口恢复旧行为。
1755
- */
1756
- shouldUseCheckoutSyncTask() {
1757
- var _a;
1758
- const configured = (_a = this.otherParams) == null ? void 0 : _a.checkoutSyncTaskEnabled;
1759
- return typeof configured === "boolean" ? configured : true;
1760
- }
1761
- /** 可由特定 solution 为真实 checkout 补充默认收据数据请求。 */
1762
- getDefaultCheckoutSmallTicketDataFlag() {
1763
- return void 0;
1764
- }
1765
1952
  async printLocalOrderReceipt(lookup) {
1766
1953
  var _a, _b, _c, _d, _e, _f, _g;
1767
1954
  if (!this.store.order) {
@@ -1821,7 +2008,6 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1821
2008
  const channel = params.channel ?? this.getSubmitOrderSalesChannel();
1822
2009
  const syncParams = {
1823
2010
  ...params,
1824
- checkoutSyncTaskEnabled: this.shouldUseCheckoutSyncTask(),
1825
2011
  ...businessCode !== void 0 ? { businessCode } : {},
1826
2012
  ...channel !== void 0 ? { channel } : {}
1827
2013
  };
@@ -1943,8 +2129,29 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1943
2129
  }
1944
2130
  }
1945
2131
  }
1946
- /** 追加单个支付项到当前订单。 */
2132
+ /**
2133
+ * 同步兼容入口。无法等待 IoT 短号时,按调用当下的 device_id 或 LOCAL 生成。
2134
+ */
1947
2135
  addOrderPayment(payment) {
2136
+ const hasPaymentNumber = String(
2137
+ payment.payment_number || ""
2138
+ ).trim() !== "";
2139
+ return this.addOrderPaymentWithDevicePrefix(
2140
+ payment,
2141
+ hasPaymentNumber ? "LOCAL" : this.getPaymentNumberDevicePrefixSync()
2142
+ );
2143
+ }
2144
+ /**
2145
+ * 创建新支付项时优先使用业务解决方案初始化阶段缓存的设备短号;
2146
+ * 未缓存的通用 BaseSales 保持实时读取设备信息的兼容语义。
2147
+ */
2148
+ async addOrderPaymentAsync(payment) {
2149
+ const paymentRecord = payment;
2150
+ const hasPaymentNumber = String(paymentRecord.payment_number || "").trim() !== "";
2151
+ const devicePrefix = hasPaymentNumber ? "LOCAL" : await this.getPaymentNumberDevicePrefixAsync();
2152
+ return this.addOrderPaymentWithDevicePrefix(payment, devicePrefix);
2153
+ }
2154
+ addOrderPaymentWithDevicePrefix(payment, devicePrefix) {
1948
2155
  var _a;
1949
2156
  if (!this.store.order)
1950
2157
  throw new Error("order 模块未初始化");
@@ -1961,21 +2168,26 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1961
2168
  if (shopWalletPassId !== void 0 && shopWalletPassId !== null) {
1962
2169
  metadata.shop_wallet_pass_id = shopWalletPassId;
1963
2170
  }
1964
- if (!metadata.unique_payment_number) {
1965
- metadata.unique_payment_number = (0, import_utils.createUuidV4)();
1966
- }
2171
+ const normalizedPaymentRecord = (0, import_payment_utils.ensureOrderPaymentNumber)(
2172
+ paymentRecord,
2173
+ devicePrefix,
2174
+ import_utils.createUuidV4
2175
+ );
1967
2176
  const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
1968
2177
  const paymentTime = paymentRecord.payment_time ?? paymentTimestamp;
1969
2178
  const createdAt = paymentRecord.created_at ?? paymentTimestamp;
1970
2179
  const serviceCharge = paymentRecord.service_charge && typeof paymentRecord.service_charge === "object" ? paymentRecord.service_charge : null;
1971
2180
  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;
1972
2181
  const payments = this.store.order.addOrderPayment({
1973
- ...paymentRecord,
2182
+ ...normalizedPaymentRecord,
1974
2183
  ...calculatedServiceFee !== void 0 ? { service_fee: calculatedServiceFee } : {},
1975
2184
  metadata,
1976
2185
  payment_time: paymentTime,
1977
2186
  created_at: createdAt
1978
2187
  });
2188
+ if (paymentRecord.status === "payment_pending") {
2189
+ return payments;
2190
+ }
1979
2191
  const amountSnapshot = this.store.order.getOrderAmountSnapshot();
1980
2192
  const syncState = this.store.order.getOrderSyncState();
1981
2193
  if (amountSnapshot) {
@@ -1997,10 +2209,73 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1997
2209
  return payments;
1998
2210
  }
1999
2211
  /** 更新当前订单中的指定支付项。 */
2000
- updateOrderPayment(paymentIdentity, updates) {
2212
+ async updateOrderPayment(paymentIdentity, updates, options = {}) {
2213
+ var _a, _b, _c;
2001
2214
  if (!this.store.order)
2002
2215
  throw new Error("order 模块未初始化");
2003
- return this.store.order.updateOrderPayment(paymentIdentity, updates);
2216
+ const matchMode = options.matchBy === "compat" || options.matchBy === "legacy" ? "compat" : "payment_number";
2217
+ const previousMatch = (0, import_payment_utils.resolveOrderPaymentIdentity)(
2218
+ this.store.order.getOrderPayments(),
2219
+ paymentIdentity,
2220
+ matchMode
2221
+ );
2222
+ const previousPayment = previousMatch == null ? void 0 : previousMatch.payment;
2223
+ if ((previousPayment == null ? void 0 : previousPayment.status) === "paid" && !options.applyUpdatesWhenPaid) {
2224
+ const currentPayments = this.store.order.getOrderPayments();
2225
+ let syncResult2;
2226
+ if (options.submitWhenPaid && options.forceSubmitIfPaid) {
2227
+ syncResult2 = await this.syncPaymentsToOrder({
2228
+ payments: currentPayments,
2229
+ paymentStatus: this.getPaymentStatusForSync(currentPayments),
2230
+ submitWhenPaid: true,
2231
+ smallTicketDataFlag: options.smallTicketDataFlag ?? 1
2232
+ });
2233
+ }
2234
+ return {
2235
+ updated: false,
2236
+ payment: previousPayment,
2237
+ payments: currentPayments,
2238
+ summary: ((_a = this.store.order.getOrderAmountSnapshot()) == null ? void 0 : _a.summary) || null,
2239
+ ...syncResult2 !== void 0 ? { syncResult: syncResult2 } : {}
2240
+ };
2241
+ }
2242
+ const result = await this.store.order.updateOrderPayment(paymentIdentity, updates, {
2243
+ matchBy: matchMode
2244
+ });
2245
+ let draftResult;
2246
+ let draftError;
2247
+ if (options.persistDraft !== false) {
2248
+ try {
2249
+ draftResult = await this.saveSalesOrderDraft();
2250
+ } catch (error) {
2251
+ draftError = error;
2252
+ this.logError("updateOrderPayment: 保存支付草稿失败", {
2253
+ paymentIdentity,
2254
+ error: error instanceof Error ? error.message : String(error)
2255
+ });
2256
+ if (!options.submitWhenPaid)
2257
+ throw error;
2258
+ }
2259
+ }
2260
+ const becamePaid = (previousPayment == null ? void 0 : previousPayment.status) !== "paid" && ((_b = result.payment) == null ? void 0 : _b.status) === "paid";
2261
+ const shouldSubmit = Boolean(
2262
+ options.submitWhenPaid && ((_c = result.payment) == null ? void 0 : _c.status) === "paid" && (becamePaid || options.forceSubmitIfPaid)
2263
+ );
2264
+ let syncResult;
2265
+ if (shouldSubmit) {
2266
+ syncResult = await this.syncPaymentsToOrder({
2267
+ payments: result.payments,
2268
+ paymentStatus: this.getPaymentStatusForSync(result.payments),
2269
+ submitWhenPaid: true,
2270
+ smallTicketDataFlag: options.smallTicketDataFlag ?? 1
2271
+ });
2272
+ }
2273
+ return {
2274
+ ...result,
2275
+ ...draftResult !== void 0 ? { draftResult } : {},
2276
+ ...draftError !== void 0 ? { draftError } : {},
2277
+ ...syncResult !== void 0 ? { syncResult } : {}
2278
+ };
2004
2279
  }
2005
2280
  /** 删除当前订单中的指定支付项。 */
2006
2281
  deleteOrderPayment(paymentIdentity) {
@@ -2014,10 +2289,24 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2014
2289
  throw new Error("order 模块未初始化");
2015
2290
  return this.store.order.updateVoucherOrderPayments(payments, options);
2016
2291
  }
2292
+ async updateVoucherOrderPaymentsAsync(payments, options) {
2293
+ if (!this.store.order)
2294
+ throw new Error("order 模块未初始化");
2295
+ return this.store.order.updateVoucherOrderPaymentsAsync(payments, options);
2296
+ }
2017
2297
  confirmPendingVoucherPayments() {
2018
2298
  if (!this.store.order)
2019
2299
  throw new Error("order 模块未初始化");
2020
- return this.store.order.confirmPendingVoucherPayments();
2300
+ const payments = this.store.order.confirmPendingVoucherPayments();
2301
+ if (this.store.payment) {
2302
+ const committed = this.getCommittedWalletAssets();
2303
+ const state = this.store.payment.wallet.setCommittedWalletAssets(
2304
+ committed.ids,
2305
+ committed.assets
2306
+ );
2307
+ void this.publishWalletAssetsState(state);
2308
+ }
2309
+ return payments;
2021
2310
  }
2022
2311
  discardPendingVoucherPayments() {
2023
2312
  if (!this.store.order)
@@ -2078,24 +2367,14 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2078
2367
  });
2079
2368
  return walletProducts;
2080
2369
  }
2081
- async initWalletData(params) {
2082
- if (!this.store.order)
2083
- throw new Error("order 模块未初始化");
2084
- if (!this.store.payment)
2085
- throw new Error("payment 模块未初始化");
2086
- const snapshot = this.store.order.getOrderSnapshot();
2370
+ buildWalletInitBusinessData(params) {
2371
+ var _a;
2372
+ const snapshot = (_a = this.store.order) == null ? void 0 : _a.getOrderSnapshot();
2087
2373
  const tempOrder = snapshot == null ? void 0 : snapshot.tempOrder;
2088
2374
  const amount = snapshot == null ? void 0 : snapshot.amount;
2089
- if (!tempOrder || !amount) {
2090
- return {
2091
- walletRecommendList: [],
2092
- userIdentificationCodes: [],
2093
- transformList: [],
2094
- noApplicableVoucher: [],
2095
- products: []
2096
- };
2097
- }
2098
- const walletBusinessData = {
2375
+ if (!tempOrder || !amount)
2376
+ return null;
2377
+ return {
2099
2378
  customer_id: tempOrder.customer_id ? Number(tempOrder.customer_id) : void 0,
2100
2379
  holder: tempOrder.holder,
2101
2380
  amountInfo: {
@@ -2109,11 +2388,29 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2109
2388
  is_price_include_tax: tempOrder.is_price_include_tax ?? this.otherParams.is_price_include_tax ?? 1,
2110
2389
  ...snapshot.identity.orderId ? { payment_order_id: String(snapshot.identity.orderId) } : {}
2111
2390
  };
2391
+ }
2392
+ async initWalletData(params) {
2393
+ var _a;
2394
+ if (!this.store.order)
2395
+ throw new Error("order 模块未初始化");
2396
+ if (!this.store.payment)
2397
+ throw new Error("payment 模块未初始化");
2398
+ const snapshot = this.store.order.getOrderSnapshot();
2399
+ const walletBusinessData = this.buildWalletInitBusinessData(params);
2400
+ if (!walletBusinessData) {
2401
+ return {
2402
+ walletRecommendList: [],
2403
+ userIdentificationCodes: [],
2404
+ transformList: [],
2405
+ noApplicableVoucher: [],
2406
+ products: []
2407
+ };
2408
+ }
2112
2409
  const result = await this.store.payment.wallet.initializeWalletDataFromBusinessAsync(
2113
2410
  walletBusinessData
2114
2411
  );
2115
2412
  await this.core.effects.emit(`${this.name}:onWalletDataInitialized`, {
2116
- orderId: snapshot.identity.orderId,
2413
+ orderId: (_a = snapshot == null ? void 0 : snapshot.identity) == null ? void 0 : _a.orderId,
2117
2414
  customerId: walletBusinessData.customer_id,
2118
2415
  walletBusinessData: {
2119
2416
  customer_id: walletBusinessData.customer_id,
@@ -2124,6 +2421,202 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2124
2421
  });
2125
2422
  return result;
2126
2423
  }
2424
+ getCommittedWalletAssets() {
2425
+ var _a, _b;
2426
+ const payments = ((_b = (_a = this.store.order) == null ? void 0 : _a.getOrderPayments) == null ? void 0 : _b.call(_a)) || [];
2427
+ const committed = payments.filter((payment) => {
2428
+ const voucherId = payment == null ? void 0 : payment.voucher_id;
2429
+ if (voucherId === void 0 || voucherId === null || voucherId === 0) {
2430
+ return false;
2431
+ }
2432
+ 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) !== "";
2433
+ });
2434
+ return {
2435
+ ids: committed.map((payment) => payment.voucher_id),
2436
+ assets: committed.map((payment) => {
2437
+ var _a2;
2438
+ const fundRecord = (payment == null ? void 0 : payment.fund_record) || {};
2439
+ const walletPassName = fundRecord.wallet_pass_name;
2440
+ const title = walletPassName && typeof walletPassName === "object" ? walletPassName.default || Object.values(walletPassName)[0] : walletPassName;
2441
+ const code = String((payment == null ? void 0 : payment.code) || "").toUpperCase();
2442
+ const tag = ((_a2 = Object.entries(WALLET_PAYMENT_CODE_BY_TAG).find(
2443
+ ([, paymentCode]) => paymentCode === code
2444
+ )) == null ? void 0 : _a2[0]) || fundRecord.tag;
2445
+ return {
2446
+ id: payment.voucher_id,
2447
+ voucher_id: payment.voucher_id,
2448
+ code: fundRecord.code,
2449
+ tag,
2450
+ product_name: title || payment.name,
2451
+ name: title || payment.name,
2452
+ amount: Number(payment.amount || 0),
2453
+ _available_max_amount: Number(payment.amount || 0),
2454
+ unified_available_status: 1,
2455
+ _unified_available_status: 1,
2456
+ _committed_payment: payment
2457
+ };
2458
+ })
2459
+ };
2460
+ }
2461
+ async publishWalletAssetsState(state) {
2462
+ await this.effectsEmit(import_types.BaseSalesHookNames.onWalletAssetsStateChanged, {
2463
+ state
2464
+ });
2465
+ return state;
2466
+ }
2467
+ async syncSelectedWalletAssets(state) {
2468
+ if (!this.store.order || !this.store.payment) {
2469
+ throw new Error("订单或支付模块未初始化");
2470
+ }
2471
+ let paymentMethods = this.getPaymentMethods();
2472
+ if (!paymentMethods.length && state.selectedItems.length) {
2473
+ paymentMethods = await this.getPaymentMethodsAsync();
2474
+ }
2475
+ const methodByCode = new Map(
2476
+ paymentMethods.map((method) => [String(method.code || "").toUpperCase(), method])
2477
+ );
2478
+ const preparePayments = this.store.payment.wallet.formatWalletPassList2PreparePayments(
2479
+ state.selectedItems
2480
+ );
2481
+ const selectedAssetById = new Map(
2482
+ state.selectedItems.map((asset) => [
2483
+ String(getSharedWalletAssetId(asset)),
2484
+ asset
2485
+ ])
2486
+ );
2487
+ const voucherPayments = preparePayments.flatMap((item) => {
2488
+ const asset = selectedAssetById.get(String(item.voucher_id));
2489
+ 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();
2490
+ const paymentMethod = methodByCode.get(paymentCode);
2491
+ const formattedAmount = Number(item.amount);
2492
+ const amount = Number.isFinite(formattedAmount) && formattedAmount > 0 ? formattedAmount : getSharedWalletAssetAmount(asset);
2493
+ if (!asset || !paymentMethod || !Number.isFinite(amount) || amount <= 0) {
2494
+ return [];
2495
+ }
2496
+ const walletPassUseValue = getSharedWalletPassUseValue({
2497
+ asset,
2498
+ amount,
2499
+ paymentMethod
2500
+ });
2501
+ return [
2502
+ {
2503
+ amount: amount.toFixed(2),
2504
+ code: paymentMethod.code,
2505
+ custom_payment_id: paymentMethod.id,
2506
+ name: paymentMethod.name,
2507
+ type: paymentMethod.type,
2508
+ voucher_id: item.voucher_id,
2509
+ wallet_pass_usage_unit: item.wallet_pass_usage_unit,
2510
+ wallet_pass_use_value: walletPassUseValue,
2511
+ fund_record: buildSharedWalletFundRecord({
2512
+ asset,
2513
+ amount,
2514
+ paymentMethod
2515
+ })
2516
+ }
2517
+ ];
2518
+ });
2519
+ const payments = this.updateVoucherOrderPayments(voucherPayments, {
2520
+ status: "payment_pending"
2521
+ });
2522
+ await this.store.order.recalculateSummary({ createIfMissing: true });
2523
+ return payments;
2524
+ }
2525
+ /** 读取购物车与 Shared Checkout 共用的钱包资产状态。 */
2526
+ getWalletAssetsState() {
2527
+ if (!this.store.payment)
2528
+ throw new Error("payment 模块未初始化");
2529
+ return this.store.payment.wallet.getWalletAssetsState();
2530
+ }
2531
+ /** 导出 Shared Checkout 跨运行时恢复所需的钱包状态与搜索缓存。 */
2532
+ exportWalletAssetsSnapshot() {
2533
+ if (!this.store.payment)
2534
+ throw new Error("payment 模块未初始化");
2535
+ return this.store.payment.wallet.exportWalletAssetsSnapshot();
2536
+ }
2537
+ /**
2538
+ * 恢复 Shared Checkout 钱包快照,并把选择重新同步为订单 pending payment。
2539
+ */
2540
+ async importWalletAssetsSnapshot(snapshot) {
2541
+ if (!this.store.payment)
2542
+ throw new Error("payment 模块未初始化");
2543
+ const state = this.store.payment.wallet.importWalletAssetsSnapshot(snapshot);
2544
+ await this.syncSelectedWalletAssets(state);
2545
+ return this.publishWalletAssetsState(state);
2546
+ }
2547
+ /**
2548
+ * 基于当前订单快照刷新钱包资产。商品变化保留并重验选择;客户变化强制清空。
2549
+ */
2550
+ async refreshWalletAssets(params) {
2551
+ if (!this.store.order)
2552
+ throw new Error("order 模块未初始化");
2553
+ if (!this.store.payment)
2554
+ throw new Error("payment 模块未初始化");
2555
+ const refreshSequence = ++this.walletAssetsRefreshSequence;
2556
+ const wallet = this.store.payment.wallet;
2557
+ const businessData = this.buildWalletInitBusinessData(params);
2558
+ if (!businessData) {
2559
+ wallet.clearAllCache();
2560
+ const emptyState = wallet.getWalletAssetsState();
2561
+ this.updateVoucherOrderPayments([], { status: "payment_pending" });
2562
+ return this.publishWalletAssetsState(emptyState);
2563
+ }
2564
+ const previousState = wallet.getWalletAssetsState();
2565
+ const hasPreviousWalletContext = previousState.status !== "idle" || previousState.items.length > 0 || previousState.selectedIds.length > 0 || previousState.customerId !== void 0;
2566
+ const customerChanged = hasPreviousWalletContext && String(previousState.customerId ?? "") !== String(businessData.customer_id ?? "");
2567
+ if (customerChanged) {
2568
+ const clearedState = wallet.clearWalletAssetSelection();
2569
+ this.updateVoucherOrderPayments([], { status: "payment_pending" });
2570
+ await this.publishWalletAssetsState(clearedState);
2571
+ }
2572
+ const refreshTask = wallet.refreshWalletAssetsFromBusinessAsync(
2573
+ businessData,
2574
+ {
2575
+ preserveSelection: (params == null ? void 0 : params.preserveSelection) !== false && !customerChanged
2576
+ }
2577
+ );
2578
+ await this.publishWalletAssetsState(wallet.getWalletAssetsState());
2579
+ let state = await refreshTask;
2580
+ if (refreshSequence !== this.walletAssetsRefreshSequence) {
2581
+ return wallet.getWalletAssetsState();
2582
+ }
2583
+ if (state.status !== "error") {
2584
+ const committed = this.getCommittedWalletAssets();
2585
+ state = wallet.setCommittedWalletAssets(committed.ids, committed.assets);
2586
+ }
2587
+ await this.syncSelectedWalletAssets(state);
2588
+ return this.publishWalletAssetsState(state);
2589
+ }
2590
+ /** 选择或取消单张钱包资产,并立即同步 pending wallet payments。 */
2591
+ async selectWalletAsset(params) {
2592
+ if (!this.store.payment)
2593
+ throw new Error("payment 模块未初始化");
2594
+ const state = this.store.payment.wallet.selectWalletAsset(params.assetId, {
2595
+ selected: params.selected,
2596
+ source: params.source
2597
+ });
2598
+ await this.syncSelectedWalletAssets(state);
2599
+ return this.publishWalletAssetsState(state);
2600
+ }
2601
+ /** 扫码精确查券;仅可用资产会被自动选中。 */
2602
+ async scanWalletAsset(code) {
2603
+ if (!this.store.payment)
2604
+ throw new Error("payment 模块未初始化");
2605
+ const result = await this.store.payment.wallet.scanWalletAssetAsync(code);
2606
+ if (result.type === "normalCode") {
2607
+ await this.syncSelectedWalletAssets(result.state);
2608
+ await this.publishWalletAssetsState(result.state);
2609
+ }
2610
+ return result;
2611
+ }
2612
+ /** 清空全部未确认钱包选择,已支付钱包项由 Order 模块继续保留。 */
2613
+ async clearWalletAssetSelection() {
2614
+ if (!this.store.payment)
2615
+ throw new Error("payment 模块未初始化");
2616
+ const state = this.store.payment.wallet.clearWalletAssetSelection();
2617
+ await this.syncSelectedWalletAssets(state);
2618
+ return this.publishWalletAssetsState(state);
2619
+ }
2127
2620
  /**
2128
2621
  * 更新当前订单客户字段。
2129
2622
  *
@@ -2160,29 +2653,349 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2160
2653
  getPaymentMethods() {
2161
2654
  return [...this.paymentMethodsCache];
2162
2655
  }
2163
- /** 轻量舍入能力,供现金支付 UI 计算 rounding_amount。 */
2164
- roundAmount(params) {
2165
- const amount = new import_decimal.default(params.amount || 0);
2166
- const interval = new import_decimal.default(params.interval || 0.05);
2167
- const rule = params.rule || "standard_rounding";
2168
- const quotient = amount.div(interval);
2169
- let roundedQuotient;
2170
- if (rule === "always_up") {
2171
- roundedQuotient = quotient.ceil();
2172
- } else if (rule === "always_down") {
2173
- roundedQuotient = quotient.floor();
2174
- } else if (rule === "standard_down") {
2175
- roundedQuotient = quotient.toDecimalPlaces(0, import_decimal.default.ROUND_HALF_DOWN);
2176
- } else {
2177
- roundedQuotient = quotient.toDecimalPlaces(0, import_decimal.default.ROUND_HALF_UP);
2656
+ findCashPaymentMethod(paymentMethods) {
2657
+ return paymentMethods.find((method) => {
2658
+ const identifiers = [method == null ? void 0 : method.code, method == null ? void 0 : method.type, method == null ? void 0 : method.tag].map(
2659
+ (value) => String(value || "").toUpperCase()
2660
+ );
2661
+ return identifiers.includes("CASHMANUAL") && (method == null ? void 0 : method.enabled) !== false && (method == null ? void 0 : method.enable) !== false;
2662
+ });
2663
+ }
2664
+ getPendingWalletPaymentAmount(payments = ((_b) => (_b = ((_a) => (_a = this.store.order) == null ? void 0 : _a.getOrderPayments)()) == null ? void 0 : _b.call(_a))() || []) {
2665
+ return payments.reduce((total, payment) => {
2666
+ if ((payment == null ? void 0 : payment.status) !== "payment_pending" || (payment == null ? void 0 : payment.voucher_id) === void 0 || Number(payment.voucher_id) === 0) {
2667
+ return total;
2668
+ }
2669
+ try {
2670
+ return total.plus(payment.amount || 0).plus(payment.rounding_amount || 0);
2671
+ } catch {
2672
+ return total;
2673
+ }
2674
+ }, new import_decimal.default(0));
2675
+ }
2676
+ /** 读取现金 action 所需的支付方式、待付金额和快捷金额。 */
2677
+ async getCashPaymentConfig() {
2678
+ var _a, _b, _c, _d, _e, _f;
2679
+ if (!this.store.payment)
2680
+ throw new Error("payment 模块未初始化");
2681
+ let paymentMethods = this.getPaymentMethods();
2682
+ let paymentMethod = this.findCashPaymentMethod(paymentMethods);
2683
+ if (!paymentMethod) {
2684
+ paymentMethods = await this.getPaymentMethodsAsync();
2685
+ paymentMethod = this.findCashPaymentMethod(paymentMethods);
2178
2686
  }
2179
- const roundedAmount = roundedQuotient.times(interval).toDecimalPlaces(2);
2687
+ const amountSnapshot = (_b = (_a = this.store.order) == null ? void 0 : _a.getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2688
+ const pendingWalletAmount = this.getPendingWalletPaymentAmount();
2689
+ const amountDue = import_decimal.default.max(
2690
+ new import_decimal.default((amountSnapshot == null ? void 0 : amountSnapshot.amountGap) || 0).minus(pendingWalletAmount),
2691
+ 0
2692
+ ).toDecimalPlaces(2).toNumber();
2693
+ 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";
2694
+ const recommendedAmounts = amountDue > 0 ? this.store.payment.cash.getRecommendedAmount(amountDue, currency) : [];
2180
2695
  return {
2181
- originalAmount: amount.toFixed(2),
2182
- roundedAmount: roundedAmount.toFixed(2),
2183
- roundingDifference: roundedAmount.minus(amount).toFixed(2)
2696
+ available: Boolean(paymentMethod && amountDue > 0),
2697
+ paymentMethod,
2698
+ amountDue,
2699
+ recommendedAmounts
2184
2700
  };
2185
2701
  }
2702
+ /**
2703
+ * 确认足额覆盖订单的 pending Wallet 支付并提交订单。
2704
+ *
2705
+ * Order 模块在构造提交参数时将 pending voucher 转为 paid;只有提交成功后
2706
+ * 才同步 Wallet committed 状态。失败时恢复调用前 payments,允许用户重试。
2707
+ */
2708
+ async confirmWalletPayment() {
2709
+ var _a, _b, _c, _d, _e;
2710
+ if (!this.store.order)
2711
+ throw new Error("order 模块未初始化");
2712
+ const beforePayments = (0, import_lodash_es.cloneDeep)(this.store.order.getOrderPayments());
2713
+ const pendingWalletAmount = this.getPendingWalletPaymentAmount(beforePayments);
2714
+ if (pendingWalletAmount.lte(0)) {
2715
+ throw new Error("当前订单没有待确认的 Wallet 支付");
2716
+ }
2717
+ const amountSnapshot = (_b = (_a = this.store.order).getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2718
+ const effectiveAmountDue = import_decimal.default.max(
2719
+ new import_decimal.default((amountSnapshot == null ? void 0 : amountSnapshot.amountGap) || 0).minus(pendingWalletAmount),
2720
+ 0
2721
+ );
2722
+ if (effectiveAmountDue.gt(0.01)) {
2723
+ throw new Error("Wallet 支付尚未覆盖全部待支付金额");
2724
+ }
2725
+ const beforePaymentStatus = (_c = this.store.order.getTempOrder()) == null ? void 0 : _c.payment_status;
2726
+ let submitResult;
2727
+ try {
2728
+ submitResult = await this.submitSalesOrder({
2729
+ smallTicketDataFlag: 1,
2730
+ confirmPendingVoucherPayments: true
2731
+ });
2732
+ if (isRejectedSalesSubmitResult(submitResult)) {
2733
+ throw new Error(getSalesSubmitErrorMessage(submitResult));
2734
+ }
2735
+ } catch (error) {
2736
+ this.store.order.setOrderPayments(beforePayments);
2737
+ const restoredTempOrder = this.store.order.getTempOrder();
2738
+ if (restoredTempOrder && beforePaymentStatus !== void 0) {
2739
+ restoredTempOrder.payment_status = beforePaymentStatus;
2740
+ this.store.order.persistTempOrder();
2741
+ }
2742
+ await this.store.order.recalculateSummary({ createIfMissing: true });
2743
+ throw error;
2744
+ }
2745
+ if (this.store.payment) {
2746
+ try {
2747
+ const committed = this.getCommittedWalletAssets();
2748
+ const walletState = this.store.payment.wallet.setCommittedWalletAssets(
2749
+ committed.ids,
2750
+ committed.assets
2751
+ );
2752
+ await this.publishWalletAssetsState(walletState);
2753
+ } catch (error) {
2754
+ this.logWarning("confirmWalletPayment: Wallet committed 状态同步失败", {
2755
+ error: error instanceof Error ? error.message : String(error)
2756
+ });
2757
+ }
2758
+ }
2759
+ const latestAmountSnapshot = (_e = (_d = this.store.order).getOrderAmountSnapshot) == null ? void 0 : _e.call(_d);
2760
+ return {
2761
+ submitResult,
2762
+ payments: this.store.order.getOrderPayments(),
2763
+ isOrderFullyPaid: new import_decimal.default(
2764
+ (latestAmountSnapshot == null ? void 0 : latestAmountSnapshot.amountGap) || 0
2765
+ ).lte(0)
2766
+ };
2767
+ }
2768
+ /**
2769
+ * 购物车现金直付:写入现金记录并等待支付同步完成。
2770
+ * 同步失败会恢复调用前 payments(包含 Wallet pending 状态)。
2771
+ */
2772
+ async payCash(params) {
2773
+ var _a, _b, _c, _d, _e, _f;
2774
+ if (!this.store.order)
2775
+ throw new Error("order 模块未初始化");
2776
+ const amount = Number(params.amount || 0);
2777
+ if (!Number.isFinite(amount) || amount <= 0) {
2778
+ throw new Error("现金支付金额必须大于 0");
2779
+ }
2780
+ const config = await this.getCashPaymentConfig();
2781
+ const paymentMethod = config.paymentMethod;
2782
+ if (!paymentMethod)
2783
+ throw new Error("未找到可用的 CASHMANUAL 支付方式");
2784
+ if (config.amountDue <= 0)
2785
+ throw new Error("当前订单没有待支付金额");
2786
+ const roundingAmount = Number(params.roundingAmount || 0);
2787
+ const effectivePaymentAmount = new import_decimal.default(amount).minus(roundingAmount);
2788
+ if (effectivePaymentAmount.gt(new import_decimal.default(config.amountDue).plus(0.01))) {
2789
+ throw new Error("现金支付金额超过当前待支付金额");
2790
+ }
2791
+ const beforePayments = (0, import_lodash_es.cloneDeep)(this.store.order.getOrderPayments());
2792
+ const beforePaymentStatus = (_a = this.store.order.getTempOrder()) == null ? void 0 : _a.payment_status;
2793
+ const uniquePaymentNumber = (0, import_utils.createUuidV4)();
2794
+ const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
2795
+ const actualPaidAmount = Number(params.actualPaidAmount ?? amount);
2796
+ const changeAmount = Number(params.changeAmount || 0);
2797
+ const shopWalletPassId = (_b = this.otherParams) == null ? void 0 : _b.shop_wallet_pass_id;
2798
+ if (!Number.isFinite(actualPaidAmount) || actualPaidAmount + 0.01 < amount) {
2799
+ throw new Error("顾客实收现金不能小于支付金额");
2800
+ }
2801
+ (_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, {
2802
+ module: "till",
2803
+ key: "open_till",
2804
+ data: { type: "cash" }
2805
+ });
2806
+ const payments = this.store.order.addOrderPayment({
2807
+ amount: amount.toFixed(2),
2808
+ code: paymentMethod.code,
2809
+ custom_payment_id: paymentMethod.id,
2810
+ name: paymentMethod.name,
2811
+ custom_payment_type: paymentMethod.type,
2812
+ voucher_id: 0,
2813
+ rounding_amount: roundingAmount.toFixed(2),
2814
+ metadata: {
2815
+ unique_payment_number: uniquePaymentNumber,
2816
+ ...shopWalletPassId !== void 0 && shopWalletPassId !== null ? { shop_wallet_pass_id: shopWalletPassId } : {},
2817
+ actual_paid_amount: Number.isFinite(actualPaidAmount) ? actualPaidAmount : amount,
2818
+ change_given_amount: Number.isFinite(changeAmount) ? changeAmount : 0
2819
+ },
2820
+ payment_time: paymentTimestamp,
2821
+ created_at: paymentTimestamp
2822
+ });
2823
+ const payment = payments.find(
2824
+ (item) => {
2825
+ var _a2;
2826
+ return ((_a2 = item == null ? void 0 : item.metadata) == null ? void 0 : _a2.unique_payment_number) === uniquePaymentNumber;
2827
+ }
2828
+ );
2829
+ try {
2830
+ const syncResult = await this.syncPaymentsToOrder({
2831
+ payments,
2832
+ submitWhenPaid: true,
2833
+ smallTicketDataFlag: 1,
2834
+ confirmPendingVoucherPayments: true
2835
+ });
2836
+ if (this.store.payment) {
2837
+ const committed = this.getCommittedWalletAssets();
2838
+ const walletState = this.store.payment.wallet.setCommittedWalletAssets(
2839
+ committed.ids,
2840
+ committed.assets
2841
+ );
2842
+ await this.publishWalletAssetsState(walletState);
2843
+ }
2844
+ return {
2845
+ payment: payment || {},
2846
+ payments: this.store.order.getOrderPayments(),
2847
+ syncResult,
2848
+ isOrderFullyPaid: syncResult.isOrderFullyPaid
2849
+ };
2850
+ } catch (error) {
2851
+ this.store.order.setOrderPayments(beforePayments);
2852
+ const restoredTempOrder = this.store.order.getTempOrder();
2853
+ if (restoredTempOrder && beforePaymentStatus !== void 0) {
2854
+ restoredTempOrder.payment_status = beforePaymentStatus;
2855
+ this.store.order.persistTempOrder();
2856
+ }
2857
+ await this.store.order.recalculateSummary({ createIfMissing: true });
2858
+ throw error;
2859
+ }
2860
+ }
2861
+ /**
2862
+ * 提交一次已由支付设备确认成功的非 Wallet 支付。
2863
+ *
2864
+ * 与 addOrderPayment 不同,本入口不会启动后台 fire-and-forget 同步;调用方会等待
2865
+ * 本次 payment、当前 pending Wallet 以及订单提交共同完成。任何同步失败都会恢复
2866
+ * 调用前的 payments 与 payment_status,便于 UI 安全解锁并重试。
2867
+ */
2868
+ async commitPaymentMethodPayment(params) {
2869
+ var _a, _b, _c, _d;
2870
+ if (!this.store.order)
2871
+ throw new Error("order 模块未初始化");
2872
+ const amount = Number(params.amount || 0);
2873
+ if (!Number.isFinite(amount) || amount <= 0) {
2874
+ throw new Error("支付金额必须大于 0");
2875
+ }
2876
+ let paymentMethods = this.getPaymentMethods();
2877
+ const findPaymentMethod = () => {
2878
+ const methodCode = String(params.paymentMethodCode || "").toUpperCase();
2879
+ return paymentMethods.find((method) => {
2880
+ const idMatched = params.paymentMethodId !== void 0 && String(method.id) === String(params.paymentMethodId);
2881
+ const codeMatched = Boolean(methodCode) && String(method.code || "").toUpperCase() === methodCode;
2882
+ return (idMatched || codeMatched) && method.enabled !== false && method.enable !== false;
2883
+ });
2884
+ };
2885
+ let paymentMethod = findPaymentMethod();
2886
+ if (!paymentMethod) {
2887
+ paymentMethods = await this.getPaymentMethodsAsync();
2888
+ paymentMethod = findPaymentMethod();
2889
+ }
2890
+ if (!paymentMethod) {
2891
+ throw new Error(
2892
+ `未找到可用的支付方式:${params.paymentMethodCode || params.paymentMethodId || ""}`
2893
+ );
2894
+ }
2895
+ const amountSnapshot = (_b = (_a = this.store.order).getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2896
+ const pendingWalletAmount = this.getPendingWalletPaymentAmount();
2897
+ const amountDue = import_decimal.default.max(
2898
+ new import_decimal.default((amountSnapshot == null ? void 0 : amountSnapshot.amountGap) || 0).minus(pendingWalletAmount),
2899
+ 0
2900
+ );
2901
+ if (amountDue.lte(0))
2902
+ throw new Error("当前订单没有待支付金额");
2903
+ if (new import_decimal.default(amount).gt(amountDue.plus(0.01))) {
2904
+ throw new Error("支付金额超过当前待支付金额");
2905
+ }
2906
+ const beforePayments = (0, import_lodash_es.cloneDeep)(this.store.order.getOrderPayments());
2907
+ const beforePaymentStatus = (_c = this.store.order.getTempOrder()) == null ? void 0 : _c.payment_status;
2908
+ const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
2909
+ const metadata = {
2910
+ ...params.metadata || {},
2911
+ unique_payment_number: ((_d = params.metadata) == null ? void 0 : _d.unique_payment_number) || (0, import_utils.createUuidV4)()
2912
+ };
2913
+ const serviceCharge = params.serviceCharge ? {
2914
+ amount: String(params.serviceCharge.amount || 0),
2915
+ percentage: String(params.serviceCharge.percentage || 0)
2916
+ } : void 0;
2917
+ const serviceFee = serviceCharge ? new import_decimal.default(params.originAmount ?? amount).times(serviceCharge.percentage || 0).plus(serviceCharge.amount || 0).toDecimalPlaces(2).toFixed(2) : void 0;
2918
+ const payments = this.store.order.addOrderPayment({
2919
+ ...params.paymentData || {},
2920
+ amount: amount.toFixed(2),
2921
+ ...params.originAmount !== void 0 ? { origin_amount: Number(params.originAmount).toFixed(2) } : {},
2922
+ code: paymentMethod.code,
2923
+ custom_payment_id: paymentMethod.id,
2924
+ name: paymentMethod.name,
2925
+ custom_payment_type: paymentMethod.type,
2926
+ voucher_id: 0,
2927
+ ...serviceCharge ? { service_charge: serviceCharge } : {},
2928
+ ...serviceFee !== void 0 ? { service_fee: serviceFee } : {},
2929
+ metadata,
2930
+ payment_time: paymentTimestamp,
2931
+ created_at: paymentTimestamp
2932
+ });
2933
+ const payment = payments.find(
2934
+ (item) => {
2935
+ var _a2;
2936
+ return ((_a2 = item == null ? void 0 : item.metadata) == null ? void 0 : _a2.unique_payment_number) === metadata.unique_payment_number;
2937
+ }
2938
+ );
2939
+ try {
2940
+ const syncResult = await this.syncPaymentsToOrder({
2941
+ payments,
2942
+ submitWhenPaid: true,
2943
+ smallTicketDataFlag: 1,
2944
+ confirmPendingVoucherPayments: true
2945
+ });
2946
+ if (this.store.payment) {
2947
+ const committed = this.getCommittedWalletAssets();
2948
+ const walletState = this.store.payment.wallet.setCommittedWalletAssets(
2949
+ committed.ids,
2950
+ committed.assets
2951
+ );
2952
+ await this.publishWalletAssetsState(walletState);
2953
+ }
2954
+ return {
2955
+ payment: payment || {},
2956
+ payments: this.store.order.getOrderPayments(),
2957
+ syncResult,
2958
+ isOrderFullyPaid: syncResult.isOrderFullyPaid
2959
+ };
2960
+ } catch (error) {
2961
+ this.store.order.setOrderPayments(beforePayments);
2962
+ const restoredTempOrder = this.store.order.getTempOrder();
2963
+ if (restoredTempOrder && beforePaymentStatus !== void 0) {
2964
+ restoredTempOrder.payment_status = beforePaymentStatus;
2965
+ this.store.order.persistTempOrder();
2966
+ }
2967
+ await this.store.order.recalculateSummary({ createIfMissing: true });
2968
+ throw error;
2969
+ }
2970
+ }
2971
+ /**
2972
+ * 按当前店铺的现金舍入配置计算金额,供现金支付 UI 使用。
2973
+ *
2974
+ * 舍入开关取自 CASHMANUAL 支付方式;舍入规则取自
2975
+ * otherParams.order_rounding_setting,金额算法统一由 PaymentModule 维护。
2976
+ */
2977
+ async roundAmount(params) {
2978
+ var _a, _b, _c;
2979
+ const amount = params.amount;
2980
+ const cashManualPayment = this.paymentMethodsCache.find(
2981
+ (paymentMethod) => paymentMethod.code === "CASHMANUAL"
2982
+ );
2983
+ if (!((_a = cashManualPayment == null ? void 0 : cashManualPayment.metadata) == null ? void 0 : _a.order_rounding_switch)) {
2984
+ return {
2985
+ originalAmount: amount.toString(),
2986
+ roundedAmount: amount.toString(),
2987
+ roundingDifference: "0.00"
2988
+ };
2989
+ }
2990
+ if (!this.payment) {
2991
+ throw new Error("payment 模块未初始化");
2992
+ }
2993
+ return this.payment.roundAmountAsync(
2994
+ amount,
2995
+ (_b = this.otherParams.order_rounding_setting) == null ? void 0 : _b.interval,
2996
+ (_c = this.otherParams.order_rounding_setting) == null ? void 0 : _c.type
2997
+ );
2998
+ }
2186
2999
  /**
2187
3000
  * 发送支付链接。
2188
3001
  *