1
0
mirror of https://github.com/aclindsa/moneygo.git synced 2024-12-25 23:23:21 -05:00

Split prices into models

This commit is contained in:
Aaron Lindsay 2017-12-04 21:05:17 -05:00
parent 128ea57c4d
commit 5f296e8669
7 changed files with 76 additions and 66 deletions

View File

@ -14,6 +14,9 @@ import (
"strings" "strings"
) )
// luaMaxLengthBuffer is intended to be enough bytes such that a given string
// no longer than models.LuaMaxLength is sure to fit within a database
// implementation's string type specified by the same.
const luaMaxLengthBuffer int = 4096 const luaMaxLengthBuffer int = 4096
func GetDbMap(db *sql.DB, dbtype config.DbType) (*gorp.DbMap, error) { func GetDbMap(db *sql.DB, dbtype config.DbType) (*gorp.DbMap, error) {
@ -40,7 +43,7 @@ func GetDbMap(db *sql.DB, dbtype config.DbType) (*gorp.DbMap, error) {
dbmap.AddTableWithName(models.Security{}, "securities").SetKeys(true, "SecurityId") dbmap.AddTableWithName(models.Security{}, "securities").SetKeys(true, "SecurityId")
dbmap.AddTableWithName(models.Transaction{}, "transactions").SetKeys(true, "TransactionId") dbmap.AddTableWithName(models.Transaction{}, "transactions").SetKeys(true, "TransactionId")
dbmap.AddTableWithName(models.Split{}, "splits").SetKeys(true, "SplitId") dbmap.AddTableWithName(models.Split{}, "splits").SetKeys(true, "SplitId")
dbmap.AddTableWithName(handlers.Price{}, "prices").SetKeys(true, "PriceId") dbmap.AddTableWithName(models.Price{}, "prices").SetKeys(true, "PriceId")
rtable := dbmap.AddTableWithName(handlers.Report{}, "reports").SetKeys(true, "ReportId") rtable := dbmap.AddTableWithName(handlers.Report{}, "reports").SetKeys(true, "ReportId")
rtable.ColMap("Lua").SetMaxSize(handlers.LuaMaxLength + luaMaxLengthBuffer) rtable.ColMap("Lua").SetMaxSize(handlers.LuaMaxLength + luaMaxLengthBuffer)

View File

@ -129,7 +129,7 @@ type GnucashImport struct {
Securities []models.Security Securities []models.Security
Accounts []models.Account Accounts []models.Account
Transactions []models.Transaction Transactions []models.Transaction
Prices []Price Prices []models.Price
} }
func ImportGnucash(r io.Reader) (*GnucashImport, error) { func ImportGnucash(r io.Reader) (*GnucashImport, error) {
@ -161,7 +161,7 @@ func ImportGnucash(r io.Reader) (*GnucashImport, error) {
// Create prices, setting security and currency IDs from securityMap // Create prices, setting security and currency IDs from securityMap
for i := range gncxml.PriceDB.Prices { for i := range gncxml.PriceDB.Prices {
price := gncxml.PriceDB.Prices[i] price := gncxml.PriceDB.Prices[i]
var p Price var p models.Price
security, ok := securityMap[price.Commodity.Name] security, ok := securityMap[price.Commodity.Name]
if !ok { if !ok {
return nil, fmt.Errorf("Unable to find commodity '%s' for price '%s'", price.Commodity.Name, price.Id) return nil, fmt.Errorf("Unable to find commodity '%s' for price '%s'", price.Commodity.Name, price.Id)

View File

@ -1,48 +1,13 @@
package handlers package handlers
import ( import (
"encoding/json"
"github.com/aclindsa/moneygo/internal/models" "github.com/aclindsa/moneygo/internal/models"
"log" "log"
"net/http" "net/http"
"strings"
"time" "time"
) )
type Price struct { func CreatePriceIfNotExist(tx *Tx, price *models.Price) error {
PriceId int64
SecurityId int64
CurrencyId int64
Date time.Time
Value string // String representation of decimal price of Security in Currency units, suitable for passing to big.Rat.SetString()
RemoteId string // unique ID from source, for detecting duplicates
}
type PriceList struct {
Prices *[]*Price `json:"prices"`
}
func (p *Price) Read(json_str string) error {
dec := json.NewDecoder(strings.NewReader(json_str))
return dec.Decode(p)
}
func (p *Price) Write(w http.ResponseWriter) error {
enc := json.NewEncoder(w)
return enc.Encode(p)
}
func (pl *PriceList) Read(json_str string) error {
dec := json.NewDecoder(strings.NewReader(json_str))
return dec.Decode(pl)
}
func (pl *PriceList) Write(w http.ResponseWriter) error {
enc := json.NewEncoder(w)
return enc.Encode(pl)
}
func CreatePriceIfNotExist(tx *Tx, price *Price) error {
if len(price.RemoteId) == 0 { if len(price.RemoteId) == 0 {
// Always create a new price if we can't match on the RemoteId // Always create a new price if we can't match on the RemoteId
err := tx.Insert(price) err := tx.Insert(price)
@ -52,7 +17,7 @@ func CreatePriceIfNotExist(tx *Tx, price *Price) error {
return nil return nil
} }
var prices []*Price var prices []*models.Price
_, err := tx.Select(&prices, "SELECT * from prices where SecurityId=? AND CurrencyId=? AND Date=? AND Value=?", price.SecurityId, price.CurrencyId, price.Date, price.Value) _, err := tx.Select(&prices, "SELECT * from prices where SecurityId=? AND CurrencyId=? AND Date=? AND Value=?", price.SecurityId, price.CurrencyId, price.Date, price.Value)
if err != nil { if err != nil {
@ -70,8 +35,8 @@ func CreatePriceIfNotExist(tx *Tx, price *Price) error {
return nil return nil
} }
func GetPrice(tx *Tx, priceid, securityid int64) (*Price, error) { func GetPrice(tx *Tx, priceid, securityid int64) (*models.Price, error) {
var p Price var p models.Price
err := tx.SelectOne(&p, "SELECT * from prices where PriceId=? AND SecurityId=?", priceid, securityid) err := tx.SelectOne(&p, "SELECT * from prices where PriceId=? AND SecurityId=?", priceid, securityid)
if err != nil { if err != nil {
return nil, err return nil, err
@ -79,8 +44,8 @@ func GetPrice(tx *Tx, priceid, securityid int64) (*Price, error) {
return &p, nil return &p, nil
} }
func GetPrices(tx *Tx, securityid int64) (*[]*Price, error) { func GetPrices(tx *Tx, securityid int64) (*[]*models.Price, error) {
var prices []*Price var prices []*models.Price
_, err := tx.Select(&prices, "SELECT * from prices where SecurityId=?", securityid) _, err := tx.Select(&prices, "SELECT * from prices where SecurityId=?", securityid)
if err != nil { if err != nil {
@ -90,8 +55,8 @@ func GetPrices(tx *Tx, securityid int64) (*[]*Price, error) {
} }
// Return the latest price for security in currency units before date // Return the latest price for security in currency units before date
func GetLatestPrice(tx *Tx, security, currency *models.Security, date *time.Time) (*Price, error) { func GetLatestPrice(tx *Tx, security, currency *models.Security, date *time.Time) (*models.Price, error) {
var p Price var p models.Price
err := tx.SelectOne(&p, "SELECT * from prices where SecurityId=? AND CurrencyId=? AND Date <= ? ORDER BY Date DESC LIMIT 1", security.SecurityId, currency.SecurityId, date) err := tx.SelectOne(&p, "SELECT * from prices where SecurityId=? AND CurrencyId=? AND Date <= ? ORDER BY Date DESC LIMIT 1", security.SecurityId, currency.SecurityId, date)
if err != nil { if err != nil {
return nil, err return nil, err
@ -100,8 +65,8 @@ func GetLatestPrice(tx *Tx, security, currency *models.Security, date *time.Time
} }
// Return the earliest price for security in currency units after date // Return the earliest price for security in currency units after date
func GetEarliestPrice(tx *Tx, security, currency *models.Security, date *time.Time) (*Price, error) { func GetEarliestPrice(tx *Tx, security, currency *models.Security, date *time.Time) (*models.Price, error) {
var p Price var p models.Price
err := tx.SelectOne(&p, "SELECT * from prices where SecurityId=? AND CurrencyId=? AND Date >= ? ORDER BY Date ASC LIMIT 1", security.SecurityId, currency.SecurityId, date) err := tx.SelectOne(&p, "SELECT * from prices where SecurityId=? AND CurrencyId=? AND Date >= ? ORDER BY Date ASC LIMIT 1", security.SecurityId, currency.SecurityId, date)
if err != nil { if err != nil {
return nil, err return nil, err
@ -110,7 +75,7 @@ func GetEarliestPrice(tx *Tx, security, currency *models.Security, date *time.Ti
} }
// Return the price for security in currency closest to date // Return the price for security in currency closest to date
func GetClosestPrice(tx *Tx, security, currency *models.Security, date *time.Time) (*Price, error) { func GetClosestPrice(tx *Tx, security, currency *models.Security, date *time.Time) (*models.Price, error) {
earliest, _ := GetEarliestPrice(tx, security, currency, date) earliest, _ := GetEarliestPrice(tx, security, currency, date)
latest, err := GetLatestPrice(tx, security, currency, date) latest, err := GetLatestPrice(tx, security, currency, date)
@ -137,7 +102,7 @@ func PriceHandler(r *http.Request, context *Context, user *models.User, security
} }
if r.Method == "POST" { if r.Method == "POST" {
var price Price var price models.Price
if err := ReadJSON(r, &price); err != nil { if err := ReadJSON(r, &price); err != nil {
return NewError(3 /*Invalid Request*/) return NewError(3 /*Invalid Request*/)
} }
@ -161,7 +126,7 @@ func PriceHandler(r *http.Request, context *Context, user *models.User, security
} else if r.Method == "GET" { } else if r.Method == "GET" {
if context.LastLevel() { if context.LastLevel() {
//Return all this security's prices //Return all this security's prices
var pl PriceList var pl models.PriceList
prices, err := GetPrices(context.Tx, security.SecurityId) prices, err := GetPrices(context.Tx, security.SecurityId)
if err != nil { if err != nil {
@ -190,7 +155,7 @@ func PriceHandler(r *http.Request, context *Context, user *models.User, security
return NewError(3 /*Invalid Request*/) return NewError(3 /*Invalid Request*/)
} }
if r.Method == "PUT" { if r.Method == "PUT" {
var price Price var price models.Price
if err := ReadJSON(r, &price); err != nil || price.PriceId != priceid { if err := ReadJSON(r, &price); err != nil || price.PriceId != priceid {
return NewError(3 /*Invalid Request*/) return NewError(3 /*Invalid Request*/)
} }

View File

@ -15,7 +15,7 @@ func luaRegisterPrices(L *lua.LState) {
L.SetField(mt, "__metatable", lua.LString("protected")) L.SetField(mt, "__metatable", lua.LString("protected"))
} }
func PriceToLua(L *lua.LState, price *Price) *lua.LUserData { func PriceToLua(L *lua.LState, price *models.Price) *lua.LUserData {
ud := L.NewUserData() ud := L.NewUserData()
ud.Value = price ud.Value = price
L.SetMetatable(ud, L.GetTypeMetatable(luaPriceTypeName)) L.SetMetatable(ud, L.GetTypeMetatable(luaPriceTypeName))
@ -23,9 +23,9 @@ func PriceToLua(L *lua.LState, price *Price) *lua.LUserData {
} }
// Checks whether the first lua argument is a *LUserData with *Price and returns this *Price. // Checks whether the first lua argument is a *LUserData with *Price and returns this *Price.
func luaCheckPrice(L *lua.LState, n int) *Price { func luaCheckPrice(L *lua.LState, n int) *models.Price {
ud := L.CheckUserData(n) ud := L.CheckUserData(n)
if price, ok := ud.Value.(*Price); ok { if price, ok := ud.Value.(*models.Price); ok {
return price return price
} }
L.ArgError(n, "price expected") L.ArgError(n, "price expected")

View File

@ -2,20 +2,21 @@ package handlers_test
import ( import (
"github.com/aclindsa/moneygo/internal/handlers" "github.com/aclindsa/moneygo/internal/handlers"
"github.com/aclindsa/moneygo/internal/models"
"net/http" "net/http"
"strconv" "strconv"
"testing" "testing"
"time" "time"
) )
func createPrice(client *http.Client, price *handlers.Price) (*handlers.Price, error) { func createPrice(client *http.Client, price *models.Price) (*models.Price, error) {
var p handlers.Price var p models.Price
err := create(client, price, &p, "/v1/securities/"+strconv.FormatInt(price.SecurityId, 10)+"/prices/") err := create(client, price, &p, "/v1/securities/"+strconv.FormatInt(price.SecurityId, 10)+"/prices/")
return &p, err return &p, err
} }
func getPrice(client *http.Client, priceid, securityid int64) (*handlers.Price, error) { func getPrice(client *http.Client, priceid, securityid int64) (*models.Price, error) {
var p handlers.Price var p models.Price
err := read(client, &p, "/v1/securities/"+strconv.FormatInt(securityid, 10)+"/prices/"+strconv.FormatInt(priceid, 10)) err := read(client, &p, "/v1/securities/"+strconv.FormatInt(securityid, 10)+"/prices/"+strconv.FormatInt(priceid, 10))
if err != nil { if err != nil {
return nil, err return nil, err
@ -23,8 +24,8 @@ func getPrice(client *http.Client, priceid, securityid int64) (*handlers.Price,
return &p, nil return &p, nil
} }
func getPrices(client *http.Client, securityid int64) (*handlers.PriceList, error) { func getPrices(client *http.Client, securityid int64) (*models.PriceList, error) {
var pl handlers.PriceList var pl models.PriceList
err := read(client, &pl, "/v1/securities/"+strconv.FormatInt(securityid, 10)+"/prices/") err := read(client, &pl, "/v1/securities/"+strconv.FormatInt(securityid, 10)+"/prices/")
if err != nil { if err != nil {
return nil, err return nil, err
@ -32,8 +33,8 @@ func getPrices(client *http.Client, securityid int64) (*handlers.PriceList, erro
return &pl, nil return &pl, nil
} }
func updatePrice(client *http.Client, price *handlers.Price) (*handlers.Price, error) { func updatePrice(client *http.Client, price *models.Price) (*models.Price, error) {
var p handlers.Price var p models.Price
err := update(client, price, &p, "/v1/securities/"+strconv.FormatInt(price.SecurityId, 10)+"/prices/"+strconv.FormatInt(price.PriceId, 10)) err := update(client, price, &p, "/v1/securities/"+strconv.FormatInt(price.SecurityId, 10)+"/prices/"+strconv.FormatInt(price.PriceId, 10))
if err != nil { if err != nil {
return nil, err return nil, err
@ -41,7 +42,7 @@ func updatePrice(client *http.Client, price *handlers.Price) (*handlers.Price, e
return &p, nil return &p, nil
} }
func deletePrice(client *http.Client, p *handlers.Price) error { func deletePrice(client *http.Client, p *models.Price) error {
err := remove(client, "/v1/securities/"+strconv.FormatInt(p.SecurityId, 10)+"/prices/"+strconv.FormatInt(p.PriceId, 10)) err := remove(client, "/v1/securities/"+strconv.FormatInt(p.SecurityId, 10)+"/prices/"+strconv.FormatInt(p.PriceId, 10))
if err != nil { if err != nil {
return err return err

View File

@ -38,7 +38,7 @@ type TestData struct {
users []User users []User
clients []*http.Client clients []*http.Client
securities []models.Security securities []models.Security
prices []handlers.Price prices []models.Price
accounts []models.Account // accounts must appear after their parents in this slice accounts []models.Account // accounts must appear after their parents in this slice
transactions []models.Transaction transactions []models.Transaction
reports []handlers.Report reports []handlers.Report
@ -209,7 +209,7 @@ var data = []TestData{
AlternateId: "978", AlternateId: "978",
}, },
}, },
prices: []handlers.Price{ prices: []models.Price{
{ {
SecurityId: 1, SecurityId: 1,
CurrencyId: 0, CurrencyId: 0,

41
internal/models/prices.go Normal file
View File

@ -0,0 +1,41 @@
package models
import (
"encoding/json"
"net/http"
"strings"
"time"
)
type Price struct {
PriceId int64
SecurityId int64
CurrencyId int64
Date time.Time
Value string // String representation of decimal price of Security in Currency units, suitable for passing to big.Rat.SetString()
RemoteId string // unique ID from source, for detecting duplicates
}
type PriceList struct {
Prices *[]*Price `json:"prices"`
}
func (p *Price) Read(json_str string) error {
dec := json.NewDecoder(strings.NewReader(json_str))
return dec.Decode(p)
}
func (p *Price) Write(w http.ResponseWriter) error {
enc := json.NewEncoder(w)
return enc.Encode(p)
}
func (pl *PriceList) Read(json_str string) error {
dec := json.NewDecoder(strings.NewReader(json_str))
return dec.Decode(pl)
}
func (pl *PriceList) Write(w http.ResponseWriter) error {
enc := json.NewEncoder(w)
return enc.Encode(pl)
}