refactor: 数据权限过滤从 GORM Callback 改为 Store 层显式调用
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m2s

- 移除 RegisterDataPermissionCallback 和 SkipDataPermission 机制
- 在 Auth 中间件预计算 SubordinateShopIDs 并注入 Context
- 新增 ApplyShopFilter/ApplyEnterpriseFilter/ApplyOwnerShopFilter 等 Helper 函数
- 所有 Store 层查询方法显式调用数据权限过滤函数
- 权限检查函数 CanManageShop/CanManageEnterprise 改为从 Context 获取数据

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-02-26 16:38:52 +08:00
parent 4ba1f5b99d
commit 03a0960c4d
46 changed files with 1573 additions and 705 deletions

View File

@@ -6,7 +6,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/config"
"github.com/break/junhong_cmp_fiber/pkg/constants"
pkgGorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
"go.uber.org/zap"
)
@@ -15,7 +14,6 @@ func initDefaultAdmin(deps *Dependencies, services *services) error {
cfg := config.Get()
ctx := context.Background()
ctx = pkgGorm.SkipDataPermission(ctx)
var count int64
if err := deps.DB.WithContext(ctx).Model(&model.Account{}).Where("user_type = ?", constants.UserTypeSuperAdmin).Count(&count).Error; err != nil {

View File

@@ -45,8 +45,8 @@ func Bootstrap(deps *Dependencies) (*BootstrapResult, error) {
deps.Logger.Error("初始化默认超级管理员失败", zap.Error(err))
}
// 5. 初始化 Middleware 层
middlewares := initMiddlewares(deps)
// 5. 初始化 Middleware 层(传入 ShopStore 以支持预计算下级店铺 ID
middlewares := initMiddlewares(deps, stores)
// 6. 初始化 Handler 层
handlers := initHandlers(services, deps)
@@ -59,17 +59,12 @@ func Bootstrap(deps *Dependencies) (*BootstrapResult, error) {
// registerGORMCallbacks 注册 GORM Callbacks
func registerGORMCallbacks(deps *Dependencies, stores *stores) error {
// 注册数据权限过滤 Callback使用 ShopStore 来查询下级店铺 ID
if err := pkgGorm.RegisterDataPermissionCallback(deps.DB, stores.Shop); err != nil {
return err
}
// 注册自动添加创建&更新人 Callback
if err := pkgGorm.RegisterSetCreatorUpdaterCallback(deps.DB); err != nil {
return err
}
// TODO: 在此添加其他 GORM Callbacks
// 数据权限过滤已移至 Store 层显式调用 ApplyXxxFilter 函数
return nil
}

View File

@@ -14,7 +14,7 @@ import (
)
// initMiddlewares 初始化所有中间件
func initMiddlewares(deps *Dependencies) *Middlewares {
func initMiddlewares(deps *Dependencies, stores *stores) *Middlewares {
// 获取全局配置
cfg := config.Get()
@@ -29,11 +29,11 @@ func initMiddlewares(deps *Dependencies) *Middlewares {
refreshTTL := time.Duration(cfg.JWT.RefreshTokenTTL) * time.Second
tokenManager := pkgauth.NewTokenManager(deps.Redis, accessTTL, refreshTTL)
// 创建后台认证中间件
adminAuthMiddleware := createAdminAuthMiddleware(tokenManager)
// 创建后台认证中间件(传入 ShopStore 以支持预计算下级店铺 ID
adminAuthMiddleware := createAdminAuthMiddleware(tokenManager, stores.Shop)
// 创建H5认证中间件
h5AuthMiddleware := createH5AuthMiddleware(tokenManager)
// 创建H5认证中间件(传入 ShopStore 以支持预计算下级店铺 ID
h5AuthMiddleware := createH5AuthMiddleware(tokenManager, stores.Shop)
return &Middlewares{
PersonalAuth: personalAuthMiddleware,
@@ -42,7 +42,7 @@ func initMiddlewares(deps *Dependencies) *Middlewares {
}
}
func createAdminAuthMiddleware(tokenManager *pkgauth.TokenManager) fiber.Handler {
func createAdminAuthMiddleware(tokenManager *pkgauth.TokenManager, shopStore pkgmiddleware.AuthShopStoreInterface) fiber.Handler {
return pkgmiddleware.Auth(pkgmiddleware.AuthConfig{
TokenValidator: func(token string) (*pkgmiddleware.UserContextInfo, error) {
tokenInfo, err := tokenManager.ValidateAccessToken(context.Background(), token)
@@ -65,10 +65,11 @@ func createAdminAuthMiddleware(tokenManager *pkgauth.TokenManager) fiber.Handler
}, nil
},
SkipPaths: []string{"/api/admin/login", "/api/admin/refresh-token"},
ShopStore: shopStore,
})
}
func createH5AuthMiddleware(tokenManager *pkgauth.TokenManager) fiber.Handler {
func createH5AuthMiddleware(tokenManager *pkgauth.TokenManager, shopStore pkgmiddleware.AuthShopStoreInterface) fiber.Handler {
return pkgmiddleware.Auth(pkgmiddleware.AuthConfig{
TokenValidator: func(token string) (*pkgmiddleware.UserContextInfo, error) {
tokenInfo, err := tokenManager.ValidateAccessToken(context.Background(), token)
@@ -90,5 +91,6 @@ func createH5AuthMiddleware(tokenManager *pkgauth.TokenManager) fiber.Handler {
}, nil
},
SkipPaths: []string{"/api/h5/login", "/api/h5/refresh-token"},
ShopStore: shopStore,
})
}

View File

@@ -147,6 +147,6 @@ func initServices(s *stores, deps *Dependencies) *services {
PollingMonitoring: pollingSvc.NewMonitoringService(deps.Redis),
PollingAlert: pollingSvc.NewAlertService(s.PollingAlertRule, s.PollingAlertHistory, deps.Redis, deps.Logger),
PollingCleanup: pollingSvc.NewCleanupService(s.DataCleanupConfig, s.DataCleanupLog, deps.Logger),
PollingManualTrigger: pollingSvc.NewManualTriggerService(s.PollingManualTriggerLog, s.IotCard, s.Shop, deps.Redis, deps.Logger),
PollingManualTrigger: pollingSvc.NewManualTriggerService(s.PollingManualTriggerLog, s.IotCard, deps.Redis, deps.Logger),
}
}

View File

@@ -17,13 +17,18 @@ import (
"gorm.io/gorm"
)
// ShopStoreInterface 店铺存储接口(仅用于获取店铺信息)
type ShopStoreInterface interface {
GetByIDs(ctx context.Context, ids []uint) ([]*model.Shop, error)
}
// Service 账号业务服务
type Service struct {
accountStore *postgres.AccountStore
roleStore *postgres.RoleStore
accountRoleStore *postgres.AccountRoleStore
shopRoleStore *postgres.ShopRoleStore
shopStore middleware.ShopStoreInterface
shopStore ShopStoreInterface
enterpriseStore middleware.EnterpriseStoreInterface
auditService AuditServiceInterface
}
@@ -38,7 +43,7 @@ func New(
roleStore *postgres.RoleStore,
accountRoleStore *postgres.AccountRoleStore,
shopRoleStore *postgres.ShopRoleStore,
shopStore middleware.ShopStoreInterface,
shopStore ShopStoreInterface,
enterpriseStore middleware.EnterpriseStoreInterface,
auditService AuditServiceInterface,
) *Service {
@@ -79,13 +84,13 @@ func (s *Service) Create(ctx context.Context, req *dto.CreateAccountRequest) (*m
}
if req.UserType == constants.UserTypeAgent && req.ShopID != nil {
if err := middleware.CanManageShop(ctx, *req.ShopID, s.shopStore); err != nil {
if err := middleware.CanManageShop(ctx, *req.ShopID); err != nil {
return nil, err
}
}
if req.UserType == constants.UserTypeEnterprise && req.EnterpriseID != nil {
if err := middleware.CanManageEnterprise(ctx, *req.EnterpriseID, s.enterpriseStore, s.shopStore); err != nil {
if err := middleware.CanManageEnterprise(ctx, *req.EnterpriseID, s.enterpriseStore); err != nil {
return nil, err
}
}
@@ -190,7 +195,7 @@ func (s *Service) Update(ctx context.Context, id uint, req *dto.UpdateAccountReq
if account.ShopID == nil {
return nil, errors.New(errors.CodeForbidden, "无权限操作该账号")
}
if err := middleware.CanManageShop(ctx, *account.ShopID, s.shopStore); err != nil {
if err := middleware.CanManageShop(ctx, *account.ShopID); err != nil {
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
}
}
@@ -291,7 +296,7 @@ func (s *Service) Delete(ctx context.Context, id uint) error {
if account.ShopID == nil {
return errors.New(errors.CodeForbidden, "无权限操作该账号")
}
if err := middleware.CanManageShop(ctx, *account.ShopID, s.shopStore); err != nil {
if err := middleware.CanManageShop(ctx, *account.ShopID); err != nil {
return errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
}
}
@@ -407,7 +412,7 @@ func (s *Service) AssignRoles(ctx context.Context, accountID uint, roleIDs []uin
if account.ShopID == nil {
return nil, errors.New(errors.CodeForbidden, "无权限操作该账号")
}
if err := middleware.CanManageShop(ctx, *account.ShopID, s.shopStore); err != nil {
if err := middleware.CanManageShop(ctx, *account.ShopID); err != nil {
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
}
}
@@ -558,7 +563,7 @@ func (s *Service) RemoveRole(ctx context.Context, accountID, roleID uint) error
if account.ShopID == nil {
return errors.New(errors.CodeForbidden, "无权限操作该账号")
}
if err := middleware.CanManageShop(ctx, *account.ShopID, s.shopStore); err != nil {
if err := middleware.CanManageShop(ctx, *account.ShopID); err != nil {
return errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
}
}

View File

@@ -10,7 +10,6 @@ import (
"github.com/break/junhong_cmp_fiber/pkg/auth"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
pkgGorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
@@ -47,8 +46,6 @@ func New(
}
func (s *Service) Login(ctx context.Context, req *dto.LoginRequest, clientIP string) (*dto.LoginResponse, error) {
ctx = pkgGorm.SkipDataPermission(ctx)
account, err := s.accountStore.GetByUsernameOrPhone(ctx, req.Username)
if err != nil {
if err == gorm.ErrRecordNotFound {

View File

@@ -9,7 +9,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
pkggorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"go.uber.org/zap"
"gorm.io/gorm"
@@ -426,10 +425,8 @@ func (s *Service) ListDevicesForEnterprise(ctx context.Context, req *dto.Enterpr
authMap[auth.DeviceID] = auth
}
skipCtx := pkggorm.SkipDataPermission(ctx)
var devices []model.Device
query := s.db.WithContext(skipCtx).Where("id IN ?", deviceIDs)
query := s.db.WithContext(ctx).Where("id IN ?", deviceIDs)
if req.DeviceNo != "" {
query = query.Where("device_no LIKE ?", "%"+req.DeviceNo+"%")
}
@@ -438,7 +435,7 @@ func (s *Service) ListDevicesForEnterprise(ctx context.Context, req *dto.Enterpr
}
var bindings []model.DeviceSimBinding
if err := s.db.WithContext(skipCtx).
if err := s.db.WithContext(ctx).
Where("device_id IN ? AND bind_status = 1", deviceIDs).
Find(&bindings).Error; err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "查询设备绑定卡失败")
@@ -480,15 +477,14 @@ func (s *Service) GetDeviceDetail(ctx context.Context, deviceID uint) (*dto.Ente
return nil, errors.New(errors.CodeDeviceNotAuthorized, "设备未授权给此企业")
}
skipCtx := pkggorm.SkipDataPermission(ctx)
var device model.Device
if err := s.db.WithContext(skipCtx).Where("id = ?", deviceID).First(&device).Error; err != nil {
if err := s.db.WithContext(ctx).Where("id = ?", deviceID).First(&device).Error; err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "查询设备信息失败")
}
var bindings []model.DeviceSimBinding
if err := s.db.WithContext(skipCtx).
if err := s.db.WithContext(ctx).
Where("device_id = ? AND bind_status = 1", deviceID).
Find(&bindings).Error; err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "查询设备绑定卡失败")
@@ -502,7 +498,7 @@ func (s *Service) GetDeviceDetail(ctx context.Context, deviceID uint) (*dto.Ente
var cards []model.IotCard
cardInfos := make([]dto.DeviceCardInfo, 0)
if len(cardIDs) > 0 {
if err := s.db.WithContext(skipCtx).Where("id IN ?", cardIDs).Find(&cards).Error; err != nil {
if err := s.db.WithContext(ctx).Where("id IN ?", cardIDs).Find(&cards).Error; err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "查询卡信息失败")
}
@@ -514,7 +510,7 @@ func (s *Service) GetDeviceDetail(ctx context.Context, deviceID uint) (*dto.Ente
var carriers []model.Carrier
carrierMap := make(map[uint]string)
if len(carrierIDs) > 0 {
if err := s.db.WithContext(skipCtx).Where("id IN ?", carrierIDs).Find(&carriers).Error; err == nil {
if err := s.db.WithContext(ctx).Where("id IN ?", carrierIDs).Find(&carriers).Error; err == nil {
for _, carrier := range carriers {
carrierMap[carrier.ID] = carrier.CarrierName
}
@@ -551,8 +547,7 @@ func (s *Service) SuspendCard(ctx context.Context, deviceID, cardID uint, req *d
return nil, err
}
skipCtx := pkggorm.SkipDataPermission(ctx)
if err := s.db.WithContext(skipCtx).Model(&model.IotCard{}).
if err := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("id = ?", cardID).
Update("network_status", 0).Error; err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "停机操作失败")
@@ -569,8 +564,7 @@ func (s *Service) ResumeCard(ctx context.Context, deviceID, cardID uint, req *dt
return nil, err
}
skipCtx := pkggorm.SkipDataPermission(ctx)
if err := s.db.WithContext(skipCtx).Model(&model.IotCard{}).
if err := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("id = ?", cardID).
Update("network_status", 1).Error; err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "复机操作失败")
@@ -593,17 +587,16 @@ func (s *Service) validateCardOperation(ctx context.Context, deviceID, cardID ui
return errors.New(errors.CodeDeviceNotAuthorized, "设备未授权给此企业")
}
skipCtx := pkggorm.SkipDataPermission(ctx)
var binding model.DeviceSimBinding
if err := s.db.WithContext(skipCtx).
if err := s.db.WithContext(ctx).
Where("device_id = ? AND iot_card_id = ? AND bind_status = 1", deviceID, cardID).
First(&binding).Error; err != nil {
return errors.New(errors.CodeForbidden, "卡不属于该设备")
}
var cardAuth model.EnterpriseCardAuthorization
if err := s.db.WithContext(skipCtx).
if err := s.db.WithContext(ctx).
Where("enterprise_id = ? AND card_id = ? AND device_auth_id IS NOT NULL AND revoked_at IS NULL", enterpriseID, cardID).
First(&cardAuth).Error; err != nil {
return errors.New(errors.CodeForbidden, "无权操作此卡")

View File

@@ -19,7 +19,6 @@ import (
type ManualTriggerService struct {
logStore *postgres.PollingManualTriggerLogStore
iotCardStore *postgres.IotCardStore
shopStore middleware.ShopStoreInterface
redis *redis.Client
logger *zap.Logger
}
@@ -28,14 +27,12 @@ type ManualTriggerService struct {
func NewManualTriggerService(
logStore *postgres.PollingManualTriggerLogStore,
iotCardStore *postgres.IotCardStore,
shopStore middleware.ShopStoreInterface,
redis *redis.Client,
logger *zap.Logger,
) *ManualTriggerService {
return &ManualTriggerService{
logStore: logStore,
iotCardStore: iotCardStore,
shopStore: shopStore,
redis: redis,
logger: logger,
}
@@ -386,7 +383,7 @@ func (s *ManualTriggerService) canManageCard(ctx context.Context, cardID uint) e
}
// 检查代理是否有权管理该店铺
return middleware.CanManageShop(ctx, *card.ShopID, s.shopStore)
return middleware.CanManageShop(ctx, *card.ShopID)
}
// canManageCards 检查用户是否有权管理多张卡
@@ -403,18 +400,13 @@ func (s *ManualTriggerService) canManageCards(ctx context.Context, cardIDs []uin
return errors.New(errors.CodeForbidden, "企业账号无权限手动触发轮询")
}
// 代理账号只能管理自己店铺及下级店铺的卡
currentShopID := middleware.GetShopIDFromContext(ctx)
if currentShopID == 0 {
// 从 Context 获取预计算的下级店铺 ID 列表
subordinateIDs := middleware.GetSubordinateShopIDs(ctx)
if subordinateIDs == nil {
// 平台用户/超管不受限制,但这里不应该进入(前面已经检查过用户类型)
return errors.New(errors.CodeForbidden, "无权限操作")
}
// 获取下级店铺ID列表
subordinateIDs, err := s.shopStore.GetSubordinateShopIDs(ctx, currentShopID)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "查询下级店铺失败")
}
// 构建可管理的店铺ID集合
allowedShopIDs := make(map[uint]bool)
for _, id := range subordinateIDs {
@@ -462,7 +454,7 @@ func (s *ManualTriggerService) applyShopPermissionFilter(ctx context.Context, fi
// 如果用户指定了 ShopID验证是否在可管理范围内
if filter.ShopID != nil {
if err := middleware.CanManageShop(ctx, *filter.ShopID, s.shopStore); err != nil {
if err := middleware.CanManageShop(ctx, *filter.ShopID); err != nil {
return err
}
// 已指定有效的 ShopID无需修改

View File

@@ -11,7 +11,7 @@ import (
)
func (s *Service) AssignRolesToShop(ctx context.Context, shopID uint, roleIDs []uint) ([]*model.ShopRole, error) {
if err := middleware.CanManageShop(ctx, shopID, s.shopStore); err != nil {
if err := middleware.CanManageShop(ctx, shopID); err != nil {
return nil, err
}
@@ -70,7 +70,7 @@ func (s *Service) AssignRolesToShop(ctx context.Context, shopID uint, roleIDs []
}
func (s *Service) GetShopRoles(ctx context.Context, shopID uint) (*dto.ShopRolesResponse, error) {
if err := middleware.CanManageShop(ctx, shopID, s.shopStore); err != nil {
if err := middleware.CanManageShop(ctx, shopID); err != nil {
return nil, err
}
@@ -128,7 +128,7 @@ func (s *Service) GetShopRoles(ctx context.Context, shopID uint) (*dto.ShopRoles
}
func (s *Service) DeleteShopRole(ctx context.Context, shopID, roleID uint) error {
if err := middleware.CanManageShop(ctx, shopID, s.shopStore); err != nil {
if err := middleware.CanManageShop(ctx, shopID); err != nil {
return err
}

View File

@@ -10,7 +10,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
pkggorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"gorm.io/gorm"
)
@@ -71,9 +70,8 @@ func (s *Service) Create(ctx context.Context, req *dto.CreateShopSeriesAllocatio
return nil, errors.Wrap(errors.CodeInternalError, err, "获取套餐系列失败")
}
// 检查是否已存在分配(跳过数据权限过滤,避免误判)
skipCtx := pkggorm.SkipDataPermission(ctx)
exists, err := s.seriesAllocationStore.ExistsByShopAndSeries(skipCtx, req.ShopID, req.SeriesID)
// 检查是否已存在分配
exists, err := s.seriesAllocationStore.ExistsByShopAndSeries(ctx, req.ShopID, req.SeriesID)
if err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "检查分配记录失败")
}
@@ -84,7 +82,7 @@ func (s *Service) Create(ctx context.Context, req *dto.CreateShopSeriesAllocatio
// 代理用户:检查自己是否有该系列的分配权限,且金额不能超过上级给的上限
// 平台用户:无上限限制,可自由设定金额
if userType == constants.UserTypeAgent {
allocatorAllocation, err := s.seriesAllocationStore.GetByShopAndSeries(skipCtx, allocatorShopID, req.SeriesID)
allocatorAllocation, err := s.seriesAllocationStore.GetByShopAndSeries(ctx, allocatorShopID, req.SeriesID)
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, errors.New(errors.CodeForbidden, "您没有该套餐系列的分配权限")
@@ -239,8 +237,7 @@ func (s *Service) Update(ctx context.Context, id uint, req *dto.UpdateShopSeries
}
func (s *Service) Delete(ctx context.Context, id uint) error {
skipCtx := pkggorm.SkipDataPermission(ctx)
_, err := s.seriesAllocationStore.GetByID(skipCtx, id)
_, err := s.seriesAllocationStore.GetByID(ctx, id)
if err != nil {
if err == gorm.ErrRecordNotFound {
return errors.New(errors.CodeNotFound, "分配记录不存在")
@@ -248,7 +245,7 @@ func (s *Service) Delete(ctx context.Context, id uint) error {
return errors.Wrap(errors.CodeInternalError, err, "获取分配记录失败")
}
count, err := s.packageAllocationStore.CountBySeriesAllocationID(skipCtx, id)
count, err := s.packageAllocationStore.CountBySeriesAllocationID(ctx, id)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "检查关联套餐分配失败")
}
@@ -256,7 +253,7 @@ func (s *Service) Delete(ctx context.Context, id uint) error {
return errors.New(errors.CodeInvalidParam, "存在关联的套餐分配,无法删除")
}
if err := s.seriesAllocationStore.Delete(skipCtx, id); err != nil {
if err := s.seriesAllocationStore.Delete(ctx, id); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "删除分配失败")
}

View File

@@ -3,9 +3,9 @@ package postgres
import (
"context"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -32,7 +32,12 @@ func (s *AccountStore) Create(ctx context.Context, account *model.Account) error
// GetByID 根据 ID 获取账号
func (s *AccountStore) GetByID(ctx context.Context, id uint) (*model.Account, error) {
var account model.Account
if err := s.db.WithContext(ctx).First(&account, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 根据当前用户类型应用数据权限过滤
// 代理用户:过滤 shop_id企业用户过滤 enterprise_id
query = middleware.ApplyShopFilter(ctx, query)
query = middleware.ApplyEnterpriseFilter(ctx, query)
if err := query.First(&account).Error; err != nil {
return nil, err
}
return &account, nil
@@ -68,7 +73,10 @@ func (s *AccountStore) GetByUsernameOrPhone(ctx context.Context, identifier stri
// GetByShopID 根据店铺 ID 查询账号列表
func (s *AccountStore) GetByShopID(ctx context.Context, shopID uint) ([]*model.Account, error) {
var accounts []*model.Account
if err := s.db.WithContext(ctx).Where("shop_id = ?", shopID).Find(&accounts).Error; err != nil {
query := s.db.WithContext(ctx).Where("shop_id = ?", shopID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&accounts).Error; err != nil {
return nil, err
}
return accounts, nil
@@ -77,7 +85,10 @@ func (s *AccountStore) GetByShopID(ctx context.Context, shopID uint) ([]*model.A
// GetByEnterpriseID 根据企业 ID 查询账号列表
func (s *AccountStore) GetByEnterpriseID(ctx context.Context, enterpriseID uint) ([]*model.Account, error) {
var accounts []*model.Account
if err := s.db.WithContext(ctx).Where("enterprise_id = ?", enterpriseID).Find(&accounts).Error; err != nil {
query := s.db.WithContext(ctx).Where("enterprise_id = ?", enterpriseID)
// 应用企业数据权限过滤
query = middleware.ApplyEnterpriseFilter(ctx, query)
if err := query.Find(&accounts).Error; err != nil {
return nil, err
}
return accounts, nil
@@ -99,6 +110,10 @@ func (s *AccountStore) List(ctx context.Context, opts *store.QueryOptions, filte
var total int64
query := s.db.WithContext(ctx).Model(&model.Account{})
// 根据当前用户类型应用数据权限过滤
// 代理用户:过滤 shop_id企业用户过滤 enterprise_id
query = middleware.ApplyShopFilter(ctx, query)
query = middleware.ApplyEnterpriseFilter(ctx, query)
// 应用过滤条件
if username, ok := filters["username"].(string); ok && username != "" {
@@ -229,7 +244,11 @@ func (s *AccountStore) GetByIDs(ctx context.Context, ids []uint) ([]*model.Accou
return []*model.Account{}, nil
}
var accounts []*model.Account
if err := s.db.WithContext(ctx).Where("id IN ?", ids).Find(&accounts).Error; err != nil {
query := s.db.WithContext(ctx).Where("id IN ?", ids)
// 根据当前用户类型应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
query = middleware.ApplyEnterpriseFilter(ctx, query)
if err := query.Find(&accounts).Error; err != nil {
return nil, err
}
return accounts, nil
@@ -240,9 +259,11 @@ func (s *AccountStore) GetPrimaryAccountsByShopIDs(ctx context.Context, shopIDs
return []*model.Account{}, nil
}
var accounts []*model.Account
if err := s.db.WithContext(ctx).
Where("shop_id IN ? AND is_primary = ?", shopIDs, true).
Find(&accounts).Error; err != nil {
query := s.db.WithContext(ctx).
Where("shop_id IN ? AND is_primary = ?", shopIDs, true)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&accounts).Error; err != nil {
return nil, err
}
return accounts, nil
@@ -254,6 +275,8 @@ func (s *AccountStore) ListByShopID(ctx context.Context, shopID uint, opts *stor
var total int64
query := s.db.WithContext(ctx).Model(&model.Account{}).Where("shop_id = ?", shopID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if username, ok := filters["username"].(string); ok && username != "" {
query = query.Where("username LIKE ?", "%"+username+"%")

View File

@@ -6,6 +6,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -41,9 +42,11 @@ func (s *AgentWalletStore) GetByShopIDAndType(ctx context.Context, shopID uint,
// 注意:这里简化处理,实际项目中可以缓存完整的钱包信息
var wallet model.AgentWallet
err := s.db.WithContext(ctx).
Where("shop_id = ? AND wallet_type = ?", shopID, walletType).
First(&wallet).Error
query := s.db.WithContext(ctx).
Where("shop_id = ? AND wallet_type = ?", shopID, walletType)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
err := query.First(&wallet).Error
if err != nil {
return nil, err
}
@@ -58,7 +61,10 @@ func (s *AgentWalletStore) GetByShopIDAndType(ctx context.Context, shopID uint,
// GetByID 根据钱包 ID 查询
func (s *AgentWalletStore) GetByID(ctx context.Context, id uint) (*model.AgentWallet, error) {
var wallet model.AgentWallet
if err := s.db.WithContext(ctx).First(&wallet, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&wallet).Error; err != nil {
return nil, err
}
return &wallet, nil
@@ -209,9 +215,11 @@ func (s *AgentWalletStore) GetShopCommissionSummaryBatch(ctx context.Context, sh
}
var wallets []model.AgentWallet
err := s.db.WithContext(ctx).
Where("shop_id IN ? AND wallet_type = ?", shopIDs, constants.AgentWalletTypeCommission).
Find(&wallets).Error
query := s.db.WithContext(ctx).
Where("shop_id IN ? AND wallet_type = ?", shopIDs, constants.AgentWalletTypeCommission)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
err := query.Find(&wallets).Error
if err != nil {
return nil, err
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -30,9 +31,11 @@ func (s *AgentWalletTransactionStore) CreateWithTx(ctx context.Context, tx *gorm
// ListByShopID 按店铺查询交易记录(支持分页)
func (s *AgentWalletTransactionStore) ListByShopID(ctx context.Context, shopID uint, offset, limit int) ([]*model.AgentWalletTransaction, error) {
var transactions []*model.AgentWalletTransaction
err := s.db.WithContext(ctx).
Where("shop_id = ?", shopID).
Order("created_at DESC").
query := s.db.WithContext(ctx).
Where("shop_id = ?", shopID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
err := query.Order("created_at DESC").
Offset(offset).
Limit(limit).
Find(&transactions).Error
@@ -45,19 +48,23 @@ func (s *AgentWalletTransactionStore) ListByShopID(ctx context.Context, shopID u
// CountByShopID 统计店铺的交易记录数量
func (s *AgentWalletTransactionStore) CountByShopID(ctx context.Context, shopID uint) (int64, error) {
var count int64
err := s.db.WithContext(ctx).
query := s.db.WithContext(ctx).
Model(&model.AgentWalletTransaction{}).
Where("shop_id = ?", shopID).
Count(&count).Error
Where("shop_id = ?", shopID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
err := query.Count(&count).Error
return count, err
}
// ListByWalletID 按钱包查询交易记录(支持分页)
func (s *AgentWalletTransactionStore) ListByWalletID(ctx context.Context, walletID uint, offset, limit int) ([]*model.AgentWalletTransaction, error) {
var transactions []*model.AgentWalletTransaction
err := s.db.WithContext(ctx).
Where("agent_wallet_id = ?", walletID).
Order("created_at DESC").
query := s.db.WithContext(ctx).
Where("agent_wallet_id = ?", walletID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
err := query.Order("created_at DESC").
Offset(offset).
Limit(limit).
Find(&transactions).Error
@@ -70,9 +77,11 @@ func (s *AgentWalletTransactionStore) ListByWalletID(ctx context.Context, wallet
// GetByReference 根据关联业务查询交易记录
func (s *AgentWalletTransactionStore) GetByReference(ctx context.Context, referenceType string, referenceID uint) (*model.AgentWalletTransaction, error) {
var transaction model.AgentWalletTransaction
err := s.db.WithContext(ctx).
Where("reference_type = ? AND reference_id = ?", referenceType, referenceID).
First(&transaction).Error
query := s.db.WithContext(ctx).
Where("reference_type = ? AND reference_id = ?", referenceType, referenceID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
err := query.First(&transaction).Error
if err != nil {
return nil, err
}

View File

@@ -6,6 +6,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -27,9 +28,11 @@ func NewCardWalletStore(db *gorm.DB, redis *redis.Client) *CardWalletStore {
// GetByResourceTypeAndID 根据资源类型和 ID 查询钱包
func (s *CardWalletStore) GetByResourceTypeAndID(ctx context.Context, resourceType string, resourceID uint) (*model.CardWallet, error) {
var wallet model.CardWallet
err := s.db.WithContext(ctx).
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID).
First(&wallet).Error
query := s.db.WithContext(ctx).
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
// 应用数据权限过滤(使用 shop_id_tag 字段)
query = middleware.ApplyShopTagFilter(ctx, query)
err := query.First(&wallet).Error
if err != nil {
return nil, err
}
@@ -39,7 +42,10 @@ func (s *CardWalletStore) GetByResourceTypeAndID(ctx context.Context, resourceTy
// GetByID 根据钱包 ID 查询
func (s *CardWalletStore) GetByID(ctx context.Context, id uint) (*model.CardWallet, error) {
var wallet model.CardWallet
if err := s.db.WithContext(ctx).First(&wallet, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤(使用 shop_id_tag 字段)
query = middleware.ApplyShopTagFilter(ctx, query)
if err := query.First(&wallet).Error; err != nil {
return nil, err
}
return &wallet, nil

View File

@@ -4,6 +4,7 @@ import (
"context"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -30,9 +31,11 @@ func (s *CardWalletTransactionStore) CreateWithTx(ctx context.Context, tx *gorm.
// ListByResourceID 按资源查询交易记录(支持分页)
func (s *CardWalletTransactionStore) ListByResourceID(ctx context.Context, resourceType string, resourceID uint, offset, limit int) ([]*model.CardWalletTransaction, error) {
var transactions []*model.CardWalletTransaction
err := s.db.WithContext(ctx).
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID).
Order("created_at DESC").
query := s.db.WithContext(ctx).
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
// 应用数据权限过滤(使用 shop_id_tag 字段)
query = middleware.ApplyShopTagFilter(ctx, query)
err := query.Order("created_at DESC").
Offset(offset).
Limit(limit).
Find(&transactions).Error
@@ -45,19 +48,23 @@ func (s *CardWalletTransactionStore) ListByResourceID(ctx context.Context, resou
// CountByResourceID 统计资源的交易记录数量
func (s *CardWalletTransactionStore) CountByResourceID(ctx context.Context, resourceType string, resourceID uint) (int64, error) {
var count int64
err := s.db.WithContext(ctx).
query := s.db.WithContext(ctx).
Model(&model.CardWalletTransaction{}).
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID).
Count(&count).Error
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
// 应用数据权限过滤(使用 shop_id_tag 字段)
query = middleware.ApplyShopTagFilter(ctx, query)
err := query.Count(&count).Error
return count, err
}
// ListByWalletID 按钱包查询交易记录(支持分页)
func (s *CardWalletTransactionStore) ListByWalletID(ctx context.Context, walletID uint, offset, limit int) ([]*model.CardWalletTransaction, error) {
var transactions []*model.CardWalletTransaction
err := s.db.WithContext(ctx).
Where("card_wallet_id = ?", walletID).
Order("created_at DESC").
query := s.db.WithContext(ctx).
Where("card_wallet_id = ?", walletID)
// 应用数据权限过滤(使用 shop_id_tag 字段)
query = middleware.ApplyShopTagFilter(ctx, query)
err := query.Order("created_at DESC").
Offset(offset).
Limit(limit).
Find(&transactions).Error
@@ -70,9 +77,11 @@ func (s *CardWalletTransactionStore) ListByWalletID(ctx context.Context, walletI
// GetByReference 根据关联业务查询交易记录
func (s *CardWalletTransactionStore) GetByReference(ctx context.Context, referenceType string, referenceID uint) (*model.CardWalletTransaction, error) {
var transaction model.CardWalletTransaction
err := s.db.WithContext(ctx).
Where("reference_type = ? AND reference_id = ?", referenceType, referenceID).
First(&transaction).Error
query := s.db.WithContext(ctx).
Where("reference_type = ? AND reference_id = ?", referenceType, referenceID)
// 应用数据权限过滤(使用 shop_id_tag 字段)
query = middleware.ApplyShopTagFilter(ctx, query)
err := query.First(&transaction).Error
if err != nil {
return nil, err
}

View File

@@ -6,6 +6,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -28,7 +29,10 @@ func (s *CommissionRecordStore) Create(ctx context.Context, record *model.Commis
func (s *CommissionRecordStore) GetByID(ctx context.Context, id uint) (*model.CommissionRecord, error) {
var record model.CommissionRecord
if err := s.db.WithContext(ctx).First(&record, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&record).Error; err != nil {
return nil, err
}
return &record, nil
@@ -50,6 +54,8 @@ func (s *CommissionRecordStore) ListByShopID(ctx context.Context, opts *store.Qu
var total int64
query := s.db.WithContext(ctx).Model(&model.CommissionRecord{})
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if filters != nil {
if filters.ShopID > 0 {
@@ -107,6 +113,8 @@ type CommissionStats struct {
func (s *CommissionRecordStore) GetStats(ctx context.Context, filters *CommissionRecordListFilters) (*CommissionStats, error) {
query := s.db.WithContext(ctx).Model(&model.CommissionRecord{}).
Where("status = ?", model.CommissionStatusReleased)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if filters != nil {
if filters.ShopID > 0 {
@@ -151,6 +159,8 @@ func (s *CommissionRecordStore) GetDailyStats(ctx context.Context, filters *Comm
query := s.db.WithContext(ctx).Model(&model.CommissionRecord{}).
Where("status = ?", model.CommissionStatusReleased)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if filters != nil {
if filters.ShopID > 0 {

View File

@@ -7,6 +7,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -29,7 +30,10 @@ func (s *CommissionWithdrawalRequestStore) Create(ctx context.Context, req *mode
func (s *CommissionWithdrawalRequestStore) GetByID(ctx context.Context, id uint) (*model.CommissionWithdrawalRequest, error) {
var req model.CommissionWithdrawalRequest
if err := s.db.WithContext(ctx).First(&req, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&req).Error; err != nil {
return nil, err
}
return &req, nil
@@ -52,6 +56,8 @@ func (s *CommissionWithdrawalRequestStore) ListByShopID(ctx context.Context, opt
var total int64
query := s.db.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{})
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if filters != nil {
if filters.ShopID > 0 {
@@ -146,6 +152,8 @@ func (s *CommissionWithdrawalRequestStore) List(ctx context.Context, opts *store
var total int64
query := s.db.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{})
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if filters != nil {
if filters.WithdrawalNo != "" {

View File

@@ -7,6 +7,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -36,7 +37,10 @@ func (s *DeviceStore) CreateBatch(ctx context.Context, devices []*model.Device)
func (s *DeviceStore) GetByID(ctx context.Context, id uint) (*model.Device, error) {
var device model.Device
if err := s.db.WithContext(ctx).First(&device, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤NULL shop_id 对代理用户不可见)
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&device).Error; err != nil {
return nil, err
}
return &device, nil
@@ -44,7 +48,10 @@ func (s *DeviceStore) GetByID(ctx context.Context, id uint) (*model.Device, erro
func (s *DeviceStore) GetByDeviceNo(ctx context.Context, deviceNo string) (*model.Device, error) {
var device model.Device
if err := s.db.WithContext(ctx).Where("device_no = ?", deviceNo).First(&device).Error; err != nil {
query := s.db.WithContext(ctx).Where("device_no = ?", deviceNo)
// 应用数据权限过滤NULL shop_id 对代理用户不可见)
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&device).Error; err != nil {
return nil, err
}
return &device, nil
@@ -55,7 +62,10 @@ func (s *DeviceStore) GetByIDs(ctx context.Context, ids []uint) ([]*model.Device
if len(ids) == 0 {
return devices, nil
}
if err := s.db.WithContext(ctx).Where("id IN ?", ids).Find(&devices).Error; err != nil {
query := s.db.WithContext(ctx).Where("id IN ?", ids)
// 应用数据权限过滤NULL shop_id 对代理用户不可见)
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&devices).Error; err != nil {
return nil, err
}
return devices, nil
@@ -74,6 +84,8 @@ func (s *DeviceStore) List(ctx context.Context, opts *store.QueryOptions, filter
var total int64
query := s.db.WithContext(ctx).Model(&model.Device{})
// 应用数据权限过滤NULL shop_id 对代理用户不可见)
query = middleware.ApplyShopFilter(ctx, query)
if deviceNo, ok := filters["device_no"].(string); ok && deviceNo != "" {
query = query.Where("device_no LIKE ?", "%"+deviceNo+"%")
@@ -179,7 +191,10 @@ func (s *DeviceStore) GetByDeviceNos(ctx context.Context, deviceNos []string) ([
if len(deviceNos) == 0 {
return devices, nil
}
if err := s.db.WithContext(ctx).Where("device_no IN ?", deviceNos).Find(&devices).Error; err != nil {
query := s.db.WithContext(ctx).Where("device_no IN ?", deviceNos)
// 应用数据权限过滤NULL shop_id 对代理用户不可见)
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&devices).Error; err != nil {
return nil, err
}
return devices, nil
@@ -198,7 +213,10 @@ func (s *DeviceStore) BatchUpdateSeriesID(ctx context.Context, deviceIDs []uint,
// ListBySeriesID 根据套餐系列ID查询设备列表
func (s *DeviceStore) ListBySeriesID(ctx context.Context, seriesID uint) ([]*model.Device, error) {
var devices []*model.Device
if err := s.db.WithContext(ctx).Where("series_id = ?", seriesID).Find(&devices).Error; err != nil {
query := s.db.WithContext(ctx).Where("series_id = ?", seriesID)
// 应用数据权限过滤NULL shop_id 对代理用户不可见)
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&devices).Error; err != nil {
return nil, err
}
return devices, nil

View File

@@ -6,7 +6,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/constants"
pkgGorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
@@ -50,9 +49,11 @@ func (s *EnterpriseCardAuthorizationStore) RevokeAuthorizations(ctx context.Cont
func (s *EnterpriseCardAuthorizationStore) GetByEnterpriseAndCard(ctx context.Context, enterpriseID, cardID uint) (*model.EnterpriseCardAuthorization, error) {
var auth model.EnterpriseCardAuthorization
err := s.db.WithContext(ctx).
Where("enterprise_id = ? AND card_id = ?", enterpriseID, cardID).
First(&auth).Error
query := s.db.WithContext(ctx).
Where("enterprise_id = ? AND card_id = ?", enterpriseID, cardID)
// 应用数据权限过滤
query = s.applyEnterpriseAuthFilter(ctx, query)
err := query.First(&auth).Error
if err != nil {
return nil, err
}
@@ -62,6 +63,8 @@ func (s *EnterpriseCardAuthorizationStore) GetByEnterpriseAndCard(ctx context.Co
func (s *EnterpriseCardAuthorizationStore) ListByEnterprise(ctx context.Context, enterpriseID uint, includeRevoked bool) ([]*model.EnterpriseCardAuthorization, error) {
var auths []*model.EnterpriseCardAuthorization
query := s.db.WithContext(ctx).Where("enterprise_id = ?", enterpriseID)
// 应用数据权限过滤
query = s.applyEnterpriseAuthFilter(ctx, query)
if !includeRevoked {
query = query.Where("revoked_at IS NULL")
}
@@ -77,6 +80,8 @@ func (s *EnterpriseCardAuthorizationStore) ListByCards(ctx context.Context, card
}
var auths []*model.EnterpriseCardAuthorization
query := s.db.WithContext(ctx).Where("card_id IN ?", cardIDs)
// 应用数据权限过滤
query = s.applyEnterpriseAuthFilter(ctx, query)
if !includeRevoked {
query = query.Where("revoked_at IS NULL")
}
@@ -88,17 +93,21 @@ func (s *EnterpriseCardAuthorizationStore) ListByCards(ctx context.Context, card
func (s *EnterpriseCardAuthorizationStore) GetActiveAuthorizedCardIDs(ctx context.Context, enterpriseID uint) ([]uint, error) {
var cardIDs []uint
err := s.db.WithContext(ctx).Model(&model.EnterpriseCardAuthorization{}).
Where("enterprise_id = ? AND revoked_at IS NULL", enterpriseID).
Pluck("card_id", &cardIDs).Error
query := s.db.WithContext(ctx).Model(&model.EnterpriseCardAuthorization{}).
Where("enterprise_id = ? AND revoked_at IS NULL", enterpriseID)
// 应用数据权限过滤
query = s.applyEnterpriseAuthFilter(ctx, query)
err := query.Pluck("card_id", &cardIDs).Error
return cardIDs, err
}
func (s *EnterpriseCardAuthorizationStore) CheckAuthorizationExists(ctx context.Context, enterpriseID, cardID uint) (bool, error) {
var count int64
err := s.db.WithContext(ctx).Model(&model.EnterpriseCardAuthorization{}).
Where("enterprise_id = ? AND card_id = ? AND revoked_at IS NULL", enterpriseID, cardID).
Count(&count).Error
query := s.db.WithContext(ctx).Model(&model.EnterpriseCardAuthorization{}).
Where("enterprise_id = ? AND card_id = ? AND revoked_at IS NULL", enterpriseID, cardID)
// 应用数据权限过滤
query = s.applyEnterpriseAuthFilter(ctx, query)
err := query.Count(&count).Error
return count > 0, err
}
@@ -115,6 +124,8 @@ type AuthorizationListOptions struct {
func (s *EnterpriseCardAuthorizationStore) ListWithOptions(ctx context.Context, opts AuthorizationListOptions) ([]*model.EnterpriseCardAuthorization, int64, error) {
var auths []*model.EnterpriseCardAuthorization
query := s.db.WithContext(ctx).Model(&model.EnterpriseCardAuthorization{})
// 应用数据权限过滤
query = s.applyEnterpriseAuthFilter(ctx, query)
if opts.EnterpriseID != nil {
query = query.Where("enterprise_id = ?", *opts.EnterpriseID)
@@ -154,9 +165,11 @@ func (s *EnterpriseCardAuthorizationStore) GetActiveAuthsByCardIDs(ctx context.C
return make(map[uint]bool), nil
}
var authCardIDs []uint
err := s.db.WithContext(ctx).Model(&model.EnterpriseCardAuthorization{}).
Where("enterprise_id = ? AND card_id IN ? AND revoked_at IS NULL", enterpriseID, cardIDs).
Pluck("card_id", &authCardIDs).Error
query := s.db.WithContext(ctx).Model(&model.EnterpriseCardAuthorization{}).
Where("enterprise_id = ? AND card_id IN ? AND revoked_at IS NULL", enterpriseID, cardIDs)
// 应用数据权限过滤
query = s.applyEnterpriseAuthFilter(ctx, query)
err := query.Pluck("card_id", &authCardIDs).Error
if err != nil {
return nil, err
}
@@ -186,9 +199,11 @@ func (s *EnterpriseCardAuthorizationStore) BatchUpdateStatus(ctx context.Context
// ListCardIDsByEnterprise 获取企业的有效授权卡ID列表
func (s *EnterpriseCardAuthorizationStore) ListCardIDsByEnterprise(ctx context.Context, enterpriseID uint) ([]uint, error) {
var cardIDs []uint
err := s.db.WithContext(ctx).Model(&model.EnterpriseCardAuthorization{}).
Where("enterprise_id = ? AND revoked_at IS NULL", enterpriseID).
Pluck("card_id", &cardIDs).Error
query := s.db.WithContext(ctx).Model(&model.EnterpriseCardAuthorization{}).
Where("enterprise_id = ? AND revoked_at IS NULL", enterpriseID)
// 应用数据权限过滤
query = s.applyEnterpriseAuthFilter(ctx, query)
err := query.Pluck("card_id", &cardIDs).Error
return cardIDs, err
}
@@ -233,31 +248,28 @@ func (s *EnterpriseCardAuthorizationStore) ListWithJoin(ctx context.Context, opt
args := []interface{}{}
// 数据权限过滤(原生 SQL 需要手动处理)
// 检查是否跳过数据权限过滤
if skip, ok := ctx.Value(pkgGorm.SkipDataPermissionKey).(bool); !ok || !skip {
userType := middleware.GetUserTypeFromContext(ctx)
// 超级管理员和平台用户跳过过滤
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
if userType == constants.UserTypeAgent {
shopID := middleware.GetShopIDFromContext(ctx)
if shopID == 0 {
// 代理用户没有 shop_id返回空结果
return []AuthorizationWithJoin{}, 0, nil
}
// 只能看到自己店铺下企业的授权记录(不包含下级店铺)
baseQuery += " AND a.enterprise_id IN (SELECT id FROM tb_enterprise WHERE owner_shop_id = ? AND deleted_at IS NULL)"
args = append(args, shopID)
} else if userType == constants.UserTypeEnterprise {
enterpriseID := middleware.GetEnterpriseIDFromContext(ctx)
if enterpriseID == 0 {
return []AuthorizationWithJoin{}, 0, nil
}
baseQuery += " AND a.enterprise_id = ?"
args = append(args, enterpriseID)
} else {
// 其他用户类型(个人客户等)不应访问授权记录
userType := middleware.GetUserTypeFromContext(ctx)
// 超级管理员和平台用户跳过过滤
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
if userType == constants.UserTypeAgent {
// 代理用户:只能看到自己及下级店铺所拥有企业的授权记录
shopIDs := middleware.GetSubordinateShopIDs(ctx)
if len(shopIDs) == 0 {
// 代理用户没有下级店铺信息,返回空结果
return []AuthorizationWithJoin{}, 0, nil
}
baseQuery += " AND a.enterprise_id IN (SELECT id FROM tb_enterprise WHERE owner_shop_id IN (?) AND deleted_at IS NULL)"
args = append(args, shopIDs)
} else if userType == constants.UserTypeEnterprise {
enterpriseID := middleware.GetEnterpriseIDFromContext(ctx)
if enterpriseID == 0 {
return []AuthorizationWithJoin{}, 0, nil
}
baseQuery += " AND a.enterprise_id = ?"
args = append(args, enterpriseID)
} else {
// 其他用户类型(个人客户等)不应访问授权记录
return []AuthorizationWithJoin{}, 0, nil
}
}
@@ -338,26 +350,25 @@ func (s *EnterpriseCardAuthorizationStore) GetByIDWithJoin(ctx context.Context,
args := []interface{}{id}
// 数据权限过滤(原生 SQL 需要手动处理)
if skip, ok := ctx.Value(pkgGorm.SkipDataPermissionKey).(bool); !ok || !skip {
userType := middleware.GetUserTypeFromContext(ctx)
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
if userType == constants.UserTypeAgent {
shopID := middleware.GetShopIDFromContext(ctx)
if shopID == 0 {
return nil, gorm.ErrRecordNotFound
}
baseSQL += " AND a.enterprise_id IN (SELECT id FROM tb_enterprise WHERE owner_shop_id = ? AND deleted_at IS NULL)"
args = append(args, shopID)
} else if userType == constants.UserTypeEnterprise {
enterpriseID := middleware.GetEnterpriseIDFromContext(ctx)
if enterpriseID == 0 {
return nil, gorm.ErrRecordNotFound
}
baseSQL += " AND a.enterprise_id = ?"
args = append(args, enterpriseID)
} else {
userType := middleware.GetUserTypeFromContext(ctx)
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
if userType == constants.UserTypeAgent {
// 代理用户:只能看到自己及下级店铺所拥有企业的授权记录
shopIDs := middleware.GetSubordinateShopIDs(ctx)
if len(shopIDs) == 0 {
return nil, gorm.ErrRecordNotFound
}
baseSQL += " AND a.enterprise_id IN (SELECT id FROM tb_enterprise WHERE owner_shop_id IN (?) AND deleted_at IS NULL)"
args = append(args, shopIDs)
} else if userType == constants.UserTypeEnterprise {
enterpriseID := middleware.GetEnterpriseIDFromContext(ctx)
if enterpriseID == 0 {
return nil, gorm.ErrRecordNotFound
}
baseSQL += " AND a.enterprise_id = ?"
args = append(args, enterpriseID)
} else {
return nil, gorm.ErrRecordNotFound
}
}
@@ -401,7 +412,10 @@ func (s *EnterpriseCardAuthorizationStore) UpdateRemarkWithConstraint(ctx contex
func (s *EnterpriseCardAuthorizationStore) GetByID(ctx context.Context, id uint) (*model.EnterpriseCardAuthorization, error) {
var auth model.EnterpriseCardAuthorization
err := s.db.WithContext(ctx).Where("id = ?", id).First(&auth).Error
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤
query = s.applyEnterpriseAuthFilter(ctx, query)
err := query.First(&auth).Error
if err != nil {
return nil, err
}
@@ -417,3 +431,23 @@ func (s *EnterpriseCardAuthorizationStore) RevokeByDeviceAuthID(ctx context.Cont
"revoked_at": now,
}).Error
}
// applyEnterpriseAuthFilter 应用企业卡授权表的数据权限过滤
// 企业用户:只能看到自己企业的授权记录
// 代理用户:只能看到自己及下级店铺所拥有企业的授权记录
// 平台/超管:不过滤
func (s *EnterpriseCardAuthorizationStore) applyEnterpriseAuthFilter(ctx context.Context, query *gorm.DB) *gorm.DB {
// 企业用户过滤
query = middleware.ApplyEnterpriseFilter(ctx, query)
// 代理用户:通过企业的 owner_shop_id 过滤
userType := middleware.GetUserTypeFromContext(ctx)
if userType == constants.UserTypeAgent {
shopIDs := middleware.GetSubordinateShopIDs(ctx)
if shopIDs != nil {
query = query.Where("enterprise_id IN (SELECT id FROM tb_enterprise WHERE owner_shop_id IN ? AND deleted_at IS NULL)", shopIDs)
}
}
return query
}

View File

@@ -5,6 +5,7 @@ import (
"time"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -45,7 +46,10 @@ func (s *EnterpriseDeviceAuthorizationStore) BatchCreate(ctx context.Context, au
func (s *EnterpriseDeviceAuthorizationStore) GetByID(ctx context.Context, id uint) (*model.EnterpriseDeviceAuthorization, error) {
var auth model.EnterpriseDeviceAuthorization
err := s.db.WithContext(ctx).Where("id = ?", id).First(&auth).Error
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用企业数据权限过滤
query = middleware.ApplyEnterpriseFilter(ctx, query)
err := query.First(&auth).Error
if err != nil {
return nil, err
}
@@ -54,9 +58,11 @@ func (s *EnterpriseDeviceAuthorizationStore) GetByID(ctx context.Context, id uin
func (s *EnterpriseDeviceAuthorizationStore) GetByDeviceID(ctx context.Context, deviceID uint) (*model.EnterpriseDeviceAuthorization, error) {
var auth model.EnterpriseDeviceAuthorization
err := s.db.WithContext(ctx).
Where("device_id = ? AND revoked_at IS NULL", deviceID).
First(&auth).Error
query := s.db.WithContext(ctx).
Where("device_id = ? AND revoked_at IS NULL", deviceID)
// 应用企业数据权限过滤
query = middleware.ApplyEnterpriseFilter(ctx, query)
err := query.First(&auth).Error
if err != nil {
return nil, err
}
@@ -66,6 +72,8 @@ func (s *EnterpriseDeviceAuthorizationStore) GetByDeviceID(ctx context.Context,
func (s *EnterpriseDeviceAuthorizationStore) GetByEnterpriseID(ctx context.Context, enterpriseID uint, includeRevoked bool) ([]*model.EnterpriseDeviceAuthorization, error) {
var auths []*model.EnterpriseDeviceAuthorization
query := s.db.WithContext(ctx).Where("enterprise_id = ?", enterpriseID)
// 应用企业数据权限过滤
query = middleware.ApplyEnterpriseFilter(ctx, query)
if !includeRevoked {
query = query.Where("revoked_at IS NULL")
}
@@ -87,6 +95,8 @@ func (s *EnterpriseDeviceAuthorizationStore) ListByEnterprise(ctx context.Contex
var total int64
query := s.db.WithContext(ctx).Model(&model.EnterpriseDeviceAuthorization{})
// 应用企业数据权限过滤
query = middleware.ApplyEnterpriseFilter(ctx, query)
if opts.EnterpriseID != nil {
query = query.Where("enterprise_id = ?", *opts.EnterpriseID)
@@ -134,10 +144,12 @@ func (s *EnterpriseDeviceAuthorizationStore) GetActiveAuthsByDeviceIDs(ctx conte
}
var auths []model.EnterpriseDeviceAuthorization
err := s.db.WithContext(ctx).
query := s.db.WithContext(ctx).
Select("device_id").
Where("enterprise_id = ? AND device_id IN ? AND revoked_at IS NULL", enterpriseID, deviceIDs).
Find(&auths).Error
Where("enterprise_id = ? AND device_id IN ? AND revoked_at IS NULL", enterpriseID, deviceIDs)
// 应用企业数据权限过滤
query = middleware.ApplyEnterpriseFilter(ctx, query)
err := query.Find(&auths).Error
if err != nil {
return nil, err
@@ -152,9 +164,11 @@ func (s *EnterpriseDeviceAuthorizationStore) GetActiveAuthsByDeviceIDs(ctx conte
func (s *EnterpriseDeviceAuthorizationStore) ListDeviceIDsByEnterprise(ctx context.Context, enterpriseID uint) ([]uint, error) {
var deviceIDs []uint
err := s.db.WithContext(ctx).
query := s.db.WithContext(ctx).
Model(&model.EnterpriseDeviceAuthorization{}).
Where("enterprise_id = ? AND revoked_at IS NULL", enterpriseID).
Pluck("device_id", &deviceIDs).Error
Where("enterprise_id = ? AND revoked_at IS NULL", enterpriseID)
// 应用企业数据权限过滤
query = middleware.ApplyEnterpriseFilter(ctx, query)
err := query.Pluck("device_id", &deviceIDs).Error
return deviceIDs, err
}

View File

@@ -6,6 +6,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -32,7 +33,10 @@ func (s *EnterpriseStore) Create(ctx context.Context, enterprise *model.Enterpri
// GetByID 根据 ID 获取企业
func (s *EnterpriseStore) GetByID(ctx context.Context, id uint) (*model.Enterprise, error) {
var enterprise model.Enterprise
if err := s.db.WithContext(ctx).First(&enterprise, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用归属店铺数据权限过滤
query = middleware.ApplyOwnerShopFilter(ctx, query)
if err := query.First(&enterprise).Error; err != nil {
return nil, err
}
return &enterprise, nil
@@ -41,7 +45,10 @@ func (s *EnterpriseStore) GetByID(ctx context.Context, id uint) (*model.Enterpri
// GetByCode 根据企业编号获取企业
func (s *EnterpriseStore) GetByCode(ctx context.Context, code string) (*model.Enterprise, error) {
var enterprise model.Enterprise
if err := s.db.WithContext(ctx).Where("enterprise_code = ?", code).First(&enterprise).Error; err != nil {
query := s.db.WithContext(ctx).Where("enterprise_code = ?", code)
// 应用归属店铺数据权限过滤
query = middleware.ApplyOwnerShopFilter(ctx, query)
if err := query.First(&enterprise).Error; err != nil {
return nil, err
}
return &enterprise, nil
@@ -63,6 +70,8 @@ func (s *EnterpriseStore) List(ctx context.Context, opts *store.QueryOptions, fi
var total int64
query := s.db.WithContext(ctx).Model(&model.Enterprise{})
// 应用归属店铺数据权限过滤
query = middleware.ApplyOwnerShopFilter(ctx, query)
// 应用过滤条件
if enterpriseName, ok := filters["enterprise_name"].(string); ok && enterpriseName != "" {
@@ -111,7 +120,10 @@ func (s *EnterpriseStore) List(ctx context.Context, opts *store.QueryOptions, fi
// GetByOwnerShopID 根据归属店铺 ID 查询企业列表
func (s *EnterpriseStore) GetByOwnerShopID(ctx context.Context, ownerShopID uint) ([]*model.Enterprise, error) {
var enterprises []*model.Enterprise
if err := s.db.WithContext(ctx).Where("owner_shop_id = ?", ownerShopID).Find(&enterprises).Error; err != nil {
query := s.db.WithContext(ctx).Where("owner_shop_id = ?", ownerShopID)
// 应用归属店铺数据权限过滤
query = middleware.ApplyOwnerShopFilter(ctx, query)
if err := query.Find(&enterprises).Error; err != nil {
return nil, err
}
return enterprises, nil
@@ -120,7 +132,10 @@ func (s *EnterpriseStore) GetByOwnerShopID(ctx context.Context, ownerShopID uint
// GetPlatformEnterprises 获取平台直属企业列表owner_shop_id 为 NULL
func (s *EnterpriseStore) GetPlatformEnterprises(ctx context.Context) ([]*model.Enterprise, error) {
var enterprises []*model.Enterprise
if err := s.db.WithContext(ctx).Where("owner_shop_id IS NULL").Find(&enterprises).Error; err != nil {
query := s.db.WithContext(ctx).Where("owner_shop_id IS NULL")
// 应用归属店铺数据权限过滤(代理用户无法看到平台直属企业)
query = middleware.ApplyOwnerShopFilter(ctx, query)
if err := query.Find(&enterprises).Error; err != nil {
return nil, err
}
return enterprises, nil
@@ -132,7 +147,10 @@ func (s *EnterpriseStore) GetByIDs(ctx context.Context, ids []uint) ([]*model.En
return []*model.Enterprise{}, nil
}
var enterprises []*model.Enterprise
if err := s.db.WithContext(ctx).Where("id IN ?", ids).Find(&enterprises).Error; err != nil {
query := s.db.WithContext(ctx).Where("id IN ?", ids)
// 应用归属店铺数据权限过滤
query = middleware.ApplyOwnerShopFilter(ctx, query)
if err := query.Find(&enterprises).Error; err != nil {
return nil, err
}
return enterprises, nil

View File

@@ -8,6 +8,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -30,7 +31,10 @@ func (s *IotCardImportTaskStore) Create(ctx context.Context, task *model.IotCard
func (s *IotCardImportTaskStore) GetByID(ctx context.Context, id uint) (*model.IotCardImportTask, error) {
var task model.IotCardImportTask
if err := s.db.WithContext(ctx).First(&task, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&task).Error; err != nil {
return nil, err
}
return &task, nil
@@ -38,7 +42,10 @@ func (s *IotCardImportTaskStore) GetByID(ctx context.Context, id uint) (*model.I
func (s *IotCardImportTaskStore) GetByTaskNo(ctx context.Context, taskNo string) (*model.IotCardImportTask, error) {
var task model.IotCardImportTask
if err := s.db.WithContext(ctx).Where("task_no = ?", taskNo).First(&task).Error; err != nil {
query := s.db.WithContext(ctx).Where("task_no = ?", taskNo)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&task).Error; err != nil {
return nil, err
}
return &task, nil
@@ -82,6 +89,8 @@ func (s *IotCardImportTaskStore) List(ctx context.Context, opts *store.QueryOpti
var total int64
query := s.db.WithContext(ctx).Model(&model.IotCardImportTask{})
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if status, ok := filters["status"].(int); ok && status > 0 {
query = query.Where("status = ?", status)

View File

@@ -11,7 +11,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/constants"
pkggorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
"github.com/break/junhong_cmp_fiber/pkg/logger"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
@@ -46,7 +45,10 @@ func (s *IotCardStore) CreateBatch(ctx context.Context, cards []*model.IotCard)
func (s *IotCardStore) GetByID(ctx context.Context, id uint) (*model.IotCard, error) {
var card model.IotCard
if err := s.db.WithContext(ctx).First(&card, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤NULL shop_id 对代理用户不可见)
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&card).Error; err != nil {
return nil, err
}
return &card, nil
@@ -54,7 +56,10 @@ func (s *IotCardStore) GetByID(ctx context.Context, id uint) (*model.IotCard, er
func (s *IotCardStore) GetByICCID(ctx context.Context, iccid string) (*model.IotCard, error) {
var card model.IotCard
if err := s.db.WithContext(ctx).Where("iccid = ?", iccid).First(&card).Error; err != nil {
query := s.db.WithContext(ctx).Where("iccid = ?", iccid)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&card).Error; err != nil {
return nil, err
}
return &card, nil
@@ -65,7 +70,10 @@ func (s *IotCardStore) GetByIDs(ctx context.Context, ids []uint) ([]*model.IotCa
return []*model.IotCard{}, nil
}
var cards []*model.IotCard
if err := s.db.WithContext(ctx).Where("id IN ?", ids).Find(&cards).Error; err != nil {
query := s.db.WithContext(ctx).Where("id IN ?", ids)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&cards).Error; err != nil {
return nil, err
}
return cards, nil
@@ -111,13 +119,15 @@ func (s *IotCardStore) List(ctx context.Context, opts *store.QueryOptions, filte
var total int64
query := s.db.WithContext(ctx).Model(&model.IotCard{})
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
// 企业用户特殊处理:只能看到授权给自己的卡
// 子查询跳过数据权限过滤,权限已由外层查询的 GORM callback 保证
skipCtx := pkggorm.SkipDataPermission(ctx)
// 子查询无需数据权限过滤(在不同表上执行)
if enterpriseID, ok := filters["authorized_enterprise_id"].(uint); ok && enterpriseID > 0 {
query = query.Where("id IN (?)",
s.db.WithContext(skipCtx).Table("tb_enterprise_card_authorization").
s.db.WithContext(ctx).Table("tb_enterprise_card_authorization").
Select("card_id").
Where("enterprise_id = ? AND revoked_at IS NULL AND deleted_at IS NULL", enterpriseID))
}
@@ -143,7 +153,7 @@ func (s *IotCardStore) List(ctx context.Context, opts *store.QueryOptions, filte
}
if packageID, ok := filters["package_id"].(uint); ok && packageID > 0 {
query = query.Where("id IN (?)",
s.db.WithContext(skipCtx).Table("tb_package_usage").
s.db.WithContext(ctx).Table("tb_package_usage").
Select("iot_card_id").
Where("package_id = ? AND deleted_at IS NULL", packageID))
}
@@ -249,6 +259,8 @@ func (s *IotCardStore) listStandaloneTwoPhase(ctx context.Context, opts *store.Q
query := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true")
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
query = s.applyStandaloneFilters(ctx, query, filters)
if cachedTotal, ok := s.getCachedCount(ctx, "standalone", filters); ok {
@@ -309,6 +321,8 @@ func (s *IotCardStore) listStandaloneDefault(ctx context.Context, opts *store.Qu
query := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true")
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
query = s.applyStandaloneFilters(ctx, query, filters)
if cachedTotal, ok := s.getCachedCount(ctx, "standalone", filters); ok {
@@ -339,7 +353,7 @@ func (s *IotCardStore) listStandaloneDefault(ctx context.Context, opts *store.Qu
// 将 shop_id IN (...) 拆分为 per-shop 独立查询,每个查询走 Index Scan
// 然后在应用层归并排序,避免 PG 对多值 IN + ORDER BY 选择全表扫描
func (s *IotCardStore) listStandaloneParallel(ctx context.Context, opts *store.QueryOptions, filters map[string]any, shopIDs []uint) ([]*model.IotCard, int64, error) {
skipCtx := pkggorm.SkipDataPermission(ctx)
// 子查询无需数据权限过滤(在不同表上执行)
fetchLimit := (opts.Page-1)*opts.PageSize + opts.PageSize
@@ -366,9 +380,9 @@ func (s *IotCardStore) listStandaloneParallel(ctx context.Context, opts *store.Q
go func(idx int, sid uint) {
defer wg.Done()
q := s.db.WithContext(skipCtx).Model(&model.IotCard{}).
q := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true AND deleted_at IS NULL AND shop_id = ?", sid)
q = s.applyStandaloneFilters(skipCtx, q, filters)
q = s.applyStandaloneFilters(ctx, q, filters)
var cards []*model.IotCard
if err := q.Select(standaloneListColumns).
@@ -381,9 +395,9 @@ func (s *IotCardStore) listStandaloneParallel(ctx context.Context, opts *store.Q
var count int64
if !hasCachedTotal {
countQ := s.db.WithContext(skipCtx).Model(&model.IotCard{}).
countQ := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true AND deleted_at IS NULL AND shop_id = ?", sid)
countQ = s.applyStandaloneFilters(skipCtx, countQ, filters)
countQ = s.applyStandaloneFilters(ctx, countQ, filters)
if err := countQ.Count(&count).Error; err != nil {
results[idx] = shopResult{err: err}
return
@@ -455,7 +469,7 @@ type cardIDWithTime struct {
// 归并排序后取目标页的 20 个 ID
// Phase 2: SELECT 完整列 WHERE id IN (20 IDs)PK 精确回表)
func (s *IotCardStore) listStandaloneParallelTwoPhase(ctx context.Context, opts *store.QueryOptions, filters map[string]any, shopIDs []uint) ([]*model.IotCard, int64, error) {
skipCtx := pkggorm.SkipDataPermission(ctx)
// 子查询无需数据权限过滤(在不同表上执行)
fetchLimit := (opts.Page-1)*opts.PageSize + opts.PageSize
@@ -476,9 +490,9 @@ func (s *IotCardStore) listStandaloneParallelTwoPhase(ctx context.Context, opts
go func(idx int, sid uint) {
defer wg.Done()
q := s.db.WithContext(skipCtx).Model(&model.IotCard{}).
q := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true AND deleted_at IS NULL AND shop_id = ?", sid)
q = s.applyStandaloneFilters(skipCtx, q, filters)
q = s.applyStandaloneFilters(ctx, q, filters)
var ids []cardIDWithTime
if err := q.Select("id, created_at").
@@ -491,9 +505,9 @@ func (s *IotCardStore) listStandaloneParallelTwoPhase(ctx context.Context, opts
var count int64
if !hasCachedTotal {
countQ := s.db.WithContext(skipCtx).Model(&model.IotCard{}).
countQ := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true AND deleted_at IS NULL AND shop_id = ?", sid)
countQ = s.applyStandaloneFilters(skipCtx, countQ, filters)
countQ = s.applyStandaloneFilters(ctx, countQ, filters)
if err := countQ.Count(&count).Error; err != nil {
results[idx] = shopResult{err: err}
return
@@ -553,7 +567,7 @@ func (s *IotCardStore) listStandaloneParallelTwoPhase(ctx context.Context, opts
// Phase 2: 用 ID 精确回表获取完整数据PK Index Scan仅 20 行)
var cards []*model.IotCard
if err := s.db.WithContext(skipCtx).Model(&model.IotCard{}).
if err := s.db.WithContext(ctx).Model(&model.IotCard{}).
Select(standaloneListColumns).
Where("id IN ?", pageIDs).
Find(&cards).Error; err != nil {
@@ -584,7 +598,7 @@ func (s *IotCardStore) listStandaloneParallelTwoPhase(ctx context.Context, opts
// 注意:不包含 is_standalone、shop_id、deleted_at 条件(由调用方控制)
// 也不包含 subordinate_shop_ids仅用于路由选择不作为查询条件
func (s *IotCardStore) applyStandaloneFilters(ctx context.Context, query *gorm.DB, filters map[string]any) *gorm.DB {
skipCtx := pkggorm.SkipDataPermission(ctx)
// 子查询无需数据权限过滤(在不同表上执行)
if status, ok := filters["status"].(int); ok && status > 0 {
query = query.Where("status = ?", status)
@@ -607,7 +621,7 @@ func (s *IotCardStore) applyStandaloneFilters(ctx context.Context, query *gorm.D
}
if packageID, ok := filters["package_id"].(uint); ok && packageID > 0 {
query = query.Where("id IN (?)",
s.db.WithContext(skipCtx).Table("tb_package_usage").
s.db.WithContext(ctx).Table("tb_package_usage").
Select("iot_card_id").
Where("package_id = ? AND deleted_at IS NULL", packageID))
}
@@ -627,12 +641,12 @@ func (s *IotCardStore) applyStandaloneFilters(ctx context.Context, query *gorm.D
if isReplaced, ok := filters["is_replaced"].(bool); ok {
if isReplaced {
query = query.Where("id IN (?)",
s.db.WithContext(skipCtx).Table("tb_card_replacement_record").
s.db.WithContext(ctx).Table("tb_card_replacement_record").
Select("old_iot_card_id").
Where("deleted_at IS NULL"))
} else {
query = query.Where("id NOT IN (?)",
s.db.WithContext(skipCtx).Table("tb_card_replacement_record").
s.db.WithContext(ctx).Table("tb_card_replacement_record").
Select("old_iot_card_id").
Where("deleted_at IS NULL"))
}
@@ -649,7 +663,10 @@ func (s *IotCardStore) GetByICCIDs(ctx context.Context, iccids []string) ([]*mod
return nil, nil
}
var cards []*model.IotCard
if err := s.db.WithContext(ctx).Where("iccid IN ?", iccids).Find(&cards).Error; err != nil {
query := s.db.WithContext(ctx).Where("iccid IN ?", iccids)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&cards).Error; err != nil {
return nil, err
}
return cards, nil
@@ -659,6 +676,8 @@ func (s *IotCardStore) GetStandaloneByICCIDRange(ctx context.Context, iccidStart
query := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true").
Where("iccid >= ? AND iccid <= ?", iccidStart, iccidEnd)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if shopID == nil {
query = query.Where("shop_id IS NULL")
@@ -676,11 +695,13 @@ func (s *IotCardStore) GetStandaloneByICCIDRange(ctx context.Context, iccidStart
// GetDistributedStandaloneByICCIDRange 根据号段范围查询已分配给店铺的单卡(用于回收)
func (s *IotCardStore) GetDistributedStandaloneByICCIDRange(ctx context.Context, iccidStart, iccidEnd string) ([]*model.IotCard, error) {
var cards []*model.IotCard
if err := s.db.WithContext(ctx).Model(&model.IotCard{}).
query := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true").
Where("shop_id IS NOT NULL").
Where("iccid >= ? AND iccid <= ?", iccidStart, iccidEnd).
Find(&cards).Error; err != nil {
Where("iccid >= ? AND iccid <= ?", iccidStart, iccidEnd)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&cards).Error; err != nil {
return nil, err
}
return cards, nil
@@ -689,6 +710,8 @@ func (s *IotCardStore) GetDistributedStandaloneByICCIDRange(ctx context.Context,
func (s *IotCardStore) GetStandaloneByFilters(ctx context.Context, filters map[string]any, shopID *uint) ([]*model.IotCard, error) {
query := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true")
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if shopID == nil {
query = query.Where("shop_id IS NULL")
@@ -718,6 +741,8 @@ func (s *IotCardStore) GetDistributedStandaloneByFilters(ctx context.Context, fi
query := s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("is_standalone = true").
Where("shop_id IS NOT NULL")
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if carrierID, ok := filters["carrier_id"].(uint); ok && carrierID > 0 {
query = query.Where("carrier_id = ?", carrierID)
@@ -764,10 +789,10 @@ func (s *IotCardStore) GetByIDsWithEnterpriseFilter(ctx context.Context, cardIDs
query := s.db.WithContext(ctx).Model(&model.IotCard{})
if enterpriseID != nil && *enterpriseID > 0 {
skipCtx := pkggorm.SkipDataPermission(ctx)
// 子查询无需数据权限过滤(在不同表上执行)
query = query.Where("id IN (?) AND id IN (?)",
cardIDs,
s.db.WithContext(skipCtx).Table("tb_enterprise_card_authorization").
s.db.WithContext(ctx).Table("tb_enterprise_card_authorization").
Select("card_id").
Where("enterprise_id = ? AND revoked_at IS NULL AND deleted_at IS NULL", *enterpriseID))
} else {
@@ -796,7 +821,10 @@ func (s *IotCardStore) BatchUpdateSeriesID(ctx context.Context, cardIDs []uint,
// 用于查询某个套餐系列下的所有卡
func (s *IotCardStore) ListBySeriesID(ctx context.Context, seriesID uint) ([]*model.IotCard, error) {
var cards []*model.IotCard
if err := s.db.WithContext(ctx).Where("series_id = ?", seriesID).Find(&cards).Error; err != nil {
query := s.db.WithContext(ctx).Where("series_id = ?", seriesID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&cards).Error; err != nil {
return nil, err
}
return cards, nil

View File

@@ -8,6 +8,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -43,7 +44,10 @@ func (s *OrderStore) Create(ctx context.Context, order *model.Order, items []*mo
func (s *OrderStore) GetByID(ctx context.Context, id uint) (*model.Order, error) {
var order model.Order
if err := s.db.WithContext(ctx).First(&order, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤(使用 seller_shop_id 字段)
query = middleware.ApplySellerShopFilter(ctx, query)
if err := query.First(&order).Error; err != nil {
return nil, err
}
return &order, nil
@@ -51,7 +55,10 @@ func (s *OrderStore) GetByID(ctx context.Context, id uint) (*model.Order, error)
func (s *OrderStore) GetByIDWithItems(ctx context.Context, id uint) (*model.Order, []*model.OrderItem, error) {
var order model.Order
if err := s.db.WithContext(ctx).First(&order, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤(使用 seller_shop_id 字段)
query = middleware.ApplySellerShopFilter(ctx, query)
if err := query.First(&order).Error; err != nil {
return nil, nil, err
}
@@ -65,7 +72,10 @@ func (s *OrderStore) GetByIDWithItems(ctx context.Context, id uint) (*model.Orde
func (s *OrderStore) GetByOrderNo(ctx context.Context, orderNo string) (*model.Order, error) {
var order model.Order
if err := s.db.WithContext(ctx).Where("order_no = ?", orderNo).First(&order).Error; err != nil {
query := s.db.WithContext(ctx).Where("order_no = ?", orderNo)
// 应用数据权限过滤(使用 seller_shop_id 字段)
query = middleware.ApplySellerShopFilter(ctx, query)
if err := query.First(&order).Error; err != nil {
return nil, err
}
return &order, nil
@@ -80,6 +90,8 @@ func (s *OrderStore) List(ctx context.Context, opts *store.QueryOptions, filters
var total int64
query := s.db.WithContext(ctx).Model(&model.Order{})
// 应用数据权限过滤(使用 seller_shop_id 字段)
query = middleware.ApplySellerShopFilter(ctx, query)
if v, ok := filters["payment_status"]; ok {
query = query.Where("payment_status = ?", v)

View File

@@ -5,6 +5,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"gorm.io/gorm"
)
@@ -22,7 +23,10 @@ func (s *ShopPackageAllocationStore) Create(ctx context.Context, allocation *mod
func (s *ShopPackageAllocationStore) GetByID(ctx context.Context, id uint) (*model.ShopPackageAllocation, error) {
var allocation model.ShopPackageAllocation
if err := s.db.WithContext(ctx).First(&allocation, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&allocation).Error; err != nil {
return nil, err
}
return &allocation, nil
@@ -30,7 +34,10 @@ func (s *ShopPackageAllocationStore) GetByID(ctx context.Context, id uint) (*mod
func (s *ShopPackageAllocationStore) GetByShopAndPackage(ctx context.Context, shopID, packageID uint) (*model.ShopPackageAllocation, error) {
var allocation model.ShopPackageAllocation
if err := s.db.WithContext(ctx).Where("shop_id = ? AND package_id = ?", shopID, packageID).First(&allocation).Error; err != nil {
query := s.db.WithContext(ctx).Where("shop_id = ? AND package_id = ?", shopID, packageID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&allocation).Error; err != nil {
return nil, err
}
return &allocation, nil
@@ -49,6 +56,8 @@ func (s *ShopPackageAllocationStore) List(ctx context.Context, opts *store.Query
var total int64
query := s.db.WithContext(ctx).Model(&model.ShopPackageAllocation{})
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if shopID, ok := filters["shop_id"].(uint); ok && shopID > 0 {
query = query.Where("shop_id = ?", shopID)
@@ -99,7 +108,10 @@ func (s *ShopPackageAllocationStore) UpdateStatus(ctx context.Context, id uint,
func (s *ShopPackageAllocationStore) GetByShopID(ctx context.Context, shopID uint) ([]*model.ShopPackageAllocation, error) {
var allocations []*model.ShopPackageAllocation
if err := s.db.WithContext(ctx).Where("shop_id = ? AND status = 1", shopID).Find(&allocations).Error; err != nil {
query := s.db.WithContext(ctx).Where("shop_id = ? AND status = 1", shopID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&allocations).Error; err != nil {
return nil, err
}
return allocations, nil
@@ -107,9 +119,11 @@ func (s *ShopPackageAllocationStore) GetByShopID(ctx context.Context, shopID uin
func (s *ShopPackageAllocationStore) GetByShopAndPackages(ctx context.Context, shopID uint, packageIDs []uint) ([]*model.ShopPackageAllocation, error) {
var allocations []*model.ShopPackageAllocation
if err := s.db.WithContext(ctx).
Where("shop_id = ? AND package_id IN ? AND status = 1", shopID, packageIDs).
Find(&allocations).Error; err != nil {
query := s.db.WithContext(ctx).
Where("shop_id = ? AND package_id IN ? AND status = 1", shopID, packageIDs)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&allocations).Error; err != nil {
return nil, err
}
return allocations, nil
@@ -117,9 +131,11 @@ func (s *ShopPackageAllocationStore) GetByShopAndPackages(ctx context.Context, s
func (s *ShopPackageAllocationStore) GetBySeriesAllocationID(ctx context.Context, seriesAllocationID uint) ([]*model.ShopPackageAllocation, error) {
var allocations []*model.ShopPackageAllocation
if err := s.db.WithContext(ctx).
Where("series_allocation_id = ? AND status = 1", seriesAllocationID).
Find(&allocations).Error; err != nil {
query := s.db.WithContext(ctx).
Where("series_allocation_id = ? AND status = 1", seriesAllocationID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&allocations).Error; err != nil {
return nil, err
}
return allocations, nil

View File

@@ -5,6 +5,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -62,9 +63,10 @@ func (s *ShopRoleStore) DeleteByShopID(ctx context.Context, shopID uint) error {
func (s *ShopRoleStore) GetByShopID(ctx context.Context, shopID uint) ([]*model.ShopRole, error) {
var srs []*model.ShopRole
if err := s.db.WithContext(ctx).
Where("shop_id = ?", shopID).
Find(&srs).Error; err != nil {
query := s.db.WithContext(ctx).Where("shop_id = ?", shopID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&srs).Error; err != nil {
return nil, err
}
return srs, nil
@@ -72,10 +74,12 @@ func (s *ShopRoleStore) GetByShopID(ctx context.Context, shopID uint) ([]*model.
func (s *ShopRoleStore) GetRoleIDsByShopID(ctx context.Context, shopID uint) ([]uint, error) {
var roleIDs []uint
if err := s.db.WithContext(ctx).
query := s.db.WithContext(ctx).
Model(&model.ShopRole{}).
Where("shop_id = ?", shopID).
Pluck("role_id", &roleIDs).Error; err != nil {
Where("shop_id = ?", shopID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Pluck("role_id", &roleIDs).Error; err != nil {
return nil, err
}
return roleIDs, nil

View File

@@ -5,6 +5,7 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"gorm.io/gorm"
)
@@ -22,7 +23,10 @@ func (s *ShopSeriesAllocationStore) Create(ctx context.Context, allocation *mode
func (s *ShopSeriesAllocationStore) GetByID(ctx context.Context, id uint) (*model.ShopSeriesAllocation, error) {
var allocation model.ShopSeriesAllocation
if err := s.db.WithContext(ctx).First(&allocation, id).Error; err != nil {
query := s.db.WithContext(ctx).Where("id = ?", id)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&allocation).Error; err != nil {
return nil, err
}
return &allocation, nil
@@ -30,9 +34,11 @@ func (s *ShopSeriesAllocationStore) GetByID(ctx context.Context, id uint) (*mode
func (s *ShopSeriesAllocationStore) GetByShopAndSeries(ctx context.Context, shopID, seriesID uint) (*model.ShopSeriesAllocation, error) {
var allocation model.ShopSeriesAllocation
if err := s.db.WithContext(ctx).
Where("shop_id = ? AND series_id = ?", shopID, seriesID).
First(&allocation).Error; err != nil {
query := s.db.WithContext(ctx).
Where("shop_id = ? AND series_id = ?", shopID, seriesID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.First(&allocation).Error; err != nil {
return nil, err
}
return &allocation, nil
@@ -51,6 +57,8 @@ func (s *ShopSeriesAllocationStore) List(ctx context.Context, opts *store.QueryO
var total int64
query := s.db.WithContext(ctx).Model(&model.ShopSeriesAllocation{})
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if shopID, ok := filters["shop_id"].(uint); ok && shopID > 0 {
query = query.Where("shop_id = ?", shopID)
@@ -100,9 +108,11 @@ func (s *ShopSeriesAllocationStore) UpdateStatus(ctx context.Context, id uint, s
func (s *ShopSeriesAllocationStore) GetByShopID(ctx context.Context, shopID uint) ([]*model.ShopSeriesAllocation, error) {
var allocations []*model.ShopSeriesAllocation
if err := s.db.WithContext(ctx).
Where("shop_id = ? AND status = 1", shopID).
Find(&allocations).Error; err != nil {
query := s.db.WithContext(ctx).
Where("shop_id = ? AND status = 1", shopID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&allocations).Error; err != nil {
return nil, err
}
return allocations, nil
@@ -132,9 +142,11 @@ func (s *ShopSeriesAllocationStore) ExistsByShopAndSeries(ctx context.Context, s
func (s *ShopSeriesAllocationStore) GetByAllocatorShopID(ctx context.Context, allocatorShopID uint) ([]*model.ShopSeriesAllocation, error) {
var allocations []*model.ShopSeriesAllocation
if err := s.db.WithContext(ctx).
Where("allocator_shop_id = ? AND status = 1", allocatorShopID).
Find(&allocations).Error; err != nil {
query := s.db.WithContext(ctx).
Where("allocator_shop_id = ? AND status = 1", allocatorShopID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Find(&allocations).Error; err != nil {
return nil, err
}
return allocations, nil
@@ -145,10 +157,12 @@ func (s *ShopSeriesAllocationStore) GetIDsByShopIDsAndSeries(ctx context.Context
return nil, nil
}
var ids []uint
if err := s.db.WithContext(ctx).
query := s.db.WithContext(ctx).
Model(&model.ShopSeriesAllocation{}).
Where("shop_id IN ? AND series_id = ? AND status = 1", shopIDs, seriesID).
Pluck("id", &ids).Error; err != nil {
Where("shop_id IN ? AND series_id = ? AND status = 1", shopIDs, seriesID)
// 应用数据权限过滤
query = middleware.ApplyShopFilter(ctx, query)
if err := query.Pluck("id", &ids).Error; err != nil {
return nil, err
}
return ids, nil

View File

@@ -9,7 +9,6 @@ import (
"gorm.io/gorm"
"github.com/break/junhong_cmp_fiber/internal/service/commission_calculation"
pkggorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
)
const (
@@ -39,8 +38,6 @@ func NewCommissionCalculationHandler(
}
func (h *CommissionCalculationHandler) HandleCommissionCalculation(ctx context.Context, task *asynq.Task) error {
ctx = pkggorm.SkipDataPermission(ctx)
var payload CommissionCalculationPayload
if err := sonic.Unmarshal(task.Payload(), &payload); err != nil {
h.logger.Error("解析佣金计算任务载荷失败",

View File

@@ -12,7 +12,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
pkggorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
)
type CommissionStatsArchiveHandler struct {
@@ -37,8 +36,6 @@ func NewCommissionStatsArchiveHandler(
}
func (h *CommissionStatsArchiveHandler) HandleCommissionStatsArchive(ctx context.Context, task *asynq.Task) error {
ctx = pkggorm.SkipDataPermission(ctx)
now := time.Now()
lastMonthStart := now.AddDate(0, -1, 0)
lastMonthStart = time.Date(lastMonthStart.Year(), lastMonthStart.Month(), 1, 0, 0, 0, 0, time.UTC)

View File

@@ -14,7 +14,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
pkggorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
)
type CommissionStatsSyncHandler struct {
@@ -39,8 +38,6 @@ func NewCommissionStatsSyncHandler(
}
func (h *CommissionStatsSyncHandler) HandleCommissionStatsSync(ctx context.Context, task *asynq.Task) error {
ctx = pkggorm.SkipDataPermission(ctx)
lockKey := constants.RedisCommissionStatsLockKey()
locked, err := h.redis.SetNX(ctx, lockKey, "1", 5*time.Minute).Result()
if err != nil {

View File

@@ -11,7 +11,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
pkggorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
)
type CommissionStatsUpdatePayload struct {
@@ -42,8 +41,6 @@ func NewCommissionStatsUpdateHandler(
}
func (h *CommissionStatsUpdateHandler) HandleCommissionStatsUpdate(ctx context.Context, task *asynq.Task) error {
ctx = pkggorm.SkipDataPermission(ctx)
var payload CommissionStatsUpdatePayload
if err := sonic.Unmarshal(task.Payload(), &payload); err != nil {
h.logger.Error("解析统计更新任务载荷失败",

View File

@@ -17,7 +17,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
pkggorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
"github.com/break/junhong_cmp_fiber/pkg/storage"
"github.com/break/junhong_cmp_fiber/pkg/utils"
)
@@ -62,8 +61,6 @@ func NewDeviceImportHandler(
}
func (h *DeviceImportHandler) HandleDeviceImport(ctx context.Context, task *asynq.Task) error {
ctx = pkggorm.SkipDataPermission(ctx)
var payload DeviceImportPayload
if err := sonic.Unmarshal(task.Payload(), &payload); err != nil {
h.logger.Error("解析设备导入任务载荷失败",

View File

@@ -17,7 +17,6 @@ import (
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
pkggorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
"github.com/break/junhong_cmp_fiber/pkg/storage"
"github.com/break/junhong_cmp_fiber/pkg/utils"
"github.com/break/junhong_cmp_fiber/pkg/validator"
@@ -72,8 +71,6 @@ func NewIotCardImportHandler(
}
func (h *IotCardImportHandler) HandleIotCardImport(ctx context.Context, task *asynq.Task) error {
ctx = pkggorm.SkipDataPermission(ctx)
var payload IotCardImportPayload
if err := sonic.Unmarshal(task.Payload(), &payload); err != nil {
h.logger.Error("解析 IoT 卡导入任务载荷失败",