feat(tenant): 按租户隔离支付退款与商户配置
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
|||||||
|
|
||||||
type PaymentOrder struct {
|
type PaymentOrder struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
|
TenantID uint64 `gorm:"not null;default:0;index:idx_payment_orders_tenant_created" json:"tenant_id"`
|
||||||
PaymentNo string `gorm:"size:64;not null;uniqueIndex" json:"payment_no"`
|
PaymentNo string `gorm:"size:64;not null;uniqueIndex" json:"payment_no"`
|
||||||
OrderID uint64 `gorm:"not null;index" json:"order_id"`
|
OrderID uint64 `gorm:"not null;index" json:"order_id"`
|
||||||
OrderNo string `gorm:"size:64;not null;index" json:"order_no"`
|
OrderNo string `gorm:"size:64;not null;index" json:"order_no"`
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
// PaymentMerchantConfig 支付商户配置
|
// PaymentMerchantConfig 支付商户配置
|
||||||
type PaymentMerchantConfig struct {
|
type PaymentMerchantConfig struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
|
OwnerTenantID uint64 `gorm:"not null;default:0;index:idx_payment_merchant_configs_owner" json:"owner_tenant_id"`
|
||||||
Name string `gorm:"size:128;not null" json:"name"`
|
Name string `gorm:"size:128;not null" json:"name"`
|
||||||
Provider string `gorm:"size:32;not null;index:idx_payment_merchant_configs_provider" json:"provider"`
|
Provider string `gorm:"size:32;not null;index:idx_payment_merchant_configs_provider" json:"provider"`
|
||||||
MerchantID string `gorm:"size:128;not null;index:idx_payment_merchant_configs_merchant_id" json:"merchant_id"`
|
MerchantID string `gorm:"size:128;not null;index:idx_payment_merchant_configs_merchant_id" json:"merchant_id"`
|
||||||
@@ -89,6 +90,7 @@ func (j *JSONArray) Scan(value any) error {
|
|||||||
// PaymentConfigUsageLog 支付配置使用日志
|
// PaymentConfigUsageLog 支付配置使用日志
|
||||||
type PaymentConfigUsageLog struct {
|
type PaymentConfigUsageLog struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
|
TenantID uint64 `gorm:"not null;default:0;index:idx_payment_config_usage_logs_tenant" json:"tenant_id"`
|
||||||
ConfigID uint64 `gorm:"not null;index:idx_payment_config_usage_logs_config" json:"config_id"`
|
ConfigID uint64 `gorm:"not null;index:idx_payment_config_usage_logs_config" json:"config_id"`
|
||||||
PaymentOrderID uint64 `gorm:"not null;index:idx_payment_config_usage_logs_payment" json:"payment_order_id"`
|
PaymentOrderID uint64 `gorm:"not null;index:idx_payment_config_usage_logs_payment" json:"payment_order_id"`
|
||||||
Provider string `gorm:"size:32;not null" json:"provider"`
|
Provider string `gorm:"size:32;not null" json:"provider"`
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
ordermodule "hfb_sys/backend/internal/modules/order"
|
ordermodule "hfb_sys/backend/internal/modules/order"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
"hfb_sys/backend/internal/timeutil"
|
"hfb_sys/backend/internal/timeutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -14,7 +15,7 @@ func (r *Repository) Dashboard(ctx context.Context, query DashboardQuery) (*Dash
|
|||||||
return cached, nil
|
return cached, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
key := r.dashboardCacheKey(query)
|
key := r.dashboardCacheKey(ctx, query)
|
||||||
val, err, _ := r.sfGroup.Do(key, func() (any, error) {
|
val, err, _ := r.sfGroup.Do(key, func() (any, error) {
|
||||||
// 在 singleflight 内部二次检查缓存,避免排队等待的并发请求重复执行大聚合
|
// 在 singleflight 内部二次检查缓存,避免排队等待的并发请求重复执行大聚合
|
||||||
if cached := r.loadDashboardCache(ctx, query); cached != nil {
|
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) {
|
func (r *Repository) operatingExpenseSummary(ctx context.Context, query DashboardQuery) (*OperatingExpenseSummaryDTO, error) {
|
||||||
var summary OperatingExpenseSummaryDTO
|
var summary OperatingExpenseSummaryDTO
|
||||||
|
if tenancy.IDFromContext(ctx) > 0 {
|
||||||
|
return &summary, nil
|
||||||
|
}
|
||||||
err := r.db.WithContext(ctx).Table("operating_expenses").
|
err := r.db.WithContext(ctx).Table("operating_expenses").
|
||||||
Select("COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count").
|
Select("COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count").
|
||||||
Where("status = ?", "paid").
|
Where("status = ?", "paid").
|
||||||
@@ -103,6 +107,9 @@ func (r *Repository) operatingExpenseSummary(ctx context.Context, query Dashboar
|
|||||||
|
|
||||||
// pickupSummary 线下提号统计,独立查询 admin_pickups 表,不混入正常订单口径。
|
// pickupSummary 线下提号统计,独立查询 admin_pickups 表,不混入正常订单口径。
|
||||||
func (r *Repository) pickupSummary(ctx context.Context, query DashboardQuery) (*PickupSummaryDTO, error) {
|
func (r *Repository) pickupSummary(ctx context.Context, query DashboardQuery) (*PickupSummaryDTO, error) {
|
||||||
|
if tenancy.IDFromContext(ctx) > 0 {
|
||||||
|
return &PickupSummaryDTO{}, nil
|
||||||
|
}
|
||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
var row struct {
|
var row struct {
|
||||||
SettledAmountCent int64
|
SettledAmountCent int64
|
||||||
@@ -170,7 +177,11 @@ func (r *Repository) mohongSummary(ctx context.Context, query DashboardQuery) (*
|
|||||||
RefundAmountCent int64
|
RefundAmountCent int64
|
||||||
PaidOrderCount 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,
|
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_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`).
|
COALESCE(SUM(CASE WHEN biz_type = 'mohong_pay' AND status = 'paid' THEN 1 ELSE 0 END), 0) AS paid_order_count`).
|
||||||
@@ -240,6 +251,7 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
|||||||
}
|
}
|
||||||
|
|
||||||
pickupProfits := make([]dailyPickupProfitRow, 0)
|
pickupProfits := make([]dailyPickupProfitRow, 0)
|
||||||
|
if tenancy.IDFromContext(ctx) == 0 {
|
||||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
||||||
Select(`DATE_FORMAT(completed_at, '%Y-%m-%d') AS date,
|
Select(`DATE_FORMAT(completed_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent,
|
COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent,
|
||||||
@@ -250,7 +262,9 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
|||||||
Scan(&pickupProfits).Error; err != nil {
|
Scan(&pickupProfits).Error; err != nil {
|
||||||
return dashboardDailyResult{}, err
|
return dashboardDailyResult{}, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
pickupAdjustments := make([]dailyPickupAdjustmentRow, 0)
|
pickupAdjustments := make([]dailyPickupAdjustmentRow, 0)
|
||||||
|
if tenancy.IDFromContext(ctx) == 0 {
|
||||||
if err := db.Table("admin_pickup_financial_adjustments AS fa").
|
if err := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||||
Select(`DATE_FORMAT(fa.created_at, '%Y-%m-%d') AS date,
|
Select(`DATE_FORMAT(fa.created_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(fa.profit_delta_cent), 0) AS profit_amount_cent`).
|
COALESCE(SUM(fa.profit_delta_cent), 0) AS profit_amount_cent`).
|
||||||
@@ -260,6 +274,7 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
|||||||
Scan(&pickupAdjustments).Error; err != nil {
|
Scan(&pickupAdjustments).Error; err != nil {
|
||||||
return dashboardDailyResult{}, err
|
return dashboardDailyResult{}, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 取消提号按取消日统计,与「已付款订单数」中的提号创建口径区分开。
|
// 取消提号按取消日统计,与「已付款订单数」中的提号创建口径区分开。
|
||||||
pickupCancelled, err := r.dailyPickupCancelled(ctx, query)
|
pickupCancelled, err := r.dailyPickupCancelled(ctx, query)
|
||||||
@@ -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) {
|
func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) ([]dailyEstimatedRow, error) {
|
||||||
rows := make([]dailyEstimatedRow, 0)
|
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,
|
Select(`DATE_FORMAT(created_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent,
|
COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent,
|
||||||
COUNT(id) AS pending_settle_order_count`).
|
COUNT(id) AS pending_settle_order_count`).
|
||||||
Where("settlement_status NOT IN ?", settledSettlementStatuses()).
|
Where("settlement_status NOT IN ?", settledSettlementStatuses()).
|
||||||
Where("status NOT IN ?", nonBillableOrderStatuses()).
|
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')").
|
Group("DATE_FORMAT(created_at, '%Y-%m-%d')").
|
||||||
Scan(&rows).Error
|
Scan(&rows).Error
|
||||||
return rows, err
|
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) {
|
func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery) ([]dailySettlementRow, error) {
|
||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
rows := make([]dailySettlementRow, 0)
|
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,
|
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(oc.platform_fee_cent), 0) AS platform_income_amount_cent,
|
||||||
COALESCE(SUM(CASE WHEN ro.compensation_plan = 'insurance' AND ro.insurance_fee_bps > 0
|
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 模块写入),不纳入本指标,此处保持既有口径不变。
|
// (由 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("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)).
|
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')").
|
Group("DATE_FORMAT(ro.settled_at, '%Y-%m-%d')").
|
||||||
Scan(&rows).Error
|
Scan(&rows).Error
|
||||||
return rows, err
|
return rows, err
|
||||||
@@ -541,7 +564,11 @@ func operatingExpenseSummaryFromDailyRows(rows []dailyOperatingExpenseRow) Opera
|
|||||||
func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([]dailyPaymentRow, error) {
|
func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([]dailyPaymentRow, error) {
|
||||||
rows := make([]dailyPaymentRow, 0)
|
rows := make([]dailyPaymentRow, 0)
|
||||||
db := r.db.WithContext(ctx)
|
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,
|
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 = '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,
|
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 按取消日统计线下提号取消笔数。
|
// dailyPickupCancelled 按取消日统计线下提号取消笔数。
|
||||||
func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQuery) ([]dailyPickupCancelledRow, error) {
|
func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQuery) ([]dailyPickupCancelledRow, error) {
|
||||||
rows := make([]dailyPickupCancelledRow, 0)
|
rows := make([]dailyPickupCancelledRow, 0)
|
||||||
|
if tenancy.IDFromContext(ctx) > 0 {
|
||||||
|
return rows, nil
|
||||||
|
}
|
||||||
err := r.db.WithContext(ctx).Table("admin_pickups").
|
err := r.db.WithContext(ctx).Table("admin_pickups").
|
||||||
Select(`DATE_FORMAT(cancelled_at, '%Y-%m-%d') AS date, COUNT(id) AS count`).
|
Select(`DATE_FORMAT(cancelled_at, '%Y-%m-%d') AS date, COUNT(id) AS count`).
|
||||||
Where("status = ?", "cancelled").
|
Where("status = ?", "cancelled").
|
||||||
@@ -577,17 +607,27 @@ func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQu
|
|||||||
// dailyPaidOrders 按实际付款日统计普通租赁订单,并将已完成的线下提号按完成日计入成交。
|
// dailyPaidOrders 按实际付款日统计普通租赁订单,并将已完成的线下提号按完成日计入成交。
|
||||||
func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery) ([]dailyPaidOrderRow, error) {
|
func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery) ([]dailyPaidOrderRow, error) {
|
||||||
items := make([]dailyPaidOrderRow, 0)
|
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(`(
|
err := r.db.WithContext(ctx).Table(`(
|
||||||
SELECT DATE_FORMAT(paid_at, '%Y-%m-%d') AS date, COUNT(DISTINCT order_id) AS paid_order_count
|
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)
|
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')
|
GROUP BY DATE_FORMAT(paid_at, '%Y-%m-%d')
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT DATE_FORMAT(completed_at, '%Y-%m-%d') AS date, COUNT(id) AS paid_order_count
|
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)
|
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')
|
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").
|
Select("date, SUM(paid_order_count) AS paid_order_count").
|
||||||
Group("date").
|
Group("date").
|
||||||
Scan(&items).Error
|
Scan(&items).Error
|
||||||
|
|||||||
@@ -5,19 +5,21 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
)
|
)
|
||||||
|
|
||||||
const dashboardCacheTTL = 5 * time.Minute
|
const dashboardCacheTTL = 5 * time.Minute
|
||||||
|
|
||||||
func (r *Repository) dashboardCacheKey(query DashboardQuery) string {
|
func (r *Repository) dashboardCacheKey(ctx context.Context, query DashboardQuery) string {
|
||||||
return fmt.Sprintf("admin-finance:dashboard:v2:%d:%d", query.StartDate.Unix(), query.EndDate.Unix())
|
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 {
|
func (r *Repository) loadDashboardCache(ctx context.Context, query DashboardQuery) *DashboardDTO {
|
||||||
if r.redis == nil {
|
if r.redis == nil {
|
||||||
return 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 {
|
if err != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -37,5 +39,5 @@ func (r *Repository) storeDashboardCache(ctx context.Context, query DashboardQue
|
|||||||
return
|
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),
|
StartDate: time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC),
|
||||||
EndDate: time.Date(2026, 9, 7, 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 == "" {
|
if key == "" {
|
||||||
t.Fatal("cache key should not be empty")
|
t.Fatal("cache key should not be empty")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
package adminfinance
|
package adminfinance
|
||||||
|
|
||||||
import "context"
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
type dailyOperatingExpenseRow struct {
|
type dailyOperatingExpenseRow struct {
|
||||||
Date string
|
Date string
|
||||||
@@ -10,6 +16,9 @@ type dailyOperatingExpenseRow struct {
|
|||||||
|
|
||||||
func (r *Repository) dailyOperatingExpenses(ctx context.Context, query DashboardQuery) ([]dailyOperatingExpenseRow, error) {
|
func (r *Repository) dailyOperatingExpenses(ctx context.Context, query DashboardQuery) ([]dailyOperatingExpenseRow, error) {
|
||||||
rows := make([]dailyOperatingExpenseRow, 0)
|
rows := make([]dailyOperatingExpenseRow, 0)
|
||||||
|
if tenancy.IDFromContext(ctx) > 0 {
|
||||||
|
return rows, nil
|
||||||
|
}
|
||||||
err := r.db.WithContext(ctx).Table("operating_expenses").
|
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`).
|
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").
|
Where("status = ?", "paid").
|
||||||
@@ -22,12 +31,13 @@ func (r *Repository) dailyOperatingExpenses(ctx context.Context, query Dashboard
|
|||||||
// disbursementSummary 使用实际确认打款时间统计区间出款,同时返回不受日期限制的当前待办。
|
// disbursementSummary 使用实际确认打款时间统计区间出款,同时返回不受日期限制的当前待办。
|
||||||
func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQuery) (*DisbursementSummaryDTO, error) {
|
func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQuery) (*DisbursementSummaryDTO, error) {
|
||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
|
tenantID := tenancy.IDFromContext(ctx)
|
||||||
|
|
||||||
var offlinePaid struct {
|
var offlinePaid struct {
|
||||||
AmountCent int64
|
AmountCent int64
|
||||||
Count 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`).
|
Select(`COALESCE(SUM(offline_settlement_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||||
Where("settlement_mode = ?", "platform_managed").
|
Where("settlement_mode = ?", "platform_managed").
|
||||||
Where("offline_settlement_status = ?", "settled").
|
Where("offline_settlement_status = ?", "settled").
|
||||||
@@ -39,6 +49,7 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
AmountCent int64
|
AmountCent int64
|
||||||
Count int64
|
Count int64
|
||||||
}
|
}
|
||||||
|
if tenantID == 0 {
|
||||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
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`).
|
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||||
Where("settlement_mode = ?", "platform_managed").
|
Where("settlement_mode = ?", "platform_managed").
|
||||||
@@ -47,10 +58,12 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
Scan(&pickupPaid).Error; err != nil {
|
Scan(&pickupPaid).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
var pickupAdjustmentPaid struct {
|
var pickupAdjustmentPaid struct {
|
||||||
AmountCent int64
|
AmountCent int64
|
||||||
Count int64
|
Count int64
|
||||||
}
|
}
|
||||||
|
if tenantID == 0 {
|
||||||
if err := db.Table("admin_pickup_financial_adjustments").
|
if err := db.Table("admin_pickup_financial_adjustments").
|
||||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||||
Where("settlement_mode = ?", "platform_managed").
|
Where("settlement_mode = ?", "platform_managed").
|
||||||
@@ -60,12 +73,13 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
Scan(&pickupAdjustmentPaid).Error; err != nil {
|
Scan(&pickupAdjustmentPaid).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var offlinePending struct {
|
var offlinePending struct {
|
||||||
AmountCent int64
|
AmountCent int64
|
||||||
Count 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`).
|
Select(`COALESCE(SUM(offline_settlement_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||||
Where("settlement_mode = ?", "platform_managed").
|
Where("settlement_mode = ?", "platform_managed").
|
||||||
Where("offline_settlement_status = ?", "pending").
|
Where("offline_settlement_status = ?", "pending").
|
||||||
@@ -77,6 +91,7 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
AmountCent int64
|
AmountCent int64
|
||||||
Count int64
|
Count int64
|
||||||
}
|
}
|
||||||
|
if tenantID == 0 {
|
||||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
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`).
|
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||||
Where("settlement_mode = ?", "platform_managed").
|
Where("settlement_mode = ?", "platform_managed").
|
||||||
@@ -85,10 +100,12 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
Scan(&pickupPending).Error; err != nil {
|
Scan(&pickupPending).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
var pickupAdjustmentPending struct {
|
var pickupAdjustmentPending struct {
|
||||||
AmountCent int64
|
AmountCent int64
|
||||||
Count int64
|
Count int64
|
||||||
}
|
}
|
||||||
|
if tenantID == 0 {
|
||||||
if err := db.Table("admin_pickup_financial_adjustments").
|
if err := db.Table("admin_pickup_financial_adjustments").
|
||||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||||
Where("settlement_mode = ?", "platform_managed").
|
Where("settlement_mode = ?", "platform_managed").
|
||||||
@@ -97,6 +114,7 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
Scan(&pickupAdjustmentPending).Error; err != nil {
|
Scan(&pickupAdjustmentPending).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 付款、处理中、待审核三类提现在一次条件聚合中完成,避免同一张表重复扫描。
|
// 付款、处理中、待审核三类提现在一次条件聚合中完成,避免同一张表重复扫描。
|
||||||
var withdrawal struct {
|
var withdrawal struct {
|
||||||
@@ -109,7 +127,11 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
ReviewAmountCent int64
|
ReviewAmountCent int64
|
||||||
ReviewCount 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 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 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,
|
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,6 +150,7 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
AmountCent int64
|
AmountCent int64
|
||||||
Count int64
|
Count int64
|
||||||
}
|
}
|
||||||
|
if tenantID == 0 {
|
||||||
if err := db.Table("manual_disbursements").
|
if err := db.Table("manual_disbursements").
|
||||||
Select(`COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
Select(`COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||||
Where("status = ?", "paid").
|
Where("status = ?", "paid").
|
||||||
@@ -135,6 +158,7 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
Scan(&manualPaid).Error; err != nil {
|
Scan(&manualPaid).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return &DisbursementSummaryDTO{
|
return &DisbursementSummaryDTO{
|
||||||
PaidAmountCent: offlinePaid.AmountCent + pickupPaid.AmountCent + pickupAdjustmentPaid.AmountCent + withdrawal.PaidActualAmountCent + manualPaid.AmountCent,
|
PaidAmountCent: offlinePaid.AmountCent + pickupPaid.AmountCent + pickupAdjustmentPaid.AmountCent + withdrawal.PaidActualAmountCent + manualPaid.AmountCent,
|
||||||
@@ -160,8 +184,9 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
|||||||
|
|
||||||
func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuery) ([]dailyDisbursementRow, error) {
|
func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuery) ([]dailyDisbursementRow, error) {
|
||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
|
tenantID := tenancy.IDFromContext(ctx)
|
||||||
offlineRows := make([]dailyDisbursementSourceRow, 0)
|
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,
|
Select(`DATE_FORMAT(offline_settled_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(offline_settlement_amount_cent), 0) AS amount_cent,
|
COALESCE(SUM(offline_settlement_amount_cent), 0) AS amount_cent,
|
||||||
COUNT(id) AS count`).
|
COUNT(id) AS count`).
|
||||||
@@ -173,6 +198,7 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pickupOfflineRows := make([]dailyDisbursementSourceRow, 0)
|
pickupOfflineRows := make([]dailyDisbursementSourceRow, 0)
|
||||||
|
if tenantID == 0 {
|
||||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
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,
|
Select(`DATE_FORMAT(offline_settled_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(settle_amount_cent), 0) AS amount_cent,
|
COALESCE(SUM(settle_amount_cent), 0) AS amount_cent,
|
||||||
@@ -184,7 +210,9 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
|||||||
Scan(&pickupOfflineRows).Error; err != nil {
|
Scan(&pickupOfflineRows).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
pickupAdjustmentRows := make([]dailyDisbursementSourceRow, 0)
|
pickupAdjustmentRows := make([]dailyDisbursementSourceRow, 0)
|
||||||
|
if tenantID == 0 {
|
||||||
if err := db.Table("admin_pickup_financial_adjustments").
|
if err := db.Table("admin_pickup_financial_adjustments").
|
||||||
Select(`DATE_FORMAT(settled_at, '%Y-%m-%d') AS date,
|
Select(`DATE_FORMAT(settled_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(settle_delta_cent), 0) AS amount_cent,
|
COALESCE(SUM(settle_delta_cent), 0) AS amount_cent,
|
||||||
@@ -197,11 +225,16 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
|||||||
Scan(&pickupAdjustmentRows).Error; err != nil {
|
Scan(&pickupAdjustmentRows).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
offlineRows = append(offlineRows, pickupOfflineRows...)
|
offlineRows = append(offlineRows, pickupOfflineRows...)
|
||||||
offlineRows = append(offlineRows, pickupAdjustmentRows...)
|
offlineRows = append(offlineRows, pickupAdjustmentRows...)
|
||||||
|
|
||||||
withdrawalRows := make([]dailyDisbursementSourceRow, 0)
|
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,
|
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(actual_amount_cent), 0) AS amount_cent,
|
COALESCE(SUM(actual_amount_cent), 0) AS amount_cent,
|
||||||
COUNT(id) AS count`).
|
COUNT(id) AS count`).
|
||||||
@@ -213,6 +246,7 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
|||||||
}
|
}
|
||||||
|
|
||||||
manualRows := make([]dailyDisbursementSourceRow, 0)
|
manualRows := make([]dailyDisbursementSourceRow, 0)
|
||||||
|
if tenantID == 0 {
|
||||||
if err := db.Table("manual_disbursements").
|
if err := db.Table("manual_disbursements").
|
||||||
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(amount_cent), 0) AS amount_cent,
|
COALESCE(SUM(amount_cent), 0) AS amount_cent,
|
||||||
@@ -223,6 +257,7 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
|||||||
Scan(&manualRows).Error; err != nil {
|
Scan(&manualRows).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
rowsByDate := make(map[string]dailyDisbursementRow, len(offlineRows)+len(withdrawalRows)+len(manualRows))
|
rowsByDate := make(map[string]dailyDisbursementRow, len(offlineRows)+len(withdrawalRows)+len(manualRows))
|
||||||
for _, row := range offlineRows {
|
for _, row := range offlineRows {
|
||||||
@@ -259,6 +294,13 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
|||||||
return rows, nil
|
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 {
|
type dailyDisbursementSourceRow struct {
|
||||||
Date string
|
Date string
|
||||||
AmountCent int64
|
AmountCent int64
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package adminfinance
|
package adminfinance
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"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 {
|
func orderPaymentForOrdersSubquery(db *gorm.DB, orderIDs []uint64) *gorm.DB {
|
||||||
return db.Table("payment_orders").
|
query := db.Table("payment_orders").
|
||||||
Select(`order_id,
|
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 = '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 = '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 = '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`,
|
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()).
|
refundBizTypes(), refundBizTypes(), refundBizTypes()).
|
||||||
Where("order_id IN ?", orderIDs).
|
Where("order_id IN ?", orderIDs)
|
||||||
Group("order_id")
|
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 {
|
func ownerWalletIncomeForOrdersSubquery(db *gorm.DB, orderIDs []uint64) *gorm.DB {
|
||||||
@@ -50,13 +55,20 @@ func ownerWalletIncomeForSettledOrdersSubquery(db *gorm.DB, query DashboardQuery
|
|||||||
// paymentOriginalAmountForRefundsInRangeSubquery 仅为当前区间内的退款单回查原支付金额。
|
// paymentOriginalAmountForRefundsInRangeSubquery 仅为当前区间内的退款单回查原支付金额。
|
||||||
// 退款统计原先会对全部历史支付单按 order_id 聚合;数据增长后这部分即使只看一天也会很慢。
|
// 退款统计原先会对全部历史支付单按 order_id 聚合;数据增长后这部分即使只看一天也会很慢。
|
||||||
func paymentOriginalAmountForRefundsInRangeSubquery(db *gorm.DB, query DashboardQuery) *gorm.DB {
|
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)").
|
refundOrders := db.Table("payment_orders AS refund USE INDEX (idx_payment_orders_dashboard_created)").
|
||||||
Select("DISTINCT refund.order_id").
|
Select("DISTINCT refund.order_id").
|
||||||
Where("refund.biz_type IN ? AND refund.status = ?", refundBizTypes(), "refunded").
|
Where("refund.biz_type IN ? AND refund.status = ?", refundBizTypes(), "refunded").
|
||||||
Where("refund.created_at >= ? AND refund.created_at <= ?", query.StartDate, query.EndDate)
|
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").
|
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).
|
Joins("JOIN (?) AS refund_order ON refund_order.order_id = paid.order_id", refundOrders).
|
||||||
Where("paid.biz_type IN ? AND paid.status = ?", payBizTypes(), "paid").
|
Where("paid.biz_type IN ? AND paid.status = ?", payBizTypes(), "paid")
|
||||||
Group("paid.order_id")
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -103,6 +103,7 @@ func appendCheckoutOwnerIncome(tx *gorm.DB, order *model.RentalOrder, listing *m
|
|||||||
var ownerEntries []wallet.Entry
|
var ownerEntries []wallet.Entry
|
||||||
if settlement.OwnerRentIncomeCent > 0 {
|
if settlement.OwnerRentIncomeCent > 0 {
|
||||||
ownerEntries = append(ownerEntries, wallet.Entry{
|
ownerEntries = append(ownerEntries, wallet.Entry{
|
||||||
|
TenantID: order.SourceTenantID,
|
||||||
UserID: order.OwnerID,
|
UserID: order.OwnerID,
|
||||||
DistributionSiteID: siteID,
|
DistributionSiteID: siteID,
|
||||||
OrderID: &orderID,
|
OrderID: &orderID,
|
||||||
@@ -116,6 +117,7 @@ func appendCheckoutOwnerIncome(tx *gorm.DB, order *model.RentalOrder, listing *m
|
|||||||
}
|
}
|
||||||
if settlement.DepositCompensationCent > 0 {
|
if settlement.DepositCompensationCent > 0 {
|
||||||
ownerEntries = append(ownerEntries, wallet.Entry{
|
ownerEntries = append(ownerEntries, wallet.Entry{
|
||||||
|
TenantID: order.SourceTenantID,
|
||||||
UserID: order.OwnerID,
|
UserID: order.OwnerID,
|
||||||
DistributionSiteID: siteID,
|
DistributionSiteID: siteID,
|
||||||
OrderID: &orderID,
|
OrderID: &orderID,
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ type StartMohongRefundRequest struct {
|
|||||||
|
|
||||||
type PaymentDTO struct {
|
type PaymentDTO struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
TenantID uint64 `json:"tenant_id"`
|
||||||
PaymentNo string `json:"payment_no"`
|
PaymentNo string `json:"payment_no"`
|
||||||
OrderID uint64 `json:"order_id"`
|
OrderID uint64 `json:"order_id"`
|
||||||
OrderNo string `json:"order_no"`
|
OrderNo string `json:"order_no"`
|
||||||
@@ -42,6 +43,7 @@ type PaymentDTO struct {
|
|||||||
|
|
||||||
type RefundDTO struct {
|
type RefundDTO struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
TenantID uint64 `json:"tenant_id"`
|
||||||
PaymentNo string `json:"payment_no"`
|
PaymentNo string `json:"payment_no"`
|
||||||
OrderID uint64 `json:"order_id"`
|
OrderID uint64 `json:"order_id"`
|
||||||
OrderNo string `json:"order_no"`
|
OrderNo string `json:"order_no"`
|
||||||
@@ -79,6 +81,7 @@ type PaginatedResult struct {
|
|||||||
|
|
||||||
type AdminPaymentDTO struct {
|
type AdminPaymentDTO struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
TenantID uint64 `json:"tenant_id"`
|
||||||
PaymentNo string `json:"payment_no"`
|
PaymentNo string `json:"payment_no"`
|
||||||
OrderID uint64 `json:"order_id"`
|
OrderID uint64 `json:"order_id"`
|
||||||
OrderNo string `json:"order_no"`
|
OrderNo string `json:"order_no"`
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -114,6 +115,7 @@ func (r *Repository) StartMohong(ctx context.Context, userID uint64, orderID uin
|
|||||||
func (r *Repository) prepareMohongPayment(ctx context.Context, userID uint64, orderID uint64, req StartPaymentRequest, runtimeConfig runtimePaymentConfig) (*model.PaymentOrder, *model.MohongOrder, error) {
|
func (r *Repository) prepareMohongPayment(ctx context.Context, userID uint64, orderID uint64, req StartPaymentRequest, runtimeConfig runtimePaymentConfig) (*model.PaymentOrder, *model.MohongOrder, error) {
|
||||||
var paymentID uint64
|
var paymentID uint64
|
||||||
var orderRow model.MohongOrder
|
var orderRow model.MohongOrder
|
||||||
|
tenantID := tenancy.IDFromContext(ctx)
|
||||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
var row model.MohongOrder
|
var row model.MohongOrder
|
||||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
@@ -137,6 +139,7 @@ func (r *Repository) prepareMohongPayment(ctx context.Context, userID uint64, or
|
|||||||
existing.PayWay = firstNonEmpty(req.PayWay, existing.PayWay, runtimeConfig.PayWay, "ZFBZF")
|
existing.PayWay = firstNonEmpty(req.PayWay, existing.PayWay, runtimeConfig.PayWay, "ZFBZF")
|
||||||
existing.JSPayFlag = firstNonEmpty(req.JSPayFlag, existing.JSPayFlag, runtimeConfig.JSPayFlag, "2")
|
existing.JSPayFlag = firstNonEmpty(req.JSPayFlag, existing.JSPayFlag, runtimeConfig.JSPayFlag, "2")
|
||||||
existing.AmountCent = row.AmountCent
|
existing.AmountCent = row.AmountCent
|
||||||
|
existing.TenantID = firstNonZero(existing.TenantID, tenantID)
|
||||||
existing.PaymentConfigID = firstNonZero(existing.PaymentConfigID, runtimeConfig.ID)
|
existing.PaymentConfigID = firstNonZero(existing.PaymentConfigID, runtimeConfig.ID)
|
||||||
existing.Provider = firstNonEmpty(existing.Provider, runtimeConfig.Provider)
|
existing.Provider = firstNonEmpty(existing.Provider, runtimeConfig.Provider)
|
||||||
existing.MerchantID = firstNonEmpty(existing.MerchantID, runtimeConfig.MerchantID)
|
existing.MerchantID = firstNonEmpty(existing.MerchantID, runtimeConfig.MerchantID)
|
||||||
@@ -153,7 +156,7 @@ func (r *Repository) prepareMohongPayment(ctx context.Context, userID uint64, or
|
|||||||
} else if err != gorm.ErrRecordNotFound {
|
} else if err != gorm.ErrRecordNotFound {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
payment, err := newMohongPayment(row, req, runtimeConfig)
|
payment, err := newMohongPayment(row, req, runtimeConfig, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -174,12 +177,13 @@ func (r *Repository) prepareMohongPayment(ctx context.Context, userID uint64, or
|
|||||||
return payment, &orderRow, nil
|
return payment, &orderRow, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newMohongPayment(row model.MohongOrder, req StartPaymentRequest, runtimeConfig runtimePaymentConfig) (model.PaymentOrder, error) {
|
func newMohongPayment(row model.MohongOrder, req StartPaymentRequest, runtimeConfig runtimePaymentConfig, tenantID uint64) (model.PaymentOrder, error) {
|
||||||
paymentNo, err := newPaymentNo()
|
paymentNo, err := newPaymentNo()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.PaymentOrder{}, err
|
return model.PaymentOrder{}, err
|
||||||
}
|
}
|
||||||
payment := model.PaymentOrder{
|
payment := model.PaymentOrder{
|
||||||
|
TenantID: tenantID,
|
||||||
PaymentNo: paymentNo,
|
PaymentNo: paymentNo,
|
||||||
OrderID: row.ID,
|
OrderID: row.ID,
|
||||||
OrderNo: row.OrderNo,
|
OrderNo: row.OrderNo,
|
||||||
@@ -205,8 +209,12 @@ func newMohongPayment(row model.MohongOrder, req StartPaymentRequest, runtimeCon
|
|||||||
// QueryMohong 查询撞车订单支付状态。
|
// QueryMohong 查询撞车订单支付状态。
|
||||||
func (r *Repository) QueryMohong(ctx context.Context, userID uint64, orderID uint64) (*PaymentDTO, error) {
|
func (r *Repository) QueryMohong(ctx context.Context, userID uint64, orderID uint64) (*PaymentDTO, error) {
|
||||||
var payment model.PaymentOrder
|
var payment model.PaymentOrder
|
||||||
if err := r.db.WithContext(ctx).
|
query := r.db.WithContext(ctx).
|
||||||
Where("order_id = ? AND user_id = ? AND biz_type = ?", orderID, userID, bizTypeMohongPay).
|
Where("order_id = ? AND user_id = ? AND biz_type = ?", orderID, userID, bizTypeMohongPay)
|
||||||
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
|
query = query.Where("tenant_id = ?", tenantID)
|
||||||
|
}
|
||||||
|
if err := query.
|
||||||
Order("id DESC").
|
Order("id DESC").
|
||||||
First(&payment).Error; err != nil {
|
First(&payment).Error; err != nil {
|
||||||
if err == gorm.ErrRecordNotFound {
|
if err == gorm.ErrRecordNotFound {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
"hfb_sys/backend/internal/timeutil"
|
"hfb_sys/backend/internal/timeutil"
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
@@ -136,11 +137,16 @@ func (r *Repository) preparePayment(ctx context.Context, userID uint64, orderID
|
|||||||
if row.Status != "pending_payment" {
|
if row.Status != "pending_payment" {
|
||||||
return ErrPaymentCannotStart
|
return ErrPaymentCannotStart
|
||||||
}
|
}
|
||||||
|
requestTenantID := tenancy.IDFromContext(ctx)
|
||||||
|
paymentTenantID := orderPaymentTenantID(row)
|
||||||
|
if requestTenantID > 0 && paymentTenantID > 0 && requestTenantID != paymentTenantID {
|
||||||
|
return ErrPaymentCannotStart
|
||||||
|
}
|
||||||
amountCent := row.RentAmountCent + row.DepositAmountCent
|
amountCent := row.RentAmountCent + row.DepositAmountCent
|
||||||
if amountCent <= 0 {
|
if amountCent <= 0 {
|
||||||
return ErrPaymentCannotStart
|
return ErrPaymentCannotStart
|
||||||
}
|
}
|
||||||
runtimeConfig, err := r.resolveOrderRuntimeConfig(ctx, tx, row.DistributionSiteID, req.PayWay)
|
runtimeConfig, err := r.resolveOrderRuntimeConfig(ctx, tx, paymentTenantID, row.DistributionSiteID, req.PayWay)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -154,6 +160,7 @@ func (r *Repository) preparePayment(ctx context.Context, userID uint64, orderID
|
|||||||
existing.PayWay = firstNonEmpty(req.PayWay, existing.PayWay, runtimeConfig.PayWay, "ZFBZF")
|
existing.PayWay = firstNonEmpty(req.PayWay, existing.PayWay, runtimeConfig.PayWay, "ZFBZF")
|
||||||
existing.JSPayFlag = firstNonEmpty(req.JSPayFlag, existing.JSPayFlag, runtimeConfig.JSPayFlag, "2")
|
existing.JSPayFlag = firstNonEmpty(req.JSPayFlag, existing.JSPayFlag, runtimeConfig.JSPayFlag, "2")
|
||||||
existing.AmountCent = amountCent
|
existing.AmountCent = amountCent
|
||||||
|
existing.TenantID = firstNonZero(existing.TenantID, paymentTenantID)
|
||||||
existing.PaymentConfigID = firstNonZero(existing.PaymentConfigID, runtimeConfig.ID)
|
existing.PaymentConfigID = firstNonZero(existing.PaymentConfigID, runtimeConfig.ID)
|
||||||
existing.Provider = firstNonEmpty(existing.Provider, runtimeConfig.Provider)
|
existing.Provider = firstNonEmpty(existing.Provider, runtimeConfig.Provider)
|
||||||
existing.MerchantID = firstNonEmpty(existing.MerchantID, runtimeConfig.MerchantID)
|
existing.MerchantID = firstNonEmpty(existing.MerchantID, runtimeConfig.MerchantID)
|
||||||
@@ -240,6 +247,7 @@ func newOrderPayment(row model.RentalOrder, amountCent int64, req StartPaymentRe
|
|||||||
return model.PaymentOrder{}, err
|
return model.PaymentOrder{}, err
|
||||||
}
|
}
|
||||||
payment := model.PaymentOrder{
|
payment := model.PaymentOrder{
|
||||||
|
TenantID: orderPaymentTenantID(row),
|
||||||
PaymentNo: paymentNo,
|
PaymentNo: paymentNo,
|
||||||
OrderID: row.ID,
|
OrderID: row.ID,
|
||||||
OrderNo: row.OrderNo,
|
OrderNo: row.OrderNo,
|
||||||
@@ -261,3 +269,10 @@ func newOrderPayment(row model.RentalOrder, amountCent int64, req StartPaymentRe
|
|||||||
}
|
}
|
||||||
return payment, nil
|
return payment, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func orderPaymentTenantID(row model.RentalOrder) uint64 {
|
||||||
|
if row.PaymentTenantID > 0 {
|
||||||
|
return row.PaymentTenantID
|
||||||
|
}
|
||||||
|
return row.BuyerTenantID
|
||||||
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
func toDTO(payment model.PaymentOrder) PaymentDTO {
|
func toDTO(payment model.PaymentOrder) PaymentDTO {
|
||||||
return PaymentDTO{
|
return PaymentDTO{
|
||||||
ID: payment.ID,
|
ID: payment.ID,
|
||||||
|
TenantID: payment.TenantID,
|
||||||
PaymentNo: payment.PaymentNo,
|
PaymentNo: payment.PaymentNo,
|
||||||
OrderID: payment.OrderID,
|
OrderID: payment.OrderID,
|
||||||
OrderNo: payment.OrderNo,
|
OrderNo: payment.OrderNo,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
"gorm.io/gorm/clause"
|
||||||
@@ -42,10 +43,14 @@ func (r *Repository) prepareQualityOwnerPayment(ctx context.Context, userID uint
|
|||||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
var user model.User
|
var user model.User
|
||||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
Select("id").
|
Select("id, tenant_id").
|
||||||
First(&user, userID).Error; err != nil {
|
First(&user, userID).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
requestTenantID := tenancy.IDFromContext(ctx)
|
||||||
|
if requestTenantID > 0 && user.TenantID > 0 && requestTenantID != user.TenantID {
|
||||||
|
return ErrPaymentCannotStart
|
||||||
|
}
|
||||||
var existing model.PaymentOrder
|
var existing model.PaymentOrder
|
||||||
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
Where("user_id = ? AND biz_type = ? AND biz_id = ?", userID, qualityOwnerPayBizType, userID).
|
Where("user_id = ? AND biz_type = ? AND biz_id = ?", userID, qualityOwnerPayBizType, userID).
|
||||||
@@ -56,6 +61,7 @@ func (r *Repository) prepareQualityOwnerPayment(ctx context.Context, userID uint
|
|||||||
existing.PayWay = firstNonEmpty(req.PayWay, existing.PayWay, runtimeConfig.PayWay, "ZFBZF")
|
existing.PayWay = firstNonEmpty(req.PayWay, existing.PayWay, runtimeConfig.PayWay, "ZFBZF")
|
||||||
existing.JSPayFlag = firstNonEmpty(req.JSPayFlag, existing.JSPayFlag, runtimeConfig.JSPayFlag, "2")
|
existing.JSPayFlag = firstNonEmpty(req.JSPayFlag, existing.JSPayFlag, runtimeConfig.JSPayFlag, "2")
|
||||||
existing.AmountCent = amountCent
|
existing.AmountCent = amountCent
|
||||||
|
existing.TenantID = firstNonZero(existing.TenantID, user.TenantID, requestTenantID)
|
||||||
existing.PaymentConfigID = firstNonZero(existing.PaymentConfigID, runtimeConfig.ID)
|
existing.PaymentConfigID = firstNonZero(existing.PaymentConfigID, runtimeConfig.ID)
|
||||||
existing.Provider = firstNonEmpty(existing.Provider, runtimeConfig.Provider)
|
existing.Provider = firstNonEmpty(existing.Provider, runtimeConfig.Provider)
|
||||||
existing.MerchantID = firstNonEmpty(existing.MerchantID, runtimeConfig.MerchantID)
|
existing.MerchantID = firstNonEmpty(existing.MerchantID, runtimeConfig.MerchantID)
|
||||||
@@ -71,7 +77,7 @@ func (r *Repository) prepareQualityOwnerPayment(ctx context.Context, userID uint
|
|||||||
} else if err != gorm.ErrRecordNotFound {
|
} else if err != gorm.ErrRecordNotFound {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
payment, err := newQualityOwnerPayment(userID, amountCent, req, *runtimeConfig)
|
payment, err := newQualityOwnerPayment(userID, amountCent, req, *runtimeConfig, firstNonZero(user.TenantID, requestTenantID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -96,13 +102,14 @@ func canReuseQualityOwnerPayment(payment model.PaymentOrder, runtimeConfig runti
|
|||||||
return canReuseOrderPayment(payment, runtimeConfig)
|
return canReuseOrderPayment(payment, runtimeConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newQualityOwnerPayment(userID uint64, amountCent int64, req StartPaymentRequest, runtimeConfig runtimePaymentConfig) (model.PaymentOrder, error) {
|
func newQualityOwnerPayment(userID uint64, amountCent int64, req StartPaymentRequest, runtimeConfig runtimePaymentConfig, tenantID uint64) (model.PaymentOrder, error) {
|
||||||
paymentNo, err := newPaymentNo()
|
paymentNo, err := newPaymentNo()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.PaymentOrder{}, err
|
return model.PaymentOrder{}, err
|
||||||
}
|
}
|
||||||
orderNo := fmt.Sprintf("QO%d", userID)
|
orderNo := fmt.Sprintf("QO%d", userID)
|
||||||
payment := model.PaymentOrder{
|
payment := model.PaymentOrder{
|
||||||
|
TenantID: tenantID,
|
||||||
PaymentNo: paymentNo,
|
PaymentNo: paymentNo,
|
||||||
OrderID: 0,
|
OrderID: 0,
|
||||||
OrderNo: orderNo,
|
OrderNo: orderNo,
|
||||||
@@ -127,8 +134,12 @@ func newQualityOwnerPayment(userID uint64, amountCent int64, req StartPaymentReq
|
|||||||
|
|
||||||
func (r *Repository) QueryQualityOwner(ctx context.Context, userID uint64) (*PaymentDTO, error) {
|
func (r *Repository) QueryQualityOwner(ctx context.Context, userID uint64) (*PaymentDTO, error) {
|
||||||
var payment model.PaymentOrder
|
var payment model.PaymentOrder
|
||||||
if err := r.db.WithContext(ctx).
|
query := r.db.WithContext(ctx).
|
||||||
Where("user_id = ? AND biz_type = ? AND biz_id = ?", userID, qualityOwnerPayBizType, userID).
|
Where("user_id = ? AND biz_type = ? AND biz_id = ?", userID, qualityOwnerPayBizType, userID)
|
||||||
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
|
query = query.Where("tenant_id = ?", tenantID)
|
||||||
|
}
|
||||||
|
if err := query.
|
||||||
Order("id DESC").
|
Order("id DESC").
|
||||||
First(&payment).Error; err != nil {
|
First(&payment).Error; err != nil {
|
||||||
if err == gorm.ErrRecordNotFound {
|
if err == gorm.ErrRecordNotFound {
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ func TestNewQualityOwnerPaymentUsesBizIDAndMockCashier(t *testing.T) {
|
|||||||
MerchantID: "mock-merchant",
|
MerchantID: "mock-merchant",
|
||||||
PayWay: "WXZF",
|
PayWay: "WXZF",
|
||||||
JSPayFlag: "2",
|
JSPayFlag: "2",
|
||||||
})
|
}, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("newQualityOwnerPayment() error = %v", err)
|
t.Fatalf("newQualityOwnerPayment() error = %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,16 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (r *Repository) Query(ctx context.Context, userID uint64, orderID uint64) (*PaymentDTO, error) {
|
func (r *Repository) Query(ctx context.Context, userID uint64, orderID uint64) (*PaymentDTO, error) {
|
||||||
var payment model.PaymentOrder
|
var payment model.PaymentOrder
|
||||||
if err := r.db.WithContext(ctx).Where("order_id = ? AND user_id = ? AND biz_type = ?", orderID, userID, "order_pay").Order("id DESC").First(&payment).Error; err != nil {
|
query := r.db.WithContext(ctx).Where("order_id = ? AND user_id = ? AND biz_type = ?", orderID, userID, "order_pay")
|
||||||
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
|
query = query.Where("tenant_id = ?", tenantID)
|
||||||
|
}
|
||||||
|
if err := query.Order("id DESC").First(&payment).Error; err != nil {
|
||||||
if err == gorm.ErrRecordNotFound {
|
if err == gorm.ErrRecordNotFound {
|
||||||
return nil, ErrPaymentNotFound
|
return nil, ErrPaymentNotFound
|
||||||
}
|
}
|
||||||
@@ -48,6 +53,10 @@ func (r *Repository) AdminList(ctx context.Context, query AdminPaymentQuery) (*P
|
|||||||
Select("p.*, COALESCE(u.phone, '') AS user_phone").
|
Select("p.*, COALESCE(u.phone, '') AS user_phone").
|
||||||
Joins("LEFT JOIN users AS u ON u.id = p.user_id")
|
Joins("LEFT JOIN users AS u ON u.id = p.user_id")
|
||||||
countDB := r.db.WithContext(ctx).Model(&model.PaymentOrder{})
|
countDB := r.db.WithContext(ctx).Model(&model.PaymentOrder{})
|
||||||
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
|
db = db.Where("p.tenant_id = ?", tenantID)
|
||||||
|
countDB = countDB.Where("tenant_id = ?", tenantID)
|
||||||
|
}
|
||||||
if query.UserID > 0 {
|
if query.UserID > 0 {
|
||||||
db = db.Where("p.user_id = ?", query.UserID)
|
db = db.Where("p.user_id = ?", query.UserID)
|
||||||
countDB = countDB.Where("user_id = ?", query.UserID)
|
countDB = countDB.Where("user_id = ?", query.UserID)
|
||||||
@@ -104,6 +113,7 @@ func (row adminPaymentRow) toDTO() AdminPaymentDTO {
|
|||||||
errorCode, errorMessage := paymentErrorSummary(row.Status, row.RawResponse)
|
errorCode, errorMessage := paymentErrorSummary(row.Status, row.RawResponse)
|
||||||
return AdminPaymentDTO{
|
return AdminPaymentDTO{
|
||||||
ID: row.ID,
|
ID: row.ID,
|
||||||
|
TenantID: row.TenantID,
|
||||||
PaymentNo: row.PaymentNo,
|
PaymentNo: row.PaymentNo,
|
||||||
OrderID: row.OrderID,
|
OrderID: row.OrderID,
|
||||||
OrderNo: row.OrderNo,
|
OrderNo: row.OrderNo,
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/modules/distribution"
|
"hfb_sys/backend/internal/modules/distribution"
|
||||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"gorm.io/datatypes"
|
"gorm.io/datatypes"
|
||||||
@@ -163,7 +164,11 @@ func (r *Repository) StartRefund(ctx context.Context, orderID uint64, refundAmou
|
|||||||
}
|
}
|
||||||
func (r *Repository) QueryRefundStatus(ctx context.Context, orderID uint64) (*RefundDTO, error) {
|
func (r *Repository) QueryRefundStatus(ctx context.Context, orderID uint64) (*RefundDTO, error) {
|
||||||
var payment model.PaymentOrder
|
var payment model.PaymentOrder
|
||||||
if err := r.db.WithContext(ctx).Where("order_id = ? AND biz_type IN ?", orderID, refundBizTypes).Order("id DESC").First(&payment).Error; err != nil {
|
query := r.db.WithContext(ctx).Where("order_id = ? AND biz_type IN ?", orderID, refundBizTypes)
|
||||||
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
|
query = query.Where("tenant_id = ?", tenantID)
|
||||||
|
}
|
||||||
|
if err := query.Order("id DESC").First(&payment).Error; err != nil {
|
||||||
if err == gorm.ErrRecordNotFound {
|
if err == gorm.ErrRecordNotFound {
|
||||||
return nil, ErrPaymentNotFound
|
return nil, ErrPaymentNotFound
|
||||||
}
|
}
|
||||||
@@ -196,7 +201,11 @@ func (r *Repository) SyncRefundStatusByPaymentID(ctx context.Context, paymentID
|
|||||||
}
|
}
|
||||||
func (r *Repository) findOriginalPayment(ctx context.Context, orderID uint64) (model.PaymentOrder, error) {
|
func (r *Repository) findOriginalPayment(ctx context.Context, orderID uint64) (model.PaymentOrder, error) {
|
||||||
var originalPayment model.PaymentOrder
|
var originalPayment model.PaymentOrder
|
||||||
if err := r.db.WithContext(ctx).Where("order_id = ? AND status = 'paid' AND biz_type = 'order_pay'", orderID).Order("id DESC").First(&originalPayment).Error; err != nil {
|
query := r.db.WithContext(ctx).Where("order_id = ? AND status = 'paid' AND biz_type = 'order_pay'", orderID)
|
||||||
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
|
query = query.Where("tenant_id = ?", tenantID)
|
||||||
|
}
|
||||||
|
if err := query.Order("id DESC").First(&originalPayment).Error; err != nil {
|
||||||
if err == gorm.ErrRecordNotFound {
|
if err == gorm.ErrRecordNotFound {
|
||||||
return originalPayment, ErrPaymentNotFound
|
return originalPayment, ErrPaymentNotFound
|
||||||
}
|
}
|
||||||
@@ -216,7 +225,7 @@ func (r *Repository) prepareRefundOrder(ctx context.Context, originalPayment mod
|
|||||||
}
|
}
|
||||||
var existingRefund model.PaymentOrder
|
var existingRefund model.PaymentOrder
|
||||||
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
Where("order_id = ? AND biz_type = ?", originalPayment.OrderID, bizType).
|
Where("order_id = ? AND biz_type = ? AND tenant_id = ?", originalPayment.OrderID, bizType, originalPayment.TenantID).
|
||||||
Order("id DESC").
|
Order("id DESC").
|
||||||
First(&existingRefund).Error
|
First(&existingRefund).Error
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -233,6 +242,7 @@ func (r *Repository) prepareRefundOrder(ctx context.Context, originalPayment mod
|
|||||||
}
|
}
|
||||||
merchantRefundID := "REF" + paymentNo[3:]
|
merchantRefundID := "REF" + paymentNo[3:]
|
||||||
refundOrder := model.PaymentOrder{
|
refundOrder := model.PaymentOrder{
|
||||||
|
TenantID: originalPayment.TenantID,
|
||||||
PaymentNo: paymentNo,
|
PaymentNo: paymentNo,
|
||||||
OrderID: originalPayment.OrderID,
|
OrderID: originalPayment.OrderID,
|
||||||
OrderNo: originalPayment.OrderNo,
|
OrderNo: originalPayment.OrderNo,
|
||||||
@@ -505,6 +515,7 @@ func (r *Repository) markRefundFailed(ctx context.Context, paymentID uint64, ord
|
|||||||
func toRefundDTO(payment model.PaymentOrder) RefundDTO {
|
func toRefundDTO(payment model.PaymentOrder) RefundDTO {
|
||||||
return RefundDTO{
|
return RefundDTO{
|
||||||
ID: payment.ID,
|
ID: payment.ID,
|
||||||
|
TenantID: payment.TenantID,
|
||||||
PaymentNo: payment.PaymentNo,
|
PaymentNo: payment.PaymentNo,
|
||||||
OrderID: payment.OrderID,
|
OrderID: payment.OrderID,
|
||||||
OrderNo: payment.OrderNo,
|
OrderNo: payment.OrderNo,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -125,8 +126,12 @@ func (r *Repository) StartMohongRefund(ctx context.Context, orderID uint64, refu
|
|||||||
|
|
||||||
func (r *Repository) findOriginalMohongPayment(ctx context.Context, orderID uint64) (model.PaymentOrder, error) {
|
func (r *Repository) findOriginalMohongPayment(ctx context.Context, orderID uint64) (model.PaymentOrder, error) {
|
||||||
var originalPayment model.PaymentOrder
|
var originalPayment model.PaymentOrder
|
||||||
if err := r.db.WithContext(ctx).
|
query := r.db.WithContext(ctx).
|
||||||
Where("order_id = ? AND status = 'paid' AND biz_type = ?", orderID, bizTypeMohongPay).
|
Where("order_id = ? AND status = 'paid' AND biz_type = ?", orderID, bizTypeMohongPay)
|
||||||
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
|
query = query.Where("tenant_id = ?", tenantID)
|
||||||
|
}
|
||||||
|
if err := query.
|
||||||
Order("id DESC").
|
Order("id DESC").
|
||||||
First(&originalPayment).Error; err != nil {
|
First(&originalPayment).Error; err != nil {
|
||||||
if err == gorm.ErrRecordNotFound {
|
if err == gorm.ErrRecordNotFound {
|
||||||
@@ -158,7 +163,7 @@ func (r *Repository) prepareMohongRefundOrder(ctx context.Context, originalPayme
|
|||||||
|
|
||||||
var existingRefund model.PaymentOrder
|
var existingRefund model.PaymentOrder
|
||||||
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
Where("order_id = ? AND biz_type = ?", originalPayment.OrderID, bizTypeMohongRefund).
|
Where("order_id = ? AND biz_type = ? AND tenant_id = ?", originalPayment.OrderID, bizTypeMohongRefund, originalPayment.TenantID).
|
||||||
Order("id DESC").
|
Order("id DESC").
|
||||||
First(&existingRefund).Error
|
First(&existingRefund).Error
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -176,6 +181,7 @@ func (r *Repository) prepareMohongRefundOrder(ctx context.Context, originalPayme
|
|||||||
}
|
}
|
||||||
merchantRefundID := "REF" + paymentNo[3:]
|
merchantRefundID := "REF" + paymentNo[3:]
|
||||||
refundOrder := model.PaymentOrder{
|
refundOrder := model.PaymentOrder{
|
||||||
|
TenantID: originalPayment.TenantID,
|
||||||
PaymentNo: paymentNo,
|
PaymentNo: paymentNo,
|
||||||
OrderID: originalPayment.OrderID,
|
OrderID: originalPayment.OrderID,
|
||||||
OrderNo: originalPayment.OrderNo,
|
OrderNo: originalPayment.OrderNo,
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/modules/order"
|
"hfb_sys/backend/internal/modules/order"
|
||||||
"hfb_sys/backend/internal/modules/paymentconfig"
|
"hfb_sys/backend/internal/modules/paymentconfig"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -176,8 +177,9 @@ func (c runtimePaymentConfig) isMockMode() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// resolveOrderRuntimeConfig 根据订单所属分销站点配置或全局默认配置解析运行时支付配置。
|
// resolveOrderRuntimeConfig 根据订单所属分销站点配置或全局默认配置解析运行时支付配置。
|
||||||
func (r *Repository) resolveOrderRuntimeConfig(ctx context.Context, tx *gorm.DB, siteID *uint64, payWay string) (*runtimePaymentConfig, error) {
|
func (r *Repository) resolveOrderRuntimeConfig(ctx context.Context, tx *gorm.DB, tenantID uint64, siteID *uint64, payWay string) (*runtimePaymentConfig, error) {
|
||||||
if siteID != nil && *siteID > 0 {
|
configCtx := scopedTenantContext(ctx, tenantID)
|
||||||
|
if tenantID == 0 && siteID != nil && *siteID > 0 {
|
||||||
var configID uint64
|
var configID uint64
|
||||||
queryDB := tx
|
queryDB := tx
|
||||||
if queryDB == nil {
|
if queryDB == nil {
|
||||||
@@ -190,13 +192,13 @@ func (r *Repository) resolveOrderRuntimeConfig(ctx context.Context, tx *gorm.DB,
|
|||||||
Limit(1).
|
Limit(1).
|
||||||
Pluck("pmc.id", &configID).Error
|
Pluck("pmc.id", &configID).Error
|
||||||
if err == nil && configID > 0 && r.configRepo != nil {
|
if err == nil && configID > 0 && r.configRepo != nil {
|
||||||
dto, err := r.configRepo.FindRuntimeByID(ctx, configID, true)
|
dto, err := r.configRepo.FindRuntimeByID(configCtx, configID, true)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return runtimeConfigFromDTO(dto), nil
|
return runtimeConfigFromDTO(dto), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return r.defaultRuntimeConfig(ctx, payWay)
|
return r.defaultRuntimeConfig(configCtx, payWay)
|
||||||
}
|
}
|
||||||
|
|
||||||
// defaultRuntimeConfig 按支付方式获取默认启用配置,用于新支付单创建。
|
// defaultRuntimeConfig 按支付方式获取默认启用配置,用于新支付单创建。
|
||||||
@@ -213,11 +215,12 @@ func (r *Repository) defaultRuntimeConfig(ctx context.Context, payWay string) (*
|
|||||||
|
|
||||||
// runtimeConfigForPayment 回溯支付单当时命中的配置,优先使用 payment_config_id。
|
// runtimeConfigForPayment 回溯支付单当时命中的配置,优先使用 payment_config_id。
|
||||||
func (r *Repository) runtimeConfigForPayment(ctx context.Context, payment *model.PaymentOrder) (*runtimePaymentConfig, error) {
|
func (r *Repository) runtimeConfigForPayment(ctx context.Context, payment *model.PaymentOrder) (*runtimePaymentConfig, error) {
|
||||||
|
configCtx := scopedTenantContext(ctx, payment.TenantID)
|
||||||
provider := firstNonEmpty(payment.Provider, "mock")
|
provider := firstNonEmpty(payment.Provider, "mock")
|
||||||
merchantID := payment.MerchantID
|
merchantID := payment.MerchantID
|
||||||
payWay := normalizePayWay(payment.PayWay)
|
payWay := normalizePayWay(payment.PayWay)
|
||||||
if r.configRepo != nil && payment.PaymentConfigID > 0 {
|
if r.configRepo != nil && payment.PaymentConfigID > 0 {
|
||||||
dto, err := r.configRepo.FindRuntimeByID(ctx, payment.PaymentConfigID, true)
|
dto, err := r.configRepo.FindRuntimeByID(configCtx, payment.PaymentConfigID, true)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return runtimeConfigFromDTO(dto), nil
|
return runtimeConfigFromDTO(dto), nil
|
||||||
}
|
}
|
||||||
@@ -226,14 +229,14 @@ func (r *Repository) runtimeConfigForPayment(ctx context.Context, payment *model
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if r.configRepo != nil && merchantID != "" {
|
if r.configRepo != nil && merchantID != "" {
|
||||||
dto, err := r.configRepo.FindByProviderMerchantPayWay(ctx, provider, merchantID, payWay, true)
|
dto, err := r.configRepo.FindByProviderMerchantPayWay(configCtx, provider, merchantID, payWay, true)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return runtimeConfigFromDTO(dto), nil
|
return runtimeConfigFromDTO(dto), nil
|
||||||
}
|
}
|
||||||
if err != paymentconfig.ErrConfigNotFound {
|
if err != paymentconfig.ErrConfigNotFound {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
dto, err = r.configRepo.FindByProviderMerchant(ctx, provider, merchantID, true)
|
dto, err = r.configRepo.FindByProviderMerchant(configCtx, provider, merchantID, true)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return runtimeConfigFromDTO(dto), nil
|
return runtimeConfigFromDTO(dto), nil
|
||||||
}
|
}
|
||||||
@@ -253,10 +256,13 @@ func (r *Repository) runtimeConfigForPayment(ctx context.Context, payment *model
|
|||||||
MerchantID: merchantID,
|
MerchantID: merchantID,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
if payment.TenantID > 0 {
|
||||||
|
return nil, ErrPaymentUnavailable
|
||||||
|
}
|
||||||
if r.configRepo == nil {
|
if r.configRepo == nil {
|
||||||
return nil, ErrPaymentUnavailable
|
return nil, ErrPaymentUnavailable
|
||||||
}
|
}
|
||||||
dto, err := r.configRepo.FindDefaultByProviderPayWay(ctx, provider, payWay, true)
|
dto, err := r.configRepo.FindDefaultByProviderPayWay(configCtx, provider, payWay, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -292,7 +298,7 @@ func (r *Repository) recordConfigUsage(ctx context.Context, runtimeConfig *runti
|
|||||||
if (payment.BizType != "order_pay" && payment.BizType != "mohong_pay") || payment.Status != "paid" {
|
if (payment.BizType != "order_pay" && payment.BizType != "mohong_pay") || payment.Status != "paid" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := r.configRepo.RecordUsage(ctx, runtimeConfig.ID, payment.ID, runtimeConfig.Provider, runtimeConfig.MerchantID, payment.AmountCent, payment.BizType); err != nil {
|
if err := r.configRepo.RecordUsage(ctx, payment.TenantID, runtimeConfig.ID, payment.ID, runtimeConfig.Provider, runtimeConfig.MerchantID, payment.AmountCent, payment.BizType); err != nil {
|
||||||
r.log().Warn("支付配置使用记录保存失败", paymentLogFields(ctx,
|
r.log().Warn("支付配置使用记录保存失败", paymentLogFields(ctx,
|
||||||
zap.Uint64("payment_config_id", runtimeConfig.ID),
|
zap.Uint64("payment_config_id", runtimeConfig.ID),
|
||||||
zap.Uint64("payment_id", payment.ID),
|
zap.Uint64("payment_id", payment.ID),
|
||||||
@@ -300,3 +306,10 @@ func (r *Repository) recordConfigUsage(ctx context.Context, runtimeConfig *runti
|
|||||||
)...)
|
)...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func scopedTenantContext(ctx context.Context, tenantID uint64) context.Context {
|
||||||
|
if tenantID == 0 || tenancy.IDFromContext(ctx) == tenantID {
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
return tenancy.WithScope(ctx, tenancy.Scope{TenantID: tenantID})
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package payment
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/modules/paymentconfig"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func paymentTenantContext(tenantID uint64) context.Context {
|
||||||
|
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||||
|
}
|
||||||
|
|
||||||
|
func createPaymentTenantOrder(t *testing.T, db *gorm.DB, tenantID uint64) model.RentalOrder {
|
||||||
|
t.Helper()
|
||||||
|
order := model.RentalOrder{
|
||||||
|
BuyerTenantID: tenantID, SourceTenantID: 101, PaymentTenantID: tenantID,
|
||||||
|
OrderNo: "RO-PAY-TENANT-" + string(rune('0'+tenantID%10)),
|
||||||
|
RenterID: 1, RentAmountCent: 1000, DepositAmountCent: 500,
|
||||||
|
Status: "pending_payment",
|
||||||
|
}
|
||||||
|
if err := db.Create(&order).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return order
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOrderPaymentUsesBuyerTenantMerchant(t *testing.T) {
|
||||||
|
db := database.NewTestDB()
|
||||||
|
dachuiConfig := model.PaymentMerchantConfig{
|
||||||
|
OwnerTenantID: 101, Name: "大锤支付宝", Provider: "mock", MerchantID: "DACHUI-MOCK",
|
||||||
|
PayWay: "ZFBZF", Status: "active", IsDefault: true, Environment: "production",
|
||||||
|
}
|
||||||
|
jieyouConfig := model.PaymentMerchantConfig{
|
||||||
|
OwnerTenantID: 202, Name: "解忧支付宝", Provider: "mock", MerchantID: "JIEYOU-MOCK",
|
||||||
|
PayWay: "ZFBZF", Status: "active", IsDefault: true, Environment: "production",
|
||||||
|
}
|
||||||
|
if err := db.Create(&dachuiConfig).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.Create(&jieyouConfig).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
configRepo := paymentconfig.NewRepository(db, &paymentconfig.MockEncryptor{})
|
||||||
|
repo := NewRepository(db, configRepo, nil)
|
||||||
|
jieyouOrder := createPaymentTenantOrder(t, db, 202)
|
||||||
|
|
||||||
|
payment, _, err := repo.preparePayment(paymentTenantContext(202), jieyouOrder.RenterID, jieyouOrder.ID, StartPaymentRequest{PayWay: "ZFBZF"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("prepare tenant payment: %v", err)
|
||||||
|
}
|
||||||
|
if payment.TenantID != 202 || payment.PaymentConfigID != jieyouConfig.ID || payment.MerchantID != "JIEYOU-MOCK" {
|
||||||
|
t.Fatalf("tenant payment = %+v", payment)
|
||||||
|
}
|
||||||
|
if _, _, err := repo.preparePayment(paymentTenantContext(101), jieyouOrder.RenterID, jieyouOrder.ID, StartPaymentRequest{PayWay: "ZFBZF"}); !errors.Is(err, ErrPaymentCannotStart) {
|
||||||
|
t.Fatalf("cross-tenant payment error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTenantPaymentDoesNotFallbackToAnotherTenantMerchant(t *testing.T) {
|
||||||
|
db := database.NewTestDB()
|
||||||
|
configRepo := paymentconfig.NewRepository(db, &paymentconfig.MockEncryptor{})
|
||||||
|
dachuiConfig := model.PaymentMerchantConfig{
|
||||||
|
OwnerTenantID: 101, Name: "大锤商户", Provider: "leshua", MerchantID: "SHARED-MERCHANT",
|
||||||
|
PayWay: "ZFBZF", Status: "active", IsDefault: true, Environment: "production",
|
||||||
|
}
|
||||||
|
if err := db.Create(&dachuiConfig).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
repo := NewRepository(db, configRepo, nil)
|
||||||
|
payment := model.PaymentOrder{
|
||||||
|
TenantID: 202, PaymentNo: "PAY-NO-FALLBACK", OrderID: 1, OrderNo: "RO-NO-FALLBACK",
|
||||||
|
UserID: 1, PaymentConfigID: dachuiConfig.ID, Provider: "leshua",
|
||||||
|
MerchantID: "SHARED-MERCHANT", ThirdOrderID: "PAY-NO-FALLBACK",
|
||||||
|
PayWay: "ZFBZF", AmountCent: 1000, BizType: "order_pay", Status: "paid",
|
||||||
|
}
|
||||||
|
if _, err := repo.runtimeConfigForPayment(context.Background(), &payment); !errors.Is(err, ErrPaymentUnavailable) {
|
||||||
|
t.Fatalf("cross-tenant merchant fallback error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
jieyouConfig := model.PaymentMerchantConfig{
|
||||||
|
OwnerTenantID: 202, Name: "解忧商户", Provider: "leshua", MerchantID: "JIEYOU-MERCHANT",
|
||||||
|
PayWay: "ZFBZF", Status: "active", IsDefault: true, Environment: "production",
|
||||||
|
}
|
||||||
|
if err := db.Create(&jieyouConfig).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
payment.PaymentConfigID = jieyouConfig.ID
|
||||||
|
payment.MerchantID = "JIEYOU-MERCHANT"
|
||||||
|
runtimeConfig, err := repo.runtimeConfigForPayment(context.Background(), &payment)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("load original tenant merchant: %v", err)
|
||||||
|
}
|
||||||
|
if runtimeConfig.ID != jieyouConfig.ID || runtimeConfig.MerchantID != "JIEYOU-MERCHANT" {
|
||||||
|
t.Fatalf("original merchant runtime = %+v", runtimeConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTenantOrderWithoutOwnConfigDoesNotUseOtherTenantDefault(t *testing.T) {
|
||||||
|
db := database.NewTestDB()
|
||||||
|
config := model.PaymentMerchantConfig{
|
||||||
|
OwnerTenantID: 101, Name: "大锤默认", Provider: "mock", MerchantID: "DACHUI-ONLY",
|
||||||
|
PayWay: "ZFBZF", Status: "active", IsDefault: true, Environment: "production",
|
||||||
|
}
|
||||||
|
if err := db.Create(&config).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
order := createPaymentTenantOrder(t, db, 202)
|
||||||
|
repo := NewRepository(db, paymentconfig.NewRepository(db, &paymentconfig.MockEncryptor{}), nil)
|
||||||
|
if _, _, err := repo.preparePayment(paymentTenantContext(202), order.RenterID, order.ID, StartPaymentRequest{PayWay: "ZFBZF"}); !errors.Is(err, paymentconfig.ErrNoActiveConfigFound) {
|
||||||
|
t.Fatalf("missing tenant config error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
"gorm.io/gorm/clause"
|
||||||
@@ -13,10 +14,11 @@ import (
|
|||||||
|
|
||||||
// ExportBackup 导出所有支付配置备份,包含解密后的密钥。
|
// ExportBackup 导出所有支付配置备份,包含解密后的密钥。
|
||||||
func (r *Repository) ExportBackup(ctx context.Context, actorID uint64, meta AuditMeta) (*ExportBackup, error) {
|
func (r *Repository) ExportBackup(ctx context.Context, actorID uint64, meta AuditMeta) (*ExportBackup, error) {
|
||||||
|
tenantID := tenancy.IDFromContext(ctx)
|
||||||
var backup *ExportBackup
|
var backup *ExportBackup
|
||||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
var items []model.PaymentMerchantConfig
|
var items []model.PaymentMerchantConfig
|
||||||
if err := tx.Order("is_default DESC, id DESC").Find(&items).Error; err != nil {
|
if err := applyOwnerTenantScope(tx, ctx).Order("is_default DESC, id DESC").Find(&items).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,6 +44,7 @@ func (r *Repository) ExportBackup(ctx context.Context, actorID uint64, meta Audi
|
|||||||
return appendAuditLog(tx, actorID, "payment_config.export", 0, meta, map[string]any{
|
return appendAuditLog(tx, actorID, "payment_config.export", 0, meta, map[string]any{
|
||||||
"total": len(configs),
|
"total": len(configs),
|
||||||
"exported_at": exportedAt,
|
"exported_at": exportedAt,
|
||||||
|
"tenant_id": tenantID,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -61,10 +64,11 @@ func (r *Repository) ImportBackup(ctx context.Context, backup ExportBackup, acto
|
|||||||
|
|
||||||
activeKeys := backupActiveKeys(backup.Configs)
|
activeKeys := backupActiveKeys(backup.Configs)
|
||||||
result := &ImportBackupResult{Total: len(backup.Configs)}
|
result := &ImportBackupResult{Total: len(backup.Configs)}
|
||||||
|
tenantID := tenancy.IDFromContext(ctx)
|
||||||
|
|
||||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
for payWay := range activeKeys {
|
for payWay := range activeKeys {
|
||||||
if err := deactivateOtherConfigs(tx, 0, actorID, payWay); err != nil {
|
if err := deactivateOtherConfigs(tx, 0, actorID, payWay, tenantID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -104,7 +108,7 @@ func (r *Repository) ImportBackup(ctx context.Context, backup ExportBackup, acto
|
|||||||
}
|
}
|
||||||
|
|
||||||
var existing model.PaymentMerchantConfig
|
var existing model.PaymentMerchantConfig
|
||||||
err = tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
err = applyOwnerTenantScope(tx.Clauses(clause.Locking{Strength: "UPDATE"}), ctx).
|
||||||
Where("provider = ? AND merchant_id = ? AND pay_way = ?", req.Provider, req.MerchantID, payWay).
|
Where("provider = ? AND merchant_id = ? AND pay_way = ?", req.Provider, req.MerchantID, payWay).
|
||||||
First(&existing).Error
|
First(&existing).Error
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -120,6 +124,7 @@ func (r *Repository) ImportBackup(ctx context.Context, backup ExportBackup, acto
|
|||||||
|
|
||||||
createdBy := actorID
|
createdBy := actorID
|
||||||
item := model.PaymentMerchantConfig{
|
item := model.PaymentMerchantConfig{
|
||||||
|
OwnerTenantID: tenantID,
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
Provider: req.Provider,
|
Provider: req.Provider,
|
||||||
MerchantID: req.MerchantID,
|
MerchantID: req.MerchantID,
|
||||||
@@ -149,6 +154,7 @@ func (r *Repository) ImportBackup(ctx context.Context, backup ExportBackup, acto
|
|||||||
"total": result.Total,
|
"total": result.Total,
|
||||||
"created": result.Created,
|
"created": result.Created,
|
||||||
"updated": result.Updated,
|
"updated": result.Updated,
|
||||||
|
"tenant_id": tenantID,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ var (
|
|||||||
// DTO 数据传输对象
|
// DTO 数据传输对象
|
||||||
type ConfigDTO struct {
|
type ConfigDTO struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
OwnerTenantID uint64 `json:"owner_tenant_id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Provider string `json:"provider"`
|
Provider string `json:"provider"`
|
||||||
MerchantID string `json:"merchant_id"`
|
MerchantID string `json:"merchant_id"`
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
"gorm.io/gorm/clause"
|
||||||
@@ -14,6 +15,7 @@ import (
|
|||||||
// Create 创建配置
|
// Create 创建配置
|
||||||
func (r *Repository) Create(ctx context.Context, req CreateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
func (r *Repository) Create(ctx context.Context, req CreateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
||||||
req = normalizeCreateRequest(req)
|
req = normalizeCreateRequest(req)
|
||||||
|
tenantID := tenancy.IDFromContext(ctx)
|
||||||
// 验证必填字段
|
// 验证必填字段
|
||||||
if err := r.validateCreateRequest(req); err != nil {
|
if err := r.validateCreateRequest(req); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -42,7 +44,7 @@ func (r *Repository) Create(ctx context.Context, req CreateRequest, actorID uint
|
|||||||
payWay := firstNonEmpty(req.PayWay, "ZFBZF")
|
payWay := firstNonEmpty(req.PayWay, "ZFBZF")
|
||||||
isDefault := req.IsDefault
|
isDefault := req.IsDefault
|
||||||
if status == "active" {
|
if status == "active" {
|
||||||
if err := deactivateOtherConfigs(tx, 0, actorID, payWay); err != nil {
|
if err := deactivateOtherConfigs(tx, 0, actorID, payWay, tenantID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
isDefault = true
|
isDefault = true
|
||||||
@@ -51,6 +53,7 @@ func (r *Repository) Create(ctx context.Context, req CreateRequest, actorID uint
|
|||||||
}
|
}
|
||||||
|
|
||||||
item := model.PaymentMerchantConfig{
|
item := model.PaymentMerchantConfig{
|
||||||
|
OwnerTenantID: tenantID,
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
Provider: req.Provider,
|
Provider: req.Provider,
|
||||||
MerchantID: req.MerchantID,
|
MerchantID: req.MerchantID,
|
||||||
@@ -79,6 +82,7 @@ func (r *Repository) Create(ctx context.Context, req CreateRequest, actorID uint
|
|||||||
if err := appendAuditLog(tx, actorID, "payment_config.create", item.ID, meta, map[string]any{
|
if err := appendAuditLog(tx, actorID, "payment_config.create", item.ID, meta, map[string]any{
|
||||||
"name": item.Name,
|
"name": item.Name,
|
||||||
"provider": item.Provider,
|
"provider": item.Provider,
|
||||||
|
"owner_tenant_id": item.OwnerTenantID,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -110,9 +114,10 @@ func (r *Repository) Update(ctx context.Context, id uint64, req UpdateRequest, a
|
|||||||
}
|
}
|
||||||
|
|
||||||
var dto ConfigDTO
|
var dto ConfigDTO
|
||||||
|
tenantID := tenancy.IDFromContext(ctx)
|
||||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
var item model.PaymentMerchantConfig
|
var item model.PaymentMerchantConfig
|
||||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&item).Error; err != nil {
|
if err := applyOwnerTenantScope(tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id), ctx).First(&item).Error; err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
return ErrConfigNotFound
|
return ErrConfigNotFound
|
||||||
}
|
}
|
||||||
@@ -187,7 +192,7 @@ func (r *Repository) Update(ctx context.Context, id uint64, req UpdateRequest, a
|
|||||||
finalPayWay = "ZFBZF"
|
finalPayWay = "ZFBZF"
|
||||||
}
|
}
|
||||||
if finalStatus == "active" {
|
if finalStatus == "active" {
|
||||||
if err := deactivateOtherConfigs(tx, id, actorID, finalPayWay); err != nil {
|
if err := deactivateOtherConfigs(tx, id, actorID, finalPayWay, tenantID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
updates["status"] = "active"
|
updates["status"] = "active"
|
||||||
@@ -288,7 +293,7 @@ func trimExtraConfig(config map[string]any) map[string]any {
|
|||||||
func (r *Repository) Delete(ctx context.Context, id uint64, actorID uint64, meta AuditMeta) error {
|
func (r *Repository) Delete(ctx context.Context, id uint64, actorID uint64, meta AuditMeta) error {
|
||||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
var item model.PaymentMerchantConfig
|
var item model.PaymentMerchantConfig
|
||||||
if err := tx.Where("id = ?", id).First(&item).Error; err != nil {
|
if err := applyOwnerTenantScope(tx.Where("id = ?", id), ctx).First(&item).Error; err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
return ErrConfigNotFound
|
return ErrConfigNotFound
|
||||||
}
|
}
|
||||||
@@ -320,8 +325,9 @@ func (r *Repository) Delete(ctx context.Context, id uint64, actorID uint64, meta
|
|||||||
}
|
}
|
||||||
|
|
||||||
// deactivateOtherConfigs 保证同一个支付方式同一时间只有一个启用配置。
|
// deactivateOtherConfigs 保证同一个支付方式同一时间只有一个启用配置。
|
||||||
func deactivateOtherConfigs(tx *gorm.DB, activeID uint64, actorID uint64, payWay string) error {
|
func deactivateOtherConfigs(tx *gorm.DB, activeID uint64, actorID uint64, payWay string, tenantID uint64) error {
|
||||||
db := tx.Model(&model.PaymentMerchantConfig{}).
|
db := tx.Model(&model.PaymentMerchantConfig{}).
|
||||||
|
Where("owner_tenant_id = ?", tenantID).
|
||||||
Where("pay_way = ? AND (status = ? OR is_default = ?)", payWay, "active", true)
|
Where("pay_way = ? AND (status = ? OR is_default = ?)", payWay, "active", true)
|
||||||
if activeID > 0 {
|
if activeID > 0 {
|
||||||
db = db.Where("id != ?", activeID)
|
db = db.Where("id != ?", activeID)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
func (r *Repository) toDTO(item model.PaymentMerchantConfig, includeSecret bool) (ConfigDTO, error) {
|
func (r *Repository) toDTO(item model.PaymentMerchantConfig, includeSecret bool) (ConfigDTO, error) {
|
||||||
dto := ConfigDTO{
|
dto := ConfigDTO{
|
||||||
ID: item.ID,
|
ID: item.ID,
|
||||||
|
OwnerTenantID: item.OwnerTenantID,
|
||||||
Name: item.Name,
|
Name: item.Name,
|
||||||
Provider: item.Provider,
|
Provider: item.Provider,
|
||||||
MerchantID: item.MerchantID,
|
MerchantID: item.MerchantID,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
@@ -14,7 +15,7 @@ func (r *Repository) List(ctx context.Context, query ListQuery) ([]ConfigDTO, in
|
|||||||
var items []model.PaymentMerchantConfig
|
var items []model.PaymentMerchantConfig
|
||||||
var total int64
|
var total int64
|
||||||
|
|
||||||
db := r.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{})
|
db := applyOwnerTenantScope(r.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{}), ctx)
|
||||||
|
|
||||||
// 过滤条件
|
// 过滤条件
|
||||||
if query.Provider != "" {
|
if query.Provider != "" {
|
||||||
@@ -72,7 +73,7 @@ func (r *Repository) List(ctx context.Context, query ListQuery) ([]ConfigDTO, in
|
|||||||
// FindByID 根据 ID 查询配置
|
// FindByID 根据 ID 查询配置
|
||||||
func (r *Repository) FindByID(ctx context.Context, id uint64, includeSecret bool, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
func (r *Repository) FindByID(ctx context.Context, id uint64, includeSecret bool, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
||||||
var item model.PaymentMerchantConfig
|
var item model.PaymentMerchantConfig
|
||||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&item).Error; err != nil {
|
if err := applyOwnerTenantScope(r.db.WithContext(ctx).Where("id = ?", id), ctx).First(&item).Error; err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
return nil, ErrConfigNotFound
|
return nil, ErrConfigNotFound
|
||||||
}
|
}
|
||||||
@@ -134,7 +135,7 @@ func (r *Repository) applyPaymentReferenceFlags(ctx context.Context, dtos []Conf
|
|||||||
// FindRuntimeByID 根据配置 ID 查询运行时配置,不写审计日志,供支付单回溯原配置使用。
|
// FindRuntimeByID 根据配置 ID 查询运行时配置,不写审计日志,供支付单回溯原配置使用。
|
||||||
func (r *Repository) FindRuntimeByID(ctx context.Context, id uint64, includeSecret bool) (*ConfigDTO, error) {
|
func (r *Repository) FindRuntimeByID(ctx context.Context, id uint64, includeSecret bool) (*ConfigDTO, error) {
|
||||||
var item model.PaymentMerchantConfig
|
var item model.PaymentMerchantConfig
|
||||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&item).Error; err != nil {
|
if err := applyOwnerTenantScope(r.db.WithContext(ctx).Where("id = ?", id), ctx).First(&item).Error; err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
return nil, ErrConfigNotFound
|
return nil, ErrConfigNotFound
|
||||||
}
|
}
|
||||||
@@ -150,7 +151,8 @@ func (r *Repository) FindRuntimeByID(ctx context.Context, id uint64, includeSecr
|
|||||||
// FindDefault 查询指定服务商的默认启用配置,兼容旧调用路径。
|
// FindDefault 查询指定服务商的默认启用配置,兼容旧调用路径。
|
||||||
func (r *Repository) FindDefault(ctx context.Context, provider string) (*model.PaymentMerchantConfig, error) {
|
func (r *Repository) FindDefault(ctx context.Context, provider string) (*model.PaymentMerchantConfig, error) {
|
||||||
var item model.PaymentMerchantConfig
|
var item model.PaymentMerchantConfig
|
||||||
if err := r.db.WithContext(ctx).Where("provider = ? AND is_default = ? AND status = ?", provider, true, "active").First(&item).Error; err != nil {
|
if err := applyOwnerTenantScope(r.db.WithContext(ctx), ctx).
|
||||||
|
Where("provider = ? AND is_default = ? AND status = ?", provider, true, "active").First(&item).Error; err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
return nil, ErrNoActiveConfigFound
|
return nil, ErrNoActiveConfigFound
|
||||||
}
|
}
|
||||||
@@ -162,7 +164,7 @@ func (r *Repository) FindDefault(ctx context.Context, provider string) (*model.P
|
|||||||
// FindDefaultByPayWay 查询指定支付方式的默认启用配置。
|
// FindDefaultByPayWay 查询指定支付方式的默认启用配置。
|
||||||
func (r *Repository) FindDefaultByPayWay(ctx context.Context, payWay string, includeSecret bool) (*ConfigDTO, error) {
|
func (r *Repository) FindDefaultByPayWay(ctx context.Context, payWay string, includeSecret bool) (*ConfigDTO, error) {
|
||||||
var item model.PaymentMerchantConfig
|
var item model.PaymentMerchantConfig
|
||||||
if err := r.db.WithContext(ctx).
|
if err := applyOwnerTenantScope(r.db.WithContext(ctx), ctx).
|
||||||
Where("pay_way = ? AND status = ?", payWay, "active").
|
Where("pay_way = ? AND status = ?", payWay, "active").
|
||||||
Order("is_default DESC, id DESC").
|
Order("is_default DESC, id DESC").
|
||||||
First(&item).Error; err != nil {
|
First(&item).Error; err != nil {
|
||||||
@@ -194,7 +196,7 @@ func (r *Repository) FindDefaultByProvider(ctx context.Context, provider string,
|
|||||||
// FindDefaultByProviderPayWay 查询指定服务商和支付方式的默认启用配置。
|
// FindDefaultByProviderPayWay 查询指定服务商和支付方式的默认启用配置。
|
||||||
func (r *Repository) FindDefaultByProviderPayWay(ctx context.Context, provider string, payWay string, includeSecret bool) (*ConfigDTO, error) {
|
func (r *Repository) FindDefaultByProviderPayWay(ctx context.Context, provider string, payWay string, includeSecret bool) (*ConfigDTO, error) {
|
||||||
var item model.PaymentMerchantConfig
|
var item model.PaymentMerchantConfig
|
||||||
if err := r.db.WithContext(ctx).
|
if err := applyOwnerTenantScope(r.db.WithContext(ctx), ctx).
|
||||||
Where("provider = ? AND pay_way = ? AND status = ?", provider, payWay, "active").
|
Where("provider = ? AND pay_way = ? AND status = ?", provider, payWay, "active").
|
||||||
Order("is_default DESC, id DESC").
|
Order("is_default DESC, id DESC").
|
||||||
First(&item).Error; err != nil {
|
First(&item).Error; err != nil {
|
||||||
@@ -213,7 +215,8 @@ func (r *Repository) FindDefaultByProviderPayWay(ctx context.Context, provider s
|
|||||||
// FindByProviderMerchantPayWay 根据服务商、商户号和支付方式查配置,用于旧支付单回溯原商户密钥。
|
// FindByProviderMerchantPayWay 根据服务商、商户号和支付方式查配置,用于旧支付单回溯原商户密钥。
|
||||||
func (r *Repository) FindByProviderMerchantPayWay(ctx context.Context, provider string, merchantID string, payWay string, includeSecret bool) (*ConfigDTO, error) {
|
func (r *Repository) FindByProviderMerchantPayWay(ctx context.Context, provider string, merchantID string, payWay string, includeSecret bool) (*ConfigDTO, error) {
|
||||||
var item model.PaymentMerchantConfig
|
var item model.PaymentMerchantConfig
|
||||||
if err := r.db.WithContext(ctx).Where("provider = ? AND merchant_id = ? AND pay_way = ?", provider, merchantID, payWay).
|
if err := applyOwnerTenantScope(r.db.WithContext(ctx), ctx).
|
||||||
|
Where("provider = ? AND merchant_id = ? AND pay_way = ?", provider, merchantID, payWay).
|
||||||
Order("status = 'active' DESC, is_default DESC, id DESC").
|
Order("status = 'active' DESC, is_default DESC, id DESC").
|
||||||
First(&item).Error; err != nil {
|
First(&item).Error; err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
@@ -231,7 +234,8 @@ func (r *Repository) FindByProviderMerchantPayWay(ctx context.Context, provider
|
|||||||
// FindByProviderMerchant 根据服务商和商户号查配置,保留给历史数据没有支付方式时兜底使用。
|
// FindByProviderMerchant 根据服务商和商户号查配置,保留给历史数据没有支付方式时兜底使用。
|
||||||
func (r *Repository) FindByProviderMerchant(ctx context.Context, provider string, merchantID string, includeSecret bool) (*ConfigDTO, error) {
|
func (r *Repository) FindByProviderMerchant(ctx context.Context, provider string, merchantID string, includeSecret bool) (*ConfigDTO, error) {
|
||||||
var item model.PaymentMerchantConfig
|
var item model.PaymentMerchantConfig
|
||||||
if err := r.db.WithContext(ctx).Where("provider = ? AND merchant_id = ?", provider, merchantID).
|
if err := applyOwnerTenantScope(r.db.WithContext(ctx), ctx).
|
||||||
|
Where("provider = ? AND merchant_id = ?", provider, merchantID).
|
||||||
Order("status = 'active' DESC, is_default DESC, id DESC").
|
Order("status = 'active' DESC, is_default DESC, id DESC").
|
||||||
First(&item).Error; err != nil {
|
First(&item).Error; err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
@@ -249,10 +253,18 @@ func (r *Repository) FindByProviderMerchant(ctx context.Context, provider string
|
|||||||
// FindActiveByProvider 查询提供商的所有激活配置
|
// FindActiveByProvider 查询提供商的所有激活配置
|
||||||
func (r *Repository) FindActiveByProvider(ctx context.Context, provider string) ([]model.PaymentMerchantConfig, error) {
|
func (r *Repository) FindActiveByProvider(ctx context.Context, provider string) ([]model.PaymentMerchantConfig, error) {
|
||||||
var items []model.PaymentMerchantConfig
|
var items []model.PaymentMerchantConfig
|
||||||
if err := r.db.WithContext(ctx).Where("provider = ? AND status = ?", provider, "active").Order("is_default DESC, id DESC").Find(&items).Error; err != nil {
|
if err := applyOwnerTenantScope(r.db.WithContext(ctx), ctx).
|
||||||
|
Where("provider = ? AND status = ?", provider, "active").Order("is_default DESC, id DESC").Find(&items).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func applyOwnerTenantScope(db *gorm.DB, ctx context.Context) *gorm.DB {
|
||||||
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
|
return db.Where("owner_tenant_id = ?", tenantID)
|
||||||
|
}
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
// Create 创建配置
|
// Create 创建配置
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package paymentconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
)
|
||||||
|
|
||||||
|
func paymentConfigTenantContext(tenantID uint64) context.Context {
|
||||||
|
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPaymentConfigsAndDefaultsAreScopedByTenant(t *testing.T) {
|
||||||
|
db := database.NewTestDB()
|
||||||
|
repo := NewRepository(db, &MockEncryptor{})
|
||||||
|
dachuiCtx := paymentConfigTenantContext(101)
|
||||||
|
jieyouCtx := paymentConfigTenantContext(202)
|
||||||
|
|
||||||
|
dachuiConfig, err := repo.Create(dachuiCtx, CreateRequest{
|
||||||
|
Name: "大锤支付宝",
|
||||||
|
Provider: "mock",
|
||||||
|
MerchantID: "DACHUI-MOCK",
|
||||||
|
PayWay: "ZFBZF",
|
||||||
|
Status: "active",
|
||||||
|
}, 1, AuditMeta{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create dachui config: %v", err)
|
||||||
|
}
|
||||||
|
jieyouConfig, err := repo.Create(jieyouCtx, CreateRequest{
|
||||||
|
Name: "解忧支付宝",
|
||||||
|
Provider: "mock",
|
||||||
|
MerchantID: "JIEYOU-MOCK",
|
||||||
|
PayWay: "ZFBZF",
|
||||||
|
Status: "active",
|
||||||
|
}, 2, AuditMeta{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create jieyou config: %v", err)
|
||||||
|
}
|
||||||
|
if dachuiConfig.OwnerTenantID != 101 || jieyouConfig.OwnerTenantID != 202 {
|
||||||
|
t.Fatalf("config tenant ids = %d/%d", dachuiConfig.OwnerTenantID, jieyouConfig.OwnerTenantID)
|
||||||
|
}
|
||||||
|
|
||||||
|
dachuiDefault, err := repo.FindDefaultByPayWay(dachuiCtx, "ZFBZF", true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
jieyouDefault, err := repo.FindDefaultByPayWay(jieyouCtx, "ZFBZF", true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if dachuiDefault.ID != dachuiConfig.ID || jieyouDefault.ID != jieyouConfig.ID {
|
||||||
|
t.Fatalf("tenant defaults = %d/%d", dachuiDefault.ID, jieyouDefault.ID)
|
||||||
|
}
|
||||||
|
if dachuiDefault.MerchantID != "DACHUI-MOCK" || jieyouDefault.MerchantID != "JIEYOU-MOCK" {
|
||||||
|
t.Fatalf("tenant merchants = %s/%s", dachuiDefault.MerchantID, jieyouDefault.MerchantID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.FindByID(jieyouCtx, dachuiConfig.ID, false, 0, AuditMeta{}); !errors.Is(err, ErrConfigNotFound) {
|
||||||
|
t.Fatalf("cross-tenant config lookup error = %v", err)
|
||||||
|
}
|
||||||
|
items, total, err := repo.List(dachuiCtx, ListQuery{Page: 1, PageSize: 20})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if total != 1 || len(items) != 1 || items[0].ID != dachuiConfig.ID {
|
||||||
|
t.Fatalf("dachui config list = %+v, total=%d", items, total)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@ import (
|
|||||||
// IncrementUsage 增加使用统计
|
// IncrementUsage 增加使用统计
|
||||||
func (r *Repository) IncrementUsage(ctx context.Context, id uint64, amountCent int64) error {
|
func (r *Repository) IncrementUsage(ctx context.Context, id uint64, amountCent int64) error {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
return r.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{}).Where("id = ?", id).Updates(map[string]any{
|
return applyOwnerTenantScope(r.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{}), ctx).Where("id = ?", id).Updates(map[string]any{
|
||||||
"total_transactions": gorm.Expr("total_transactions + ?", 1),
|
"total_transactions": gorm.Expr("total_transactions + ?", 1),
|
||||||
"total_amount_cent": gorm.Expr("total_amount_cent + ?", amountCent),
|
"total_amount_cent": gorm.Expr("total_amount_cent + ?", amountCent),
|
||||||
"last_used_at": now,
|
"last_used_at": now,
|
||||||
@@ -23,7 +23,7 @@ func (r *Repository) IncrementUsage(ctx context.Context, id uint64, amountCent i
|
|||||||
// RecordUsage 记录支付配置命中情况,同一个支付单只记录一次。
|
// RecordUsage 记录支付配置命中情况,同一个支付单只记录一次。
|
||||||
|
|
||||||
// RecordUsage 记录支付配置命中情况,同一个支付单只记录一次。
|
// RecordUsage 记录支付配置命中情况,同一个支付单只记录一次。
|
||||||
func (r *Repository) RecordUsage(ctx context.Context, configID uint64, paymentOrderID uint64, provider string, merchantID string, amountCent int64, bizType string) error {
|
func (r *Repository) RecordUsage(ctx context.Context, tenantID uint64, configID uint64, paymentOrderID uint64, provider string, merchantID string, amountCent int64, bizType string) error {
|
||||||
if configID == 0 || paymentOrderID == 0 {
|
if configID == 0 || paymentOrderID == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -37,6 +37,7 @@ func (r *Repository) RecordUsage(ctx context.Context, configID uint64, paymentOr
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
log := model.PaymentConfigUsageLog{
|
log := model.PaymentConfigUsageLog{
|
||||||
|
TenantID: tenantID,
|
||||||
ConfigID: configID,
|
ConfigID: configID,
|
||||||
PaymentOrderID: paymentOrderID,
|
PaymentOrderID: paymentOrderID,
|
||||||
Provider: provider,
|
Provider: provider,
|
||||||
@@ -48,7 +49,9 @@ func (r *Repository) RecordUsage(ctx context.Context, configID uint64, paymentOr
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
return tx.Model(&model.PaymentMerchantConfig{}).Where("id = ?", configID).Updates(map[string]any{
|
return tx.Model(&model.PaymentMerchantConfig{}).
|
||||||
|
Where("id = ? AND owner_tenant_id = ?", configID, tenantID).
|
||||||
|
Updates(map[string]any{
|
||||||
"total_transactions": gorm.Expr("total_transactions + ?", 1),
|
"total_transactions": gorm.Expr("total_transactions + ?", 1),
|
||||||
"total_amount_cent": gorm.Expr("total_amount_cent + ?", amountCent),
|
"total_amount_cent": gorm.Expr("total_amount_cent + ?", amountCent),
|
||||||
"last_used_at": now,
|
"last_used_at": now,
|
||||||
|
|||||||
@@ -274,17 +274,19 @@ func resolveTenantID(db *gorm.DB, explicitTenantID uint64, userID uint64) uint64
|
|||||||
if explicitTenantID > 0 {
|
if explicitTenantID > 0 {
|
||||||
return explicitTenantID
|
return explicitTenantID
|
||||||
}
|
}
|
||||||
|
if userID > 0 {
|
||||||
|
var tenantID uint64
|
||||||
|
if err := db.Model(&model.User{}).Select("tenant_id").Where("id = ?", userID).Scan(&tenantID).Error; err == nil && tenantID > 0 {
|
||||||
|
return tenantID
|
||||||
|
}
|
||||||
|
}
|
||||||
if tenantID := tenantIDFromDB(db); tenantID > 0 {
|
if tenantID := tenantIDFromDB(db); tenantID > 0 {
|
||||||
return tenantID
|
return tenantID
|
||||||
}
|
}
|
||||||
if userID == 0 {
|
if userID == 0 {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
var tenantID uint64
|
|
||||||
if err := db.Model(&model.User{}).Select("tenant_id").Where("id = ?", userID).Scan(&tenantID).Error; err != nil {
|
|
||||||
return 0
|
return 0
|
||||||
}
|
|
||||||
return tenantID
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func tenantIDFromDB(db *gorm.DB) uint64 {
|
func tenantIDFromDB(db *gorm.DB) uint64 {
|
||||||
|
|||||||
@@ -67,3 +67,34 @@ func TestWalletAccountsAndLedgerAreScopedByTenant(t *testing.T) {
|
|||||||
t.Fatalf("tenant wallet accounts = %+v", accounts)
|
t.Fatalf("tenant wallet accounts = %+v", accounts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWalletCreditsUserTenantWhenRequestComesFromBuyerTenant(t *testing.T) {
|
||||||
|
db := database.NewTestDB()
|
||||||
|
owner := model.User{TenantID: 202, Phone: "13400000009", Status: "active"}
|
||||||
|
if err := db.Create(&owner).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
buyerCtx := walletTenantContext(101)
|
||||||
|
if err := db.WithContext(buyerCtx).Transaction(func(tx *gorm.DB) error {
|
||||||
|
return AppendEntries(tx, Entry{
|
||||||
|
UserID: owner.ID, Direction: "in", AmountCent: 800,
|
||||||
|
BalanceType: "available", BizType: "owner_income", BizNo: "RO-CROSS-TENANT",
|
||||||
|
})
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("credit cross-tenant owner wallet: %v", err)
|
||||||
|
}
|
||||||
|
var account model.WalletAccount
|
||||||
|
if err := db.Where("user_id = ?", owner.ID).First(&account).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if account.TenantID != 202 || account.AvailableBalanceCent != 800 {
|
||||||
|
t.Fatalf("owner wallet = %+v", account)
|
||||||
|
}
|
||||||
|
var ledger model.WalletLedger
|
||||||
|
if err := db.Where("user_id = ?", owner.ID).First(&ledger).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ledger.TenantID != 202 {
|
||||||
|
t.Fatalf("owner ledger tenant = %d, want 202", ledger.TenantID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
-- +goose Up
|
||||||
|
|
||||||
|
ALTER TABLE payment_merchant_configs
|
||||||
|
ADD COLUMN owner_tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||||
|
ADD KEY idx_payment_merchant_configs_owner (owner_tenant_id, pay_way, status);
|
||||||
|
|
||||||
|
UPDATE payment_merchant_configs
|
||||||
|
SET owner_tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
|
||||||
|
WHERE owner_tenant_id = 0;
|
||||||
|
|
||||||
|
ALTER TABLE payment_orders
|
||||||
|
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||||
|
ADD KEY idx_payment_orders_tenant_created (tenant_id, created_at);
|
||||||
|
|
||||||
|
UPDATE payment_orders p
|
||||||
|
JOIN rental_orders o ON o.id = p.order_id
|
||||||
|
SET p.tenant_id = o.payment_tenant_id
|
||||||
|
WHERE p.tenant_id = 0
|
||||||
|
AND o.payment_tenant_id > 0;
|
||||||
|
|
||||||
|
UPDATE payment_orders p
|
||||||
|
JOIN users u ON u.id = p.user_id
|
||||||
|
SET p.tenant_id = u.tenant_id
|
||||||
|
WHERE p.tenant_id = 0;
|
||||||
|
|
||||||
|
ALTER TABLE payment_config_usage_logs
|
||||||
|
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||||
|
ADD KEY idx_payment_config_usage_logs_tenant (tenant_id, created_at);
|
||||||
|
|
||||||
|
UPDATE payment_config_usage_logs l
|
||||||
|
JOIN payment_orders p ON p.id = l.payment_order_id
|
||||||
|
SET l.tenant_id = p.tenant_id
|
||||||
|
WHERE l.tenant_id = 0;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
|
||||||
|
ALTER TABLE payment_config_usage_logs
|
||||||
|
DROP KEY idx_payment_config_usage_logs_tenant,
|
||||||
|
DROP COLUMN tenant_id;
|
||||||
|
|
||||||
|
ALTER TABLE payment_orders
|
||||||
|
DROP KEY idx_payment_orders_tenant_created,
|
||||||
|
DROP COLUMN tenant_id;
|
||||||
|
|
||||||
|
ALTER TABLE payment_merchant_configs
|
||||||
|
DROP KEY idx_payment_merchant_configs_owner,
|
||||||
|
DROP COLUMN owner_tenant_id;
|
||||||
@@ -4,6 +4,7 @@ import type { ApiResponse, PaginatedResult } from '@/shared/types/types'
|
|||||||
|
|
||||||
export interface AdminPayment {
|
export interface AdminPayment {
|
||||||
id: number
|
id: number
|
||||||
|
tenant_id?: number
|
||||||
payment_no: string
|
payment_no: string
|
||||||
order_id: number
|
order_id: number
|
||||||
order_no: string
|
order_no: string
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { ApiResponse } from '@/shared/types/types'
|
|||||||
|
|
||||||
export interface PaymentConfig {
|
export interface PaymentConfig {
|
||||||
id: number
|
id: number
|
||||||
|
owner_tenant_id?: number
|
||||||
name: string
|
name: string
|
||||||
provider: string
|
provider: string
|
||||||
merchant_id: string
|
merchant_id: string
|
||||||
|
|||||||
@@ -252,6 +252,7 @@ export interface ProcessEvent {
|
|||||||
|
|
||||||
export interface PaymentOrder {
|
export interface PaymentOrder {
|
||||||
id: number
|
id: number
|
||||||
|
tenant_id?: number
|
||||||
payment_no: string
|
payment_no: string
|
||||||
order_id: number
|
order_id: number
|
||||||
order_no: string
|
order_no: string
|
||||||
|
|||||||
Reference in New Issue
Block a user