-
Notifications
You must be signed in to change notification settings - Fork 0
/
envelopes.go
351 lines (308 loc) · 8.79 KB
/
envelopes.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
344
345
346
347
348
349
350
351
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"github.com/google/uuid"
)
var templFuncs = template.FuncMap{
"prettyDisplay": prettyDisplay,
"delta": computeDelta,
}
var templ = template.Must(template.New("").Funcs(templFuncs).ParseGlob("templates/*.html"))
func prettyDisplay(cents int) string {
return fmt.Sprintf("%.02f", float64(cents)/100)
}
func computeDelta(balance, target int) []string {
delta := balance - target
cls := "delta-ok"
if delta < 0 {
cls = "delta-warn"
}
return []string{cls, fmt.Sprintf(`%.02f`, float64(delta)/100)}
}
func handleDeleteRequest(db *DB, w http.ResponseWriter, r *http.Request) {
log.Printf(`delete: %v`, r.URL)
log.Printf(`id: %s`, r.FormValue("id"))
id, err := uuid.Parse(r.FormValue("id"))
if err != nil {
log.Printf(`update: can't parse ID: %s`, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
db.DeleteEnvelope(id)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func handleUpdateRequest(db *DB, w http.ResponseWriter, r *http.Request) {
log.Printf(`update: %v`, r.URL)
log.Printf(`name: %s`, r.FormValue("env-name"))
log.Printf(`target: %s`, r.FormValue("env-target"))
log.Printf(`monthtarget: %s`, r.FormValue("env-monthtarget"))
log.Printf(`return: %s`, r.FormValue("env-return"))
returnTo := "/"
if r.FormValue("env-return") != "" {
returnTo = "/details?id=" + r.FormValue("env-return")
}
id, err := uuid.Parse(r.FormValue("env-id"))
if err != nil {
log.Printf(`update: can't parse ID: %s`, err)
id = uuid.New()
}
name := r.FormValue("env-name")
newTarget := 0
if tgt, err := strconv.ParseFloat(r.FormValue("env-target"), 64); err == nil {
newTarget = int(tgt * 100)
}
newMonthTarget := 0
if monthtgt, err := strconv.ParseFloat(r.FormValue("env-monthtarget"), 64); err == nil {
newMonthTarget = int(monthtgt * 100)
}
if err = db.UpdateEnvelopeMeta(id, name, newTarget, newMonthTarget); err != nil {
log.Printf(`can't update envelope %s: %s`, id, err)
http.Redirect(w, r, returnTo, http.StatusSeeOther)
return
}
http.Redirect(w, r, returnTo, http.StatusSeeOther)
}
func handleDebug(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/plain")
w.Write([]byte("Hic sunt dracones\r\n\r\n"))
}
func handleDetail(db *DB, w http.ResponseWriter, r *http.Request) {
log.Printf(`handling detail for id %s`, r.FormValue("id"))
id, err := uuid.Parse(r.FormValue("id"))
if err != nil {
log.Printf(`detail: can't parse ID: %s`, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
e, events, err := db.EnvelopeWithHistory(id)
if err != nil {
log.Printf(`detail: can't get envelope and history from DB: %s`, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
events_rev := []Event{}
for idx := len(events) - 1; idx >= 0; idx-- {
events_rev = append(events_rev, events[idx])
}
param := struct {
Envelope *Envelope
Events []Event
}{e, events_rev}
if err := templ.ExecuteTemplate(w, "details.html", param); err != nil {
log.Printf(`error rendering details template: %s`, err)
}
}
func handleTx(db *DB, w http.ResponseWriter, r *http.Request) {
log.Printf(`tx for id %s`, r.FormValue(`id`))
id, err := uuid.Parse(r.FormValue("id"))
if err != nil {
log.Printf(`tx: can't parse ID: %s`, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
dir := r.FormValue(`dir`)
switch dir {
case `in`:
/* nothing */
case `out`:
/* nothing */
case `inout`:
/* nothing */
default:
dir = `inout`
}
env, err := db.Envelope(id)
if err != nil {
log.Printf(`tx: can't get envelope %s: %s`, r.FormValue(`id`), err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
if r.Method != "POST" {
switch dir {
case `in`:
fallthrough
case `out`:
log.Printf(`tx %s`, dir)
params := struct {
Envelope *Envelope
Direction string
}{
Envelope: env,
Direction: dir,
}
if err := templ.ExecuteTemplate(w, "transfer_in.html", params); err != nil {
log.Printf(`error rendering details template: %s`, err)
}
default:
params := struct {
AllEnvelopes []*Envelope
This *Envelope
}{
AllEnvelopes: []*Envelope{},
This: env,
}
for _, e := range db.AllEnvelopes() {
if e.Id != env.Id {
params.AllEnvelopes = append(params.AllEnvelopes, e)
}
}
if err := templ.ExecuteTemplate(w, "transfer.html", params); err != nil {
log.Printf(`error rendering details template: %s`, err)
}
log.Printf(`tx inout`)
}
} else {
log.Printf(`updating env %s`, r.FormValue(`id`))
log.Printf(` amount: %s`, r.FormValue(`amount`))
amount, err := strconv.ParseFloat(r.FormValue(`amount`), 64)
if err != nil {
log.Printf(`can't parse %s: %s`, r.FormValue(`amount`), err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
switch dir {
case `in`:
if err = db.UpdateEnvelopeBalance(id, int(amount*100), r.FormValue(`comment`)); err != nil {
log.Printf(`can't update balance: %s`, err)
}
case `out`:
if err = db.UpdateEnvelopeBalance(id, -int(amount*100), r.FormValue(`comment`)); err != nil {
log.Printf(`can't update balance: %s`, err)
}
default:
destId, err := uuid.Parse(r.FormValue("destination"))
if err != nil {
log.Printf(`tx: can't parse ID: %s`, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
dest, err := db.Envelope(destId)
if err != nil {
log.Printf(`can't get destination %s: %s`, destId, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
src, err := db.Envelope(id)
if err != nil {
log.Printf(`can't get source %s: %s`, destId, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
srccmmt := fmt.Sprintf("From %s", src.Name)
destcmmt := fmt.Sprintf(`To %s`, dest.Name)
if r.FormValue(`comment`) != "" {
cmmt := fmt.Sprintf(": %s", r.FormValue(`comment`))
srccmmt += cmmt
destcmmt += cmmt
}
if err = db.UpdateEnvelopeBalance(destId, int(amount*100), srccmmt); err != nil {
log.Printf(`can't update balance: %s`, err)
} else if err = db.UpdateEnvelopeBalance(id, -int(amount*100), destcmmt); err != nil {
log.Printf(`can't update balance: %s`, err)
}
http.Redirect(w, r, fmt.Sprintf("/details?id=%s", destId), http.StatusSeeOther)
return
}
http.Redirect(w, r, fmt.Sprintf("/details?id=%s", r.FormValue(`id`)), http.StatusSeeOther)
return
}
}
func handleSpread(db *DB, w http.ResponseWriter, r *http.Request) {
log.Printf(`handling spread for id %s`, r.FormValue("id"))
id, err := uuid.Parse(r.FormValue("id"))
if err != nil {
log.Printf(`spread: can't parse ID: %s`, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
if err := db.Spread(id); err != nil {
log.Printf(`something went wrong with the spread`, err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func handleRequest(db *DB, w http.ResponseWriter, r *http.Request) {
if r.URL.String() != "/" {
log.Printf(`ignoring request for %s`, r.URL)
http.NotFound(w, r)
return
}
log.Printf(`request: %v`, r.URL)
w.Header().Add("Content-Type", "text/html")
es := db.AllEnvelopes()
delta := int(0)
balance := int(0)
monthtarget := int(0)
for i := range es {
delta += es[i].Balance - es[i].Target
balance += es[i].Balance
monthtarget += es[i].MonthTarget
}
dcls := "delta-ok"
if delta < 0 {
dcls = "delta-warn"
}
param := struct {
Envelopes []*Envelope
TotalDelta struct {
Cls string
Val int
}
TotalBalance int
MonthTarget int
}{
es,
struct {
Cls string
Val int
}{dcls, delta},
balance,
monthtarget,
}
if err := templ.ExecuteTemplate(w, "index.html", param); err != nil {
log.Printf(`error rendering overview template: %s`, err)
}
}
func main() {
log.Printf("Here we go")
db, err := OpenDB()
if err != nil {
log.Fatal(err)
}
defer func() {
if err := db.Close(); err != nil {
log.Printf(`error while saving DB: %s`, err)
}
}()
http.Handle("/static/", http.FileServer(http.Dir(".")))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handleRequest(db, w, r)
})
http.HandleFunc("/update", func(w http.ResponseWriter, r *http.Request) {
handleUpdateRequest(db, w, r)
})
http.HandleFunc("/delete", func(w http.ResponseWriter, r *http.Request) {
handleDeleteRequest(db, w, r)
})
http.HandleFunc("/details", func(w http.ResponseWriter, r *http.Request) {
handleDetail(db, w, r)
})
http.HandleFunc("/spread", func(w http.ResponseWriter, r *http.Request) {
handleSpread(db, w, r)
})
http.HandleFunc("/tx", func(w http.ResponseWriter, r *http.Request) {
handleTx(db, w, r)
})
http.HandleFunc("/debug", func(w http.ResponseWriter, r *http.Request) {
handleDebug(w, r)
})
err = http.ListenAndServe("127.0.0.1:8081", nil)
if err != nil {
log.Printf(`HTTP died: %s`, err)
}
}