-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
106 lines (85 loc) · 2.22 KB
/
table.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
package commands
import (
"fmt"
"regexp"
"time"
api "github.com/uhppoted/uhppoted-lib/acl"
)
func makeTable(rows [][]interface{}) (*api.Table, error) {
if len(rows) == 0 {
return nil, fmt.Errorf("empty sheet")
}
// .. build index
index := map[string]int{}
record := rows[0]
for i, v := range record {
k := normalise(v.(string))
if _, ok := index[k]; ok {
return nil, fmt.Errorf("duplicate column name '%s'", v.(string))
}
index[k] = i
}
// ... header
record = rows[0]
header := []string{}
if ix, ok := index["cardnumber"]; ok {
header = append(header, clean(record[ix].(string)))
}
if ix, ok := index["from"]; ok {
header = append(header, clean(record[ix].(string)))
}
if ix, ok := index["to"]; ok {
header = append(header, clean(record[ix].(string)))
}
for _, v := range record {
k := normalise(v.(string))
if k != "cardnumber" && k != "from" && k != "to" {
header = append(header, clean(v.(string)))
}
}
if len(header) == 0 {
return nil, fmt.Errorf("missing/invalid header row")
}
if len(header) < 1 || normalise(header[0]) != "cardnumber" {
return nil, fmt.Errorf("missing 'card number' column")
}
if len(header) < 2 || normalise(header[1]) != "from" {
return nil, fmt.Errorf("missing 'from' column")
}
if len(header) < 3 || normalise(header[2]) != "to" {
return nil, fmt.Errorf("missing 'to' column")
}
// ... records
records := [][]string{}
for _, row := range rows[1:] {
if cardnumber, ok := row[index["cardnumber"]].(string); !ok {
continue
} else if ok := regexp.MustCompile(`^\s*[0-9]+\s*$`).MatchString(cardnumber); !ok {
continue
}
if from, ok := row[index["from"]].(string); !ok {
continue
} else if _, err := time.ParseInLocation("2006-01-02", from, time.Local); err != nil {
continue
}
if to, ok := row[index["to"]].(string); !ok {
continue
} else if _, err := time.ParseInLocation("2006-01-02", to, time.Local); err != nil {
continue
}
record := []string{}
for _, h := range header {
k := normalise(h)
v := ""
if ix, ok := index[k]; ok {
v = row[ix].(string)
}
record = append(record, clean(v))
}
records = append(records, record)
}
return &api.Table{
Header: header,
Records: records,
}, nil
}