createDeptLogic.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package dept
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "perms-system-server/internal/consts"
  7. authHelper "perms-system-server/internal/logic/auth"
  8. deptModel "perms-system-server/internal/model/dept"
  9. "perms-system-server/internal/response"
  10. "perms-system-server/internal/svc"
  11. "perms-system-server/internal/types"
  12. "github.com/zeromicro/go-zero/core/logx"
  13. "github.com/zeromicro/go-zero/core/stores/sqlx"
  14. )
  15. type CreateDeptLogic struct {
  16. logx.Logger
  17. ctx context.Context
  18. svcCtx *svc.ServiceContext
  19. }
  20. func NewCreateDeptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateDeptLogic {
  21. return &CreateDeptLogic{
  22. Logger: logx.WithContext(ctx),
  23. ctx: ctx,
  24. svcCtx: svcCtx,
  25. }
  26. }
  27. func (l *CreateDeptLogic) CreateDept(req *types.CreateDeptReq) (resp *types.IdResp, err error) {
  28. if err := authHelper.RequireSuperAdmin(l.ctx); err != nil {
  29. return nil, err
  30. }
  31. parentPath := "/"
  32. if req.ParentId > 0 {
  33. parent, err := l.svcCtx.SysDeptModel.FindOne(l.ctx, req.ParentId)
  34. if err != nil {
  35. return nil, response.ErrNotFound("父部门不存在")
  36. }
  37. parentPath = parent.Path
  38. }
  39. now := time.Now().Unix()
  40. var deptId int64
  41. deptType := req.DeptType
  42. if deptType == "" {
  43. deptType = consts.DeptTypeNormal
  44. } else if deptType != consts.DeptTypeNormal && deptType != consts.DeptTypeDev {
  45. return nil, response.ErrBadRequest("无效的部门类型")
  46. }
  47. err = l.svcCtx.SysDeptModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  48. result, err := l.svcCtx.SysDeptModel.InsertWithTx(ctx, session, &deptModel.SysDept{
  49. ParentId: req.ParentId,
  50. Name: req.Name,
  51. Path: parentPath,
  52. Sort: req.Sort,
  53. DeptType: deptType,
  54. Remark: req.Remark,
  55. Status: consts.StatusEnabled,
  56. CreateTime: now,
  57. UpdateTime: now,
  58. })
  59. if err != nil {
  60. return err
  61. }
  62. deptId, _ = result.LastInsertId()
  63. d, err := l.svcCtx.SysDeptModel.FindOneWithTx(ctx, session, deptId)
  64. if err != nil {
  65. return err
  66. }
  67. d.Path = fmt.Sprintf("%s%d/", parentPath, deptId)
  68. return l.svcCtx.SysDeptModel.UpdateWithTx(ctx, session, d)
  69. })
  70. if err != nil {
  71. return nil, err
  72. }
  73. return &types.IdResp{Id: deptId}, nil
  74. }