pg_add_user_service.go 1.8 KB
package domainService

import (
	"fmt"
	coreDomain "github.com/linmadan/egglib-go/core/domain"
	"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/repository"

	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
)

type AddUserService struct {
	coreDomain.BaseEventPublisher
	transactionContext *pgTransaction.TransactionContext
}

func (service *AddUserService) AddUser(user *domain.User) (*domain.User, error) {

	if user.UserType&1 > 0 {
		if _, err := domain.CheckAdminUserType(user); err != nil {
			return nil, err
		}
	}

	if user.UserType&2 > 0 {
		if _, err := domain.CheckPartnerUserType(user); err != nil {
			return nil, err
		}
	}

	var userRepository domain.UserRepository
	if repository, err := repository.NewUserRepository(service.transactionContext); err != nil {
		return nil, err
	} else {
		userRepository = repository
	}

	count, existUser, err := userRepository.Find(map[string]interface{}{
		"userAccount": user.UserAccount,
		"companyId":   user.CompanyId,
	})

	if count != 0 {
		if existUser[0].UserType^user.UserType == 0 {
			return nil, fmt.Errorf("用户已存在")
		}
		if existUser[0].UserType&1 > 0 {
			user.UserInfo = existUser[0].UserInfo
		}
		if existUser[0].UserType&2 > 0 {
			user.PartnerInfo = existUser[0].PartnerInfo
		}
		user.UserType = existUser[0].UserType + user.UserType
	}

	user, err = userRepository.Save(user)

	if err != nil {
		return nil, err
	}

	return user, nil
}

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