@pisell/pisellos 2.2.23 → 2.2.25

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.
@@ -52,6 +52,8 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
52
52
  // LoggerManager 实例
53
53
  // 计算缓存(用于性能优化)
54
54
  this.calculationCache = {};
55
+ // 同步订单到后端锁(按订单维度),防止短时间内重复触发导致同一订单多次同步
56
+ this.syncOrderToBackendInFlightByOrderKey = /* @__PURE__ */ new Map();
55
57
  }
56
58
  async initialize(core, options) {
57
59
  this.core = core;
@@ -859,12 +861,22 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
859
861
  console.warn("[Checkout] 没有当前订单,无法替换订单ID");
860
862
  return null;
861
863
  }
864
+ const previousOrder = this.store.currentOrder;
865
+ const latestPaymentStatus = previousOrder.payment_status;
862
866
  const updatedOrder = await this.payment.replaceOrderIdByUuidAsync(
863
- this.store.currentOrder.uuid,
867
+ previousOrder.uuid,
864
868
  newOrderId
865
869
  );
866
870
  if (updatedOrder) {
867
- this.store.currentOrder = updatedOrder;
871
+ this.store.currentOrder = {
872
+ ...previousOrder,
873
+ ...updatedOrder,
874
+ payment_status: latestPaymentStatus
875
+ };
876
+ if (latestPaymentStatus)
877
+ await this.payment.updateOrderAsync(previousOrder.uuid, {
878
+ payment_status: latestPaymentStatus
879
+ });
868
880
  await this.core.effects.emit(`${this.name}:onOrderCreated`, {
869
881
  order: updatedOrder,
870
882
  timestamp: Date.now()
@@ -1623,9 +1635,11 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1623
1635
  const allPaymentItems = await this.payment.getPaymentItemsAsync(
1624
1636
  this.store.currentOrder.uuid
1625
1637
  );
1638
+ const orderPaymentStatus = allPaymentItems.filter((item) => item.status !== "voided").length > 0 ? "partially_paid" : "payment_processing";
1626
1639
  const syncResult = await this.syncOrderToBackendWithReturn(
1627
1640
  true,
1628
- allPaymentItems
1641
+ allPaymentItems,
1642
+ orderPaymentStatus
1629
1643
  );
1630
1644
  this.logInfo("保存订单完成:", {
1631
1645
  orderUuid,
@@ -2356,283 +2370,347 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2356
2370
  * @param customPaymentItems 自定义支付项列表,如果提供则使用此列表而不是从数据库获取
2357
2371
  * @returns 包含订单ID、UUID和完整后端响应的对象
2358
2372
  */
2359
- async syncOrderToBackendWithReturn(isManual = false, customPaymentItems) {
2373
+ async syncOrderToBackendWithReturn(isManual = false, customPaymentItems, paymentStatus) {
2360
2374
  var _a, _b, _c, _d, _e, _f, _g, _h;
2361
2375
  if (!this.store.localOrderData || !this.store.currentOrder) {
2362
2376
  throw new Error("缺少必要的订单数据,无法同步到后端");
2363
2377
  }
2364
- this.logInfo("syncOrderToBackendWithReturn called", { isManual });
2365
- const currentOrderId = this.store.currentOrder.order_id;
2366
- const isUpdateOperation = this.store.isOrderSynced || !(0, import_utils.isVirtualOrderId)(currentOrderId);
2367
- this.logInfo(`开始同步订单到后端...`, {
2368
- currentOrderId,
2369
- isVirtualId: (0, import_utils.isVirtualOrderId)(currentOrderId || ""),
2370
- orderUuid: this.store.currentOrder.uuid,
2371
- isOrderSynced: this.store.isOrderSynced,
2372
- isManual
2373
- });
2374
- const paymentItems = customPaymentItems || await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid);
2375
- const processedPaymentItems = paymentItems.map((item) => {
2376
- var _a2, _b2;
2377
- return {
2378
- ...item,
2379
- metadata: {
2380
- ...item.metadata,
2381
- rounding_rule: ((_a2 = item.metadata) == null ? void 0 : _a2.rounding_rule) || this.otherParams.order_rounding_setting,
2382
- shop_wallet_pass_id: ((_b2 = item.metadata) == null ? void 0 : _b2.shop_wallet_pass_id) || this.otherParams.shop_wallet_pass_id
2383
- }
2384
- };
2385
- });
2386
- let finalDepositAmount;
2387
- const manualDepositAmount = ((_a = this.store.currentOrder) == null ? void 0 : _a.deposit_amount) || "0.00";
2388
- const manualDepositValue = new import_decimal.default(manualDepositAmount);
2389
- if (manualDepositValue.gt(0)) {
2390
- finalDepositAmount = manualDepositAmount;
2391
- this.logInfo("使用手动设置的定金金额", {
2392
- manualDepositAmount,
2393
- reason: "用户通过setDepositAmountAsync手动设置了定金金额"
2394
- });
2395
- } else {
2396
- finalDepositAmount = "0.00";
2397
- this.logInfo("定金金额为0", {
2398
- manualDepositAmount,
2399
- reason: "手动设置和计算值均为0"
2400
- });
2378
+ const orderLockKey = this.store.currentOrder.uuid || this.store.currentOrder.order_id;
2379
+ if (!orderLockKey) {
2380
+ throw new Error("缺少订单标识,无法同步到后端");
2401
2381
  }
2402
- if (this.store.currentOrder.is_deposit === 0 && processedPaymentItems.every((item) => item.order_payment_type !== "deposit")) {
2403
- finalDepositAmount = "0.00";
2404
- this.store.currentOrder.is_deposit = 0;
2405
- }
2406
- if (this.store.currentOrder.is_deposit === 0 && processedPaymentItems.some((item) => item.order_payment_type === "deposit")) {
2407
- finalDepositAmount = processedPaymentItems.filter((item) => item.status !== "voided" && item.order_payment_type === "deposit").reduce((sum, item) => {
2408
- const amt = new import_decimal.default(item.amount || "0");
2409
- const rounding = new import_decimal.default(item.rounding_amount || "0");
2410
- return sum.plus(amt).sub(rounding);
2411
- }, new import_decimal.default(0)).toFixed(2);
2412
- }
2413
- if (this.store.currentOrder.is_deposit === 1 && new import_decimal.default(finalDepositAmount).gte(new import_decimal.default(this.store.currentOrder.total_amount))) {
2414
- finalDepositAmount = processedPaymentItems.filter((item) => item.status !== "voided" && item.order_payment_type === "deposit").reduce((sum, item) => {
2415
- const amt = new import_decimal.default(item.amount || "0");
2416
- const rounding = new import_decimal.default(item.rounding_amount || "0");
2417
- return sum.plus(amt).sub(rounding);
2418
- }, new import_decimal.default(0)).toFixed(2);
2382
+ const existingInFlight = this.syncOrderToBackendInFlightByOrderKey.get(orderLockKey);
2383
+ if (existingInFlight) {
2384
+ this.logInfo(
2385
+ "syncOrderToBackendWithReturn 触发锁:当前订单正在同步中,将等待当前同步结束",
2386
+ {
2387
+ orderLockKey,
2388
+ orderUuid: this.store.currentOrder.uuid,
2389
+ orderId: this.store.currentOrder.order_id,
2390
+ isManual,
2391
+ hasCustomPaymentItems: !!customPaymentItems
2392
+ }
2393
+ );
2394
+ return await existingInFlight;
2419
2395
  }
2420
- this.logInfo("定金金额确定结果", {
2421
- depositPaymentItemsCount: processedPaymentItems.length,
2422
- depositPaymentItems: processedPaymentItems.map((item) => ({
2423
- uuid: item.uuid,
2424
- code: item.code,
2425
- amount: item.amount,
2426
- rounding_amount: item.rounding_amount,
2427
- order_payment_type: item.order_payment_type,
2428
- status: item.status
2429
- })),
2430
- manualDepositAmount,
2431
- finalDepositAmount,
2432
- isDeposit: ((_b = this.store.currentOrder) == null ? void 0 : _b.is_deposit) || 0
2396
+ let resolveInFlight;
2397
+ let rejectInFlight;
2398
+ const inFlightPromise = new Promise((resolve, reject) => {
2399
+ resolveInFlight = resolve;
2400
+ rejectInFlight = reject;
2433
2401
  });
2434
- const orderParams = {
2435
- ...this.store.localOrderData,
2436
- type: this.store.localOrderData.type,
2437
- platform: this.store.localOrderData.platform,
2438
- payments: processedPaymentItems,
2439
- // 使用处理过的支付项数据
2440
- customer_id: (_c = this.store.currentCustomer) == null ? void 0 : _c.customer_id,
2441
- // 添加客户ID
2442
- is_price_include_tax: this.otherParams.is_price_include_tax,
2443
- // core 有
2444
- tax_title: this.otherParams.tax_title,
2445
- // core 没有
2446
- tax_rate: this.otherParams.tax_rate,
2447
- // core
2448
- tax_country_code: this.otherParams.tax_country_code,
2449
- // core 没有
2450
- currency_code: this.otherParams.currency_code,
2451
- currency_symbol: this.otherParams.currency_symbol,
2452
- currency_format: this.otherParams.currency_format,
2453
- is_deposit: (((_d = this.store.currentOrder) == null ? void 0 : _d.is_deposit) || Number(finalDepositAmount) > 0 ? 1 : 0) || 0,
2454
- deposit_amount: finalDepositAmount,
2455
- // 使用最终确定的定金金额(手动设置优先)
2456
- product_tax_fee: this.store.localOrderData.tax_fee,
2457
- note: this.store.localOrderData.shop_note,
2458
- bookings: (_e = this.store.localOrderData.bookings) == null ? void 0 : _e.map((item) => {
2402
+ this.syncOrderToBackendInFlightByOrderKey.set(orderLockKey, inFlightPromise);
2403
+ try {
2404
+ this.logInfo("syncOrderToBackendWithReturn called", { isManual });
2405
+ const currentOrderId = this.store.currentOrder.order_id;
2406
+ const isUpdateOperation = this.store.isOrderSynced || !(0, import_utils.isVirtualOrderId)(currentOrderId);
2407
+ this.logInfo(`开始同步订单到后端...`, {
2408
+ currentOrderId,
2409
+ isVirtualId: (0, import_utils.isVirtualOrderId)(currentOrderId || ""),
2410
+ orderUuid: this.store.currentOrder.uuid,
2411
+ isOrderSynced: this.store.isOrderSynced,
2412
+ isManual
2413
+ });
2414
+ const paymentItems = customPaymentItems || await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid);
2415
+ const processedPaymentItems = paymentItems.map((item) => {
2416
+ var _a2, _b2;
2459
2417
  return {
2460
2418
  ...item,
2461
- product: {
2462
- ...item.product,
2463
- custom_deposit_data: void 0
2464
- },
2465
- deposit: void 0
2419
+ metadata: {
2420
+ ...item.metadata,
2421
+ rounding_rule: ((_a2 = item.metadata) == null ? void 0 : _a2.rounding_rule) || this.otherParams.order_rounding_setting,
2422
+ shop_wallet_pass_id: ((_b2 = item.metadata) == null ? void 0 : _b2.shop_wallet_pass_id) || this.otherParams.shop_wallet_pass_id
2423
+ }
2466
2424
  };
2467
- }),
2468
- relation_products: (_f = this.store.localOrderData.relation_products) == null ? void 0 : _f.map(
2469
- (item) => {
2425
+ });
2426
+ let finalDepositAmount;
2427
+ const manualDepositAmount = ((_a = this.store.currentOrder) == null ? void 0 : _a.deposit_amount) || "0.00";
2428
+ const manualDepositValue = new import_decimal.default(manualDepositAmount);
2429
+ if (manualDepositValue.gt(0)) {
2430
+ finalDepositAmount = manualDepositAmount;
2431
+ this.logInfo("使用手动设置的定金金额", {
2432
+ manualDepositAmount,
2433
+ reason: "用户通过setDepositAmountAsync手动设置了定金金额"
2434
+ });
2435
+ } else {
2436
+ finalDepositAmount = "0.00";
2437
+ this.logInfo("定金金额为0", {
2438
+ manualDepositAmount,
2439
+ reason: "手动设置和计算值均为0"
2440
+ });
2441
+ }
2442
+ if (this.store.currentOrder.is_deposit === 0 && processedPaymentItems.every((item) => item.order_payment_type !== "deposit")) {
2443
+ finalDepositAmount = "0.00";
2444
+ this.store.currentOrder.is_deposit = 0;
2445
+ }
2446
+ if (this.store.currentOrder.is_deposit === 0 && processedPaymentItems.some((item) => item.order_payment_type === "deposit")) {
2447
+ finalDepositAmount = processedPaymentItems.filter((item) => item.status !== "voided" && item.order_payment_type === "deposit").reduce((sum, item) => {
2448
+ const amt = new import_decimal.default(item.amount || "0");
2449
+ const rounding = new import_decimal.default(item.rounding_amount || "0");
2450
+ return sum.plus(amt).sub(rounding);
2451
+ }, new import_decimal.default(0)).toFixed(2);
2452
+ }
2453
+ if (this.store.currentOrder.is_deposit === 1 && new import_decimal.default(finalDepositAmount).gte(new import_decimal.default(this.store.currentOrder.total_amount))) {
2454
+ finalDepositAmount = processedPaymentItems.filter((item) => item.status !== "voided" && item.order_payment_type === "deposit").reduce((sum, item) => {
2455
+ const amt = new import_decimal.default(item.amount || "0");
2456
+ const rounding = new import_decimal.default(item.rounding_amount || "0");
2457
+ return sum.plus(amt).sub(rounding);
2458
+ }, new import_decimal.default(0)).toFixed(2);
2459
+ }
2460
+ this.logInfo("定金金额确定结果", {
2461
+ depositPaymentItemsCount: processedPaymentItems.length,
2462
+ depositPaymentItems: processedPaymentItems.map((item) => ({
2463
+ uuid: item.uuid,
2464
+ code: item.code,
2465
+ amount: item.amount,
2466
+ rounding_amount: item.rounding_amount,
2467
+ order_payment_type: item.order_payment_type,
2468
+ status: item.status
2469
+ })),
2470
+ manualDepositAmount,
2471
+ finalDepositAmount,
2472
+ isDeposit: ((_b = this.store.currentOrder) == null ? void 0 : _b.is_deposit) || 0
2473
+ });
2474
+ let orderPaymentStatus = paymentStatus;
2475
+ if (!orderPaymentStatus) {
2476
+ const totalPaidAmount = processedPaymentItems.filter((item) => item.status !== "voided").reduce((sum, item) => {
2477
+ const amt = new import_decimal.default(item.amount || "0");
2478
+ const rounding = new import_decimal.default(item.rounding_amount || "0");
2479
+ return sum.plus(amt).sub(rounding);
2480
+ }, new import_decimal.default(0));
2481
+ if (totalPaidAmount.gte(new import_decimal.default(this.store.currentOrder.total_amount))) {
2482
+ orderPaymentStatus = "paid";
2483
+ } else if (totalPaidAmount.gt(0)) {
2484
+ orderPaymentStatus = "partially_paid";
2485
+ } else {
2486
+ orderPaymentStatus = "unpaid";
2487
+ }
2488
+ }
2489
+ const orderParams = {
2490
+ ...this.store.localOrderData,
2491
+ payment_status: orderPaymentStatus,
2492
+ type: this.store.localOrderData.type,
2493
+ platform: this.store.localOrderData.platform,
2494
+ payments: processedPaymentItems,
2495
+ // 使用处理过的支付项数据
2496
+ customer_id: (_c = this.store.currentCustomer) == null ? void 0 : _c.customer_id,
2497
+ // 添加客户ID
2498
+ is_price_include_tax: this.otherParams.is_price_include_tax,
2499
+ // core 有
2500
+ tax_title: this.otherParams.tax_title,
2501
+ // core 没有
2502
+ tax_rate: this.otherParams.tax_rate,
2503
+ // core 有
2504
+ tax_country_code: this.otherParams.tax_country_code,
2505
+ // core 没有
2506
+ currency_code: this.otherParams.currency_code,
2507
+ currency_symbol: this.otherParams.currency_symbol,
2508
+ currency_format: this.otherParams.currency_format,
2509
+ is_deposit: (((_d = this.store.currentOrder) == null ? void 0 : _d.is_deposit) || Number(finalDepositAmount) > 0 ? 1 : 0) || 0,
2510
+ deposit_amount: finalDepositAmount,
2511
+ // 使用最终确定的定金金额(手动设置优先)
2512
+ product_tax_fee: this.store.localOrderData.tax_fee,
2513
+ note: this.store.localOrderData.shop_note,
2514
+ bookings: (_e = this.store.localOrderData.bookings) == null ? void 0 : _e.map((item) => {
2470
2515
  return {
2471
2516
  ...item,
2472
- custom_deposit_data: void 0,
2517
+ product: {
2518
+ ...item.product,
2519
+ custom_deposit_data: void 0
2520
+ },
2473
2521
  deposit: void 0
2474
2522
  };
2523
+ }),
2524
+ relation_products: (_f = this.store.localOrderData.relation_products) == null ? void 0 : _f.map(
2525
+ (item) => {
2526
+ return {
2527
+ ...item,
2528
+ custom_deposit_data: void 0,
2529
+ deposit: void 0
2530
+ };
2531
+ }
2532
+ )
2533
+ };
2534
+ if (isUpdateOperation) {
2535
+ if ((0, import_utils.isVirtualOrderId)(currentOrderId)) {
2536
+ this.logWarning(
2537
+ "尝试数据修复:暂时不包含order_id,注意:这次调用将作为创建操作处理,但后续会修复数据一致性"
2538
+ );
2539
+ } else {
2540
+ orderParams.order_id = currentOrderId;
2475
2541
  }
2476
- )
2477
- };
2478
- if (isUpdateOperation) {
2479
- if ((0, import_utils.isVirtualOrderId)(currentOrderId)) {
2480
- this.logWarning(
2481
- "尝试数据修复:暂时不包含order_id,注意:这次调用将作为创建操作处理,但后续会修复数据一致性"
2482
- );
2483
- } else {
2484
- orderParams.order_id = currentOrderId;
2485
2542
  }
2486
- }
2487
- const startTime = Date.now();
2488
- await this.core.effects.emit(`${this.name}:onOrderSubmitStart`, {
2489
- orderUuid: this.store.currentOrder.uuid,
2490
- operation: isUpdateOperation ? "update" : "create",
2491
- isManual,
2492
- paymentItemCount: paymentItems.length,
2493
- timestamp: startTime
2494
- });
2495
- let checkoutResponse;
2496
- let submitSuccess = false;
2497
- let submitError;
2498
- try {
2499
- this.logInfo("Calling backend checkout API", {
2500
- url: "/order/checkout",
2501
- isManual,
2502
- ...orderParams
2503
- });
2504
- checkoutResponse = await this.order.createOrderByCheckout(orderParams);
2505
- submitSuccess = true;
2506
- this.logInfo("下单接口调用成功", checkoutResponse);
2507
- } catch (error) {
2508
- submitSuccess = false;
2509
- submitError = error instanceof Error ? error.message : String(error);
2510
- this.logError("下单接口调用失败:", submitError);
2511
- await this.core.effects.emit(`${this.name}:onOrderSyncFailed`, {
2543
+ const startTime = Date.now();
2544
+ await this.core.effects.emit(`${this.name}:onOrderSubmitStart`, {
2512
2545
  orderUuid: this.store.currentOrder.uuid,
2513
2546
  operation: isUpdateOperation ? "update" : "create",
2514
2547
  isManual,
2515
- error: submitError,
2516
- errorType: "network_error",
2517
- duration: Date.now() - startTime,
2518
- timestamp: Date.now()
2548
+ paymentItemCount: paymentItems.length,
2549
+ timestamp: startTime
2519
2550
  });
2520
- throw error;
2521
- } finally {
2522
- await this.core.effects.emit(`${this.name}:onOrderSubmitEnd`, {
2523
- success: submitSuccess,
2524
- orderUuid: this.store.currentOrder.uuid,
2525
- operation: isUpdateOperation ? "update" : "create",
2526
- isManual,
2527
- orderId: submitSuccess ? ((_g = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _g.order_id) || (checkoutResponse == null ? void 0 : checkoutResponse.order_id) : void 0,
2528
- error: submitError,
2529
- duration: Date.now() - startTime,
2530
- timestamp: Date.now()
2531
- });
2532
- }
2533
- const responseStatus = checkoutResponse == null ? void 0 : checkoutResponse.status;
2534
- const isSuccessResponse = responseStatus === true || responseStatus === 200 || responseStatus === "success" || responseStatus === 1 && (checkoutResponse == null ? void 0 : checkoutResponse.code) === 200;
2535
- if (!isSuccessResponse) {
2536
- const errorMessage = (checkoutResponse == null ? void 0 : checkoutResponse.message) || "订单同步失败,后端返回非成功状态";
2537
- await this.core.effects.emit(`${this.name}:onOrderSyncFailed`, {
2538
- orderUuid: this.store.currentOrder.uuid,
2539
- operation: isUpdateOperation ? "update" : "create",
2540
- isManual,
2541
- error: errorMessage,
2542
- errorType: "api_error",
2543
- response: checkoutResponse,
2544
- duration: Date.now() - startTime,
2545
- timestamp: Date.now()
2546
- });
2547
- throw new Error(errorMessage);
2548
- }
2549
- let realOrderId;
2550
- if (isUpdateOperation) {
2551
- realOrderId = currentOrderId;
2552
- } else {
2553
- let extractedOrderId = (_h = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _h.order_id;
2554
- if (!extractedOrderId) {
2555
- extractedOrderId = checkoutResponse == null ? void 0 : checkoutResponse.order_id;
2556
- }
2557
- if (extractedOrderId !== void 0 && extractedOrderId !== null) {
2558
- extractedOrderId = String(extractedOrderId);
2551
+ let checkoutResponse;
2552
+ let submitSuccess = false;
2553
+ let submitError;
2554
+ try {
2555
+ this.logInfo("Calling backend checkout API", {
2556
+ url: "/order/checkout",
2557
+ isManual,
2558
+ ...orderParams
2559
+ });
2560
+ checkoutResponse = await this.order.createOrderByCheckout(orderParams);
2561
+ submitSuccess = true;
2562
+ this.store.currentOrder.payment_status = checkoutResponse.data.payment_status;
2563
+ this.logInfo("下单接口调用成功", checkoutResponse);
2564
+ } catch (error) {
2565
+ submitSuccess = false;
2566
+ submitError = error instanceof Error ? error.message : String(error);
2567
+ this.logError("下单接口调用失败:", submitError);
2568
+ await this.core.effects.emit(`${this.name}:onOrderSyncFailed`, {
2569
+ orderUuid: this.store.currentOrder.uuid,
2570
+ operation: isUpdateOperation ? "update" : "create",
2571
+ isManual,
2572
+ error: submitError,
2573
+ errorType: "network_error",
2574
+ duration: Date.now() - startTime,
2575
+ timestamp: Date.now()
2576
+ });
2577
+ throw error;
2578
+ } finally {
2579
+ await this.core.effects.emit(`${this.name}:onOrderSubmitEnd`, {
2580
+ success: submitSuccess,
2581
+ orderUuid: this.store.currentOrder.uuid,
2582
+ operation: isUpdateOperation ? "update" : "create",
2583
+ isManual,
2584
+ orderId: submitSuccess ? ((_g = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _g.order_id) || (checkoutResponse == null ? void 0 : checkoutResponse.order_id) : void 0,
2585
+ error: submitError,
2586
+ duration: Date.now() - startTime,
2587
+ timestamp: Date.now()
2588
+ });
2559
2589
  }
2560
- if (!extractedOrderId) {
2561
- this.logError("后端返回的订单信息中未包含订单ID");
2590
+ const responseStatus = checkoutResponse == null ? void 0 : checkoutResponse.status;
2591
+ const isSuccessResponse = responseStatus === true || responseStatus === 200 || responseStatus === "success" || responseStatus === 1 && (checkoutResponse == null ? void 0 : checkoutResponse.code) === 200;
2592
+ if (!isSuccessResponse) {
2593
+ const errorMessage = (checkoutResponse == null ? void 0 : checkoutResponse.message) || "订单同步失败,后端返回非成功状态";
2594
+ await this.core.effects.emit(`${this.name}:onOrderSyncFailed`, {
2595
+ orderUuid: this.store.currentOrder.uuid,
2596
+ operation: isUpdateOperation ? "update" : "create",
2597
+ isManual,
2598
+ error: errorMessage,
2599
+ errorType: "api_error",
2600
+ response: checkoutResponse,
2601
+ duration: Date.now() - startTime,
2602
+ timestamp: Date.now()
2603
+ });
2604
+ throw new Error(errorMessage);
2562
2605
  }
2563
- realOrderId = extractedOrderId;
2564
- this.logInfo("准备替换订单ID:", {
2565
- orderUuid: this.store.currentOrder.uuid,
2566
- oldOrderId: this.store.currentOrder.order_id,
2567
- newOrderId: realOrderId
2568
- });
2569
- try {
2570
- const updatedOrder = await this.payment.replaceOrderIdByUuidAsync(
2571
- this.store.currentOrder.uuid,
2572
- realOrderId
2573
- );
2574
- this.logInfo("Payment模块替换订单ID结果:", {
2575
- wasSuccessful: !!updatedOrder,
2576
- returnedOrderId: updatedOrder == null ? void 0 : updatedOrder.order_id,
2577
- expectedOrderId: realOrderId
2606
+ let realOrderId;
2607
+ if (isUpdateOperation) {
2608
+ realOrderId = currentOrderId;
2609
+ } else {
2610
+ let extractedOrderId = (_h = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _h.order_id;
2611
+ if (!extractedOrderId) {
2612
+ extractedOrderId = checkoutResponse == null ? void 0 : checkoutResponse.order_id;
2613
+ }
2614
+ if (extractedOrderId !== void 0 && extractedOrderId !== null) {
2615
+ extractedOrderId = String(extractedOrderId);
2616
+ }
2617
+ if (!extractedOrderId) {
2618
+ this.logError("后端返回的订单信息中未包含订单ID");
2619
+ }
2620
+ realOrderId = extractedOrderId;
2621
+ this.logInfo("准备替换订单ID:", {
2622
+ orderUuid: this.store.currentOrder.uuid,
2623
+ oldOrderId: this.store.currentOrder.order_id,
2624
+ newOrderId: realOrderId
2578
2625
  });
2579
- if (updatedOrder) {
2580
- this.logInfo("Payment模块返回的更新后订单:", {
2581
- uuid: updatedOrder.uuid,
2582
- orderId: updatedOrder.order_id,
2583
- totalAmount: updatedOrder.total_amount
2584
- });
2585
- this.store.currentOrder = updatedOrder;
2586
- this.logInfo(
2587
- "[Checkout] 订单ID替换成功,当前订单ID:",
2588
- this.store.currentOrder.order_id
2589
- );
2590
- } else {
2591
- this.logError(
2592
- "[Checkout] Payment模块返回空订单,订单ID替换失败,开始手动替换"
2626
+ try {
2627
+ const latestPaymentStatus = this.store.currentOrder.payment_status;
2628
+ const previousOrder = this.store.currentOrder;
2629
+ const updatedOrder = await this.payment.replaceOrderIdByUuidAsync(
2630
+ previousOrder.uuid,
2631
+ realOrderId
2593
2632
  );
2594
- const beforeManualUpdate = this.store.currentOrder.order_id;
2595
- this.store.currentOrder.order_id = realOrderId;
2596
- this.logInfo("手动设置订单ID:", {
2597
- beforeReplacement: beforeManualUpdate,
2598
- afterReplacement: this.store.currentOrder.order_id,
2599
- 目标ID: realOrderId
2633
+ this.logInfo("Payment模块替换订单ID结果:", {
2634
+ wasSuccessful: !!updatedOrder,
2635
+ returnedOrderId: updatedOrder == null ? void 0 : updatedOrder.order_id,
2636
+ expectedOrderId: realOrderId
2600
2637
  });
2638
+ if (updatedOrder) {
2639
+ this.logInfo("Payment模块返回的更新后订单:", {
2640
+ uuid: updatedOrder.uuid,
2641
+ orderId: updatedOrder.order_id,
2642
+ totalAmount: updatedOrder.total_amount
2643
+ });
2644
+ this.store.currentOrder = {
2645
+ ...previousOrder,
2646
+ ...updatedOrder,
2647
+ payment_status: latestPaymentStatus
2648
+ };
2649
+ if (latestPaymentStatus)
2650
+ await this.payment.updateOrderAsync(previousOrder.uuid, {
2651
+ payment_status: latestPaymentStatus
2652
+ });
2653
+ this.logInfo(
2654
+ "[Checkout] 订单ID替换成功,当前订单ID:",
2655
+ this.store.currentOrder.order_id
2656
+ );
2657
+ } else {
2658
+ this.logError(
2659
+ "[Checkout] Payment模块返回空订单,订单ID替换失败,开始手动替换"
2660
+ );
2661
+ const beforeManualUpdate = this.store.currentOrder.order_id;
2662
+ this.store.currentOrder.order_id = realOrderId;
2663
+ this.logInfo("手动设置订单ID:", {
2664
+ beforeReplacement: beforeManualUpdate,
2665
+ afterReplacement: this.store.currentOrder.order_id,
2666
+ 目标ID: realOrderId
2667
+ });
2668
+ }
2669
+ } catch (error) {
2670
+ this.logError("调用Payment模块替换订单ID时发生错误:", error);
2671
+ this.store.currentOrder.order_id = realOrderId;
2672
+ this.logInfo("错误恢复:手动设置订单ID:", realOrderId);
2601
2673
  }
2602
- } catch (error) {
2603
- this.logError("调用Payment模块替换订单ID时发生错误:", error);
2604
- this.store.currentOrder.order_id = realOrderId;
2605
- this.logInfo("错误恢复:手动设置订单ID:", realOrderId);
2606
2674
  }
2607
- }
2608
- try {
2609
- const syncedPaymentUuids = processedPaymentItems.filter((item) => item.status !== "voided").map((item) => item.uuid).filter(Boolean);
2610
- for (const paymentUuid of syncedPaymentUuids) {
2611
- await this.payment.updatePaymentAsync(
2612
- this.store.currentOrder.uuid,
2613
- paymentUuid,
2614
- { isSynced: true, syncError: void 0 }
2615
- );
2675
+ try {
2676
+ const syncedPaymentUuids = processedPaymentItems.filter((item) => item.status !== "voided").map((item) => item.uuid).filter(Boolean);
2677
+ for (const paymentUuid of syncedPaymentUuids) {
2678
+ await this.payment.updatePaymentAsync(
2679
+ this.store.currentOrder.uuid,
2680
+ paymentUuid,
2681
+ { isSynced: true, syncError: void 0 }
2682
+ );
2683
+ }
2684
+ } catch (e) {
2685
+ this.logWarning("标记支付项已同步失败(不阻塞主流程)", { error: e });
2686
+ }
2687
+ this.store.isOrderSynced = true;
2688
+ this.clearCalculationCache();
2689
+ await this.core.effects.emit(`${this.name}:onOrderSynced`, {
2690
+ orderUuid: this.store.currentOrder.uuid,
2691
+ realOrderId,
2692
+ virtualOrderId: this.store.currentOrder.order_id,
2693
+ timestamp: Date.now(),
2694
+ isManual,
2695
+ response: checkoutResponse
2696
+ });
2697
+ const result = {
2698
+ success: true,
2699
+ orderId: realOrderId,
2700
+ orderUuid: this.store.currentOrder.uuid,
2701
+ response: checkoutResponse
2702
+ };
2703
+ resolveInFlight(result);
2704
+ return result;
2705
+ } catch (error) {
2706
+ rejectInFlight(error);
2707
+ throw error;
2708
+ } finally {
2709
+ const currentInFlight = this.syncOrderToBackendInFlightByOrderKey.get(orderLockKey);
2710
+ if (currentInFlight === inFlightPromise) {
2711
+ this.syncOrderToBackendInFlightByOrderKey.delete(orderLockKey);
2616
2712
  }
2617
- } catch (e) {
2618
- this.logWarning("标记支付项已同步失败(不阻塞主流程)", { error: e });
2619
2713
  }
2620
- this.store.isOrderSynced = true;
2621
- this.clearCalculationCache();
2622
- await this.core.effects.emit(`${this.name}:onOrderSynced`, {
2623
- orderUuid: this.store.currentOrder.uuid,
2624
- realOrderId,
2625
- virtualOrderId: this.store.currentOrder.order_id,
2626
- timestamp: Date.now(),
2627
- isManual,
2628
- response: checkoutResponse
2629
- });
2630
- return {
2631
- success: true,
2632
- orderId: realOrderId,
2633
- orderUuid: this.store.currentOrder.uuid,
2634
- response: checkoutResponse
2635
- };
2636
2714
  }
2637
2715
  async setOtherParams(params, { cover = false } = {}) {
2638
2716
  if (cover) {