@pisell/pisellos 0.10.2 → 0.10.3

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 (131) 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 +0 -9
  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/OpenData/index.d.ts +2 -0
  16. package/dist/modules/OpenData/index.js +8 -0
  17. package/dist/modules/Order/index.d.ts +28 -8
  18. package/dist/modules/Order/index.js +818 -503
  19. package/dist/modules/Order/payment-utils.d.ts +26 -0
  20. package/dist/modules/Order/payment-utils.js +225 -0
  21. package/dist/modules/Order/types.d.ts +35 -1
  22. package/dist/modules/Order/utils/orderCollectionIdentity.js +7 -2
  23. package/dist/modules/Order/utils.js +10 -6
  24. package/dist/modules/Payment/index.d.ts +2 -0
  25. package/dist/modules/Payment/index.js +79 -50
  26. package/dist/modules/Payment/types.d.ts +107 -28
  27. package/dist/modules/Payment/types.js +20 -3
  28. package/dist/modules/Payment/walletpass.d.ts +38 -1
  29. package/dist/modules/Payment/walletpass.js +917 -114
  30. package/dist/modules/ProductList/index.js +1 -1
  31. package/dist/modules/Rules/index.d.ts +3 -0
  32. package/dist/modules/Rules/index.js +130 -99
  33. package/dist/server/index.d.ts +16 -0
  34. package/dist/server/index.js +2084 -1188
  35. package/dist/server/modules/index.d.ts +1 -1
  36. package/dist/server/modules/order/index.d.ts +70 -4
  37. package/dist/server/modules/order/index.js +1816 -728
  38. package/dist/server/modules/order/types.d.ts +25 -3
  39. package/dist/server/modules/order/types.js +7 -1
  40. package/dist/solution/BaseSales/index.d.ts +111 -13
  41. package/dist/solution/BaseSales/index.js +1799 -446
  42. package/dist/solution/BaseSales/types.d.ts +55 -1
  43. package/dist/solution/BaseSales/types.js +2 -1
  44. package/dist/solution/BaseSales/utils/cartPromotion.d.ts +3 -1
  45. package/dist/solution/BaseSales/utils/cartPromotion.js +90 -31
  46. package/dist/solution/BaseSales/utils/parseSalesResponse.d.ts +6 -1
  47. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +6 -3
  48. package/dist/solution/BookingByStep/index.d.ts +1 -1
  49. package/dist/solution/BookingTicket/index.d.ts +7 -3
  50. package/dist/solution/BookingTicket/index.js +138 -52
  51. package/dist/solution/BookingTicket/types.d.ts +1 -0
  52. package/dist/solution/BookingTicket/utils/addProductDecision.js +6 -0
  53. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +8 -0
  54. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +173 -83
  55. package/dist/solution/BookingTicket/utils/weighingProductSku.d.ts +5 -0
  56. package/dist/solution/BookingTicket/utils/weighingProductSku.js +45 -0
  57. package/dist/solution/Sales/index.d.ts +1 -0
  58. package/dist/solution/Sales/index.js +10 -2
  59. package/dist/solution/ScanOrder/index.js +31 -20
  60. package/dist/solution/UnifiedBookingSales/index.js +23 -3
  61. package/dist/solution/VenueBooking/index.d.ts +1 -0
  62. package/dist/solution/VenueBooking/index.js +34 -24
  63. package/dist/types/index.d.ts +1 -0
  64. package/dist/utils/payment-number.d.ts +9 -0
  65. package/dist/utils/payment-number.js +69 -0
  66. package/lib/core/index.d.ts +2 -0
  67. package/lib/core/index.js +4 -0
  68. package/lib/model/strategy/adapter/promotion/adapter.d.ts +4 -0
  69. package/lib/model/strategy/adapter/promotion/adapter.js +20 -0
  70. package/lib/model/strategy/adapter/promotion/evaluator.d.ts +17 -0
  71. package/lib/model/strategy/adapter/promotion/evaluator.js +235 -0
  72. package/lib/model/strategy/adapter/promotion/examples.d.ts +86 -0
  73. package/lib/model/strategy/adapter/promotion/examples.js +91 -0
  74. package/lib/model/strategy/adapter/promotion/index.d.ts +1 -1
  75. package/lib/model/strategy/adapter/promotion/index.js +0 -49
  76. package/lib/model/strategy/adapter/promotion/type.d.ts +90 -2
  77. package/lib/model/strategy/adapter/promotion/type.js +2 -0
  78. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +2 -1
  79. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +2 -1
  80. package/lib/modules/OpenData/index.d.ts +2 -0
  81. package/lib/modules/OpenData/index.js +5 -0
  82. package/lib/modules/Order/index.d.ts +28 -8
  83. package/lib/modules/Order/index.js +233 -68
  84. package/lib/modules/Order/payment-utils.d.ts +26 -0
  85. package/lib/modules/Order/payment-utils.js +224 -0
  86. package/lib/modules/Order/types.d.ts +35 -1
  87. package/lib/modules/Order/utils/orderCollectionIdentity.js +3 -0
  88. package/lib/modules/Order/utils.js +11 -4
  89. package/lib/modules/Payment/index.d.ts +2 -0
  90. package/lib/modules/Payment/index.js +34 -13
  91. package/lib/modules/Payment/types.d.ts +107 -28
  92. package/lib/modules/Payment/types.js +4 -3
  93. package/lib/modules/Payment/walletpass.d.ts +38 -1
  94. package/lib/modules/Payment/walletpass.js +730 -21
  95. package/lib/modules/ProductList/index.js +9 -1
  96. package/lib/modules/Rules/index.d.ts +3 -0
  97. package/lib/modules/Rules/index.js +39 -10
  98. package/lib/server/index.d.ts +16 -0
  99. package/lib/server/index.js +677 -28
  100. package/lib/server/modules/index.d.ts +1 -1
  101. package/lib/server/modules/order/index.d.ts +70 -4
  102. package/lib/server/modules/order/index.js +818 -69
  103. package/lib/server/modules/order/types.d.ts +25 -3
  104. package/lib/server/modules/order/types.js +1 -0
  105. package/lib/solution/BaseSales/index.d.ts +111 -13
  106. package/lib/solution/BaseSales/index.js +882 -46
  107. package/lib/solution/BaseSales/types.d.ts +55 -1
  108. package/lib/solution/BaseSales/types.js +2 -1
  109. package/lib/solution/BaseSales/utils/cartPromotion.d.ts +3 -1
  110. package/lib/solution/BaseSales/utils/cartPromotion.js +63 -12
  111. package/lib/solution/BaseSales/utils/parseSalesResponse.d.ts +6 -1
  112. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +3 -2
  113. package/lib/solution/BookingByStep/index.d.ts +1 -1
  114. package/lib/solution/BookingTicket/index.d.ts +7 -3
  115. package/lib/solution/BookingTicket/index.js +63 -9
  116. package/lib/solution/BookingTicket/types.d.ts +1 -0
  117. package/lib/solution/BookingTicket/utils/addProductDecision.js +4 -0
  118. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +8 -0
  119. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +37 -5
  120. package/lib/solution/BookingTicket/utils/weighingProductSku.d.ts +5 -0
  121. package/lib/solution/BookingTicket/utils/weighingProductSku.js +63 -0
  122. package/lib/solution/Sales/index.d.ts +1 -0
  123. package/lib/solution/Sales/index.js +5 -3
  124. package/lib/solution/ScanOrder/index.js +8 -0
  125. package/lib/solution/UnifiedBookingSales/index.js +10 -2
  126. package/lib/solution/VenueBooking/index.d.ts +1 -0
  127. package/lib/solution/VenueBooking/index.js +13 -6
  128. package/lib/types/index.d.ts +1 -0
  129. package/lib/utils/payment-number.d.ts +9 -0
  130. package/lib/utils/payment-number.js +64 -0
  131. package/package.json +1 -1
