createDeptLogic.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. if len(req.Name) > 64 {
  32. return nil, response.ErrBadRequest("部门名称长度不能超过64个字符")
  33. }
  34. if len(req.Remark) > 255 {
  35. return nil, response.ErrBadRequest("备注长度不能超过255个字符")
  36. }
  37. parentPath := "/"
  38. if req.ParentId > 0 {
  39. parent, err := l.svcCtx.SysDeptModel.FindOne(l.ctx, req.ParentId)
  40. if err != nil {
  41. return nil, response.ErrNotFound("父部门不存在")
  42. }
  43. parentPath = parent.Path
  44. }
  45. now := time.Now().Unix()
  46. var deptId int64
  47. deptType := req.DeptType
  48. if deptType == "" {
  49. deptType = consts.DeptTypeNormal
  50. } else if deptType != consts.DeptTypeNormal && deptType != consts.DeptTypeDev {
  51. return nil, response.ErrBadRequest("无效的部门类型")
  52. }
  53. err = l.svcCtx.SysDeptModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  54. result, err := l.svcCtx.SysDeptModel.InsertWithTx(ctx, session, &deptModel.SysDept{
  55. ParentId: req.ParentId,
  56. Name: req.Name,
  57. Path: parentPath,
  58. Sort: req.Sort,
  59. DeptType: deptType,
  60. Remark: req.Remark,
  61. Status: consts.StatusEnabled,
  62. CreateTime: now,
  63. UpdateTime: now,
  64. })
  65. if err != nil {
  66. return err
  67. }
  68. deptId, _ = result.LastInsertId()
  69. d, err := l.svcCtx.SysDeptModel.FindOneWithTx(ctx, session, deptId)
  70. if err != nil {
  71. return err
  72. }
  73. d.Path = fmt.Sprintf("%s%d/", parentPath, deptId)
  74. return l.svcCtx.SysDeptModel.UpdateWithTx(ctx, session, d)
  75. })
  76. if err != nil {
  77. return nil, err
  78. }
  79. return &types.IdResp{Id: deptId}, nil
  80. }