feat(tenant): 按租户隔离支付退款与商户配置
This commit is contained in:
@@ -6,6 +6,7 @@ import (
|
||||
"sync"
|
||||
|
||||
ordermodule "hfb_sys/backend/internal/modules/order"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
)
|
||||
|
||||
@@ -14,7 +15,7 @@ func (r *Repository) Dashboard(ctx context.Context, query DashboardQuery) (*Dash
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
key := r.dashboardCacheKey(query)
|
||||
key := r.dashboardCacheKey(ctx, query)
|
||||
val, err, _ := r.sfGroup.Do(key, func() (any, error) {
|
||||
// 在 singleflight 内部二次检查缓存,避免排队等待的并发请求重复执行大聚合
|
||||
if cached := r.loadDashboardCache(ctx, query); cached != nil {
|
||||
@@ -90,6 +91,9 @@ func (r *Repository) calculateDashboard(ctx context.Context, query DashboardQuer
|
||||
|
||||
func (r *Repository) operatingExpenseSummary(ctx context.Context, query DashboardQuery) (*OperatingExpenseSummaryDTO, error) {
|
||||
var summary OperatingExpenseSummaryDTO
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
return &summary, nil
|
||||
}
|
||||
err := r.db.WithContext(ctx).Table("operating_expenses").
|
||||
Select("COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count").
|
||||
Where("status = ?", "paid").
|
||||
@@ -103,6 +107,9 @@ func (r *Repository) operatingExpenseSummary(ctx context.Context, query Dashboar
|
||||
|
||||
// pickupSummary 线下提号统计,独立查询 admin_pickups 表,不混入正常订单口径。
|
||||
func (r *Repository) pickupSummary(ctx context.Context, query DashboardQuery) (*PickupSummaryDTO, error) {
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
return &PickupSummaryDTO{}, nil
|
||||
}
|
||||
db := r.db.WithContext(ctx)
|
||||
var row struct {
|
||||
SettledAmountCent int64
|
||||
@@ -170,7 +177,11 @@ func (r *Repository) mohongSummary(ctx context.Context, query DashboardQuery) (*
|
||||
RefundAmountCent int64
|
||||
PaidOrderCount int64
|
||||
}
|
||||
if err := db.Table("payment_orders").
|
||||
paymentQuery := db.Table("payment_orders")
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
paymentQuery = paymentQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := paymentQuery.
|
||||
Select(`COALESCE(SUM(CASE WHEN biz_type = 'mohong_pay' AND status = 'paid' THEN amount_cent ELSE 0 END), 0) AS flow_amount_cent,
|
||||
COALESCE(SUM(CASE WHEN biz_type = 'mohong_refund' AND status = 'refunded' THEN amount_cent ELSE 0 END), 0) AS refund_amount_cent,
|
||||
COALESCE(SUM(CASE WHEN biz_type = 'mohong_pay' AND status = 'paid' THEN 1 ELSE 0 END), 0) AS paid_order_count`).
|
||||
@@ -240,25 +251,29 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
||||
}
|
||||
|
||||
pickupProfits := make([]dailyPickupProfitRow, 0)
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
||||
Select(`DATE_FORMAT(completed_at, '%Y-%m-%d') AS date,
|
||||
if tenancy.IDFromContext(ctx) == 0 {
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
||||
Select(`DATE_FORMAT(completed_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent,
|
||||
COUNT(id) AS completed_count`).
|
||||
Where("status = ?", "completed").
|
||||
Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(completed_at, '%Y-%m-%d')").
|
||||
Scan(&pickupProfits).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
Where("status = ?", "completed").
|
||||
Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(completed_at, '%Y-%m-%d')").
|
||||
Scan(&pickupProfits).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
}
|
||||
}
|
||||
pickupAdjustments := make([]dailyPickupAdjustmentRow, 0)
|
||||
if err := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
Select(`DATE_FORMAT(fa.created_at, '%Y-%m-%d') AS date,
|
||||
if tenancy.IDFromContext(ctx) == 0 {
|
||||
if err := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
Select(`DATE_FORMAT(fa.created_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(fa.profit_delta_cent), 0) AS profit_amount_cent`).
|
||||
Joins("JOIN admin_pickups AS p ON p.id = fa.pickup_id AND p.status = ?", "completed").
|
||||
Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(fa.created_at, '%Y-%m-%d')").
|
||||
Scan(&pickupAdjustments).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
Joins("JOIN admin_pickups AS p ON p.id = fa.pickup_id AND p.status = ?", "completed").
|
||||
Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(fa.created_at, '%Y-%m-%d')").
|
||||
Scan(&pickupAdjustments).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
}
|
||||
}
|
||||
|
||||
// 取消提号按取消日统计,与「已付款订单数」中的提号创建口径区分开。
|
||||
@@ -388,13 +403,17 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
||||
|
||||
func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) ([]dailyEstimatedRow, error) {
|
||||
rows := make([]dailyEstimatedRow, 0)
|
||||
err := r.db.WithContext(ctx).Table("rental_orders USE INDEX (idx_rental_orders_dashboard_estimates)").
|
||||
orderQuery := r.db.WithContext(ctx).Table("rental_orders USE INDEX (idx_rental_orders_dashboard_estimates)").
|
||||
Select(`DATE_FORMAT(created_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent,
|
||||
COUNT(id) AS pending_settle_order_count`).
|
||||
Where("settlement_status NOT IN ?", settledSettlementStatuses()).
|
||||
Where("status NOT IN ?", nonBillableOrderStatuses()).
|
||||
Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate).
|
||||
Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
orderQuery = orderQuery.Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID)
|
||||
}
|
||||
err := orderQuery.
|
||||
Group("DATE_FORMAT(created_at, '%Y-%m-%d')").
|
||||
Scan(&rows).Error
|
||||
return rows, err
|
||||
@@ -403,7 +422,7 @@ func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) (
|
||||
func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery) ([]dailySettlementRow, error) {
|
||||
db := r.db.WithContext(ctx)
|
||||
rows := make([]dailySettlementRow, 0)
|
||||
err := db.Table("rental_orders AS ro USE INDEX (idx_rental_orders_dashboard_settled)").
|
||||
settlementQuery := db.Table("rental_orders AS ro USE INDEX (idx_rental_orders_dashboard_settled)").
|
||||
Select(`DATE_FORMAT(ro.settled_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent,
|
||||
COALESCE(SUM(CASE WHEN ro.compensation_plan = 'insurance' AND ro.insurance_fee_bps > 0
|
||||
@@ -459,7 +478,11 @@ func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery)
|
||||
// (由 dispute 模块写入),不纳入本指标,此处保持既有口径不变。
|
||||
Joins("JOIN order_checkouts AS oc USE INDEX (idx_order_checkouts_dashboard_accepted) ON oc.order_id = ro.id AND oc.status = ?", ordermodule.CheckoutStatusAccepted).
|
||||
Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeForSettledOrdersSubquery(db, query)).
|
||||
Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
settlementQuery = settlementQuery.Where("(ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)", tenantID, tenantID)
|
||||
}
|
||||
err := settlementQuery.
|
||||
Group("DATE_FORMAT(ro.settled_at, '%Y-%m-%d')").
|
||||
Scan(&rows).Error
|
||||
return rows, err
|
||||
@@ -541,7 +564,11 @@ func operatingExpenseSummaryFromDailyRows(rows []dailyOperatingExpenseRow) Opera
|
||||
func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([]dailyPaymentRow, error) {
|
||||
rows := make([]dailyPaymentRow, 0)
|
||||
db := r.db.WithContext(ctx)
|
||||
err := db.Table("payment_orders AS po USE INDEX (idx_payment_orders_dashboard_created)").
|
||||
paymentQuery := db.Table("payment_orders AS po USE INDEX (idx_payment_orders_dashboard_created)")
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
paymentQuery = paymentQuery.Where("po.tenant_id = ?", tenantID)
|
||||
}
|
||||
err := paymentQuery.
|
||||
Select(`DATE_FORMAT(po.created_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'paid' THEN po.amount_cent ELSE 0 END), 0) AS total_flow_amount_cent,
|
||||
COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' THEN po.amount_cent ELSE 0 END), 0) AS total_refund_amount_cent,
|
||||
@@ -565,6 +592,9 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([
|
||||
// dailyPickupCancelled 按取消日统计线下提号取消笔数。
|
||||
func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQuery) ([]dailyPickupCancelledRow, error) {
|
||||
rows := make([]dailyPickupCancelledRow, 0)
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
return rows, nil
|
||||
}
|
||||
err := r.db.WithContext(ctx).Table("admin_pickups").
|
||||
Select(`DATE_FORMAT(cancelled_at, '%Y-%m-%d') AS date, COUNT(id) AS count`).
|
||||
Where("status = ?", "cancelled").
|
||||
@@ -577,17 +607,27 @@ func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQu
|
||||
// dailyPaidOrders 按实际付款日统计普通租赁订单,并将已完成的线下提号按完成日计入成交。
|
||||
func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery) ([]dailyPaidOrderRow, error) {
|
||||
items := make([]dailyPaidOrderRow, 0)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
paymentTenantFilter := ""
|
||||
pickupTenantFilter := ""
|
||||
args := []any{query.StartDate, query.EndDate}
|
||||
if tenantID > 0 {
|
||||
paymentTenantFilter = " AND tenant_id = ?"
|
||||
pickupTenantFilter = " AND 1 = 0"
|
||||
args = append(args, tenantID)
|
||||
}
|
||||
args = append(args, query.StartDate, query.EndDate)
|
||||
err := r.db.WithContext(ctx).Table(`(
|
||||
SELECT DATE_FORMAT(paid_at, '%Y-%m-%d') AS date, COUNT(DISTINCT order_id) AS paid_order_count
|
||||
FROM payment_orders USE INDEX (idx_payment_orders_biz_status_paid_at_order)
|
||||
WHERE biz_type = 'order_pay' AND status = 'paid' AND paid_at >= ? AND paid_at <= ?
|
||||
WHERE biz_type = 'order_pay' AND status = 'paid' AND paid_at >= ? AND paid_at <= ?`+paymentTenantFilter+`
|
||||
GROUP BY DATE_FORMAT(paid_at, '%Y-%m-%d')
|
||||
UNION ALL
|
||||
SELECT DATE_FORMAT(completed_at, '%Y-%m-%d') AS date, COUNT(id) AS paid_order_count
|
||||
FROM admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)
|
||||
WHERE status = 'completed' AND completed_at >= ? AND completed_at <= ?
|
||||
WHERE status = 'completed' AND completed_at >= ? AND completed_at <= ?`+pickupTenantFilter+`
|
||||
GROUP BY DATE_FORMAT(completed_at, '%Y-%m-%d')
|
||||
) AS daily_paid_orders`, query.StartDate, query.EndDate, query.StartDate, query.EndDate).
|
||||
) AS daily_paid_orders`, args...).
|
||||
Select("date, SUM(paid_order_count) AS paid_order_count").
|
||||
Group("date").
|
||||
Scan(&items).Error
|
||||
|
||||
@@ -5,19 +5,21 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
const dashboardCacheTTL = 5 * time.Minute
|
||||
|
||||
func (r *Repository) dashboardCacheKey(query DashboardQuery) string {
|
||||
return fmt.Sprintf("admin-finance:dashboard:v2:%d:%d", query.StartDate.Unix(), query.EndDate.Unix())
|
||||
func (r *Repository) dashboardCacheKey(ctx context.Context, query DashboardQuery) string {
|
||||
return fmt.Sprintf("admin-finance:dashboard:v3:%d:%d:%d", tenancy.IDFromContext(ctx), query.StartDate.Unix(), query.EndDate.Unix())
|
||||
}
|
||||
|
||||
func (r *Repository) loadDashboardCache(ctx context.Context, query DashboardQuery) *DashboardDTO {
|
||||
if r.redis == nil {
|
||||
return nil
|
||||
}
|
||||
raw, err := r.redis.Get(ctx, r.dashboardCacheKey(query)).Bytes()
|
||||
raw, err := r.redis.Get(ctx, r.dashboardCacheKey(ctx, query)).Bytes()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -37,5 +39,5 @@ func (r *Repository) storeDashboardCache(ctx context.Context, query DashboardQue
|
||||
return
|
||||
}
|
||||
// 缓存不可用时静默降级到实时统计,不能影响财务页面可用性。
|
||||
_ = r.redis.Set(ctx, r.dashboardCacheKey(query), raw, dashboardCacheTTL).Err()
|
||||
_ = r.redis.Set(ctx, r.dashboardCacheKey(ctx, query), raw, dashboardCacheTTL).Err()
|
||||
}
|
||||
|
||||
@@ -346,7 +346,7 @@ func TestDashboardCacheKeyAndSingleflight(t *testing.T) {
|
||||
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)
|
||||
key := repo.dashboardCacheKey(t.Context(), q)
|
||||
if key == "" {
|
||||
t.Fatal("cache key should not be empty")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
package adminfinance
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type dailyOperatingExpenseRow struct {
|
||||
Date string
|
||||
@@ -10,6 +16,9 @@ type dailyOperatingExpenseRow struct {
|
||||
|
||||
func (r *Repository) dailyOperatingExpenses(ctx context.Context, query DashboardQuery) ([]dailyOperatingExpenseRow, error) {
|
||||
rows := make([]dailyOperatingExpenseRow, 0)
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
return rows, nil
|
||||
}
|
||||
err := r.db.WithContext(ctx).Table("operating_expenses").
|
||||
Select(`DATE_FORMAT(occurred_at, '%Y-%m-%d') AS date, COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("status = ?", "paid").
|
||||
@@ -22,12 +31,13 @@ func (r *Repository) dailyOperatingExpenses(ctx context.Context, query Dashboard
|
||||
// disbursementSummary 使用实际确认打款时间统计区间出款,同时返回不受日期限制的当前待办。
|
||||
func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQuery) (*DisbursementSummaryDTO, error) {
|
||||
db := r.db.WithContext(ctx)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
|
||||
var offlinePaid struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("rental_orders USE INDEX (idx_rental_orders_dashboard_offline_settlement)").
|
||||
if err := applyRentalOrderTenantScope(db.Table("rental_orders USE INDEX (idx_rental_orders_dashboard_offline_settlement)"), tenantID).
|
||||
Select(`COALESCE(SUM(offline_settlement_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
@@ -39,33 +49,37 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&pickupPaid).Error; err != nil {
|
||||
return nil, err
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&pickupPaid).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var pickupAdjustmentPaid struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "settled").
|
||||
Where("settle_delta_cent > 0").
|
||||
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&pickupAdjustmentPaid).Error; err != nil {
|
||||
return nil, err
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "settled").
|
||||
Where("settle_delta_cent > 0").
|
||||
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&pickupAdjustmentPaid).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var offlinePending struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("rental_orders USE INDEX (idx_rental_orders_dashboard_offline_settlement)").
|
||||
if err := applyRentalOrderTenantScope(db.Table("rental_orders USE INDEX (idx_rental_orders_dashboard_offline_settlement)"), tenantID).
|
||||
Select(`COALESCE(SUM(offline_settlement_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "pending").
|
||||
@@ -77,25 +91,29 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "pending").
|
||||
Where("settle_amount_cent > 0").
|
||||
Scan(&pickupPending).Error; err != nil {
|
||||
return nil, err
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "pending").
|
||||
Where("settle_amount_cent > 0").
|
||||
Scan(&pickupPending).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var pickupAdjustmentPending struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "pending").
|
||||
Where("settle_delta_cent > 0").
|
||||
Scan(&pickupAdjustmentPending).Error; err != nil {
|
||||
return nil, err
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "pending").
|
||||
Where("settle_delta_cent > 0").
|
||||
Scan(&pickupAdjustmentPending).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// 付款、处理中、待审核三类提现在一次条件聚合中完成,避免同一张表重复扫描。
|
||||
@@ -109,7 +127,11 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
ReviewAmountCent int64
|
||||
ReviewCount int64
|
||||
}
|
||||
if err := db.Table("withdrawal_requests").Select(`
|
||||
withdrawalQuery := db.Table("withdrawal_requests")
|
||||
if tenantID > 0 {
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := withdrawalQuery.Select(`
|
||||
COALESCE(SUM(CASE WHEN status = 'completed' AND paid_at >= ? AND paid_at <= ? THEN amount_cent ELSE 0 END), 0) AS paid_amount_cent,
|
||||
COALESCE(SUM(CASE WHEN status = 'completed' AND paid_at >= ? AND paid_at <= ? THEN fee_cent ELSE 0 END), 0) AS paid_fee_amount_cent,
|
||||
COALESCE(SUM(CASE WHEN status = 'completed' AND paid_at >= ? AND paid_at <= ? THEN actual_amount_cent ELSE 0 END), 0) AS paid_actual_amount_cent,
|
||||
@@ -128,12 +150,14 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("manual_disbursements").
|
||||
Select(`COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("status = ?", "paid").
|
||||
Where("paid_at >= ? AND paid_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&manualPaid).Error; err != nil {
|
||||
return nil, err
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("manual_disbursements").
|
||||
Select(`COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("status = ?", "paid").
|
||||
Where("paid_at >= ? AND paid_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&manualPaid).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &DisbursementSummaryDTO{
|
||||
@@ -160,8 +184,9 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
|
||||
func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuery) ([]dailyDisbursementRow, error) {
|
||||
db := r.db.WithContext(ctx)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
offlineRows := make([]dailyDisbursementSourceRow, 0)
|
||||
if err := db.Table("rental_orders USE INDEX (idx_rental_orders_dashboard_offline_settlement)").
|
||||
if err := applyRentalOrderTenantScope(db.Table("rental_orders USE INDEX (idx_rental_orders_dashboard_offline_settlement)"), tenantID).
|
||||
Select(`DATE_FORMAT(offline_settled_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(offline_settlement_amount_cent), 0) AS amount_cent,
|
||||
COUNT(id) AS count`).
|
||||
@@ -173,35 +198,43 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
||||
return nil, err
|
||||
}
|
||||
pickupOfflineRows := make([]dailyDisbursementSourceRow, 0)
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`DATE_FORMAT(offline_settled_at, '%Y-%m-%d') AS date,
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`DATE_FORMAT(offline_settled_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(settle_amount_cent), 0) AS amount_cent,
|
||||
COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(offline_settled_at, '%Y-%m-%d')").
|
||||
Scan(&pickupOfflineRows).Error; err != nil {
|
||||
return nil, err
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(offline_settled_at, '%Y-%m-%d')").
|
||||
Scan(&pickupOfflineRows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
pickupAdjustmentRows := make([]dailyDisbursementSourceRow, 0)
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`DATE_FORMAT(settled_at, '%Y-%m-%d') AS date,
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`DATE_FORMAT(settled_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(settle_delta_cent), 0) AS amount_cent,
|
||||
COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "settled").
|
||||
Where("settle_delta_cent > 0").
|
||||
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(settled_at, '%Y-%m-%d')").
|
||||
Scan(&pickupAdjustmentRows).Error; err != nil {
|
||||
return nil, err
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "settled").
|
||||
Where("settle_delta_cent > 0").
|
||||
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(settled_at, '%Y-%m-%d')").
|
||||
Scan(&pickupAdjustmentRows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
offlineRows = append(offlineRows, pickupOfflineRows...)
|
||||
offlineRows = append(offlineRows, pickupAdjustmentRows...)
|
||||
|
||||
withdrawalRows := make([]dailyDisbursementSourceRow, 0)
|
||||
if err := db.Table("withdrawal_requests").
|
||||
withdrawalQuery := db.Table("withdrawal_requests")
|
||||
if tenantID > 0 {
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := withdrawalQuery.
|
||||
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(actual_amount_cent), 0) AS amount_cent,
|
||||
COUNT(id) AS count`).
|
||||
@@ -213,15 +246,17 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
||||
}
|
||||
|
||||
manualRows := make([]dailyDisbursementSourceRow, 0)
|
||||
if err := db.Table("manual_disbursements").
|
||||
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("manual_disbursements").
|
||||
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(amount_cent), 0) AS amount_cent,
|
||||
COUNT(id) AS count`).
|
||||
Where("status = ?", "paid").
|
||||
Where("paid_at >= ? AND paid_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(paid_at, '%Y-%m-%d')").
|
||||
Scan(&manualRows).Error; err != nil {
|
||||
return nil, err
|
||||
Where("status = ?", "paid").
|
||||
Where("paid_at >= ? AND paid_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(paid_at, '%Y-%m-%d')").
|
||||
Scan(&manualRows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
rowsByDate := make(map[string]dailyDisbursementRow, len(offlineRows)+len(withdrawalRows)+len(manualRows))
|
||||
@@ -259,6 +294,13 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func applyRentalOrderTenantScope(db *gorm.DB, tenantID uint64) *gorm.DB {
|
||||
if tenantID == 0 {
|
||||
return db
|
||||
}
|
||||
return db.Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID)
|
||||
}
|
||||
|
||||
type dailyDisbursementSourceRow struct {
|
||||
Date string
|
||||
AmountCent int64
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package adminfinance
|
||||
|
||||
import (
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -14,15 +16,18 @@ func acceptedCheckoutForOrdersSubquery(db *gorm.DB, orderIDs []uint64) *gorm.DB
|
||||
}
|
||||
|
||||
func orderPaymentForOrdersSubquery(db *gorm.DB, orderIDs []uint64) *gorm.DB {
|
||||
return db.Table("payment_orders").
|
||||
query := db.Table("payment_orders").
|
||||
Select(`order_id,
|
||||
COALESCE(SUM(CASE WHEN biz_type = 'order_pay' AND status = 'paid' THEN amount_cent ELSE 0 END), 0) AS paid_amount_cent,
|
||||
COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunded' THEN amount_cent ELSE 0 END), 0) AS refunded_amount_cent,
|
||||
COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunding' THEN amount_cent ELSE 0 END), 0) AS refunding_amount_cent,
|
||||
COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'failed' THEN amount_cent ELSE 0 END), 0) AS failed_refund_amount_cent`,
|
||||
refundBizTypes(), refundBizTypes(), refundBizTypes()).
|
||||
Where("order_id IN ?", orderIDs).
|
||||
Group("order_id")
|
||||
Where("order_id IN ?", orderIDs)
|
||||
if tenantID := tenancy.IDFromContext(db.Statement.Context); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
return query.Group("order_id")
|
||||
}
|
||||
|
||||
func ownerWalletIncomeForOrdersSubquery(db *gorm.DB, orderIDs []uint64) *gorm.DB {
|
||||
@@ -50,13 +55,20 @@ func ownerWalletIncomeForSettledOrdersSubquery(db *gorm.DB, query DashboardQuery
|
||||
// paymentOriginalAmountForRefundsInRangeSubquery 仅为当前区间内的退款单回查原支付金额。
|
||||
// 退款统计原先会对全部历史支付单按 order_id 聚合;数据增长后这部分即使只看一天也会很慢。
|
||||
func paymentOriginalAmountForRefundsInRangeSubquery(db *gorm.DB, query DashboardQuery) *gorm.DB {
|
||||
tenantID := tenancy.IDFromContext(db.Statement.Context)
|
||||
refundOrders := db.Table("payment_orders AS refund USE INDEX (idx_payment_orders_dashboard_created)").
|
||||
Select("DISTINCT refund.order_id").
|
||||
Where("refund.biz_type IN ? AND refund.status = ?", refundBizTypes(), "refunded").
|
||||
Where("refund.created_at >= ? AND refund.created_at <= ?", query.StartDate, query.EndDate)
|
||||
return db.Table("payment_orders AS paid USE INDEX (idx_payment_orders_dashboard_order)").
|
||||
if tenantID > 0 {
|
||||
refundOrders = refundOrders.Where("refund.tenant_id = ?", tenantID)
|
||||
}
|
||||
paidQuery := db.Table("payment_orders AS paid USE INDEX (idx_payment_orders_dashboard_order)").
|
||||
Select("paid.order_id, MAX(paid.amount_cent) AS amount_cent").
|
||||
Joins("JOIN (?) AS refund_order ON refund_order.order_id = paid.order_id", refundOrders).
|
||||
Where("paid.biz_type IN ? AND paid.status = ?", payBizTypes(), "paid").
|
||||
Group("paid.order_id")
|
||||
Where("paid.biz_type IN ? AND paid.status = ?", payBizTypes(), "paid")
|
||||
if tenantID > 0 {
|
||||
paidQuery = paidQuery.Where("paid.tenant_id = ?", tenantID)
|
||||
}
|
||||
return paidQuery.Group("paid.order_id")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package adminfinance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
func financeTenantContext(tenantID uint64) context.Context {
|
||||
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
|
||||
func TestFinancePaymentStatsAreScopedByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
now := time.Now()
|
||||
payments := []model.PaymentOrder{
|
||||
{
|
||||
TenantID: 101, PaymentNo: "PAY-FIN-A", OrderID: 1, OrderNo: "RO-FIN-A",
|
||||
UserID: 1, PaymentConfigID: 1, Provider: "mock", MerchantID: "A",
|
||||
ThirdOrderID: "PAY-FIN-A", PayWay: "ZFBZF", AmountCent: 1000,
|
||||
BizType: "order_pay", Status: "paid", PaidAt: &now,
|
||||
},
|
||||
{
|
||||
TenantID: 202, PaymentNo: "PAY-FIN-B", OrderID: 2, OrderNo: "RO-FIN-B",
|
||||
UserID: 2, PaymentConfigID: 2, Provider: "mock", MerchantID: "B",
|
||||
ThirdOrderID: "PAY-FIN-B", PayWay: "ZFBZF", AmountCent: 2000,
|
||||
BizType: "order_pay", Status: "paid", PaidAt: &now,
|
||||
},
|
||||
}
|
||||
if err := db.Create(&payments).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
query := DashboardQuery{StartDate: now.Add(-time.Hour), EndDate: now.Add(time.Hour)}
|
||||
rows, err := repo.dailyPayments(financeTenantContext(101), query)
|
||||
if err != nil {
|
||||
t.Fatalf("daily payments: %v", err)
|
||||
}
|
||||
var flow int64
|
||||
for _, row := range rows {
|
||||
flow += row.TotalFlowAmountCent
|
||||
}
|
||||
if flow != 1000 {
|
||||
t.Fatalf("dachui payment flow = %d, want 1000", flow)
|
||||
}
|
||||
if repo.dashboardCacheKey(financeTenantContext(101), query) == repo.dashboardCacheKey(financeTenantContext(202), query) {
|
||||
t.Fatal("dashboard cache key must include tenant")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user