-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
343 lines (297 loc) · 9.12 KB
/
main.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package main
//all made to work even if there is no db
import (
"context"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
func initdb(ctx *context.Context, pool *pgxpool.Pool, insertData string) error {
var rerr error
fmt.Println("Creating table if not exists")
_, cerr := pool.Exec(*ctx, createTable)
if cerr != nil {
rerr = fmt.Errorf("db query failed: %v", cerr)
} else {
var count int
cerr = pool.QueryRow(*ctx, `SELECT count(*) FROM stock; `).Scan(&count)
if cerr != nil {
rerr = fmt.Errorf("select count failed: %v", cerr)
} else {
fmt.Println(count, "rows in table")
if count == 0 {
_, cerr := pool.Exec(context.Background(), insertData)
if cerr != nil {
rerr = fmt.Errorf("insert random data query failed: %v", cerr)
} else {
fmt.Println("Inserted random data")
}
}
}
}
return rerr
}
func main() {
fmt.Println("v 1.1")
flag.Parse()
/*
docker container run --name stockdb -p 5432:5432 -e POSTGRES_USER=root -e POSTGRES_PASSWORD=notsecure -e POSTGRES_DB=stock -d postgres
set POSTGRES_SERVER=localhost
set POSTGRES_USER=root
set POSTGRES_PASSWORD=notsecure
set POSTGRES_DB=stock
set POSTGRES_PORT=5432
docker container run --name stockfrontend -p 14000:8080 -e POSTGRES_SERVER=stockdb -e POSTGRES_USER=root -e POSTGRES_PASSWORD=notsecure -e POSTGRES_PORT=5432 -e POSTGRES_DB=stock -d tdewin/stock-demo
*/
//use ?adminkey=unlock to do editing
adminkey := "unlock"
testenvadmin := os.Getenv("ADMINKEY")
if testenvadmin != "" {
adminkey = testenvadmin
}
//data that is insert when calling init
insertData := defaultInsertData
content, err := ioutil.ReadFile("/var/stockdb/initinsert.psql")
if err == nil {
insertData = string(content)
} else {
fmt.Println("Loaded default insert query")
}
server := os.Getenv("POSTGRES_SERVER")
username := os.Getenv("POSTGRES_USER")
password := os.Getenv("POSTGRES_PASSWORD")
dbname := os.Getenv("POSTGRES_DB")
port := os.Getenv("POSTGRES_PORT")
if port == "" {
port = "5432"
}
dburl := fmt.Sprintf("postgres://%s:%s@%s:%s/%s", username, password, server, port, dbname)
fmt.Printf("DB string postgres://%s:***@%s:%s/%s\n", username, server, port, dbname)
config, err := pgxpool.ParseConfig(dburl)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to parse config: %v\n", err)
}
//lazy loading so can start with errors
config.LazyConnect = true
pool, err := pgxpool.ConnectConfig(context.Background(), config)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to lazy load db: %v\n", err)
}
defer pool.Close()
tmpl, terr := template.New("msg").Parse(msghtml)
//panic should never happen but okay
if terr != nil {
panic(terr)
}
tmplproduct, terr := template.New("productpage").Parse(mainhtml)
//panic should never happen but okay
if terr != nil {
panic(terr)
}
//when first deploying, run this to create the table
http.HandleFunc("/init", func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
err = initdb(&ctx, pool, insertData)
if err == nil {
msg := NewMessage("Init OK")
terr = tmpl.Execute(w, msg)
if terr != nil {
fmt.Fprint(w, "Internal Error, could not render")
}
} else {
w.WriteHeader(http.StatusInternalServerError)
terr = tmpl.Execute(w, NewError(err.Error()))
if terr != nil {
fmt.Fprint(w, "Internal Error, could not render")
}
}
})
//admin function
http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
r.ParseForm()
transactions := &pgx.Batch{}
deleteids := []string{}
for k, v := range r.PostForm {
test := strings.Split(k, "-")
if len(test) == 2 && len(v) > 0 {
if test[0] == "setstock" {
transactions.Queue(`UPDATE stock SET amount = $2 WHERE id=$1;`, test[1], v[0])
} else if test[0] == "setprice" {
transactions.Queue(`UPDATE stock SET price = $2 WHERE id=$1;`, test[1], v[0])
} else if test[0] == "setproduct" {
transactions.Queue(`UPDATE stock SET product = $2 WHERE id=$1;`, test[1], v[0])
} else if test[0] == "setunit" {
transactions.Queue(`UPDATE stock SET unit = $2 WHERE id=$1;`, test[1], v[0])
} else if test[0] == "setkeep" && v[0] == "delete" {
deleteids = append(deleteids, test[1])
}
}
//fmt.Println(k, v)
}
for _, delid := range deleteids {
transactions.Queue(`DELETE FROM stock WHERE id=$1;`, delid)
}
br := pool.SendBatch(ctx, transactions)
_, err := br.Exec()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
terr = tmpl.Execute(w, NewError(err.Error()))
if terr != nil {
fmt.Fprint(w, "Internal Error, could not render")
}
} else {
defer br.Close()
msg := NewMessage("Admin set executed")
msg.Refresh = 2
msg.Redirect = "./"
terr = tmpl.Execute(w, msg)
if terr != nil {
fmt.Fprint(w, "Internal Error, could not render")
}
}
})
//buying items, lowering the stock
http.HandleFunc("/buy", func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
r.ParseForm()
idindex := []string{}
buymap := make(map[string]*BuyTransaction)
for k, v := range r.PostForm {
test := strings.Split(k, "-")
if len(test) == 2 && test[0] == "qty" {
buyid := test[1]
qty, _ := strconv.ParseFloat(v[0], 64)
if qty > 0 {
idindex = append(idindex, buyid)
buymap[buyid] = &BuyTransaction{qty, 0, 0, "", false, 0, 0}
}
}
}
rows, err := pool.Query(ctx, `SELECT id,product,unit,amount,price FROM stock WHERE id = ANY ($1);`, idindex)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
terr = tmpl.Execute(w, NewError(err.Error()))
if terr != nil {
fmt.Fprint(w, "Internal Error, could not render")
}
} else {
defer rows.Close()
processedanything := false
total := 0.0
for rows.Next() {
var id int
var product, unit string
var amount, price float64
err := rows.Scan(&id, &product, &unit, &amount, &price)
if err != nil {
fmt.Println(err)
} else {
strid := fmt.Sprintf("%d", id)
processedanything = true
buymap[strid].Product = product
buymap[strid].StockCalculated = true
buymap[strid].Price = price
if buymap[strid].Request > amount {
buymap[strid].Bought = amount
buymap[strid].Remaining = 0
} else {
buymap[strid].Bought = buymap[strid].Request
buymap[strid].Remaining = amount - buymap[strid].Request
}
buymap[strid].Sum = (buymap[strid].Bought) * price
total = total + buymap[strid].Sum
}
}
if processedanything {
transactions := &pgx.Batch{}
for buyid, transaction := range buymap {
if transaction.StockCalculated {
transactions.Queue(`UPDATE stock SET amount = $2 WHERE id=$1;`, buyid, transaction.Remaining)
}
}
br := pool.SendBatch(ctx, transactions)
_, err := br.Exec()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
terr = tmpl.Execute(w, NewError(err.Error()))
if terr != nil {
fmt.Fprint(w, "Internal Error, could not render")
}
} else {
defer br.Close()
for k, transaction := range buymap {
println(k, transaction.Bought, transaction.Product)
}
msg := NewMessage("Thanks for buying")
msg.BuyTable = &buymap
msg.BuySum = total
terr = tmpl.Execute(w, msg)
if terr != nil {
fmt.Fprint(w, "Internal Error, could not render")
}
}
} else {
w.WriteHeader(http.StatusInternalServerError)
errmsg := NewError("We were not able to find any of your products or you didnt buy anything")
errmsg.Redirect = "./"
errmsg.Refresh = 3
terr = tmpl.Execute(w, errmsg)
if terr != nil {
fmt.Fprint(w, "Internal Error, could not render")
}
}
}
})
//main function
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
isAdmin := false
r.ParseForm()
testadmin := r.Form.Get("adminkey")
if testadmin == adminkey {
isAdmin = true
fmt.Println("Admin mode unlocked")
}
rows, err := pool.Query(ctx, `SELECT id, product, unit, amount, price FROM stock ORDER BY id`)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
terr = tmpl.Execute(w, NewError(err.Error()))
if terr != nil {
fmt.Fprint(w, "Internal Error, could not render")
}
} else {
defer rows.Close()
allstock := []Stock{}
for rows.Next() {
var id int
var product, unit string
var amount, price float64
err := rows.Scan(&id, &product, &unit, &amount, &price)
if err != nil {
fmt.Println(err)
}
allstock = append(allstock, Stock{id, product, fmt.Sprintf("%.2f %s", amount, unit), amount, unit, price})
}
terr = tmplproduct.Execute(w, StockMessage{allstock, isAdmin})
if terr != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "Internal Error, could not render")
}
}
})
log.Fatal(http.ListenAndServe(":8080", nil))
}