package adminfinance import ( "sync" "sync/atomic" "testing" "time" "hfb_sys/backend/internal/database" "hfb_sys/backend/internal/timeutil" ) func TestDailyPaidOrdersUsePaidAtAndIncludeCreatedPickups(t *testing.T) { db := database.NewTestDB() loc := timeutil.ShanghaiLocation() day := func(value int) time.Time { return time.Date(2026, 8, value, 10, 0, 0, 0, loc) } rows := [][]any{ {1, "PAY-1", 101, "ORD-101", 11, "mockpay", "T-101", "order_pay", "paid", day(2)}, {2, "PAY-2", 101, "ORD-101", 11, "mockpay", "T-102", "order_pay", "paid", day(2)}, {3, "PAY-3", 102, "ORD-102", 12, "mockpay", "T-103", "order_pay", "paid", day(3)}, {4, "PAY-4", 201, "ORD-201", 21, "mockpay", "T-201", "mohong_pay", "paid", day(2)}, {5, "PAY-5", 103, "ORD-103", 13, "mockpay", "T-104", "order_pay", "created", nil}, {6, "PAY-6", 104, "ORD-104", 14, "mockpay", "T-105", "order_pay", "paid", day(1)}, } for _, row := range rows { if err := db.Exec(`INSERT INTO payment_orders (id, payment_no, order_id, order_no, user_id, provider, third_order_id, biz_type, status, paid_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil { t.Fatalf("写入支付单失败: %v", err) } } for _, row := range [][]any{ {1, "PK-1", 1, 1, 1, 1, "completed", day(2), day(2)}, {2, "PK-2", 2, 2, 2, 1, "picking_up", day(2), nil}, {3, "PK-3", 3, 3, 3, 1, "completed", day(3), day(3)}, {4, "PK-4", 4, 4, 4, 1, "cancelled", day(1), nil}, } { if err := db.Exec(`INSERT INTO admin_pickups (id, pickup_no, listing_id, account_id, owner_id, admin_id, status, created_at, completed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil { t.Fatalf("写入提号记录失败: %v", err) } } repo := NewRepository(db) query := DashboardQuery{ StartDate: time.Date(2026, 8, 2, 0, 0, 0, 0, loc), EndDate: time.Date(2026, 8, 3, 23, 59, 59, 0, loc), } result, err := repo.dailyPaidOrders(t.Context(), query) if err != nil { t.Fatalf("读取每日已付款订单失败: %v", err) } if len(result) != 2 { t.Fatalf("每日已付款记录数 = %d, want 2", len(result)) } counts := make(map[string]int64, len(result)) for _, row := range result { counts[row.Date] = row.PaidOrderCount } if counts["2026-08-02"] != 2 || counts["2026-08-03"] != 2 { t.Fatalf("每日已付款订单 = %#v, want 8月2日为2、8月3日为2", counts) } } func TestDailyPaymentsNormalFullRefundExcludesMohong(t *testing.T) { db := database.NewTestDB() loc := timeutil.ShanghaiLocation() day := func(value int) time.Time { return time.Date(2026, 8, value, 10, 0, 0, 0, loc) } rows := [][]any{ // 正常订单全额退款:计入 full_refund_count 与 normal_full_refund_count {1, "PAY-1", 101, "ORD-101", 11, "mockpay", "T-101", "rent_refund", "refunded", 5000, day(2)}, {2, "PAY-2", 101, "ORD-101", 11, "mockpay", "T-102", "order_pay", "paid", 5000, day(1)}, // 正常订单部分退款:不计入全额 {3, "PAY-3", 102, "ORD-102", 12, "mockpay", "T-103", "rent_refund", "refunded", 2000, day(2)}, {4, "PAY-4", 102, "ORD-102", 12, "mockpay", "T-104", "order_pay", "paid", 5000, day(1)}, // 撞车商城全额退款:只计入 full_refund_count,不计入 normal_full_refund_count {5, "PAY-5", 201, "ORD-201", 21, "mockpay", "T-201", "mohong_refund", "refunded", 3000, day(2)}, {6, "PAY-6", 201, "ORD-201", 21, "mockpay", "T-202", "mohong_pay", "paid", 3000, day(1)}, } for _, row := range rows { if err := db.Exec(`INSERT INTO payment_orders (id, payment_no, order_id, order_no, user_id, provider, third_order_id, biz_type, status, amount_cent, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil { t.Fatalf("写入支付单失败: %v", err) } } repo := NewRepository(db) query := DashboardQuery{ StartDate: time.Date(2026, 8, 2, 0, 0, 0, 0, loc), EndDate: time.Date(2026, 8, 2, 23, 59, 59, 0, loc), } result, err := repo.dailyPayments(t.Context(), query) if err != nil { t.Fatalf("读取每日收付款失败: %v", err) } if len(result) != 1 { t.Fatalf("每日收付款记录数 = %d, want 1", len(result)) } row := result[0] if row.FullRefundCount != 2 { t.Fatalf("full_refund_count = %d, want 2(正常1笔 + 撞车1笔)", row.FullRefundCount) } if row.NormalFullRefundCount != 1 { t.Fatalf("normal_full_refund_count = %d, want 1(仅正常订单全额退款)", row.NormalFullRefundCount) } if row.PartialRefundCount != 1 { t.Fatalf("partial_refund_count = %d, want 1", row.PartialRefundCount) } } func TestDailyPickupCancelledByCancelledAt(t *testing.T) { db := database.NewTestDB() loc := timeutil.ShanghaiLocation() day := func(value int) time.Time { return time.Date(2026, 8, value, 15, 0, 0, 0, loc) } for _, row := range [][]any{ {1, "PK-1", 1, 1, 1, 1, "cancelled", day(1), day(2)}, {2, "PK-2", 2, 2, 2, 1, "cancelled", day(1), day(2)}, {3, "PK-3", 3, 3, 3, 1, "cancelled", day(1), day(3)}, {4, "PK-4", 4, 4, 4, 1, "cancelled", day(1), nil}, // 取消时间缺失的不计 {5, "PK-5", 5, 5, 5, 1, "completed", day(1), day(2)}, } { if err := db.Exec(`INSERT INTO admin_pickups (id, pickup_no, listing_id, account_id, owner_id, admin_id, status, created_at, cancelled_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil { t.Fatalf("写入提号记录失败: %v", err) } } repo := NewRepository(db) query := DashboardQuery{ StartDate: time.Date(2026, 8, 2, 0, 0, 0, 0, loc), EndDate: time.Date(2026, 8, 2, 23, 59, 59, 0, loc), } result, err := repo.dailyPickupCancelled(t.Context(), query) if err != nil { t.Fatalf("读取每日取消提号失败: %v", err) } if len(result) != 1 { t.Fatalf("每日取消提号记录数 = %d, want 1", len(result)) } if result[0].Count != 2 { t.Fatalf("8月2日取消提号数 = %d, want 2", result[0].Count) } } func TestPickupSummaryKeepsOriginalAndAdjustmentOnTheirOwnDates(t *testing.T) { db := database.NewTestDB() loc := timeutil.ShanghaiLocation() completedAt := time.Date(2026, 8, 2, 10, 0, 0, 0, loc) adjustedAt := time.Date(2026, 8, 4, 10, 0, 0, 0, loc) if err := db.Exec(`INSERT INTO admin_pickups (id, pickup_no, listing_id, account_id, owner_id, admin_id, status, settle_amount_cent, profit_amount_cent, created_at, completed_at) VALUES (1, 'PK-1', 1, 1, 1, 1, 'completed', 12000, 1000, ?, ?)`, adjustedAt, completedAt).Error; err != nil { t.Fatalf("写入提号失败: %v", err) } if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments (id, pickup_id, settlement_mode, status, reason, created_by, settle_delta_cent, profit_delta_cent, created_at) VALUES (1, 1, 'owner_wallet', 'settled', '测试调整', 1, 1500, 500, ?)`, adjustedAt).Error; err != nil { t.Fatalf("写入调整失败: %v", err) } repo := NewRepository(db) dayQuery := func(day int) DashboardQuery { return DashboardQuery{ StartDate: time.Date(2026, 8, day, 0, 0, 0, 0, loc), EndDate: time.Date(2026, 8, day, 23, 59, 59, 0, loc), } } original, err := repo.pickupSummary(t.Context(), dayQuery(2)) if err != nil { t.Fatalf("查询完成日提号汇总失败: %v", err) } if original.SettledAmountCent != 12000 || original.ProfitAmountCent != 1000 || original.CompletedCount != 1 { t.Fatalf("完成日汇总 = %+v", original) } adjusted, err := repo.pickupSummary(t.Context(), dayQuery(4)) if err != nil { t.Fatalf("查询调整日提号汇总失败: %v", err) } if adjusted.SettledAmountCent != 1500 || adjusted.ProfitAmountCent != 500 || adjusted.CompletedCount != 0 { t.Fatalf("调整日汇总 = %+v", adjusted) } } func TestSummaryReturnsNormalOrderCountAndScopedExceptionCount(t *testing.T) { db := database.NewTestDB() loc := timeutil.ShanghaiLocation() settledAt := time.Date(2026, 8, 2, 10, 0, 0, 0, loc) // ORD-S3 的结账单终态是 settled(仲裁结案),不纳入"正常结账确认"口径。 for _, row := range [][]any{ {1, "ORD-S1", 1, 1, 1, 1, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 300}, {2, "ORD-S2", 2, 2, 2, 2, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 200}, {3, "ORD-S3", 3, 3, 3, 3, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 0}, } { if err := db.Exec(`INSERT INTO rental_orders (id, order_no, listing_id, account_id, owner_id, renter_id, settled_at, settlement_mode, offline_settlement_amount_cent, offline_settlement_status, refund_status, settlement_status, status, created_at, platform_fee_cent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil { t.Fatalf("写入订单失败: %v", err) } } for _, row := range [][]any{ {1, 1, 1, "accepted", 300, 700}, {2, 2, 1, "accepted", 200, 600}, {3, 3, 1, "settled", 0, 0}, } { if err := db.Exec(`INSERT INTO order_checkouts (id, order_id, initiated_by, status, platform_fee_cent, owner_income_amount_cent) VALUES (?, ?, ?, ?, ?, ?)`, row...).Error; err != nil { t.Fatalf("写入结账单失败: %v", err) } } for _, row := range [][]any{ {1, "WL-1", 1, 1, "in", "available", "owner_income", "WL-1", 700}, {2, "WL-2", 2, 2, "in", "available", "owner_income", "WL-2", 500}, } { if err := db.Exec(`INSERT INTO wallet_ledger (id, ledger_no, order_id, user_id, direction, balance_type, biz_type, biz_no, amount_cent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil { t.Fatalf("写入钱包流水失败: %v", err) } } query := DashboardQuery{ StartDate: time.Date(2026, 8, 2, 0, 0, 0, 0, loc), EndDate: time.Date(2026, 8, 2, 23, 59, 59, 0, loc), } repo := NewRepository(db) pickup, err := repo.pickupSummary(t.Context(), query) if err != nil { t.Fatalf("读取提号汇总失败: %v", err) } settlements, err := repo.dailySettlements(t.Context(), query) if err != nil { t.Fatalf("读取每日结算汇总失败: %v", err) } summary := summaryWithPickup(summaryFromDailyRows(nil, settlements, nil), pickup) // ORD-S3 的结账单终态为 settled(仲裁结案),按既有口径不计入"已结算订单数"。 if summary.SettledOrderCount != 2 || summary.NormalOrderProfitAmountCent != 500 { t.Fatalf("普通订单数量或利润错误: %+v", summary) } if summary.FinancialExceptionCount != 1 { t.Fatalf("财务异常数 = %d, want 1", summary.FinancialExceptionCount) } } func TestSummaryFromDailyRowsPreservesDashboardTotals(t *testing.T) { paymentRows := []dailyPaymentRow{ {TotalFlowAmountCent: 1000, TotalRefundAmountCent: 100, PendingRefundAmountCent: 30, SuccessfulPayCount: 3, FullRefundCount: 1}, {TotalFlowAmountCent: 2500, TotalRefundAmountCent: 400, PendingRefundAmountCent: 70, SuccessfulPayCount: 5, PartialRefundCount: 2, PendingRefundCount: 1}, } settlementRows := []dailySettlementRow{ {PlatformIncomeAmountCent: 300, OwnerShouldIncomeAmountCent: 900, OwnerWalletIncomeAmountCent: 850, OwnerEffectiveSettlementAmountCent: 850, OfflineSettlementAmountCent: 100, OfflineSettlementPendingAmountCent: 20, OfflineSettlementPendingCount: 1, FinancialExceptionCount: 2, SettledOrderCount: 3}, {PlatformIncomeAmountCent: 200, OwnerShouldIncomeAmountCent: 600, OwnerWalletIncomeAmountCent: 500, OwnerEffectiveSettlementAmountCent: 550, OfflineSettlementAmountCent: 200, OfflineSettlementPendingAmountCent: 40, OfflineSettlementPendingCount: 2, FinancialExceptionCount: 1, SettledOrderCount: 2}, } estimateRows := []dailyEstimatedRow{ {EstimatedIncomeAmountCent: 120, PendingSettleOrderCount: 4}, {EstimatedIncomeAmountCent: 80, PendingSettleOrderCount: 3}, } pickup := &PickupSummaryDTO{ProfitAmountCent: 90, CompletedCount: 2, PendingAmountCent: 60, PendingCount: 3} summary := summaryWithPickup(summaryFromDailyRows(paymentRows, settlementRows, estimateRows), pickup) if summary.TotalFlowAmountCent != 3500 || summary.TotalRefundAmountCent != 500 || summary.ChannelNetAmountCent != 3000 { t.Fatalf("支付汇总错误: %+v", summary) } if summary.PendingRefundAmountCent != 100 || summary.SuccessfulPayCount != 8 || summary.SuccessfulRefundCount != 3 || summary.FullRefundCount != 1 || summary.PartialRefundCount != 2 || summary.PendingRefundCount != 1 { t.Fatalf("支付笔数汇总错误: %+v", summary) } if summary.NormalOrderProfitAmountCent != 500 || summary.PickupProfitAmountCent != 90 || summary.PlatformIncomeAmountCent != 590 || summary.PickupCompletedCount != 2 { t.Fatalf("平台利润汇总错误: %+v", summary) } if summary.OwnerShouldIncomeAmountCent != 1500 || summary.OwnerWalletIncomeAmountCent != 1350 || summary.OwnerEffectiveSettlementAmountCent != 1400 || summary.SettlementDiffAmountCent != 100 { t.Fatalf("货主结算汇总错误: %+v", summary) } if summary.OfflineSettlementAmountCent != 300 || summary.OfflineSettlementPendingAmountCent != 120 || summary.OfflineSettlementPendingCount != 6 { t.Fatalf("线下结算汇总错误: %+v", summary) } if summary.EstimatedIncomeAmountCent != 200 || summary.PendingSettleOrderCount != 7 || summary.SettledOrderCount != 5 || summary.FinancialExceptionCount != 3 { t.Fatalf("订单状态汇总错误: %+v", summary) } } func TestDashboardCacheKeyAndSingleflight(t *testing.T) { repo := NewRepository(nil) q := DashboardQuery{ StartDate: time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), EndDate: time.Date(2026, 9, 7, 0, 0, 0, 0, time.UTC), } key := repo.dashboardCacheKey(q) if key == "" { t.Fatal("cache key should not be empty") } var callCount atomic.Int32 var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() _, _, _ = repo.sfGroup.Do(key, func() (any, error) { callCount.Add(1) time.Sleep(20 * time.Millisecond) return &DashboardDTO{}, nil }) }() } wg.Wait() if count := callCount.Load(); count != 1 { t.Fatalf("singleflight 并发合并失败: got %d, want 1", count) } }