feat(adminfinance): 新增预计收入指标并优化明细查询性能
- 财务看板增加预计收入与待结算订单数统计 - 明细列表 COUNT 改为仅扫描 rental_orders 主表,避免 5-JOIN 子查询 - 统一前后端结算差异判定阈值为常量 5 分 - 修复日期选择器使用 UTC 日期导致东八区凌晨偏移前一天的问题
This commit is contained in:
@@ -62,6 +62,18 @@ func (r *Repository) summary(ctx context.Context, query DashboardQuery) (*Financ
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 预计收入:尚未结算订单的下单预估平台手续费之和,按下单时间落在查询区间内统计。
|
||||
var estimated estimatedIncomeRow
|
||||
if err := db.Table("rental_orders").
|
||||
Select(`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).
|
||||
Scan(&estimated).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &FinanceSummaryDTO{
|
||||
TotalFlowAmountCent: payment.TotalFlowAmountCent,
|
||||
TotalRefundAmountCent: payment.TotalRefundAmountCent,
|
||||
@@ -71,10 +83,12 @@ func (r *Repository) summary(ctx context.Context, query DashboardQuery) (*Financ
|
||||
OwnerShouldIncomeAmountCent: settlement.OwnerShouldIncomeAmountCent,
|
||||
OwnerWalletIncomeAmountCent: settlement.OwnerWalletIncomeAmountCent,
|
||||
SettlementDiffAmountCent: settlement.OwnerShouldIncomeAmountCent - settlement.OwnerWalletIncomeAmountCent,
|
||||
EstimatedIncomeAmountCent: estimated.EstimatedIncomeAmountCent,
|
||||
SuccessfulPayCount: payment.SuccessfulPayCount,
|
||||
SuccessfulRefundCount: payment.SuccessfulRefundCount,
|
||||
PendingRefundCount: payment.PendingRefundCount,
|
||||
SettledOrderCount: settlement.SettledOrderCount,
|
||||
PendingSettleOrderCount: estimated.PendingSettleOrderCount,
|
||||
FinancialExceptionCount: exceptionCount,
|
||||
}, nil
|
||||
}
|
||||
@@ -112,6 +126,19 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) ([]Fi
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 每日预计收入:尚未结算订单的下单预估平台手续费,按下单日期归集,口径与 summary 一致。
|
||||
estimates := make([]dailyEstimatedRow, 0)
|
||||
if err := db.Table("rental_orders").
|
||||
Select(`DATE(created_at) AS date,
|
||||
COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent`).
|
||||
Where("settlement_status NOT IN ?", settledSettlementStatuses()).
|
||||
Where("status NOT IN ?", nonBillableOrderStatuses()).
|
||||
Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE(created_at)").
|
||||
Scan(&estimates).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
itemsByDate := make(map[string]FinanceDailyDTO)
|
||||
for day := dayStart(query.StartDate); !day.After(query.EndDate); day = day.AddDate(0, 0, 1) {
|
||||
date := day.Format("2006-01-02")
|
||||
@@ -141,6 +168,13 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) ([]Fi
|
||||
item.SettledOrderCount = row.SettledOrderCount
|
||||
itemsByDate[date] = item
|
||||
}
|
||||
for _, row := range estimates {
|
||||
date := dailyDateKey(row.Date)
|
||||
item := itemsByDate[date]
|
||||
item.Date = date
|
||||
item.EstimatedIncomeAmountCent = row.EstimatedIncomeAmountCent
|
||||
itemsByDate[date] = item
|
||||
}
|
||||
|
||||
items := make([]FinanceDailyDTO, 0, len(itemsByDate))
|
||||
for day := dayStart(query.StartDate); !day.After(query.EndDate); day = day.AddDate(0, 0, 1) {
|
||||
@@ -165,6 +199,11 @@ type settlementSummaryRow struct {
|
||||
SettledOrderCount int64
|
||||
}
|
||||
|
||||
type estimatedIncomeRow struct {
|
||||
EstimatedIncomeAmountCent int64
|
||||
PendingSettleOrderCount int64
|
||||
}
|
||||
|
||||
type dailyPaymentRow struct {
|
||||
Date string
|
||||
TotalFlowAmountCent int64
|
||||
@@ -182,3 +221,8 @@ type dailySettlementRow struct {
|
||||
OwnerWalletIncomeAmountCent int64
|
||||
SettledOrderCount int64
|
||||
}
|
||||
|
||||
type dailyEstimatedRow struct {
|
||||
Date string
|
||||
EstimatedIncomeAmountCent int64
|
||||
}
|
||||
|
||||
@@ -7,14 +7,20 @@ import (
|
||||
)
|
||||
|
||||
func (r *Repository) Details(ctx context.Context, query DetailQuery) (*PaginatedResult, error) {
|
||||
baseDB := r.db.WithContext(ctx)
|
||||
db := r.financeDetailBaseQuery(ctx, query)
|
||||
// COUNT 只扫描 rental_orders 主表(过滤条件全部落在 ro.* 上,可命中
|
||||
// idx_rental_orders_settled_at_id / created_at_id 索引),不再套完整 5-JOIN
|
||||
// 子查询,避免大数据量翻页时 COUNT 拖慢。
|
||||
countDB := r.applyDetailFilters(r.db.WithContext(ctx).Table("rental_orders AS ro"), query)
|
||||
var total int64
|
||||
countDB := baseDB.Table("(?) AS finance_rows", db)
|
||||
if err := countDB.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if total == 0 {
|
||||
return &PaginatedResult{Items: []FinanceDetailDTO{}, Total: 0, Page: query.Page, PageSize: query.PageSize}, nil
|
||||
}
|
||||
|
||||
// 明细行查询保留完整 JOIN,仅对当前分页命中的订单做金额聚合。
|
||||
db := r.financeDetailBaseQuery(ctx, query)
|
||||
offset := (query.Page - 1) * query.PageSize
|
||||
rows := make([]financeDetailRow, 0, query.PageSize)
|
||||
if err := db.Order("ro.id DESC").Offset(offset).Limit(query.PageSize).Scan(&rows).Error; err != nil {
|
||||
@@ -27,6 +33,31 @@ func (r *Repository) Details(ctx context.Context, query DetailQuery) (*Paginated
|
||||
return &PaginatedResult{Items: items, Total: total, Page: query.Page, PageSize: query.PageSize}, nil
|
||||
}
|
||||
|
||||
// applyDetailFilters 把仅依赖 rental_orders 主表字段的过滤条件挂到查询上,
|
||||
// COUNT 与明细行查询共用,保证两者口径一致。
|
||||
func (r *Repository) applyDetailFilters(db *gorm.DB, query DetailQuery) *gorm.DB {
|
||||
if query.OrderNo != "" {
|
||||
db = db.Where("ro.order_no = ?", query.OrderNo)
|
||||
}
|
||||
if query.UserID > 0 {
|
||||
db = db.Where("(ro.renter_id = ? OR ro.owner_id = ?)", query.UserID, query.UserID)
|
||||
}
|
||||
if query.OrderStatus != "" {
|
||||
db = db.Where("ro.status = ?", query.OrderStatus)
|
||||
}
|
||||
if query.SettlementStatus != "" {
|
||||
db = db.Where("ro.settlement_status = ?", query.SettlementStatus)
|
||||
}
|
||||
if !query.StartDate.IsZero() && !query.EndDate.IsZero() {
|
||||
if query.DateType == "created" {
|
||||
db = db.Where("ro.created_at >= ? AND ro.created_at <= ?", query.StartDate, query.EndDate)
|
||||
} else {
|
||||
db = db.Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate)
|
||||
}
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func (r *Repository) financeDetailBaseQuery(ctx context.Context, query DetailQuery) *gorm.DB {
|
||||
db := r.db.WithContext(ctx).Table("rental_orders AS ro").
|
||||
Select(`ro.id AS order_id, ro.order_no, ro.status AS order_status, ro.settlement_status, ro.refund_status,
|
||||
@@ -48,34 +79,15 @@ func (r *Repository) financeDetailBaseQuery(ctx context.Context, query DetailQue
|
||||
CASE
|
||||
WHEN COALESCE(p.failed_refund_amount_cent, 0) > 0 THEN 'refund_failed'
|
||||
WHEN COALESCE(p.refunding_amount_cent, 0) > 0 OR ro.refund_status = 'refunding' THEN 'refund_pending'
|
||||
WHEN ABS(COALESCE(oc.owner_income_amount_cent, 0) - COALESCE(w.owner_wallet_income_amount_cent, 0)) >= 5 THEN 'settlement_diff'
|
||||
WHEN ABS(COALESCE(oc.owner_income_amount_cent, 0) - COALESCE(w.owner_wallet_income_amount_cent, 0)) >= ? THEN 'settlement_diff'
|
||||
ELSE 'normal'
|
||||
END AS finance_status,
|
||||
ro.created_at, ro.settled_at`).
|
||||
ro.created_at, ro.settled_at`, settlementDiffThresholdCent).
|
||||
Joins("LEFT JOIN users AS ru ON ru.id = ro.renter_id").
|
||||
Joins("LEFT JOIN users AS ou ON ou.id = ro.owner_id").
|
||||
Joins("LEFT JOIN (?) AS oc ON oc.order_id = ro.id", acceptedCheckoutSubquery(r.db.WithContext(ctx))).
|
||||
Joins("LEFT JOIN (?) AS p ON p.order_id = ro.id", orderPaymentSubquery(r.db.WithContext(ctx))).
|
||||
Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeSubquery(r.db.WithContext(ctx)))
|
||||
|
||||
if query.OrderNo != "" {
|
||||
db = db.Where("ro.order_no = ?", query.OrderNo)
|
||||
}
|
||||
if query.UserID > 0 {
|
||||
db = db.Where("(ro.renter_id = ? OR ro.owner_id = ?)", query.UserID, query.UserID)
|
||||
}
|
||||
if query.OrderStatus != "" {
|
||||
db = db.Where("ro.status = ?", query.OrderStatus)
|
||||
}
|
||||
if query.SettlementStatus != "" {
|
||||
db = db.Where("ro.settlement_status = ?", query.SettlementStatus)
|
||||
}
|
||||
if !query.StartDate.IsZero() && !query.EndDate.IsZero() {
|
||||
if query.DateType == "created" {
|
||||
db = db.Where("ro.created_at >= ? AND ro.created_at <= ?", query.StartDate, query.EndDate)
|
||||
} else {
|
||||
db = db.Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate)
|
||||
}
|
||||
}
|
||||
return db
|
||||
return r.applyDetailFilters(db, query)
|
||||
}
|
||||
|
||||
@@ -34,10 +34,12 @@ type FinanceSummaryDTO struct {
|
||||
OwnerShouldIncomeAmountCent int64 `json:"owner_should_income_amount_cent"`
|
||||
OwnerWalletIncomeAmountCent int64 `json:"owner_wallet_income_amount_cent"`
|
||||
SettlementDiffAmountCent int64 `json:"settlement_diff_amount_cent"`
|
||||
EstimatedIncomeAmountCent int64 `json:"estimated_income_amount_cent"`
|
||||
SuccessfulPayCount int64 `json:"successful_pay_count"`
|
||||
SuccessfulRefundCount int64 `json:"successful_refund_count"`
|
||||
PendingRefundCount int64 `json:"pending_refund_count"`
|
||||
SettledOrderCount int64 `json:"settled_order_count"`
|
||||
PendingSettleOrderCount int64 `json:"pending_settle_order_count"`
|
||||
FinancialExceptionCount int64 `json:"financial_exception_count"`
|
||||
}
|
||||
|
||||
@@ -51,6 +53,7 @@ type FinanceDailyDTO struct {
|
||||
OwnerShouldIncomeAmountCent int64 `json:"owner_should_income_amount_cent"`
|
||||
OwnerWalletIncomeAmountCent int64 `json:"owner_wallet_income_amount_cent"`
|
||||
SettlementDiffAmountCent int64 `json:"settlement_diff_amount_cent"`
|
||||
EstimatedIncomeAmountCent int64 `json:"estimated_income_amount_cent"`
|
||||
SuccessfulPayCount int64 `json:"successful_pay_count"`
|
||||
SuccessfulRefundCount int64 `json:"successful_refund_count"`
|
||||
PendingRefundCount int64 `json:"pending_refund_count"`
|
||||
|
||||
@@ -7,6 +7,11 @@ import (
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
)
|
||||
|
||||
// settlementDiffThresholdCent 是判定"结算差异"的最小绝对金额(分)。
|
||||
// 号主应得与实际入账的差额绝对值达到此阈值,才视为财务异常。
|
||||
// SQL、presenter、前端展示统一引用此口径,避免多处硬编码不一致。
|
||||
const settlementDiffThresholdCent = 5
|
||||
|
||||
func refundBizTypes() []string {
|
||||
return []string{
|
||||
"cancel_refund",
|
||||
@@ -19,6 +24,18 @@ func refundBizTypes() []string {
|
||||
}
|
||||
}
|
||||
|
||||
// settledSettlementStatuses 是视为"已完成结算"的结算状态集合。
|
||||
// 预计收入只统计尚未结算的订单,这些状态需从预计口径中排除。
|
||||
func settledSettlementStatuses() []string {
|
||||
return []string{"settled", "closed"}
|
||||
}
|
||||
|
||||
// nonBillableOrderStatuses 是不产生平台收入的订单状态集合(待支付、已取消、已关闭)。
|
||||
// 预计收入排除这些状态,只保留进行中/待结算且未来会产生手续费的订单。
|
||||
func nonBillableOrderStatuses() []string {
|
||||
return []string{"pending_payment", "cancelled", "closed"}
|
||||
}
|
||||
|
||||
func dayStart(value time.Time) time.Time {
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
local := value.In(loc)
|
||||
|
||||
@@ -41,7 +41,7 @@ func (r financeDetailRow) toDTO() FinanceDetailDTO {
|
||||
if status == "" {
|
||||
status = "normal"
|
||||
}
|
||||
if absCent(diff) < 5 && status == "settlement_diff" {
|
||||
if absCent(diff) < settlementDiffThresholdCent && status == "settlement_diff" {
|
||||
status = "normal"
|
||||
}
|
||||
return FinanceDetailDTO{
|
||||
|
||||
Reference in New Issue
Block a user