pg_exchange_su_money_service.go 2.8 KB
package domain_service

import (
	"fmt"
	coreDomain "github.com/linmadan/egglib-go/core/domain"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
	"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/dao"
	"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/repository"
	"time"
)

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

func (service *ExchangeSuMoneyService) Exchange(uid int64, operatorUid int64, suMoney float64, recordDescription string) (*domain.SuMoneyTransactionRecord, error) {
	var employeeRepository domain.EmployeeRepository
	var suMoneyTransactionRecordRepository domain.SuMoneyTransactionRecordRepository
	var employeeDao *dao.EmployeeDao
	if repository, err := repository.NewEmployeeRepository(service.transactionContext); err != nil {
		return nil, err
	} else {
		employeeRepository = repository
	}
	if repository, err := repository.NewSuMoneyTransactionRecordRepository(service.transactionContext); err != nil {
		return nil, err
	} else {
		suMoneyTransactionRecordRepository = repository
	}
	if dao, err := dao.NewEmployeeDao(service.transactionContext); err != nil {
		return nil, err
	} else {
		employeeDao = dao
	}
	employee, err := employeeRepository.FindOne(map[string]interface{}{
		"uid": uid,
	})
	if err != nil {
		return nil, err
	}
	if employee == nil {
		return nil, fmt.Errorf("无效的兑换者")
	}
	operator, err := employeeRepository.FindOne(map[string]interface{}{
		"uid": operatorUid,
	})
	if err != nil {
		return nil, err
	}
	if operator == nil {
		return nil, fmt.Errorf("无效的操作者")
	}
	if employee.SuMoney < suMoney {
		return nil, fmt.Errorf("当前素币不足")
	}
	suMoneyTransactionRecord := &domain.SuMoneyTransactionRecord{
		RecordType:               domain.SU_MONEY_TRANSACTION_RECORD_TYPE_EXCHANGE,
		Employee:                 employee.EmployeeInfo,
		SuMoneyBeforeTransaction: employee.SuMoney,
		SuMoney:                  suMoney,
		Operator:                 operator.EmployeeInfo,
		RecordDescription:        recordDescription,
		CreateTime:               time.Now(),
	}
	if err := employeeDao.TransferSuMoney(employee.EmployeeInfo.Uid, 0-suMoney); err != nil {
		return nil, err
	}
	if suMoneyTransactionRecord, err := suMoneyTransactionRecordRepository.Save(suMoneyTransactionRecord); err != nil {
		return nil, err
	} else {
		return suMoneyTransactionRecord, nil
	}
}

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