feat: actualize models

This commit is contained in:
Kirill 2023-06-01 00:28:35 +03:00
parent 9d2a97e74d
commit 1c4bd425d2
5 changed files with 151 additions and 24 deletions

@ -3,12 +3,29 @@ package models
import "time" import "time"
type Account struct { type Account struct {
ID string `json:"id" bson:"_id,omitempty"` ID string `json:"id" bson:"_id,omitempty"`
UserID string `json:"userId" bson:"userId"` UserID string `json:"userId" bson:"userId"`
Cart []string `json:"cart" bson:"cart"` Cart []string `json:"cart" bson:"cart"`
Wallet Wallet `json:"wallet" bson:"wallet"` Wallet Wallet `json:"wallet" bson:"wallet"`
Deleted bool `json:"deleted" bson:"deleted"` Name Name `json:"name" bson:"name"`
CreatedAt time.Time `json:"createdAt" bson:"createdAt"` Status AccountStatus `json:"status" bson:"status"`
UpdatedAt time.Time `json:"updatedAt" bson:"updatedAt"` Deleted bool `json:"deleted" bson:"deleted"`
DeletedAt *time.Time `json:"deletedAt,omitempty" bson:"deletedAt,omitempty"` CreatedAt time.Time `json:"createdAt" bson:"createdAt"`
UpdatedAt time.Time `json:"updatedAt" bson:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt,omitempty" bson:"deletedAt,omitempty"`
} }
type Name struct {
Lastname *string `json:"lastname,omitempty"`
Name *string `json:"name,omitempty"`
Orgname *string `json:"orgname,omitempty"`
Secondname *string `json:"secondname,omitempty"`
}
type AccountStatus string
const (
AccountStatusNko AccountStatus = "nko"
AccountStatusNo AccountStatus = "no"
AccountStatusOrg AccountStatus = "org"
)

