Skip to content

Commit

Permalink
Wallet API - Refactor / Bug Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
cristiandean committed Jan 3, 2022
1 parent 38f6076 commit 8ca3817
Show file tree
Hide file tree
Showing 17 changed files with 64 additions and 56 deletions.
2 changes: 1 addition & 1 deletion api/certificates_of_deposit_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (s *server) getAllCertificatesOfDepositOperations(c echo.Context) error {
func (s *server) getCertificateOfDepositOperationByID(c echo.Context) error {
id := c.Param("id")
log.Debugf("[API] Retrieving certificate of deposit operation with id: %s", id)
result := &wallet.CertificateOfDeposit{}
result := wallet.NewCertificateOfDeposit()
if err := s.db.Get(id, result); err != nil {
errMsg := fmt.Sprintf("Error on retrieve '%s' operations: %v", id, err)
return logAndReturnError(c, errMsg)
Expand Down
2 changes: 1 addition & 1 deletion api/ficfi_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (s *server) getAllFICFIOperations(c echo.Context) error {
func (s *server) getFICFIOperationByID(c echo.Context) error {
id := c.Param("id")
log.Debugf("[API] Retrieving FICFI operation with id: %s", id)
result := &wallet.FICFI{}
result := wallet.NewFICFI()
if err := s.db.Get(id, result); err != nil {
errMsg := fmt.Sprintf("Error on retrieve '%s' operations: %v", id, err)
return logAndReturnError(c, errMsg)
Expand Down
2 changes: 1 addition & 1 deletion api/fiis_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (s *server) getAllFIIOperations(c echo.Context) error {
func (s *server) getFIIOperationByID(c echo.Context) error {
id := c.Param("id")
log.Debugf("[API] Retrieving stock operation with id: %s", id)
result := &wallet.FII{}
result := wallet.NewFII()
if err := s.db.Get(id, result); err != nil {
errMsg := fmt.Sprintf("Error on retrieve '%s' operations: %v", id, err)
return logAndReturnError(c, errMsg)
Expand Down
8 changes: 2 additions & 6 deletions api/portfolios.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,10 @@ import (
)

func getYear(c echo.Context) (int, error) {
var year int
yearString := c.QueryParam("year")
if yearString != "" {
if yearString := c.QueryParam("year"); yearString != "" {
return strconv.Atoi(yearString)
} else {
t := time.Now()
year = t.Year()
}
year := time.Now().Year()
return year, nil
}

Expand Down
2 changes: 1 addition & 1 deletion api/stocks_funds_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (s *server) getAllStockFundsOperations(c echo.Context) error {
func (s *server) getStockFundOperationByID(c echo.Context) error {
id := c.Param("id")
log.Debugf("[API] Retrieving stock fund operation with id: %s", id)
result := &wallet.StockFund{}
result := wallet.NewStockFund()
if err := s.db.Get(id, result); err != nil {
errMsg := fmt.Sprintf("Error on retrieve '%s' operations: %v", id, err)
return logAndReturnError(c, errMsg)
Expand Down
2 changes: 1 addition & 1 deletion api/treasuries_direct_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (s *server) getAllTreasuriesDirectOperations(c echo.Context) error {
func (s *server) getTreasuryDirectOperationByID(c echo.Context) error {
id := c.Param("id")
log.Debugf("[API] Retrieving treasury direct operation with id: %s", id)
result := &wallet.TreasuryDirect{}
result := wallet.NewTreasuryDirect()
if err := s.db.Get(id, result); err != nil {
errMsg := fmt.Sprintf("Error on retrieve '%s' operations: %v", id, err)
return logAndReturnError(c, errMsg)
Expand Down
8 changes: 4 additions & 4 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ func init() {
viper.SetDefault("mongodb.name", "finance-wallet")
viper.SetDefault("port", 8889)
viper.SetDefault("debug", false)
viper.SetDefault("db.operation.timeout", 3)
viper.SetDefault("collection.operation.timeout", 3)
viper.SetDefault("financeapi.operation.timeout", 3)
viper.SetDefault("financeapi.url", "https://mfinance.com.br/api/v1")
logLevel := log.InfoLevel
if viper.GetBool("debug") {
logLevel = log.DebugLevel
Expand All @@ -28,8 +32,4 @@ func init() {
DisableColors: true,
FullTimestamp: true,
})
viper.SetDefault("db.operation.timeout", 3)
viper.SetDefault("collection.operation.timeout", 3)
viper.SetDefault("financeapi.operation.timeout", 3)
viper.SetDefault("financeapi.url", "https://mfinance.com.br/api/v1")
}
46 changes: 24 additions & 22 deletions db/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
package db

import (
"errors"
"fmt"
"time"

"github.com/mfinancecombr/finance-wallet-api/wallet"
Expand All @@ -12,6 +14,15 @@ import (
"go.mongodb.org/mongo-driver/mongo/options"
)

var operationTypes = map[string]func() wallet.Tradable{
wallet.ItemTypeStocks: func() wallet.Tradable { return wallet.NewStock() },
wallet.ItemTypeFIIS: func() wallet.Tradable { return wallet.NewFII() },
wallet.ItemTypeCertificateOfDeposit: func() wallet.Tradable { return wallet.NewCertificateOfDeposit() },
wallet.ItemTypeStocksTreasuriesDirect: func() wallet.Tradable { return wallet.NewTreasuryDirect() },
wallet.ItemTypeStocksStocksFunds: func() wallet.Tradable { return wallet.NewStock() },
wallet.ItemTypeStocksFICFI: func() wallet.Tradable { return wallet.NewFICFI() },
}

func (m *mongoSession) getOperationsSymbols(filter bson.M) ([]interface{}, error) {
log.Debug("[DB] getOperationSymbols")
return m.collection.Distinct(operationsCollection, "symbol", filter)
Expand All @@ -23,35 +34,26 @@ func (m *mongoSession) getItemTypes() ([]interface{}, error) {
}

func (m *mongoSession) getAllOperationsBySymbol(symbol, itemType string, year int) (wallet.OperationsList, error) {
log.Debug("[DB] getAllOperationsBySymbol")
date := time.Date(year, 12, 31, 23, 59, 59, 0, time.UTC)
query := bson.M{"symbol": symbol, "date": bson.M{"$lte": date}}
opts := options.Find().SetSort(bson.D{{"date", 1}})
log.Debug("[DB] getAllOperationsBySymbol", "year", year)
date := time.Date(year+1, 1, 1, 0, 0, 0, 0, time.UTC)
query := bson.M{"symbol": symbol, "date": bson.M{"$lt": date}}
opts := options.Find().SetSort(bson.D{{Key: "date", Value: 1}})
results, err := m.collection.FindAll(operationsCollection, query, opts)
if err != nil {
return nil, err
}
// FIXME
operationsList := wallet.OperationsList{}
for _, result := range results {
var operation wallet.Tradable
switch itemType {
case "stocks":
operation = &wallet.Stock{}
case "fiis":
operation = &wallet.FII{}
case "certificates-of-deposit":
operation = &wallet.CertificateOfDeposit{}
case "treasuries-direct":
operation = &wallet.TreasuryDirect{}
case "stocks-funds":
operation = &wallet.StockFund{}
case "ficfi":
operation = &wallet.FICFI{}
default:
log.Errorf("Item type '%s' not found", itemType)
newOperationType, ok := operationTypes[itemType]
if !ok {
errMsg := fmt.Sprintf("operation type)Item type '%s' not found", itemType)
return nil, errors.New(errMsg)
}
operation := newOperationType()
bsonBytes, err := bson.Marshal(result)
if err != nil {
return nil, err
}
bsonBytes, _ := bson.Marshal(result)
bson.Unmarshal(bsonBytes, operation)
operationsList = append(operationsList, operation)
}
Expand Down
2 changes: 1 addition & 1 deletion wallet/certificate_of_deposit.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type CertificateOfDeposit struct {

type CertificateOfDepositList []CertificateOfDeposit

const CertificateOfDepositItemType = "certificate-of-deposit"
const CertificateOfDepositItemType = ItemTypeCertificateOfDeposit

func NewCertificateOfDeposit() *CertificateOfDeposit {
return &CertificateOfDeposit{ItemType: CertificateOfDepositItemType}
Expand Down
2 changes: 1 addition & 1 deletion wallet/ficfi.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type FICFI struct {

type FICFIList []FICFI

const FICFIItemType = "ficfi"
const FICFIItemType = ItemTypeStocksFICFI

func NewFICFI() *FICFI {
return &FICFI{ItemType: FICFIItemType}
Expand Down
2 changes: 1 addition & 1 deletion wallet/fii.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type FII struct {

type FIIList []FII

const FIIItemType = "fiis"
const FIIItemType = ItemTypeFIIS

func NewFII() *FII {
return &FII{ItemType: FIIItemType}
Expand Down
4 changes: 3 additions & 1 deletion wallet/portfolio.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,7 @@ func (p *Portfolio) Recalculate() {

p.CostBasis = roundFloatTwoDecimalPlaces(costBasis)
p.Gain = roundFloatTwoDecimalPlaces(gain)
p.OverallReturn = roundFloatTwoDecimalPlaces(p.Gain * 100 / p.CostBasis)
if p.CostBasis > 0 {
p.OverallReturn = roundFloatTwoDecimalPlaces(p.Gain * 100 / p.CostBasis)
}
}
2 changes: 1 addition & 1 deletion wallet/position.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (pi *Position) Recalculate() {
pi.AveragePrice = roundFloatTwoDecimalPlaces(pi.CostBasis / pi.Shares)

// FIXME
if pi.ItemType == "stocks" || pi.ItemType == "fiis" {
if pi.ItemType == ItemTypeStocks || pi.ItemType == ItemTypeFIIS {
gain := (pi.Shares * pi.LastPrice) - pi.CostBasis
pi.Gain = roundFloatTwoDecimalPlaces(gain)
pi.OverallReturn = roundFloatTwoDecimalPlaces((gain * 100) / pi.CostBasis)
Expand Down
2 changes: 1 addition & 1 deletion wallet/stock.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type Stock struct {

type StockList []Stock

const StockItemType = "stocks"
const StockItemType = ItemTypeStocks

func NewStock() *Stock {
return &Stock{ItemType: StockItemType}
Expand Down
2 changes: 1 addition & 1 deletion wallet/stock_fund.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type StockFund struct {

type StockFundList []StockFund

const StockFundItemType = "stocks-funds"
const StockFundItemType = ItemTypeStocksStocksFunds

func NewStockFund() *StockFund {
return &StockFund{ItemType: StockFundItemType}
Expand Down
9 changes: 9 additions & 0 deletions wallet/tradable.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,12 @@ type Tradable interface {
GetType() string
GetBrokerSlug() string
}

const (
ItemTypeStocks = "stocks"
ItemTypeFIIS = "fiis"
ItemTypeCertificateOfDeposit = "certificate-of-deposit"
ItemTypeStocksTreasuriesDirect = "treasury-direct"
ItemTypeStocksStocksFunds = "stocks-funds"
ItemTypeStocksFICFI = "ficfi"
)
23 changes: 11 additions & 12 deletions wallet/treasury_direct.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,17 @@ import (
)

type TreasuryDirect struct {
BrokerSlug string `json:"brokerSlug" bson:"brokerSlug" validate:"required"`
Commission float64 `json:"commission" bson:"commission"`
Date *time.Time `json:"date" bson:"date" validate:"required"`
//DueDate *time.Time `json:"dueDate" bson:"dueDate" validate:"required"`
FixedInterestRate float64 `json:"fixedInterestRate" bson:"fixedInterestRate" validate:"required"`
ID string `json:"id,omitempty" bson:"_id,omitempty"`
ItemType string `json:"itemType" bson:"itemType" validate:"required"`
PortfolioSlug string `json:"portfolioSlug" bson:"portfolioSlug" validate:"required"`
Price float64 `json:"price" bson:"price" validate:"required"`
Shares float64 `json:"shares" bson:"shares" validate:"required"`
Symbol string `json:"symbol" bson:"symbol" validate:"required"`
Type string `json:"type" bson:"type" validate:"required"`
BrokerSlug string `json:"brokerSlug" bson:"brokerSlug" validate:"required"`
Commission float64 `json:"commission" bson:"commission"`
Date *time.Time `json:"date" bson:"date" validate:"required"`
FixedInterestRate float64 `json:"fixedInterestRate" bson:"fixedInterestRate" validate:"required"`
ID string `json:"id,omitempty" bson:"_id,omitempty"`
ItemType string `json:"itemType" bson:"itemType" validate:"required"`
PortfolioSlug string `json:"portfolioSlug" bson:"portfolioSlug" validate:"required"`
Price float64 `json:"price" bson:"price" validate:"required"`
Shares float64 `json:"shares" bson:"shares" validate:"required"`
Symbol string `json:"symbol" bson:"symbol" validate:"required"`
Type string `json:"type" bson:"type" validate:"required"`
}

type TreasuryDirectList []TreasuryDirect
Expand Down

0 comments on commit 8ca3817

Please sign in to comment.