deleteDeptLogic.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // DeleteDept 删除部门。在事务内加行锁后检查是否存在子部门或关联用户,均无则删除。仅超管可调用。
  25. func (l *DeleteDeptLogic) DeleteDept(req *types.DeleteDeptReq) error {
  26. if err := authHelper.RequireSuperAdmin(l.ctx); err != nil {
  27. return err
  28. }
  29. return l.svcCtx.SysDeptModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  30. // 行锁锁定目标部门,防止并发删除/修改
  31. var deptId int64
  32. lockQuery := fmt.Sprintf("SELECT `id` FROM %s WHERE `id` = ? FOR UPDATE", l.svcCtx.SysDeptModel.TableName())
  33. if err := session.QueryRowCtx(ctx, &deptId, lockQuery, req.Id); err != nil {
  34. return response.ErrNotFound("部门不存在")
  35. }
  36. var childCount int64
  37. countChildQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE `parentId` = ?", l.svcCtx.SysDeptModel.TableName())
  38. if err := session.QueryRowCtx(ctx, &childCount, countChildQuery, req.Id); err != nil {
  39. return err
  40. }
  41. if childCount > 0 {
  42. return response.ErrBadRequest("该部门下存在子部门,无法删除")
  43. }
  44. var userCount int64
  45. countUserQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE `deptId` = ?", l.svcCtx.SysUserModel.TableName())
  46. if err := session.QueryRowCtx(ctx, &userCount, countUserQuery, req.Id); err != nil {
  47. return err
  48. }
  49. if userCount > 0 {
  50. return response.ErrBadRequest("该部门下仍有关联用户,无法删除")
  51. }
  52. return l.svcCtx.SysDeptModel.DeleteWithTx(ctx, session, req.Id)
  53. })
  54. }