forked from ebhomengo/niki
58 lines
1.6 KiB
Go
58 lines
1.6 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"git.gocasts.ir/ebhomengo/niki/domain/wallet/entity"
|
|
"git.gocasts.ir/ebhomengo/niki/domain/wallet/param"
|
|
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
|
|
"git.gocasts.ir/ebhomengo/niki/pkg/types"
|
|
|
|
//"git.gocasts.ir/ebhomengo/niki/pkg/types"
|
|
"github.com/shopspring/decimal"
|
|
)
|
|
|
|
func (s Service) CreateTransaction(ctx context.Context, request param.CreateTransactionRequest) (param.InsertTransactionResponse, error) {
|
|
|
|
const op = richerror.Op("wallet.service.CreateTransaction")
|
|
|
|
currencyRate := s.convertCurrency(request.Currency)
|
|
|
|
convertedAmount, _ := decimal.NewFromString(request.Amount)
|
|
|
|
transaction := entity.Transaction{
|
|
ID: 0,
|
|
UserID: request.UserID,
|
|
Amount: convertedAmount,
|
|
Currency: request.Currency,
|
|
ActionType: request.ActionType,
|
|
Timestamp: request.Timestamp,
|
|
CreatedAt: time.Now(),
|
|
}
|
|
|
|
balance, walletCurrency, inErr := s.repo.InsertTransaction(ctx, transaction, currencyRate)
|
|
if inErr != nil {
|
|
return param.InsertTransactionResponse{}, richerror.New(op).WithErr(inErr)
|
|
}
|
|
|
|
return param.InsertTransactionResponse{Balance: balance, Currency: walletCurrency}, nil
|
|
|
|
}
|
|
|
|
func (s Service) convertCurrency(currency types.Currency) decimal.Decimal {
|
|
|
|
if currency != types.IRR {
|
|
currencyRate, cErr := s.currencyRateProvider.GetCurrencyPriceRateInIRR(currency)
|
|
if cErr != nil {
|
|
// log // fallback or change provider
|
|
return decimal.Zero // if 0 => transaction commited with currency but wallet doesn't update or add 0 to wallet
|
|
}
|
|
|
|
return currencyRate
|
|
|
|
}
|
|
return decimal.NewFromInt(1)
|
|
|
|
}
|