fix(tenant): 收紧双站运营提号与录单边界
This commit is contained in:
@@ -25,7 +25,7 @@
|
||||
- 分销管理后台:`http://localhost:5190`(在主站后台“分销站点”开通站点并配置分销操作员登录)
|
||||
- 分销专属前台:`http://localhost:5191`(独立端口隔离,支持 Host 域名与 X-Distribution-Site 头识别站点)
|
||||
|
||||
> 生产环境不使用上述端口:Caddy 按域名分流,主站和解忧商行后台分别通过各自经营域名进入,分销管理后台固定为 `https://distribution.<CADDY_DOMAIN>`,平台运营统计后台固定为 `https://ops.<CADDY_DOMAIN>`(见 `deploy/caddy/Caddyfile`)。主站后台的「打开独立分销后台」与开通凭证通过构建期 `VITE_DISTRIBUTION_ADMIN_URL` 注入该地址;未配置时按当前主站域名推导。
|
||||
> 生产环境不使用上述端口:Caddy 按域名分流,主站和解忧商行后台分别通过各自经营域名进入,分销管理后台固定为 `https://distribution.<CADDY_DOMAIN>`,平台运营统计后台使用 `OPS_DOMAIN`,未配置时默认 `https://ops.<CADDY_DOMAIN>`(见 `deploy/caddy/Caddyfile`)。主站后台的「打开独立分销后台」与开通凭证通过构建期 `VITE_DISTRIBUTION_ADMIN_URL` 注入该地址;未配置时按当前主站域名推导。
|
||||
|
||||
|
||||
如需拆分调试,可手动执行:
|
||||
|
||||
@@ -8,6 +8,7 @@ CADDY_EMAIL=admin@example.com
|
||||
# 解忧商行前台域名;未启用解忧时留空。
|
||||
TENANT_JIEYOU_DOMAIN=zuhaox.com
|
||||
# 平台运营统计后台域名;留空时生产环境按 ops.<CADDY_DOMAIN> 推导。
|
||||
# Caddy、前端构建和后端必须使用同一个域名。
|
||||
OPS_DOMAIN=
|
||||
# 选号网(hfb_show)独立域名,与主站同机;不部署选号网可留空。
|
||||
# CADDY_SHOW_DOMAIN=show.example.com
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
-- +goose Up
|
||||
|
||||
-- 管理员上传的私有文件在业务记录保存前也需要可预览。
|
||||
ALTER TABLE file_upload_owners
|
||||
ADD COLUMN admin_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER user_id,
|
||||
ADD KEY idx_file_upload_owners_admin (admin_id, object_key);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
ALTER TABLE file_upload_owners
|
||||
DROP KEY idx_file_upload_owners_admin,
|
||||
DROP COLUMN admin_id;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- +goose Up
|
||||
|
||||
-- 历史分销账号仍属于大锤租户,但渠道归属独立;同一手机号可以再注册大锤经营账号。
|
||||
ALTER TABLE users
|
||||
DROP KEY uk_users_tenant_phone,
|
||||
ADD UNIQUE KEY uk_users_tenant_site_phone (tenant_id, distribution_site_id, phone);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
ALTER TABLE users
|
||||
DROP KEY uk_users_tenant_site_phone,
|
||||
ADD UNIQUE KEY uk_users_tenant_phone (tenant_id, phone);
|
||||
@@ -0,0 +1,71 @@
|
||||
-- +goose Up
|
||||
|
||||
ALTER TABLE admin_pickups
|
||||
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||
ADD COLUMN source_tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER tenant_id,
|
||||
ADD KEY idx_admin_pickups_tenant_status_created (tenant_id, status, created_at),
|
||||
ADD KEY idx_admin_pickups_source_tenant_status_created (source_tenant_id, status, created_at);
|
||||
|
||||
UPDATE admin_pickups p
|
||||
JOIN rental_listings l ON l.id = p.listing_id
|
||||
SET p.source_tenant_id = l.source_tenant_id
|
||||
WHERE p.source_tenant_id = 0;
|
||||
|
||||
UPDATE admin_pickups
|
||||
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
|
||||
WHERE tenant_id = 0;
|
||||
|
||||
UPDATE admin_pickups
|
||||
SET source_tenant_id = tenant_id
|
||||
WHERE source_tenant_id = 0;
|
||||
|
||||
ALTER TABLE admin_pickup_financial_adjustments
|
||||
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||
ADD KEY idx_pickup_financial_adjustment_tenant (tenant_id, status, created_at);
|
||||
|
||||
UPDATE admin_pickup_financial_adjustments fa
|
||||
JOIN admin_pickups p ON p.id = fa.pickup_id
|
||||
SET fa.tenant_id = p.tenant_id
|
||||
WHERE fa.tenant_id = 0;
|
||||
|
||||
ALTER TABLE pickup_shops
|
||||
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||
DROP KEY uk_pickup_shop_name,
|
||||
ADD UNIQUE KEY uk_pickup_shops_tenant_name (tenant_id, name),
|
||||
ADD KEY idx_pickup_shops_tenant_status (tenant_id, status);
|
||||
|
||||
UPDATE pickup_shops
|
||||
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
|
||||
WHERE tenant_id = 0;
|
||||
|
||||
ALTER TABLE pickup_shop_mappings
|
||||
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||
DROP KEY uk_pickup_shop_mapping_source,
|
||||
ADD UNIQUE KEY uk_pickup_shop_mappings_tenant_source (tenant_id, source_name);
|
||||
|
||||
UPDATE pickup_shop_mappings
|
||||
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
|
||||
WHERE tenant_id = 0;
|
||||
|
||||
-- +goose Down
|
||||
|
||||
ALTER TABLE pickup_shop_mappings
|
||||
DROP KEY uk_pickup_shop_mappings_tenant_source,
|
||||
ADD UNIQUE KEY uk_pickup_shop_mapping_source (source_name),
|
||||
DROP COLUMN tenant_id;
|
||||
|
||||
ALTER TABLE pickup_shops
|
||||
DROP KEY idx_pickup_shops_tenant_status,
|
||||
DROP KEY uk_pickup_shops_tenant_name,
|
||||
ADD UNIQUE KEY uk_pickup_shop_name (name),
|
||||
DROP COLUMN tenant_id;
|
||||
|
||||
ALTER TABLE admin_pickup_financial_adjustments
|
||||
DROP KEY idx_pickup_financial_adjustment_tenant,
|
||||
DROP COLUMN tenant_id;
|
||||
|
||||
ALTER TABLE admin_pickups
|
||||
DROP KEY idx_admin_pickups_source_tenant_status_created,
|
||||
DROP KEY idx_admin_pickups_tenant_status_created,
|
||||
DROP COLUMN source_tenant_id,
|
||||
DROP COLUMN tenant_id;
|
||||
@@ -0,0 +1,35 @@
|
||||
-- +goose Up
|
||||
|
||||
ALTER TABLE cs_manual_entries
|
||||
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||
DROP KEY uk_cs_manual_entries_entry_no_group,
|
||||
ADD UNIQUE KEY uk_cs_manual_entries_tenant_entry_group (tenant_id, entry_no, entry_group),
|
||||
ADD KEY idx_cs_manual_entries_tenant_admin_created (tenant_id, admin_id, created_at);
|
||||
|
||||
UPDATE cs_manual_entries
|
||||
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
|
||||
WHERE tenant_id = 0;
|
||||
|
||||
ALTER TABLE cs_manual_entry_options
|
||||
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
|
||||
DROP KEY uk_cs_manual_entry_options_type_name,
|
||||
ADD UNIQUE KEY uk_cs_manual_entry_options_tenant_type_name (tenant_id, type, name),
|
||||
ADD KEY idx_cs_manual_entry_options_tenant_type_sort (tenant_id, type, sort_order, id);
|
||||
|
||||
UPDATE cs_manual_entry_options
|
||||
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
|
||||
WHERE tenant_id = 0;
|
||||
|
||||
-- +goose Down
|
||||
|
||||
ALTER TABLE cs_manual_entry_options
|
||||
DROP KEY idx_cs_manual_entry_options_tenant_type_sort,
|
||||
DROP KEY uk_cs_manual_entry_options_tenant_type_name,
|
||||
ADD UNIQUE KEY uk_cs_manual_entry_options_type_name (type, name),
|
||||
DROP COLUMN tenant_id;
|
||||
|
||||
ALTER TABLE cs_manual_entries
|
||||
DROP KEY idx_cs_manual_entries_tenant_admin_created,
|
||||
DROP KEY uk_cs_manual_entries_tenant_entry_group,
|
||||
ADD UNIQUE KEY uk_cs_manual_entries_entry_no_group (entry_no, entry_group),
|
||||
DROP COLUMN tenant_id;
|
||||
+5
-4
@@ -4,7 +4,7 @@
|
||||
|
||||
```text
|
||||
https://主站域名 # CADDY_DOMAIN,哈夫币系统
|
||||
https://ops.主站域名 # 平台运营只读统计后台,仅平台超级管理员
|
||||
https://OPS_DOMAIN # 平台运营只读统计后台,仅平台超级管理员;默认 ops.主站域名
|
||||
https://选号网域名 # CADDY_SHOW_DOMAIN(可选),hfb_show 静态选号站
|
||||
https://monitor.主站域名 # Beszel 监控
|
||||
```
|
||||
@@ -13,7 +13,7 @@ https://monitor.主站域名 # Beszel 监控
|
||||
|
||||
部署前请确认:
|
||||
|
||||
- 主站域名和 `ops.主站域名` A 记录已解析到服务器公网 IP;启用选号网时,选号网域名也要解析到同一 IP。
|
||||
- 主站域名和 `OPS_DOMAIN`(默认 `ops.主站域名`)A 记录已解析到服务器公网 IP;启用选号网时,选号网域名也要解析到同一 IP。
|
||||
- 服务器安全组或防火墙已放行 `80/tcp` 和 `443/tcp`。
|
||||
- 服务器上没有其他服务占用 `80`、`443`。
|
||||
- 国内服务器如需对外访问,请先确认域名备案和云厂商限制。
|
||||
@@ -30,6 +30,7 @@ cp backend/.env.prod.example backend/.env
|
||||
CADDY_DOMAIN
|
||||
CADDY_EMAIL
|
||||
TENANT_JIEYOU_DOMAIN
|
||||
OPS_DOMAIN
|
||||
MYSQL_ROOT_PASSWORD
|
||||
MYSQL_PASSWORD
|
||||
MYSQL_DSN
|
||||
@@ -196,7 +197,7 @@ set +a
|
||||
docker compose -f deploy/docker-compose.prod.yml up -d --build
|
||||
```
|
||||
|
||||
手动执行 `docker compose` 时需要先导出 `CADDY_DOMAIN`、`CADDY_EMAIL` 和 `TENANT_JIEYOU_DOMAIN`,否则 Caddy 无法读取证书域名和解忧后台入口配置。优先推荐使用一键部署脚本,它会自动从 `backend/.env` 导出这些变量。
|
||||
手动执行 `docker compose` 时需要先导出 `CADDY_DOMAIN`、`CADDY_EMAIL`、`TENANT_JIEYOU_DOMAIN` 和 `OPS_DOMAIN`,否则 Caddy 无法读取证书域名、解忧后台和平台运营后台入口配置。`OPS_DOMAIN` 留空时部署脚本会使用 `ops.<CADDY_DOMAIN>`。优先推荐使用一键部署脚本,它会自动计算并导出这些变量。
|
||||
|
||||
## 4. 手动执行数据库迁移
|
||||
|
||||
@@ -231,7 +232,7 @@ curl "https://选号网域名/api/listings?page=1&page_size=1"
|
||||
```text
|
||||
https://主站域名
|
||||
https://主站域名/你配置的后台入口/login
|
||||
https://ops.主站域名/你配置的后台入口/login # 平台运营统计后台
|
||||
https://OPS_DOMAIN/你配置的后台入口/login # 平台运营统计后台
|
||||
https://选号网域名 # 选号网首页
|
||||
```
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ distribution.{$CADDY_DOMAIN} {
|
||||
}
|
||||
|
||||
# 平台运营只读统计后台:仅平台超级管理员登录。
|
||||
ops.{$CADDY_DOMAIN} {
|
||||
{$OPS_DOMAIN} {
|
||||
encode zstd gzip
|
||||
import public_api
|
||||
|
||||
@@ -152,6 +152,13 @@ ops.{$CADDY_DOMAIN} {
|
||||
file_server
|
||||
}
|
||||
|
||||
# 后台 HTML 使用根路径引用 /assets 等构建产物,必须单独放行,否则页面会白屏。
|
||||
@ops_static path /assets/* /apple-touch-icon.png /favicon.ico /robots.txt
|
||||
handle @ops_static {
|
||||
root * /srv/dist
|
||||
file_server
|
||||
}
|
||||
|
||||
handle {
|
||||
respond 404
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ FROM node:24-alpine AS build
|
||||
|
||||
ARG VITE_ADMIN_BASE_PATH=/manage-7x9k2p
|
||||
ENV VITE_ADMIN_BASE_PATH=${VITE_ADMIN_BASE_PATH}
|
||||
ARG VITE_OPS_DOMAIN=ops.localhost
|
||||
ENV VITE_OPS_DOMAIN=${VITE_OPS_DOMAIN}
|
||||
# 主站后台里「打开独立分销后台」按钮与开通凭证使用的分销后台地址。
|
||||
# 留空时前端按 distribution.<当前主站域名> 推导,显式配置可覆盖(如独立后台子域改名)。
|
||||
ARG VITE_DISTRIBUTION_ADMIN_URL=
|
||||
|
||||
@@ -5,6 +5,7 @@ services:
|
||||
dockerfile: deploy/caddy/Dockerfile
|
||||
args:
|
||||
VITE_ADMIN_BASE_PATH: ${VITE_ADMIN_BASE_PATH:-/manage-7x9k2p}
|
||||
VITE_OPS_DOMAIN: ${VITE_OPS_DOMAIN:-${OPS_DOMAIN:-ops.${CADDY_DOMAIN}}}
|
||||
# 留空时前端按 distribution.<CADDY_DOMAIN> 推导,与 Caddyfile 的站点规则保持一致。
|
||||
VITE_DISTRIBUTION_ADMIN_URL: ${VITE_DISTRIBUTION_ADMIN_URL:-}
|
||||
restart: unless-stopped
|
||||
@@ -13,6 +14,7 @@ services:
|
||||
CADDY_DOMAIN: ${CADDY_DOMAIN:?请先导出 CADDY_DOMAIN,或使用 scripts/deploy-prod.sh 部署}
|
||||
CADDY_EMAIL: ${CADDY_EMAIL:?请先导出 CADDY_EMAIL,或使用 scripts/deploy-prod.sh 部署}
|
||||
TENANT_JIEYOU_DOMAIN: ${TENANT_JIEYOU_DOMAIN:-tenant-jieyou.invalid}
|
||||
OPS_DOMAIN: ${OPS_DOMAIN:-ops.${CADDY_DOMAIN}}
|
||||
# Caddyfile 用它放行主站后台隐藏入口,并与前端构建期的 VITE_ADMIN_BASE_PATH 保持一致。
|
||||
ADMIN_BASE_PATH: ${VITE_ADMIN_BASE_PATH:-/manage-7x9k2p}
|
||||
# 选号网域名可选;未配置时 conf.d 为空,不影响主站
|
||||
|
||||
@@ -94,6 +94,15 @@
|
||||
|
||||
## 三、方案设计与改造范围
|
||||
|
||||
### 0. 双站点租户边界(2026-11-16)
|
||||
|
||||
- `admin_pickups.tenant_id` 表示实际创建和管理提号记录的提号站点。
|
||||
- `admin_pickups.source_tenant_id` 表示商品和号主所属的货源站点。
|
||||
- 提号列表、详情、导出、操作权限、店铺配置、历史映射和财务统计均按 `tenant_id` 隔离。
|
||||
- 可提号商品池同时包含大锤商行和解忧商行货源;选择跨站商品时保存两个站点快照,并在后台明确显示“跨站提号”。
|
||||
- 站内上传的号主结算仍进入号主所属货源站点钱包;平台代管的线下打款也归属提号站点处理。
|
||||
- `admin_pickup_financial_adjustments.tenant_id`、`pickup_shops.tenant_id`、`pickup_shop_mappings.tenant_id` 必须与提号记录保持同一提号站点。
|
||||
|
||||
### 1. 数据库升级 (`000079_admin_pickup_extra_fields_and_shops.sql`)
|
||||
1. 对 `admin_pickups` 表增加 4 个字段及必要索引:
|
||||
- `operator VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作人(如客服/运营人员名字)'`
|
||||
|
||||
+27
-8
@@ -1,7 +1,7 @@
|
||||
# 解忧商行双站点改造方案
|
||||
|
||||
> 状态:阶段 1~7 本地功能闭环已完成,后台租户边界修复完成,待真实域名切换
|
||||
> 更新时间:2026-11-15
|
||||
> 状态:阶段 1~7 本地功能闭环已完成,后台租户、平台财务、私有文件和任务边界已收口,待真实域名验收
|
||||
> 更新时间:2026-11-16
|
||||
> 目标:用一套后端、一套数据库和一套前端,上线大锤商行、解忧商行两个经营站点
|
||||
|
||||
## 1. 基调
|
||||
@@ -63,9 +63,15 @@
|
||||
- 租户各自复制一套后台程序;后台仍复用各经营站点 Host,平台运营统计使用独立只读域名。
|
||||
- 统一跨站客服工作台。
|
||||
- 双向自动铺货规则、复杂供货合同和自动追偿。
|
||||
- 与首期无关的撞车、积分、邀请、成长、优质号主、线下提号和广告归因改造。
|
||||
- 撞车商城和积分商城的完整经营租户拆分。
|
||||
|
||||
> 撞车、积分商城、线下提号等未完成经营租户隔离的模块,当前仍按平台共享能力处理;在完成独立租户改造前,不应把它们的结果当作某一经营站点的独立经营数据。
|
||||
> 撞车商城、积分商城等未完成经营租户隔离的模块,当前仍按平台共享能力处理;在完成独立租户改造前,不应把它们的结果当作某一经营站点的独立经营数据。
|
||||
>
|
||||
> 运营开支、其他线下出款属于平台级财务数据,不是单站经营数据,仅平台超级管理员可操作。
|
||||
>
|
||||
> 线下提号按提号站点独立记录、统计和操作,同时允许选择另一经营站点的已上架货源;货源站点单独保存在提号记录中。
|
||||
>
|
||||
> 客服手动录单及平台、操作人、出款操作人选项按经营站点独立维护,不跨站共享。
|
||||
|
||||
## 4. 目标架构
|
||||
|
||||
@@ -105,7 +111,7 @@
|
||||
|
||||
| 表 | 字段 |
|
||||
|---|---|
|
||||
| `users` | `tenant_id`,手机号唯一键改为 `(tenant_id, phone)` |
|
||||
| `users` | `tenant_id`,手机号唯一键为 `(tenant_id, distribution_site_id, phone)`;经营用户使用 `distribution_site_id=0`,历史分销用户保留原渠道 ID |
|
||||
| `user_realname` | `tenant_id`,身份证唯一键改为 `(tenant_id, id_no_hash)` |
|
||||
| `user_payment_accounts` | `tenant_id` |
|
||||
| `wallet_accounts`、`wallet_ledger` | `tenant_id` |
|
||||
@@ -113,6 +119,8 @@
|
||||
| `game_accounts` | `source_tenant_id` |
|
||||
| `rental_listings` | `source_tenant_id`(号主所属租户由 `owner_id -> users.tenant_id` 约束) |
|
||||
| `rental_orders` | `buyer_tenant_id`、`source_tenant_id`、`payment_tenant_id`、`source_amount_cent` |
|
||||
| `admin_pickups` | `tenant_id`(提号站点)、`source_tenant_id`(货源站点) |
|
||||
| `cs_manual_entries`、`cs_manual_entry_options` | `tenant_id`,录单编号和选项名称按经营站点分别唯一 |
|
||||
| `payment_merchant_configs` | `owner_tenant_id` |
|
||||
| `payment_orders` | `tenant_id` |
|
||||
| `notifications`、`sms_messages` | `tenant_id`、`source_tenant_id` |
|
||||
@@ -148,6 +156,7 @@ source_amount_cent
|
||||
|
||||
- 同一手机号可以在两个租户分别注册。
|
||||
- 历史分销用户只能从原分销域名登录,不进入经营站点用户体系。
|
||||
- 同一手机号的历史分销身份和大锤经营身份可以并存,按 `tenant_id + distribution_site_id + phone` 区分。
|
||||
- JWT 必须包含 `tenant_id` 和 `scope`。
|
||||
- 用户令牌只能访问令牌所属经营租户。
|
||||
- 短信验证码、登录失败、限流、实名和钱包 Key 都带租户。
|
||||
@@ -155,8 +164,8 @@ source_amount_cent
|
||||
- 共享客服可以同时拥有两个租户的客服角色。
|
||||
- `super_admin` 使用 `tenant_id=0` 的平台角色,可以查看全部租户。
|
||||
- 首期复用同一套后台页面,通过当前 Host 确定租户;主站和解忧各自通过本站域名进入后台。
|
||||
- 平台运营使用独立 `ops.<主域名>` 只读统计后台,仅平台超级管理员可登录。
|
||||
- 权限缓存 Key 至少包含管理员 ID 和租户 ID。
|
||||
- 平台运营使用独立 `OPS_DOMAIN` 只读统计后台,未配置时默认 `ops.<主域名>`,仅平台超级管理员可登录。
|
||||
- 权限缓存 Key 至少包含管理员 ID,并区分经营租户和平台运营作用域。
|
||||
|
||||
## 7. 共享号库和双站货架
|
||||
|
||||
@@ -249,7 +258,7 @@ A 站商品进入 B 站货架
|
||||
|
||||
平台统计按租户分组展示,不把两个租户的内部交易重复相加为公司 GMV。
|
||||
|
||||
平台运营后台另设 `ops.<主域名>`,只提供只读统计,不开放用户、订单、商品和资金操作。
|
||||
平台运营后台另设 `OPS_DOMAIN`,只提供只读统计,不开放用户、订单、商品和资金操作。
|
||||
|
||||
## 11. 客服、通知、文件和任务
|
||||
|
||||
@@ -263,6 +272,8 @@ A 站商品进入 B 站货架
|
||||
- 通知、短信、未读统计和消息缓存按租户隔离。
|
||||
- 私有文件上传和读取校验租户及业务角色。
|
||||
- 经营站点管理员读取私有文件时同样校验当前租户,不允许按对象 key 越站读取。
|
||||
- 管理员临时上传的文件记录管理员归属,业务记录保存前即可安全预览。
|
||||
- 二维码、运营开支凭证和手工出款凭证必须纳入对应业务关联授权。
|
||||
- 定时任务从订单、支付、会话等业务记录恢复租户,无法解析时暂停并告警。
|
||||
|
||||
首期不做客户会话、货源会话、内部案件的复杂拆分。
|
||||
@@ -350,12 +361,15 @@ A 站商品进入 B 站货架
|
||||
现有分销表不迁移为经营租户。
|
||||
|
||||
启用解忧前必须保留大锤完整回归数据。启用同手机号双租户后,应用回滚不能再退回旧全局手机号版本;故障回滚通过关闭解忧域名和功能开关、保留兼容代码完成。
|
||||
历史分销身份和大锤经营身份并存后,数据库回滚不能再恢复旧的 `(tenant_id, phone)` 唯一键。
|
||||
两个站点分别创建同名线下提号店铺后,数据库回滚也不能恢复旧的全局店铺名唯一键;故障回滚应关闭解忧提号入口并保留复合唯一键。
|
||||
|
||||
## 15. 上线验收
|
||||
|
||||
- 未知域名不会落到大锤。
|
||||
- 主站和解忧域名都能打开各自后台登录入口。
|
||||
- 同一手机号可以在两个租户注册。
|
||||
- 同一手机号的历史分销与大锤经营身份可以并存,且不能互相登录对方入口。
|
||||
- 大锤 JWT 不能访问解忧数据,反向同样拒绝。
|
||||
- 两个站点都能看到双方开放的商品。
|
||||
- 未开放商品无法通过详情、图片、搜索或分享链接访问。
|
||||
@@ -367,7 +381,12 @@ A 站商品进入 B 站货架
|
||||
- 两个站点的用户、订单、支付、钱包和统计互不串数据。
|
||||
- 用户管理、申诉仲裁和钱包调账不能跨经营租户操作。
|
||||
- 审计日志、公告、管理员通知和私有文件访问不能跨经营租户。
|
||||
- 站点管理员不能访问平台级运营开支和其他线下出款;平台超级管理员可正常预览财务凭证。
|
||||
- 平台运营后台的 HTML、JS、CSS 和静态图标均可正常加载。
|
||||
- 出货站不能关闭或封存买方已支付订单;退款只能由买方租户发起。
|
||||
- 每个站点只能管理本站发起的线下提号;提号时可以选择另一站点的已上架货源。
|
||||
- 跨站线下提号的利润和出款统计归属提号站点,号主结算进入货源站点号主钱包。
|
||||
- 两个站点的手动录单、平台选项、操作人选项和出款操作人选项互不可见。
|
||||
- 历史分销用户、订单、钱包和提现不会进入经营站点后台及统计。
|
||||
- 每个经营站点可以在商品详情中独立设置本站售价和展示状态。
|
||||
- 无租户上下文的任务暂停并告警。
|
||||
|
||||
@@ -10,6 +10,13 @@ export type AvailableListingSourceType = '' | 'external' | 'internal'
|
||||
|
||||
export interface AdminPickup {
|
||||
id: number
|
||||
tenant_id: number
|
||||
tenant_code: string
|
||||
tenant_name: string
|
||||
source_tenant_id: number
|
||||
source_tenant_code: string
|
||||
source_tenant_name: string
|
||||
is_cross_tenant: boolean
|
||||
pickup_no: string
|
||||
listing_id: number
|
||||
listing_no: string
|
||||
@@ -91,6 +98,10 @@ export interface AdminPickupProcessEvent {
|
||||
|
||||
export interface AvailableListing {
|
||||
id: number
|
||||
source_tenant_id: number
|
||||
source_tenant_code: string
|
||||
source_tenant_name: string
|
||||
is_cross_tenant: boolean
|
||||
listing_no: string
|
||||
account_id: number
|
||||
account_title: string
|
||||
|
||||
@@ -51,7 +51,9 @@ const voucherUploading = ref(false)
|
||||
const manualActionID = ref(0)
|
||||
const selectedManual = ref<FinanceDisbursementItem | null>(null)
|
||||
const summary = ref<FinanceDisbursementListSummary>(emptySummary())
|
||||
const canManageManual = computed(() => adminSession.hasPermission('finance:manual_disbursement'))
|
||||
const canManageManual = computed(
|
||||
() => adminSession.isSuperAdmin && adminSession.hasPermission('finance:manual_disbursement')
|
||||
)
|
||||
|
||||
const manualCategories = [
|
||||
{ value: 'user_compensation', label: '用户补偿' },
|
||||
|
||||
@@ -41,7 +41,9 @@ const total = ref(0)
|
||||
const currentPage = ref(1)
|
||||
const currentPageSize = ref(20)
|
||||
const summary = ref<OperatingExpenseListSummary>(emptySummary())
|
||||
const canManage = computed(() => adminSession.hasPermission('finance:operating_expense'))
|
||||
const canManage = computed(
|
||||
() => adminSession.isSuperAdmin && adminSession.hasPermission('finance:operating_expense')
|
||||
)
|
||||
|
||||
const filters = reactive({
|
||||
date_type: 'created' as 'created' | 'occurred',
|
||||
|
||||
@@ -462,6 +462,19 @@ function readSnapshotResources(summary: Record<string, unknown> | null): Snapsho
|
||||
<dt>提号编号</dt>
|
||||
<dd>{{ pickup.pickup_no }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>提号站点</dt>
|
||||
<dd>{{ pickup.tenant_name || pickup.tenant_code || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>货源站点</dt>
|
||||
<dd>
|
||||
{{ pickup.source_tenant_name || pickup.source_tenant_code || '-' }}
|
||||
<el-tag v-if="pickup.is_cross_tenant" type="warning" size="small" effect="light">
|
||||
跨站提号
|
||||
</el-tag>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>上架编号</dt>
|
||||
<dd>{{ listingCode }}</dd>
|
||||
|
||||
@@ -604,8 +604,22 @@ function listingSourceText(item: AvailableListing) {
|
||||
return item.source_channel ? `${label} · ${item.source_channel}` : label
|
||||
}
|
||||
|
||||
function siteName(code: string, name: string) {
|
||||
return name || code || '未配置站点'
|
||||
}
|
||||
|
||||
function pickupSiteText(row: AdminPickup) {
|
||||
if (!row.is_cross_tenant) return '本站货源'
|
||||
return `跨站 · ${siteName(row.source_tenant_code, row.source_tenant_name)}`
|
||||
}
|
||||
|
||||
function listingSiteText(item: AvailableListing) {
|
||||
const source = siteName(item.source_tenant_code, item.source_tenant_name)
|
||||
return item.is_cross_tenant ? `跨站 · ${source}` : `本站 · ${source}`
|
||||
}
|
||||
|
||||
function listingOptionLabel(item: AvailableListing) {
|
||||
return `${listingSourceText(item)} · ${item.listing_no} · ${item.account_title} · ${formatCentWithSymbol(listingOwnerTotalCent(item))} / ${formatCentWithSymbol(item.listing_price_cent)}`
|
||||
return `${listingSiteText(item)} · ${listingSourceText(item)} · ${item.listing_no} · ${item.account_title} · ${formatCentWithSymbol(listingOwnerTotalCent(item))} / ${formatCentWithSymbol(item.listing_price_cent)}`
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -615,7 +629,7 @@ function listingOptionLabel(item: AvailableListing) {
|
||||
<div class="page-header">
|
||||
<p class="eyebrow">Admin Pickup</p>
|
||||
<h1>线下提号</h1>
|
||||
<p>管理员线下提号,站内上传结算到钱包,平台代管通过线下结算确认打款。</p>
|
||||
<p>各站点独立管理提号记录,可选择本站或另一站点货源;结算仍进入货源站点号主钱包。</p>
|
||||
</div>
|
||||
<div class="toolbar-actions">
|
||||
<el-dropdown
|
||||
@@ -710,6 +724,13 @@ function listingOptionLabel(item: AvailableListing) {
|
||||
|
||||
<el-table v-loading="loading" :data="items" class="table-panel">
|
||||
<el-table-column prop="pickup_no" label="提号编号" width="190" />
|
||||
<el-table-column label="站点关系" width="170">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.is_cross_tenant ? 'warning' : 'info'" effect="light" size="small">
|
||||
{{ pickupSiteText(row) }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="account_title" label="账号" min-width="180" />
|
||||
<el-table-column label="区服/平台" width="150">
|
||||
<template #default="{ row }"
|
||||
@@ -923,6 +944,13 @@ function listingOptionLabel(item: AvailableListing) {
|
||||
:value="item.id"
|
||||
>
|
||||
<div class="listing-option">
|
||||
<el-tag
|
||||
:type="item.is_cross_tenant ? 'warning' : 'info'"
|
||||
effect="light"
|
||||
size="small"
|
||||
>
|
||||
{{ listingSiteText(item) }}
|
||||
</el-tag>
|
||||
<el-tag
|
||||
:type="pickupSourceTagType(item.account_source)"
|
||||
effect="light"
|
||||
@@ -944,6 +972,9 @@ function listingOptionLabel(item: AvailableListing) {
|
||||
</el-form-item>
|
||||
<el-form-item v-if="selectedListing" label="来源确认">
|
||||
<div class="selected-source">
|
||||
<el-tag :type="selectedListing.is_cross_tenant ? 'warning' : 'info'" effect="light">
|
||||
{{ listingSiteText(selectedListing) }}
|
||||
</el-tag>
|
||||
<el-tag :type="pickupSourceTagType(selectedListing.account_source)" effect="light">
|
||||
{{ pickupSourceLabel(selectedListing.account_source) }}
|
||||
</el-tag>
|
||||
|
||||
@@ -77,6 +77,7 @@ interface NavItem {
|
||||
icon: Component
|
||||
permission?: string
|
||||
shared?: boolean
|
||||
platformOnly?: boolean
|
||||
}
|
||||
|
||||
interface NavGroup {
|
||||
@@ -122,7 +123,6 @@ const allNavGroups: NavGroup[] = [
|
||||
to: adminPath('pickup'),
|
||||
icon: Switch,
|
||||
permission: 'order:pickup',
|
||||
shared: true,
|
||||
},
|
||||
{ label: '商品管理', to: adminPath('listings'), icon: Shop, permission: 'listing:view' },
|
||||
{
|
||||
@@ -245,7 +245,6 @@ const allNavGroups: NavGroup[] = [
|
||||
to: adminPath('manual-entries'),
|
||||
icon: EditPen,
|
||||
permission: 'cs_manual_entry:view',
|
||||
shared: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -277,6 +276,7 @@ const allNavGroups: NavGroup[] = [
|
||||
to: adminPath('finance/operating-expenses'),
|
||||
icon: Money,
|
||||
permission: 'finance:operating_expense',
|
||||
platformOnly: true,
|
||||
},
|
||||
{
|
||||
label: '资金流水',
|
||||
@@ -361,6 +361,7 @@ const allNavGroups: NavGroup[] = [
|
||||
const allNavItems = allNavGroups.flatMap(group => group.children)
|
||||
|
||||
function canAccessNavItem(item: NavItem) {
|
||||
if (item.platformOnly && !adminSession.isSuperAdmin) return false
|
||||
if (adminSession.isSuperAdmin) return true
|
||||
if (!item.permission) return true
|
||||
return adminSession.hasPermission(item.permission)
|
||||
|
||||
@@ -205,7 +205,7 @@ export function isPlatformOpsHostname(
|
||||
const host = hostname.trim().toLowerCase()
|
||||
if (!host) return false
|
||||
const configured = ((import.meta.env.VITE_OPS_DOMAIN as string) || '').trim().toLowerCase()
|
||||
if (configured && host === configured) return true
|
||||
if (configured) return host === configured
|
||||
return host.startsWith('ops.')
|
||||
}
|
||||
|
||||
|
||||
+13
-10
@@ -54,6 +54,7 @@ function stripVantRemoteIconFont() {
|
||||
const frontendPort = Number(process.env.DEV_FRONTEND_PORT || process.env.PORT || 5189)
|
||||
const backendPort = Number(process.env.DEV_BACKEND_PORT || 18088)
|
||||
const apiProxyTarget = process.env.VITE_API_PROXY_TARGET || `http://127.0.0.1:${backendPort}`
|
||||
const opsHost = (process.env.VITE_OPS_DOMAIN || 'ops.localhost').trim()
|
||||
|
||||
export default defineConfig({
|
||||
// 禁止 vite 清屏,避免把后端启动日志(GIN 路由、迁移等)从终端滚动缓冲里抹掉
|
||||
@@ -92,16 +93,18 @@ export default defineConfig({
|
||||
xfwd: true,
|
||||
},
|
||||
},
|
||||
allowedHosts: [
|
||||
'dachui.localhost',
|
||||
'jieyou.localhost',
|
||||
'ops.localhost',
|
||||
'221329.cc.cd',
|
||||
'd4aa-77-93-89-84.ngrok-free.app',
|
||||
'frp-bus.com',
|
||||
'www.u499731.nyat.app',
|
||||
'fn.221329.xyz',
|
||||
],
|
||||
allowedHosts: Array.from(
|
||||
new Set([
|
||||
'dachui.localhost',
|
||||
'jieyou.localhost',
|
||||
opsHost,
|
||||
'221329.cc.cd',
|
||||
'd4aa-77-93-89-84.ngrok-free.app',
|
||||
'frp-bus.com',
|
||||
'www.u499731.nyat.app',
|
||||
'fn.221329.xyz',
|
||||
])
|
||||
),
|
||||
},
|
||||
build: {
|
||||
rollupOptions: {
|
||||
|
||||
@@ -65,7 +65,7 @@ require_pattern "backend/internal/modules/order/queries.go" "offline_settlement_
|
||||
require_pattern "backend/internal/modules/order/queries.go" "page == 1 && len(rows) < pageSize" "订单列表首页面单扫描短路"
|
||||
|
||||
require_pattern "backend/internal/modules/pickup/repository.go" "p.pickup_no = ?" "提号列表提号单号唯一索引直达"
|
||||
require_pattern "backend/internal/modules/pickup/repository.go" "p.owner_id = (SELECT id FROM users WHERE phone = ?)" "提号列表号主手机号解析用户索引直达"
|
||||
require_pattern "backend/internal/modules/pickup/repository.go" "pickup_owner.id = p.owner_id AND pickup_owner.phone = ?" "提号列表号主手机号按已关联号主精确匹配"
|
||||
require_pattern "backend/internal/modules/pickup/repository.go" "page == 1 && len(rows) < pageSize" "提号列表首页面单扫描短路"
|
||||
|
||||
require_pattern "backend/internal/modules/dispute/query.go" "o.order_no = ?" "纠纷列表订单号唯一索引直达"
|
||||
|
||||
+21
-2
@@ -151,11 +151,15 @@ validate_env() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local app_env caddy_domain caddy_email jieyou_domain mysql_dsn redis_addr storage_endpoint backend_uid backend_gid backup_dir backup_status_dir backup_restore_dir backup_oss_uri backup_user
|
||||
local app_env caddy_domain caddy_email jieyou_domain ops_domain mysql_dsn redis_addr storage_endpoint backend_uid backend_gid backup_dir backup_status_dir backup_restore_dir backup_oss_uri backup_user
|
||||
app_env="$(require_env APP_ENV)"
|
||||
caddy_domain="$(require_env CADDY_DOMAIN)"
|
||||
caddy_email="$(require_env CADDY_EMAIL)"
|
||||
jieyou_domain="$(require_env TENANT_JIEYOU_DOMAIN)"
|
||||
ops_domain="$(env_value OPS_DOMAIN || true)"
|
||||
if [[ -z "${ops_domain}" ]]; then
|
||||
ops_domain="ops.${caddy_domain}"
|
||||
fi
|
||||
mysql_dsn="$(require_env MYSQL_DSN)"
|
||||
redis_addr="$(require_env REDIS_ADDR)"
|
||||
storage_endpoint="$(require_env STORAGE_ENDPOINT)"
|
||||
@@ -202,6 +206,14 @@ validate_env() {
|
||||
log_error "TENANT_JIEYOU_DOMAIN 不能与 CADDY_DOMAIN 相同"
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${ops_domain}" == http://* || "${ops_domain}" == https://* || "${ops_domain}" == */* || "${ops_domain}" != *"."* ]]; then
|
||||
log_error "OPS_DOMAIN 必须填写平台运营后台的正式域名,当前值:${ops_domain}"
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${ops_domain}" == "${caddy_domain}" || "${ops_domain}" == "${jieyou_domain}" ]]; then
|
||||
log_error "OPS_DOMAIN 不能与主站或解忧商行域名相同"
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${caddy_email}" == "admin@example.com" || "${caddy_email}" != *"@"* ]]; then
|
||||
log_error "CADDY_EMAIL 需要填写真实邮箱,用于 ACME 证书通知"
|
||||
exit 1
|
||||
@@ -270,10 +282,17 @@ export_caddy_env() {
|
||||
export CADDY_EMAIL
|
||||
export CADDY_SHOW_DOMAIN
|
||||
export TENANT_JIEYOU_DOMAIN
|
||||
export OPS_DOMAIN
|
||||
export VITE_OPS_DOMAIN
|
||||
CADDY_DOMAIN="$(require_env CADDY_DOMAIN)"
|
||||
CADDY_EMAIL="$(require_env CADDY_EMAIL)"
|
||||
CADDY_SHOW_DOMAIN="$(env_value CADDY_SHOW_DOMAIN || true)"
|
||||
TENANT_JIEYOU_DOMAIN="$(require_env TENANT_JIEYOU_DOMAIN)"
|
||||
OPS_DOMAIN="$(env_value OPS_DOMAIN || true)"
|
||||
if [[ -z "${OPS_DOMAIN}" ]]; then
|
||||
OPS_DOMAIN="ops.${CADDY_DOMAIN}"
|
||||
fi
|
||||
VITE_OPS_DOMAIN="${OPS_DOMAIN}"
|
||||
export CADDY_SHOW_DOMAIN
|
||||
|
||||
# 分销后台地址:未在 backend/.env 显式配置时,按 Caddyfile 的 distribution.<CADDY_DOMAIN>
|
||||
@@ -731,7 +750,7 @@ main() {
|
||||
|
||||
log_success "部署完成:$(public_url)"
|
||||
log_success "解忧商行后台:https://$(require_env TENANT_JIEYOU_DOMAIN)${VITE_ADMIN_BASE_PATH:-/manage-7x9k2p}/login"
|
||||
log_success "平台运营统计后台:https://ops.$(require_env CADDY_DOMAIN)"
|
||||
log_success "平台运营统计后台:https://$(env_value OPS_DOMAIN || printf 'ops.%s' "$(require_env CADDY_DOMAIN)")"
|
||||
if [[ -n "$(env_value CADDY_SHOW_DOMAIN || true)" ]]; then
|
||||
log_success "选号网:https://$(env_value CADDY_SHOW_DOMAIN)"
|
||||
fi
|
||||
|
||||
@@ -581,9 +581,11 @@ start_frontend() {
|
||||
log "启动前端:http://localhost:${FRONTEND_PORT}"
|
||||
(
|
||||
cd "${FRONTEND_DIR}"
|
||||
load_env_file "${BACKEND_ENV}"
|
||||
export DEV_FRONTEND_PORT="${FRONTEND_PORT}"
|
||||
export DEV_BACKEND_PORT="${BACKEND_PORT}"
|
||||
export VITE_API_PROXY_TARGET="${VITE_API_PROXY_TARGET:-http://127.0.0.1:${BACKEND_PORT}}"
|
||||
export VITE_OPS_DOMAIN="${VITE_OPS_DOMAIN:-${OPS_DOMAIN:-ops.localhost}}"
|
||||
npm run dev
|
||||
) &
|
||||
FRONTEND_PID="$!"
|
||||
|
||||
Reference in New Issue
Block a user