pg_update_user_base_service.go 2.2 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"
	"strings"
	"time"
)

// PgUpdateUserBaseService 用户基础更新服务
type PgUpdateUserBaseService struct {
	transactionContext *pgTransaction.TransactionContext
}

func (ptr *PgUpdateUserService) UpdateUserBase(optUser *domain.OperateInfo, userBaseId int64, userInfo *domain.UserInfo) (*domain.UserBase, error) {
	var err error

	//1.更新用户信息
	userBaseRepository, _ := repository.NewUserBaseRepository(ptr.transactionContext)
	var userBase *domain.UserBase
	if userBase, err = userBaseRepository.FindOne(map[string]interface{}{"userBaseId": userBaseId}); err != nil {
		return nil, err
	}
	if userBase.Account != strings.TrimSpace(userInfo.Phone) && len(userInfo.Phone) > 0 { // 修改了手机号
		if _, err = userBaseRepository.FindOne(map[string]interface{}{"account": strings.TrimSpace(userInfo.Phone)}); err == nil {
			return nil, fmt.Errorf("手机号已存在")
		}
		if err = userBase.ResetPhone(userBase.Account, userInfo.Phone); err != nil {
			return nil, err
		}
	}
	if err = userBase.UpdateUserInfo(userInfo); err != nil {
		return nil, err
	}
	if userBase, err = userBaseRepository.Save(userBase); err != nil {
		return nil, err
	}

	//2.更新用户、冗余信息
	var users []*domain.User
	userRepository, _ := repository.NewUserRepository(ptr.transactionContext)
	if _, users, err = userRepository.Find(map[string]interface{}{"userBaseId": userBaseId}); err != nil {
		return nil, err
	}
	for i := range users {
		user := users[i]
		user.Ext.Phone = userBase.UserInfo.Phone
		user.Ext.UserName = userBase.UserInfo.UserName
		user.UpdatedAt = time.Now()
		if user, err = userRepository.Save(user); err != nil {
			return nil, err
		}
	}

	return userBase, nil
}

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