fix(tenant): 收紧双站后台边界并补齐货架管理
This commit is contained in:
@@ -21,10 +21,11 @@
|
||||
- 主站前台地址:`http://localhost:5189`
|
||||
- 主站后台地址:`http://localhost:5189/admin/login`(超级管理员默认 `admin` / `admin123456`)
|
||||
- 平台运营统计后台:`http://ops.localhost:5189/admin/login`(仅平台超级管理员,只读统计)
|
||||
- 解忧商行后台:`https://<TENANT_JIEYOU_DOMAIN>/<ADMIN_BASE_PATH>/login`
|
||||
- 分销管理后台:`http://localhost:5190`(在主站后台“分销站点”开通站点并配置分销操作员登录)
|
||||
- 分销专属前台:`http://localhost:5191`(独立端口隔离,支持 Host 域名与 X-Distribution-Site 头识别站点)
|
||||
|
||||
> 生产环境不使用上述端口:Caddy 按域名分流,分销管理后台固定为 `https://distribution.<CADDY_DOMAIN>`,平台运营统计后台固定为 `https://ops.<CADDY_DOMAIN>`(见 `deploy/caddy/Caddyfile`)。主站后台的「打开独立分销后台」与开通凭证通过构建期 `VITE_DISTRIBUTION_ADMIN_URL` 注入该地址;未配置时按当前主站域名推导。
|
||||
> 生产环境不使用上述端口:Caddy 按域名分流,主站和解忧商行后台分别通过各自经营域名进入,分销管理后台固定为 `https://distribution.<CADDY_DOMAIN>`,平台运营统计后台固定为 `https://ops.<CADDY_DOMAIN>`(见 `deploy/caddy/Caddyfile`)。主站后台的「打开独立分销后台」与开通凭证通过构建期 `VITE_DISTRIBUTION_ADMIN_URL` 注入该地址;未配置时按当前主站域名推导。
|
||||
|
||||
|
||||
如需拆分调试,可手动执行:
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/config"
|
||||
"hfb_sys/backend/internal/platformscope"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RequireKnownApplicationHost prevents unknown hosts from falling through to
|
||||
// legacy unscoped handlers when the application is reached without the Caddy
|
||||
// on-demand TLS guard.
|
||||
func RequireKnownApplicationHost(appEnv string) gin.HandlerFunc {
|
||||
if !config.IsProductionEnv(appEnv) {
|
||||
return func(c *gin.Context) { c.Next() }
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
if platformscope.IsScope(c.Request.Context()) ||
|
||||
tenancy.IDFromContext(c.Request.Context()) > 0 ||
|
||||
sitecode.HasDomainScope(c.Request.Context()) ||
|
||||
isInfrastructureOrCallbackPath(c.Request.URL.Path) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
response.Error(c, http.StatusNotFound, "site_not_found", "当前域名未配置站点")
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
|
||||
func isInfrastructureOrCallbackPath(path string) bool {
|
||||
switch path {
|
||||
case "/health", "/health/ready", "/api/health", "/api/site/check-domain":
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(path, "/api/payments/") && strings.HasSuffix(path, "/notify")
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestRequireKnownApplicationHostFailsClosedOnlyInProduction(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
newEngine := func(appEnv string) *gin.Engine {
|
||||
engine := gin.New()
|
||||
engine.Use(RequireKnownApplicationHost(appEnv))
|
||||
engine.GET("/api/listings", func(c *gin.Context) { c.Status(http.StatusOK) })
|
||||
engine.POST("/api/payments/leshua/notify", func(c *gin.Context) { c.Status(http.StatusOK) })
|
||||
return engine
|
||||
}
|
||||
|
||||
production := newEngine("production")
|
||||
req := httptest.NewRequest(http.MethodGet, "http://unknown.example.com/api/listings", nil)
|
||||
req.Host = "unknown.example.com"
|
||||
rec := httptest.NewRecorder()
|
||||
production.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("unknown production host status = %d, want 404", rec.Code)
|
||||
}
|
||||
|
||||
req = httptest.NewRequest(http.MethodPost, "http://callback.example.com/api/payments/leshua/notify", nil)
|
||||
req.Host = "callback.example.com"
|
||||
rec = httptest.NewRecorder()
|
||||
production.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("payment callback status = %d, want 200", rec.Code)
|
||||
}
|
||||
|
||||
req = httptest.NewRequest(http.MethodGet, "http://unknown.example.com/api/listings", nil)
|
||||
req.Host = "unknown.example.com"
|
||||
req = req.WithContext(tenancy.WithScope(req.Context(), tenancy.Scope{TenantID: 101}))
|
||||
rec = httptest.NewRecorder()
|
||||
production.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("known tenant status = %d, want 200", rec.Code)
|
||||
}
|
||||
|
||||
development := newEngine("development")
|
||||
req = httptest.NewRequest(http.MethodGet, "http://unknown.example.com/api/listings", nil)
|
||||
req.Host = "unknown.example.com"
|
||||
rec = httptest.NewRecorder()
|
||||
development.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("development unknown host status = %d, want 200", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,7 @@ func SiteDomainFallback(resolver SiteDomainResolver, logger *zap.Logger) gin.Han
|
||||
}
|
||||
if code := resolveSiteCodeByHost(c, resolver, cache, logger); code != "" {
|
||||
c.Request.Header.Set(sitecode.HeaderName, code)
|
||||
c.Request = c.Request.WithContext(sitecode.WithDomainScope(c.Request.Context()))
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
|
||||
userQuery := db.Model(&model.User{})
|
||||
if tenantID > 0 {
|
||||
userQuery = userQuery.Where("tenant_id = ?", tenantID)
|
||||
userQuery = userQuery.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := userQuery.Count(&metrics.TotalUsers).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -51,7 +51,8 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
}
|
||||
listingQuery := db.Model(&model.RentalListing{})
|
||||
if tenantID > 0 {
|
||||
listingQuery = listingQuery.Where("source_tenant_id = ?", tenantID)
|
||||
listingQuery = listingQuery.Where("source_tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)")
|
||||
}
|
||||
if err := listingQuery.Count(&metrics.TotalListings).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -72,7 +73,8 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
}
|
||||
ledgerQuery := db.Model(&model.WalletLedger{})
|
||||
if tenantID > 0 {
|
||||
ledgerQuery = ledgerQuery.Where("tenant_id = ?", tenantID)
|
||||
ledgerQuery = ledgerQuery.Where("tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)")
|
||||
}
|
||||
if err := ledgerQuery.
|
||||
Select("COALESCE(SUM(amount_cent), 0)").
|
||||
@@ -88,8 +90,9 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
disputeQuery = disputeQuery.Where(`EXISTS (
|
||||
SELECT 1 FROM rental_orders AS tenant_order
|
||||
WHERE tenant_order.id = d.order_id
|
||||
AND (tenant_order.buyer_tenant_id = ? OR tenant_order.source_tenant_id = ?)
|
||||
)`, tenantID, tenantID)
|
||||
AND tenant_order.buyer_tenant_id = ?
|
||||
AND (tenant_order.distribution_site_id IS NULL OR tenant_order.distribution_site_id = 0)
|
||||
)`, tenantID)
|
||||
}
|
||||
if err := disputeQuery.Where("d.status IN ?", []string{"open", "processing"}).Count(&pending.Disputes).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -159,6 +162,7 @@ func (r *Repository) tenantStats(ctx context.Context, tenantID uint64, metrics M
|
||||
}
|
||||
if err := db.Table("rental_orders AS o").
|
||||
Where("o.buyer_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
|
||||
Where(tradingOrderPaidCondition).
|
||||
Select("COUNT(*) AS buyer_order_count, COALESCE(SUM(o.rent_amount_cent), 0) AS buyer_gmv_cent").
|
||||
Scan(&buyerStats).Error; err != nil {
|
||||
@@ -172,6 +176,7 @@ func (r *Repository) tenantStats(ctx context.Context, tenantID uint64, metrics M
|
||||
}
|
||||
if err := db.Table("rental_orders AS o").
|
||||
Where("o.source_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
|
||||
Where(tradingOrderPaidCondition).
|
||||
Select("COUNT(*) AS source_order_count, COALESCE(SUM(o.source_amount_cent), 0) AS source_amount_cent").
|
||||
Scan(&sourceStats).Error; err != nil {
|
||||
@@ -186,7 +191,9 @@ func applyDashboardOrderScope(query *gorm.DB, tenantID uint64) *gorm.DB {
|
||||
if tenantID == 0 {
|
||||
return query
|
||||
}
|
||||
return query.Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID)
|
||||
return query.
|
||||
Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func (r *Repository) listingDailyOverview(ctx context.Context, now time.Time, days int) (ListingDailyOverviewDTO, error) {
|
||||
@@ -223,7 +230,8 @@ func (r *Repository) listingDailyOverview(ctx context.Context, now time.Time, da
|
||||
Where("e.created_at >= ? AND e.created_at < ?", start, end)
|
||||
if tenantID > 0 {
|
||||
eventQuery = eventQuery.Joins("JOIN rental_listings AS tenant_listing ON tenant_listing.id = e.listing_id").
|
||||
Where("tenant_listing.source_tenant_id = ?", tenantID)
|
||||
Where("tenant_listing.source_tenant_id = ?", tenantID).
|
||||
Where("(tenant_listing.distribution_site_id IS NULL OR tenant_listing.distribution_site_id = 0)")
|
||||
}
|
||||
if err := eventQuery.Scan(&events).Error; err != nil {
|
||||
return ListingDailyOverviewDTO{}, err
|
||||
@@ -232,7 +240,8 @@ func (r *Repository) listingDailyOverview(ctx context.Context, now time.Time, da
|
||||
uploadQuery := db.Table("listing_uploads AS lu")
|
||||
if tenantID > 0 {
|
||||
uploadQuery = uploadQuery.Joins("JOIN rental_listings AS tenant_listing ON tenant_listing.id = lu.listing_id").
|
||||
Where("tenant_listing.source_tenant_id = ?", tenantID)
|
||||
Where("tenant_listing.source_tenant_id = ?", tenantID).
|
||||
Where("(tenant_listing.distribution_site_id IS NULL OR tenant_listing.distribution_site_id = 0)")
|
||||
}
|
||||
if err := uploadQuery.
|
||||
Select("COALESCE(lu.matched_admin_id, 0) AS uploader_id, lu.uploader_name, lu.created_at").
|
||||
@@ -584,7 +593,11 @@ func (r *Repository) recentDisputes(ctx context.Context) ([]RecentDisputeDTO, er
|
||||
Select("d.id, d.order_id, o.order_no, a.title, d.type, d.status, d.initiator_id, d.created_at").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
|
||||
Joins("JOIN game_accounts AS a ON a.id = o.account_id")
|
||||
query = applyDashboardOrderScope(query, tenancy.IDFromContext(ctx))
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.
|
||||
Where("o.buyer_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
err := query.
|
||||
Order("d.id DESC").
|
||||
Limit(8).
|
||||
|
||||
@@ -411,7 +411,9 @@ func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) (
|
||||
Where("status NOT IN ?", nonBillableOrderStatuses()).
|
||||
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)
|
||||
orderQuery = orderQuery.
|
||||
Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)")
|
||||
}
|
||||
err := orderQuery.
|
||||
Group("DATE_FORMAT(created_at, '%Y-%m-%d')").
|
||||
@@ -480,7 +482,9 @@ func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery)
|
||||
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)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
settlementQuery = settlementQuery.Where("(ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)", tenantID, tenantID)
|
||||
settlementQuery = settlementQuery.
|
||||
Where("(ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(ro.distribution_site_id IS NULL OR ro.distribution_site_id = 0)")
|
||||
}
|
||||
err := settlementQuery.
|
||||
Group("DATE_FORMAT(ro.settled_at, '%Y-%m-%d')").
|
||||
@@ -566,7 +570,15 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([
|
||||
db := r.db.WithContext(ctx)
|
||||
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)
|
||||
paymentQuery = paymentQuery.
|
||||
Where("po.tenant_id = ?", tenantID).
|
||||
Where(`NOT EXISTS (
|
||||
SELECT 1 FROM rental_orders AS legacy_order
|
||||
WHERE legacy_order.id = po.order_id
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
AND po.biz_type IN ?
|
||||
)`, append([]string{"order_pay"}, refundBizTypes()...))
|
||||
}
|
||||
err := paymentQuery.
|
||||
Select(`DATE_FORMAT(po.created_at, '%Y-%m-%d') AS date,
|
||||
@@ -612,7 +624,13 @@ func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery)
|
||||
pickupTenantFilter := ""
|
||||
args := []any{query.StartDate, query.EndDate}
|
||||
if tenantID > 0 {
|
||||
paymentTenantFilter = " AND tenant_id = ?"
|
||||
paymentTenantFilter = ` AND tenant_id = ?
|
||||
AND (biz_type <> 'order_pay' OR NOT EXISTS (
|
||||
SELECT 1 FROM rental_orders AS legacy_order
|
||||
WHERE legacy_order.id = payment_orders.order_id
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
))`
|
||||
pickupTenantFilter = " AND 1 = 0"
|
||||
args = append(args, tenantID)
|
||||
}
|
||||
|
||||
@@ -129,7 +129,8 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
}
|
||||
withdrawalQuery := db.Table("withdrawal_requests")
|
||||
if tenantID > 0 {
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID)
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID).
|
||||
Where("distribution_site_id = 0")
|
||||
}
|
||||
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,
|
||||
@@ -232,7 +233,8 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
||||
withdrawalRows := make([]dailyDisbursementSourceRow, 0)
|
||||
withdrawalQuery := db.Table("withdrawal_requests")
|
||||
if tenantID > 0 {
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID)
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID).
|
||||
Where("distribution_site_id = 0")
|
||||
}
|
||||
if err := withdrawalQuery.
|
||||
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
||||
@@ -298,7 +300,9 @@ 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)
|
||||
return db.
|
||||
Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
type dailyDisbursementSourceRow struct {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"hfb_sys/backend/internal/modules/realname"
|
||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/crypto"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -74,6 +75,7 @@ func (r *Repository) List(ctx context.Context, page, pageSize int, query ListQue
|
||||
Joins("LEFT JOIN (SELECT renter_id AS user_id, SUM(deposit_waived_amount_cent) AS deposit_free_used_cent FROM rental_orders WHERE status NOT IN ('completed', 'cancelled', 'closed') GROUP BY renter_id) AS df ON df.user_id = u.id").
|
||||
Joins("LEFT JOIN wallet_accounts AS w ON w.user_id = u.id AND w.distribution_site_id = 0")
|
||||
listTx = applyUserFilter(listTx, query, growthConfig)
|
||||
listTx = applyUserContextScope(ctx, listTx, "u")
|
||||
err = listTx.
|
||||
Order("u.id DESC").
|
||||
Offset(offset).Limit(pageSize).
|
||||
@@ -89,6 +91,7 @@ func (r *Repository) List(ctx context.Context, page, pageSize int, query ListQue
|
||||
} else {
|
||||
countTx := applyUserFilter(r.db.WithContext(ctx).Table("users AS u").
|
||||
Joins("LEFT JOIN tenants AS t ON t.id = u.tenant_id"), query, growthConfig)
|
||||
countTx = applyUserContextScope(ctx, countTx, "u")
|
||||
if err := countTx.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -101,6 +104,28 @@ func (r *Repository) List(ctx context.Context, page, pageSize int, query ListQue
|
||||
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
|
||||
}
|
||||
|
||||
// applyUserContextScope 将经营站点后台固定到当前租户及其本站用户。
|
||||
// 历史分销用户虽回填到大锤租户,但仍通过 distribution_site_id 保留渠道归属。
|
||||
func applyUserContextScope(ctx context.Context, db *gorm.DB, alias string) *gorm.DB {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return db
|
||||
}
|
||||
column := "tenant_id"
|
||||
siteColumn := "distribution_site_id"
|
||||
if alias != "" {
|
||||
column = alias + "." + column
|
||||
siteColumn = alias + "." + siteColumn
|
||||
}
|
||||
return db.Where(column+" = ?", tenantID).Where(siteColumn + " = 0")
|
||||
}
|
||||
|
||||
func lockScopedUser(ctx context.Context, tx *gorm.DB, userID uint64, user *model.User) error {
|
||||
return applyUserContextScope(ctx, tx, "").
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
First(user, userID).Error
|
||||
}
|
||||
|
||||
// applyUserFilter 将列表筛选条件应用到查询(基于 users 表别名 u)。
|
||||
func applyUserFilter(tx *gorm.DB, query ListQuery, growthConfig rentergrowth.Config) *gorm.DB {
|
||||
if query.Status != "" {
|
||||
@@ -208,7 +233,7 @@ func (r *Repository) SetDepositFreeQuota(ctx context.Context, adminID uint64, us
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
beforeAmountCent := user.DepositFreeQuotaCent
|
||||
@@ -231,7 +256,7 @@ func (r *Repository) SetDepositFreeQuota(ctx context.Context, adminID uint64, us
|
||||
func (r *Repository) AdjustGrowthPoints(ctx context.Context, adminID uint64, userID uint64, req GrowthPointsAdjustRequest, meta AuditMeta) (*UserDTO, error) {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.RenterGrowthPoints == req.TargetPoints {
|
||||
@@ -298,7 +323,7 @@ func (r *Repository) AdjustGrowthPoints(ctx context.Context, adminID uint64, use
|
||||
func (r *Repository) AdjustGrowthLevel(ctx context.Context, adminID uint64, userID uint64, req GrowthLevelAdjustRequest, meta AuditMeta) (*UserDTO, error) {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := rentergrowth.ConfigForTx(tx)
|
||||
@@ -349,7 +374,7 @@ func (r *Repository) updateStatus(ctx context.Context, adminID uint64, userID ui
|
||||
statusChanged := false
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
beforeStatus := user.Status
|
||||
@@ -389,7 +414,7 @@ func (r *Repository) updateStatus(ctx context.Context, adminID uint64, userID ui
|
||||
func (r *Repository) RevokeRealname(ctx context.Context, adminID uint64, userID uint64, req RevokeRealnameRequest, meta AuditMeta) (*UserDTO, error) {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
var realnameCount int64
|
||||
@@ -457,7 +482,7 @@ func (r *Repository) ManualRealname(ctx context.Context, adminID uint64, userID
|
||||
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.RealnameStatus == "verified" {
|
||||
@@ -533,7 +558,7 @@ func (r *Repository) Find(ctx context.Context, userID uint64) (*UserDTO, error)
|
||||
return nil, err
|
||||
}
|
||||
var row userRow
|
||||
err = r.db.WithContext(ctx).Table("users AS u").
|
||||
query := r.db.WithContext(ctx).Table("users AS u").
|
||||
Select(`u.*, COALESCE(t.code, '') AS tenant_code, COALESCE(t.name, '') AS tenant_name,
|
||||
COALESCE(o.order_count, 0) AS order_count,
|
||||
COALESCE(l.listing_count, 0) AS listing_count,
|
||||
@@ -547,8 +572,9 @@ func (r *Repository) Find(ctx context.Context, userID uint64) (*UserDTO, error)
|
||||
Joins("LEFT JOIN (SELECT user_id, COUNT(*) AS dispute_count FROM (SELECT initiator_id AS user_id FROM disputes UNION ALL SELECT target_user_id AS user_id FROM disputes) AS dispute_users GROUP BY user_id) AS d ON d.user_id = u.id").
|
||||
Joins("LEFT JOIN (SELECT renter_id AS user_id, SUM(deposit_waived_amount_cent) AS deposit_free_used_cent FROM rental_orders WHERE status NOT IN ('completed', 'cancelled', 'closed') GROUP BY renter_id) AS df ON df.user_id = u.id").
|
||||
Joins("LEFT JOIN wallet_accounts AS w ON w.user_id = u.id AND w.distribution_site_id = 0").
|
||||
Where("u.id = ?", userID).
|
||||
First(&row).Error
|
||||
Where("u.id = ?", userID)
|
||||
query = applyUserContextScope(ctx, query, "u")
|
||||
err = query.First(&row).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -581,7 +607,7 @@ func (r *Repository) AdjustWallet(ctx context.Context, adminID uint64, userID ui
|
||||
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package adminuser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -8,10 +9,15 @@ import (
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func adminUserTenantContext(tenantID uint64) context.Context {
|
||||
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
|
||||
func TestDepositFreeQuotaAmountCent(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -578,6 +584,45 @@ func TestFreezeAndUnfreezeBumpUserTokenVersion(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserAdminIsScopedToCurrentTenantAndOperatingUsers(t *testing.T) {
|
||||
db := setupAdminUserTestDB(t)
|
||||
tenants := []model.Tenant{
|
||||
{ID: 101, Code: "tenant_a", Name: "A站", Status: "active"},
|
||||
{ID: 202, Code: "tenant_b", Name: "B站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
users := []model.User{
|
||||
{TenantID: 101, Phone: "13700000101", Status: "active"},
|
||||
{TenantID: 101, Phone: "13700000102", Status: "active", DistributionSiteID: 999},
|
||||
{TenantID: 202, Phone: "13700000201", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&users).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
ctx := adminUserTenantContext(101)
|
||||
|
||||
result, err := repo.List(ctx, 1, 20, ListQuery{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items := result.Items.([]UserDTO)
|
||||
if result.Total != 1 || len(items) != 1 || items[0].ID != users[0].ID {
|
||||
t.Fatalf("tenant user list = %+v", result)
|
||||
}
|
||||
if _, err := repo.Find(ctx, users[2].ID); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant user detail error = %v", err)
|
||||
}
|
||||
if _, err := repo.Freeze(ctx, 9, users[2].ID, FreezeRequest{Reason: "越权测试"}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant user freeze error = %v", err)
|
||||
}
|
||||
if _, err := repo.Find(ctx, users[1].ID); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("legacy distribution user detail error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func setupAdminUserTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
|
||||
@@ -38,6 +38,9 @@ func (r *Repository) Arbitrate(ctx context.Context, adminID uint64, id uint64, r
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&order, row.OrderID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if !currentTenantCanAdminDisputeOrder(ctx, order.BuyerTenantID, order.DistributionSiteID) {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
var listing model.RentalListing
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&listing, order.ListingID).Error; err != nil {
|
||||
return err
|
||||
|
||||
@@ -171,6 +171,9 @@ func (r *Repository) AdminCreateByOrder(ctx context.Context, adminID uint64, ord
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&order, orderID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if !currentTenantCanAdminDisputeOrder(ctx, order.BuyerTenantID, order.DistributionSiteID) {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
if order.Status == "completed" || order.Status == "cancelled" || order.Status == "closed" {
|
||||
return ErrInvalidDispute
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -48,7 +50,7 @@ func (r *Repository) ListAdmin(ctx context.Context, query AdminListQuery) (*Pagi
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
var rows []disputeRow
|
||||
err := applyAdminListFilters(r.baseQuery(ctx), query).
|
||||
err := applyAdminListFilters(r.adminScopedBaseQuery(ctx), query).
|
||||
Order("d.id DESC").
|
||||
Offset(offset).
|
||||
Limit(pageSize).
|
||||
@@ -72,7 +74,7 @@ func (r *Repository) ListAdmin(ctx context.Context, query AdminListQuery) (*Pagi
|
||||
|
||||
func (r *Repository) FindAdminByID(ctx context.Context, id uint64) (*DisputeDTO, error) {
|
||||
var row disputeRow
|
||||
if err := r.baseQuery(ctx).Where("d.id = ?", id).First(&row).Error; err != nil {
|
||||
if err := r.adminScopedBaseQuery(ctx).Where("d.id = ?", id).First(&row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dto := row.toDTO()
|
||||
@@ -105,6 +107,30 @@ func (r *Repository) baseQuery(ctx context.Context) *gorm.DB {
|
||||
CASE WHEN c.deposit_deduct_amount_cent > 0 THEN c.deposit_deduct_amount_cent ELSE c.other_amount_cent END AS checkout_deposit_deduct_amount_cent`)
|
||||
}
|
||||
|
||||
func (r *Repository) adminScopedBaseQuery(ctx context.Context) *gorm.DB {
|
||||
return applyAdminDisputeTenantScope(ctx, r.baseQuery(ctx))
|
||||
}
|
||||
|
||||
func applyAdminDisputeTenantScope(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return db
|
||||
}
|
||||
return db.Where("o.buyer_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func currentTenantCanAdminDisputeOrder(ctx context.Context, orderBuyerTenantID uint64, distributionSiteID *uint64) bool {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return true
|
||||
}
|
||||
if orderBuyerTenantID != tenantID {
|
||||
return false
|
||||
}
|
||||
return distributionSiteID == nil || *distributionSiteID == 0
|
||||
}
|
||||
|
||||
func (r *Repository) adminFilterQuery(ctx context.Context) *gorm.DB {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
|
||||
@@ -116,29 +142,7 @@ func (r *Repository) adminFilterQuery(ctx context.Context) *gorm.DB {
|
||||
}
|
||||
|
||||
func (r *Repository) adminDisputeCountQuery(ctx context.Context, query AdminListQuery) *gorm.DB {
|
||||
kw := strings.TrimSpace(query.Keyword)
|
||||
if kw == "" {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d")
|
||||
}
|
||||
upper := strings.ToUpper(kw)
|
||||
if id, err := strconv.ParseUint(kw, 10, 64); err == nil && id > 0 && kw[0] != '0' && id < 100000000 {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id")
|
||||
}
|
||||
if strings.HasPrefix(upper, "RO") || strings.HasPrefix(upper, "ORD") {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id")
|
||||
}
|
||||
if strings.HasPrefix(upper, "L") || (len(kw) >= 12 && isAllDigits(kw)) {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
|
||||
Joins("JOIN rental_listings AS l ON l.id = o.listing_id")
|
||||
}
|
||||
if isPhoneKeyword(kw) {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id")
|
||||
}
|
||||
return r.adminFilterQuery(ctx)
|
||||
return applyAdminDisputeTenantScope(ctx, r.adminFilterQuery(ctx))
|
||||
}
|
||||
|
||||
func applyAdminListFilters(db *gorm.DB, query AdminListQuery) *gorm.DB {
|
||||
|
||||
@@ -3,6 +3,7 @@ package dispute
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"hfb_sys/backend/internal/model"
|
||||
ordermodule "hfb_sys/backend/internal/modules/order"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
@@ -56,11 +58,15 @@ func setupDisputeTestDB(t *testing.T) *gorm.DB {
|
||||
|
||||
func createDisputeOrderFixture(t *testing.T, db *gorm.DB, order model.RentalOrder) (model.User, model.User, model.RentalOrder) {
|
||||
t.Helper()
|
||||
owner := model.User{Phone: "13800000001"}
|
||||
var userCount int64
|
||||
if err := db.Model(&model.User{}).Count(&userCount).Error; err != nil {
|
||||
t.Fatalf("统计用户失败: %v", err)
|
||||
}
|
||||
owner := model.User{Phone: fmt.Sprintf("138%08d", userCount*2+1)}
|
||||
if err := db.Create(&owner).Error; err != nil {
|
||||
t.Fatalf("创建号主失败: %v", err)
|
||||
}
|
||||
renter := model.User{Phone: "13800000002"}
|
||||
renter := model.User{Phone: fmt.Sprintf("138%08d", userCount*2+2)}
|
||||
if err := db.Create(&renter).Error; err != nil {
|
||||
t.Fatalf("创建租客失败: %v", err)
|
||||
}
|
||||
@@ -74,6 +80,7 @@ func createDisputeOrderFixture(t *testing.T, db *gorm.DB, order model.RentalOrde
|
||||
t.Fatalf("创建账号失败: %v", err)
|
||||
}
|
||||
listing := model.RentalListing{
|
||||
ListingNo: fmt.Sprintf("L-DISPUTE-%d", userCount/2+1),
|
||||
AccountID: account.ID,
|
||||
OwnerID: owner.ID,
|
||||
PriceCent: 1000,
|
||||
@@ -84,7 +91,9 @@ func createDisputeOrderFixture(t *testing.T, db *gorm.DB, order model.RentalOrde
|
||||
if err := db.Create(&listing).Error; err != nil {
|
||||
t.Fatalf("创建商品失败: %v", err)
|
||||
}
|
||||
order.OrderNo = "RO202606130001"
|
||||
if order.OrderNo == "" {
|
||||
order.OrderNo = "RO202606130001"
|
||||
}
|
||||
order.ListingID = listing.ID
|
||||
order.AccountID = account.ID
|
||||
order.OwnerID = owner.ID
|
||||
@@ -812,6 +821,53 @@ func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminDisputeQueriesAndActionsAreScopedByBuyerTenant(t *testing.T) {
|
||||
db := setupDisputeTestDB(t)
|
||||
tenantA := model.Tenant{ID: 101, Code: "tenant_a", Name: "A站", Status: "active"}
|
||||
tenantB := model.Tenant{ID: 202, Code: "tenant_b", Name: "B站", Status: "active"}
|
||||
if err := db.Create(&tenantA).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&tenantB).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _, orderA := createDisputeOrderFixture(t, db, model.RentalOrder{
|
||||
OrderNo: "RO-DISPUTE-TENANT-A", BuyerTenantID: 101, SourceTenantID: 202, Status: "renting",
|
||||
})
|
||||
_, _, orderB := createDisputeOrderFixture(t, db, model.RentalOrder{
|
||||
OrderNo: "RO-DISPUTE-TENANT-B", BuyerTenantID: 202, SourceTenantID: 101, Status: "renting",
|
||||
})
|
||||
disputes := []model.Dispute{
|
||||
{OrderID: orderA.ID, InitiatorID: orderA.RenterID, InitiatorType: "user", TargetUserID: orderA.OwnerID, Type: "cannot_login", Status: "open"},
|
||||
{OrderID: orderB.ID, InitiatorID: orderB.RenterID, InitiatorType: "user", TargetUserID: orderB.OwnerID, Type: "cannot_login", Status: "open"},
|
||||
}
|
||||
if err := db.Create(&disputes).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
repo := NewRepository(db)
|
||||
result, err := repo.ListAdmin(ctx, AdminListQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Total != 1 || result.Items[0].ID != disputes[0].ID {
|
||||
t.Fatalf("tenant dispute list = %+v", result)
|
||||
}
|
||||
if _, err := repo.FindAdminByID(ctx, disputes[1].ID); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant dispute detail error = %v", err)
|
||||
}
|
||||
if _, err := repo.AdminCreateByOrder(ctx, 9, orderB.ID, AdminCreateRequest{
|
||||
Type: "cannot_login", Description: "越权测试", TargetRole: "owner",
|
||||
}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant admin create error = %v", err)
|
||||
}
|
||||
if _, err := repo.Arbitrate(ctx, 9, disputes[1].ID, ArbitrateRequest{
|
||||
Result: "full_refund", Remark: "越权测试",
|
||||
}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant arbitrate error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStampOwnerIncomeSiteUsesListingSite(t *testing.T) {
|
||||
siteID := uint64(3)
|
||||
orderID := uint64(9)
|
||||
|
||||
@@ -324,7 +324,7 @@ func applyTenantOfferVisibility(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
return db.Joins(
|
||||
"INNER JOIN tenant_listing_offers AS tlo ON tlo.listing_id = l.id AND tlo.tenant_id = ? AND tlo.display_status = 'enabled'",
|
||||
tenantID,
|
||||
)
|
||||
).Where("(l.distribution_site_id IS NULL OR l.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func (r *Repository) applyTenantOfferPrices(ctx context.Context, items []ListingDTO) error {
|
||||
|
||||
@@ -266,10 +266,14 @@ func applyListingSourceTenantScope(ctx context.Context, query *gorm.DB, alias st
|
||||
return query
|
||||
}
|
||||
column := "source_tenant_id"
|
||||
distributionColumn := "distribution_site_id"
|
||||
if alias != "" {
|
||||
column = alias + "." + column
|
||||
distributionColumn = alias + "." + distributionColumn
|
||||
}
|
||||
return query.Where(column+" = ?", tenantID)
|
||||
return query.
|
||||
Where(column+" = ?", tenantID).
|
||||
Where("(" + distributionColumn + " IS NULL OR " + distributionColumn + " = 0)")
|
||||
}
|
||||
|
||||
func (r *Repository) findForReviewUpdate(ctx context.Context, tx *gorm.DB, listingID uint64) (*model.RentalListing, *model.GameAccount, error) {
|
||||
|
||||
@@ -18,7 +18,10 @@ func (r *Repository) FindTenantOffer(ctx context.Context, listingID uint64) (*Te
|
||||
return nil, ErrTenantRequired
|
||||
}
|
||||
var listing model.RentalListing
|
||||
if err := r.db.WithContext(ctx).Select("id, price_cent").First(&listing, listingID).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id, price_cent").
|
||||
Where("id = ? AND (distribution_site_id IS NULL OR distribution_site_id = 0)", listingID).
|
||||
First(&listing).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var offer model.TenantListingOffer
|
||||
@@ -50,7 +53,10 @@ func (r *Repository) UpdateTenantOffer(
|
||||
return nil, ErrInvalidPrice
|
||||
}
|
||||
var listing model.RentalListing
|
||||
if err := r.db.WithContext(ctx).Select("id, price_cent").First(&listing, listingID).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id, price_cent").
|
||||
Where("id = ? AND (distribution_site_id IS NULL OR distribution_site_id = 0)", listingID).
|
||||
First(&listing).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrListingNotFound
|
||||
}
|
||||
|
||||
@@ -29,6 +29,13 @@ func TestPublicListingUsesCurrentTenantOffer(t *testing.T) {
|
||||
if err := db.Create(&other).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacySite := model.DistributionSite{
|
||||
ID: 999, SiteCode: "legacy_listing_offer", SiteName: "历史分销测试站",
|
||||
Domain: "legacy-listing-offer.example.com", Status: "active",
|
||||
}
|
||||
if err := db.Create(&legacySite).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner := model.User{TenantID: dachui.ID, Phone: "13100000001", Status: "active"}
|
||||
if err := db.Create(&owner).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -57,6 +64,20 @@ func TestPublicListingUsesCurrentTenantOffer(t *testing.T) {
|
||||
if err := db.Create(&offers).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacySiteID := legacySite.ID
|
||||
legacyListing := model.RentalListing{
|
||||
SourceTenantID: dachui.ID, ListingNo: "L-LEGACY-DIST",
|
||||
AccountID: account.ID, OwnerID: owner.ID, PriceCent: 9000,
|
||||
Status: "published", ReviewStatus: "approved", DistributionSiteID: &legacySiteID,
|
||||
}
|
||||
if err := db.Create(&legacyListing).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.TenantListingOffer{
|
||||
TenantID: jieyou.ID, ListingID: legacyListing.ID, DisplayStatus: "enabled",
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db, nil)
|
||||
|
||||
dachuiResult, err := repo.ListPublic(listingTenantContext(dachui.ID), PublicListQuery{})
|
||||
|
||||
@@ -44,6 +44,9 @@ func (r *Repository) Create(ctx context.Context, renterID uint64, req CreateRequ
|
||||
if requestTenantID > 0 && renter.TenantID != requestTenantID {
|
||||
return ErrPermissionDenied
|
||||
}
|
||||
if requestTenantID > 0 && listing.DistributionSiteID != nil && *listing.DistributionSiteID > 0 {
|
||||
return ErrListingUnavailable
|
||||
}
|
||||
buyerTenantID := renter.TenantID
|
||||
if requestTenantID > 0 {
|
||||
buyerTenantID = requestTenantID
|
||||
|
||||
@@ -546,7 +546,9 @@ func applyTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB {
|
||||
if tenantID == 0 {
|
||||
return query
|
||||
}
|
||||
return query.Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID)
|
||||
return query.
|
||||
Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func applyBuyerTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB {
|
||||
@@ -554,7 +556,9 @@ func applyBuyerTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB {
|
||||
if tenantID == 0 {
|
||||
return query
|
||||
}
|
||||
return query.Where("o.buyer_tenant_id = ?", tenantID)
|
||||
return query.
|
||||
Where("o.buyer_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func tenantOrderRole(ctx context.Context, order model.RentalOrder) string {
|
||||
|
||||
@@ -229,7 +229,7 @@ func (s *Service) AdminClose(ctx context.Context, adminID uint64, orderID uint64
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrOrderCannotComplete
|
||||
}
|
||||
if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil {
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminClose(ctx, adminID, orderID, req, meta)
|
||||
@@ -255,7 +255,7 @@ func (s *Service) AdminSeal(ctx context.Context, adminID uint64, orderID uint64,
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrOrderCannotComplete
|
||||
}
|
||||
if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil {
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminSeal(ctx, adminID, orderID, req, meta)
|
||||
|
||||
@@ -180,6 +180,13 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacySite := model.DistributionSite{
|
||||
ID: 999, SiteCode: "legacy_ops_test", SiteName: "历史分销测试站",
|
||||
Domain: "legacy-ops-test.example.com", Status: "active",
|
||||
}
|
||||
if err := db.Create(&legacySite).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner := model.User{TenantID: 101, Phone: "13000000101", Status: "active"}
|
||||
renterB := model.User{TenantID: 202, Phone: "13000000202", Status: "active"}
|
||||
renterA := model.User{TenantID: 101, Phone: "13000000102", Status: "active"}
|
||||
@@ -234,6 +241,13 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
|
||||
SourceTenantID: 303, PaymentTenantID: 101, Status: orderStatusRenting,
|
||||
},
|
||||
}
|
||||
legacySiteID := legacySite.ID
|
||||
orders = append(orders, model.RentalOrder{
|
||||
OrderNo: "RO-LEGACY-DISTRIBUTION", ListingID: listingA.ID, AccountID: accountA.ID,
|
||||
OwnerID: owner.ID, RenterID: renterA.ID, BuyerTenantID: 101,
|
||||
SourceTenantID: 101, PaymentTenantID: 101, DistributionSiteID: &legacySiteID,
|
||||
Status: orderStatusRenting,
|
||||
})
|
||||
if err := db.Create(&orders).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -268,6 +282,12 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
|
||||
if err := repo.EnsureAdminOrderCapability(orderTenantContext(202), orders[0].ID, tenantOrderCapabilityHandoff); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("buyer tenant handoff capability error = %v", err)
|
||||
}
|
||||
if err := service.AdminClose(orderTenantContext(101), 9, orders[0].ID, AdminActionRequest{Reason: "source close"}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("source tenant close capability error = %v", err)
|
||||
}
|
||||
if err := service.AdminSeal(orderTenantContext(101), 9, orders[0].ID, AdminActionRequest{Reason: "source seal"}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("source tenant seal capability error = %v", err)
|
||||
}
|
||||
|
||||
sourceResult, err := repo.ListAdmin(orderTenantContext(101), AdminOrderQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
|
||||
@@ -21,12 +21,13 @@ func (r *Repository) EnsureAdminOrderCapability(ctx context.Context, orderID uin
|
||||
return nil
|
||||
}
|
||||
var order struct {
|
||||
BuyerTenantID uint64
|
||||
SourceTenantID uint64
|
||||
BuyerTenantID uint64
|
||||
SourceTenantID uint64
|
||||
DistributionSiteID *uint64
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("rental_orders").
|
||||
Select("buyer_tenant_id, source_tenant_id").
|
||||
Select("buyer_tenant_id, source_tenant_id, distribution_site_id").
|
||||
Where("id = ?", orderID).
|
||||
Scan(&order).Error; err != nil {
|
||||
return err
|
||||
@@ -34,6 +35,9 @@ func (r *Repository) EnsureAdminOrderCapability(ctx context.Context, orderID uin
|
||||
if order.BuyerTenantID == 0 && order.SourceTenantID == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
if order.DistributionSiteID != nil && *order.DistributionSiteID > 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
isBuyer := order.BuyerTenantID == tenantID
|
||||
isSource := order.SourceTenantID == tenantID
|
||||
if !isBuyer && !isSource {
|
||||
|
||||
@@ -54,8 +54,26 @@ func (r *Repository) AdminList(ctx context.Context, query AdminPaymentQuery) (*P
|
||||
Joins("LEFT JOIN users AS u ON u.id = p.user_id")
|
||||
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)
|
||||
legacyDistributionCondition := `NOT EXISTS (
|
||||
SELECT 1 FROM rental_orders AS legacy_order
|
||||
WHERE legacy_order.id = p.order_id
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
AND p.biz_type IN ?
|
||||
)`
|
||||
orderBizTypes := append([]string{"order_pay"}, RefundBizTypes()...)
|
||||
db = db.Where("p.tenant_id = ?", tenantID).
|
||||
Where(legacyDistributionCondition, orderBizTypes)
|
||||
countDB = countDB.Where("tenant_id = ?", tenantID).Where(
|
||||
`NOT EXISTS (
|
||||
SELECT 1 FROM rental_orders AS legacy_order
|
||||
WHERE legacy_order.id = payment_orders.order_id
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
AND payment_orders.biz_type IN ?
|
||||
)`,
|
||||
orderBizTypes,
|
||||
)
|
||||
}
|
||||
if query.UserID > 0 {
|
||||
db = db.Where("p.user_id = ?", query.UserID)
|
||||
|
||||
@@ -65,6 +65,7 @@ func (r *Repository) Overview(ctx context.Context) (*OverviewDTO, error) {
|
||||
func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
|
||||
result := &TotalsDTO{}
|
||||
if err := db.Table("users").
|
||||
Where("distribution_site_id = 0").
|
||||
Select("COUNT(*) AS user_count, COALESCE(SUM(realname_status = 'verified'), 0) AS verified_users, COALESCE(SUM(created_at >= ?), 0) AS today_new_users", today).
|
||||
Row().
|
||||
Scan(&result.UserCount, &result.VerifiedUsers, &result.TodayNewUsers); err != nil {
|
||||
@@ -72,6 +73,7 @@ func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
|
||||
}
|
||||
|
||||
if err := db.Table("rental_listings").
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)").
|
||||
Select(`COUNT(*) AS total_listings,
|
||||
COALESCE(SUM(status = 'published' AND review_status = 'approved'), 0) AS published_listings,
|
||||
COALESCE(SUM(created_at >= ?), 0) AS today_new_listings,
|
||||
@@ -89,6 +91,7 @@ func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
|
||||
TodayGMVCent int64 `gorm:"column:today_gmv_cent"`
|
||||
}
|
||||
if err := db.Table("rental_orders AS o").
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
|
||||
Select(`COUNT(*) AS total_orders,
|
||||
COALESCE(SUM(o.`+paidOrderCondition+`), 0) AS paid_orders,
|
||||
COALESCE(SUM(o.status = 'renting'), 0) AS renting_orders,
|
||||
@@ -104,20 +107,27 @@ func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
|
||||
result.TodayOrders = orderStats.TodayOrders
|
||||
result.PaidGMVCent = orderStats.PaidGMVCent
|
||||
result.TodayGMVCent = orderStats.TodayGMVCent
|
||||
if err := db.Table("disputes AS d").Where("d.status IN ?", []string{"open", "processing"}).Count(&result.PendingDisputes).Error; err != nil {
|
||||
if err := db.Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
|
||||
Where("d.status IN ?", []string{"open", "processing"}).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
|
||||
Count(&result.PendingDisputes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := db.Table("rental_orders AS o").
|
||||
Where("o.status = ? AND o.handoff_status IN ?", "pending_handoff", []string{"pending_owner", "pending_renter_confirm"}).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
|
||||
Count(&result.PendingHandoffs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := db.Table("rental_orders AS o").
|
||||
Where("o.status IN ?", []string{"pending_checkout_confirm", "pending_checkout_accept"}).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
|
||||
Count(&result.PendingReturns).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := db.Table("wallet_ledger").
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)").
|
||||
Select(`COALESCE(SUM(CASE WHEN direction = 'in' THEN amount_cent ELSE 0 END), 0) AS wallet_inflow_cent,
|
||||
COALESCE(SUM(CASE WHEN direction = 'out' THEN amount_cent ELSE 0 END), 0) AS wallet_outflow_cent,
|
||||
COALESCE(SUM(CASE WHEN direction = 'in' AND created_at >= ? THEN amount_cent ELSE 0 END), 0) AS today_wallet_inflow_cent,
|
||||
@@ -128,6 +138,7 @@ func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
|
||||
}
|
||||
if err := db.Table("withdrawal_requests").
|
||||
Where("status IN ?", []string{"pending", "processing"}).
|
||||
Where("distribution_site_id = 0").
|
||||
Count(&result.PendingWithdrawals).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -141,14 +152,16 @@ func (r *Repository) siteStats(db *gorm.DB, tenant model.Tenant, today time.Time
|
||||
TenantName: tenant.Name,
|
||||
Status: tenant.Status,
|
||||
}
|
||||
if err := db.Table("users").Where("tenant_id = ?", tenant.ID).
|
||||
if err := db.Table("users").Where("tenant_id = ? AND distribution_site_id = 0", tenant.ID).
|
||||
Select("COUNT(*) AS user_count, COALESCE(SUM(realname_status = 'verified'), 0) AS verified_users, COALESCE(SUM(created_at >= ?), 0) AS today_new_users", today).
|
||||
Row().
|
||||
Scan(&result.UserCount, &result.VerifiedUsers, &result.TodayNewUsers); err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
if err := db.Table("rental_listings").Where("source_tenant_id = ?", tenant.ID).
|
||||
if err := db.Table("rental_listings").
|
||||
Where("source_tenant_id = ?", tenant.ID).
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)").
|
||||
Select(`COUNT(*) AS total_listings,
|
||||
COALESCE(SUM(status = 'published' AND review_status = 'approved'), 0) AS published_listings,
|
||||
COALESCE(SUM(created_at >= ?), 0) AS today_new_listings,
|
||||
@@ -167,6 +180,7 @@ func (r *Repository) siteStats(db *gorm.DB, tenant model.Tenant, today time.Time
|
||||
TodayGMVCent int64 `gorm:"column:today_gmv_cent"`
|
||||
}
|
||||
if err := db.Table("rental_orders AS o").
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
|
||||
Select(`COALESCE(SUM(o.buyer_tenant_id = ? AND o.`+paidOrderCondition+`), 0) AS buyer_orders,
|
||||
COALESCE(SUM(CASE WHEN o.buyer_tenant_id = ? AND o.`+paidOrderCondition+` THEN o.rent_amount_cent ELSE 0 END), 0) AS buyer_gmv_cent,
|
||||
COALESCE(SUM(o.source_tenant_id = ? AND o.`+paidOrderCondition+`), 0) AS source_orders,
|
||||
@@ -185,7 +199,9 @@ func (r *Repository) siteStats(db *gorm.DB, tenant model.Tenant, today time.Time
|
||||
result.RentingOrders = orderStats.RentingOrders
|
||||
result.TodayOrders = orderStats.TodayOrders
|
||||
result.TodayGMVCent = orderStats.TodayGMVCent
|
||||
if err := db.Table("wallet_ledger").Where("tenant_id = ?", tenant.ID).
|
||||
if err := db.Table("wallet_ledger").
|
||||
Where("tenant_id = ?", tenant.ID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)").
|
||||
Select(`COALESCE(SUM(CASE WHEN direction = 'in' THEN amount_cent ELSE 0 END), 0) AS wallet_inflow_cent,
|
||||
COALESCE(SUM(CASE WHEN direction = 'out' THEN amount_cent ELSE 0 END), 0) AS wallet_outflow_cent,
|
||||
COALESCE(SUM(CASE WHEN direction = 'in' AND created_at >= ? THEN amount_cent ELSE 0 END), 0) AS today_wallet_inflow_cent,
|
||||
@@ -194,7 +210,9 @@ func (r *Repository) siteStats(db *gorm.DB, tenant model.Tenant, today time.Time
|
||||
Scan(&result.WalletInflowCent, &result.WalletOutflowCent, &result.TodayWalletInflowCent, &result.TodayWalletOutflowCent); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := db.Table("withdrawal_requests").Where("tenant_id = ?", tenant.ID).
|
||||
if err := db.Table("withdrawal_requests").
|
||||
Where("tenant_id = ?", tenant.ID).
|
||||
Where("distribution_site_id = 0").
|
||||
Where("status IN ?", []string{"pending", "processing"}).
|
||||
Count(&result.PendingWithdrawals).Error; err != nil {
|
||||
return result, err
|
||||
@@ -218,6 +236,7 @@ func (r *Repository) trend(db *gorm.DB, now time.Time, days int) ([]TrendPointDT
|
||||
var userRows []row
|
||||
if err := db.Table("users").
|
||||
Select("DATE(created_at) AS date, COUNT(*) AS value").
|
||||
Where("distribution_site_id = 0").
|
||||
Where("created_at >= ? AND created_at < ?", start, end).
|
||||
Group("DATE(created_at)").Scan(&userRows).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -230,6 +249,7 @@ func (r *Repository) trend(db *gorm.DB, now time.Time, days int) ([]TrendPointDT
|
||||
var listingRows []row
|
||||
if err := db.Table("rental_listings").
|
||||
Select("DATE(created_at) AS date, COUNT(*) AS value").
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)").
|
||||
Where("created_at >= ? AND created_at < ?", start, end).
|
||||
Group("DATE(created_at)").Scan(&listingRows).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -244,6 +264,7 @@ func (r *Repository) trend(db *gorm.DB, now time.Time, days int) ([]TrendPointDT
|
||||
Select(`DATE(created_at) AS date,
|
||||
COALESCE(SUM(`+paidOrderCondition+`), 0) AS value,
|
||||
COALESCE(SUM(CASE WHEN `+paidOrderCondition+` THEN rent_amount_cent ELSE 0 END), 0) AS amount_cent`).
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)").
|
||||
Where("created_at >= ? AND created_at < ?", start, end).
|
||||
Group("DATE(created_at)").Scan(&orderRows).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -258,6 +279,7 @@ func (r *Repository) trend(db *gorm.DB, now time.Time, days int) ([]TrendPointDT
|
||||
Select(`DATE(created_at) AS date,
|
||||
COALESCE(SUM(CASE WHEN direction = 'in' THEN amount_cent ELSE 0 END), 0) AS inflow_cent,
|
||||
COALESCE(SUM(CASE WHEN direction = 'out' THEN amount_cent ELSE 0 END), 0) AS outflow_cent`).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)").
|
||||
Where("created_at >= ? AND created_at < ?", start, end).
|
||||
Group("DATE(created_at)").Scan(&walletRows).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -97,8 +97,64 @@ func TestOverviewAggregatesAllTenantsAndSites(t *testing.T) {
|
||||
if err := db.Create(&withdrawals).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacySite := model.DistributionSite{
|
||||
SiteCode: "legacy_platform_ops", SiteName: "历史分销测试站",
|
||||
Domain: "legacy-platform-ops.example.com", Status: "active",
|
||||
}
|
||||
if err := db.Create(&legacySite).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyUser := model.User{
|
||||
TenantID: tenants[0].ID, Phone: "13100000999", Status: "active",
|
||||
DistributionSiteID: legacySite.ID,
|
||||
}
|
||||
if err := db.Create(&legacyUser).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyAccount := model.GameAccount{
|
||||
SourceTenantID: tenants[0].ID, OwnerID: legacyUser.ID,
|
||||
GameName: "delta_force", ServerRegion: "国服", LoginPlatform: "QQ",
|
||||
Title: "历史分销商品", Status: "published",
|
||||
}
|
||||
if err := db.Create(&legacyAccount).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyListing := model.RentalListing{
|
||||
SourceTenantID: tenants[0].ID, ListingNo: "OPS-LEGACY-DIST",
|
||||
AccountID: legacyAccount.ID, OwnerID: legacyUser.ID,
|
||||
Status: "published", ReviewStatus: "approved", PriceCent: 5000,
|
||||
DistributionSiteID: &legacySite.ID,
|
||||
}
|
||||
if err := db.Create(&legacyListing).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyOrder := model.RentalOrder{
|
||||
OrderNo: "OPS-LEGACY-ORDER", BuyerTenantID: tenants[0].ID,
|
||||
SourceTenantID: tenants[0].ID, PaymentTenantID: tenants[0].ID,
|
||||
ListingID: legacyListing.ID, AccountID: legacyAccount.ID,
|
||||
OwnerID: legacyUser.ID, RenterID: legacyUser.ID,
|
||||
Status: "completed", RentAmountCent: 5000, SourceAmountCent: 4000,
|
||||
DistributionSiteID: &legacySite.ID,
|
||||
}
|
||||
if err := db.Create(&legacyOrder).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.WalletLedger{
|
||||
LedgerNo: "OPS-LEGACY-WL", TenantID: tenants[0].ID, UserID: legacyUser.ID,
|
||||
DistributionSiteID: legacySite.ID, Direction: "in", AmountCent: 5000,
|
||||
BalanceType: "available", BizType: "owner_income", BizNo: legacyOrder.OrderNo,
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.WithdrawalRequest{
|
||||
WithdrawNo: "OPS-LEGACY-WD", TenantID: tenants[0].ID, UserID: legacyUser.ID,
|
||||
DistributionSiteID: legacySite.ID, AmountCent: 500, ActualAmountCent: 500,
|
||||
AccountType: "bank", AccountName: "历史站用户", AccountNo: "****9999", Status: "pending",
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var userCount int64
|
||||
if err := db.Model(&model.User{}).Count(&userCount).Error; err != nil || userCount != 4 {
|
||||
if err := db.Model(&model.User{}).Count(&userCount).Error; err != nil || userCount != 5 {
|
||||
t.Fatalf("seeded users = %d, err=%v", userCount, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -80,13 +80,15 @@ func (r *Repository) Status(ctx context.Context, userID uint64) (*StatusDTO, err
|
||||
return nil, err
|
||||
}
|
||||
var user model.User
|
||||
if err := r.db.WithContext(ctx).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, r.db.WithContext(ctx), userID, false, &user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var account model.WalletAccount
|
||||
walletErr := r.db.WithContext(ctx).
|
||||
Where("user_id = ? AND distribution_site_id = 0", userID).
|
||||
First(&account).Error
|
||||
accountQuery := r.db.WithContext(ctx).Where("user_id = ? AND distribution_site_id = 0", userID)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
accountQuery = accountQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
walletErr := accountQuery.First(&account).Error
|
||||
if walletErr != nil && !errors.Is(walletErr, gorm.ErrRecordNotFound) {
|
||||
return nil, walletErr
|
||||
}
|
||||
@@ -107,7 +109,7 @@ func (r *Repository) PaymentAmount(ctx context.Context, userID uint64) (int64, b
|
||||
return 0, false, ErrInvalidUser
|
||||
}
|
||||
var user model.User
|
||||
if err := r.db.WithContext(ctx).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, r.db.WithContext(ctx), userID, false, &user); err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if user.QualityOwnerStatus == StatusActive {
|
||||
@@ -130,8 +132,12 @@ func (r *Repository) ConfirmQualityOwnerDepositPaidTx(tx *gorm.DB, userID uint64
|
||||
if tx == nil || userID == 0 || amountCent <= 0 || paymentNo == "" {
|
||||
return ErrInvalidUser
|
||||
}
|
||||
ctx := tx.Statement.Context
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, tx, userID, true, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
var appliedCount int64
|
||||
@@ -208,7 +214,7 @@ func (r *Repository) Activate(ctx context.Context, userID uint64) (*StatusDTO, e
|
||||
}
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, tx, userID, true, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.RealnameStatus != "verified" {
|
||||
@@ -303,7 +309,7 @@ func (r *Repository) Cancel(ctx context.Context, userID uint64, meta AuditMeta)
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, tx, userID, true, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.QualityOwnerStatus != StatusActive {
|
||||
@@ -358,7 +364,7 @@ func (r *Repository) AdminSet(ctx context.Context, adminID uint64, userID uint64
|
||||
}
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, tx, userID, true, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
beforeStatus := user.QualityOwnerStatus
|
||||
@@ -414,6 +420,17 @@ func (r *Repository) AdminSet(ctx context.Context, adminID uint64, userID uint64
|
||||
return r.Status(ctx, userID)
|
||||
}
|
||||
|
||||
func loadQualityOwnerUser(ctx context.Context, db *gorm.DB, userID uint64, lock bool, user *model.User) error {
|
||||
query := db.Model(&model.User{})
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if lock {
|
||||
query = query.Clauses(clause.Locking{Strength: "UPDATE"})
|
||||
}
|
||||
return query.First(user, userID).Error
|
||||
}
|
||||
|
||||
func activePremiumListingCount(db *gorm.DB, userID uint64) (int64, error) {
|
||||
var count int64
|
||||
err := db.Model(&model.RentalListing{}).
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package qualityowner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestAdminSetRejectsCrossTenantUser(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenants := []model.Tenant{
|
||||
{ID: 101, Code: "quality_tenant_a", Name: "A站", Status: "active"},
|
||||
{ID: 202, Code: "quality_tenant_b", Name: "B站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := model.User{TenantID: 202, Phone: "13600000202", Status: "active"}
|
||||
if err := db.Create(&user).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
repo := NewRepository(db)
|
||||
if _, err := repo.AdminSet(ctx, 9, user.ID, AdminSetRequest{
|
||||
Enabled: true,
|
||||
Reason: "跨站越权测试",
|
||||
}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant quality owner error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -166,8 +166,10 @@ func (r *Repository) AdminLedger(ctx context.Context, query AdminLedgerQuery) (*
|
||||
|
||||
countDB := r.db.WithContext(ctx).Model(&model.WalletLedger{})
|
||||
if tenantID > 0 {
|
||||
db = db.Where("wl.tenant_id = ?", tenantID)
|
||||
countDB = countDB.Where("tenant_id = ?", tenantID)
|
||||
db = db.Where("wl.tenant_id = ?", tenantID).
|
||||
Where("(wl.distribution_site_id = 0 OR wl.distribution_site_id IS NULL)")
|
||||
countDB = countDB.Where("tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)")
|
||||
}
|
||||
if query.UserID > 0 {
|
||||
db = db.Where("wl.user_id = ?", query.UserID)
|
||||
|
||||
@@ -18,7 +18,8 @@ import (
|
||||
func (r *Repository) AdminList(ctx context.Context, query AdminListQuery) (*AdminPaginatedResult, error) {
|
||||
db := r.db.WithContext(ctx).Model(&model.WithdrawalRequest{})
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
db = db.Where("tenant_id = ?", tenantID)
|
||||
db = db.Where("tenant_id = ?", tenantID).
|
||||
Where("distribution_site_id = 0")
|
||||
}
|
||||
|
||||
if query.Status != "" {
|
||||
|
||||
@@ -371,6 +371,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
if distributionRepo != nil {
|
||||
engine.Use(middleware.SiteDomainFallback(distributionRepo, logger))
|
||||
}
|
||||
engine.Use(middleware.RequireKnownApplicationHost(cfg.AppEnv))
|
||||
engine.Use(middleware.BlockTenantLegacyDistributionAdmin())
|
||||
engine.Use(middleware.PlatformOpsReadOnlyGuard())
|
||||
distributionHandler := distribution.NewHandler(distributionService)
|
||||
|
||||
@@ -26,6 +26,7 @@ const HeaderName = "X-Distribution-Site-Code"
|
||||
const LegacyHeaderName = "X-Site-Code"
|
||||
|
||||
type tenantScopeContextKey struct{}
|
||||
type domainScopeContextKey struct{}
|
||||
|
||||
// WithTenantScope 标记当前请求已识别为经营租户。
|
||||
// 经营租户与历史分销站点使用不同归属模型,识别成功后必须忽略旧分销站点编码。
|
||||
@@ -39,6 +40,16 @@ func HasTenantScope(ctx context.Context) bool {
|
||||
return enabled
|
||||
}
|
||||
|
||||
// WithDomainScope 标记当前 Host 已通过历史分销站点域名解析。
|
||||
func WithDomainScope(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, domainScopeContextKey{}, true)
|
||||
}
|
||||
|
||||
func HasDomainScope(ctx context.Context) bool {
|
||||
enabled, _ := ctx.Value(domainScopeContextKey{}).(bool)
|
||||
return enabled
|
||||
}
|
||||
|
||||
// FromRequest 按权威优先级解析站点编码:
|
||||
// X-Distribution-Site-Code 头 → X-Site-Code 旧头 → distribution_site_code / site_code query。
|
||||
// 所有来源均做 TrimSpace,返回空串表示主站。经营租户请求始终返回空串,
|
||||
|
||||
+2
-1
@@ -29,6 +29,7 @@ cp backend/.env.prod.example backend/.env
|
||||
```text
|
||||
CADDY_DOMAIN
|
||||
CADDY_EMAIL
|
||||
TENANT_JIEYOU_DOMAIN
|
||||
MYSQL_ROOT_PASSWORD
|
||||
MYSQL_PASSWORD
|
||||
MYSQL_DSN
|
||||
@@ -195,7 +196,7 @@ set +a
|
||||
docker compose -f deploy/docker-compose.prod.yml up -d --build
|
||||
```
|
||||
|
||||
手动执行 `docker compose` 时需要先导出 `CADDY_DOMAIN` 和 `CADDY_EMAIL`,否则 Caddy 无法读取证书域名配置。优先推荐使用一键部署脚本,它会自动从 `backend/.env` 导出这两个变量。
|
||||
手动执行 `docker compose` 时需要先导出 `CADDY_DOMAIN`、`CADDY_EMAIL` 和 `TENANT_JIEYOU_DOMAIN`,否则 Caddy 无法读取证书域名和解忧后台入口配置。优先推荐使用一键部署脚本,它会自动从 `backend/.env` 导出这些变量。
|
||||
|
||||
## 4. 手动执行数据库迁移
|
||||
|
||||
|
||||
@@ -108,6 +108,19 @@
|
||||
import storefront
|
||||
}
|
||||
|
||||
# 解忧商行使用同一套前端和后台,通过独立 Host 识别经营租户。
|
||||
# storefront 片段默认拦截后台入口,因此经营租户域名必须像主站一样单独放行。
|
||||
{$TENANT_JIEYOU_DOMAIN:tenant-jieyou.invalid} {
|
||||
@tenant_admin path {$ADMIN_BASE_PATH:/manage-7x9k2p} {$ADMIN_BASE_PATH:/manage-7x9k2p}/*
|
||||
handle @tenant_admin {
|
||||
root * /srv/dist
|
||||
try_files {path} /index.html
|
||||
file_server
|
||||
}
|
||||
|
||||
import storefront
|
||||
}
|
||||
|
||||
# 分销管理后台使用独立 React + Ant Design 静态资源,API 与主站复用 backend。
|
||||
distribution.{$CADDY_DOMAIN} {
|
||||
encode zstd gzip
|
||||
|
||||
@@ -12,6 +12,7 @@ services:
|
||||
TZ: Asia/Shanghai
|
||||
CADDY_DOMAIN: ${CADDY_DOMAIN:?请先导出 CADDY_DOMAIN,或使用 scripts/deploy-prod.sh 部署}
|
||||
CADDY_EMAIL: ${CADDY_EMAIL:?请先导出 CADDY_EMAIL,或使用 scripts/deploy-prod.sh 部署}
|
||||
TENANT_JIEYOU_DOMAIN: ${TENANT_JIEYOU_DOMAIN:-tenant-jieyou.invalid}
|
||||
# Caddyfile 用它放行主站后台隐藏入口,并与前端构建期的 VITE_ADMIN_BASE_PATH 保持一致。
|
||||
ADMIN_BASE_PATH: ${VITE_ADMIN_BASE_PATH:-/manage-7x9k2p}
|
||||
# 选号网域名可选;未配置时 conf.d 为空,不影响主站
|
||||
|
||||
+16
-5
@@ -1,6 +1,6 @@
|
||||
# 解忧商行双站点改造方案
|
||||
|
||||
> 状态:阶段 1~7 本地验收已完成,待真实域名切换
|
||||
> 状态:阶段 1~7 本地功能闭环已完成,后台租户边界修复完成,待真实域名切换
|
||||
> 更新时间:2026-11-15
|
||||
> 目标:用一套后端、一套数据库和一套前端,上线大锤商行、解忧商行两个经营站点
|
||||
|
||||
@@ -60,11 +60,13 @@
|
||||
- `fulfillment_tasks`、`order_tenant_roles` 等额外订单体系。
|
||||
- 客户会话、号主会话和平台内部案件三套聊天体系。
|
||||
- 独立租户二维码表。
|
||||
- 独立平台后台域名和租户后台域名。
|
||||
- 租户各自复制一套后台程序;后台仍复用各经营站点 Host,平台运营统计使用独立只读域名。
|
||||
- 统一跨站客服工作台。
|
||||
- 双向自动铺货规则、复杂供货合同和自动追偿。
|
||||
- 与首期无关的撞车、积分、邀请、成长、优质号主、线下提号和广告归因改造。
|
||||
|
||||
> 撞车、积分商城、线下提号等未完成经营租户隔离的模块,当前仍按平台共享能力处理;在完成独立租户改造前,不应把它们的结果当作某一经营站点的独立经营数据。
|
||||
|
||||
## 4. 目标架构
|
||||
|
||||
```text
|
||||
@@ -109,7 +111,7 @@
|
||||
| `wallet_accounts`、`wallet_ledger` | `tenant_id` |
|
||||
| `withdrawal_requests` | `tenant_id` |
|
||||
| `game_accounts` | `source_tenant_id` |
|
||||
| `rental_listings` | `source_tenant_id`、`owner_tenant_id` |
|
||||
| `rental_listings` | `source_tenant_id`(号主所属租户由 `owner_id -> users.tenant_id` 约束) |
|
||||
| `rental_orders` | `buyer_tenant_id`、`source_tenant_id`、`payment_tenant_id`、`source_amount_cent` |
|
||||
| `payment_merchant_configs` | `owner_tenant_id` |
|
||||
| `payment_orders` | `tenant_id` |
|
||||
@@ -151,7 +153,8 @@ source_amount_cent
|
||||
- 管理员仍是全局身份,通过 `admin_user_roles.tenant_id` 获得一个或多个租户角色。
|
||||
- 共享客服可以同时拥有两个租户的客服角色。
|
||||
- `super_admin` 使用 `tenant_id=0` 的平台角色,可以查看全部租户。
|
||||
- 首期复用同一套后台页面,通过当前 Host 确定租户;不拆独立后台域名。
|
||||
- 首期复用同一套后台页面,通过当前 Host 确定租户;主站和解忧各自通过本站域名进入后台。
|
||||
- 平台运营使用独立 `ops.<主域名>` 只读统计后台,仅平台超级管理员可登录。
|
||||
- 权限缓存 Key 至少包含管理员 ID 和租户 ID。
|
||||
|
||||
## 7. 共享号库和双站货架
|
||||
@@ -245,6 +248,8 @@ A 站商品进入 B 站货架
|
||||
|
||||
平台统计按租户分组展示,不把两个租户的内部交易重复相加为公司 GMV。
|
||||
|
||||
平台运营后台另设 `ops.<主域名>`,只提供只读统计,不开放用户、订单、商品和资金操作。
|
||||
|
||||
## 11. 客服、通知、文件和任务
|
||||
|
||||
首期使用最小隔离:
|
||||
@@ -267,6 +272,7 @@ A 站商品进入 B 站货架
|
||||
- 历史分销域名继续由现有分销解析逻辑处理。
|
||||
- 新经营租户订单不写分销财务快照。
|
||||
- 历史分销订单不根据 `distribution_site_id` 猜测经营租户。
|
||||
- 经营站点后台、统计和公开货架默认排除 `distribution_site_id > 0` 的历史分销数据。
|
||||
- 现有分销 E2E 测试必须全部保持通过。
|
||||
|
||||
## 13. 实施阶段
|
||||
@@ -345,6 +351,7 @@ A 站商品进入 B 站货架
|
||||
## 15. 上线验收
|
||||
|
||||
- 未知域名不会落到大锤。
|
||||
- 主站和解忧域名都能打开各自后台登录入口。
|
||||
- 同一手机号可以在两个租户注册。
|
||||
- 大锤 JWT 不能访问解忧数据,反向同样拒绝。
|
||||
- 两个站点都能看到双方开放的商品。
|
||||
@@ -355,6 +362,10 @@ A 站商品进入 B 站货架
|
||||
- 支付只进入买方租户商户,缺失时失败关闭。
|
||||
- 退款只使用原支付租户和原商户。
|
||||
- 两个站点的用户、订单、支付、钱包和统计互不串数据。
|
||||
- 用户管理、申诉仲裁和钱包调账不能跨经营租户操作。
|
||||
- 出货站不能关闭或封存买方已支付订单;退款只能由买方租户发起。
|
||||
- 历史分销用户、订单、钱包和提现不会进入经营站点后台及统计。
|
||||
- 每个经营站点可以在商品详情中独立设置本站售价和展示状态。
|
||||
- 无租户上下文的任务暂停并告警。
|
||||
- 现有分销 E2E 全部通过。
|
||||
|
||||
@@ -366,5 +377,5 @@ A 站商品进入 B 站货架
|
||||
- 自动供货合同和追偿。
|
||||
- 客户会话、货源会话、平台内部案件拆分。
|
||||
- 统一跨站客服工作台。
|
||||
- 独立平台后台域名和租户后台域名。
|
||||
- 租户复制独立后台程序。
|
||||
- 自动双向铺货策略和复杂定价规则。
|
||||
|
||||
@@ -476,6 +476,34 @@
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.tenant-offer-form {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.tenant-offer-form label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
color: #475569;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.tenant-offer-form .el-input-number {
|
||||
width: 160px;
|
||||
}
|
||||
|
||||
.tenant-offer-form small {
|
||||
color: #94a3b8;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.tenant-offer-form .el-button {
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.listing-detail-header,
|
||||
.listing-workspace {
|
||||
|
||||
@@ -22,13 +22,17 @@ import {
|
||||
adminOfflineListing,
|
||||
adminTransferListingOwner,
|
||||
emptyListingSalePriceConfig,
|
||||
fetchAdminTenantListingOffer,
|
||||
fetchAdminListing,
|
||||
fetchListingSalePriceConfig,
|
||||
updateAdminTenantListingOffer,
|
||||
type AdminExternalListingAdjustMode,
|
||||
type PublishSalePriceConfig,
|
||||
type Listing,
|
||||
type TenantListingOffer,
|
||||
} from '@/features/listings'
|
||||
import { useAdminSessionStore } from '@/stores/adminSession'
|
||||
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||
import {
|
||||
listingReviewStatusLabel,
|
||||
listingStatusLabel,
|
||||
@@ -57,6 +61,7 @@ import {
|
||||
import { calculatePlatformPricing, roundRatio as roundPricingRatio } from '@/shared/utils/pricing'
|
||||
|
||||
const adminSession = useAdminSessionStore()
|
||||
const siteStore = useDistributionSiteStore()
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
@@ -83,6 +88,10 @@ const userOptions = ref<AdminUserItem[]>([])
|
||||
const selectedUser = ref<AdminUserItem | null>(null)
|
||||
const externalAdjustVisible = ref(false)
|
||||
const externalAdjustSaving = ref(false)
|
||||
const tenantOffer = ref<TenantListingOffer | null>(null)
|
||||
const tenantOfferSaving = ref(false)
|
||||
const tenantOfferStatus = ref<'enabled' | 'disabled'>('enabled')
|
||||
const tenantOfferPriceYuan = ref<number | undefined>(undefined)
|
||||
const salePriceConfig = ref<PublishSalePriceConfig>(emptyListingSalePriceConfig)
|
||||
const externalAdjustModes: Array<{ label: string; value: AdminExternalListingAdjustMode }> = [
|
||||
{ label: '按降价金额', value: 'discount_amount' },
|
||||
@@ -113,6 +122,9 @@ const canTransfer = computed(() => !!listing.value && listing.value.status !== '
|
||||
const canAdjustExternal = computed(
|
||||
() => !!listing.value?.is_external_upload && adminSession.hasPermission('listing:edit_external')
|
||||
)
|
||||
const canManageTenantOffer = computed(
|
||||
() => siteStore.isTenant && adminSession.hasPermission('listing:approve')
|
||||
)
|
||||
const externalAdjustmentLocked = computed(
|
||||
() =>
|
||||
!listing.value ||
|
||||
@@ -292,11 +304,51 @@ async function loadListing() {
|
||||
loading.value = true
|
||||
try {
|
||||
listing.value = await fetchAdminListing(String(route.params.id))
|
||||
if (siteStore.isTenant) {
|
||||
try {
|
||||
tenantOffer.value = await fetchAdminTenantListingOffer(Number(route.params.id))
|
||||
tenantOfferStatus.value =
|
||||
tenantOffer.value.display_status === 'disabled' ? 'disabled' : 'enabled'
|
||||
tenantOfferPriceYuan.value =
|
||||
tenantOffer.value.price_cent && tenantOffer.value.price_cent > 0
|
||||
? centToYuan(tenantOffer.value.price_cent)
|
||||
: undefined
|
||||
} catch {
|
||||
tenantOffer.value = null
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveTenantOffer() {
|
||||
if (!listing.value || !canManageTenantOffer.value) return
|
||||
if (tenantOfferPriceYuan.value !== undefined && tenantOfferPriceYuan.value < 0) {
|
||||
ElMessage.warning('本站售价不能小于 0')
|
||||
return
|
||||
}
|
||||
tenantOfferSaving.value = true
|
||||
try {
|
||||
tenantOffer.value = await updateAdminTenantListingOffer(listing.value.id, {
|
||||
display_status: tenantOfferStatus.value,
|
||||
price_cent:
|
||||
tenantOfferPriceYuan.value === undefined ? null : yuanToCent(tenantOfferPriceYuan.value),
|
||||
})
|
||||
tenantOfferStatus.value =
|
||||
tenantOffer.value.display_status === 'disabled' ? 'disabled' : 'enabled'
|
||||
tenantOfferPriceYuan.value =
|
||||
tenantOffer.value.price_cent && tenantOffer.value.price_cent > 0
|
||||
? centToYuan(tenantOffer.value.price_cent)
|
||||
: undefined
|
||||
ElMessage.success('本站货架已更新')
|
||||
} catch (error) {
|
||||
ElMessage.error(readError(error, '本站货架更新失败'))
|
||||
} finally {
|
||||
tenantOfferSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function openExternalAdjustment() {
|
||||
if (!listing.value || !canAdjustExternal.value || externalAdjustmentLocked.value) return
|
||||
const row = listing.value
|
||||
@@ -856,6 +908,51 @@ async function openScreenshot(url: string) {
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="siteStore.isTenant" class="detail-panel side-panel tenant-offer-panel">
|
||||
<div class="panel-heading">
|
||||
<h2>本站货架</h2>
|
||||
<el-tag
|
||||
size="small"
|
||||
:type="tenantOfferStatus === 'enabled' ? 'success' : 'info'"
|
||||
effect="plain"
|
||||
>
|
||||
{{ tenantOfferStatus === 'enabled' ? '展示中' : '已隐藏' }}
|
||||
</el-tag>
|
||||
</div>
|
||||
<div class="tenant-offer-form">
|
||||
<label>
|
||||
<span>展示状态</span>
|
||||
<el-switch
|
||||
v-model="tenantOfferStatus"
|
||||
active-value="enabled"
|
||||
inactive-value="disabled"
|
||||
:disabled="!canManageTenantOffer"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<span>本站售价</span>
|
||||
<el-input-number
|
||||
v-model="tenantOfferPriceYuan"
|
||||
:min="0"
|
||||
:precision="2"
|
||||
:step="1"
|
||||
:disabled="!canManageTenantOffer"
|
||||
controls-position="right"
|
||||
placeholder="使用货源价"
|
||||
/>
|
||||
</label>
|
||||
<small>不填写时按货源价格 {{ formatCentWithSymbol(listing.price_cent) }} 展示</small>
|
||||
<el-button
|
||||
v-if="canManageTenantOffer"
|
||||
type="primary"
|
||||
:loading="tenantOfferSaving"
|
||||
@click="saveTenantOffer"
|
||||
>
|
||||
保存本站货架
|
||||
</el-button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="detail-panel primary-panel">
|
||||
<div class="panel-heading">
|
||||
<h2>库存资产</h2>
|
||||
|
||||
@@ -1089,14 +1089,14 @@ function formatRatioNumber(value: number) {
|
||||
<el-button type="warning" :disabled="!canOperate" @click="openAction('abnormal')"
|
||||
>标记异常</el-button
|
||||
>
|
||||
<el-tooltip :content="closeActionTip" placement="top">
|
||||
<el-tooltip v-if="hasBuyerRole" :content="closeActionTip" placement="top">
|
||||
<span>
|
||||
<el-button type="danger" :disabled="!canOperate" @click="confirmCloseAction"
|
||||
>客服关闭</el-button
|
||||
>
|
||||
</span>
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="sealActionTip" placement="top">
|
||||
<el-tooltip v-if="hasBuyerRole" :content="sealActionTip" placement="top">
|
||||
<span>
|
||||
<el-button type="danger" plain :disabled="!canOperate" @click="confirmSealAction"
|
||||
>封存订单</el-button
|
||||
|
||||
@@ -24,10 +24,12 @@ import { useAdminPaginatedTable } from '@/features/admin/composables/useAdminPag
|
||||
import { realnameStatusLabel, userStatusLabel } from '@/shared/utils/statusLabels'
|
||||
import { formatDateTime } from '@/shared/utils/time'
|
||||
import { useAdminSessionStore } from '@/stores/adminSession'
|
||||
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||
import AdminTablePagination from '../components/AdminTablePagination.vue'
|
||||
import AdminUserDetailDrawer from '../components/AdminUserDetailDrawer.vue'
|
||||
|
||||
const adminSession = useAdminSessionStore()
|
||||
const siteStore = useDistributionSiteStore()
|
||||
const canAdjustWallet = computed(() => adminSession.hasPermission('user:wallet_adjust'))
|
||||
const canAdjustGrowthPoints = computed(() => adminSession.hasPermission('user:growth_points'))
|
||||
const canAdjustGrowthLevel = computed(() => adminSession.hasPermission('user:growth_level'))
|
||||
@@ -469,7 +471,7 @@ function moneyCent(value: number | string | undefined) {
|
||||
@clear="queryUsers"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="所属站点">
|
||||
<el-form-item v-if="!siteStore.isTenant" label="所属站点">
|
||||
<el-select
|
||||
v-model="filters.tenant_id"
|
||||
clearable
|
||||
|
||||
@@ -2,11 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const apiClient = vi.hoisted(() => ({
|
||||
get: vi.fn(),
|
||||
put: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/shared/api/client', () => ({ apiClient }))
|
||||
|
||||
import { fetchListingsPage } from './listings'
|
||||
import {
|
||||
fetchListingsPage,
|
||||
fetchAdminTenantListingOffer,
|
||||
updateAdminTenantListingOffer,
|
||||
} from './listings'
|
||||
|
||||
describe('listing API site scope', () => {
|
||||
beforeEach(() => {
|
||||
@@ -46,4 +51,37 @@ describe('listing API site scope', () => {
|
||||
distribution_site_code: 'explicit_site',
|
||||
})
|
||||
})
|
||||
|
||||
it('读取本站货架配置', async () => {
|
||||
const offer = {
|
||||
tenant_id: 2,
|
||||
listing_id: 8,
|
||||
display_status: 'enabled',
|
||||
price_cent: 1200,
|
||||
effective_price_cent: 1200,
|
||||
}
|
||||
apiClient.get.mockResolvedValueOnce({ data: { data: offer } })
|
||||
|
||||
await expect(fetchAdminTenantListingOffer(8)).resolves.toEqual(offer)
|
||||
expect(apiClient.get).toHaveBeenCalledWith('/admin/listings/8/tenant-offer')
|
||||
})
|
||||
|
||||
it('更新本站货架展示与售价', async () => {
|
||||
const offer = {
|
||||
tenant_id: 2,
|
||||
listing_id: 8,
|
||||
display_status: 'disabled',
|
||||
price_cent: null,
|
||||
effective_price_cent: 1000,
|
||||
}
|
||||
apiClient.put.mockResolvedValueOnce({ data: { data: offer } })
|
||||
|
||||
await expect(
|
||||
updateAdminTenantListingOffer(8, { display_status: 'disabled', price_cent: null })
|
||||
).resolves.toEqual(offer)
|
||||
expect(apiClient.put).toHaveBeenCalledWith('/admin/listings/8/tenant-offer', {
|
||||
display_status: 'disabled',
|
||||
price_cent: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -242,6 +242,37 @@ export async function fetchAdminListing(id: string | number) {
|
||||
return data.data
|
||||
}
|
||||
|
||||
export interface TenantListingOffer {
|
||||
tenant_id: number
|
||||
listing_id: number
|
||||
display_status: 'enabled' | 'disabled' | string
|
||||
price_cent: number | null
|
||||
effective_price_cent: number
|
||||
}
|
||||
|
||||
export interface UpdateTenantListingOfferPayload {
|
||||
display_status: 'enabled' | 'disabled'
|
||||
price_cent: number | null
|
||||
}
|
||||
|
||||
export async function fetchAdminTenantListingOffer(id: number) {
|
||||
const { data } = await apiClient.get<ApiResponse<TenantListingOffer>>(
|
||||
`/admin/listings/${id}/tenant-offer`
|
||||
)
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function updateAdminTenantListingOffer(
|
||||
id: number,
|
||||
payload: UpdateTenantListingOfferPayload
|
||||
) {
|
||||
const { data } = await apiClient.put<ApiResponse<TenantListingOffer>>(
|
||||
`/admin/listings/${id}/tenant-offer`,
|
||||
payload
|
||||
)
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function adminOfflineListing(id: number, reason: string) {
|
||||
const { data } = await apiClient.post<ApiResponse<Listing>>(`/admin/listings/${id}/offline`, {
|
||||
reason,
|
||||
|
||||
+13
-1
@@ -151,10 +151,11 @@ validate_env() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local app_env caddy_domain caddy_email mysql_dsn redis_addr storage_endpoint backend_uid backend_gid backup_dir backup_status_dir backup_restore_dir backup_oss_uri backup_user
|
||||
local app_env caddy_domain caddy_email jieyou_domain mysql_dsn redis_addr storage_endpoint backend_uid backend_gid backup_dir backup_status_dir backup_restore_dir backup_oss_uri backup_user
|
||||
app_env="$(require_env APP_ENV)"
|
||||
caddy_domain="$(require_env CADDY_DOMAIN)"
|
||||
caddy_email="$(require_env CADDY_EMAIL)"
|
||||
jieyou_domain="$(require_env TENANT_JIEYOU_DOMAIN)"
|
||||
mysql_dsn="$(require_env MYSQL_DSN)"
|
||||
redis_addr="$(require_env REDIS_ADDR)"
|
||||
storage_endpoint="$(require_env STORAGE_ENDPOINT)"
|
||||
@@ -193,6 +194,14 @@ validate_env() {
|
||||
log_error "CADDY_DOMAIN 必须填写可公网解析到本机的正式域名,当前值:${caddy_domain}"
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${jieyou_domain}" == http://* || "${jieyou_domain}" == https://* || "${jieyou_domain}" == */* || "${jieyou_domain}" != *"."* ]]; then
|
||||
log_error "TENANT_JIEYOU_DOMAIN 必须填写解忧商行的正式域名,当前值:${jieyou_domain}"
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${jieyou_domain}" == "${caddy_domain}" ]]; then
|
||||
log_error "TENANT_JIEYOU_DOMAIN 不能与 CADDY_DOMAIN 相同"
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${caddy_email}" == "admin@example.com" || "${caddy_email}" != *"@"* ]]; then
|
||||
log_error "CADDY_EMAIL 需要填写真实邮箱,用于 ACME 证书通知"
|
||||
exit 1
|
||||
@@ -260,9 +269,11 @@ export_caddy_env() {
|
||||
export CADDY_DOMAIN
|
||||
export CADDY_EMAIL
|
||||
export CADDY_SHOW_DOMAIN
|
||||
export TENANT_JIEYOU_DOMAIN
|
||||
CADDY_DOMAIN="$(require_env CADDY_DOMAIN)"
|
||||
CADDY_EMAIL="$(require_env CADDY_EMAIL)"
|
||||
CADDY_SHOW_DOMAIN="$(env_value CADDY_SHOW_DOMAIN || true)"
|
||||
TENANT_JIEYOU_DOMAIN="$(require_env TENANT_JIEYOU_DOMAIN)"
|
||||
export CADDY_SHOW_DOMAIN
|
||||
|
||||
# 分销后台地址:未在 backend/.env 显式配置时,按 Caddyfile 的 distribution.<CADDY_DOMAIN>
|
||||
@@ -719,6 +730,7 @@ main() {
|
||||
fi
|
||||
|
||||
log_success "部署完成:$(public_url)"
|
||||
log_success "解忧商行后台:https://$(require_env TENANT_JIEYOU_DOMAIN)${VITE_ADMIN_BASE_PATH:-/manage-7x9k2p}/login"
|
||||
log_success "平台运营统计后台:https://ops.$(require_env CADDY_DOMAIN)"
|
||||
if [[ -n "$(env_value CADDY_SHOW_DOMAIN || true)" ]]; then
|
||||
log_success "选号网:https://$(env_value CADDY_SHOW_DOMAIN)"
|
||||
|
||||
Reference in New Issue
Block a user