deleteDeptLogic.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package dept
  2. import (
  3. "context"
  4. "fmt"
  5. authHelper "perms-system-server/internal/logic/auth"
  6. "perms-system-server/internal/response"
  7. "perms-system-server/internal/svc"
  8. "perms-system-server/internal/types"
  9. "github.com/zeromicro/go-zero/core/logx"
  10. "github.com/zeromicro/go-zero/core/stores/sqlx"
  11. )
  12. type DeleteDeptLogic struct {
  13. logx.Logger
  14. ctx context.Context
  15. svcCtx *svc.ServiceContext
  16. }
  17. func NewDeleteDeptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteDeptLogic {
  18. return &DeleteDeptLogic{
  19. Logger: logx.WithContext(ctx),
  20. ctx: ctx,
  21. svcCtx: svcCtx,
  22. }
  23. }
  24. func (l *DeleteDeptLogic) DeleteDept(req *types.DeleteDeptReq) error {
  25. if err := authHelper.RequireSuperAdmin(l.ctx); err != nil {
  26. return err
  27. }
  28. return l.svcCtx.SysDeptModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  29. // 行锁锁定目标部门,防止并发删除/修改
  30. var deptId int64
  31. lockQuery := fmt.Sprintf("SELECT `id` FROM %s WHERE `id` = ? FOR UPDATE", l.svcCtx.SysDeptModel.TableName())
  32. if err := session.QueryRowCtx(ctx, &deptId, lockQuery, req.Id); err != nil {
  33. return response.ErrNotFound("部门不存在")
  34. }
  35. var childCount int64
  36. countChildQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE `parentId` = ?", l.svcCtx.SysDeptModel.TableName())
  37. if err := session.QueryRowCtx(ctx, &childCount, countChildQuery, req.Id); err != nil {
  38. return err
  39. }
  40. if childCount > 0 {
  41. return response.ErrBadRequest("该部门下存在子部门,无法删除")
  42. }
  43. var userCount int64
  44. countUserQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE `deptId` = ?", l.svcCtx.SysUserModel.TableName())
  45. if err := session.QueryRowCtx(ctx, &userCount, countUserQuery, req.Id); err != nil {
  46. return err
  47. }
  48. if userCount > 0 {
  49. return response.ErrBadRequest("该部门下仍有关联用户,无法删除")
  50. }
  51. return l.svcCtx.SysDeptModel.DeleteWithTx(ctx, session, req.Id)
  52. })
  53. }