pg_create_company_service.go 2.9 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"
	"time"
)

// PgCreateCompanyService 创建公司服务
type PgCreateCompanyService struct {
	transactionContext *pgTransaction.TransactionContext
}

// CreateCompany  创建公司
//
// registerPhone 注册手机号
// companyInfo 注册公司信息
func (s *PgCreateCompanyService) CreateCompany(optUser *domain.User, registerPhone string, companyInfo *domain.CompanyInfo) (*domain.Company, error) {
	if companyInfo == nil {
		return nil, fmt.Errorf("企业信息不能为空")
	}
	if len(companyInfo.CompanyName) == 0 {
		return nil, fmt.Errorf("企业名称不能为空")
	}

	var err error
	var company *domain.Company
	companyRepository, _ := repository.NewCompanyRepository(s.transactionContext)

	// 1.检查账号是否被注册过,一个手机号只能注册一家企业
	var userBase *domain.UserBase
	userBaseRepository, _ := repository.NewUserBaseRepository(s.transactionContext)
	if userBase, err = userBaseRepository.FindOne(map[string]interface{}{"account": registerPhone}); err == nil && userBase != nil {
		userRepository, _ := repository.NewUserRepository(s.transactionContext)
		if _, users, _ := userRepository.Find(map[string]interface{}{"userBaseId": userBase.UserBaseId}); len(users) > 0 {
			for i := 0; i < len(users); i++ {
				if users[i].UserType&domain.RoleTypeAdmin > 0 && users[i].Company != nil {
					if company, err = companyRepository.FindOne(map[string]interface{}{"companyId": users[i].Company.CompanyId}); err != nil {
						return nil, err
					} else if company.Status != domain.CompanyUnauthenticated {
						return nil, fmt.Errorf("该手机号已注册")
					}
				}
			}
		}
	}

	// 2.企业名称检查

	if company, err = companyRepository.FindOne(map[string]interface{}{"companyName": companyInfo.CompanyName, "statusNotIn": []int{domain.CompanyUnauthenticated}}); err != nil && err != domain.ErrorNotFound {
		return nil, fmt.Errorf("该企业已经注册")
	} else if company != nil && company.CompanyInfo.CompanyName == companyInfo.CompanyName {
		return nil, fmt.Errorf("该企业已经注册")
	}
	company = &domain.Company{
		CompanyConfig: &domain.CompanyConfig{SystemName: companyInfo.CompanyName},
		CompanyInfo:   companyInfo,
		Status:        domain.CompanyRegistered,
		CreatedAt:     time.Now(),
		UpdatedAt:     time.Now(),
	}
	if company, err = companyRepository.Save(company); err != nil {
		return nil, err
	}
	return company, nil
}

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