pg_auth_account_destroy_service.go 2.5 KB
package domainService

import (
	"fmt"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/repository"

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

// PgAuthAccountDestroyService 账号注销服务
type PgAuthAccountDestroyService struct {
	transactionContext *pgTransaction.TransactionContext
}

func (ptr *PgAuthAccountDestroyService) DestroyAccount(optUser *domain.User, userId int64) error {
	// 1.查询账号记录
	userRepository, _ := repository.NewUserRepository(ptr.transactionContext)
	var userBaseId int64
	if user, err := userRepository.FindOne(map[string]interface{}{"userId": userId}); err != nil {
		if err == domain.ErrorNotFound {
			return fmt.Errorf("该用户不存在")
		}
		return err
	} else {
		userBaseId = user.UserBaseId
	}

	userBaseRepository, _ := repository.NewUserBaseRepository(ptr.transactionContext)
	userBase, err := userBaseRepository.FindOne(map[string]interface{}{"userBaseId": userBaseId})
	if err != nil {
		return err
	}
	if err == domain.ErrorNotFound {
		return fmt.Errorf("该用户不存在")
	}

	// 2.查询历史账号注销记录,生成当前账号的注销记录
	accountDestroyRecordRepository, _ := repository.NewAccountDestroyRecordRepository(ptr.transactionContext)
	var total int64
	if total, _, err = accountDestroyRecordRepository.Find(map[string]interface{}{"accountBefore": userBase.Account}); err != nil {
		return err
	}
	record := domain.NewAccountDestroyRecord(userBase.UserBaseId, total, userBase.Account)
	if _, err := accountDestroyRecordRepository.Save(record); err != nil {
		return err
	}

	// 3.注销相关联的账号
	for i := 0; i < len(userBase.RelatedUsers); i++ {
		userId := userBase.RelatedUsers[i]
		if user, _ := userRepository.FindOne(map[string]interface{}{"userId": userId}); user != nil {
			user.DestroyAccount(record.AccountAfter)
			if _, err := userRepository.Save(user); err != nil {
				return err
			}
		}
	}

	// 4.注销账号
	if err = userBase.DestroyAccount(record.AccountAfter); err != nil {
		return err
	}
	if _, err = userBaseRepository.Save(userBase); err != nil {
		return err
	}
	return nil
}

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