@pisell/pisellos 2.3.29 → 2.3.30

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 (98) hide show
  1. package/dist/model/strategy/adapter/index.d.ts +0 -4
  2. package/dist/model/strategy/adapter/index.js +1 -5
  3. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  4. package/dist/modules/Discount/index.d.ts +2 -5
  5. package/dist/modules/Discount/index.js +7 -30
  6. package/dist/modules/Discount/types.d.ts +0 -4
  7. package/dist/modules/Order/index.d.ts +28 -10
  8. package/dist/modules/Order/index.js +747 -498
  9. package/dist/modules/Order/payment-utils.d.ts +23 -0
  10. package/dist/modules/Order/payment-utils.js +203 -0
  11. package/dist/modules/Order/types.d.ts +33 -3
  12. package/dist/modules/Order/utils.js +4 -4
  13. package/dist/modules/Payment/index.d.ts +2 -0
  14. package/dist/modules/Payment/index.js +78 -49
  15. package/dist/modules/Payment/types.d.ts +26 -24
  16. package/dist/modules/Payment/types.js +2 -0
  17. package/dist/modules/Product/index.d.ts +1 -1
  18. package/dist/modules/Product/types.d.ts +0 -22
  19. package/dist/modules/ProductList/index.d.ts +1 -1
  20. package/dist/modules/ProductList/index.js +2 -4
  21. package/dist/modules/ProductList/types.d.ts +0 -2
  22. package/dist/server/index.d.ts +14 -50
  23. package/dist/server/index.js +1975 -1395
  24. package/dist/server/modules/order/index.d.ts +40 -3
  25. package/dist/server/modules/order/index.js +1200 -501
  26. package/dist/server/modules/order/types.d.ts +11 -3
  27. package/dist/server/modules/order/types.js +1 -1
  28. package/dist/server/modules/products/index.d.ts +7 -26
  29. package/dist/server/modules/products/index.js +76 -167
  30. package/dist/server/modules/products/types.d.ts +0 -14
  31. package/dist/solution/BaseSales/index.d.ts +33 -5
  32. package/dist/solution/BaseSales/index.js +622 -345
  33. package/dist/solution/BaseSales/utils/parseSalesResponse.d.ts +6 -1
  34. package/dist/solution/BookingByStep/index.d.ts +1 -1
  35. package/dist/solution/BookingTicket/index.d.ts +1 -1
  36. package/dist/solution/BookingTicket/index.js +2 -1
  37. package/dist/solution/BookingTicket/types.d.ts +0 -2
  38. package/dist/solution/ShopDiscount/index.js +14 -15
  39. package/dist/utils/payment-number.d.ts +9 -0
  40. package/dist/utils/payment-number.js +69 -0
  41. package/lib/model/strategy/adapter/index.d.ts +0 -4
  42. package/lib/model/strategy/adapter/index.js +2 -13
  43. package/lib/modules/Discount/index.d.ts +2 -5
  44. package/lib/modules/Discount/index.js +3 -23
  45. package/lib/modules/Discount/types.d.ts +0 -4
  46. package/lib/modules/Order/index.d.ts +28 -10
  47. package/lib/modules/Order/index.js +181 -73
  48. package/lib/modules/Order/payment-utils.d.ts +23 -0
  49. package/lib/modules/Order/payment-utils.js +193 -0
  50. package/lib/modules/Order/types.d.ts +33 -3
  51. package/lib/modules/Order/utils.js +2 -3
  52. package/lib/modules/Payment/index.d.ts +2 -0
  53. package/lib/modules/Payment/index.js +33 -12
  54. package/lib/modules/Payment/types.d.ts +26 -24
  55. package/lib/modules/Product/index.d.ts +1 -1
  56. package/lib/modules/Product/types.d.ts +0 -22
  57. package/lib/modules/ProductList/index.d.ts +1 -1
  58. package/lib/modules/ProductList/index.js +2 -4
  59. package/lib/modules/ProductList/types.d.ts +0 -2
  60. package/lib/server/index.d.ts +14 -50
  61. package/lib/server/index.js +633 -214
  62. package/lib/server/modules/order/index.d.ts +40 -3
  63. package/lib/server/modules/order/index.js +434 -31
  64. package/lib/server/modules/order/types.d.ts +11 -3
  65. package/lib/server/modules/products/index.d.ts +7 -26
  66. package/lib/server/modules/products/index.js +35 -114
  67. package/lib/server/modules/products/types.d.ts +0 -14
  68. package/lib/solution/BaseSales/index.d.ts +33 -5
  69. package/lib/solution/BaseSales/index.js +170 -19
  70. package/lib/solution/BaseSales/utils/parseSalesResponse.d.ts +6 -1
  71. package/lib/solution/BookingByStep/index.d.ts +1 -1
  72. package/lib/solution/BookingTicket/index.d.ts +1 -1
  73. package/lib/solution/BookingTicket/index.js +2 -1
  74. package/lib/solution/BookingTicket/types.d.ts +0 -2
  75. package/lib/solution/ShopDiscount/index.js +1 -2
  76. package/lib/utils/payment-number.d.ts +9 -0
  77. package/lib/utils/payment-number.js +64 -0
  78. package/package.json +1 -1
  79. package/dist/model/strategy/adapter/dataVariant/adapter.d.ts +0 -50
  80. package/dist/model/strategy/adapter/dataVariant/adapter.js +0 -167
  81. package/dist/model/strategy/adapter/dataVariant/evaluator.d.ts +0 -89
  82. package/dist/model/strategy/adapter/dataVariant/evaluator.js +0 -780
  83. package/dist/model/strategy/adapter/dataVariant/examples.d.ts +0 -39
  84. package/dist/model/strategy/adapter/dataVariant/examples.js +0 -277
  85. package/dist/model/strategy/adapter/dataVariant/index.d.ts +0 -4
  86. package/dist/model/strategy/adapter/dataVariant/index.js +0 -4
  87. package/dist/model/strategy/adapter/dataVariant/type.d.ts +0 -148
  88. package/dist/model/strategy/adapter/dataVariant/type.js +0 -54
  89. package/lib/model/strategy/adapter/dataVariant/adapter.d.ts +0 -50
  90. package/lib/model/strategy/adapter/dataVariant/adapter.js +0 -149
  91. package/lib/model/strategy/adapter/dataVariant/evaluator.d.ts +0 -89
  92. package/lib/model/strategy/adapter/dataVariant/evaluator.js +0 -583
  93. package/lib/model/strategy/adapter/dataVariant/examples.d.ts +0 -39
  94. package/lib/model/strategy/adapter/dataVariant/examples.js +0 -293
  95. package/lib/model/strategy/adapter/dataVariant/index.d.ts +0 -4
  96. package/lib/model/strategy/adapter/dataVariant/index.js +0 -38
  97. package/lib/model/strategy/adapter/dataVariant/type.d.ts +0 -148
  98. package/lib/model/strategy/adapter/dataVariant/type.js +0 -31
