fix(tenant): 收紧双站运营提号与录单边界
This commit is contained in:
@@ -83,10 +83,11 @@ func (j *Job) run(ctx context.Context) {
|
||||
j.logger.Warn("读取经营租户失败", zap.Error(err))
|
||||
return
|
||||
}
|
||||
total := 0
|
||||
if len(tenantIDs) == 0 {
|
||||
tenantIDs = []uint64{0}
|
||||
j.logger.Warn("上架未成交提醒任务未找到有效经营租户,本轮暂停")
|
||||
return
|
||||
}
|
||||
total := 0
|
||||
for _, tenantID := range tenantIDs {
|
||||
tenantCtx := ctx
|
||||
if tenantID > 0 {
|
||||
|
||||
@@ -233,3 +233,25 @@ func TestRunOnceRespectsConfiguredStaleDays(t *testing.T) {
|
||||
t.Fatalf("阈值 5 天时 RunOnce() = %d, want 0", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPausesWhenNoActiveTenant(t *testing.T) {
|
||||
db := newStaleTestDB(t)
|
||||
owner := model.User{Phone: "13900000008"}
|
||||
if err := db.Create(&owner).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publishedAt := time.Now().Add(-3*24*time.Hour - 6*time.Hour)
|
||||
seedListing(t, db, model.RentalListing{
|
||||
ListingNo: "L-NO-TENANT", OwnerID: owner.ID, Status: "published", PublishedAt: &publishedAt,
|
||||
})
|
||||
|
||||
New(db, nil, zap.NewNop(), &fakeConfigReader{value: staleConfig(t, true, 3)}).run(t.Context())
|
||||
|
||||
var count int64
|
||||
if err := db.Model(&model.SmsMessage{}).Count(&count).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("sms messages = %d, want 0 when no active tenant", count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,7 +189,8 @@ func (j *Job) run(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
if len(tenantIDs) == 0 {
|
||||
tenantIDs = []uint64{0}
|
||||
j.logger.Warn("订单超时任务未找到有效经营租户,本轮暂停")
|
||||
return
|
||||
}
|
||||
total := 0
|
||||
for _, handler := range handlers {
|
||||
|
||||
@@ -244,6 +244,28 @@ func TestHandleOwnerReturnConfirmTimeoutUsesStageTime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPausesWhenNoActiveTenant(t *testing.T) {
|
||||
db := setupOrderTimeoutTestDB(t)
|
||||
order := model.RentalOrder{
|
||||
OrderNo: "ORDER-NO-TENANT",
|
||||
Status: "pending_payment",
|
||||
CreatedAt: time.Now().Add(-time.Hour),
|
||||
}
|
||||
if err := db.Create(&order).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
New(db, nil, zap.NewNop(), nil).run(t.Context())
|
||||
|
||||
var saved model.RentalOrder
|
||||
if err := db.First(&saved, order.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if saved.Status != "pending_payment" {
|
||||
t.Fatalf("status = %q, want pending_payment when no active tenant", saved.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClampRenterRetentionDays(t *testing.T) {
|
||||
tests := []struct {
|
||||
value int
|
||||
|
||||
@@ -7,11 +7,13 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"hfb_sys/backend/internal/platformscope"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// RequirePermission 检查当前管理员是否拥有指定权限。
|
||||
@@ -46,6 +48,46 @@ func RequirePermissionIf(permCode string, rdb *redis.Client, predicate func(*gin
|
||||
}
|
||||
}
|
||||
|
||||
// RequirePlatformSuperAdmin 仅放行平台超级管理员,用于不属于单一经营站点的全局财务数据。
|
||||
func RequirePlatformSuperAdmin(db *gorm.DB) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
value, ok := c.Get(ContextAdminID)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
adminID, ok := value.(uint64)
|
||||
if !ok || adminID == 0 {
|
||||
response.Unauthorized(c, "管理员上下文无效")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if db == nil {
|
||||
response.ServiceUnavailable(c, "权限校验服务暂时不可用")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
var count int64
|
||||
err := db.WithContext(c.Request.Context()).
|
||||
Table("admin_user_roles AS aur").
|
||||
Joins("JOIN roles AS r ON r.id = aur.role_id").
|
||||
Where("aur.admin_user_id = ? AND r.code = ?", adminID, "super_admin").
|
||||
Count(&count).Error
|
||||
if err != nil {
|
||||
response.ServiceUnavailable(c, "权限校验服务暂时不可用")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if count == 0 {
|
||||
response.Error(c, http.StatusForbidden, "platform_super_admin_required", "仅平台超级管理员可访问")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func checkAnyPermission(c *gin.Context, rdb *redis.Client, permCodes ...string) bool {
|
||||
value, ok := c.Get(ContextAdminID)
|
||||
if !ok {
|
||||
@@ -108,6 +150,9 @@ func getPermCodes(c *gin.Context, rdb *redis.Client, adminID uint64) ([]string,
|
||||
|
||||
func adminPermissionCacheKey(ctx context.Context, adminID uint64) string {
|
||||
key := fmt.Sprintf("admin:perms:%d", adminID)
|
||||
if platformscope.IsScope(ctx) {
|
||||
return key + ":platform"
|
||||
}
|
||||
if scope := tenancy.ScopeKey(ctx); scope != "" {
|
||||
key += ":" + scope
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/platformscope"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -20,11 +23,66 @@ func TestAdminPermissionCacheKeyIncludesTenant(t *testing.T) {
|
||||
if got := adminPermissionCacheKey(ctx, 7); got != "admin:perms:7:tenant:101" {
|
||||
t.Fatalf("tenant permission cache key = %q", got)
|
||||
}
|
||||
platformCtx := platformscope.WithScope(context.Background())
|
||||
if got := adminPermissionCacheKey(platformCtx, 7); got != "admin:perms:7:platform" {
|
||||
t.Fatalf("platform permission cache key = %q", got)
|
||||
}
|
||||
if got := adminPermissionCacheKey(context.Background(), 7); got != "admin:perms:7" {
|
||||
t.Fatalf("legacy permission cache key = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequirePlatformSuperAdmin(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
roles := []model.Role{
|
||||
{Code: "super_admin", Name: "超级管理员"},
|
||||
{Code: "finance", Name: "财务"},
|
||||
}
|
||||
if err := db.Create(&roles).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
admins := []model.AdminUser{
|
||||
{Username: "platform-root", PasswordHash: "x", Status: "active"},
|
||||
{Username: "tenant-finance", PasswordHash: "x", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&admins).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&[]model.AdminUserRole{
|
||||
{AdminID: admins[0].ID, RoleID: roles[0].ID, TenantID: 0},
|
||||
{AdminID: admins[1].ID, RoleID: roles[1].ID, TenantID: 101},
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
engine := gin.New()
|
||||
engine.Use(func(c *gin.Context) {
|
||||
if c.GetHeader("X-Test-Admin") == "1" {
|
||||
c.Set(ContextAdminID, admins[0].ID)
|
||||
} else {
|
||||
c.Set(ContextAdminID, admins[1].ID)
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
engine.GET("/probe", RequirePlatformSuperAdmin(db), func(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
req.Header.Set("X-Test-Admin", "1")
|
||||
rec := httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("super admin status = %d, want %d", rec.Code, http.StatusNoContent)
|
||||
}
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/probe", nil))
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("tenant admin status = %d, want %d", rec.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireAnyPermission(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
|
||||
@@ -15,15 +15,16 @@ const (
|
||||
// platform / operator 存名称快照:后台删掉选项也不影响历史记录展示。
|
||||
type CSManualEntry struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
EntryNo string `gorm:"size:64;not null;uniqueIndex:uk_cs_manual_entries_entry_no_group,priority:1" json:"entry_no"`
|
||||
EntryGroup string `gorm:"size:16;not null;default:'collect';uniqueIndex:uk_cs_manual_entries_entry_no_group,priority:2;index" json:"entry_group"`
|
||||
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_cs_manual_entries_tenant_entry_group,priority:1;index:idx_cs_manual_entries_tenant_admin_created" json:"tenant_id"`
|
||||
EntryNo string `gorm:"size:64;not null;uniqueIndex:uk_cs_manual_entries_tenant_entry_group,priority:2" json:"entry_no"`
|
||||
EntryGroup string `gorm:"size:16;not null;default:'collect';uniqueIndex:uk_cs_manual_entries_tenant_entry_group,priority:3;index" json:"entry_group"`
|
||||
Platform string `gorm:"size:64;not null;default:'';index" json:"platform"`
|
||||
Operator string `gorm:"size:64;not null;default:'';index" json:"operator"`
|
||||
AdminID uint64 `gorm:"not null;index" json:"admin_id"`
|
||||
AdminID uint64 `gorm:"not null;index;index:idx_cs_manual_entries_tenant_admin_created,priority:2" json:"admin_id"`
|
||||
AdminName string `gorm:"size:64;not null;default:''" json:"admin_name"`
|
||||
AdminUsername string `gorm:"size:64;not null;default:''" json:"admin_username"`
|
||||
Remark string `gorm:"size:255;not null;default:''" json:"remark"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
CreatedAt time.Time `gorm:"index:idx_cs_manual_entries_tenant_admin_created,priority:3" json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
@@ -36,10 +37,11 @@ func (CSManualEntry) TableName() string {
|
||||
// 操作人选项可通过 group_tag 标记所属组别(收号/出号),录单时用于自动带出组别。
|
||||
type CSManualEntryOption struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
Type string `gorm:"size:32;not null;uniqueIndex:uk_cs_manual_entry_options_type_name,priority:1" json:"type"`
|
||||
Name string `gorm:"size:64;not null;uniqueIndex:uk_cs_manual_entry_options_type_name,priority:2" json:"name"`
|
||||
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_cs_manual_entry_options_tenant_type_name,priority:1;index:idx_cs_manual_entry_options_tenant_type_sort,priority:1" json:"tenant_id"`
|
||||
Type string `gorm:"size:32;not null;uniqueIndex:uk_cs_manual_entry_options_tenant_type_name,priority:2;index:idx_cs_manual_entry_options_tenant_type_sort,priority:2" json:"type"`
|
||||
Name string `gorm:"size:64;not null;uniqueIndex:uk_cs_manual_entry_options_tenant_type_name,priority:3" json:"name"`
|
||||
GroupTag string `gorm:"size:16;not null;default:''" json:"group_tag"`
|
||||
SortOrder int `gorm:"not null;default:0" json:"sort_order"`
|
||||
SortOrder int `gorm:"not null;default:0;index:idx_cs_manual_entry_options_tenant_type_sort,priority:3" json:"sort_order"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
@@ -2,11 +2,12 @@ package model
|
||||
|
||||
import "time"
|
||||
|
||||
// FileUploadOwner 记录用户上传的私有文件归属,用于业务关联创建前的临时访问授权。
|
||||
// FileUploadOwner 记录用户或管理员上传的私有文件归属,用于业务关联创建前的临时访问授权。
|
||||
type FileUploadOwner struct {
|
||||
ID uint64 `gorm:"primaryKey"`
|
||||
TenantID uint64 `gorm:"not null;default:0;index:idx_file_upload_owners_tenant_user"`
|
||||
UserID uint64 `gorm:"not null;index"`
|
||||
AdminID uint64 `gorm:"not null;default:0;index:idx_file_upload_owners_admin"`
|
||||
ObjectKey string `gorm:"size:512;not null;uniqueIndex"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
// 站内上传完成时入卖家钱包;平台代管完成后进入线下结算。
|
||||
type AdminPickup struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;default:0;index:idx_admin_pickups_tenant_status_created" json:"tenant_id"`
|
||||
SourceTenantID uint64 `gorm:"not null;default:0;index:idx_admin_pickups_source_tenant_status_created" json:"source_tenant_id"`
|
||||
PickupNo string `gorm:"size:64;not null;uniqueIndex" json:"pickup_no"`
|
||||
ListingID uint64 `gorm:"not null;index" json:"listing_id"`
|
||||
AccountID uint64 `gorm:"not null;index" json:"account_id"`
|
||||
|
||||
@@ -5,6 +5,7 @@ import "time"
|
||||
// AdminPickupFinancialAdjustment 保存已完成提号的财务调整,原始结算快照不可修改。
|
||||
type AdminPickupFinancialAdjustment struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;default:0;index:idx_pickup_financial_adjustment_tenant" json:"tenant_id"`
|
||||
PickupID uint64 `gorm:"not null;index" json:"pickup_id"`
|
||||
ProfitDeltaCent int64 `gorm:"not null;default:0" json:"profit_delta_cent"`
|
||||
SettleDeltaCent int64 `gorm:"not null;default:0" json:"settle_delta_cent"`
|
||||
|
||||
@@ -5,7 +5,8 @@ import "time"
|
||||
// PickupShop 线下提号店铺配置模型。
|
||||
type PickupShop struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null;uniqueIndex" json:"name"`
|
||||
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_pickup_shops_tenant_name,priority:1;index:idx_pickup_shops_tenant_status" json:"tenant_id"`
|
||||
Name string `gorm:"size:100;not null;uniqueIndex:uk_pickup_shops_tenant_name,priority:2" json:"name"`
|
||||
Platform string `gorm:"size:32;not null;default:''" json:"platform"`
|
||||
Status string `gorm:"size:20;not null;default:'active';index" json:"status"`
|
||||
SortOrder int `gorm:"not null;default:0" json:"sort_order"`
|
||||
@@ -21,7 +22,8 @@ func (PickupShop) TableName() string {
|
||||
// PickupShopMapping 线下提号店铺历史映射/别名模型。
|
||||
type PickupShopMapping struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
SourceName string `gorm:"size:100;not null;uniqueIndex" json:"source_name"`
|
||||
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_pickup_shop_mappings_tenant_source,priority:1" json:"tenant_id"`
|
||||
SourceName string `gorm:"size:100;not null;uniqueIndex:uk_pickup_shop_mappings_tenant_source,priority:2" json:"source_name"`
|
||||
TargetShopID uint64 `gorm:"not null;default:0" json:"target_shop_id"`
|
||||
TargetShopName string `gorm:"size:100;not null;index" json:"target_shop_name"`
|
||||
MappedCount int64 `gorm:"not null;default:0" json:"mapped_count"`
|
||||
@@ -33,4 +35,3 @@ type PickupShopMapping struct {
|
||||
func (PickupShopMapping) TableName() string {
|
||||
return "pickup_shop_mappings"
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ import "time"
|
||||
|
||||
type User struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_users_tenant_phone;index:idx_users_tenant_status" json:"tenant_id"`
|
||||
Phone string `gorm:"size:32;not null;uniqueIndex:uk_users_tenant_phone" json:"phone"`
|
||||
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_users_tenant_site_phone,priority:1;index:idx_users_tenant_status" json:"tenant_id"`
|
||||
Phone string `gorm:"size:32;not null;uniqueIndex:uk_users_tenant_site_phone,priority:3" json:"phone"`
|
||||
PasswordHash string `gorm:"size:255;not null;default:''" json:"-"`
|
||||
Nickname string `gorm:"size:64;not null;default:''" json:"nickname"`
|
||||
AvatarURL string `gorm:"size:512;not null;default:''" json:"avatar_url"`
|
||||
@@ -27,7 +27,7 @@ type User struct {
|
||||
TokenVersion int64 `gorm:"not null;default:0" json:"-"`
|
||||
// 注册归因:注册时由前端携带的推广短码。
|
||||
RegisterTrackCode string `gorm:"size:64;index:idx_users_register_track_code" json:"register_track_code,omitempty"`
|
||||
DistributionSiteID uint64 `gorm:"not null;default:0;index:idx_users_distribution_site_id" json:"distribution_site_id"` // 0=主站, >0=对应分销站点
|
||||
DistributionSiteID uint64 `gorm:"not null;default:0;uniqueIndex:uk_users_tenant_site_phone,priority:2;index:idx_users_distribution_site_id" json:"distribution_site_id"` // 0=主站, >0=对应分销站点
|
||||
InviteCode *string `gorm:"size:32;uniqueIndex:uk_users_tenant_invite_code" json:"invite_code,omitempty"`
|
||||
InvitedByID uint64 `gorm:"not null;default:0;index:idx_users_invited_by_id" json:"invited_by_id,omitempty"`
|
||||
InviteVerifiedAt *time.Time `json:"invite_verified_at,omitempty"`
|
||||
|
||||
@@ -535,9 +535,6 @@ func (r *Repository) tradingDailyOverview(ctx context.Context, now time.Time, da
|
||||
// 录单表是后来新增的功能表,若迁移尚未执行(表不存在)则降级为空统计,
|
||||
// 避免连带整个仪表盘不可用。
|
||||
func (r *Repository) manualEntryToday(ctx context.Context, now time.Time) ([]ManualEntryAgentStatsDTO, error) {
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
return []ManualEntryAgentStatsDTO{}, nil
|
||||
}
|
||||
if r.db == nil || !r.db.Migrator().HasTable("cs_manual_entries") {
|
||||
return []ManualEntryAgentStatsDTO{}, nil
|
||||
}
|
||||
@@ -551,7 +548,11 @@ func (r *Repository) manualEntryToday(ctx context.Context, now time.Time) ([]Man
|
||||
Count int64
|
||||
}
|
||||
rows := make([]row, 0)
|
||||
if err := r.db.WithContext(ctx).Table("cs_manual_entries").
|
||||
query := r.db.WithContext(ctx).Table("cs_manual_entries")
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.
|
||||
Select("admin_id, MAX(admin_name) AS admin_name, COUNT(*) AS count").
|
||||
Where("created_at >= ? AND created_at < ?", start, end).
|
||||
Group("admin_id").
|
||||
|
||||
@@ -3,16 +3,44 @@ package admindashboard
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
)
|
||||
|
||||
func dashboardTenantContext(tenantID uint64) context.Context {
|
||||
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
|
||||
func TestManualEntryTodayScopesByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
now := time.Date(2026, 11, 16, 12, 0, 0, 0, timeutil.ShanghaiLocation())
|
||||
entries := []model.CSManualEntry{
|
||||
{TenantID: 101, EntryNo: "MT-A", EntryGroup: "collect", AdminID: 1, AdminName: "A客服", CreatedAt: now},
|
||||
{TenantID: 202, EntryNo: "MT-B", EntryGroup: "sell", AdminID: 2, AdminName: "B客服", CreatedAt: now},
|
||||
}
|
||||
if err := db.Create(&entries).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db)
|
||||
itemsA, err := repo.manualEntryToday(dashboardTenantContext(101), now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
itemsB, err := repo.manualEntryToday(dashboardTenantContext(202), now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(itemsA) != 1 || itemsA[0].AdminName != "A客服" ||
|
||||
len(itemsB) != 1 || itemsB[0].AdminName != "B客服" {
|
||||
t.Fatalf("tenant manual entry stats A=%+v B=%+v", itemsA, itemsB)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummaryScopesBuyerAndSourceMetricsByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenants := []model.Tenant{
|
||||
|
||||
@@ -107,56 +107,70 @@ func (r *Repository) operatingExpenseSummary(ctx context.Context, query Dashboar
|
||||
|
||||
// pickupSummary 线下提号统计,独立查询 admin_pickups 表,不混入正常订单口径。
|
||||
func (r *Repository) pickupSummary(ctx context.Context, query DashboardQuery) (*PickupSummaryDTO, error) {
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
return &PickupSummaryDTO{}, nil
|
||||
}
|
||||
db := r.db.WithContext(ctx)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
var row struct {
|
||||
SettledAmountCent int64
|
||||
ProfitAmountCent int64
|
||||
CompletedCount int64
|
||||
}
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
||||
pickupQuery := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS settled_amount_cent, COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent, COUNT(id) AS completed_count`).
|
||||
Where("status = ?", "completed").
|
||||
Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&row).Error; err != nil {
|
||||
Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID > 0 {
|
||||
pickupQuery = pickupQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pickupQuery.Scan(&row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var adjustments struct {
|
||||
SettledAmountCent int64
|
||||
ProfitAmountCent int64
|
||||
}
|
||||
if err := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
adjustmentQuery := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
Select(`COALESCE(SUM(fa.settle_delta_cent), 0) AS settled_amount_cent,
|
||||
COALESCE(SUM(fa.profit_delta_cent), 0) AS profit_amount_cent`).
|
||||
Joins("JOIN admin_pickups AS p ON p.id = fa.pickup_id AND p.status = ?", "completed").
|
||||
Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&adjustments).Error; err != nil {
|
||||
Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID > 0 {
|
||||
adjustmentQuery = adjustmentQuery.Where("fa.tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := adjustmentQuery.Scan(&adjustments).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var inProgress int64
|
||||
if err := db.Table("admin_pickups").Where("status = ?", "picking_up").Count(&inProgress).Error; err != nil {
|
||||
inProgressQuery := db.Table("admin_pickups").Where("status = ?", "picking_up")
|
||||
if tenantID > 0 {
|
||||
inProgressQuery = inProgressQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := inProgressQuery.Count(&inProgress).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pending struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
pendingQuery := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ? AND offline_settlement_status = ? AND settle_amount_cent > 0", "platform_managed", "pending").
|
||||
Scan(&pending).Error; err != nil {
|
||||
Where("settlement_mode = ? AND offline_settlement_status = ? AND settle_amount_cent > 0", "platform_managed", "pending")
|
||||
if tenantID > 0 {
|
||||
pendingQuery = pendingQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pendingQuery.Scan(&pending).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pendingAdjustments struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
pendingAdjustmentQuery := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ? AND status = ? AND settle_delta_cent > 0", "platform_managed", "pending").
|
||||
Scan(&pendingAdjustments).Error; err != nil {
|
||||
Where("settlement_mode = ? AND status = ? AND settle_delta_cent > 0", "platform_managed", "pending")
|
||||
if tenantID > 0 {
|
||||
pendingAdjustmentQuery = pendingAdjustmentQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pendingAdjustmentQuery.Scan(&pendingAdjustments).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &PickupSummaryDTO{
|
||||
@@ -251,29 +265,29 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
||||
}
|
||||
|
||||
pickupProfits := make([]dailyPickupProfitRow, 0)
|
||||
if tenancy.IDFromContext(ctx) == 0 {
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
||||
Select(`DATE_FORMAT(completed_at, '%Y-%m-%d') AS date,
|
||||
pickupProfitQuery := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_completed)").
|
||||
Select(`DATE_FORMAT(completed_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent,
|
||||
COUNT(id) AS completed_count`).
|
||||
Where("status = ?", "completed").
|
||||
Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(completed_at, '%Y-%m-%d')").
|
||||
Scan(&pickupProfits).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
}
|
||||
Where("status = ?", "completed").
|
||||
Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
pickupProfitQuery = pickupProfitQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pickupProfitQuery.Group("DATE_FORMAT(completed_at, '%Y-%m-%d')").Scan(&pickupProfits).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
}
|
||||
pickupAdjustments := make([]dailyPickupAdjustmentRow, 0)
|
||||
if tenancy.IDFromContext(ctx) == 0 {
|
||||
if err := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
Select(`DATE_FORMAT(fa.created_at, '%Y-%m-%d') AS date,
|
||||
pickupAdjustmentQuery := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
Select(`DATE_FORMAT(fa.created_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(fa.profit_delta_cent), 0) AS profit_amount_cent`).
|
||||
Joins("JOIN admin_pickups AS p ON p.id = fa.pickup_id AND p.status = ?", "completed").
|
||||
Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(fa.created_at, '%Y-%m-%d')").
|
||||
Scan(&pickupAdjustments).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
}
|
||||
Joins("JOIN admin_pickups AS p ON p.id = fa.pickup_id AND p.status = ?", "completed").
|
||||
Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
pickupAdjustmentQuery = pickupAdjustmentQuery.Where("fa.tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := pickupAdjustmentQuery.Group("DATE_FORMAT(fa.created_at, '%Y-%m-%d')").Scan(&pickupAdjustments).Error; err != nil {
|
||||
return dashboardDailyResult{}, err
|
||||
}
|
||||
|
||||
// 取消提号按取消日统计,与「已付款订单数」中的提号创建口径区分开。
|
||||
@@ -604,15 +618,14 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([
|
||||
// dailyPickupCancelled 按取消日统计线下提号取消笔数。
|
||||
func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQuery) ([]dailyPickupCancelledRow, error) {
|
||||
rows := make([]dailyPickupCancelledRow, 0)
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
return rows, nil
|
||||
}
|
||||
err := r.db.WithContext(ctx).Table("admin_pickups").
|
||||
db := r.db.WithContext(ctx).Table("admin_pickups").
|
||||
Select(`DATE_FORMAT(cancelled_at, '%Y-%m-%d') AS date, COUNT(id) AS count`).
|
||||
Where("status = ?", "cancelled").
|
||||
Where("cancelled_at >= ? AND cancelled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(cancelled_at, '%Y-%m-%d')").
|
||||
Scan(&rows).Error
|
||||
Where("cancelled_at >= ? AND cancelled_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
db = db.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
err := db.Group("DATE_FORMAT(cancelled_at, '%Y-%m-%d')").Scan(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
@@ -631,10 +644,13 @@ func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery)
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
))`
|
||||
pickupTenantFilter = " AND 1 = 0"
|
||||
pickupTenantFilter = " AND tenant_id = ?"
|
||||
args = append(args, tenantID)
|
||||
}
|
||||
args = append(args, query.StartDate, query.EndDate)
|
||||
if tenantID > 0 {
|
||||
args = append(args, tenantID)
|
||||
}
|
||||
err := r.db.WithContext(ctx).Table(`(
|
||||
SELECT DATE_FORMAT(paid_at, '%Y-%m-%d') AS date, COUNT(DISTINCT order_id) AS paid_order_count
|
||||
FROM payment_orders USE INDEX (idx_payment_orders_biz_status_paid_at_order)
|
||||
|
||||
@@ -14,6 +14,13 @@ type dailyOperatingExpenseRow struct {
|
||||
Count int64
|
||||
}
|
||||
|
||||
func financePickupTenantScope(db *gorm.DB, tenantID uint64, column string) *gorm.DB {
|
||||
if tenantID > 0 {
|
||||
return db.Where(column+" = ?", tenantID)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func (r *Repository) dailyOperatingExpenses(ctx context.Context, query DashboardQuery) ([]dailyOperatingExpenseRow, error) {
|
||||
rows := make([]dailyOperatingExpenseRow, 0)
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
@@ -49,30 +56,30 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&pickupPaid).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := financePickupTenantScope(
|
||||
db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)"),
|
||||
tenantID,
|
||||
"tenant_id",
|
||||
).
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&pickupPaid).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pickupAdjustmentPaid struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "settled").
|
||||
Where("settle_delta_cent > 0").
|
||||
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&pickupAdjustmentPaid).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := financePickupTenantScope(db.Table("admin_pickup_financial_adjustments"), tenantID, "tenant_id").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "settled").
|
||||
Where("settle_delta_cent > 0").
|
||||
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Scan(&pickupAdjustmentPaid).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var offlinePending struct {
|
||||
@@ -91,29 +98,29 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "pending").
|
||||
Where("settle_amount_cent > 0").
|
||||
Scan(&pickupPending).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := financePickupTenantScope(
|
||||
db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)"),
|
||||
tenantID,
|
||||
"tenant_id",
|
||||
).
|
||||
Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "pending").
|
||||
Where("settle_amount_cent > 0").
|
||||
Scan(&pickupPending).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pickupAdjustmentPending struct {
|
||||
AmountCent int64
|
||||
Count int64
|
||||
}
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "pending").
|
||||
Where("settle_delta_cent > 0").
|
||||
Scan(&pickupAdjustmentPending).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := financePickupTenantScope(db.Table("admin_pickup_financial_adjustments"), tenantID, "tenant_id").
|
||||
Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "pending").
|
||||
Where("settle_delta_cent > 0").
|
||||
Scan(&pickupAdjustmentPending).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 付款、处理中、待审核三类提现在一次条件聚合中完成,避免同一张表重复扫描。
|
||||
@@ -199,33 +206,33 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
||||
return nil, err
|
||||
}
|
||||
pickupOfflineRows := make([]dailyDisbursementSourceRow, 0)
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)").
|
||||
Select(`DATE_FORMAT(offline_settled_at, '%Y-%m-%d') AS date,
|
||||
if err := financePickupTenantScope(
|
||||
db.Table("admin_pickups USE INDEX (idx_admin_pickups_dashboard_offline_settlement)"),
|
||||
tenantID,
|
||||
"tenant_id",
|
||||
).
|
||||
Select(`DATE_FORMAT(offline_settled_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(settle_amount_cent), 0) AS amount_cent,
|
||||
COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(offline_settled_at, '%Y-%m-%d')").
|
||||
Scan(&pickupOfflineRows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(offline_settled_at, '%Y-%m-%d')").
|
||||
Scan(&pickupOfflineRows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pickupAdjustmentRows := make([]dailyDisbursementSourceRow, 0)
|
||||
if tenantID == 0 {
|
||||
if err := db.Table("admin_pickup_financial_adjustments").
|
||||
Select(`DATE_FORMAT(settled_at, '%Y-%m-%d') AS date,
|
||||
if err := financePickupTenantScope(db.Table("admin_pickup_financial_adjustments"), tenantID, "tenant_id").
|
||||
Select(`DATE_FORMAT(settled_at, '%Y-%m-%d') AS date,
|
||||
COALESCE(SUM(settle_delta_cent), 0) AS amount_cent,
|
||||
COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "settled").
|
||||
Where("settle_delta_cent > 0").
|
||||
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(settled_at, '%Y-%m-%d')").
|
||||
Scan(&pickupAdjustmentRows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "settled").
|
||||
Where("settle_delta_cent > 0").
|
||||
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE_FORMAT(settled_at, '%Y-%m-%d')").
|
||||
Scan(&pickupAdjustmentRows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
offlineRows = append(offlineRows, pickupOfflineRows...)
|
||||
offlineRows = append(offlineRows, pickupAdjustmentRows...)
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -54,6 +56,7 @@ func (r *Repository) Disbursements(ctx context.Context, query DisbursementQuery)
|
||||
|
||||
func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword string) *gorm.DB {
|
||||
db := r.db.WithContext(ctx)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
platformManaged := db.Table("rental_orders AS ro").
|
||||
Select(`'platform_managed' AS source_type,
|
||||
ro.id AS source_id,
|
||||
@@ -95,6 +98,11 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
Where("ro.settlement_mode = ?", "platform_managed").
|
||||
Where("ro.offline_settlement_status IN ?", []string{"pending", "settled"}).
|
||||
Where("ro.offline_settlement_amount_cent > 0")
|
||||
if tenantID > 0 {
|
||||
platformManaged = platformManaged.
|
||||
Where("(ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(ro.distribution_site_id IS NULL OR ro.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
pickupManaged := db.Table("admin_pickups AS ap").
|
||||
Select(`'pickup' AS source_type,
|
||||
@@ -134,6 +142,9 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
Where("ap.settlement_mode = ?", "platform_managed").
|
||||
Where("ap.offline_settlement_status IN ?", []string{"pending", "settled"}).
|
||||
Where("ap.settle_amount_cent > 0")
|
||||
if tenantID > 0 {
|
||||
pickupManaged = pickupManaged.Where("ap.tenant_id = ?", tenantID)
|
||||
}
|
||||
|
||||
pickupAdjustments := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||
Select(`'pickup_adjustment' AS source_type,
|
||||
@@ -174,6 +185,9 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
Where("fa.settlement_mode = ?", "platform_managed").
|
||||
Where("fa.status IN ?", []string{"pending", "settled"}).
|
||||
Where("fa.settle_delta_cent > 0")
|
||||
if tenantID > 0 {
|
||||
pickupAdjustments = pickupAdjustments.Where("fa.tenant_id = ?", tenantID)
|
||||
}
|
||||
|
||||
withdrawal := db.Table("withdrawal_requests AS wr").
|
||||
Select(`'withdrawal' AS source_type,
|
||||
@@ -216,6 +230,9 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
NULL AS source_payload`).
|
||||
Joins("LEFT JOIN users AS u ON u.id = wr.user_id").
|
||||
Joins("LEFT JOIN admin_users AS operator ON operator.id = COALESCE(wr.paid_by, wr.reviewed_by)")
|
||||
if tenantID > 0 {
|
||||
withdrawal = withdrawal.Where("wr.tenant_id = ? AND wr.distribution_site_id = 0", tenantID)
|
||||
}
|
||||
|
||||
if phoneKeyword = strings.TrimSpace(phoneKeyword); isPhoneKeyword(phoneKeyword) {
|
||||
withdrawal = withdrawal.Where("wr.user_id = (SELECT id FROM users WHERE phone = ?)", phoneKeyword)
|
||||
@@ -258,6 +275,9 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
|
||||
NULL AS source_payload`).
|
||||
Joins("LEFT JOIN admin_users AS creator ON creator.id = md.created_by").
|
||||
Joins("LEFT JOIN admin_users AS voider ON voider.id = md.voided_by")
|
||||
if tenantID > 0 {
|
||||
manualOffline = manualOffline.Where("1 = 0")
|
||||
}
|
||||
|
||||
union := db.Raw("? UNION ALL ? UNION ALL ? UNION ALL ? UNION ALL ?", platformManaged, pickupManaged, pickupAdjustments, withdrawal, manualOffline)
|
||||
return db.Table("(?) AS d", union)
|
||||
|
||||
@@ -2,6 +2,27 @@ package adminfinance
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidFinanceVoucherURLUsesScenePrefix(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
scene string
|
||||
want bool
|
||||
}{
|
||||
{name: "manual", raw: "/api/files/object?key=manual-disbursement%2Fvoucher.webp", scene: "manual-disbursement/", want: true},
|
||||
{name: "operating", raw: "/api/files/object?key=operating-expense%2Fvoucher.webp", scene: "operating-expense/", want: true},
|
||||
{name: "wrong scene", raw: "/api/files/object?key=manual-disbursement%2Fvoucher.webp", scene: "operating-expense/", want: false},
|
||||
{name: "external", raw: "https://example.com/voucher.webp", scene: "operating-expense/", want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := validFinanceVoucherURL(tc.raw, tc.scene); got != tc.want {
|
||||
t.Fatalf("validFinanceVoucherURL() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDailyDateKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -102,7 +102,7 @@ func (s *Service) CreateManualDisbursement(
|
||||
utf8.RuneCountInString(req.PayeeName) < 1 || utf8.RuneCountInString(req.PayeeName) > 100 ||
|
||||
req.AmountCent <= 0 || req.PaidAt.IsZero() ||
|
||||
utf8.RuneCountInString(req.Remark) < 1 || utf8.RuneCountInString(req.Remark) > 500 ||
|
||||
!validManualVoucherURL(req.VoucherURL) {
|
||||
!validFinanceVoucherURL(req.VoucherURL, "manual-disbursement/") {
|
||||
return nil, ErrInvalidManualDisbursement
|
||||
}
|
||||
return s.repo.CreateManualDisbursement(ctx, req, adminID, meta)
|
||||
@@ -137,7 +137,7 @@ func (s *Service) CreateOperatingExpense(ctx context.Context, req CreateOperatin
|
||||
utf8.RuneCountInString(req.PayeeName) < 1 || utf8.RuneCountInString(req.PayeeName) > 100 ||
|
||||
req.AmountCent <= 0 || req.OccurredAt.IsZero() ||
|
||||
utf8.RuneCountInString(req.Remark) < 1 || utf8.RuneCountInString(req.Remark) > 500 ||
|
||||
!validManualVoucherURL(req.VoucherURL) {
|
||||
!validFinanceVoucherURL(req.VoucherURL, "operating-expense/") {
|
||||
return nil, ErrInvalidOperatingExpense
|
||||
}
|
||||
return s.repo.CreateOperatingExpense(ctx, req, adminID, meta)
|
||||
@@ -170,7 +170,7 @@ func validManualDisbursementCustomCategoryName(category, name string) bool {
|
||||
return utf8.RuneCountInString(name) >= 1 && utf8.RuneCountInString(name) <= 50
|
||||
}
|
||||
|
||||
func validManualVoucherURL(raw string) bool {
|
||||
func validFinanceVoucherURL(raw string, scenePrefix string) bool {
|
||||
if raw == "" {
|
||||
return true
|
||||
}
|
||||
@@ -181,5 +181,5 @@ func validManualVoucherURL(raw string) bool {
|
||||
if err != nil || parsed.IsAbs() || parsed.Path != "/api/files/object" {
|
||||
return false
|
||||
}
|
||||
return strings.HasPrefix(parsed.Query().Get("key"), "manual-disbursement/")
|
||||
return strings.HasPrefix(parsed.Query().Get("key"), scenePrefix)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
)
|
||||
|
||||
func financeTenantContext(tenantID uint64) context.Context {
|
||||
@@ -51,3 +52,87 @@ func TestFinancePaymentStatsAreScopedByTenant(t *testing.T) {
|
||||
t.Fatal("dashboard cache key must include tenant")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinancePickupStatsAndDisbursementsAreScopedByPickupTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
now := time.Date(2026, 11, 16, 12, 0, 0, 0, loc)
|
||||
if err := db.Exec(`INSERT INTO admin_pickups
|
||||
(id, tenant_id, source_tenant_id, pickup_no, listing_id, account_id, owner_id, admin_id,
|
||||
listing_price_cent, settle_amount_cent, profit_amount_cent, status, settlement_mode,
|
||||
offline_settlement_status, created_at, completed_at)
|
||||
VALUES
|
||||
(1, 101, 202, 'PK-SCOPE-A', 11, 12, 13, 1, 1000, 100, 20, 'completed', 'platform_managed', 'pending', ?, ?),
|
||||
(2, 202, 101, 'PK-SCOPE-B', 21, 22, 23, 2, 2000, 200, 40, 'completed', 'platform_managed', 'pending', ?, ?),
|
||||
(3, 101, 101, 'PK-SCOPE-CANCEL-A', 31, 32, 33, 1, 1000, 0, 0, 'cancelled', 'owner_wallet', 'none', ?, NULL),
|
||||
(4, 202, 202, 'PK-SCOPE-CANCEL-B', 41, 42, 43, 2, 1000, 0, 0, 'cancelled', 'owner_wallet', 'none', ?, NULL)`,
|
||||
now, now, now, now, now, now).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`UPDATE admin_pickups SET cancelled_at = ? WHERE status = 'cancelled'`, now).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments
|
||||
(id, tenant_id, pickup_id, profit_delta_cent, settle_delta_cent, settlement_mode,
|
||||
status, reason, created_by, created_at)
|
||||
VALUES
|
||||
(1, 101, 1, 1, 10, 'platform_managed', 'settled', 'A调整', 1, ?),
|
||||
(2, 202, 2, 2, 20, 'platform_managed', 'settled', 'B调整', 2, ?)`,
|
||||
now, now).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db)
|
||||
ctxA := financeTenantContext(101)
|
||||
query := DashboardQuery{StartDate: now.Add(-time.Hour), EndDate: now.Add(time.Hour)}
|
||||
summary, err := repo.pickupSummary(ctxA, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.CompletedCount != 1 || summary.SettledAmountCent != 110 ||
|
||||
summary.ProfitAmountCent != 21 || summary.PendingCount != 1 ||
|
||||
summary.PendingAmountCent != 100 {
|
||||
t.Fatalf("tenant pickup summary = %+v", summary)
|
||||
}
|
||||
|
||||
paid, err := repo.dailyPaidOrders(ctxA, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(paid) != 1 || paid[0].PaidOrderCount != 1 {
|
||||
t.Fatalf("tenant paid pickup orders = %+v", paid)
|
||||
}
|
||||
cancelled, err := repo.dailyPickupCancelled(ctxA, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cancelled) != 1 || cancelled[0].Count != 1 {
|
||||
t.Fatalf("tenant cancelled pickups = %+v", cancelled)
|
||||
}
|
||||
disbursement, err := repo.disbursementSummary(ctxA, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if disbursement.PendingPaymentCount != 1 || disbursement.PendingPaymentAmountCent != 100 ||
|
||||
disbursement.OfflineSettlementPendingCount != 1 ||
|
||||
disbursement.OfflineSettlementPendingAmountCent != 100 {
|
||||
t.Fatalf("tenant pickup disbursement summary = %+v", disbursement)
|
||||
}
|
||||
list, err := repo.Disbursements(ctxA, DisbursementQuery{
|
||||
StartDate: now.Add(-time.Hour),
|
||||
EndDate: now.Add(time.Hour),
|
||||
Page: 1,
|
||||
PageSize: 20,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if list.Total != 2 {
|
||||
t.Fatalf("tenant disbursement items = %+v", list)
|
||||
}
|
||||
for _, item := range list.Items {
|
||||
if item.BusinessNo == "PK-SCOPE-B" {
|
||||
t.Fatalf("tenant A disbursements leaked tenant B pickup: %+v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,7 +223,8 @@ func (h *Handler) PasswordLogin(c *gin.Context) {
|
||||
response.BadRequest(c, "手机号和密码不能为空,密码长度 8-20 位")
|
||||
return
|
||||
}
|
||||
result, err := h.service.LoginWithPassword(c.Request.Context(), strings.TrimSpace(req.Phone), req.Password, c.ClientIP())
|
||||
siteCode := sitecode.FromRequest(c)
|
||||
result, err := h.service.LoginWithPassword(c.Request.Context(), strings.TrimSpace(req.Phone), req.Password, c.ClientIP(), siteCode)
|
||||
if err != nil {
|
||||
writeAuthError(c, err)
|
||||
return
|
||||
@@ -275,7 +276,8 @@ func (h *Handler) ResetPassword(c *gin.Context) {
|
||||
response.BadRequest(c, "手机号、验证码和新密码不能为空")
|
||||
return
|
||||
}
|
||||
if err := h.service.ResetPassword(c.Request.Context(), strings.TrimSpace(req.Phone), strings.TrimSpace(req.Code), req.NewPassword); err != nil {
|
||||
siteCode := sitecode.FromRequest(c)
|
||||
if err := h.service.ResetPassword(c.Request.Context(), strings.TrimSpace(req.Phone), strings.TrimSpace(req.Code), req.NewPassword, siteCode); err != nil {
|
||||
writeAuthError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -311,8 +313,6 @@ func writeAuthError(c *gin.Context, err error) {
|
||||
response.Error(c, http.StatusTooManyRequests, "login_locked", "登录失败次数过多,请 15 分钟后再试")
|
||||
case errors.Is(err, ErrUserAlreadyExists):
|
||||
response.BadRequest(c, "该手机号已注册,请直接登录或使用短信验证码登录")
|
||||
case errors.Is(err, ErrLegacyDistributionUser):
|
||||
response.Error(c, http.StatusForbidden, "legacy_distribution_user", "该手机号属于历史分销渠道,请从原分销站点登录")
|
||||
default:
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "服务暂时不可用")
|
||||
}
|
||||
|
||||
@@ -98,33 +98,29 @@ func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string,
|
||||
now := time.Now()
|
||||
code := sanitizeTrackCode(trackCode)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID > 0 {
|
||||
var existing model.User
|
||||
query := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND phone = ? AND distribution_site_id = 0", tenantID, phone)
|
||||
if err := query.First(&existing).Error; err == nil {
|
||||
_ = r.db.WithContext(ctx).Model(&existing).Updates(map[string]any{
|
||||
"last_login_at": now,
|
||||
"updated_at": now,
|
||||
}).Error
|
||||
return &existing, nil
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
var legacyCount int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.User{}).
|
||||
Where("tenant_id = ? AND phone = ? AND distribution_site_id > 0", tenantID, phone).
|
||||
Count(&legacyCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if legacyCount > 0 {
|
||||
return nil, ErrLegacyDistributionUser
|
||||
}
|
||||
}
|
||||
var siteID uint64
|
||||
if len(siteCode) > 0 {
|
||||
siteID = r.resolveSiteID(ctx, siteCode[0])
|
||||
}
|
||||
if tenantID > 0 {
|
||||
siteID = 0
|
||||
}
|
||||
var existing model.User
|
||||
query := r.db.WithContext(ctx).Where("phone = ?", phone)
|
||||
if siteID > 0 {
|
||||
query = query.Where("distribution_site_id = ?", siteID)
|
||||
} else {
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := query.First(&existing).Error; err == nil {
|
||||
_ = r.db.WithContext(ctx).Model(&existing).Updates(map[string]any{
|
||||
"last_login_at": now,
|
||||
"updated_at": now,
|
||||
}).Error
|
||||
return &existing, nil
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
user := model.User{
|
||||
TenantID: tenantID,
|
||||
Phone: phone,
|
||||
@@ -140,11 +136,11 @@ func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string,
|
||||
|
||||
onConflict := clause.OnConflict{
|
||||
DoUpdates: clause.AssignmentColumns([]string{"last_login_at", "updated_at"}),
|
||||
}
|
||||
if tenantID > 0 {
|
||||
onConflict.Columns = []clause.Column{{Name: "tenant_id"}, {Name: "phone"}}
|
||||
} else {
|
||||
onConflict.Columns = []clause.Column{{Name: "phone"}}
|
||||
Columns: []clause.Column{
|
||||
{Name: "tenant_id"},
|
||||
{Name: "distribution_site_id"},
|
||||
{Name: "phone"},
|
||||
},
|
||||
}
|
||||
err := r.db.WithContext(ctx).Clauses(onConflict).Create(&user).Error
|
||||
if err != nil {
|
||||
@@ -152,8 +148,10 @@ func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string,
|
||||
}
|
||||
|
||||
var found model.User
|
||||
query := r.db.WithContext(ctx).Where("phone = ?", phone)
|
||||
if tenantID > 0 {
|
||||
query = r.db.WithContext(ctx).Where("phone = ?", phone)
|
||||
if siteID > 0 {
|
||||
query = query.Where("distribution_site_id = ?", siteID)
|
||||
} else {
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := query.First(&found).Error; err != nil {
|
||||
@@ -162,24 +160,23 @@ func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string,
|
||||
return &found, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) FindByPhone(ctx context.Context, phone string) (*model.User, error) {
|
||||
func (r *UserRepository) FindByPhone(ctx context.Context, phone string, siteCode ...string) (*model.User, error) {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
var siteID uint64
|
||||
if len(siteCode) > 0 {
|
||||
siteID = r.resolveSiteID(ctx, siteCode[0])
|
||||
}
|
||||
if tenantID > 0 {
|
||||
siteID = 0
|
||||
}
|
||||
var user model.User
|
||||
query := r.db.WithContext(ctx).Where("phone = ?", phone)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
if siteID > 0 {
|
||||
query = query.Where("distribution_site_id = ?", siteID)
|
||||
} else {
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := query.First(&user).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) && tenancy.IDFromContext(ctx) > 0 {
|
||||
var legacyCount int64
|
||||
if countErr := r.db.WithContext(ctx).Model(&model.User{}).
|
||||
Where("tenant_id = ? AND phone = ? AND distribution_site_id > 0", tenancy.IDFromContext(ctx), phone).
|
||||
Count(&legacyCount).Error; countErr != nil {
|
||||
return nil, countErr
|
||||
}
|
||||
if legacyCount > 0 {
|
||||
return nil, ErrLegacyDistributionUser
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
@@ -209,21 +206,13 @@ func (r *UserRepository) RegisterWithPassword(ctx context.Context, phone string,
|
||||
now := time.Now()
|
||||
code := sanitizeTrackCode(trackCode)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID > 0 {
|
||||
var legacyCount int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.User{}).
|
||||
Where("tenant_id = ? AND phone = ? AND distribution_site_id > 0", tenantID, phone).
|
||||
Count(&legacyCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if legacyCount > 0 {
|
||||
return nil, ErrLegacyDistributionUser
|
||||
}
|
||||
}
|
||||
var siteID uint64
|
||||
if len(siteCode) > 0 {
|
||||
siteID = r.resolveSiteID(ctx, siteCode[0])
|
||||
}
|
||||
if tenantID > 0 {
|
||||
siteID = 0
|
||||
}
|
||||
user := model.User{
|
||||
TenantID: tenantID,
|
||||
Phone: phone,
|
||||
|
||||
@@ -22,21 +22,20 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
ErrInvalidPhone = errors.New("invalid phone")
|
||||
ErrCaptchaInvalid = errors.New("captcha invalid")
|
||||
ErrCodeRateLimited = errors.New("sms code rate limited")
|
||||
ErrCodeInvalid = errors.New("sms code invalid")
|
||||
ErrSMSSendFailed = errors.New("sms send failed")
|
||||
ErrUserDisabled = errors.New("user disabled")
|
||||
ErrInvalidPassword = errors.New("invalid password")
|
||||
ErrInvalidOldPassword = errors.New("invalid old password")
|
||||
ErrPasswordNotSet = errors.New("password not set")
|
||||
ErrPasswordTooWeak = errors.New("password too weak")
|
||||
ErrLoginLocked = errors.New("login locked")
|
||||
ErrUserAlreadyExists = errors.New("user already exists")
|
||||
ErrLegacyDistributionUser = errors.New("user belongs to legacy distribution channel")
|
||||
ErrTokenVersionMismatch = errors.New("user token version mismatch")
|
||||
ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
ErrInvalidPhone = errors.New("invalid phone")
|
||||
ErrCaptchaInvalid = errors.New("captcha invalid")
|
||||
ErrCodeRateLimited = errors.New("sms code rate limited")
|
||||
ErrCodeInvalid = errors.New("sms code invalid")
|
||||
ErrSMSSendFailed = errors.New("sms send failed")
|
||||
ErrUserDisabled = errors.New("user disabled")
|
||||
ErrInvalidPassword = errors.New("invalid password")
|
||||
ErrInvalidOldPassword = errors.New("invalid old password")
|
||||
ErrPasswordNotSet = errors.New("password not set")
|
||||
ErrPasswordTooWeak = errors.New("password too weak")
|
||||
ErrLoginLocked = errors.New("login locked")
|
||||
ErrUserAlreadyExists = errors.New("user already exists")
|
||||
ErrTokenVersionMismatch = errors.New("user token version mismatch")
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -309,7 +308,7 @@ func PublicPhone(phone string) string {
|
||||
return fmt.Sprintf("%s****%s", phone[:3], phone[len(phone)-4:])
|
||||
}
|
||||
|
||||
func (s *Service) LoginWithPassword(ctx context.Context, phone, password, clientIP string) (LoginResult, error) {
|
||||
func (s *Service) LoginWithPassword(ctx context.Context, phone, password, clientIP string, siteCode ...string) (LoginResult, error) {
|
||||
if s.redis == nil || s.users == nil {
|
||||
return LoginResult{}, ErrDependencyUnavailable
|
||||
}
|
||||
@@ -326,7 +325,7 @@ func (s *Service) LoginWithPassword(ctx context.Context, phone, password, client
|
||||
return LoginResult{}, ErrLoginLocked
|
||||
}
|
||||
|
||||
user, err := s.users.FindByPhone(ctx, phone)
|
||||
user, err := s.users.FindByPhone(ctx, phone, siteCode...)
|
||||
if IsNotFound(err) {
|
||||
// 用户不存在也计失败次数,避免该接口被用于探测手机号是否已注册
|
||||
_ = recordLoginFailure(ctx, s.redis, tenantID, phone, clientIP)
|
||||
@@ -378,7 +377,7 @@ func (s *Service) SetPassword(ctx context.Context, userID uint64, password, oldP
|
||||
return s.users.SetPassword(ctx, userID, string(hash))
|
||||
}
|
||||
|
||||
func (s *Service) ResetPassword(ctx context.Context, phone, code, newPassword string) error {
|
||||
func (s *Service) ResetPassword(ctx context.Context, phone, code, newPassword string, siteCode ...string) error {
|
||||
if s.redis == nil || s.users == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
@@ -398,7 +397,7 @@ func (s *Service) ResetPassword(ctx context.Context, phone, code, newPassword st
|
||||
return ErrPasswordTooWeak
|
||||
}
|
||||
|
||||
user, err := s.users.FindByPhone(ctx, phone)
|
||||
user, err := s.users.FindByPhone(ctx, phone, siteCode...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -435,7 +434,7 @@ func (s *Service) RegisterWithPassword(ctx context.Context, phone, code, passwor
|
||||
}
|
||||
|
||||
// 已注册的号不允许通过注册流程覆盖密码,避免"注册即改密"接管账号
|
||||
existing, err := s.users.FindByPhone(ctx, phone)
|
||||
existing, err := s.users.FindByPhone(ctx, phone, siteCode...)
|
||||
if err == nil && existing != nil {
|
||||
return LoginResult{}, ErrUserAlreadyExists
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
@@ -109,16 +108,17 @@ func TestLegacyDistributionUserCannotEnterTenantSite(t *testing.T) {
|
||||
if _, err := repo.FindByID(ctx, legacy.ID); err == nil {
|
||||
t.Fatal("tenant site must not load legacy distribution user")
|
||||
}
|
||||
if _, err := repo.FindByPhone(ctx, legacy.Phone); !errors.Is(err, ErrLegacyDistributionUser) {
|
||||
t.Fatalf("legacy phone login error = %v", err)
|
||||
if _, err := repo.FindByPhone(ctx, legacy.Phone); !IsNotFound(err) {
|
||||
t.Fatalf("tenant phone login should not resolve legacy user, got %v", err)
|
||||
}
|
||||
if _, err := repo.FindOrCreateByPhone(ctx, legacy.Phone, ""); !errors.Is(err, ErrLegacyDistributionUser) {
|
||||
t.Fatalf("legacy SMS login error = %v", err)
|
||||
mainUser, err := repo.FindOrCreateByPhone(ctx, legacy.Phone, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create tenant user with legacy phone: %v", err)
|
||||
}
|
||||
if _, err := repo.RegisterWithPassword(ctx, legacy.Phone, "hash", ""); !errors.Is(err, ErrLegacyDistributionUser) {
|
||||
t.Fatalf("legacy registration error = %v", err)
|
||||
if mainUser.ID == legacy.ID || mainUser.TenantID != legacy.TenantID || mainUser.DistributionSiteID != 0 {
|
||||
t.Fatalf("main user = %+v, legacy = %+v", mainUser, legacy)
|
||||
}
|
||||
if _, err := repo.FindByPhone(context.Background(), legacy.Phone); err != nil {
|
||||
if _, err := repo.FindByPhone(context.Background(), legacy.Phone, site.SiteCode); err != nil {
|
||||
t.Fatalf("legacy distribution domain login failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ type UpdateRequest struct {
|
||||
// EntryDTO 录单记录。
|
||||
type EntryDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
EntryNo string `json:"entry_no"`
|
||||
EntryGroup string `json:"entry_group"`
|
||||
Platform string `json:"platform"`
|
||||
@@ -86,6 +87,7 @@ type CreateResult struct {
|
||||
// OptionDTO 可选项(平台 / 操作人 / 出款实际操作人)。
|
||||
type OptionDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
GroupTag string `json:"group_tag"` // 操作人组别标记:collect/sell/空
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -21,6 +22,10 @@ func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
func manualEntryTenantScope(ctx context.Context, db *gorm.DB, column string) *gorm.DB {
|
||||
return db.Where(column+" = ?", tenancy.IDFromContext(ctx))
|
||||
}
|
||||
|
||||
// FindAdminSnapshot 读取客服的昵称与登录名,用于录单时绑定快照。
|
||||
func (r *Repository) FindAdminSnapshot(ctx context.Context, adminID uint64) (name, username string, err error) {
|
||||
var admin model.AdminUser
|
||||
@@ -36,6 +41,7 @@ func (r *Repository) FindAdminSnapshot(ctx context.Context, adminID uint64) (nam
|
||||
// Create 写入一条录单记录。
|
||||
func (r *Repository) Create(ctx context.Context, adminID uint64, adminName, adminUsername, entryNo, entryGroup, platform, operator, remark string) (*EntryDTO, error) {
|
||||
row := model.CSManualEntry{
|
||||
TenantID: tenancy.IDFromContext(ctx),
|
||||
EntryNo: entryNo,
|
||||
EntryGroup: entryGroup,
|
||||
Platform: platform,
|
||||
@@ -58,7 +64,7 @@ func (r *Repository) Create(ctx context.Context, adminID uint64, adminName, admi
|
||||
// FindByID 按 ID 查询单条录单记录。
|
||||
func (r *Repository) FindByID(ctx context.Context, id uint64) (*EntryDTO, error) {
|
||||
var row model.CSManualEntry
|
||||
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
|
||||
if err := manualEntryTenantScope(ctx, r.db.WithContext(ctx), "tenant_id").First(&row, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrEntryNotFound
|
||||
}
|
||||
@@ -70,7 +76,7 @@ func (r *Repository) FindByID(ctx context.Context, id uint64) (*EntryDTO, error)
|
||||
|
||||
// Update 修正录单的编号、组别、平台、操作人与备注。同组内编号唯一冲突返回 ErrEntryNoExists。
|
||||
func (r *Repository) Update(ctx context.Context, id uint64, entryNo, entryGroup, platform, operator, remark string) (*EntryDTO, error) {
|
||||
result := r.db.WithContext(ctx).Model(&model.CSManualEntry{}).
|
||||
result := manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntry{}), "tenant_id").
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]any{
|
||||
"entry_no": entryNo,
|
||||
@@ -87,7 +93,8 @@ func (r *Repository) Update(ctx context.Context, id uint64, entryNo, entryGroup,
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.CSManualEntry{}).Where("id = ?", id).Count(&count).Error; err != nil {
|
||||
if err := manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntry{}), "tenant_id").
|
||||
Where("id = ?", id).Count(&count).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count == 0 {
|
||||
@@ -99,7 +106,8 @@ func (r *Repository) Update(ctx context.Context, id uint64, entryNo, entryGroup,
|
||||
|
||||
// Delete 删除一条录单记录。
|
||||
func (r *Repository) Delete(ctx context.Context, id uint64) error {
|
||||
result := r.db.WithContext(ctx).Delete(&model.CSManualEntry{}, id)
|
||||
result := manualEntryTenantScope(ctx, r.db.WithContext(ctx), "tenant_id").
|
||||
Delete(&model.CSManualEntry{}, id)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
@@ -111,8 +119,8 @@ func (r *Repository) Delete(ctx context.Context, id uint64) error {
|
||||
|
||||
// List 按条件分页查询录单记录。
|
||||
func (r *Repository) List(ctx context.Context, query ListQuery) (*PaginatedResult, error) {
|
||||
db := r.db.WithContext(ctx).Model(&model.CSManualEntry{})
|
||||
countDB := r.db.WithContext(ctx).Model(&model.CSManualEntry{})
|
||||
db := manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntry{}), "tenant_id")
|
||||
countDB := manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntry{}), "tenant_id")
|
||||
|
||||
// 编号查询:精确匹配该编号,并同时展示其带后缀的变体(如 202611060124-0、202611060124/1)。
|
||||
if query.EntryNo != "" {
|
||||
@@ -189,7 +197,7 @@ func (r *Repository) TodayAgentStats(ctx context.Context, day time.Time) ([]Agen
|
||||
SellCount int64
|
||||
}
|
||||
rows := make([]row, 0)
|
||||
if err := r.db.WithContext(ctx).Table("cs_manual_entries").
|
||||
if err := manualEntryTenantScope(ctx, r.db.WithContext(ctx).Table("cs_manual_entries"), "tenant_id").
|
||||
Select(`admin_id, MAX(admin_name) AS admin_name, COUNT(*) AS count,
|
||||
SUM(CASE WHEN entry_group = 'collect' THEN 1 ELSE 0 END) AS collect_count,
|
||||
SUM(CASE WHEN entry_group = 'sell' THEN 1 ELSE 0 END) AS sell_count`).
|
||||
@@ -225,7 +233,7 @@ func (r *Repository) ListOptions(ctx context.Context, optionType string) ([]Opti
|
||||
return nil, ErrOptionTypeInvalid
|
||||
}
|
||||
rows := make([]model.CSManualEntryOption, 0)
|
||||
if err := r.db.WithContext(ctx).
|
||||
if err := manualEntryTenantScope(ctx, r.db.WithContext(ctx), "tenant_id").
|
||||
Where("type = ?", optionType).
|
||||
Order("sort_order ASC, id ASC").
|
||||
Find(&rows).Error; err != nil {
|
||||
@@ -265,7 +273,12 @@ func (r *Repository) CreateOption(ctx context.Context, optionType, name, groupTa
|
||||
if !IsValidOptionType(optionType) {
|
||||
return nil, ErrOptionTypeInvalid
|
||||
}
|
||||
row := model.CSManualEntryOption{Type: optionType, Name: name, GroupTag: groupTag}
|
||||
row := model.CSManualEntryOption{
|
||||
TenantID: tenancy.IDFromContext(ctx),
|
||||
Type: optionType,
|
||||
Name: name,
|
||||
GroupTag: groupTag,
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(&row).Error; err != nil {
|
||||
if isDuplicateEntry(err) {
|
||||
return nil, ErrOptionExists
|
||||
@@ -279,13 +292,13 @@ func (r *Repository) CreateOption(ctx context.Context, optionType, name, groupTa
|
||||
// UpdateOption 重命名一个选项并可更新组别标记,重名返回 ErrOptionExists。
|
||||
func (r *Repository) UpdateOption(ctx context.Context, id uint64, name, groupTag string) (*OptionDTO, error) {
|
||||
var row model.CSManualEntryOption
|
||||
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
|
||||
if err := manualEntryTenantScope(ctx, r.db.WithContext(ctx), "tenant_id").First(&row, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrOptionNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
result := r.db.WithContext(ctx).Model(&model.CSManualEntryOption{}).
|
||||
result := manualEntryTenantScope(ctx, r.db.WithContext(ctx).Model(&model.CSManualEntryOption{}), "tenant_id").
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]any{
|
||||
"name": name,
|
||||
@@ -305,7 +318,8 @@ func (r *Repository) UpdateOption(ctx context.Context, id uint64, name, groupTag
|
||||
|
||||
// DeleteOption 删除一个选项(历史录单里的名称快照不受影响)。
|
||||
func (r *Repository) DeleteOption(ctx context.Context, id uint64) error {
|
||||
result := r.db.WithContext(ctx).Delete(&model.CSManualEntryOption{}, id)
|
||||
result := manualEntryTenantScope(ctx, r.db.WithContext(ctx), "tenant_id").
|
||||
Delete(&model.CSManualEntryOption{}, id)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
@@ -340,6 +354,7 @@ func isDuplicateEntry(err error) bool {
|
||||
func toDTO(row model.CSManualEntry) EntryDTO {
|
||||
return EntryDTO{
|
||||
ID: row.ID,
|
||||
TenantID: row.TenantID,
|
||||
EntryNo: row.EntryNo,
|
||||
EntryGroup: row.EntryGroup,
|
||||
Platform: row.Platform,
|
||||
@@ -355,6 +370,7 @@ func toDTO(row model.CSManualEntry) EntryDTO {
|
||||
func toOptionDTO(row model.CSManualEntryOption) OptionDTO {
|
||||
return OptionDTO{
|
||||
ID: row.ID,
|
||||
TenantID: row.TenantID,
|
||||
Type: row.Type,
|
||||
Name: row.Name,
|
||||
GroupTag: row.GroupTag,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package csmanualentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
func manualEntryTenantContext(tenantID uint64) context.Context {
|
||||
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
|
||||
func TestManualEntriesAndOptionsAreScopedByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenants := []model.Tenant{
|
||||
{Code: "manual_entry_a", Name: "录单A站", Status: "active"},
|
||||
{Code: "manual_entry_b", Name: "录单B站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
admin := model.AdminUser{Username: "manual-cs", Nickname: "录单客服", PasswordHash: "x", Status: "active"}
|
||||
if err := db.Create(&admin).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
ctxA := manualEntryTenantContext(tenants[0].ID)
|
||||
ctxB := manualEntryTenantContext(tenants[1].ID)
|
||||
|
||||
entryA, err := repo.Create(ctxA, admin.ID, admin.Nickname, admin.Username, "SAME-ENTRY", EntryGroupCollect, "平台A", "客服A", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entryB, err := repo.Create(ctxB, admin.ID, admin.Nickname, admin.Username, "SAME-ENTRY", EntryGroupCollect, "平台B", "客服B", "")
|
||||
if err != nil {
|
||||
t.Fatalf("same entry number in another tenant: %v", err)
|
||||
}
|
||||
if entryA.ID == entryB.ID || entryA.TenantID != tenants[0].ID || entryB.TenantID != tenants[1].ID {
|
||||
t.Fatalf("tenant entries A=%+v B=%+v", entryA, entryB)
|
||||
}
|
||||
|
||||
listA, err := repo.List(ctxA, ListQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listB, err := repo.List(ctxB, ListQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if listA.Total != 1 || listA.Items[0].ID != entryA.ID || listB.Total != 1 || listB.Items[0].ID != entryB.ID {
|
||||
t.Fatalf("tenant manual entry lists A=%+v B=%+v", listA, listB)
|
||||
}
|
||||
if _, err := repo.FindByID(ctxB, entryA.ID); !errors.Is(err, ErrEntryNotFound) {
|
||||
t.Fatalf("cross-tenant find error = %v", err)
|
||||
}
|
||||
if _, err := repo.Update(ctxB, entryA.ID, "HACK", EntryGroupSell, "", "", ""); !errors.Is(err, ErrEntryNotFound) {
|
||||
t.Fatalf("cross-tenant update error = %v", err)
|
||||
}
|
||||
if err := repo.Delete(ctxB, entryA.ID); !errors.Is(err, ErrEntryNotFound) {
|
||||
t.Fatalf("cross-tenant delete error = %v", err)
|
||||
}
|
||||
|
||||
optionA, err := repo.CreateOption(ctxA, OptionTypePlatform, "同名平台", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
optionB, err := repo.CreateOption(ctxB, OptionTypePlatform, "同名平台", "")
|
||||
if err != nil {
|
||||
t.Fatalf("same option name in another tenant: %v", err)
|
||||
}
|
||||
if optionA.ID == optionB.ID || optionA.TenantID != tenants[0].ID || optionB.TenantID != tenants[1].ID {
|
||||
t.Fatalf("tenant options A=%+v B=%+v", optionA, optionB)
|
||||
}
|
||||
optionsA, err := repo.ListAllOptions(ctxA)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
optionsB, err := repo.ListAllOptions(ctxB)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(optionsA.Platforms) != 1 || optionsA.Platforms[0].ID != optionA.ID ||
|
||||
len(optionsB.Platforms) != 1 || optionsB.Platforms[0].ID != optionB.ID {
|
||||
t.Fatalf("tenant options list A=%+v B=%+v", optionsA, optionsB)
|
||||
}
|
||||
if _, err := repo.UpdateOption(ctxB, optionA.ID, "越权", ""); !errors.Is(err, ErrOptionNotFound) {
|
||||
t.Fatalf("cross-tenant option update error = %v", err)
|
||||
}
|
||||
if err := repo.DeleteOption(ctxB, optionA.ID); !errors.Is(err, ErrOptionNotFound) {
|
||||
t.Fatalf("cross-tenant option delete error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -27,8 +27,8 @@ type ObjectAuthorizer func(ctx context.Context, userID uint64, key string) (bool
|
||||
// AdminObjectAuthorizer 校验管理员是否可在当前经营站点读取指定私有对象。
|
||||
type AdminObjectAuthorizer func(ctx context.Context, adminID uint64, key string) (bool, error)
|
||||
|
||||
// UploadOwnerRecorder 保存用户上传私有文件的归属。
|
||||
type UploadOwnerRecorder func(ctx context.Context, userID uint64, objectKeys []string) error
|
||||
// UploadOwnerRecorder 保存用户或管理员上传私有文件的归属。
|
||||
type UploadOwnerRecorder func(ctx context.Context, userID, adminID uint64, objectKeys []string) error
|
||||
|
||||
func NewHandler(service *Service, storage *Storage, objectAuthorizer ObjectAuthorizer, uploadOwnerRecorder UploadOwnerRecorder, adminObjectAuthorizers ...AdminObjectAuthorizer) *Handler {
|
||||
var adminObjectAuthorizer AdminObjectAuthorizer
|
||||
@@ -69,9 +69,27 @@ func (h *Handler) Upload(c *gin.Context) {
|
||||
writeFileError(c, err)
|
||||
return
|
||||
}
|
||||
if userID, ok := c.Get("user_id"); ok && h.uploadOwnerRecorder != nil {
|
||||
id, valid := userID.(uint64)
|
||||
if !valid || h.uploadOwnerRecorder(c.Request.Context(), id, item.ObjectKeys()) != nil {
|
||||
if h.uploadOwnerRecorder != nil {
|
||||
var userID uint64
|
||||
if value, exists := c.Get("user_id"); exists {
|
||||
id, ok := value.(uint64)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "用户上下文无效")
|
||||
return
|
||||
}
|
||||
userID = id
|
||||
}
|
||||
var adminID uint64
|
||||
if value, exists := c.Get("admin_id"); exists {
|
||||
id, ok := value.(uint64)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "管理员上下文无效")
|
||||
return
|
||||
}
|
||||
adminID = id
|
||||
}
|
||||
if (userID > 0 || adminID > 0) &&
|
||||
h.uploadOwnerRecorder(c.Request.Context(), userID, adminID, item.ObjectKeys()) != nil {
|
||||
// 归属记录失败时补偿删除刚写入的对象,避免用户重试产生孤儿文件。
|
||||
if h.storage != nil {
|
||||
if removeErr := h.storage.RemoveObjects(c.Request.Context(), item.ObjectKeys()); removeErr != nil {
|
||||
|
||||
@@ -51,6 +51,13 @@ var (
|
||||
|
||||
type PickupDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
TenantCode string `json:"tenant_code"`
|
||||
TenantName string `json:"tenant_name"`
|
||||
SourceTenantID uint64 `json:"source_tenant_id"`
|
||||
SourceTenantCode string `json:"source_tenant_code"`
|
||||
SourceTenantName string `json:"source_tenant_name"`
|
||||
IsCrossTenant bool `json:"is_cross_tenant"`
|
||||
PickupNo string `json:"pickup_no"`
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
ListingNo string `json:"listing_no"`
|
||||
@@ -98,6 +105,7 @@ type PickupDTO struct {
|
||||
|
||||
type FinancialAdjustmentDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
PickupID uint64 `json:"pickup_id"`
|
||||
ProfitDeltaCent int64 `json:"profit_delta_cent"`
|
||||
SettleDeltaCent int64 `json:"settle_delta_cent"`
|
||||
@@ -246,6 +254,10 @@ type SellerPickupQuery struct {
|
||||
|
||||
type AvailableListingDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
SourceTenantID uint64 `json:"source_tenant_id"`
|
||||
SourceTenantCode string `json:"source_tenant_code"`
|
||||
SourceTenantName string `json:"source_tenant_name"`
|
||||
IsCrossTenant bool `json:"is_cross_tenant"`
|
||||
ListingNo string `json:"listing_no"`
|
||||
AccountID uint64 `json:"account_id"`
|
||||
AccountTitle string `json:"account_title"`
|
||||
|
||||
@@ -97,19 +97,26 @@ func (r *Repository) RecordAdminPickupExport(
|
||||
}
|
||||
|
||||
func (r *Repository) adminPickupExportQuery(ctx context.Context) *gorm.DB {
|
||||
return r.db.WithContext(ctx).Table("admin_pickups AS p").
|
||||
Select(`p.id, p.pickup_no, p.listing_id, p.account_id, p.owner_id, p.admin_id,
|
||||
db := r.db.WithContext(ctx).Table("admin_pickups AS p").
|
||||
Select(`p.id, p.tenant_id, p.source_tenant_id, p.pickup_no, p.listing_id, p.account_id, p.owner_id, p.admin_id,
|
||||
p.operator, p.platform, p.third_party_order_no, p.shop_name, p.raw_shop_name,
|
||||
p.account_source, p.source_channel, p.settlement_mode,
|
||||
p.order_amount_cent, p.deposit_amount_cent, p.profit_amount_cent, p.settle_amount_cent,
|
||||
p.status, p.offline_settlement_status, p.remark, p.complete_remark,
|
||||
p.created_at, p.completed_at, p.cancelled_at,
|
||||
l.listing_no, a.title AS account_title, a.server_region, a.login_platform, owner.phone AS owner_phone,
|
||||
COALESCE(pickup_tenant.code, '') AS tenant_code,
|
||||
COALESCE(pickup_tenant.name, '') AS tenant_name,
|
||||
COALESCE(source_tenant.code, '') AS source_tenant_code,
|
||||
COALESCE(source_tenant.name, '') AS source_tenant_name,
|
||||
COALESCE((SELECT SUM(fa.profit_delta_cent) FROM admin_pickup_financial_adjustments AS fa WHERE fa.pickup_id = p.id), 0) AS profit_adjustment_cent,
|
||||
COALESCE((SELECT SUM(fa.settle_delta_cent) FROM admin_pickup_financial_adjustments AS fa WHERE fa.pickup_id = p.id), 0) AS settle_adjustment_cent`).
|
||||
Joins("JOIN rental_listings AS l ON l.id = p.listing_id").
|
||||
Joins("JOIN game_accounts AS a ON a.id = p.account_id").
|
||||
Joins("JOIN users AS owner ON owner.id = p.owner_id")
|
||||
Joins("JOIN users AS owner ON owner.id = p.owner_id").
|
||||
Joins("LEFT JOIN tenants AS pickup_tenant ON pickup_tenant.id = p.tenant_id").
|
||||
Joins("LEFT JOIN tenants AS source_tenant ON source_tenant.id = p.source_tenant_id")
|
||||
return pickupTenantScope(ctx, db, "p.tenant_id")
|
||||
}
|
||||
|
||||
func buildAdminPickupCSV(items []PickupDTO) ([]byte, error) {
|
||||
|
||||
@@ -51,7 +51,7 @@ func appendPickupEvent(tx *gorm.DB, pickup model.AdminPickup, action string, adm
|
||||
|
||||
func (r *Repository) ProcessEvents(ctx context.Context, pickupID uint64) ([]ProcessEventDTO, error) {
|
||||
var pickup model.AdminPickup
|
||||
if err := r.db.WithContext(ctx).First(&pickup, pickupID).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, r.db.WithContext(ctx), "tenant_id").First(&pickup, pickupID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := processlog.List(r.db.WithContext(ctx), processBusinessPickup, pickupID)
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"hfb_sys/backend/internal/modules/notification"
|
||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
"hfb_sys/backend/pkg/money"
|
||||
|
||||
@@ -34,6 +35,10 @@ func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
func pickupTenantScope(ctx context.Context, db *gorm.DB, column string) *gorm.DB {
|
||||
return db.Where(column+" = ?", tenancy.IDFromContext(ctx))
|
||||
}
|
||||
|
||||
// Create 创建提号订单(状态:提号中)。
|
||||
// 与正常订单支付成功一致:listing 置 rented + in_transaction,从商品管理「已上架」中移出。
|
||||
// 不结算、不动钱包。
|
||||
@@ -92,8 +97,15 @@ func (r *Repository) Create(ctx context.Context, req CreateRequest, adminID uint
|
||||
}
|
||||
}
|
||||
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
sourceTenantID := listing.SourceTenantID
|
||||
if sourceTenantID == 0 {
|
||||
sourceTenantID = tenantID
|
||||
}
|
||||
pickup := model.AdminPickup{
|
||||
PickupNo: pickupNo,
|
||||
TenantID: tenantID,
|
||||
SourceTenantID: sourceTenantID,
|
||||
ListingID: listing.ID,
|
||||
AccountID: listing.AccountID,
|
||||
OwnerID: listing.OwnerID,
|
||||
@@ -122,6 +134,8 @@ func (r *Repository) Create(ctx context.Context, req CreateRequest, adminID uint
|
||||
return err
|
||||
}
|
||||
if err := appendPickupEvent(tx, pickup, "pickup_created", adminID, "管理员创建线下提号。", pickup.Remark, map[string]any{
|
||||
"tenant_id": pickup.TenantID,
|
||||
"source_tenant_id": pickup.SourceTenantID,
|
||||
"listing_price_cent": pickup.ListingPriceCent,
|
||||
"order_amount_cent": pickup.OrderAmountCent,
|
||||
"deposit_amount_cent": pickup.DepositAmountCent,
|
||||
@@ -180,6 +194,8 @@ func (r *Repository) Create(ctx context.Context, req CreateRequest, adminID uint
|
||||
Meta: meta,
|
||||
Detail: map[string]any{
|
||||
"pickup_no": pickupNo,
|
||||
"tenant_id": pickup.TenantID,
|
||||
"source_tenant_id": pickup.SourceTenantID,
|
||||
"listing_id": listing.ID,
|
||||
"platform": pickup.Platform,
|
||||
"third_party_order_no": pickup.ThirdPartyOrderNo,
|
||||
@@ -212,7 +228,8 @@ func (r *Repository) Complete(ctx context.Context, pickupID uint64, req Complete
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var pickup model.AdminPickup
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrPickupNotFound
|
||||
}
|
||||
@@ -382,7 +399,8 @@ func (r *Repository) MarkOfflineSettlement(ctx context.Context, pickupID uint64,
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var pickup model.AdminPickup
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrPickupNotFound
|
||||
}
|
||||
@@ -462,7 +480,8 @@ func (r *Repository) UpdateProfit(ctx context.Context, pickupID uint64, req Upda
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var pickup model.AdminPickup
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrPickupNotFound
|
||||
}
|
||||
@@ -517,7 +536,8 @@ func (r *Repository) UpdateThirdPartyOrderNo(ctx context.Context, pickupID uint6
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var pickup model.AdminPickup
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrPickupNotFound
|
||||
}
|
||||
@@ -568,7 +588,8 @@ func (r *Repository) CreateFinancialAdjustment(ctx context.Context, pickupID uin
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var pickup model.AdminPickup
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrPickupNotFound
|
||||
}
|
||||
@@ -607,6 +628,7 @@ func (r *Repository) CreateFinancialAdjustment(ctx context.Context, pickupID uin
|
||||
}
|
||||
}
|
||||
adjustment := model.AdminPickupFinancialAdjustment{
|
||||
TenantID: pickup.TenantID,
|
||||
PickupID: pickup.ID,
|
||||
ProfitDeltaCent: profitDeltaCent,
|
||||
SettleDeltaCent: settleDeltaCent,
|
||||
@@ -672,14 +694,15 @@ func (r *Repository) ListFinancialAdjustments(ctx context.Context, pickupID uint
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.AdminPickup{}).Where("id = ?", pickupID).Count(&count).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.AdminPickup{}), "tenant_id").
|
||||
Where("id = ?", pickupID).Count(&count).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count == 0 {
|
||||
return nil, ErrPickupNotFound
|
||||
}
|
||||
items := make([]FinancialAdjustmentDTO, 0)
|
||||
if err := r.db.WithContext(ctx).Model(&model.AdminPickupFinancialAdjustment{}).
|
||||
if err := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.AdminPickupFinancialAdjustment{}), "tenant_id").
|
||||
Where("pickup_id = ?", pickupID).
|
||||
Order("id DESC").
|
||||
Find(&items).Error; err != nil {
|
||||
@@ -695,7 +718,8 @@ func (r *Repository) SettleFinancialAdjustment(ctx context.Context, adjustmentID
|
||||
}
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var adjustment model.AdminPickupFinancialAdjustment
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&adjustment, adjustmentID).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).First(&adjustment, adjustmentID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrFinancialAdjustmentNotFound
|
||||
}
|
||||
@@ -714,7 +738,7 @@ func (r *Repository) SettleFinancialAdjustment(ctx context.Context, adjustmentID
|
||||
return err
|
||||
}
|
||||
var pickup model.AdminPickup
|
||||
if err := tx.First(&pickup, adjustment.PickupID).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").First(&pickup, adjustment.PickupID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := appendPickupEvent(tx, pickup, "pickup_adjustment_settled", adminID, "确认提号财务调整已处理。", adjustment.SettlementRemark, map[string]any{
|
||||
@@ -751,7 +775,8 @@ func (r *Repository) Cancel(ctx context.Context, pickupID uint64, reason string,
|
||||
}
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var pickup model.AdminPickup
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).First(&pickup, pickupID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrPickupNotFound
|
||||
}
|
||||
@@ -827,7 +852,7 @@ func (r *Repository) FindByID(ctx context.Context, id uint64) (*PickupDTO, error
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
var row pickupRow
|
||||
if err := r.baseQuery(ctx).Where("p.id = ?", id).First(&row).Error; err != nil {
|
||||
if err := r.adminBaseQuery(ctx).Where("p.id = ?", id).First(&row).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrPickupNotFound
|
||||
}
|
||||
@@ -870,8 +895,11 @@ func applyAdminPickupFilters(db *gorm.DB, query AdminPickupQuery) *gorm.DB {
|
||||
if kw := strings.TrimSpace(query.Keyword); kw != "" {
|
||||
upper := strings.ToUpper(kw)
|
||||
if isPhoneKeyword(kw) {
|
||||
// 先由 users(phone) 唯一索引解析用户,再让 admin_pickups(owner_id) 索引驱动。
|
||||
db = db.Where("p.owner_id = (SELECT id FROM users WHERE phone = ?)", kw)
|
||||
// 同手机号可同时存在于多个经营站点,必须按提号单已关联的 owner_id 精确匹配。
|
||||
db = db.Where(
|
||||
"EXISTS (SELECT 1 FROM users AS pickup_owner WHERE pickup_owner.id = p.owner_id AND pickup_owner.phone = ?)",
|
||||
kw,
|
||||
)
|
||||
} else if strings.HasPrefix(upper, "PK") || strings.HasPrefix(upper, "P") {
|
||||
// 提号编号:命中 admin_pickups(pickup_no) 唯一索引
|
||||
db = db.Where("p.pickup_no = ?", kw)
|
||||
@@ -898,25 +926,26 @@ func applyAdminPickupFilters(db *gorm.DB, query AdminPickupQuery) *gorm.DB {
|
||||
}
|
||||
|
||||
func (r *Repository) adminPickupCountQuery(ctx context.Context, query AdminPickupQuery) *gorm.DB {
|
||||
base := pickupTenantScope(ctx, r.db.WithContext(ctx).Table("admin_pickups AS p"), "p.tenant_id")
|
||||
kw := strings.TrimSpace(query.Keyword)
|
||||
if kw == "" {
|
||||
return r.db.WithContext(ctx).Table("admin_pickups AS p")
|
||||
return base
|
||||
}
|
||||
upper := strings.ToUpper(kw)
|
||||
if strings.HasPrefix(upper, "PK") || strings.HasPrefix(upper, "P") {
|
||||
return r.db.WithContext(ctx).Table("admin_pickups AS p")
|
||||
return base
|
||||
}
|
||||
if id, err := strconv.ParseUint(kw, 10, 64); err == nil && id > 0 && kw[0] != '0' && id < 100000000 {
|
||||
return r.db.WithContext(ctx).Table("admin_pickups AS p")
|
||||
return base
|
||||
}
|
||||
if isPhoneKeyword(kw) {
|
||||
return r.db.WithContext(ctx).Table("admin_pickups AS p")
|
||||
return base
|
||||
}
|
||||
if strings.HasPrefix(upper, "L") || (len(kw) >= 12 && isAllDigits(kw)) {
|
||||
return r.db.WithContext(ctx).Table("admin_pickups AS p").
|
||||
return base.
|
||||
Joins("JOIN rental_listings AS l ON l.id = p.listing_id")
|
||||
}
|
||||
return r.db.WithContext(ctx).Table("admin_pickups AS p").
|
||||
return base.
|
||||
Joins("JOIN rental_listings AS l ON l.id = p.listing_id").
|
||||
Joins("JOIN game_accounts AS a ON a.id = p.account_id").
|
||||
Joins("JOIN users AS owner ON owner.id = p.owner_id")
|
||||
@@ -930,7 +959,7 @@ func (r *Repository) ListAdmin(ctx context.Context, query AdminPickupQuery) (*Pa
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
var rows []pickupRow
|
||||
db := applyAdminPickupFilters(r.baseQuery(ctx), query)
|
||||
db := applyAdminPickupFilters(r.adminBaseQuery(ctx), query)
|
||||
if err := db.Order("p.id DESC").Offset(offset).Limit(pageSize).Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -966,7 +995,8 @@ func (r *Repository) ListShopNames(ctx context.Context, platform string) ([]stri
|
||||
seen := make(map[string]struct{})
|
||||
|
||||
// 1. 查询店铺配置表中的 active 店铺
|
||||
shopDB := r.db.WithContext(ctx).Model(&model.PickupShop{}).Where("status = ?", PickupShopStatusActive)
|
||||
shopDB := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.PickupShop{}), "tenant_id").
|
||||
Where("status = ?", PickupShopStatusActive)
|
||||
if val := strings.TrimSpace(platform); val != "" {
|
||||
shopDB = shopDB.Where("platform = ? OR platform = ''", val)
|
||||
}
|
||||
@@ -984,7 +1014,8 @@ func (r *Repository) ListShopNames(ctx context.Context, platform string) ([]stri
|
||||
}
|
||||
|
||||
// 2. 查询 admin_pickups 中的历史店铺作为补充
|
||||
historyDB := r.db.WithContext(ctx).Model(&model.AdminPickup{}).Where("shop_name <> ''")
|
||||
historyDB := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.AdminPickup{}), "tenant_id").
|
||||
Where("shop_name <> ''")
|
||||
if val := strings.TrimSpace(platform); val != "" {
|
||||
historyDB = historyDB.Where("platform = ?", val)
|
||||
}
|
||||
@@ -1010,7 +1041,7 @@ func (r *Repository) ListShops(ctx context.Context, query PickupShopQuery) ([]Pi
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
db := r.db.WithContext(ctx).Model(&model.PickupShop{})
|
||||
db := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.PickupShop{}), "tenant_id")
|
||||
if kw := strings.TrimSpace(query.Keyword); kw != "" {
|
||||
like := "%" + kw + "%"
|
||||
db = db.Where("name LIKE ? OR remark LIKE ?", like, like)
|
||||
@@ -1051,7 +1082,9 @@ func (r *Repository) CreateShop(ctx context.Context, req CreatePickupShopRequest
|
||||
return nil, ErrInvalidAmount
|
||||
}
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.PickupShop{}).Where("name = ?", name).Count(&count).Error; err != nil {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if err := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.PickupShop{}), "tenant_id").
|
||||
Where("name = ?", name).Count(&count).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count > 0 {
|
||||
@@ -1063,6 +1096,7 @@ func (r *Repository) CreateShop(ctx context.Context, req CreatePickupShopRequest
|
||||
}
|
||||
now := time.Now()
|
||||
shop := model.PickupShop{
|
||||
TenantID: tenantID,
|
||||
Name: name,
|
||||
Platform: strings.TrimSpace(req.Platform),
|
||||
Status: status,
|
||||
@@ -1083,10 +1117,11 @@ func (r *Repository) CreateShop(ctx context.Context, req CreatePickupShopRequest
|
||||
BizID: &bid,
|
||||
Meta: meta,
|
||||
Detail: map[string]any{
|
||||
"shop_id": shop.ID,
|
||||
"name": shop.Name,
|
||||
"platform": shop.Platform,
|
||||
"status": shop.Status,
|
||||
"tenant_id": tenantID,
|
||||
"shop_id": shop.ID,
|
||||
"name": shop.Name,
|
||||
"platform": shop.Platform,
|
||||
"status": shop.Status,
|
||||
},
|
||||
})
|
||||
return &PickupShopDTO{
|
||||
@@ -1111,14 +1146,15 @@ func (r *Repository) UpdateShop(ctx context.Context, id uint64, req UpdatePickup
|
||||
return nil, ErrInvalidAmount
|
||||
}
|
||||
var shop model.PickupShop
|
||||
if err := r.db.WithContext(ctx).First(&shop, id).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, r.db.WithContext(ctx), "tenant_id").First(&shop, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrPickupShopNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.PickupShop{}).Where("name = ? AND id <> ?", name, id).Count(&count).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.PickupShop{}), "tenant_id").
|
||||
Where("name = ? AND id <> ?", name, id).Count(&count).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count > 0 {
|
||||
@@ -1142,10 +1178,11 @@ func (r *Repository) UpdateShop(ctx context.Context, id uint64, req UpdatePickup
|
||||
BizID: &bid,
|
||||
Meta: meta,
|
||||
Detail: map[string]any{
|
||||
"shop_id": shop.ID,
|
||||
"name": shop.Name,
|
||||
"platform": shop.Platform,
|
||||
"status": shop.Status,
|
||||
"tenant_id": shop.TenantID,
|
||||
"shop_id": shop.ID,
|
||||
"name": shop.Name,
|
||||
"platform": shop.Platform,
|
||||
"status": shop.Status,
|
||||
},
|
||||
})
|
||||
return &PickupShopDTO{
|
||||
@@ -1166,7 +1203,7 @@ func (r *Repository) DeleteShop(ctx context.Context, id uint64, adminID uint64,
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
var shop model.PickupShop
|
||||
if err := r.db.WithContext(ctx).First(&shop, id).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, r.db.WithContext(ctx), "tenant_id").First(&shop, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrPickupShopNotFound
|
||||
}
|
||||
@@ -1184,8 +1221,9 @@ func (r *Repository) DeleteShop(ctx context.Context, id uint64, adminID uint64,
|
||||
BizID: &bid,
|
||||
Meta: meta,
|
||||
Detail: map[string]any{
|
||||
"shop_id": shop.ID,
|
||||
"name": shop.Name,
|
||||
"tenant_id": shop.TenantID,
|
||||
"shop_id": shop.ID,
|
||||
"name": shop.Name,
|
||||
},
|
||||
})
|
||||
return nil
|
||||
@@ -1202,7 +1240,7 @@ func (r *Repository) GetHistoricalShopStats(ctx context.Context) (*PickupShopHis
|
||||
Cnt int64 `gorm:"column:cnt"`
|
||||
}
|
||||
var rows []rawCountRow
|
||||
err := r.db.WithContext(ctx).Model(&model.AdminPickup{}).
|
||||
err := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.AdminPickup{}), "tenant_id").
|
||||
Select("CASE WHEN raw_shop_name <> '' THEN raw_shop_name ELSE shop_name END AS source_name, COUNT(*) AS cnt").
|
||||
Group("source_name").
|
||||
Order("cnt DESC, source_name ASC").
|
||||
@@ -1212,7 +1250,8 @@ func (r *Repository) GetHistoricalShopStats(ctx context.Context) (*PickupShopHis
|
||||
}
|
||||
|
||||
var standardShops []model.PickupShop
|
||||
if err := r.db.WithContext(ctx).Model(&model.PickupShop{}).Find(&standardShops).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.PickupShop{}), "tenant_id").
|
||||
Find(&standardShops).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
standardMap := make(map[string]model.PickupShop)
|
||||
@@ -1221,7 +1260,8 @@ func (r *Repository) GetHistoricalShopStats(ctx context.Context) (*PickupShopHis
|
||||
}
|
||||
|
||||
var mappings []model.PickupShopMapping
|
||||
if err := r.db.WithContext(ctx).Model(&model.PickupShopMapping{}).Find(&mappings).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, r.db.WithContext(ctx).Model(&model.PickupShopMapping{}), "tenant_id").
|
||||
Find(&mappings).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mappingMap := make(map[string]model.PickupShopMapping)
|
||||
@@ -1314,16 +1354,18 @@ func (r *Repository) MapHistoricalShops(ctx context.Context, req MapHistoricalSh
|
||||
|
||||
var result MapHistoricalShopsResultDTO
|
||||
result.TargetShopName = targetName
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var targetShop model.PickupShop
|
||||
findErr := tx.Where("name = ?", targetName).First(&targetShop).Error
|
||||
findErr := pickupTenantScope(ctx, tx, "tenant_id").Where("name = ?", targetName).First(&targetShop).Error
|
||||
if errors.Is(findErr, gorm.ErrRecordNotFound) {
|
||||
if !req.CreateTargetMissing {
|
||||
return ErrPickupShopNotFound
|
||||
}
|
||||
now := time.Now()
|
||||
targetShop = model.PickupShop{
|
||||
TenantID: tenantID,
|
||||
Name: targetName,
|
||||
Platform: strings.TrimSpace(req.TargetPlatform),
|
||||
Status: PickupShopStatusActive,
|
||||
@@ -1345,12 +1387,13 @@ func (r *Repository) MapHistoricalShops(ctx context.Context, req MapHistoricalSh
|
||||
if err := tx.Exec(`UPDATE admin_pickups
|
||||
SET raw_shop_name = shop_name
|
||||
WHERE (raw_shop_name = '' OR raw_shop_name IS NULL)
|
||||
AND (shop_name IN ? OR (shop_name = '' AND '' IN ?))`, fromNames, fromNames).Error; err != nil {
|
||||
AND tenant_id = ?
|
||||
AND (shop_name IN ? OR (shop_name = '' AND '' IN ?))`, tenantID, fromNames, fromNames).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 批量更新 admin_pickups 的 shop_name
|
||||
res := tx.Model(&model.AdminPickup{}).
|
||||
res := pickupTenantScope(ctx, tx.Model(&model.AdminPickup{}), "tenant_id").
|
||||
Where("raw_shop_name IN ?", fromNames).
|
||||
Update("shop_name", targetName)
|
||||
if res.Error != nil {
|
||||
@@ -1364,11 +1407,14 @@ func (r *Repository) MapHistoricalShops(ctx context.Context, req MapHistoricalSh
|
||||
continue
|
||||
}
|
||||
var mappedCount int64
|
||||
tx.Model(&model.AdminPickup{}).Where("raw_shop_name = ?", fromName).Count(&mappedCount)
|
||||
pickupTenantScope(ctx, tx.Model(&model.AdminPickup{}), "tenant_id").
|
||||
Where("raw_shop_name = ?", fromName).Count(&mappedCount)
|
||||
|
||||
var existing model.PickupShopMapping
|
||||
if err := tx.Where("source_name = ?", fromName).First(&existing).Error; errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").
|
||||
Where("source_name = ?", fromName).First(&existing).Error; errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
newMapping := model.PickupShopMapping{
|
||||
TenantID: tenantID,
|
||||
SourceName: fromName,
|
||||
TargetShopID: targetShop.ID,
|
||||
TargetShopName: targetName,
|
||||
@@ -1405,6 +1451,7 @@ func (r *Repository) MapHistoricalShops(ctx context.Context, req MapHistoricalSh
|
||||
BizID: &bid,
|
||||
Meta: meta,
|
||||
Detail: map[string]any{
|
||||
"tenant_id": tenantID,
|
||||
"target_shop_id": targetShop.ID,
|
||||
"target_shop_name": targetName,
|
||||
"from_shop_names": fromNames,
|
||||
@@ -1428,13 +1475,14 @@ func (r *Repository) DeleteShopMapping(ctx context.Context, sourceName string, a
|
||||
}
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var mapping model.PickupShopMapping
|
||||
if err := tx.Where("source_name = ?", sourceName).First(&mapping).Error; err != nil {
|
||||
if err := pickupTenantScope(ctx, tx, "tenant_id").
|
||||
Where("source_name = ?", sourceName).First(&mapping).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&model.AdminPickup{}).
|
||||
if err := pickupTenantScope(ctx, tx.Model(&model.AdminPickup{}), "tenant_id").
|
||||
Where("raw_shop_name = ?", sourceName).
|
||||
Update("shop_name", sourceName).Error; err != nil {
|
||||
return err
|
||||
@@ -1451,6 +1499,7 @@ func (r *Repository) DeleteShopMapping(ctx context.Context, sourceName string, a
|
||||
BizID: &bid,
|
||||
Meta: meta,
|
||||
Detail: map[string]any{
|
||||
"tenant_id": mapping.TenantID,
|
||||
"source_name": sourceName,
|
||||
"target_shop_name": mapping.TargetShopName,
|
||||
},
|
||||
@@ -1517,9 +1566,11 @@ func (r *Repository) ListAvailableListings(ctx context.Context, query AvailableL
|
||||
q := r.db.WithContext(ctx).Table("rental_listings AS l").
|
||||
Joins("JOIN game_accounts AS a ON a.id = l.account_id").
|
||||
Joins("JOIN users AS owner ON owner.id = l.owner_id").
|
||||
Joins("LEFT JOIN tenants AS source_tenant ON source_tenant.id = l.source_tenant_id").
|
||||
Joins("LEFT JOIN (?) AS latest_upload ON latest_upload.listing_id = l.id", latestUploads).
|
||||
Joins("LEFT JOIN listing_uploads AS lu ON lu.id = latest_upload.upload_id").
|
||||
Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false)
|
||||
Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false).
|
||||
Where("(l.distribution_site_id IS NULL OR l.distribution_site_id = 0)")
|
||||
if kw := strings.TrimSpace(query.Keyword); kw != "" {
|
||||
upper := strings.ToUpper(kw)
|
||||
if strings.HasPrefix(upper, "L") || (len(kw) >= 12 && isAllDigits(kw)) {
|
||||
@@ -1540,7 +1591,10 @@ func (r *Repository) ListAvailableListings(ctx context.Context, query AvailableL
|
||||
|
||||
page, pageSize := normalizePaging(query.Page, query.PageSize)
|
||||
var rows []availableListingRow
|
||||
if err := buildQuery().Select(`l.id, l.listing_no, l.account_id, l.owner_id, l.price_cent AS listing_price_cent,
|
||||
if err := buildQuery().Select(`l.id, l.source_tenant_id,
|
||||
COALESCE(source_tenant.code, '') AS source_tenant_code,
|
||||
COALESCE(source_tenant.name, '') AS source_tenant_name,
|
||||
l.listing_no, l.account_id, l.owner_id, l.price_cent AS listing_price_cent,
|
||||
a.title AS account_title, a.server_region, a.login_platform, a.haf_coin_amount, a.asset_summary,
|
||||
owner.phone AS owner_phone, l.handoff_mode, l.settlement_mode,
|
||||
CASE WHEN lu.id IS NULL THEN 0 ELSE 1 END AS is_external_upload,
|
||||
@@ -1557,8 +1611,11 @@ func (r *Repository) ListAvailableListings(ctx context.Context, query AvailableL
|
||||
}
|
||||
}
|
||||
items := make([]AvailableListingDTO, 0, len(rows))
|
||||
currentTenantID := tenancy.IDFromContext(ctx)
|
||||
for _, row := range rows {
|
||||
items = append(items, row.toDTO())
|
||||
item := row.toDTO()
|
||||
item.IsCrossTenant = currentTenantID > 0 && item.SourceTenantID > 0 && item.SourceTenantID != currentTenantID
|
||||
items = append(items, item)
|
||||
}
|
||||
return &AvailableListingsResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
|
||||
}
|
||||
@@ -1566,15 +1623,29 @@ func (r *Repository) ListAvailableListings(ctx context.Context, query AvailableL
|
||||
func (r *Repository) baseQuery(ctx context.Context) *gorm.DB {
|
||||
return r.db.WithContext(ctx).Table("admin_pickups AS p").
|
||||
Select(`p.*, l.listing_no, a.title AS account_title, a.server_region, a.login_platform, owner.phone AS owner_phone,
|
||||
COALESCE(pickup_tenant.code, '') AS tenant_code,
|
||||
COALESCE(pickup_tenant.name, '') AS tenant_name,
|
||||
COALESCE(source_tenant.code, '') AS source_tenant_code,
|
||||
COALESCE(source_tenant.name, '') AS source_tenant_name,
|
||||
COALESCE((SELECT SUM(fa.profit_delta_cent) FROM admin_pickup_financial_adjustments AS fa WHERE fa.pickup_id = p.id), 0) AS profit_adjustment_cent,
|
||||
COALESCE((SELECT SUM(fa.settle_delta_cent) FROM admin_pickup_financial_adjustments AS fa WHERE fa.pickup_id = p.id), 0) AS settle_adjustment_cent`).
|
||||
Joins("JOIN rental_listings AS l ON l.id = p.listing_id").
|
||||
Joins("JOIN game_accounts AS a ON a.id = p.account_id").
|
||||
Joins("JOIN users AS owner ON owner.id = p.owner_id")
|
||||
Joins("JOIN users AS owner ON owner.id = p.owner_id").
|
||||
Joins("LEFT JOIN tenants AS pickup_tenant ON pickup_tenant.id = p.tenant_id").
|
||||
Joins("LEFT JOIN tenants AS source_tenant ON source_tenant.id = p.source_tenant_id")
|
||||
}
|
||||
|
||||
func (r *Repository) adminBaseQuery(ctx context.Context) *gorm.DB {
|
||||
return pickupTenantScope(ctx, r.baseQuery(ctx), "p.tenant_id")
|
||||
}
|
||||
|
||||
type pickupRow struct {
|
||||
model.AdminPickup
|
||||
TenantCode string
|
||||
TenantName string
|
||||
SourceTenantCode string
|
||||
SourceTenantName string
|
||||
ListingNo string
|
||||
AccountTitle string
|
||||
ServerRegion string
|
||||
@@ -1587,6 +1658,13 @@ type pickupRow struct {
|
||||
func (row pickupRow) toDTO() PickupDTO {
|
||||
return PickupDTO{
|
||||
ID: row.ID,
|
||||
TenantID: row.TenantID,
|
||||
TenantCode: row.TenantCode,
|
||||
TenantName: row.TenantName,
|
||||
SourceTenantID: row.SourceTenantID,
|
||||
SourceTenantCode: row.SourceTenantCode,
|
||||
SourceTenantName: row.SourceTenantName,
|
||||
IsCrossTenant: row.TenantID > 0 && row.SourceTenantID > 0 && row.TenantID != row.SourceTenantID,
|
||||
PickupNo: row.PickupNo,
|
||||
ListingID: row.ListingID,
|
||||
ListingNo: row.ListingNo,
|
||||
@@ -1675,6 +1753,9 @@ func pickupRequiresOfflineSettlement(pickup model.AdminPickup) bool {
|
||||
|
||||
type availableListingRow struct {
|
||||
ID uint64
|
||||
SourceTenantID uint64
|
||||
SourceTenantCode string
|
||||
SourceTenantName string
|
||||
ListingNo string
|
||||
AccountID uint64
|
||||
AccountTitle string
|
||||
@@ -1702,6 +1783,9 @@ func (row availableListingRow) toDTO() AvailableListingDTO {
|
||||
}
|
||||
return AvailableListingDTO{
|
||||
ID: row.ID,
|
||||
SourceTenantID: row.SourceTenantID,
|
||||
SourceTenantCode: row.SourceTenantCode,
|
||||
SourceTenantName: row.SourceTenantName,
|
||||
ListingNo: row.ListingNo,
|
||||
AccountID: row.AccountID,
|
||||
AccountTitle: row.AccountTitle,
|
||||
|
||||
@@ -857,9 +857,9 @@ func TestApplyAdminPickupFiltersSmartRouting(t *testing.T) {
|
||||
wantSQLFrag string
|
||||
}{
|
||||
{
|
||||
name: "11位手机号先解析用户再走提号号主索引",
|
||||
name: "11位手机号按提号单号主精确匹配",
|
||||
query: AdminPickupQuery{Keyword: "13800138000"},
|
||||
wantSQLFrag: "p.owner_id = (SELECT id FROM users WHERE phone = ?)",
|
||||
wantSQLFrag: "pickup_owner.id = p.owner_id AND pickup_owner.phone = ?",
|
||||
},
|
||||
{
|
||||
name: "PK前缀提号编号路由至admin_pickups(pickup_no)",
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package pickup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func pickupTenantContext(tenantID uint64) context.Context {
|
||||
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
|
||||
func seedPickupTenantListing(t *testing.T, db *gorm.DB, tenantID uint64, suffix string) model.RentalListing {
|
||||
t.Helper()
|
||||
owner := model.User{
|
||||
TenantID: tenantID,
|
||||
Phone: "1880000" + suffix,
|
||||
Nickname: "号主" + suffix,
|
||||
Status: "active",
|
||||
}
|
||||
if err := db.Create(&owner).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
account := model.GameAccount{
|
||||
SourceTenantID: tenantID,
|
||||
OwnerID: owner.ID,
|
||||
ServerRegion: "测试区",
|
||||
LoginPlatform: "微信",
|
||||
Title: "测试账号" + suffix,
|
||||
Status: "published",
|
||||
}
|
||||
if err := db.Create(&account).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listing := model.RentalListing{
|
||||
SourceTenantID: tenantID,
|
||||
ListingNo: "LST-PICKUP-TENANT-" + suffix,
|
||||
AccountID: account.ID,
|
||||
OwnerID: owner.ID,
|
||||
PriceCent: 10000,
|
||||
Status: "published",
|
||||
ReviewStatus: "approved",
|
||||
HandoffMode: "owner",
|
||||
SettlementMode: "owner_wallet",
|
||||
}
|
||||
if err := db.Create(&listing).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return listing
|
||||
}
|
||||
|
||||
func TestPickupTenantScopeSupportsCrossTenantCreationAndSeparateLists(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenants := []model.Tenant{
|
||||
{Code: "pickup_tenant_a", Name: "提号A站", Status: "active"},
|
||||
{Code: "pickup_tenant_b", Name: "提号B站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tenantA, tenantB := tenants[0], tenants[1]
|
||||
listingFromA := seedPickupTenantListing(t, db, tenantA.ID, "01")
|
||||
listingFromB := seedPickupTenantListing(t, db, tenantB.ID, "02")
|
||||
listingFromBForB := seedPickupTenantListing(t, db, tenantB.ID, "03")
|
||||
|
||||
repo := NewRepository(db)
|
||||
ctxA := pickupTenantContext(tenantA.ID)
|
||||
ctxB := pickupTenantContext(tenantB.ID)
|
||||
|
||||
available, err := repo.ListAvailableListings(ctxA, AvailableListingQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crossSeen := false
|
||||
for _, item := range available.Items {
|
||||
if item.ID == listingFromB.ID {
|
||||
crossSeen = item.IsCrossTenant && item.SourceTenantID == tenantB.ID
|
||||
}
|
||||
}
|
||||
if !crossSeen {
|
||||
t.Fatalf("available listings missing cross tenant source: %+v", available.Items)
|
||||
}
|
||||
|
||||
crossPickup, err := repo.Create(ctxA, CreateRequest{ListingID: listingFromB.ID}, 1, auditlog.Meta{})
|
||||
if err != nil {
|
||||
t.Fatalf("cross tenant pickup: %v", err)
|
||||
}
|
||||
if crossPickup.TenantID != tenantA.ID || crossPickup.SourceTenantID != tenantB.ID || !crossPickup.IsCrossTenant {
|
||||
t.Fatalf("cross pickup scope = %+v", crossPickup)
|
||||
}
|
||||
completedCross, err := repo.Complete(ctxA, crossPickup.ID, CompleteRequest{
|
||||
SettleAmountCent: 8000,
|
||||
CompleteRemark: "跨站提号完成",
|
||||
}, 1, auditlog.Meta{})
|
||||
if err != nil {
|
||||
t.Fatalf("complete cross tenant pickup: %v", err)
|
||||
}
|
||||
if completedCross.Status != StatusCompleted {
|
||||
t.Fatalf("cross pickup status = %s", completedCross.Status)
|
||||
}
|
||||
var ledger model.WalletLedger
|
||||
if err := db.Where("biz_type = ? AND biz_no = ?", "admin_pickup_settle", crossPickup.PickupNo).
|
||||
First(&ledger).Error; err != nil {
|
||||
t.Fatalf("source tenant wallet ledger: %v", err)
|
||||
}
|
||||
if ledger.TenantID != tenantB.ID || ledger.UserID != crossPickup.OwnerID {
|
||||
t.Fatalf("cross pickup wallet ledger = %+v", ledger)
|
||||
}
|
||||
ownPickup, err := repo.Create(ctxA, CreateRequest{ListingID: listingFromA.ID}, 1, auditlog.Meta{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tenantBPickup, err := repo.Create(ctxB, CreateRequest{ListingID: listingFromBForB.ID}, 2, auditlog.Meta{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
listA, err := repo.ListAdmin(ctxA, AdminPickupQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if listA.Total != 2 || len(listA.Items) != 2 {
|
||||
t.Fatalf("tenant A pickups = %+v", listA)
|
||||
}
|
||||
for _, item := range listA.Items {
|
||||
if item.TenantID != tenantA.ID {
|
||||
t.Fatalf("tenant A list leaked pickup: %+v", item)
|
||||
}
|
||||
}
|
||||
listB, err := repo.ListAdmin(ctxB, AdminPickupQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if listB.Total != 1 || listB.Items[0].ID != tenantBPickup.ID {
|
||||
t.Fatalf("tenant B pickups = %+v", listB)
|
||||
}
|
||||
|
||||
if _, err := repo.FindByID(ctxB, ownPickup.ID); !errors.Is(err, ErrPickupNotFound) {
|
||||
t.Fatalf("cross-tenant detail error = %v, want ErrPickupNotFound", err)
|
||||
}
|
||||
if _, err := repo.UpdateProfit(ctxB, ownPickup.ID, UpdateProfitRequest{ProfitAmountCent: 2000}, 2, auditlog.Meta{}); !errors.Is(err, ErrPickupNotFound) {
|
||||
t.Fatalf("cross-tenant update error = %v, want ErrPickupNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPickupShopsAreSeparatedByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenants := []model.Tenant{
|
||||
{Code: "pickup_shop_a", Name: "A站", Status: "active"},
|
||||
{Code: "pickup_shop_b", Name: "B站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
ctxA := pickupTenantContext(tenants[0].ID)
|
||||
ctxB := pickupTenantContext(tenants[1].ID)
|
||||
|
||||
shopA, err := repo.CreateShop(ctxA, CreatePickupShopRequest{Name: "同名店铺"}, 1, auditlog.Meta{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shopB, err := repo.CreateShop(ctxB, CreatePickupShopRequest{Name: "同名店铺"}, 2, auditlog.Meta{})
|
||||
if err != nil {
|
||||
t.Fatalf("same shop name in another tenant: %v", err)
|
||||
}
|
||||
if shopA.ID == shopB.ID {
|
||||
t.Fatal("tenant shops must be separate rows")
|
||||
}
|
||||
itemsA, err := repo.ListShops(ctxA, PickupShopQuery{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
itemsB, err := repo.ListShops(ctxB, PickupShopQuery{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(itemsA) != 1 || len(itemsB) != 1 || itemsA[0].ID != shopA.ID || itemsB[0].ID != shopB.ID {
|
||||
t.Fatalf("tenant shops A=%+v B=%+v", itemsA, itemsB)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPickupTenantScopeSourceTenantFallback(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenant := model.Tenant{Code: "pickup_same", Name: "同站", Status: "active"}
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listing := seedPickupTenantListing(t, db, tenant.ID, "09")
|
||||
repo := NewRepository(db)
|
||||
pickup, err := repo.Create(pickupTenantContext(tenant.ID), CreateRequest{ListingID: listing.ID}, 1, auditlog.Meta{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pickup.IsCrossTenant || pickup.SourceTenantID != pickup.TenantID {
|
||||
t.Fatalf("same-site pickup scope = %+v", pickup)
|
||||
}
|
||||
if pickup.PickupNo == "" {
|
||||
t.Fatal("pickup number must not be empty")
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,16 @@ func privateFileAuthorizer(db *gorm.DB) func(context.Context, uint64, string) (b
|
||||
sql: "SELECT COUNT(1) FROM file_upload_owners WHERE user_id = ? AND object_key = ? AND (? = 0 OR tenant_id = ?)",
|
||||
args: []any{userID, key, tenantID, tenantID},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM chat_qrcode_pool q
|
||||
JOIN chat_conversations c ON c.id = q.conversation_id
|
||||
JOIN chat_participants p ON p.conversation_id = c.id AND p.participant_type = 'user' AND p.participant_id = ?
|
||||
WHERE (? = 0 OR c.tenant_id = ? OR EXISTS (
|
||||
SELECT 1 FROM rental_orders ro WHERE ro.id = c.order_id AND (ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)
|
||||
))
|
||||
AND (INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0)`,
|
||||
args: []any{userID, tenantID, tenantID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM game_accounts a
|
||||
JOIN rental_listings l ON l.account_id = a.id
|
||||
@@ -138,7 +148,7 @@ WHERE w.user_id = ?
|
||||
// adminPrivateFileAuthorizer 将经营站点后台的私有文件访问限制在当前租户。
|
||||
// 历史分销后台(tenant_id=0)保留原有平台级访问语义。
|
||||
func adminPrivateFileAuthorizer(db *gorm.DB) func(context.Context, uint64, string) (bool, error) {
|
||||
return func(ctx context.Context, _ uint64, key string) (bool, error) {
|
||||
return func(ctx context.Context, adminID uint64, key string) (bool, error) {
|
||||
if db == nil || key == "" {
|
||||
return false, nil
|
||||
}
|
||||
@@ -152,8 +162,8 @@ func adminPrivateFileAuthorizer(db *gorm.DB) func(context.Context, uint64, strin
|
||||
args []any
|
||||
}{
|
||||
{
|
||||
sql: "SELECT COUNT(1) FROM file_upload_owners WHERE object_key = ? AND (? = 0 OR tenant_id = ?)",
|
||||
args: []any{key, tenantID, tenantID},
|
||||
sql: "SELECT COUNT(1) FROM file_upload_owners WHERE admin_id = ? AND object_key = ? AND (? = 0 OR tenant_id = ?)",
|
||||
args: []any{adminID, key, tenantID, tenantID},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM game_accounts a
|
||||
@@ -204,6 +214,33 @@ WHERE (? = 0 OR (w.tenant_id = ? AND w.distribution_site_id = 0))
|
||||
AND (INSTR(w.payment_proof_url, ?) > 0 OR INSTR(w.payment_proof_url, ?) > 0 OR INSTR(w.payment_proof_url, ?) > 0 OR INSTR(w.payment_proof_url, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM chat_qrcode_pool q
|
||||
WHERE (? = 0 OR (q.tenant_id = ? AND (q.distribution_site_id IS NULL OR q.distribution_site_id = 0)))
|
||||
AND (INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
}
|
||||
if (strings.HasPrefix(key, "operating-expense/") || strings.HasPrefix(key, "manual-disbursement/")) &&
|
||||
isPlatformSuperAdmin(ctx, db, adminID) {
|
||||
queries = append(queries,
|
||||
struct {
|
||||
sql string
|
||||
args []any
|
||||
}{
|
||||
sql: `SELECT COUNT(1) FROM operating_expenses oe
|
||||
WHERE INSTR(oe.voucher_url, ?) > 0 OR INSTR(oe.voucher_url, ?) > 0 OR INSTR(oe.voucher_url, ?) > 0 OR INSTR(oe.voucher_url, ?) > 0`,
|
||||
args: []any{key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
struct {
|
||||
sql string
|
||||
args []any
|
||||
}{
|
||||
sql: `SELECT COUNT(1) FROM manual_disbursements md
|
||||
WHERE INSTR(md.voucher_url, ?) > 0 OR INSTR(md.voucher_url, ?) > 0 OR INSTR(md.voucher_url, ?) > 0 OR INSTR(md.voucher_url, ?) > 0`,
|
||||
args: []any{key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
)
|
||||
}
|
||||
for _, query := range queries {
|
||||
var count int64
|
||||
@@ -221,10 +258,10 @@ WHERE (? = 0 OR (w.tenant_id = ? AND w.distribution_site_id = 0))
|
||||
}
|
||||
}
|
||||
|
||||
// recordPrivateFileUpload 记录用户上传的原图和变体,保证草稿状态下也仅上传者可预览。
|
||||
func recordPrivateFileUpload(db *gorm.DB) func(context.Context, uint64, []string) error {
|
||||
return func(ctx context.Context, userID uint64, objectKeys []string) error {
|
||||
if db == nil || userID == 0 || len(objectKeys) == 0 {
|
||||
// recordPrivateFileUpload 记录用户或管理员上传的原图和变体,保证业务记录保存前仅上传者可预览。
|
||||
func recordPrivateFileUpload(db *gorm.DB) func(context.Context, uint64, uint64, []string) error {
|
||||
return func(ctx context.Context, userID, adminID uint64, objectKeys []string) error {
|
||||
if db == nil || (userID == 0 && adminID == 0) || len(objectKeys) == 0 {
|
||||
return nil
|
||||
}
|
||||
records := make([]model.FileUploadOwner, 0, len(objectKeys))
|
||||
@@ -233,7 +270,12 @@ func recordPrivateFileUpload(db *gorm.DB) func(context.Context, uint64, []string
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
records = append(records, model.FileUploadOwner{TenantID: tenantID, UserID: userID, ObjectKey: key})
|
||||
records = append(records, model.FileUploadOwner{
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
AdminID: adminID,
|
||||
ObjectKey: key,
|
||||
})
|
||||
}
|
||||
if len(records) == 0 {
|
||||
return nil
|
||||
@@ -241,3 +283,16 @@ func recordPrivateFileUpload(db *gorm.DB) func(context.Context, uint64, []string
|
||||
return db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&records).Error
|
||||
}
|
||||
}
|
||||
|
||||
func isPlatformSuperAdmin(ctx context.Context, db *gorm.DB, adminID uint64) bool {
|
||||
if db == nil || adminID == 0 {
|
||||
return false
|
||||
}
|
||||
var count int64
|
||||
err := db.WithContext(ctx).
|
||||
Table("admin_user_roles AS aur").
|
||||
Joins("JOIN roles AS r ON r.id = aur.role_id").
|
||||
Where("aur.admin_user_id = ? AND r.code = ?", adminID, "super_admin").
|
||||
Count(&count).Error
|
||||
return err == nil && count > 0
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package router
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
@@ -91,10 +92,10 @@ func TestRecordPrivateFileUpload(t *testing.T) {
|
||||
}
|
||||
record := recordPrivateFileUpload(db)
|
||||
keys := []string{"listing/original.jpg", "listing/original.thumb.jpg", "listing/original.medium.jpg"}
|
||||
if err := record(context.Background(), 11, keys); err != nil {
|
||||
if err := record(context.Background(), 11, 0, keys); err != nil {
|
||||
t.Fatalf("record() error = %v", err)
|
||||
}
|
||||
if err := record(context.Background(), 11, keys); err != nil {
|
||||
if err := record(context.Background(), 11, 0, keys); err != nil {
|
||||
t.Fatalf("duplicate record() error = %v", err)
|
||||
}
|
||||
var count int64
|
||||
@@ -104,6 +105,16 @@ func TestRecordPrivateFileUpload(t *testing.T) {
|
||||
if count != int64(len(keys)) {
|
||||
t.Fatalf("record count = %d, want %d", count, len(keys))
|
||||
}
|
||||
adminKeys := []string{"qrcode/admin.jpg", "qrcode/admin.thumb.jpg"}
|
||||
if err := record(context.Background(), 0, 21, adminKeys); err != nil {
|
||||
t.Fatalf("record admin uploads: %v", err)
|
||||
}
|
||||
if err := db.Model(&model.FileUploadOwner{}).Where("admin_id = ?", 21).Count(&count).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != int64(len(adminKeys)) {
|
||||
t.Fatalf("admin record count = %d, want %d", count, len(adminKeys))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateFileAuthorizerRejectsCrossTenantOwner(t *testing.T) {
|
||||
@@ -136,8 +147,8 @@ func TestAdminPrivateFileAuthorizerScopesOperatingTenant(t *testing.T) {
|
||||
t.Fatalf("AutoMigrate() error = %v", err)
|
||||
}
|
||||
rows := []model.FileUploadOwner{
|
||||
{TenantID: 101, UserID: 11, ObjectKey: "listing/admin-tenant-a.jpg"},
|
||||
{TenantID: 202, UserID: 12, ObjectKey: "listing/admin-tenant-b.jpg"},
|
||||
{TenantID: 101, UserID: 11, AdminID: 1, ObjectKey: "listing/admin-tenant-a.jpg"},
|
||||
{TenantID: 202, UserID: 12, AdminID: 2, ObjectKey: "listing/admin-tenant-b.jpg"},
|
||||
}
|
||||
if err := db.Create(&rows).Error; err != nil {
|
||||
t.Fatalf("create upload owners: %v", err)
|
||||
@@ -157,11 +168,118 @@ func TestAdminPrivateFileAuthorizerScopesOperatingTenant(t *testing.T) {
|
||||
if allowed, err := authorize(ctxB, 2, "listing/admin-tenant-b.jpg"); err != nil || !allowed {
|
||||
t.Fatalf("tenant B own file allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
if allowed, err := authorize(context.Background(), 3, "listing/admin-tenant-a.jpg"); err != nil || !allowed {
|
||||
if allowed, err := authorize(context.Background(), 1, "listing/admin-tenant-a.jpg"); err != nil || !allowed {
|
||||
t.Fatalf("legacy admin file allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateFileAuthorizerAllowsDeliveredQrCodeParticipants(t *testing.T) {
|
||||
db := openAuthorizerTestDB(t)
|
||||
tenants := []model.Tenant{
|
||||
{Code: "file_tenant_a", Name: "A站", Status: "active"},
|
||||
{Code: "file_tenant_b", Name: "B站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tenantA := tenants[0]
|
||||
tenantB := tenants[1]
|
||||
conversations := []model.ChatConversation{
|
||||
{TenantID: tenantA.ID, Type: "listing_group", Title: "A会话", Status: "active"},
|
||||
{TenantID: tenantB.ID, Type: "listing_group", Title: "B会话", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&conversations).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conversationA := conversations[0]
|
||||
conversationB := conversations[1]
|
||||
participants := []model.ChatParticipant{
|
||||
{ConversationID: conversationA.ID, ParticipantType: "user", ParticipantID: 31, Role: "renter", JoinedAt: time.Now()},
|
||||
{ConversationID: conversationB.ID, ParticipantType: "user", ParticipantID: 32, Role: "renter", JoinedAt: time.Now()},
|
||||
}
|
||||
if err := db.Create(&participants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
qrcodes := []model.ChatQrCode{
|
||||
{TenantID: tenantA.ID, ImageURL: "/api/files/object?key=qrcode%2Fa.png", ConversationID: &conversationA.ID, Status: "used"},
|
||||
{TenantID: tenantB.ID, ImageURL: "/api/files/object?key=qrcode%2Fb.png", ConversationID: &conversationB.ID, Status: "used"},
|
||||
}
|
||||
if err := db.Create(&qrcodes).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
userAuthorize := privateFileAuthorizer(db)
|
||||
ctxA := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantA.ID})
|
||||
ctxB := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantB.ID})
|
||||
if allowed, err := userAuthorize(ctxA, 31, "qrcode/a.png"); err != nil || !allowed {
|
||||
t.Fatalf("A participant qrcode allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
if allowed, err := userAuthorize(ctxA, 32, "qrcode/b.png"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if allowed {
|
||||
t.Fatal("cross-tenant qrcode must be denied")
|
||||
}
|
||||
|
||||
adminAuthorize := adminPrivateFileAuthorizer(db)
|
||||
if allowed, err := adminAuthorize(ctxA, 1, "qrcode/a.png"); err != nil || !allowed {
|
||||
t.Fatalf("A admin qrcode allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
if allowed, err := adminAuthorize(ctxB, 1, "qrcode/a.png"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if allowed {
|
||||
t.Fatal("cross-tenant admin qrcode must be denied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminPrivateFileAuthorizerAllowsOnlySuperAdminFinanceVouchers(t *testing.T) {
|
||||
db := openAuthorizerTestDB(t)
|
||||
roles := []model.Role{
|
||||
{Code: "super_admin", Name: "超级管理员"},
|
||||
{Code: "finance", Name: "财务"},
|
||||
}
|
||||
if err := db.Create(&roles).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
admins := []model.AdminUser{
|
||||
{Username: "file-root", PasswordHash: "x", Status: "active"},
|
||||
{Username: "file-finance", PasswordHash: "x", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&admins).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&[]model.AdminUserRole{
|
||||
{AdminID: admins[0].ID, RoleID: roles[0].ID, TenantID: 0},
|
||||
{AdminID: admins[1].ID, RoleID: roles[1].ID, TenantID: 101},
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO operating_expenses
|
||||
(expense_no, category, payee_name, amount_cent, occurred_at, remark, voucher_url, status, created_by)
|
||||
VALUES ('OE-FILE', '推广', '测试', 100, NOW(), '测试', ?, 'paid', ?)`,
|
||||
"/api/files/object?key=operating-expense%2Fvoucher.webp", admins[0].ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO manual_disbursements
|
||||
(disbursement_no, category, payee_name, amount_cent, paid_at, remark, voucher_url, status, created_by)
|
||||
VALUES ('OD-FILE', 'other', '测试', 100, NOW(), '测试', ?, 'paid', ?)`,
|
||||
"/api/files/object?key=manual-disbursement%2Fvoucher.webp", admins[0].ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authorize := adminPrivateFileAuthorizer(db)
|
||||
ctxA := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
for _, key := range []string{"operating-expense/voucher.webp", "manual-disbursement/voucher.webp"} {
|
||||
if allowed, err := authorize(ctxA, admins[0].ID, key); err != nil || !allowed {
|
||||
t.Fatalf("super admin %s allowed=%v err=%v", key, allowed, err)
|
||||
}
|
||||
if allowed, err := authorize(ctxA, admins[1].ID, key); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if allowed {
|
||||
t.Fatalf("tenant finance must not read %s", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func openAuthorizerTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
|
||||
@@ -479,6 +479,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
requirePerm := func(code string) gin.HandlerFunc {
|
||||
return middleware.RequirePermission(code, deps.Redis)
|
||||
}
|
||||
requirePlatformSuperAdmin := middleware.RequirePlatformSuperAdmin(deps.DB)
|
||||
requireAnyPerm := func(codes ...string) gin.HandlerFunc {
|
||||
return middleware.RequireAnyPermission(deps.Redis, codes...)
|
||||
}
|
||||
@@ -952,11 +953,11 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
adminRoutes.GET("/finance/dashboard", requirePerm("wallet:view"), adminFinanceHandler.Dashboard)
|
||||
adminRoutes.GET("/finance/details", requirePerm("wallet:view"), adminFinanceHandler.Details)
|
||||
adminRoutes.GET("/finance/disbursements", requirePerm("wallet:view"), adminFinanceHandler.Disbursements)
|
||||
adminRoutes.POST("/finance/manual-disbursements", requirePerm("finance:manual_disbursement"), adminFinanceHandler.CreateManualDisbursement)
|
||||
adminRoutes.POST("/finance/manual-disbursements/:id/void", requirePerm("finance:manual_disbursement"), adminFinanceHandler.VoidManualDisbursement)
|
||||
adminRoutes.GET("/finance/operating-expenses", requirePerm("finance:operating_expense"), adminFinanceHandler.OperatingExpenses)
|
||||
adminRoutes.POST("/finance/operating-expenses", requirePerm("finance:operating_expense"), adminFinanceHandler.CreateOperatingExpense)
|
||||
adminRoutes.POST("/finance/operating-expenses/:id/void", requirePerm("finance:operating_expense"), adminFinanceHandler.VoidOperatingExpense)
|
||||
adminRoutes.POST("/finance/manual-disbursements", requirePlatformSuperAdmin, requirePerm("finance:manual_disbursement"), adminFinanceHandler.CreateManualDisbursement)
|
||||
adminRoutes.POST("/finance/manual-disbursements/:id/void", requirePlatformSuperAdmin, requirePerm("finance:manual_disbursement"), adminFinanceHandler.VoidManualDisbursement)
|
||||
adminRoutes.GET("/finance/operating-expenses", requirePlatformSuperAdmin, requirePerm("finance:operating_expense"), adminFinanceHandler.OperatingExpenses)
|
||||
adminRoutes.POST("/finance/operating-expenses", requirePlatformSuperAdmin, requirePerm("finance:operating_expense"), adminFinanceHandler.CreateOperatingExpense)
|
||||
adminRoutes.POST("/finance/operating-expenses/:id/void", requirePlatformSuperAdmin, requirePerm("finance:operating_expense"), adminFinanceHandler.VoidOperatingExpense)
|
||||
adminRoutes.GET("/wallet/ledger", requirePerm("wallet:view"), walletHandler.AdminLedger)
|
||||
adminRoutes.GET("/payments", requirePerm("wallet:view"), paymentHandler.AdminList)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user