-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
516 lines (491 loc) · 10.3 KB
/
transaction.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
package main
import (
"fmt"
"log"
"strings"
"time"
. "github.com/logrusorgru/aurora"
"github.com/mgutz/str"
"github.com/satori/go.uuid"
)
const (
TS_UNSET = ""
TS_PLANNED = "P"
TS_SCHEDULED = "S" // E.g.: transações futuras já programadas
TS_ON_GOING = "G"
TS_FINISHED = "F"
TS_CANCELED = "C"
)
type Transaction struct {
Id string
Name string
Desc string
RefTimeSpan TimePeriod
Parts []TransactionPart
Items []TransactionItem
Tags map[string]bool
}
func NewTransaction() *Transaction {
tr := Transaction{}
tr.Init()
return &tr
}
func (tr Transaction) MultilineString() string {
s := ""
s += fmt.Sprintf("%s %s\n", Bold(" Id:"), tr.Id)
s += fmt.Sprintf("%s %s\n", Bold(" Name:"), tr.Name)
s += fmt.Sprintf("%s %s\n", Bold(" Desc:"), tr.Desc)
s += fmt.Sprintf("%s %s\n", Bold("Period:"), tr.RefTimeSpan.String())
s += fmt.Sprintf("------------------------------ %s -------------------------------\n", Bold("Transaction Parts"))
for _, tp := range tr.Parts {
s += tp.ANSIString() + "\n"
}
s += fmt.Sprintf("------------------------------ %s -------------------------------\n", Bold("Transaction Items"))
for _, ti := range tr.Items {
s += ti.ANSIString() + "\n"
}
return s
}
func (tr *Transaction) Init() {
if tr.Id == "" {
tr.Id = uuid.NewV4().String()
}
if tr.Parts == nil {
tr.Parts = make([]TransactionPart, 0)
}
if tr.Items == nil {
tr.Items = make([]TransactionItem, 0)
}
if tr.Tags == nil {
tr.Tags = make(map[string]bool)
}
}
func (tr *Transaction) Load(id string) error {
var start, end int64
// Load basic info
tr.Init()
err := DB.QueryRow("SELECT `Id`, `Name`, `Desc`, `RefStart`, `RefEnd` FROM `Transaction` WHERE `Id` = ?", id).
Scan(&tr.Id, &tr.Name, &tr.Desc, &start, &end)
tr.RefTimeSpan.Start = time.Unix(start, 0)
tr.RefTimeSpan.End = time.Unix(end, 0)
if err != nil {
return err
}
err = tr.load_parts()
if err != nil {
return err
}
err = tr.load_items()
if err != nil {
return err
}
return nil
}
func (tr *Transaction) load_parts() error {
rows, err := DB.Query("SELECT `Id` FROM `TransactionPart` WHERE `TransactionId` = ?", tr.Id)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
tp := TransactionPart{}
id := ""
err := rows.Scan(&id)
if err != nil {
log.Fatal(err)
}
err = tp.Load(id)
if err != nil {
log.Fatal(err)
}
tr.Parts = append(tr.Parts, tp)
}
return nil
}
func (tr *Transaction) load_items() error {
rows, err := DB.Query("SELECT `Id` FROM `TransactionItem` WHERE `TransactionId` = ?", tr.Id)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
ti := TransactionItem{}
id := ""
err := rows.Scan(&id)
if err != nil {
log.Fatal(err)
}
err = ti.Load(id)
if err != nil {
log.Fatal(err)
}
tr.Items = append(tr.Items, ti)
}
return nil
}
func (tr Transaction) Del(id string) error {
tr.Init()
_, err := DB.Exec("DELETE FROM `Transaction` WHERE `Id` = ?", id)
if err != nil {
return err
}
_, err = DB.Exec("DELETE FROM `TransactionPart` WHERE `TransactionId` = ?", id)
if err != nil {
return err
}
_, err = DB.Exec("DELETE FROM `TransactionItem` WHERE `TransactionId` = ?", id)
if err != nil {
return err
}
return nil
}
func (tr *Transaction) Save() error {
tr.Init()
_, err := DB.Exec("INSERT INTO `Transaction` (`Id`, `Name`, `Desc`, `RefStart`, `RefEnd`) VALUES (?, ?, ?, ?, ?)",
tr.Id,
tr.Name,
tr.Desc,
tr.RefTimeSpan.Start.Unix(),
tr.RefTimeSpan.End.Unix())
if err != nil {
return err
}
return tr.Update()
}
func (tr *Transaction) Update() error {
tr.Init()
_, err := DB.Exec("UPDATE `Transaction` SET `Name` = ?, `Desc` = ?, `RefStart` = ?, `RefEnd` = ? WHERE `Id` = ?",
tr.Name,
tr.Desc,
tr.RefTimeSpan.Start.Unix(),
tr.RefTimeSpan.End.Unix(),
tr.Id)
if err != nil {
return err
}
err = tr.UpdateParts()
if err != nil {
return err
}
err = tr.UpdateItems()
if err != nil {
return err
}
return nil
}
func (tr *Transaction) UpdateParts() error {
tr.Init()
// First, delete all
_, err := DB.Exec("DELETE FROM `TransactionPart` WHERE `TransactionId` = ?", tr.Id)
if err != nil {
return err
}
// Now let us add them back
for _, tp := range tr.Parts {
err = tp.Save()
if err != nil {
return err
}
}
return nil
}
func (tr *Transaction) UpdateItems() error {
tr.Init()
// First, delete all
_, err := DB.Exec("DELETE FROM `TransactionItem` WHERE `TransactionId` = ?", tr.Id)
if err != nil {
return err
}
// Now let us add them back
for _, ti := range tr.Items {
err = ti.Save()
if err != nil {
return err
}
}
return nil
}
func transaction_add(line []string) {
var err error
tr := NewTransaction()
// Ask user for basic info
tr.Name = ask_user(
LocalLine,
Sprintf(Bold(" Name: ")),
"",
nil,
True)
tr.Desc = ask_user(
LocalLine,
Sprintf(Bold(" Desc: ")),
"",
nil,
True)
period := ask_user(
LocalLine,
Sprintf(Bold("Period: ")),
"",
nil,
func(s string) bool {
_, err := ParseTimePeriod(s)
return err == nil
})
// Parse stuff
tr.RefTimeSpan, err = ParseTimePeriod(period)
if err != nil {
fmt.Println(err.Error())
return
}
// Ask user for transaction items
last_currency := ""
sum := 0
for {
flag := ToBool(ask_user(
LocalLine,
Sprintf(Bold("Add transaction item? [y/n] ")),
"",
nil,
IsBool))
if flag != true {
break
}
// Ask transaction item details
ti := NewTransactionItem()
ti.TransactionId = tr.Id
ti.Name = ask_user(
LocalLine,
Sprintf(Bold(" Name: ")),
"",
nil,
True)
ti.AssetKindId = ask_user(
LocalLine,
Sprintf(Bold(" AssetId: ")),
last_currency,
CompleterAssetKind,
IsAssetKind)
// Ensure we do not sum when differnt currencies are invovled
if last_currency != "" && last_currency != ti.AssetKindId {
sum = -1
}
last_currency = ti.AssetKindId
tot_str := ask_user(
LocalLine,
Sprintf(Bold("TotalCost: ")),
"",
nil,
IsFloat)
ti.Quantity = str.ToFloatOr(ask_user(
LocalLine,
Sprintf(Bold(" Quantity: ")),
"",
nil,
IsFloat), 0)
guess := fmt.Sprintf("%f", str.ToFloatOr(tot_str, 0)/ti.Quantity)
uni_str := ask_user(
LocalLine,
Sprintf(Bold(" UnitCost: ")),
guess,
nil,
IsFloat)
ti.SetTotalCost(tot_str)
ti.SetUnitCost(uni_str)
if sum >= 0 {
sum += ti.TotalCost
}
tr.Items = append(tr.Items, *ti)
}
// Ask user for transaction parts
for {
flag := ToBool(ask_user(
LocalLine,
Sprintf(Bold("Add transaction part? [y/n] ")),
"",
nil,
IsBool))
if flag != true {
break
}
// Ask transaction part details
tp := NewTransactionPart()
tp.TransactionId = tr.Id
tp.AccountId = ask_user(
LocalLine,
Sprintf(Bold(" AccountId: ")),
"",
CompleterAccount,
IsAccount)
tp.AssetKindId = ask_user(
LocalLine,
Sprintf(Bold(" AssetId: ")),
last_currency,
CompleterAssetKind,
IsAssetKind)
last_currency = tp.AssetKindId
guess := ""
if sum >= 0 {
guess, _ = full_decimal_fmt(sum, last_currency)
}
val_str := ask_user(
LocalLine,
Sprintf(Bold(" Value: ")),
guess,
nil,
IsFloat)
schdul := ask_user(
LocalLine,
Sprintf(Bold("Scheduled for: ")),
"",
nil,
IsDay)
actual := ask_user(
LocalLine,
Sprintf(Bold(" Actual date: ")),
schdul,
nil,
IsDay)
status := ask_user(
LocalLine,
Sprintf(Bold(" Status: ")),
"",
CompleterTransactionStatus,
func(s string) bool {
tp := NewTransactionPart()
return tp.SetStatus(s) == nil
})
tp.SetValue(val_str)
tp.SetDates(schdul, actual)
tp.SetStatus(status)
tr.Parts = append(tr.Parts, *tp)
}
// Save
err = tr.Save()
if err != nil {
fmt.Println(err.Error())
return
}
}
func transaction_edit(line []string) {
var err error
if len(line) == 0 {
fmt.Println(Red("No id specified"))
return
}
// Load transaction
tr := NewTransaction()
err = tr.Load(line[len(line)-1])
if err != nil {
fmt.Println(err.Error())
return
}
// Ask user for basic info
tr.Name = ask_user(
LocalLine,
Sprintf(Bold(" Name: ")),
tr.Name,
nil,
True)
tr.Desc = ask_user(
LocalLine,
Sprintf(Bold(" Desc: ")),
tr.Desc,
nil,
True)
period := ask_user(
LocalLine,
Sprintf(Bold("Period: ")),
tr.RefTimeSpan.StringDay(),
nil,
func(s string) bool {
_, err := ParseTimePeriod(s)
return err == nil
})
// Parse stuff
tr.RefTimeSpan, err = ParseTimePeriod(period)
if err != nil {
fmt.Println(err.Error())
return
}
// Save
err = tr.Update()
if err != nil {
fmt.Println(err.Error())
return
}
}
func transaction_show(line []string) {
spec := ""
if len(line) > 0 {
spec = line[0]
}
tr := NewTransaction()
err := tr.Load(spec)
if err == nil {
fmt.Printf(tr.MultilineString())
return
}
rows, err := DB.Query("SELECT `Id`, `Name`, `RefStart`, `RefEnd` FROM `Transaction` WHERE `Name` LIKE '%%"+spec+"%%' OR ? = '' LIMIT 64", spec)
if err != nil {
log.Fatal(err)
}
// Read Stuff
for rows.Next() {
var id, name string
var start_int, end_int int64
err := rows.Scan(&id, &name, &start_int, &end_int)
if err != nil {
log.Fatal(err)
}
start := time.Unix(start_int, 0)
end := time.Unix(end_int, 0)
tmp_id := Sprintf(Gray(id))
tmp_name := Sprintf(Bold(fmt.Sprintf("%-19.19s", name)))
fmt.Printf("%s %s %10s - %10s\n", tmp_id, tmp_name, start.Format(DAY_FMT), end.Format(DAY_FMT))
}
}
func transaction_del(line []string) {
if len(line) == 0 {
fmt.Println(Red("No id specified"))
return
}
id := line[len(line)-1]
deleter(id, NewTransaction())
}
func CompleteTransactionFunc(prefix string) []string {
tmp := strings.Split(prefix, " ")
spec := tmp[len(tmp)-1]
rows, err := DB.Query("SELECT `Id` FROM `Transaction` WHERE `Id` LIKE '"+spec+"%%' OR ? = '' LIMIT 64", spec)
if err != nil {
log.Fatal(err)
}
// Read accounts
found := make([]string, 0)
defer rows.Close()
for rows.Next() {
s := ""
err := rows.Scan(&s)
if err != nil {
log.Fatal(err)
}
found = append(found, s)
}
return found
}
func CompleteTransactionStatusFunc(prefix string) []string {
tmp := strings.Split(prefix, " ")
spec := tmp[len(tmp)-1]
statuses := []string{
"TS_UNSET",
"TS_PLANNED",
"TS_SCHEDULED",
"TS_ON_GOING",
"TS_FINISHED",
"TS_CANCELED"}
ret := make([]string, 0)
for _, status := range statuses {
if strings.HasPrefix(status, spec) {
ret = append(ret, status)
}
}
return ret
}