forked from leavengood/donation_tracker
-
Notifications
You must be signed in to change notification settings - Fork 1
/
transactions.go
84 lines (66 loc) · 1.46 KB
/
transactions.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
package main
import (
"encoding/csv"
"os"
"reflect"
"strconv"
"time"
)
const CsvDateFormat = "2006-01-02"
type Transaction struct {
Date time.Time
Type string
Name string
Email string
Amt float32
FeeAmt float32
CurrencyCode string
}
func NewTransaction(row []string, headers []string) *Transaction {
result := new(Transaction)
elem := reflect.ValueOf(result).Elem()
for i, header := range headers {
field := elem.FieldByName(header)
if field.IsValid() && field.CanSet() {
value := row[i]
switch field.Kind() {
case reflect.String:
field.SetString(value)
case reflect.Float32:
f, _ := strconv.ParseFloat(value, 32)
field.SetFloat(f)
default:
// its the Date field
date, _ := time.Parse(CsvDateFormat, value)
field.Set(reflect.ValueOf(date))
}
}
}
return result
}
func (t *Transaction) NetAmt() float32 {
return t.Amt - t.FeeAmt
}
func ReadCsv(name string) ([][]string, error) {
file, err := os.Open(name)
if err != nil {
return [][]string{}, err
}
rows, err := csv.NewReader(file).ReadAll()
if err != nil {
return [][]string{}, err
}
return rows, nil
}
func TransactionsFromCsv(name string) ([]*Transaction, error) {
rows, err := ReadCsv(name)
if err != nil {
return []*Transaction{}, err
}
ts := make([]*Transaction, len(rows)-1)
headers := rows[0]
for i := 1; i < len(rows); i++ {
ts[i-1] = NewTransaction(rows[i], headers)
}
return ts, nil
}