@@ -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");
@@ -836,6 +1011,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
836
1011
  var _a, _b, _c, _d;
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();
@@ -896,8 +1072,10 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
896
1072
  }
897
1073
  });
898
1074
  this.currentSalesDetail = null;
1075
+ this.paymentNumberDevicePrefix = null;
899
1076
  this.queuedServerOrderChanges = [];
900
1077
  this.salesDetailLoadSequence += 1;
1078
+ this.walletAssetsRefreshSequence += 1;
901
1079
  await this.core.effects.emit(`${this.name}:onDestroy`, {});
902
1080
  super.destroy();
903
1081
  }
@@ -929,13 +1107,16 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
929
1107
  const message = loadedRecord && (loadedRecord.message || loadedRecord.msg) || `加载销售详情失败: ${lookup}`;
930
1108
  throw new Error(message);
931
1109
  }
932
- const remoteRecord = preloadedSalesDetail ?? loadedRecord.data;
1110
+ const remoteRecord = filterPendingPaymentsFromLoadedSalesDetail(
1111
+ preloadedSalesDetail ?? loadedRecord.data
1112
+ );
933
1113
  const currentTempOrder = params.merge ? this.store.order.getTempOrder() : null;
934
- const record = params.merge ? mergeSalesDetailRecordWithTempOrder(
1114
+ const mergedRecord = params.merge ? mergeSalesDetailRecordWithTempOrder(
935
1115
  currentTempOrder,
936
1116
  remoteRecord,
937
1117
  "preserve-local"
938
1118
  ) : remoteRecord;
1119
+ const record = filterPendingPaymentsFromLoadedSalesDetail(mergedRecord);
939
1120
  return await this.hydrateLatestLoadedSalesDetail(record, loadSequence);
940
1121
  } finally {
941
1122
  this.salesDetailLoadInFlightCount = Math.max(
@@ -1111,6 +1292,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1111
1292
  // 重置 tempOrder 与与上一单强相关的运行态(resource/entryPaxNumber/enabledReservationRuleProducts),
1112
1293
  // 适用于从支付页通过 react-router 跳回继续下单时清理残留数据
1113
1294
  async restoreOrder() {
1295
+ var _a;
1114
1296
  try {
1115
1297
  if (!this.store.order) {
1116
1298
  throw new Error("scanOrder 解决方案需要 order 模块支持");
@@ -1119,6 +1301,12 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1119
1301
  this.currentSalesDetail = null;
1120
1302
  this.discountConfigCacheKey = null;
1121
1303
  this.hasManualDiscountSelection = false;
1304
+ const wallet = (_a = this.store.payment) == null ? void 0 : _a.wallet;
1305
+ if (wallet) {
1306
+ this.walletAssetsRefreshSequence += 1;
1307
+ wallet.clearAllCache();
1308
+ await this.publishWalletAssetsState(wallet.getWalletAssetsState());
1309
+ }
1122
1310
  await this.effectsEmit("onTempOrderReplaced", { tempOrder });
1123
1311
  if (this.syncAppDataToTempOrder(tempOrder) && this.isTempOrderPersistEnabled()) {
1124
1312
  this.store.order.persistTempOrder();
@@ -1531,6 +1719,7 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1531
1719
  }
1532
1720
  return {
1533
1721
  isAvailable: raw.isAvailable,
1722
+ ...raw.isAccepted !== void 0 ? { isAccepted: raw.isAccepted } : {},
1534
1723
  type: raw.type,
1535
1724
  unavailableReason: raw.unavailableReason,
1536
1725
  scannedDiscountList: raw.scannedDiscountList
@@ -1727,6 +1916,20 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1727
1916
  };
1728
1917
  return this.shouldUseCheckoutSyncTask() ? this.store.order.submitTempOrder(submitParams) : this.store.order.submitTempOrderAsync(submitParams);
1729
1918
  }
1919
+ async saveSalesOrderDraft(params) {
1920
+ var _a, _b, _c, _d;
1921
+ if (!this.store.order) {
1922
+ throw new Error("BaseSales 解决方案需要 order 模块支持");
1923
+ }
1924
+ return this.store.order.saveTempOrderAsDraft({
1925
+ cacheId: this.cacheId,
1926
+ platform: (params == null ? void 0 : params.platform) ?? ((_a = this.otherParams) == null ? void 0 : _a.platform),
1927
+ businessCode: (params == null ? void 0 : params.businessCode) || ((_b = this.otherParams) == null ? void 0 : _b.businessCode) || ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1928
+ channel: (params == null ? void 0 : params.channel) ?? this.getSubmitOrderSalesChannel(),
1929
+ type: (params == null ? void 0 : params.type) ?? ((_d = this.otherParams) == null ? void 0 : _d.type),
1930
+ ...(params == null ? void 0 : params.enhancePayload) !== void 0 ? { enhancePayload: params.enhancePayload } : {}
1931
+ });
1932
+ }
1730
1933
  async submitTempOrderAsync(params) {
1731
1934
  var _a, _b, _c, _d;
1732
1935
  if (!this.store.order) {
@@ -1943,8 +2146,29 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1943
2146
  }
1944
2147
  }
1945
2148
  }
1946
- /** 追加单个支付项到当前订单。 */
2149
+ /**
2150
+ * 同步兼容入口。无法等待 IoT 短号时,按调用当下的 device_id 或 LOCAL 生成。
2151
+ */
1947
2152
  addOrderPayment(payment) {
2153
+ const hasPaymentNumber = String(
2154
+ payment.payment_number || ""
2155
+ ).trim() !== "";
2156
+ return this.addOrderPaymentWithDevicePrefix(
2157
+ payment,
2158
+ hasPaymentNumber ? "LOCAL" : this.getPaymentNumberDevicePrefixSync()
2159
+ );
2160
+ }
2161
+ /**
2162
+ * 创建新支付项时优先使用业务解决方案初始化阶段缓存的设备短号;
2163
+ * 未缓存的通用 BaseSales 保持实时读取设备信息的兼容语义。
2164
+ */
2165
+ async addOrderPaymentAsync(payment) {
2166
+ const paymentRecord = payment;
2167
+ const hasPaymentNumber = String(paymentRecord.payment_number || "").trim() !== "";
2168
+ const devicePrefix = hasPaymentNumber ? "LOCAL" : await this.getPaymentNumberDevicePrefixAsync();
2169
+ return this.addOrderPaymentWithDevicePrefix(payment, devicePrefix);
2170
+ }
2171
+ addOrderPaymentWithDevicePrefix(payment, devicePrefix) {
1948
2172
  var _a;
1949
2173
  if (!this.store.order)
1950
2174
  throw new Error("order 模块未初始化");
@@ -1961,21 +2185,26 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1961
2185
  if (shopWalletPassId !== void 0 && shopWalletPassId !== null) {
1962
2186
  metadata.shop_wallet_pass_id = shopWalletPassId;
1963
2187
  }
1964
- if (!metadata.unique_payment_number) {
1965
- metadata.unique_payment_number = (0, import_utils.createUuidV4)();
1966
- }
2188
+ const normalizedPaymentRecord = (0, import_payment_utils.ensureOrderPaymentNumber)(
2189
+ paymentRecord,
2190
+ devicePrefix,
2191
+ import_utils.createUuidV4
2192
+ );
1967
2193
  const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
1968
2194
  const paymentTime = paymentRecord.payment_time ?? paymentTimestamp;
1969
2195
  const createdAt = paymentRecord.created_at ?? paymentTimestamp;
1970
2196
  const serviceCharge = paymentRecord.service_charge && typeof paymentRecord.service_charge === "object" ? paymentRecord.service_charge : null;
1971
2197
  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
2198
  const payments = this.store.order.addOrderPayment({
1973
- ...paymentRecord,
2199
+ ...normalizedPaymentRecord,
1974
2200
  ...calculatedServiceFee !== void 0 ? { service_fee: calculatedServiceFee } : {},
1975
2201
  metadata,
1976
2202
  payment_time: paymentTime,
1977
2203
  created_at: createdAt
1978
2204
  });
2205
+ if (paymentRecord.status === "payment_pending") {
2206
+ return payments;
2207
+ }
1979
2208
  const amountSnapshot = this.store.order.getOrderAmountSnapshot();
1980
2209
  const syncState = this.store.order.getOrderSyncState();
1981
2210
  if (amountSnapshot) {
@@ -1997,10 +2226,73 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
1997
2226
  return payments;
1998
2227
  }
1999
2228
  /** 更新当前订单中的指定支付项。 */
2000
- updateOrderPayment(paymentIdentity, updates) {
2229
+ async updateOrderPayment(paymentIdentity, updates, options = {}) {
2230
+ var _a, _b, _c;
2001
2231
  if (!this.store.order)
2002
2232
  throw new Error("order 模块未初始化");
2003
- return this.store.order.updateOrderPayment(paymentIdentity, updates);
2233
+ const matchMode = options.matchBy === "compat" || options.matchBy === "legacy" ? "compat" : "payment_number";
2234
+ const previousMatch = (0, import_payment_utils.resolveOrderPaymentIdentity)(
2235
+ this.store.order.getOrderPayments(),
2236
+ paymentIdentity,
2237
+ matchMode
2238
+ );
2239
+ const previousPayment = previousMatch == null ? void 0 : previousMatch.payment;
2240
+ if ((previousPayment == null ? void 0 : previousPayment.status) === "paid" && !options.applyUpdatesWhenPaid) {
2241
+ const currentPayments = this.store.order.getOrderPayments();
2242
+ let syncResult2;
2243
+ if (options.submitWhenPaid && options.forceSubmitIfPaid) {
2244
+ syncResult2 = await this.syncPaymentsToOrder({
2245
+ payments: currentPayments,
2246
+ paymentStatus: this.getPaymentStatusForSync(currentPayments),
2247
+ submitWhenPaid: true,
2248
+ smallTicketDataFlag: options.smallTicketDataFlag ?? 1
2249
+ });
2250
+ }
2251
+ return {
2252
+ updated: false,
2253
+ payment: previousPayment,
2254
+ payments: currentPayments,
2255
+ summary: ((_a = this.store.order.getOrderAmountSnapshot()) == null ? void 0 : _a.summary) || null,
2256
+ ...syncResult2 !== void 0 ? { syncResult: syncResult2 } : {}
2257
+ };
2258
+ }
2259
+ const result = await this.store.order.updateOrderPayment(paymentIdentity, updates, {
2260
+ matchBy: matchMode
2261
+ });
2262
+ let draftResult;
2263
+ let draftError;
2264
+ if (options.persistDraft !== false) {
2265
+ try {
2266
+ draftResult = await this.saveSalesOrderDraft();
2267
+ } catch (error) {
2268
+ draftError = error;
2269
+ this.logError("updateOrderPayment: 保存支付草稿失败", {
2270
+ paymentIdentity,
2271
+ error: error instanceof Error ? error.message : String(error)
2272
+ });
2273
+ if (!options.submitWhenPaid)
2274
+ throw error;
2275
+ }
2276
+ }
2277
+ const becamePaid = (previousPayment == null ? void 0 : previousPayment.status) !== "paid" && ((_b = result.payment) == null ? void 0 : _b.status) === "paid";
2278
+ const shouldSubmit = Boolean(
2279
+ options.submitWhenPaid && ((_c = result.payment) == null ? void 0 : _c.status) === "paid" && (becamePaid || options.forceSubmitIfPaid)
2280
+ );
2281
+ let syncResult;
2282
+ if (shouldSubmit) {
2283
+ syncResult = await this.syncPaymentsToOrder({
2284
+ payments: result.payments,
2285
+ paymentStatus: this.getPaymentStatusForSync(result.payments),
2286
+ submitWhenPaid: true,
2287
+ smallTicketDataFlag: options.smallTicketDataFlag ?? 1
2288
+ });
2289
+ }
2290
+ return {
2291
+ ...result,
2292
+ ...draftResult !== void 0 ? { draftResult } : {},
2293
+ ...draftError !== void 0 ? { draftError } : {},
2294
+ ...syncResult !== void 0 ? { syncResult } : {}
2295
+ };
2004
2296
  }
2005
2297
  /** 删除当前订单中的指定支付项。 */
2006
2298
  deleteOrderPayment(paymentIdentity) {
@@ -2014,10 +2306,24 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2014
2306
  throw new Error("order 模块未初始化");
2015
2307
  return this.store.order.updateVoucherOrderPayments(payments, options);
2016
2308
  }
2309
+ async updateVoucherOrderPaymentsAsync(payments, options) {
2310
+ if (!this.store.order)
2311
+ throw new Error("order 模块未初始化");
2312
+ return this.store.order.updateVoucherOrderPaymentsAsync(payments, options);
2313
+ }
2017
2314
  confirmPendingVoucherPayments() {
2018
2315
  if (!this.store.order)
2019
2316
  throw new Error("order 模块未初始化");
2020
- return this.store.order.confirmPendingVoucherPayments();
2317
+ const payments = this.store.order.confirmPendingVoucherPayments();
2318
+ if (this.store.payment) {
2319
+ const committed = this.getCommittedWalletAssets();
2320
+ const state = this.store.payment.wallet.setCommittedWalletAssets(
2321
+ committed.ids,
2322
+ committed.assets
2323
+ );
2324
+ void this.publishWalletAssetsState(state);
2325
+ }
2326
+ return payments;
2021
2327
  }
2022
2328
  discardPendingVoucherPayments() {
2023
2329
  if (!this.store.order)
@@ -2078,24 +2384,14 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2078
2384
  });
2079
2385
  return walletProducts;
2080
2386
  }
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();
2387
+ buildWalletInitBusinessData(params) {
2388
+ var _a;
2389
+ const snapshot = (_a = this.store.order) == null ? void 0 : _a.getOrderSnapshot();
2087
2390
  const tempOrder = snapshot == null ? void 0 : snapshot.tempOrder;
2088
2391
  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 = {
2392
+ if (!tempOrder || !amount)
2393
+ return null;
2394
+ return {
2099
2395
  customer_id: tempOrder.customer_id ? Number(tempOrder.customer_id) : void 0,
2100
2396
  holder: tempOrder.holder,
2101
2397
  amountInfo: {
@@ -2109,11 +2405,29 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2109
2405
  is_price_include_tax: tempOrder.is_price_include_tax ?? this.otherParams.is_price_include_tax ?? 1,
2110
2406
  ...snapshot.identity.orderId ? { payment_order_id: String(snapshot.identity.orderId) } : {}
2111
2407
  };
2408
+ }
2409
+ async initWalletData(params) {
2410
+ var _a;
2411
+ if (!this.store.order)
2412
+ throw new Error("order 模块未初始化");
2413
+ if (!this.store.payment)
2414
+ throw new Error("payment 模块未初始化");
2415
+ const snapshot = this.store.order.getOrderSnapshot();
2416
+ const walletBusinessData = this.buildWalletInitBusinessData(params);
2417
+ if (!walletBusinessData) {
2418
+ return {
2419
+ walletRecommendList: [],
2420
+ userIdentificationCodes: [],
2421
+ transformList: [],
2422
+ noApplicableVoucher: [],
2423
+ products: []
2424
+ };
2425
+ }
2112
2426
  const result = await this.store.payment.wallet.initializeWalletDataFromBusinessAsync(
2113
2427
  walletBusinessData
2114
2428
  );
2115
2429
  await this.core.effects.emit(`${this.name}:onWalletDataInitialized`, {
2116
- orderId: snapshot.identity.orderId,
2430
+ orderId: (_a = snapshot == null ? void 0 : snapshot.identity) == null ? void 0 : _a.orderId,
2117
2431
  customerId: walletBusinessData.customer_id,
2118
2432
  walletBusinessData: {
2119
2433
  customer_id: walletBusinessData.customer_id,
@@ -2124,6 +2438,208 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2124
2438
  });
2125
2439
  return result;
2126
2440
  }
2441
+ getCommittedWalletAssets() {
2442
+ var _a, _b;
2443
+ const payments = ((_b = (_a = this.store.order) == null ? void 0 : _a.getOrderPayments) == null ? void 0 : _b.call(_a)) || [];
2444
+ const committed = payments.filter((payment) => {
2445
+ const voucherId = payment == null ? void 0 : payment.voucher_id;
2446
+ if (voucherId === void 0 || voucherId === null || voucherId === 0) {
2447
+ return false;
2448
+ }
2449
+ 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) !== "";
2450
+ });
2451
+ return {
2452
+ ids: committed.map((payment) => payment.voucher_id),
2453
+ assets: committed.map((payment) => {
2454
+ var _a2;
2455
+ const fundRecord = (payment == null ? void 0 : payment.fund_record) || {};
2456
+ const walletPassName = fundRecord.wallet_pass_name;
2457
+ const title = walletPassName && typeof walletPassName === "object" ? walletPassName.default || Object.values(walletPassName)[0] : walletPassName;
2458
+ const code = String((payment == null ? void 0 : payment.code) || "").toUpperCase();
2459
+ const tag = ((_a2 = Object.entries(WALLET_PAYMENT_CODE_BY_TAG).find(
2460
+ ([, paymentCode]) => paymentCode === code
2461
+ )) == null ? void 0 : _a2[0]) || fundRecord.tag;
2462
+ return {
2463
+ id: payment.voucher_id,
2464
+ voucher_id: payment.voucher_id,
2465
+ code: fundRecord.code,
2466
+ tag,
2467
+ product_name: title || payment.name,
2468
+ name: title || payment.name,
2469
+ amount: Number(payment.amount || 0),
2470
+ _available_max_amount: Number(payment.amount || 0),
2471
+ unified_available_status: 1,
2472
+ _unified_available_status: 1,
2473
+ _committed_payment: payment
2474
+ };
2475
+ })
2476
+ };
2477
+ }
2478
+ async publishWalletAssetsState(state) {
2479
+ await this.effectsEmit(import_types.BaseSalesHookNames.onWalletAssetsStateChanged, {
2480
+ state
2481
+ });
2482
+ return state;
2483
+ }
2484
+ async syncSelectedWalletAssets(state) {
2485
+ if (!this.store.order || !this.store.payment) {
2486
+ throw new Error("订单或支付模块未初始化");
2487
+ }
2488
+ let paymentMethods = this.getPaymentMethods();
2489
+ if (!paymentMethods.length && state.selectedItems.length) {
2490
+ paymentMethods = await this.getPaymentMethodsAsync();
2491
+ }
2492
+ const methodByCode = new Map(
2493
+ paymentMethods.map((method) => [String(method.code || "").toUpperCase(), method])
2494
+ );
2495
+ const preparePayments = this.store.payment.wallet.formatWalletPassList2PreparePayments(
2496
+ state.selectedItems
2497
+ );
2498
+ const selectedAssetById = new Map(
2499
+ state.selectedItems.map((asset) => [
2500
+ String(getSharedWalletAssetId(asset)),
2501
+ asset
2502
+ ])
2503
+ );
2504
+ const voucherPayments = preparePayments.flatMap((item) => {
2505
+ const asset = selectedAssetById.get(String(item.voucher_id));
2506
+ 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();
2507
+ const paymentMethod = methodByCode.get(paymentCode);
2508
+ const formattedAmount = Number(item.amount);
2509
+ const amount = Number.isFinite(formattedAmount) && formattedAmount > 0 ? formattedAmount : getSharedWalletAssetAmount(asset);
2510
+ if (!asset || !paymentMethod || !Number.isFinite(amount) || amount <= 0) {
2511
+ return [];
2512
+ }
2513
+ const walletPassUseValue = getSharedWalletPassUseValue({
2514
+ asset,
2515
+ amount,
2516
+ paymentMethod
2517
+ });
2518
+ return [
2519
+ {
2520
+ amount: amount.toFixed(2),
2521
+ code: paymentMethod.code,
2522
+ custom_payment_id: paymentMethod.id,
2523
+ name: paymentMethod.name,
2524
+ type: paymentMethod.type,
2525
+ voucher_id: item.voucher_id,
2526
+ wallet_pass_usage_unit: item.wallet_pass_usage_unit,
2527
+ wallet_pass_use_value: walletPassUseValue,
2528
+ fund_record: buildSharedWalletFundRecord({
2529
+ asset,
2530
+ amount,
2531
+ paymentMethod
2532
+ })
2533
+ }
2534
+ ];
2535
+ });
2536
+ const payments = this.updateVoucherOrderPayments(voucherPayments, {
2537
+ status: "payment_pending"
2538
+ });
2539
+ await this.store.order.recalculateSummary({ createIfMissing: true });
2540
+ return payments;
2541
+ }
2542
+ /** 读取购物车与 Shared Checkout 共用的钱包资产状态。 */
2543
+ getWalletAssetsState() {
2544
+ if (!this.store.payment)
2545
+ throw new Error("payment 模块未初始化");
2546
+ return this.store.payment.wallet.getWalletAssetsState();
2547
+ }
2548
+ /** 导出 Shared Checkout 跨运行时恢复所需的钱包状态与搜索缓存。 */
2549
+ exportWalletAssetsSnapshot() {
2550
+ if (!this.store.payment)
2551
+ throw new Error("payment 模块未初始化");
2552
+ return this.store.payment.wallet.exportWalletAssetsSnapshot();
2553
+ }
2554
+ /** 配置仅影响 Wallet Assets,不改变 Promotion/Voucher 选择流程。 */
2555
+ configureWalletAssetsBehavior(options) {
2556
+ if (!this.store.payment)
2557
+ throw new Error("payment 模块未初始化");
2558
+ this.store.payment.wallet.configureWalletAssetsBehavior(options);
2559
+ }
2560
+ /**
2561
+ * 恢复 Shared Checkout 钱包快照,并把选择重新同步为订单 pending payment。
2562
+ */
2563
+ async importWalletAssetsSnapshot(snapshot) {
2564
+ if (!this.store.payment)
2565
+ throw new Error("payment 模块未初始化");
2566
+ const state = this.store.payment.wallet.importWalletAssetsSnapshot(snapshot);
2567
+ await this.syncSelectedWalletAssets(state);
2568
+ return this.publishWalletAssetsState(state);
2569
+ }
2570
+ /**
2571
+ * 基于当前订单快照刷新钱包资产。商品变化保留并重验选择;客户变化强制清空。
2572
+ */
2573
+ async refreshWalletAssets(params) {
2574
+ if (!this.store.order)
2575
+ throw new Error("order 模块未初始化");
2576
+ if (!this.store.payment)
2577
+ throw new Error("payment 模块未初始化");
2578
+ const refreshSequence = ++this.walletAssetsRefreshSequence;
2579
+ const wallet = this.store.payment.wallet;
2580
+ const businessData = this.buildWalletInitBusinessData(params);
2581
+ if (!businessData) {
2582
+ wallet.clearAllCache();
2583
+ const emptyState = wallet.getWalletAssetsState();
2584
+ this.updateVoucherOrderPayments([], { status: "payment_pending" });
2585
+ return this.publishWalletAssetsState(emptyState);
2586
+ }
2587
+ const previousState = wallet.getWalletAssetsState();
2588
+ const hasPreviousWalletContext = previousState.status !== "idle" || previousState.items.length > 0 || previousState.selectedIds.length > 0 || previousState.customerId !== void 0;
2589
+ const customerChanged = hasPreviousWalletContext && String(previousState.customerId ?? "") !== String(businessData.customer_id ?? "");
2590
+ if (customerChanged) {
2591
+ const clearedState = wallet.clearWalletAssetSelection();
2592
+ this.updateVoucherOrderPayments([], { status: "payment_pending" });
2593
+ await this.publishWalletAssetsState(clearedState);
2594
+ }
2595
+ const refreshTask = wallet.refreshWalletAssetsFromBusinessAsync(
2596
+ businessData,
2597
+ {
2598
+ preserveSelection: (params == null ? void 0 : params.preserveSelection) !== false && !customerChanged
2599
+ }
2600
+ );
2601
+ await this.publishWalletAssetsState(wallet.getWalletAssetsState());
2602
+ let state = await refreshTask;
2603
+ if (refreshSequence !== this.walletAssetsRefreshSequence) {
2604
+ return wallet.getWalletAssetsState();
2605
+ }
2606
+ if (state.status !== "error") {
2607
+ const committed = this.getCommittedWalletAssets();
2608
+ state = wallet.setCommittedWalletAssets(committed.ids, committed.assets);
2609
+ }
2610
+ await this.syncSelectedWalletAssets(state);
2611
+ return this.publishWalletAssetsState(state);
2612
+ }
2613
+ /** 选择或取消单张钱包资产,并立即同步 pending wallet payments。 */
2614
+ async selectWalletAsset(params) {
2615
+ if (!this.store.payment)
2616
+ throw new Error("payment 模块未初始化");
2617
+ const state = this.store.payment.wallet.selectWalletAsset(params.assetId, {
2618
+ selected: params.selected,
2619
+ source: params.source
2620
+ });
2621
+ await this.syncSelectedWalletAssets(state);
2622
+ return this.publishWalletAssetsState(state);
2623
+ }
2624
+ /** 扫码精确查券;仅可用资产会被自动选中。 */
2625
+ async scanWalletAsset(code) {
2626
+ if (!this.store.payment)
2627
+ throw new Error("payment 模块未初始化");
2628
+ const result = await this.store.payment.wallet.scanWalletAssetAsync(code);
2629
+ if (result.type === "normalCode") {
2630
+ await this.syncSelectedWalletAssets(result.state);
2631
+ await this.publishWalletAssetsState(result.state);
2632
+ }
2633
+ return result;
2634
+ }
2635
+ /** 清空全部未确认钱包选择,已支付钱包项由 Order 模块继续保留。 */
2636
+ async clearWalletAssetSelection() {
2637
+ if (!this.store.payment)
2638
+ throw new Error("payment 模块未初始化");
2639
+ const state = this.store.payment.wallet.clearWalletAssetSelection();
2640
+ await this.syncSelectedWalletAssets(state);
2641
+ return this.publishWalletAssetsState(state);
2642
+ }
2127
2643
  /**
2128
2644
  * 更新当前订单客户字段。
2129
2645
  *
@@ -2160,28 +2676,348 @@ var BaseSalesImpl = class extends import_BaseModule.BaseModule {
2160
2676
  getPaymentMethods() {
2161
2677
  return [...this.paymentMethodsCache];
2162
2678
  }
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);
2679
+ findCashPaymentMethod(paymentMethods) {
2680
+ return paymentMethods.find((method) => {
2681
+ const identifiers = [method == null ? void 0 : method.code, method == null ? void 0 : method.type, method == null ? void 0 : method.tag].map(
2682
+ (value) => String(value || "").toUpperCase()
2683
+ );
2684
+ return identifiers.includes("CASHMANUAL") && (method == null ? void 0 : method.enabled) !== false && (method == null ? void 0 : method.enable) !== false;
2685
+ });
2686
+ }
2687
+ getPendingWalletPaymentAmount(payments = ((_b) => (_b = ((_a) => (_a = this.store.order) == null ? void 0 : _a.getOrderPayments)()) == null ? void 0 : _b.call(_a))() || []) {
2688
+ return payments.reduce((total, payment) => {
2689
+ if ((payment == null ? void 0 : payment.status) !== "payment_pending" || (payment == null ? void 0 : payment.voucher_id) === void 0 || Number(payment.voucher_id) === 0) {
2690
+ return total;
2691
+ }
2692
+ try {
2693
+ return total.plus(payment.amount || 0).plus(payment.rounding_amount || 0);
2694
+ } catch {
2695
+ return total;
2696
+ }
2697
+ }, new import_decimal.default(0));
2698
+ }
2699
+ /** 读取现金 action 所需的支付方式、待付金额和快捷金额。 */
2700
+ async getCashPaymentConfig() {
2701
+ var _a, _b, _c, _d, _e, _f;
2702
+ if (!this.store.payment)
2703
+ throw new Error("payment 模块未初始化");
2704
+ let paymentMethods = this.getPaymentMethods();
2705
+ let paymentMethod = this.findCashPaymentMethod(paymentMethods);
2706
+ if (!paymentMethod) {
2707
+ paymentMethods = await this.getPaymentMethodsAsync();
2708
+ paymentMethod = this.findCashPaymentMethod(paymentMethods);
2709
+ }
2710
+ const amountSnapshot = (_b = (_a = this.store.order) == null ? void 0 : _a.getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2711
+ const pendingWalletAmount = this.getPendingWalletPaymentAmount();
2712
+ const amountDue = import_decimal.default.max(
2713
+ new import_decimal.default((amountSnapshot == null ? void 0 : amountSnapshot.amountGap) || 0).minus(pendingWalletAmount),
2714
+ 0
2715
+ ).toDecimalPlaces(2).toNumber();
2716
+ 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";
2717
+ const recommendedAmounts = amountDue > 0 ? this.store.payment.cash.getRecommendedAmount(amountDue, currency) : [];
2718
+ return {
2719
+ available: Boolean(paymentMethod && amountDue > 0),
2720
+ paymentMethod,
2721
+ amountDue,
2722
+ recommendedAmounts
2723
+ };
2724
+ }
2725
+ /**
2726
+ * 确认足额覆盖订单的 pending Wallet 支付并提交订单。
2727
+ *
2728
+ * Order 模块在构造提交参数时将 pending voucher 转为 paid;只有提交成功后
2729
+ * 才同步 Wallet committed 状态。失败时恢复调用前 payments,允许用户重试。
2730
+ */
2731
+ async confirmWalletPayment() {
2732
+ var _a, _b, _c, _d, _e;
2733
+ if (!this.store.order)
2734
+ throw new Error("order 模块未初始化");
2735
+ const beforePayments = (0, import_lodash_es.cloneDeep)(this.store.order.getOrderPayments());
2736
+ const pendingWalletAmount = this.getPendingWalletPaymentAmount(beforePayments);
2737
+ if (pendingWalletAmount.lte(0)) {
2738
+ throw new Error("当前订单没有待确认的 Wallet 支付");
2739
+ }
2740
+ const amountSnapshot = (_b = (_a = this.store.order).getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2741
+ const effectiveAmountDue = import_decimal.default.max(
2742
+ new import_decimal.default((amountSnapshot == null ? void 0 : amountSnapshot.amountGap) || 0).minus(pendingWalletAmount),
2743
+ 0
2744
+ );
2745
+ if (effectiveAmountDue.gt(0.01)) {
2746
+ throw new Error("Wallet 支付尚未覆盖全部待支付金额");
2178
2747
  }
2179
- const roundedAmount = roundedQuotient.times(interval).toDecimalPlaces(2);
2748
+ const beforePaymentStatus = (_c = this.store.order.getTempOrder()) == null ? void 0 : _c.payment_status;
2749
+ let submitResult;
2750
+ try {
2751
+ submitResult = await this.submitSalesOrder({
2752
+ smallTicketDataFlag: 1,
2753
+ confirmPendingVoucherPayments: true
2754
+ });
2755
+ if (isRejectedSalesSubmitResult(submitResult)) {
2756
+ throw new Error(getSalesSubmitErrorMessage(submitResult));
2757
+ }
2758
+ } catch (error) {
2759
+ this.store.order.setOrderPayments(beforePayments);
2760
+ const restoredTempOrder = this.store.order.getTempOrder();
2761
+ if (restoredTempOrder && beforePaymentStatus !== void 0) {
2762
+ restoredTempOrder.payment_status = beforePaymentStatus;
2763
+ this.store.order.persistTempOrder();
2764
+ }
2765
+ await this.store.order.recalculateSummary({ createIfMissing: true });
2766
+ throw error;
2767
+ }
2768
+ if (this.store.payment) {
2769
+ try {
2770
+ const committed = this.getCommittedWalletAssets();
2771
+ const walletState = this.store.payment.wallet.setCommittedWalletAssets(
2772
+ committed.ids,
2773
+ committed.assets
2774
+ );
2775
+ await this.publishWalletAssetsState(walletState);
2776
+ } catch (error) {
2777
+ this.logWarning("confirmWalletPayment: Wallet committed 状态同步失败", {
2778
+ error: error instanceof Error ? error.message : String(error)
2779
+ });
2780
+ }
2781
+ }
2782
+ const latestAmountSnapshot = (_e = (_d = this.store.order).getOrderAmountSnapshot) == null ? void 0 : _e.call(_d);
2180
2783
  return {
2181
- originalAmount: amount.toFixed(2),
2182
- roundedAmount: roundedAmount.toFixed(2),
2183
- roundingDifference: roundedAmount.minus(amount).toFixed(2)
2784
+ submitResult,
2785
+ payments: this.store.order.getOrderPayments(),
2786
+ isOrderFullyPaid: new import_decimal.default(
2787
+ (latestAmountSnapshot == null ? void 0 : latestAmountSnapshot.amountGap) || 0
2788
+ ).lte(0)
2789
+ };
2790
+ }
2791
+ /**
2792
+ * 购物车现金直付:写入现金记录并等待支付同步完成。
2793
+ * 同步失败会恢复调用前 payments(包含 Wallet pending 状态)。
2794
+ */
2795
+ async payCash(params) {
2796
+ var _a, _b, _c, _d, _e, _f;
2797
+ if (!this.store.order)
2798
+ throw new Error("order 模块未初始化");
2799
+ const amount = Number(params.amount || 0);
2800
+ if (!Number.isFinite(amount) || amount <= 0) {
2801
+ throw new Error("现金支付金额必须大于 0");
2802
+ }
2803
+ const config = await this.getCashPaymentConfig();
2804
+ const paymentMethod = config.paymentMethod;
2805
+ if (!paymentMethod)
2806
+ throw new Error("未找到可用的 CASHMANUAL 支付方式");
2807
+ if (config.amountDue <= 0)
2808
+ throw new Error("当前订单没有待支付金额");
2809
+ const roundingAmount = Number(params.roundingAmount || 0);
2810
+ const effectivePaymentAmount = new import_decimal.default(amount).minus(roundingAmount);
2811
+ if (effectivePaymentAmount.gt(new import_decimal.default(config.amountDue).plus(0.01))) {
2812
+ throw new Error("现金支付金额超过当前待支付金额");
2813
+ }
2814
+ const beforePayments = (0, import_lodash_es.cloneDeep)(this.store.order.getOrderPayments());
2815
+ const beforePaymentStatus = (_a = this.store.order.getTempOrder()) == null ? void 0 : _a.payment_status;
2816
+ const uniquePaymentNumber = (0, import_utils.createUuidV4)();
2817
+ const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
2818
+ const actualPaidAmount = Number(params.actualPaidAmount ?? amount);
2819
+ const changeAmount = Number(params.changeAmount || 0);
2820
+ const shopWalletPassId = (_b = this.otherParams) == null ? void 0 : _b.shop_wallet_pass_id;
2821
+ if (!Number.isFinite(actualPaidAmount) || actualPaidAmount + 0.01 < amount) {
2822
+ throw new Error("顾客实收现金不能小于支付金额");
2823
+ }
2824
+ (_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, {
2825
+ module: "till",
2826
+ key: "open_till",
2827
+ data: { type: "cash" }
2828
+ });
2829
+ const payments = this.store.order.addOrderPayment({
2830
+ amount: amount.toFixed(2),
2831
+ code: paymentMethod.code,
2832
+ custom_payment_id: paymentMethod.id,
2833
+ name: paymentMethod.name,
2834
+ custom_payment_type: paymentMethod.type,
2835
+ voucher_id: 0,
2836
+ rounding_amount: roundingAmount.toFixed(2),
2837
+ metadata: {
2838
+ unique_payment_number: uniquePaymentNumber,
2839
+ ...shopWalletPassId !== void 0 && shopWalletPassId !== null ? { shop_wallet_pass_id: shopWalletPassId } : {},
2840
+ actual_paid_amount: Number.isFinite(actualPaidAmount) ? actualPaidAmount : amount,
2841
+ change_given_amount: Number.isFinite(changeAmount) ? changeAmount : 0
2842
+ },
2843
+ payment_time: paymentTimestamp,
2844
+ created_at: paymentTimestamp
2845
+ });
2846
+ const payment = payments.find(
2847
+ (item) => {
2848
+ var _a2;
2849
+ return ((_a2 = item == null ? void 0 : item.metadata) == null ? void 0 : _a2.unique_payment_number) === uniquePaymentNumber;
2850
+ }
2851
+ );
2852
+ try {
2853
+ const syncResult = await this.syncPaymentsToOrder({
2854
+ payments,
2855
+ submitWhenPaid: true,
2856
+ smallTicketDataFlag: 1,
2857
+ confirmPendingVoucherPayments: true
2858
+ });
2859
+ if (this.store.payment) {
2860
+ const committed = this.getCommittedWalletAssets();
2861
+ const walletState = this.store.payment.wallet.setCommittedWalletAssets(
2862
+ committed.ids,
2863
+ committed.assets
2864
+ );
2865
+ await this.publishWalletAssetsState(walletState);
2866
+ }
2867
+ return {
2868
+ payment: payment || {},
2869
+ payments: this.store.order.getOrderPayments(),
2870
+ syncResult,
2871
+ isOrderFullyPaid: syncResult.isOrderFullyPaid
2872
+ };
2873
+ } catch (error) {
2874
+ this.store.order.setOrderPayments(beforePayments);
2875
+ const restoredTempOrder = this.store.order.getTempOrder();
2876
+ if (restoredTempOrder && beforePaymentStatus !== void 0) {
2877
+ restoredTempOrder.payment_status = beforePaymentStatus;
2878
+ this.store.order.persistTempOrder();
2879
+ }
2880
+ await this.store.order.recalculateSummary({ createIfMissing: true });
2881
+ throw error;
2882
+ }
2883
+ }
2884
+ /**
2885
+ * 提交一次已由支付设备确认成功的非 Wallet 支付。
2886
+ *
2887
+ * 与 addOrderPayment 不同,本入口不会启动后台 fire-and-forget 同步;调用方会等待
2888
+ * 本次 payment、当前 pending Wallet 以及订单提交共同完成。任何同步失败都会恢复
2889
+ * 调用前的 payments 与 payment_status,便于 UI 安全解锁并重试。
2890
+ */
2891
+ async commitPaymentMethodPayment(params) {
2892
+ var _a, _b, _c, _d;
2893
+ if (!this.store.order)
2894
+ throw new Error("order 模块未初始化");
2895
+ const amount = Number(params.amount || 0);
2896
+ if (!Number.isFinite(amount) || amount <= 0) {
2897
+ throw new Error("支付金额必须大于 0");
2898
+ }
2899
+ let paymentMethods = this.getPaymentMethods();
2900
+ const findPaymentMethod = () => {
2901
+ const methodCode = String(params.paymentMethodCode || "").toUpperCase();
2902
+ return paymentMethods.find((method) => {
2903
+ const idMatched = params.paymentMethodId !== void 0 && String(method.id) === String(params.paymentMethodId);
2904
+ const codeMatched = Boolean(methodCode) && String(method.code || "").toUpperCase() === methodCode;
2905
+ return (idMatched || codeMatched) && method.enabled !== false && method.enable !== false;
2906
+ });
2907
+ };
2908
+ let paymentMethod = findPaymentMethod();
2909
+ if (!paymentMethod) {
2910
+ paymentMethods = await this.getPaymentMethodsAsync();
2911
+ paymentMethod = findPaymentMethod();
2912
+ }
2913
+ if (!paymentMethod) {
2914
+ throw new Error(
2915
+ `未找到可用的支付方式:${params.paymentMethodCode || params.paymentMethodId || ""}`
2916
+ );
2917
+ }
2918
+ const amountSnapshot = (_b = (_a = this.store.order).getOrderAmountSnapshot) == null ? void 0 : _b.call(_a);
2919
+ const pendingWalletAmount = this.getPendingWalletPaymentAmount();
2920
+ const amountDue = import_decimal.default.max(
2921
+ new import_decimal.default((amountSnapshot == null ? void 0 : amountSnapshot.amountGap) || 0).minus(pendingWalletAmount),
2922
+ 0
2923
+ );
2924
+ if (amountDue.lte(0))
2925
+ throw new Error("当前订单没有待支付金额");
2926
+ if (new import_decimal.default(amount).gt(amountDue.plus(0.01))) {
2927
+ throw new Error("支付金额超过当前待支付金额");
2928
+ }
2929
+ const beforePayments = (0, import_lodash_es.cloneDeep)(this.store.order.getOrderPayments());
2930
+ const beforePaymentStatus = (_c = this.store.order.getTempOrder()) == null ? void 0 : _c.payment_status;
2931
+ const paymentTimestamp = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
2932
+ const metadata = {
2933
+ ...params.metadata || {},
2934
+ unique_payment_number: ((_d = params.metadata) == null ? void 0 : _d.unique_payment_number) || (0, import_utils.createUuidV4)()
2184
2935
  };
2936
+ const serviceCharge = params.serviceCharge ? {
2937
+ amount: String(params.serviceCharge.amount || 0),
2938
+ percentage: String(params.serviceCharge.percentage || 0)
2939
+ } : void 0;
2940
+ const serviceFee = serviceCharge ? new import_decimal.default(params.originAmount ?? amount).times(serviceCharge.percentage || 0).plus(serviceCharge.amount || 0).toDecimalPlaces(2).toFixed(2) : void 0;
2941
+ const payments = this.store.order.addOrderPayment({
2942
+ ...params.paymentData || {},
2943
+ amount: amount.toFixed(2),
2944
+ ...params.originAmount !== void 0 ? { origin_amount: Number(params.originAmount).toFixed(2) } : {},
2945
+ code: paymentMethod.code,
2946
+ custom_payment_id: paymentMethod.id,
2947
+ name: paymentMethod.name,
2948
+ custom_payment_type: paymentMethod.type,
2949
+ voucher_id: 0,
2950
+ ...serviceCharge ? { service_charge: serviceCharge } : {},
2951
+ ...serviceFee !== void 0 ? { service_fee: serviceFee } : {},
2952
+ metadata,
2953
+ payment_time: paymentTimestamp,
2954
+ created_at: paymentTimestamp
2955
+ });
2956
+ const payment = payments.find(
2957
+ (item) => {
2958
+ var _a2;
2959
+ return ((_a2 = item == null ? void 0 : item.metadata) == null ? void 0 : _a2.unique_payment_number) === metadata.unique_payment_number;
2960
+ }
2961
+ );
2962
+ try {
2963
+ const syncResult = await this.syncPaymentsToOrder({
2964
+ payments,
2965
+ submitWhenPaid: true,
2966
+ smallTicketDataFlag: 1,
2967
+ confirmPendingVoucherPayments: true
2968
+ });
2969
+ if (this.store.payment) {
2970
+ const committed = this.getCommittedWalletAssets();
2971
+ const walletState = this.store.payment.wallet.setCommittedWalletAssets(
2972
+ committed.ids,
2973
+ committed.assets
2974
+ );
2975
+ await this.publishWalletAssetsState(walletState);
2976
+ }
2977
+ return {
2978
+ payment: payment || {},
2979
+ payments: this.store.order.getOrderPayments(),
2980
+ syncResult,
2981
+ isOrderFullyPaid: syncResult.isOrderFullyPaid
2982
+ };
2983
+ } catch (error) {
2984
+ this.store.order.setOrderPayments(beforePayments);
2985
+ const restoredTempOrder = this.store.order.getTempOrder();
2986
+ if (restoredTempOrder && beforePaymentStatus !== void 0) {
2987
+ restoredTempOrder.payment_status = beforePaymentStatus;
2988
+ this.store.order.persistTempOrder();
2989
+ }
2990
+ await this.store.order.recalculateSummary({ createIfMissing: true });
2991
+ throw error;
2992
+ }
2993
+ }
2994
+ /**
2995
+ * 按当前店铺的现金舍入配置计算金额,供现金支付 UI 使用。
2996
+ *
2997
+ * 舍入开关取自 CASHMANUAL 支付方式;舍入规则取自
2998
+ * otherParams.order_rounding_setting,金额算法统一由 PaymentModule 维护。
2999
+ */
3000
+ async roundAmount(params) {
3001
+ var _a, _b, _c;
3002
+ const amount = params.amount;
3003
+ const cashManualPayment = this.paymentMethodsCache.find(
3004
+ (paymentMethod) => paymentMethod.code === "CASHMANUAL"
3005
+ );
3006
+ if (!((_a = cashManualPayment == null ? void 0 : cashManualPayment.metadata) == null ? void 0 : _a.order_rounding_switch)) {
3007
+ return {
3008
+ originalAmount: amount.toString(),
3009
+ roundedAmount: amount.toString(),
3010
+ roundingDifference: "0.00"
3011
+ };
3012
+ }
3013
+ if (!this.payment) {
3014
+ throw new Error("payment 模块未初始化");
3015
+ }
3016
+ return this.payment.roundAmountAsync(
3017
+ amount,
3018
+ (_b = this.otherParams.order_rounding_setting) == null ? void 0 : _b.interval,
3019
+ (_c = this.otherParams.order_rounding_setting) == null ? void 0 : _c.type
3020
+ );
2185
3021
  }
2186
3022
  /**
2187
3023
  * 发送支付链接。