package dept import ( "context" "fmt" authHelper "perms-system-server/internal/logic/auth" "perms-system-server/internal/response" "perms-system-server/internal/svc" "perms-system-server/internal/types" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/stores/sqlx" ) type DeleteDeptLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewDeleteDeptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteDeptLogic { return &DeleteDeptLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *DeleteDeptLogic) DeleteDept(req *types.DeleteDeptReq) error { if err := authHelper.RequireSuperAdmin(l.ctx); err != nil { return err } return l.svcCtx.SysDeptModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error { // 行锁锁定目标部门,防止并发删除/修改 var deptId int64 lockQuery := fmt.Sprintf("SELECT `id` FROM %s WHERE `id` = ? FOR UPDATE", l.svcCtx.SysDeptModel.TableName()) if err := session.QueryRowCtx(ctx, &deptId, lockQuery, req.Id); err != nil { return response.ErrNotFound("部门不存在") } var childCount int64 countChildQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE `parentId` = ?", l.svcCtx.SysDeptModel.TableName()) if err := session.QueryRowCtx(ctx, &childCount, countChildQuery, req.Id); err != nil { return err } if childCount > 0 { return response.ErrBadRequest("该部门下存在子部门,无法删除") } var userCount int64 countUserQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE `deptId` = ?", l.svcCtx.SysUserModel.TableName()) if err := session.QueryRowCtx(ctx, &userCount, countUserQuery, req.Id); err != nil { return err } if userCount > 0 { return response.ErrBadRequest("该部门下仍有关联用户,无法删除") } return l.svcCtx.SysDeptModel.DeleteWithTx(ctx, session, req.Id) }) }