pg_auth_reset_phone_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"
)

// PgAuthResetPhoneService 重置手机号服务
type PgAuthResetPhoneService struct {
	transactionContext *pgTransaction.TransactionContext
}

// ResetPhone  重置手机号
//
// oldPhone 旧手机号
// newPhone 新手机号
func (ptr *PgAuthResetPhoneService) ResetPhone(optUser *domain.User, oldPhone, newPhone string) error {
	if len(oldPhone) == 0 {
		return fmt.Errorf("旧手机号不能为空")
	}
	if len(newPhone) == 0 {
		return fmt.Errorf("新手机号不能为空")
	}

	// 1.重置当前账号的手机号
	var err error
	var userBase *domain.UserBase
	userBaseRepository, _ := repository.NewUserBaseRepository(ptr.transactionContext)
	if userBase, err = userBaseRepository.FindOne(map[string]interface{}{"account": newPhone}); err == nil && userBase != nil {
		return fmt.Errorf("手机号已存在")
	}
	if userBase, err = userBaseRepository.FindOne(map[string]interface{}{"account": oldPhone}); err != nil {
		return err
	}
	if err == domain.ErrorNotFound {
		return fmt.Errorf("该用户不存在")
	}
	if err = userBase.ResetPhone(oldPhone, newPhone); err != nil {
		return err
	}
	if _, err := userBaseRepository.Save(userBase); err != nil {
		return err
	}

	// 2.重置跟账号相关的账号的手机号(冗余的扩展数据)
	userRepository, _ := repository.NewUserRepository(ptr.transactionContext)
	for i := 0; i < len(userBase.RelatedUsers); i++ {
		userId := userBase.RelatedUsers[i]
		if user, _ := userRepository.FindOne(map[string]interface{}{"userId": userId}); user != nil {
			user.Update(map[string]interface{}{"phone": newPhone}) //,"userBaseId":userBase.UserBaseId
			if _, err := userRepository.Save(user); err != nil {
				return err
			}
		}
	}

	return err
}

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