-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
452 lines (357 loc) · 11.6 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package main
import (
"fmt"
"net/http"
"html/template"
"time"
"strings"
"strconv"
"sort"
"path/filepath"
"os"
"encoding/json"
"io/ioutil"
)
type Document struct {
PrevDebt map[string]float64
Categories []string
Payers []string
Currencies []string
LastUsedCat string
LastUsedPayer string
LastUsedCurr string
LastUsedDate time.Time
MonthRecs []MonthRec
}
var (
tpl = template.Must(template.ParseFiles("index.html"))
inputFileRead = false
)
// *******************************
// Entry point from loaded or empty entries
// *******************************
func (doc *Document) indexHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// TODO this should't be called every time, they should always be sorted
doc.sortMonthsByDate()
// TODO don't recalculate stats on just opening a file
doc.calcAllStats()
tpl.Execute(w, doc)
}
}
// *******************************
// Get the active month and calculate its exchange rate
// *******************************
func (doc *Document) calcExchRate() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
for index, month := range doc.MonthRecs {
if month.ActiveGroup {
doc.MonthRecs[index].AvgExchRates = month.ExchRatesCalcs()
break
}
}
doc.calcAllStats()
tpl.Execute(w, doc)
}
}
// *******************************
// Create an empty Document
// *******************************
func newDocument() *Document {
doc := &Document{}
// Default values for Document
doc.Payers = append(doc.Payers, "All")
doc.Currencies = append(doc.Currencies, "EUR")
doc.LastUsedDate = time.Now()
return doc
}
// *******************************
// Add new category to the list
// *******************************
func (doc *Document) addCategory() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
newCategory := strings.TrimSpace(r.FormValue("newCategory"))
doc.Categories = append(doc.Categories, newCategory)
tpl.Execute(w, doc)
}
}
// *******************************
// Prepend string with fewer allocations,
// compared to using compose literal append([]string{1}, x...)
// *******************************
func prependStr(x []string, y string) []string {
x = append(x, "")
copy(x[1:], x)
x[0] = y
return x
}
// *******************************
// Add new payer to the list
// *******************************
func (doc *Document) addPayer() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
newPayer := strings.TrimSpace(r.FormValue("newPayer"))
// Put new payer on top
doc.Payers = prependStr(doc.Payers, newPayer)
tpl.Execute(w, doc)
}
}
// *******************************
// Add new currency to the list
// *******************************
func (doc *Document) addCurrency() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
newCurrency := strings.TrimSpace(r.FormValue("newCurrency"))
// TODO check that length is 3 and capital letters
doc.Currencies = append(doc.Currencies, newCurrency)
tpl.Execute(w, doc)
}
}
// *******************************
// Calculate all months statistics
// *******************************
func (doc *Document) calcAllStats() {
// Recalculate month statistics
// Months sorted by date is assumed
for index, month := range doc.MonthRecs {
// TODO Introduce checks to not calculate this every time
// TODO calculate only from current month, without the previous ones
if index == 0 {
doc.MonthRecs[index].Stats = month.calcStats(nil, doc.PrevDebt)
} else {
// TODO probably doesn't need a pointer to all the data
doc.MonthRecs[index].Stats = month.calcStats(&(doc.MonthRecs[index - 1]), doc.PrevDebt)
}
}
}
// *******************************
// Add previous document debt data
// This is a manual step to be introduced by the user
// *******************************
func (doc *Document) addPreviousDebts() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
prevName := strings.TrimSpace(r.FormValue("prevDebtName"))
prevAmount := strings.TrimSpace(r.FormValue("prevDebtAmount"))
if doc.PrevDebt == nil {
doc.PrevDebt = map[string]float64{}
}
if convQuantity, err := strconv.ParseFloat(prevAmount, 64); err == nil {
doc.PrevDebt[prevName] = convQuantity
}
doc.calcAllStats()
tpl.Execute(w, doc)
}
}
// *******************************
// Helper function to check if month and year are the same for two dates
// *******************************
func isSameMonthYear(a, b time.Time) bool {
aM := int(a.Month())
bM := int(b.Month())
if (aM == bM) && (a.Year() == b.Year()) {
return true
} else {
return false
}
}
// *******************************
// Add new entry
// *******************************
func (doc *Document) addEntry() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Add entry from form
recDate, err := time.Parse("2006-01-02", strings.TrimSpace(r.FormValue("date")))
if err != nil {
fmt.Println(err)
recDate = time.Time{}
}
r.ParseForm()
entry := EntryRec{
Date: recDate,
Category: r.FormValue("category"),
PersonName: r.FormValue("who"),
Currency: r.FormValue("currency"),
Amount: 0.0,
Comment: r.FormValue("comment"),
}
if convAmount, err := strconv.ParseFloat(r.FormValue("quantity"), 64); err == nil {
entry.Amount = convAmount
} else {
fmt.Println("There was an error processing the quantity input: not a float64")
}
// Find correct month to insert to
for index, month := range doc.MonthRecs {
if isSameMonthYear(recDate, month.StartDate) {
if entry.Currency == "EUR" {
entry.ExchRate = 1.0
} else {
entry.ExchRate = 0.0
}
// Add entry to the list and sort
doc.MonthRecs[index].EntryRecords = append(doc.MonthRecs[index].EntryRecords, entry)
doc.MonthRecs[index].sortRecordsByDate()
break
}
// Check for last item
if index + 1 == len(doc.MonthRecs) {
fmt.Printf("Date %s did not fit in any current month", recDate)
}
}
doc.calcAllStats()
doc.updateLastUsed(entry.Category, entry.PersonName, entry.Currency, entry.Date)
tpl.Execute(w, doc)
}
}
// *******************************
// Change active month to selected month
// *******************************
func (doc *Document) updateLastUsed(lastCat, lastPayer, lastCurr string, lastDate time.Time) {
doc.LastUsedCat = lastCat
doc.LastUsedPayer = lastPayer
doc.LastUsedCurr = lastCurr
doc.LastUsedDate = lastDate
}
// *******************************
// Change active month to selected month
// *******************************
func (doc *Document) changeToSheet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
selectedSheet := r.FormValue("changeSheet")
doc.markMonthAsActive(selectedSheet)
tpl.Execute(w, doc)
}
}
// *******************************
// Sort months by ascending date within a document
// *******************************
func (doc *Document) sortMonthsByDate() {
sort.SliceStable(doc.MonthRecs, func(i, j int) bool {
return doc.MonthRecs[i].StartDate.Before(doc.MonthRecs[j].StartDate)
})
}
// *******************************
// Write changes into a JSON file
// *******************************
func (doc *Document) writeJson(fileName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
b, err := json.MarshalIndent(doc, "", " ")
if err != nil {
fmt.Println(err)
return
}
t := time.Now()
fmt.Printf("Saving current data at %s in file named %s\n", t.Format("15:04:05"), fileName)
_ = ioutil.WriteFile(fileName, b, 0644)
tpl.Execute(w, doc)
}
}
// *******************************
// Add sheet given a name
// *******************************
func (doc *Document) markMonthAsActive(name string) {
for index, month := range doc.MonthRecs {
if name != month.GroupName {
month.ActiveGroup = false
doc.MonthRecs[index] = month
} else {
month.ActiveGroup = true
doc.MonthRecs[index] = month
}
}
}
// *******************************
// Add sheet given a name
// *******************************
func (doc *Document) addSheet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer tpl.Execute(w, doc)
monthRec := newMonthRec()
inputName := strings.TrimSpace(r.FormValue("sheetName"))
// Check if name was already used
for _, month := range doc.MonthRecs {
if inputName == month.GroupName {
fmt.Printf("Name %s was already used.", inputName)
return
}
}
monthRec.GroupName = inputName
// If no input is provided, use date
if monthRec.GroupName == "" {
selectedMonthYear := r.FormValue("monthYearSheet")
// Check if name was already used
for _, month := range doc.MonthRecs {
if selectedMonthYear == month.GroupName {
fmt.Sprintf("Name %s was already used.", inputName)
return
}
}
monthRec.GroupName = selectedMonthYear
}
// Create starting date for new month
monthYearSlice := strings.Split(r.FormValue("monthYearSheet"), "-")
sheetYear, err := strconv.Atoi(monthYearSlice[0])
if err != nil {
fmt.Println(err)
return
}
monthNum, err := strconv.Atoi(monthYearSlice[1])
if err != nil {
fmt.Println(err)
return
}
firstDayMonth := time.Date(sheetYear, time.Month(monthNum), 1, 0, 0, 0, 0, time.Now().Location())
monthRec.StartDate = firstDayMonth
// Mark new month as active
doc.markMonthAsActive(monthRec.GroupName)
// Add it do the document and sort months
doc.MonthRecs = append(doc.MonthRecs, *monthRec)
doc.sortMonthsByDate()
}
}
func main() {
port := "3000"
document := newDocument()
// Check input file type
if inputFileRead == false && len(os.Args) == 2 {
filePath := os.Args[1]
extensionType := filepath.Ext(filePath)
if extensionType == ".json" {
fmt.Println("Reading input file: filePath")
jsonFile, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
json.Unmarshal(byteValue, &document)
} else {
fmt.Println("Input file type not recognized")
}
} else if len(os.Args) == 1 {
fmt.Println("No input file: creating empty record")
}
fmt.Println("Listening on localhost:"+port)
// Serve assets folder
fs := http.FileServer(http.Dir("assets"))
mux := http.NewServeMux()
mux.Handle("/assets/", http.StripPrefix("/assets/", fs))
if len(os.Args) == 2 {
mux.HandleFunc("/writeJSON", document.writeJson(os.Args[1]))
} else {
currentTime := time.Now()
fileName := "apunta" + currentTime.Format("2006-01-02_150405.json")
mux.HandleFunc("/writeJSON", document.writeJson(fileName))
}
mux.HandleFunc("/addCategory", document.addCategory())
mux.HandleFunc("/addWho", document.addPayer())
mux.HandleFunc("/addCurrency", document.addCurrency())
mux.HandleFunc("/inputPreviousDebts", document.addPreviousDebts())
mux.HandleFunc("/changeSheet", document.changeToSheet())
mux.HandleFunc("/addSheet", document.addSheet())
mux.HandleFunc("/calcExchRateMonth", document.calcExchRate())
mux.HandleFunc("/addEntry", document.addEntry())
mux.HandleFunc("/", document.indexHandler())
http.ListenAndServe(":"+port, mux)
fmt.Println("Listening on localhost:"+port)
}