-
Notifications
You must be signed in to change notification settings - Fork 0
/
portfolio.go
289 lines (248 loc) · 7.63 KB
/
portfolio.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package handlers
import (
"database/sql"
"fmt"
"net/http"
"reflect"
"strconv"
"time"
"github.com/fercevik729/STLKER/octopus/data"
"github.com/gorilla/mux"
)
type Username struct{}
type IsAdmin struct{}
type NamePair struct {
Name string
Username string
}
const databasePath string = "./database/stlker.db"
type ResponseMessage struct {
Msg string `json:"Message"`
}
type STLKERModel struct {
ID uint `gorm:"primaryKey" json:"-"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt sql.NullTime `json:"-" gorm:"index"`
}
// A Portfolio is a GORM model that is intended to mirror the structure
// of a simple portfolio
type Portfolio struct {
STLKERModel
// Name is the name of the portfolio
Name string `json:"Name"`
Username string `json:"Username"`
// Stocks is a slice of Security structs
Securities []*Security `json:"Securities" gorm:"foreignKey:PortfolioID"`
}
type Profits struct {
Name string `json:"Portfolio Name"`
OriginalValue float64 `json:"Original Value"`
NewValue float64 `json:"Current Value"`
NetGain float64 `json:"Net Gain"`
NetChange string `json:"Net Change"`
Moves []*Security `json:"Securities"`
}
func (p *Portfolio) calcProfits() (*Profits, error) {
original := 0.
new := 0.
// Iterate over securities and calculate change and percent change
for _, sec := range p.Securities {
original += sec.BoughtPrice * sec.Shares
new += sec.CurrPrice * sec.Shares
}
// Round original and new
var err error
original, err = strconv.ParseFloat(fmt.Sprintf("%.2f", original), 64)
if err != nil {
return nil, err
}
new, err = strconv.ParseFloat(fmt.Sprintf("%.2f", new), 64)
if err != nil {
return nil, err
}
// Compute and round change and profits
percChange := fmt.Sprintf("%.2f%%", (new-original)/original*100)
netGain, err := strconv.ParseFloat(fmt.Sprintf("%.2f", (new-original)), 64)
if err != nil {
return nil, err
}
// Return profits
return &Profits{
Name: p.Name,
OriginalValue: original,
NewValue: new,
Moves: p.Securities,
NetGain: netGain,
NetChange: percChange,
}, nil
}
func (c *ControlHandler) CreatePortfolio(w http.ResponseWriter, r *http.Request) {
// Retrieve the portfolio from the request body
reqPort := Portfolio{}
data.FromJSON(&reqPort, r.Body)
// Validate the portfolio
ok, msg := validatePortfolio(&reqPort)
if !ok {
c.logHTTPError(w, msg, http.StatusBadRequest)
return
}
// Set username of the requested portfolio
username := retrieveUsername(r)
reqPort.Username = username
// Open sqlite db connection
db, err := newGormDBConn(databasePath)
if err != nil {
c.logHTTPError(w, "Couldn't connect to database", http.StatusInternalServerError)
return
}
// Migrate schema
db.AutoMigrate(&Portfolio{}, &Security{})
sqlPort := Portfolio{}
// Check if a portfolio with that name for that user already exists
db.Debug().Where("name=? AND username=?", reqPort.Name, username).First(&sqlPort)
// If a portfolio with that name does exist return an error
if !reflect.DeepEqual(&sqlPort, &Portfolio{}) {
c.logHTTPError(w, "A portfolio with that name already exists", http.StatusBadRequest)
return
}
// Retrieve prices for all stocks in the portfolio
c.l.Println("[INFO] Retrieving updated stock prices")
c.updatePrices(&reqPort)
// Create portfolio entry
db.Debug().Create(&reqPort)
msg = fmt.Sprintf("Created portfolio named %s for %s", reqPort.Name, reqPort.Username)
c.l.Printf("[DEBUG] %s", msg)
// Write to response body
w.WriteHeader(http.StatusCreated)
data.ToJSON(&ResponseMessage{
Msg: msg,
}, w)
}
func (c *ControlHandler) GetAll(w http.ResponseWriter, r *http.Request) {
username := retrieveUsername(r)
isAdmin := retrieveAdmin(r)
var ports []Portfolio
// Open database
db, err := newGormDBConn(databasePath)
if err != nil {
c.logHTTPError(w, "Couldn't connect to database", http.StatusInternalServerError)
return
}
// If the username is admin, retrieve all portfolio names and associated usernames
// Then return in an ordered format
if isAdmin {
var (
usernames []string
portnames []string
)
if err != nil {
c.logHTTPError(w, "Couldn't open user's database", http.StatusInternalServerError)
return
}
// Get all usernames except for admin
db.Model(&User{}).Not("username=?", "admin").Select("username").Find(&usernames)
// Create a map of usernames to slices of portfolio names
table := make(map[string][]string)
// Iterate ove all users
for _, user := range usernames {
db.Table("portfolios").Where("username=?", user).Select("name").Find(&portnames)
table[user] = portnames
}
// Return the table in json format
data.ToJSON(table, w)
// Cache it as well
err = c.setCache(r, table)
if err != nil {
c.logHTTPError(w, "Couldn't set value into cache", http.StatusInternalServerError)
return
}
}
// Otherwise retrieve all portfolio data for a user
db.Where("username=?", username).Preload("Securities").Find(&ports)
profits := make([]*Profits, 0)
for i := range ports {
prof, err := ports[i].calcProfits()
if err != nil {
c.logHTTPError(w, fmt.Sprintf("Couldn't calculate profits for %s", ports[i].Name), http.StatusInternalServerError)
return
}
profits = append(profits, prof)
}
c.setCache(r, &profits)
data.ToJSON(profits, w)
}
func (c *ControlHandler) GetPortfolio(w http.ResponseWriter, r *http.Request) {
// Retrieve portfolio name parameter and username
name := mux.Vars(r)["name"]
username := retrieveUsername(r)
// Open sqlite db connection
db, err := newGormDBConn(databasePath)
if err != nil {
c.logHTTPError(w, "Couldn't connect to database", http.StatusInternalServerError)
return
}
var port Portfolio
// Check if a portfolio with that name for that user can be found
db.Where("name=?", name).Where("username=?", username).Preload("Securities").Find(&port)
// Check if any results were found
if port.ID == 0 {
c.logHTTPError(w, fmt.Sprintf("no results found with name %s, and user %s", name, username), http.StatusBadRequest)
return
}
// Update the database entry with the new prices
err = c.updateDB(&port)
if err != nil {
c.logHTTPError(w, err.Error(), http.StatusBadRequest)
return
}
// Calculate the profits
profits, err := port.calcProfits()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
err = c.setCache(r, profits)
if err != nil {
c.logHTTPError(w, "Couldn't set value into cache", http.StatusInternalServerError)
}
data.ToJSON(profits, w)
}
func (c *ControlHandler) UpdatePortfolio(w http.ResponseWriter, r *http.Request) {
// Get variables
username := retrieveUsername(r)
// Retrieve the portfolio from the request body
reqPort := Portfolio{}
data.FromJSON(&reqPort, r.Body)
reqPort.Username = username
name := reqPort.Name
// Check if request payload is empty
if reflect.DeepEqual(reqPort, Portfolio{}) {
c.logHTTPError(w, "Bad request payload", http.StatusBadRequest)
return
}
// Call helper method
err := replacePortfolio(name, username, &reqPort)
if err != nil {
c.logHTTPError(w, err.Error(), http.StatusBadRequest)
return
}
// Send response message
msg := fmt.Sprintf("Updated portfolio with name %s", name)
data.ToJSON(&ResponseMessage{
Msg: msg,
}, w)
}
func (c *ControlHandler) DeletePortfolio(w http.ResponseWriter, r *http.Request) {
name := mux.Vars(r)["name"]
username := retrieveUsername(r)
// Delete portfolio and all child securities
err := replacePortfolio(name, username, nil)
if err != nil {
c.logHTTPError(w, err.Error(), http.StatusBadRequest)
return
}
data.ToJSON(&ResponseMessage{
Msg: fmt.Sprintf("Deleted portfolio %s", name),
}, w)
}