pg_create_org_service.go 2.3 KB
package domainService

import (
	"fmt"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/repository"
)

// PgCreateOrgService 创建组织服务
type PgCreateOrgService struct {
	transactionContext *pgTransaction.TransactionContext
}

// CreateOrg  创建组织
//
// optUser  操作人
// orgInfo   组织信息
func (ptr *PgCreateOrgService) CreateOrg(optUser *domain.CheckOptions, orgInfo *domain.Org) (*domain.Org, error) {
	var (
		err error
		org *domain.Org
	)
	// 1.检查当前父级部门下,名称不重复 && 部门编码不重复
	orgRepository, _ := repository.NewOrgRepository(ptr.transactionContext)
	if err = CheckCreatedOrgInfo(orgRepository, orgInfo); err != nil {
		return nil, err
	}

	// 2.保存部门
	if org, err = orgRepository.Save(orgInfo); err != nil {
		return nil, err
	}
	return org, nil
}

func CheckCreatedOrgInfo(orgRepository *repository.OrgRepository, orgInfo *domain.Org) error {
	var org *domain.Org
	var err error
	if orgInfo.ParentId != 0 {
		if org, err = orgRepository.FindOne(map[string]interface{}{"companyId": orgInfo.CompanyId, "orgId": orgInfo.ParentId}); err != nil || org == nil {
			return fmt.Errorf("父级部门不存在")
		}
		if org.OrgStatus != domain.OrgStatusEnable {
			return fmt.Errorf("父级部门不可用")
		}
		orgInfo.ParentPath = org.GetFullPath()
		orgInfo.Ext.ParentDepName = org.OrgName
		if org, err = orgRepository.FindOne(map[string]interface{}{"companyId": orgInfo.CompanyId, "parentId": orgInfo.ParentId, "orgCode": orgInfo.OrgCode}); err == nil && org != nil {
			return fmt.Errorf("部门编码重复")
		}
		if org, err = orgRepository.FindOne(map[string]interface{}{"companyId": orgInfo.CompanyId, "parentId": orgInfo.ParentId, "orgName": orgInfo.OrgName}); err == nil && org != nil {
			return fmt.Errorf("部门名称重复")
		}
	}
	return nil
}

func NewPgCreateOrgService(transactionContext *pgTransaction.TransactionContext) (*PgCreateOrgService, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &PgCreateOrgService{
			transactionContext: transactionContext,
		}, nil
	}
}