fix(tenant): 收紧双站运营提号与录单边界
This commit is contained in:
@@ -107,56 +107,70 @@ 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)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
var row struct {
|
||||
SettledAmountCent int64
|
||||
ProfitAmountCent int64
|
||||
CompletedCount int64
|
||||
}
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
||||
pickupQuery := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS settled_amount_cent, 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).
|
||||
Scan(&row).Error; err != nil {
|
||||
Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID > 0 {
|
||||
pickupQuery = pickupQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pickupQuery.Scan(&row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var adjustments struct {
|
||||
SettledAmountCent int64
|
||||
ProfitAmountCent int64
|
||||
}
|
||||
if err := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
adjustmentQuery := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
Select(`COALESCE(SUM(fa.settle_delta_cent), 0) AS settled_amount_cent,
|
||||
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).
|
||||
Scan(&adjustments).Error; err != nil {
|
||||
Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID > 0 {
|
||||
adjustmentQuery = adjustmentQuery.Where("fa.tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := adjustmentQuery.Scan(&adjustments).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var inProgress int64
|
||||
if err := db.Table("admin_pickups").Where("status = ?", "picking_up").Count(&inProgress).Error; err != nil {
|
||||
inProgressQuery := db.Table("admin_pickups").Where("status = ?", "picking_up")
|
||||
if tenantID > 0 {
|
||||
inProgressQuery = inProgressQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := inProgressQuery.Count(&inProgress).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pending struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
pendingQuery := 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 = ? AND offline_settlement_status = ? AND settle_amount_cent > 0", "platform_managed", "pending").
|
||||
Scan(&pending).Error; err != nil {
|
||||
Where("settlement_mode = ? AND offline_settlement_status = ? AND settle_amount_cent > 0", "platform_managed", "pending")
|
||||
if tenantID > 0 {
|
||||
pendingQuery = pendingQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pendingQuery.Scan(&pending).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pendingAdjustments struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
pendingAdjustmentQuery := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ? AND status = ? AND settle_delta_cent > 0", "platform_managed", "pending").
|
||||
Scan(&pendingAdjustments).Error; err != nil {
|
||||
Where("settlement_mode = ? AND status = ? AND settle_delta_cent > 0", "platform_managed", "pending")
|
||||
if tenantID > 0 {
|
||||
pendingAdjustmentQuery = pendingAdjustmentQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pendingAdjustmentQuery.Scan(&pendingAdjustments).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &PickupSummaryDTO{
|
||||
@@ -251,29 +265,29 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
||||
}
|
||||
|
||||
pickupProfits := make([]dailyPickupProfitRow, 0)
|
||||
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,
|
||||
pickupProfitQuery := 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)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
pickupProfitQuery = pickupProfitQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pickupProfitQuery.Group("DATE_FORMAT(completed_at, '%Y-%m-%d')").Scan(&pickupProfits).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
}
|
||||
pickupAdjustments := make([]dailyPickupAdjustmentRow, 0)
|
||||
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,
|
||||
pickupAdjustmentQuery := 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)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
pickupAdjustmentQuery = pickupAdjustmentQuery.Where("fa.tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pickupAdjustmentQuery.Group("DATE_FORMAT(fa.created_at, '%Y-%m-%d')").Scan(&pickupAdjustments).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
}
|
||||
|
||||
// 取消提号按取消日统计,与「已付款订单数」中的提号创建口径区分开。
|
||||
@@ -604,15 +618,14 @@ 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").
|
||||
db := r.db.WithContext(ctx).Table("admin_pickups").
|
||||
Select(`DATE_FORMAT(cancelled_at, '%Y-%m-%d') AS date, COUNT(id) AS count`).
|
||||
Where("status = ?", "cancelled").
|
||||
Where("cancelled_at >= ? AND cancelled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(cancelled_at, '%Y-%m-%d')").
|
||||
Scan(&rows).Error
|
||||
Where("cancelled_at >= ? AND cancelled_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
db = db.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
err := db.Group("DATE_FORMAT(cancelled_at, '%Y-%m-%d')").Scan(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
@@ -631,10 +644,13 @@ func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery)
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
))`
|
||||
pickupTenantFilter = " AND 1 = 0"
|
||||
pickupTenantFilter = " AND tenant_id = ?"
|
||||
args = append(args, tenantID)
|
||||
}
|
||||
args = append(args, query.StartDate, query.EndDate)
|
||||
if tenantID > 0 {
|
||||
args = append(args, tenantID)
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -14,6 +14,13 @@ type dailyOperatingExpenseRow struct {
|
||||
Count int64
|
||||
}
|
||||
|
||||
func financePickupTenantScope(db *gorm.DB, tenantID uint64, column string) *gorm.DB {
|
||||
if tenantID > 0 {
|
||||
return db.Where(column+" = ?", tenantID)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func (r *Repository) dailyOperatingExpenses(ctx context.Context, query DashboardQuery) ([]dailyOperatingExpenseRow, error) {
|
||||
rows := make([]dailyOperatingExpenseRow, 0)
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
@@ -49,30 +56,30 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
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
|
||||
}
|
||||
if err := financePickupTenantScope(
|
||||
db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)"),
|
||||
tenantID,
|
||||
"tenant_id",
|
||||
).
|
||||
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 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
|
||||
}
|
||||
if err := financePickupTenantScope(db.Table("admin_pickup_financial_adjustments"), tenantID, "tenant_id").
|
||||
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 {
|
||||
@@ -91,29 +98,29 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
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
|
||||
}
|
||||
if err := financePickupTenantScope(
|
||||
db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)"),
|
||||
tenantID,
|
||||
"tenant_id",
|
||||
).
|
||||
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 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
|
||||
}
|
||||
if err := financePickupTenantScope(db.Table("admin_pickup_financial_adjustments"), tenantID, "tenant_id").
|
||||
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
|
||||
}
|
||||
|
||||
// 付款、处理中、待审核三类提现在一次条件聚合中完成,避免同一张表重复扫描。
|
||||
@@ -199,33 +206,33 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
||||
return nil, err
|
||||
}
|
||||
pickupOfflineRows := make([]dailyDisbursementSourceRow, 0)
|
||||
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,
|
||||
if err := financePickupTenantScope(
|
||||
db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)"),
|
||||
tenantID,
|
||||
"tenant_id",
|
||||
).
|
||||
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 tenantID == 0 {
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`DATE_FORMAT(settled_at, '%Y-%m-%d') AS date,
|
||||
if err := financePickupTenantScope(db.Table("admin_pickup_financial_adjustments"), tenantID, "tenant_id").
|
||||
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...)
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -54,6 +56,7 @@ func (r *Repository) Disbursements(ctx context.Context, query DisbursementQuery)
|
||||
|
||||
func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword string) *gorm.DB {
|
||||
db := r.db.WithContext(ctx)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
platformManaged := db.Table("rental_orders AS ro").
|
||||
Select(`'platform_managed' AS source_type,
|
||||
ro.id AS source_id,
|
||||
@@ -95,6 +98,11 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
Where("ro.settlement_mode = ?", "platform_managed").
|
||||
Where("ro.offline_settlement_status IN ?", []string{"pending", "settled"}).
|
||||
Where("ro.offline_settlement_amount_cent > 0")
|
||||
if tenantID > 0 {
|
||||
platformManaged = platformManaged.
|
||||
Where("(ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(ro.distribution_site_id IS NULL OR ro.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
pickupManaged := db.Table("admin_pickups AS ap").
|
||||
Select(`'pickup' AS source_type,
|
||||
@@ -134,6 +142,9 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
Where("ap.settlement_mode = ?", "platform_managed").
|
||||
Where("ap.offline_settlement_status IN ?", []string{"pending", "settled"}).
|
||||
Where("ap.settle_amount_cent > 0")
|
||||
if tenantID > 0 {
|
||||
pickupManaged = pickupManaged.Where("ap.tenant_id = ?", tenantID)
|
||||
}
|
||||
|
||||
pickupAdjustments := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
Select(`'pickup_adjustment' AS source_type,
|
||||
@@ -174,6 +185,9 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
Where("fa.settlement_mode = ?", "platform_managed").
|
||||
Where("fa.status IN ?", []string{"pending", "settled"}).
|
||||
Where("fa.settle_delta_cent > 0")
|
||||
if tenantID > 0 {
|
||||
pickupAdjustments = pickupAdjustments.Where("fa.tenant_id = ?", tenantID)
|
||||
}
|
||||
|
||||
withdrawal := db.Table("withdrawal_requests AS wr").
|
||||
Select(`'withdrawal' AS source_type,
|
||||
@@ -216,6 +230,9 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
NULL AS source_payload`).
|
||||
Joins("LEFT JOIN users AS u ON u.id = wr.user_id").
|
||||
Joins("LEFT JOIN admin_users AS operator ON operator.id = COALESCE(wr.paid_by, wr.reviewed_by)")
|
||||
if tenantID > 0 {
|
||||
withdrawal = withdrawal.Where("wr.tenant_id = ? AND wr.distribution_site_id = 0", tenantID)
|
||||
}
|
||||
|
||||
if phoneKeyword = strings.TrimSpace(phoneKeyword); isPhoneKeyword(phoneKeyword) {
|
||||
withdrawal = withdrawal.Where("wr.user_id = (SELECT id FROM users WHERE phone = ?)", phoneKeyword)
|
||||
@@ -258,6 +275,9 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
NULL AS source_payload`).
|
||||
Joins("LEFT JOIN admin_users AS creator ON creator.id = md.created_by").
|
||||
Joins("LEFT JOIN admin_users AS voider ON voider.id = md.voided_by")
|
||||
if tenantID > 0 {
|
||||
manualOffline = manualOffline.Where("1 = 0")
|
||||
}
|
||||
|
||||
union := db.Raw("? UNION ALL ? UNION ALL ? UNION ALL ? UNION ALL ?", platformManaged, pickupManaged, pickupAdjustments, withdrawal, manualOffline)
|
||||
return db.Table("(?) AS d", union)
|
||||
|
||||
@@ -2,6 +2,27 @@ package adminfinance
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidFinanceVoucherURLUsesScenePrefix(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
scene string
|
||||
want bool
|
||||
}{
|
||||
{name: "manual", raw: "/api/files/object?key=manual-disbursement%2Fvoucher.webp", scene: "manual-disbursement/", want: true},
|
||||
{name: "operating", raw: "/api/files/object?key=operating-expense%2Fvoucher.webp", scene: "operating-expense/", want: true},
|
||||
{name: "wrong scene", raw: "/api/files/object?key=manual-disbursement%2Fvoucher.webp", scene: "operating-expense/", want: false},
|
||||
{name: "external", raw: "https://example.com/voucher.webp", scene: "operating-expense/", want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := validFinanceVoucherURL(tc.raw, tc.scene); got != tc.want {
|
||||
t.Fatalf("validFinanceVoucherURL() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDailyDateKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -102,7 +102,7 @@ func (s *Service) CreateManualDisbursement(
|
||||
utf8.RuneCountInString(req.PayeeName) < 1 || utf8.RuneCountInString(req.PayeeName) > 100 ||
|
||||
req.AmountCent <= 0 || req.PaidAt.IsZero() ||
|
||||
utf8.RuneCountInString(req.Remark) < 1 || utf8.RuneCountInString(req.Remark) > 500 ||
|
||||
!validManualVoucherURL(req.VoucherURL) {
|
||||
!validFinanceVoucherURL(req.VoucherURL, "manual-disbursement/") {
|
||||
return nil, ErrInvalidManualDisbursement
|
||||
}
|
||||
return s.repo.CreateManualDisbursement(ctx, req, adminID, meta)
|
||||
@@ -137,7 +137,7 @@ func (s *Service) CreateOperatingExpense(ctx context.Context, req CreateOperatin
|
||||
utf8.RuneCountInString(req.PayeeName) < 1 || utf8.RuneCountInString(req.PayeeName) > 100 ||
|
||||
req.AmountCent <= 0 || req.OccurredAt.IsZero() ||
|
||||
utf8.RuneCountInString(req.Remark) < 1 || utf8.RuneCountInString(req.Remark) > 500 ||
|
||||
!validManualVoucherURL(req.VoucherURL) {
|
||||
!validFinanceVoucherURL(req.VoucherURL, "operating-expense/") {
|
||||
return nil, ErrInvalidOperatingExpense
|
||||
}
|
||||
return s.repo.CreateOperatingExpense(ctx, req, adminID, meta)
|
||||
@@ -170,7 +170,7 @@ func validManualDisbursementCustomCategoryName(category, name string) bool {
|
||||
return utf8.RuneCountInString(name) >= 1 && utf8.RuneCountInString(name) <= 50
|
||||
}
|
||||
|
||||
func validManualVoucherURL(raw string) bool {
|
||||
func validFinanceVoucherURL(raw string, scenePrefix string) bool {
|
||||
if raw == "" {
|
||||
return true
|
||||
}
|
||||
@@ -181,5 +181,5 @@ func validManualVoucherURL(raw string) bool {
|
||||
if err != nil || parsed.IsAbs() || parsed.Path != "/api/files/object" {
|
||||
return false
|
||||
}
|
||||
return strings.HasPrefix(parsed.Query().Get("key"), "manual-disbursement/")
|
||||
return strings.HasPrefix(parsed.Query().Get("key"), scenePrefix)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
)
|
||||
|
||||
func financeTenantContext(tenantID uint64) context.Context {
|
||||
@@ -51,3 +52,87 @@ func TestFinancePaymentStatsAreScopedByTenant(t *testing.T) {
|
||||
t.Fatal("dashboard cache key must include tenant")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinancePickupStatsAndDisbursementsAreScopedByPickupTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
now := time.Date(2026, 11, 16, 12, 0, 0, 0, loc)
|
||||
if err := db.Exec(`INSERT INTO admin_pickups
|
||||
(id, tenant_id, source_tenant_id, pickup_no, listing_id, account_id, owner_id, admin_id,
|
||||
listing_price_cent, settle_amount_cent, profit_amount_cent, status, settlement_mode,
|
||||
offline_settlement_status, created_at, completed_at)
|
||||
VALUES
|
||||
(1, 101, 202, 'PK-SCOPE-A', 11, 12, 13, 1, 1000, 100, 20, 'completed', 'platform_managed', 'pending', ?, ?),
|
||||
(2, 202, 101, 'PK-SCOPE-B', 21, 22, 23, 2, 2000, 200, 40, 'completed', 'platform_managed', 'pending', ?, ?),
|
||||
(3, 101, 101, 'PK-SCOPE-CANCEL-A', 31, 32, 33, 1, 1000, 0, 0, 'cancelled', 'owner_wallet', 'none', ?, NULL),
|
||||
(4, 202, 202, 'PK-SCOPE-CANCEL-B', 41, 42, 43, 2, 1000, 0, 0, 'cancelled', 'owner_wallet', 'none', ?, NULL)`,
|
||||
now, now, now, now, now, now).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`UPDATE admin_pickups SET cancelled_at = ? WHERE status = 'cancelled'`, now).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments
|
||||
(id, tenant_id, pickup_id, profit_delta_cent, settle_delta_cent, settlement_mode,
|
||||
status, reason, created_by, created_at)
|
||||
VALUES
|
||||
(1, 101, 1, 1, 10, 'platform_managed', 'settled', 'A调整', 1, ?),
|
||||
(2, 202, 2, 2, 20, 'platform_managed', 'settled', 'B调整', 2, ?)`,
|
||||
now, now).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db)
|
||||
ctxA := financeTenantContext(101)
|
||||
query := DashboardQuery{StartDate: now.Add(-time.Hour), EndDate: now.Add(time.Hour)}
|
||||
summary, err := repo.pickupSummary(ctxA, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.CompletedCount != 1 || summary.SettledAmountCent != 110 ||
|
||||
summary.ProfitAmountCent != 21 || summary.PendingCount != 1 ||
|
||||
summary.PendingAmountCent != 100 {
|
||||
t.Fatalf("tenant pickup summary = %+v", summary)
|
||||
}
|
||||
|
||||
paid, err := repo.dailyPaidOrders(ctxA, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(paid) != 1 || paid[0].PaidOrderCount != 1 {
|
||||
t.Fatalf("tenant paid pickup orders = %+v", paid)
|
||||
}
|
||||
cancelled, err := repo.dailyPickupCancelled(ctxA, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cancelled) != 1 || cancelled[0].Count != 1 {
|
||||
t.Fatalf("tenant cancelled pickups = %+v", cancelled)
|
||||
}
|
||||
disbursement, err := repo.disbursementSummary(ctxA, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if disbursement.PendingPaymentCount != 1 || disbursement.PendingPaymentAmountCent != 100 ||
|
||||
disbursement.OfflineSettlementPendingCount != 1 ||
|
||||
disbursement.OfflineSettlementPendingAmountCent != 100 {
|
||||
t.Fatalf("tenant pickup disbursement summary = %+v", disbursement)
|
||||
}
|
||||
list, err := repo.Disbursements(ctxA, DisbursementQuery{
|
||||
StartDate: now.Add(-time.Hour),
|
||||
EndDate: now.Add(time.Hour),
|
||||
Page: 1,
|
||||
PageSize: 20,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if list.Total != 2 {
|
||||
t.Fatalf("tenant disbursement items = %+v", list)
|
||||
}
|
||||
for _, item := range list.Items {
|
||||
if item.BusinessNo == "PK-SCOPE-B" {
|
||||
t.Fatalf("tenant A disbursements leaked tenant B pickup: %+v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user