@@ -37,6 +37,8 @@ var import_types = require("./types");
37
37
  var import_utils = require("./utils");
38
38
  var import_utils2 = require("../Product/utils");
39
39
  var import_dayjs = __toESM(require("dayjs"));
40
+ var import_payment_utils = require("./payment-utils");
41
+ var import_payment_number = require("../../utils/payment-number");
40
42
  var import_cartPromotion = require("../../solution/BaseSales/utils/cartPromotion");
41
43
  var import_utils3 = require("../../solution/ScanOrder/utils");
42
44
  var import_manualProductDiscount = require("./utils/manualProductDiscount");
@@ -309,15 +311,12 @@ var OrderModule = class extends import_BaseModule.BaseModule {
309
311
  if (!this.store.summary) {
310
312
  this.store.summary = (0, import_utils.createEmptySummary)();
311
313
  }
312
- if (!Array.isArray(this.store.availableWalletIds)) {
313
- this.store.availableWalletIds = [];
314
- }
315
314
  this.request = this.core.getPlugin("request");
316
- const appPlugin = this.core.getPlugin("app");
317
- if (!appPlugin) {
315
+ this.appPlugin = this.core.getPlugin("app");
316
+ if (!this.appPlugin) {
318
317
  throw new Error("Order 模块需要 app 插件支持");
319
318
  }
320
- const app = appPlugin.getApp();
319
+ const app = this.appPlugin.getApp();
321
320
  this.logger = app.logger;
322
321
  this.window = this.core.getPlugin("window");
323
322
  const otherParams = options.otherParams || {};
@@ -439,19 +438,15 @@ var OrderModule = class extends import_BaseModule.BaseModule {
439
438
  async loadDiscountConfig(params) {
440
439
  var _a, _b, _c, _d, _e, _f, _g;
441
440
  const orderId = params.orderId || ((_a = this.store.tempOrder) == null ? void 0 : _a.order_id) || void 0;
442
- const prepareConfigResult = await ((_b = this.store.discount) == null ? void 0 : _b.loadPrepareConfig({
441
+ const discountList = await ((_b = this.store.discount) == null ? void 0 : _b.loadPrepareConfig({
443
442
  customer_id: params.customerId,
444
443
  action: params.action || (orderId ? "edit" : "create"),
445
444
  with_good_pass: 1,
446
445
  with_discount_card: 1,
447
446
  with_wallet_pass_holder: 1,
448
- with_available_wallet_flag: 1,
449
- with_available_wallet_pass_flag: 1,
450
447
  request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
451
448
  ...orderId ? { order_id: orderId } : {}
452
449
  }));
453
- const discountList = prepareConfigResult == null ? void 0 : prepareConfigResult.discountList;
454
- this.store.availableWalletIds = (prepareConfigResult == null ? void 0 : prepareConfigResult.availableWalletIds) || [];
455
450
  if (discountList) {
456
451
  const currentDiscountList = ((_c = this.store.discount) == null ? void 0 : _c.getDiscountList()) || [];
457
452
  const currentEditDiscounts = currentDiscountList.filter((discount) => discount == null ? void 0 : discount.isEditMode);
@@ -485,9 +480,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
485
480
  var _a;
486
481
  return ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList()) || [];
487
482
  }
488
- getAvailableWalletIds() {
489
- return Array.isArray(this.store.availableWalletIds) ? [...this.store.availableWalletIds] : [];
490
- }
491
483
  async syncScannedDiscountsToOriginalDiscountList(discountList) {
492
484
  var _a, _b, _c, _d;
493
485
  const scanDiscounts = (discountList || []).filter((discount) => discount == null ? void 0 : discount.isScan);
@@ -1053,17 +1045,40 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1053
1045
  const depositPaidAmount = this.calculateDepositPaidAmount(tempOrder.payments || []);
1054
1046
  return depositPaidAmount.lt(depositAmount) ? "deposit" : "normal";
1055
1047
  }
1048
+ getPaymentNumberAppData(key) {
1049
+ var _a, _b, _c, _d, _e;
1050
+ const appPlugin = this.appPlugin;
1051
+ if (!appPlugin)
1052
+ return void 0;
1053
+ const getData = (_a = appPlugin.getData) == null ? void 0 : _a.call(appPlugin);
1054
+ if (typeof getData === "function")
1055
+ return getData(key);
1056
+ const app = appPlugin.getApp();
1057
+ const coreData = (_e = (_c = (_b = app == null ? void 0 : app.models) == null ? void 0 : _b.getStore) == null ? void 0 : (_d = _c.call(_b)).getDataByModel) == null ? void 0 : _e.call(_d, "core", "core");
1058
+ return coreData == null ? void 0 : coreData[key];
1059
+ }
1060
+ getPaymentNumberDevicePrefixSync() {
1061
+ return (0, import_payment_number.resolvePaymentNumberDevicePrefixFromDeviceId)(
1062
+ (key) => this.getPaymentNumberAppData(key)
1063
+ );
1064
+ }
1065
+ getPaymentNumberDevicePrefixAsync() {
1066
+ return (0, import_payment_number.resolvePaymentNumberDevicePrefix)(
1067
+ (key) => this.getPaymentNumberAppData(key)
1068
+ );
1069
+ }
1056
1070
  normalizePaymentSource(payment, options) {
1057
1071
  const paymentRecord = payment;
1058
1072
  const metadata = paymentRecord.metadata && typeof paymentRecord.metadata === "object" ? { ...paymentRecord.metadata } : {};
1059
- if (!metadata.unique_payment_number) {
1060
- metadata.unique_payment_number = (0, import_utils.createUuidV4)();
1061
- }
1062
- const normalized = {
1063
- ...paymentRecord,
1064
- metadata,
1065
- origin_amount: paymentRecord.origin_amount ?? paymentRecord.amount ?? "0.00"
1066
- };
1073
+ const normalized = (0, import_payment_utils.ensureOrderPaymentNumber)(
1074
+ {
1075
+ ...paymentRecord,
1076
+ metadata,
1077
+ origin_amount: paymentRecord.origin_amount ?? paymentRecord.amount ?? "0.00"
1078
+ },
1079
+ (options == null ? void 0 : options.devicePrefix) || this.getPaymentNumberDevicePrefixSync(),
1080
+ import_utils.createUuidV4
1081
+ );
1067
1082
  if (paymentRecord.status !== void 0) {
1068
1083
  normalized.status = paymentRecord.status;
1069
1084
  } else if ((options == null ? void 0 : options.defaultPaid) !== false) {
@@ -2412,7 +2427,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2412
2427
  }
2413
2428
  const nextCustomerId = tempOrder.customer_id ?? null;
2414
2429
  if (String(previousCustomerId ?? "") !== String(nextCustomerId ?? "")) {
2415
- this.store.availableWalletIds = [];
2416
2430
  (0, import_utils.clearTempOrderHolderAssignments)(tempOrder);
2417
2431
  this.clearCustomerBoundDiscounts(tempOrder);
2418
2432
  this.applyDiscount();
@@ -2452,7 +2466,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2452
2466
  tempOrder.customer = null;
2453
2467
  if (tempOrder._extend)
2454
2468
  delete tempOrder._extend.customerSnapshot;
2455
- this.store.availableWalletIds = [];
2456
2469
  this.clearCustomerBoundDiscounts(tempOrder);
2457
2470
  this.persistTempOrder();
2458
2471
  this.saveDraftInBackground();
@@ -2484,17 +2497,36 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2484
2497
  * 用一组支付来源覆盖当前订单支付项。
2485
2498
  *
2486
2499
  * 入参允许来自 PaymentModule 的 PaymentItem,内部统一映射为 Sales 协议:
2487
- * uuid -> metadata.unique_payment_number,id -> custom_payment_id,
2500
+ * 新支付来源的 uuid 会作为 payment_number 的唯一号段,id -> custom_payment_id,
2488
2501
  * isSynced 等运行态字段不会进入 tempOrder.payments。
2489
2502
  */
2490
2503
  setOrderPayments(payments) {
2491
2504
  const tempOrder = this.ensureTempOrder();
2492
- tempOrder.payments = (0, import_utils.mapPaymentItemsToOrderPayments)(payments);
2505
+ tempOrder.payments = (0, import_utils.mapPaymentItemsToOrderPayments)(
2506
+ (payments || []).map((payment) => this.normalizePaymentSource(payment, { defaultPaid: false }))
2507
+ );
2493
2508
  this.persistTempOrder();
2494
2509
  return tempOrder.payments;
2495
2510
  }
2496
- /** 追加单个支付项,并立即持久化当前 tempOrder。 */
2511
+ /** 同步兼容入口:按调用当下的 device_id 或 LOCAL 生成支付编号。 */
2497
2512
  addOrderPayment(payment) {
2513
+ const hasPaymentNumber = String(
2514
+ payment.payment_number || ""
2515
+ ).trim() !== "";
2516
+ return this.addOrderPaymentWithDevicePrefix(
2517
+ payment,
2518
+ hasPaymentNumber ? "LOCAL" : this.getPaymentNumberDevicePrefixSync()
2519
+ );
2520
+ }
2521
+ /** 异步入口:创建支付项时读取最新 IoT 设备短号。 */
2522
+ async addOrderPaymentAsync(payment) {
2523
+ const hasPaymentNumber = String(
2524
+ payment.payment_number || ""
2525
+ ).trim() !== "";
2526
+ const devicePrefix = hasPaymentNumber ? "LOCAL" : await this.getPaymentNumberDevicePrefixAsync();
2527
+ return this.addOrderPaymentWithDevicePrefix(payment, devicePrefix);
2528
+ }
2529
+ addOrderPaymentWithDevicePrefix(payment, devicePrefix) {
2498
2530
  this.logInfo("addOrderPayment", {
2499
2531
  payment
2500
2532
  });
@@ -2507,7 +2539,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2507
2539
  type: orderPaymentType,
2508
2540
  order_payment_type: orderPaymentType
2509
2541
  },
2510
- { defaultPaid: true }
2542
+ { defaultPaid: true, devicePrefix }
2511
2543
  )
2512
2544
  ]);
2513
2545
  tempOrder.payments = [...tempOrder.payments || [], ...mapped];
@@ -2520,57 +2552,55 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2520
2552
  return tempOrder.payments;
2521
2553
  }
2522
2554
  /**
2523
- * 按支付唯一号、后端支付 ID、自定义支付方式 ID 或旧 uuid 更新支付项。
2524
- *
2525
- * 该方法服务 PaymentModal 的 void / 编辑场景;更新 metadata 时会做浅合并,
2526
- * 避免覆盖 unique_payment_number、现金实付/找零等已有元数据。
2555
+ * 默认按支付唯一号精确更新;仅显式指定 legacy 时兼容历史支付标识。
2556
+ * metadata 与 transactions 会分别合并,避免覆盖支付会话号和已有交易记录。
2527
2557
  */
2528
- updateOrderPayment(paymentIdentity, updates) {
2558
+ async updateOrderPayment(paymentIdentity, updates, options = {}) {
2529
2559
  const tempOrder = this.ensureTempOrder();
2530
2560
  const identity = String(paymentIdentity);
2531
- tempOrder.payments = (tempOrder.payments || []).map((payment) => {
2532
- var _a;
2533
- const uniquePaymentNumber = (_a = payment == null ? void 0 : payment.metadata) == null ? void 0 : _a.unique_payment_number;
2534
- const orderPaymentId = payment == null ? void 0 : payment.order_payment_id;
2535
- const customPaymentId = payment == null ? void 0 : payment.custom_payment_id;
2536
- const uuid = payment == null ? void 0 : payment.uuid;
2537
- const matched = [
2538
- uniquePaymentNumber,
2539
- orderPaymentId,
2540
- customPaymentId,
2541
- uuid
2542
- ].some((value) => value !== void 0 && String(value) === identity);
2543
- if (!matched)
2561
+ const matchMode = options.matchBy === "compat" || options.matchBy === "legacy" ? "compat" : "payment_number";
2562
+ const matchedPayment = (0, import_payment_utils.resolveOrderPaymentIdentity)(
2563
+ tempOrder.payments || [],
2564
+ identity,
2565
+ matchMode
2566
+ );
2567
+ if (!matchedPayment) {
2568
+ throw new Error(`未找到支付项: ${identity}`);
2569
+ }
2570
+ let updatedPayment = null;
2571
+ tempOrder.payments = (tempOrder.payments || []).map((payment, index) => {
2572
+ if (index !== matchedPayment.index)
2544
2573
  return payment;
2545
- return {
2546
- ...payment,
2574
+ const nextPayment = (0, import_payment_utils.mergeOrderPaymentRecord)(payment, {
2547
2575
  ...updates,
2548
- metadata: {
2549
- ...payment.metadata || {},
2550
- ...updates.metadata || {}
2551
- }
2552
- };
2576
+ updated_at: updates.updated_at || (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
2577
+ });
2578
+ updatedPayment = nextPayment;
2579
+ return nextPayment;
2553
2580
  });
2554
2581
  this.persistTempOrder();
2555
- return tempOrder.payments;
2582
+ const summary = await this.recalculateSummary({ createIfMissing: true });
2583
+ this.persistTempOrder();
2584
+ const payments = tempOrder.payments;
2585
+ return {
2586
+ updated: true,
2587
+ payment: payments[matchedPayment.index] || updatedPayment,
2588
+ payments,
2589
+ summary
2590
+ };
2556
2591
  }
2557
2592
  /** 从当前订单支付项中移除指定支付项。 */
2558
2593
  deleteOrderPayment(paymentIdentity) {
2559
2594
  const tempOrder = this.ensureTempOrder();
2560
2595
  const identity = String(paymentIdentity);
2561
- tempOrder.payments = (tempOrder.payments || []).filter((payment) => {
2562
- var _a;
2563
- const uniquePaymentNumber = (_a = payment == null ? void 0 : payment.metadata) == null ? void 0 : _a.unique_payment_number;
2564
- const orderPaymentId = payment == null ? void 0 : payment.order_payment_id;
2565
- const customPaymentId = payment == null ? void 0 : payment.custom_payment_id;
2566
- const uuid = payment == null ? void 0 : payment.uuid;
2567
- return ![
2568
- uniquePaymentNumber,
2569
- orderPaymentId,
2570
- customPaymentId,
2571
- uuid
2572
- ].some((value) => value !== void 0 && String(value) === identity);
2573
- });
2596
+ const matchedPayment = (0, import_payment_utils.resolveOrderPaymentIdentity)(
2597
+ tempOrder.payments || [],
2598
+ identity,
2599
+ "compat"
2600
+ );
2601
+ if (!matchedPayment)
2602
+ return tempOrder.payments;
2603
+ tempOrder.payments = (tempOrder.payments || []).filter((_, index) => index !== matchedPayment.index);
2574
2604
  this.persistTempOrder();
2575
2605
  return tempOrder.payments;
2576
2606
  }
@@ -2679,7 +2709,10 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2679
2709
  payments.map(
2680
2710
  (payment) => this.normalizePaymentSource(
2681
2711
  normalizeVoucherPaymentStatus(withVoucherPaymentType(payment)),
2682
- { defaultPaid: false }
2712
+ {
2713
+ defaultPaid: false,
2714
+ devicePrefix: options == null ? void 0 : options.devicePrefix
2715
+ }
2683
2716
  )
2684
2717
  )
2685
2718
  ).filter((payment) => {
@@ -2730,6 +2763,14 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2730
2763
  });
2731
2764
  return tempOrder.payments;
2732
2765
  }
2766
+ async updateVoucherOrderPaymentsAsync(payments, options) {
2767
+ const needsPaymentNumber = (payments || []).some((payment) => String(payment.payment_number || "").trim() === "");
2768
+ const devicePrefix = needsPaymentNumber ? await this.getPaymentNumberDevicePrefixAsync() : "LOCAL";
2769
+ return this.updateVoucherOrderPayments(payments, {
2770
+ ...options,
2771
+ devicePrefix
2772
+ });
2773
+ }
2733
2774
  async shouldMergeProductToOrder(params) {
2734
2775
  var _a;
2735
2776
  const onBeforeMergeProductToOrder = (_a = this.orderHooks) == null ? void 0 : _a.onBeforeMergeProductToOrder;
@@ -3496,6 +3537,38 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3496
3537
  await this.saveDraft();
3497
3538
  return tempOrder;
3498
3539
  }
3540
+ async saveTempOrderAsDraft(params) {
3541
+ var _a, _b, _c, _d, _e;
3542
+ const tempOrder = this.ensureTempOrder();
3543
+ this.ensureExternalSaleNumber(tempOrder);
3544
+ this.persistTempOrder();
3545
+ const latestSummary = await this.recalculateSummary({ createIfMissing: true }) || this.store.summary || (0, import_utils.createEmptySummary)();
3546
+ const payload = (0, import_utils.buildSubmitPayload)({
3547
+ tempOrder,
3548
+ cacheId: (params == null ? void 0 : params.cacheId) ?? this.cacheId,
3549
+ platform: (params == null ? void 0 : params.platform) || ((_a = this.otherParams) == null ? void 0 : _a.platform),
3550
+ businessCode: (params == null ? void 0 : params.businessCode) ?? ((_b = this.otherParams) == null ? void 0 : _b.businessCode) ?? ((_c = this.otherParams) == null ? void 0 : _c.business_code),
3551
+ channel: params == null ? void 0 : params.channel,
3552
+ type: (params == null ? void 0 : params.type) ?? ((_d = this.otherParams) == null ? void 0 : _d.type),
3553
+ summary: latestSummary,
3554
+ enhance: params == null ? void 0 : params.enhancePayload
3555
+ });
3556
+ if (!payload.created_at) {
3557
+ payload.created_at = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
3558
+ }
3559
+ payload.need_sync = 0;
3560
+ payload.is_draft_order = 1;
3561
+ this.logInfo("saveTempOrderAsDraft calling sales draft", {
3562
+ orderId: payload.order_id,
3563
+ externalSaleNumber: payload.external_sale_number,
3564
+ productsCount: ((_e = payload.products) == null ? void 0 : _e.length) || 0
3565
+ });
3566
+ return this.request.post("/order/sales/draft", payload, {
3567
+ osServer: true,
3568
+ customToast: () => {
3569
+ }
3570
+ });
3571
+ }
3499
3572
  /**
3500
3573
  * 提交当前 Sales tempOrder。
3501
3574
  *
@@ -3696,8 +3769,13 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3696
3769
  }
3697
3770
  async syncPaymentsToOrder(params) {
3698
3771
  const tempOrder = this.ensureTempOrder();
3772
+ const needsPaymentNumber = (params.payments || []).some((payment) => String(payment.payment_number || "").trim() === "");
3773
+ const devicePrefix = needsPaymentNumber ? await this.getPaymentNumberDevicePrefixAsync() : "LOCAL";
3699
3774
  const mappedPayments = (0, import_utils.mapPaymentItemsToOrderPayments)(
3700
- params.payments || []
3775
+ (params.payments || []).map((payment) => this.normalizePaymentSource(payment, {
3776
+ defaultPaid: false,
3777
+ devicePrefix
3778
+ }))
3701
3779
  );
3702
3780
  const shouldConfirmPendingVoucherPayments = params.confirmPendingVoucherPayments ?? params.submitWhenPaid === true;
3703
3781
  const effectivePayments = shouldConfirmPendingVoucherPayments ? this.confirmPendingVoucherPaymentsInList(mappedPayments) : params.confirmPendingVoucherPayments === false ? this.discardPendingVoucherPaymentsFromList(mappedPayments) : mappedPayments;
@@ -4073,6 +4151,12 @@ var OrderModule = class extends import_BaseModule.BaseModule {
4073
4151
  }
4074
4152
  }
4075
4153
  const nextTempOrder = this.normalizeTempOrderForRuntime(raw, { makeEditMark: true });
4154
+ const sourceLastOrderInfo = raw.lastOrderInfo || raw;
4155
+ const isDraftOrder = Number(nextTempOrder.is_draft_order || 0) === 1;
4156
+ const syntheticIdentityOptions = {
4157
+ isDraftOrder,
4158
+ externalSaleNumber: nextTempOrder.external_sale_number
4159
+ };
4076
4160
  const rawSummary = raw.summary && typeof raw.summary === "object" ? raw.summary : {};
4077
4161
  const summarySurcharges = Array.isArray(rawSummary.surcharges) ? rawSummary.surcharges.map((s) => ({ ...s || {} })) : (0, import_lodash_es.cloneDeep)(nextTempOrder.surcharges || []);
4078
4162
  this.store.tempOrder = nextTempOrder;
@@ -4093,7 +4177,14 @@ var OrderModule = class extends import_BaseModule.BaseModule {
4093
4177
  productFingerprint: this.buildOrderProductsFingerprint(nextTempOrder.products || [])
4094
4178
  }
4095
4179
  };
4096
- this.store.lastOrderInfo = sourceRaw.lastOrderInfo || sourceRaw;
4180
+ this.store.lastOrderInfo = this.withoutSyntheticDraftOrderIdForRuntime(
4181
+ sourceLastOrderInfo,
4182
+ syntheticIdentityOptions
4183
+ );
4184
+ const hadSyntheticDraftOrderId = this.isSyntheticDraftOrderIdForRuntime(raw, syntheticIdentityOptions) || this.isSyntheticDraftOrderIdForRuntime(sourceLastOrderInfo, syntheticIdentityOptions);
4185
+ if (hadSyntheticDraftOrderId && this.store.syncState !== "submitting") {
4186
+ this.store.syncState = "local";
4187
+ }
4097
4188
  const hydratedEditDiscounts = this.collectHydratedEditDiscounts(nextTempOrder.products);
4098
4189
  const currentDiscounts = typeof ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList) === "function" ? this.store.discount.getDiscountList() || [] : [];
4099
4190
  const currentScanDiscounts = currentDiscounts.filter((discount) => discount == null ? void 0 : discount.isScan);
@@ -4206,12 +4297,13 @@ var OrderModule = class extends import_BaseModule.BaseModule {
4206
4297
  }
4207
4298
  normalizeTempOrderForRuntime(raw, options) {
4208
4299
  var _a, _b;
4300
+ const runtimeRaw = this.withoutSyntheticDraftOrderIdForRuntime(raw);
4209
4301
  const nextTempOrder = {
4210
4302
  ...this.createDefaultTempOrderInstance(),
4211
- ...raw || {}
4303
+ ...runtimeRaw || {}
4212
4304
  };
4213
- if ((nextTempOrder.order_id === void 0 || nextTempOrder.order_id === null) && (raw == null ? void 0 : raw.id) !== void 0 && (raw == null ? void 0 : raw.id) !== null) {
4214
- nextTempOrder.order_id = raw.id;
4305
+ if ((nextTempOrder.order_id === void 0 || nextTempOrder.order_id === null) && (runtimeRaw == null ? void 0 : runtimeRaw.id) !== void 0 && (runtimeRaw == null ? void 0 : runtimeRaw.id) !== null) {
4306
+ nextTempOrder.order_id = runtimeRaw.id;
4215
4307
  }
4216
4308
  delete nextTempOrder.summary;
4217
4309
  delete nextTempOrder.lastOrderInfo;
@@ -4279,6 +4371,22 @@ var OrderModule = class extends import_BaseModule.BaseModule {
4279
4371
  nextTempOrder.vouchers = raw.vouchers || [];
4280
4372
  return nextTempOrder;
4281
4373
  }
4374
+ isSyntheticDraftOrderIdForRuntime(record, options) {
4375
+ const isDraftOrder = (options == null ? void 0 : options.isDraftOrder) ?? Number((record == null ? void 0 : record.is_draft_order) || 0) === 1;
4376
+ const externalSaleNumber = (record == null ? void 0 : record.external_sale_number) ?? (options == null ? void 0 : options.externalSaleNumber);
4377
+ const orderId = record == null ? void 0 : record.order_id;
4378
+ return Boolean(
4379
+ isDraftOrder && orderId !== void 0 && orderId !== null && orderId !== "" && externalSaleNumber !== void 0 && externalSaleNumber !== null && externalSaleNumber !== "" && String(orderId) === String(externalSaleNumber)
4380
+ );
4381
+ }
4382
+ withoutSyntheticDraftOrderIdForRuntime(record, options) {
4383
+ if (!this.isSyntheticDraftOrderIdForRuntime(record, options))
4384
+ return record;
4385
+ return {
4386
+ ...record,
4387
+ order_id: null
4388
+ };
4389
+ }
4282
4390
  hydrateLinkedBookingIdentity(tempOrder) {
4283
4391
  const bookingUidByProductUid = /* @__PURE__ */ new Map();
4284
4392
  const productByUid = /* @__PURE__ */ new Map();
@@ -0,0 +1,23 @@
1
+ export type OrderPaymentTransactionStatus = 'success' | 'fail';
2
+ export interface OrderPaymentTransaction {
3
+ number: string;
4
+ status: OrderPaymentTransactionStatus;
5
+ }
6
+ export type OrderPaymentIdentityType = 'order_payment_id' | 'payment_number' | 'unique_payment_number';
7
+ export interface OrderPaymentIdentityMatch<T> {
8
+ index: number;
9
+ payment: T;
10
+ matchedBy: OrderPaymentIdentityType;
11
+ }
12
+ export declare function getOrderPaymentIdentityKeys(payment: unknown): string[];
13
+ export declare function hasOrderPaymentIdentityOverlap(left: unknown, right: unknown): boolean;
14
+ export declare function resolveOrderPaymentIdentity<T extends Record<string, any>>(payments: T[] | null | undefined, identity: string | number, mode?: 'payment_number' | 'compat'): OrderPaymentIdentityMatch<T> | null;
15
+ export declare function ensureOrderPaymentNumber<T extends Record<string, any>>(payment: T, devicePrefix: string, createPaymentNumber: () => string): T & {
16
+ payment_number: string;
17
+ };
18
+ export declare function mergeOrderPaymentTransactions(current: unknown, incoming: unknown): OrderPaymentTransaction[];
19
+ export declare function mergeOrderPaymentRecord<T extends Record<string, any>>(payment: T, updates: Record<string, any>): T;
20
+ export declare function mergeOrderPaymentSnapshot<T extends Record<string, any>>(current: T, incoming: T): T;
21
+ export declare function mergeOrderPaymentListsByIdentity<T extends Record<string, any>>(existing: T[] | null | undefined, incoming: T[] | null | undefined, options?: {
22
+ preserveUnmatchedExisting?: boolean;
23
+ }): T[];
@@ -0,0 +1,193 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/modules/Order/payment-utils.ts
20
+ var payment_utils_exports = {};
21
+ __export(payment_utils_exports, {
22
+ ensureOrderPaymentNumber: () => ensureOrderPaymentNumber,
23
+ getOrderPaymentIdentityKeys: () => getOrderPaymentIdentityKeys,
24
+ hasOrderPaymentIdentityOverlap: () => hasOrderPaymentIdentityOverlap,
25
+ mergeOrderPaymentListsByIdentity: () => mergeOrderPaymentListsByIdentity,
26
+ mergeOrderPaymentRecord: () => mergeOrderPaymentRecord,
27
+ mergeOrderPaymentSnapshot: () => mergeOrderPaymentSnapshot,
28
+ mergeOrderPaymentTransactions: () => mergeOrderPaymentTransactions,
29
+ resolveOrderPaymentIdentity: () => resolveOrderPaymentIdentity
30
+ });
31
+ module.exports = __toCommonJS(payment_utils_exports);
32
+ var PAYMENT_IDENTITY_TYPES = [
33
+ "payment_number",
34
+ "order_payment_id",
35
+ "unique_payment_number"
36
+ ];
37
+ function normalizePaymentIdentityValue(value) {
38
+ if (value === void 0 || value === null || value === "")
39
+ return null;
40
+ return String(value);
41
+ }
42
+ function getPaymentIdentityValue(payment, type) {
43
+ var _a;
44
+ if (type === "unique_payment_number") {
45
+ return (_a = payment == null ? void 0 : payment.metadata) == null ? void 0 : _a.unique_payment_number;
46
+ }
47
+ return payment == null ? void 0 : payment[type];
48
+ }
49
+ function getOrderPaymentIdentityKeys(payment) {
50
+ const record = payment;
51
+ if (!record)
52
+ return [];
53
+ return PAYMENT_IDENTITY_TYPES.flatMap((type) => {
54
+ const value = normalizePaymentIdentityValue(getPaymentIdentityValue(record, type));
55
+ return value === null ? [] : [`${type}:${value}`];
56
+ });
57
+ }
58
+ function hasOrderPaymentIdentityOverlap(left, right) {
59
+ const leftKeys = new Set(getOrderPaymentIdentityKeys(left));
60
+ if (leftKeys.size === 0)
61
+ return false;
62
+ return getOrderPaymentIdentityKeys(right).some((key) => leftKeys.has(key));
63
+ }
64
+ function resolveOrderPaymentIdentity(payments, identity, mode = "payment_number") {
65
+ const target = String(identity);
66
+ const identityTypes = mode === "payment_number" ? ["payment_number"] : PAYMENT_IDENTITY_TYPES;
67
+ const matchesByIndex = /* @__PURE__ */ new Map();
68
+ for (const type of identityTypes) {
69
+ (payments || []).forEach((payment, index) => {
70
+ const value = normalizePaymentIdentityValue(getPaymentIdentityValue(payment, type));
71
+ if (value === target && !matchesByIndex.has(index)) {
72
+ matchesByIndex.set(index, { index, payment, matchedBy: type });
73
+ }
74
+ });
75
+ }
76
+ const matches = [...matchesByIndex.values()];
77
+ if (matches.length > 1) {
78
+ throw new Error(`支付项身份存在歧义: ${target}`);
79
+ }
80
+ return matches[0] || null;
81
+ }
82
+ function ensureOrderPaymentNumber(payment, devicePrefix, createPaymentNumber) {
83
+ const existing = normalizePaymentIdentityValue(payment.payment_number);
84
+ if (existing)
85
+ return { ...payment, payment_number: existing };
86
+ const uuid = normalizePaymentIdentityValue(payment.uuid) || createPaymentNumber();
87
+ const prefix = normalizePaymentIdentityValue(devicePrefix) || "LOCAL";
88
+ return { ...payment, payment_number: `${prefix}_${uuid}` };
89
+ }
90
+ function mergeOrderPaymentTransactions(current, incoming) {
91
+ const records = /* @__PURE__ */ new Map();
92
+ const append = (value) => {
93
+ if (!Array.isArray(value))
94
+ return;
95
+ value.forEach((item) => {
96
+ const number = item && typeof item === "object" ? String(item.number || "") : "";
97
+ const status = item && typeof item === "object" ? item.status : void 0;
98
+ if (!number || status !== "success" && status !== "fail")
99
+ return;
100
+ const previous = records.get(number);
101
+ if ((previous == null ? void 0 : previous.status) === "success" && status === "fail")
102
+ return;
103
+ records.set(number, { number, status });
104
+ });
105
+ };
106
+ append(current);
107
+ append(incoming);
108
+ return [...records.values()];
109
+ }
110
+ function mergeOrderPaymentRecord(payment, updates) {
111
+ const currentMetadata = payment.metadata || {};
112
+ const incomingMetadata = updates.metadata || {};
113
+ const transactions = mergeOrderPaymentTransactions(
114
+ currentMetadata.transactions,
115
+ incomingMetadata.transactions
116
+ );
117
+ const currentPaid = payment.status === "paid";
118
+ const nextStatus = currentPaid && updates.status !== "paid" ? "paid" : updates.status ?? payment.status;
119
+ return {
120
+ ...payment,
121
+ ...updates,
122
+ status: nextStatus,
123
+ updated_at: updates.updated_at ?? payment.updated_at,
124
+ metadata: {
125
+ ...currentMetadata,
126
+ ...incomingMetadata,
127
+ ...transactions.length > 0 || Array.isArray(incomingMetadata.transactions) ? { transactions } : {}
128
+ }
129
+ };
130
+ }
131
+ function mergeOrderPaymentSnapshot(current, incoming) {
132
+ const currentMetadata = current.metadata || {};
133
+ const incomingMetadata = incoming.metadata || {};
134
+ const transactions = mergeOrderPaymentTransactions(
135
+ currentMetadata.transactions,
136
+ incomingMetadata.transactions
137
+ );
138
+ return {
139
+ ...current,
140
+ ...incoming,
141
+ payment_number: incoming.payment_number || current.payment_number,
142
+ metadata: {
143
+ ...currentMetadata,
144
+ ...incomingMetadata,
145
+ ...transactions.length > 0 ? { transactions } : {}
146
+ }
147
+ };
148
+ }
149
+ function compactOrderPaymentList(payments) {
150
+ const result = [];
151
+ for (const payment of payments) {
152
+ const matchingIndexes = result.flatMap((existing, index) => hasOrderPaymentIdentityOverlap(existing, payment) ? [index] : []);
153
+ if (matchingIndexes.length === 0) {
154
+ result.push(mergeOrderPaymentSnapshot({}, payment));
155
+ continue;
156
+ }
157
+ const firstIndex = matchingIndexes[0];
158
+ let merged = result[firstIndex];
159
+ for (const index of matchingIndexes.slice(1)) {
160
+ merged = mergeOrderPaymentSnapshot(merged, result[index]);
161
+ }
162
+ result[firstIndex] = mergeOrderPaymentSnapshot(merged, payment);
163
+ for (const index of matchingIndexes.slice(1).sort((a, b) => b - a)) {
164
+ result.splice(index, 1);
165
+ }
166
+ }
167
+ return result;
168
+ }
169
+ function mergeOrderPaymentListsByIdentity(existing, incoming, options = {}) {
170
+ const existingList = compactOrderPaymentList([...existing || []]);
171
+ const incomingList = compactOrderPaymentList([...incoming || []]);
172
+ if (options.preserveUnmatchedExisting) {
173
+ return compactOrderPaymentList([...existingList, ...incomingList]);
174
+ }
175
+ return compactOrderPaymentList(incomingList.map((incomingPayment) => {
176
+ const matchingExisting = existingList.filter((existingPayment) => hasOrderPaymentIdentityOverlap(existingPayment, incomingPayment));
177
+ return matchingExisting.reduce(
178
+ (merged, existingPayment) => mergeOrderPaymentSnapshot(existingPayment, merged),
179
+ incomingPayment
180
+ );
181
+ }));
182
+ }
183
+ // Annotate the CommonJS export names for ESM import in node:
184
+ 0 && (module.exports = {
185
+ ensureOrderPaymentNumber,
186
+ getOrderPaymentIdentityKeys,
187
+ hasOrderPaymentIdentityOverlap,
188
+ mergeOrderPaymentListsByIdentity,
189
+ mergeOrderPaymentRecord,
190
+ mergeOrderPaymentSnapshot,
191
+ mergeOrderPaymentTransactions,
192
+ resolveOrderPaymentIdentity
193
+ });