| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package dept
- import (
- "context"
- "fmt"
- "time"
- "perms-system-server/internal/consts"
- authHelper "perms-system-server/internal/logic/auth"
- deptModel "perms-system-server/internal/model/dept"
- "perms-system-server/internal/response"
- "perms-system-server/internal/svc"
- "perms-system-server/internal/types"
- "github.com/zeromicro/go-zero/core/logx"
- "github.com/zeromicro/go-zero/core/stores/sqlx"
- )
- type CreateDeptLogic struct {
- logx.Logger
- ctx context.Context
- svcCtx *svc.ServiceContext
- }
- func NewCreateDeptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateDeptLogic {
- return &CreateDeptLogic{
- Logger: logx.WithContext(ctx),
- ctx: ctx,
- svcCtx: svcCtx,
- }
- }
- func (l *CreateDeptLogic) CreateDept(req *types.CreateDeptReq) (resp *types.IdResp, err error) {
- if err := authHelper.RequireSuperAdmin(l.ctx); err != nil {
- return nil, err
- }
- parentPath := "/"
- if req.ParentId > 0 {
- parent, err := l.svcCtx.SysDeptModel.FindOne(l.ctx, req.ParentId)
- if err != nil {
- return nil, response.ErrNotFound("父部门不存在")
- }
- parentPath = parent.Path
- }
- now := time.Now().Unix()
- var deptId int64
- deptType := req.DeptType
- if deptType == "" {
- deptType = consts.DeptTypeNormal
- }
- err = l.svcCtx.SysDeptModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
- result, err := l.svcCtx.SysDeptModel.InsertWithTx(ctx, session, &deptModel.SysDept{
- ParentId: req.ParentId,
- Name: req.Name,
- Path: parentPath,
- Sort: req.Sort,
- DeptType: deptType,
- Remark: req.Remark,
- Status: consts.StatusEnabled,
- CreateTime: now,
- UpdateTime: now,
- })
- if err != nil {
- return err
- }
- deptId, _ = result.LastInsertId()
- d, err := l.svcCtx.SysDeptModel.FindOneWithTx(ctx, session, deptId)
- if err != nil {
- return err
- }
- d.Path = fmt.Sprintf("%s%d/", parentPath, deptId)
- return l.svcCtx.SysDeptModel.UpdateWithTx(ctx, session, d)
- })
- if err != nil {
- return nil, err
- }
- return &types.IdResp{Id: deptId}, nil
- }
|