createDeptLogic.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. }
  45. err = l.svcCtx.SysDeptModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  46. result, err := l.svcCtx.SysDeptModel.InsertWithTx(ctx, session, &deptModel.SysDept{
  47. ParentId: req.ParentId,
  48. Name: req.Name,
  49. Path: parentPath,
  50. Sort: req.Sort,
  51. DeptType: deptType,
  52. Remark: req.Remark,
  53. Status: consts.StatusEnabled,
  54. CreateTime: now,
  55. UpdateTime: now,
  56. })
  57. if err != nil {
  58. return err
  59. }
  60. deptId, _ = result.LastInsertId()
  61. d, err := l.svcCtx.SysDeptModel.FindOneWithTx(ctx, session, deptId)
  62. if err != nil {
  63. return err
  64. }
  65. d.Path = fmt.Sprintf("%s%d/", parentPath, deptId)
  66. return l.svcCtx.SysDeptModel.UpdateWithTx(ctx, session, d)
  67. })
  68. if err != nil {
  69. return nil, err
  70. }
  71. return &types.IdResp{Id: deptId}, nil
  72. }