@ -1,8 +1,16 @@
package models package models
/*
TODO:
5) актуализировать поле spent при покупке средств
*/
type Wallet struct { type Wallet struct {
Cash int64 `json:"cash"` Cash int64 `json:"cash" bson:"cash"`
Currency string `json:"currency"` Currency string `json:"currency" bson:"currency"`
Spent int64 `json:"spent" bson:"spent"`
PurchasesAmount int64 `json:"purchasesAmount" bson:"purchasesAmount"`
/* /*
Money деньги на счету в копейках. Чтобы при перессчётах не возникало денег из ни откуда. Money деньги на счету в копейках. Чтобы при перессчётах не возникало денег из ни откуда.

@ -15,6 +15,8 @@ import (
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/utils/transfer" "penahub.gitlab.yandexcloud.net/pena-services/customer/internal/utils/transfer"
) )
// TODO: добавить интерфейс клиента сервиса оплаты
type accountRepository interface { type accountRepository interface {
FindByUserID(ctx context.Context, id string) (*models.Account, errors.Error) FindByUserID(ctx context.Context, id string) (*models.Account, errors.Error)
AddItemToCart(ctx context.Context, userID, itemID string) (*models.Account, errors.Error) AddItemToCart(ctx context.Context, userID, itemID string) (*models.Account, errors.Error)
@ -136,9 +138,9 @@ func (receiver *Service) Pay(ctx context.Context, userID string) errors.Error {
response, err := receiver.discountClient.Apply(ctx, &discount.ApplyDiscountRequest{ response, err := receiver.discountClient.Apply(ctx, &discount.ApplyDiscountRequest{
UserInformation: &discount.UserInformation{ UserInformation: &discount.UserInformation{
ID: account.UserID, ID: account.UserID,
Type: "", // TODO: Добавить тип Type: string(account.Status),
PurchasesAmount: 0, // TODO: Добавить PurchasesAmount: float64(account.Wallet.PurchasesAmount),
CartPurchasesAmount: float64(tariffsAmount), // TODO: Перевести в int64 CartPurchasesAmount: float64(tariffsAmount),
}, },
Products: transfer.TariffsToProductInformations(tariffs), Products: transfer.TariffsToProductInformations(tariffs),
Date: timestamppb.New(time.Now()), Date: timestamppb.New(time.Now()),
@ -161,6 +163,7 @@ func (receiver *Service) Pay(ctx context.Context, userID string) errors.Error {
) )
} }
// TODO: изменить метод пополнения на метод вычитания средств с кошелька
if _, err := receiver.walletService.ReplenishAccountWallet(ctx, &models.ReplenishAccountWallet{ if _, err := receiver.walletService.ReplenishAccountWallet(ctx, &models.ReplenishAccountWallet{
Cash: -int64(response.Price), Cash: -int64(response.Price),
Currency: account.Wallet.Currency, Currency: account.Wallet.Currency,

@ -95,9 +95,10 @@ func (receiver *Service) ReplenishAccountWallet(ctx context.Context, request *mo
if request.Currency == models.InternalCurrencyKey { if request.Currency == models.InternalCurrencyKey {
updatedAccount, changeErr := receiver.repository.ChangeWallet(ctx, account.UserID, &models.Wallet{ updatedAccount, changeErr := receiver.repository.ChangeWallet(ctx, account.UserID, &models.Wallet{
Cash: account.Wallet.Cash + cash, Cash: account.Wallet.Cash + cash,
Money: account.Wallet.Money + request.Cash, Money: account.Wallet.Money + request.Cash,
Currency: account.Wallet.Currency, PurchasesAmount: account.Wallet.PurchasesAmount + request.Cash,
Currency: account.Wallet.Currency,
}) })
if changeErr != nil { if changeErr != nil {
receiver.logger.Error("failed to replenish wallet on <ReplenishAccountWallet> of <WalletService>", receiver.logger.Error("failed to replenish wallet on <ReplenishAccountWallet> of <WalletService>",
@ -128,9 +129,103 @@ func (receiver *Service) ReplenishAccountWallet(ctx context.Context, request *mo
} }
updatedAccount, err := receiver.repository.ChangeWallet(ctx, account.UserID, &models.Wallet{ updatedAccount, err := receiver.repository.ChangeWallet(ctx, account.UserID, &models.Wallet{
Cash: account.Wallet.Cash + cash, Cash: account.Wallet.Cash + cash,
Money: account.Wallet.Money + money, Money: account.Wallet.Money + money,
Currency: account.Wallet.Currency, PurchasesAmount: account.Wallet.PurchasesAmount + money,
Currency: account.Wallet.Currency,
})
if err != nil {
receiver.logger.Error("failed to replenish wallet on <ReplenishAccountWallet> of <WalletService>",
zap.Error(err.Extract()),
zap.String("Currency", account.Wallet.Currency),
zap.Int64("Money", account.Wallet.Money+request.Cash),
zap.Int64("Cash", account.Wallet.Cash+cash),
zap.Bool("Is currensy equal internal", request.Currency == models.InternalCurrencyKey),
)
return nil, err
}
return updatedAccount, nil
}
func (receiver *Service) WithdrawAccountWalletMoney(ctx context.Context, money int64) (*models.Account, errors.Error) {
account, err := receiver.repository.FindByUserID(ctx, request.UserID)
if err != nil {
receiver.logger.Error("failed to find account on <ReplenishAccountWallet> of <WalletService>",
zap.Error(err.Extract()),
zap.String("userID", request.UserID),
)
return nil, err
}
if validate.IsStringEmpty(account.Wallet.Currency) {
return nil, errors.New(
fmt.Errorf("currency of account <%s> is empty <ReplenishAccountWallet> of <WalletService>", account.UserID),
errors.ErrInternalError,
)
}
cash := request.Cash
if request.Currency != account.Wallet.Currency {
translatedCash, translateErr := receiver.currencyClient.Translate(ctx, &models.TranslateCurrency{
Money: request.Cash,
From: request.Currency,
To: account.Wallet.Currency,
})
if translateErr != nil {
receiver.logger.Error("failed to translate cash on <ReplenishAccountWallet> of <WalletService>",
zap.Error(translateErr.Extract()),
)
return nil, translateErr
}
cash = translatedCash
}
if request.Currency == models.InternalCurrencyKey {
updatedAccount, changeErr := receiver.repository.ChangeWallet(ctx, account.UserID, &models.Wallet{
Cash: account.Wallet.Cash + cash,
Money: account.Wallet.Money + request.Cash,
PurchasesAmount: account.Wallet.PurchasesAmount + request.Cash,
Currency: account.Wallet.Currency,
})
if changeErr != nil {
receiver.logger.Error("failed to replenish wallet on <ReplenishAccountWallet> of <WalletService>",
zap.Error(changeErr.Extract()),
zap.String("Currency", account.Wallet.Currency),
zap.Int64("Money", account.Wallet.Money+request.Cash),
zap.Int64("Cash", account.Wallet.Cash+cash),
zap.Bool("Is currensy equal internal", request.Currency == models.InternalCurrencyKey),
)
return nil, changeErr
}
return updatedAccount, nil
}
money, err := receiver.currencyClient.Translate(ctx, &models.TranslateCurrency{
Money: request.Cash,
From: request.Currency,
To: models.InternalCurrencyKey,
})
if err != nil {
receiver.logger.Error("failed to translate money on <ReplenishAccountWallet> of <WalletService>",
zap.Error(err.Extract()),
)
return nil, err
}
updatedAccount, err := receiver.repository.ChangeWallet(ctx, account.UserID, &models.Wallet{
Cash: account.Wallet.Cash + cash,
Money: account.Wallet.Money + money,
PurchasesAmount: account.Wallet.PurchasesAmount + money,
Currency: account.Wallet.Currency,
}) })
if err != nil { if err != nil {
receiver.logger.Error("failed to replenish wallet on <ReplenishAccountWallet> of <WalletService>", receiver.logger.Error("failed to replenish wallet on <ReplenishAccountWallet> of <WalletService>",

@ -656,7 +656,7 @@ components:
Account: Account:
type: object type: object
required: [_id, userId, cart, wallet, deleted, createdAt, updatedAt] required: [_id, userId, cart, wallet, name, status, deleted, createdAt, updatedAt]
properties: properties:
_id: _id:
type: string type: string
@ -677,7 +677,7 @@ components:
$ref: "#/components/schemas/Wallet" $ref: "#/components/schemas/Wallet"
status: status:
type: string type: string
enum: ["no", "org", "nko"] enum: ["no", "org", "nko"] /* TODO: no по дефолту */
deleted: deleted:
type: boolean type: boolean
example: false example: false
@ -694,7 +694,7 @@ components:
Name: Name:
type: object type: object
properties: properties:
name: firstname:
type: string type: string
example: Иван example: Иван
secondname: secondname:
@ -709,7 +709,7 @@ components:
Wallet: Wallet:
type: object type: object
required: [currency, cash, money] required: [currency, cash, money, purchasesAmount, spent]
properties: properties:
currency: currency:
description: Текущий курс валюты description: Текущий курс валюты
@ -720,10 +720,14 @@ components:
type: integer type: integer
format: int64 format: int64
example: 10701 example: 10701
purchasesAmount:
type: integer
format: int64
description: Общая сумма денег, которые внёс пользователь
spent: spent:
type: integer type: integer
format: int64 format: int64
description: общая сумма потраченных денег за всё время существования аккаунта description: Общая сумма потраченных денег за всё время существования аккаунта
money: money:
type: integer type: integer
format: int64 format: int64