This repository has been archived by the owner on Jan 2, 2023. It is now read-only.
/
main.go
363 lines (306 loc) · 8.85 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
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"github.com/hitjim/ting-bill-split/internal/tingcsv"
"github.com/hitjim/ting-bill-split/internal/tingbill"
"github.com/hitjim/ting-bill-split/internal/tingparse"
"github.com/hitjim/ting-bill-split/internal/tingpdf"
"github.com/BurntSushi/toml"
)
func checkParam(param string, ptr *string, badParam *bool) {
if *ptr == "" {
*badParam = true
fmt.Printf("%s parameter is bad\n", param)
}
}
func createNewBillingDir(args []string) {
newDirName := "new-billing-period"
if len(args) > 2 {
fmt.Println("Syntax: `new <dir-name>`")
} else {
if len(args) == 2 {
newDirName = args[1]
}
if _, err := os.Stat(newDirName); os.IsNotExist(err) {
fmt.Println("Creating a directory for a new billing period.")
if err := os.MkdirAll(newDirName, os.ModePerm); err != nil {
log.Fatal("Failed to create new billing directory: ", err)
}
createBillFile(newDirName)
fmt.Printf("\n1. Enter values for the bill.toml file in new directory `%s`\n", newDirName)
fmt.Println("2. Add csv files for minutes, message, megabytes in the new directory")
fmt.Printf("3. run `tingbill dir %s`\n", newDirName)
} else {
fmt.Println("Directory already exists.")
}
}
}
func createBillFile(path string) {
path += "/bill.toml"
f, err := os.Create(path)
if err != nil {
panic(err)
}
// TODO - instead of encoding the struct, maybe define the newBill to ensure we
// don't forget to create requisite parts in the toml, but then use the newBill
// to "hand-craft" the example toml. So we can group values in a sensible way
// and provide helpful comment text
newBill := tingbill.Bill{
Description: "Ting Bill Split YYYY-MM-DD",
Devices: []tingbill.Device{
tingbill.Device{
DeviceID: "1112223333",
Owner: "owner1",
},
tingbill.Device{
DeviceID: "2229998888",
Owner: "owner2",
},
tingbill.Device{
DeviceID: "3331119999",
Owner: "owner1",
},
},
ShortStrawID: "1112223333",
Total: 0.00,
DevicesCost: 0.00,
Minutes: 0.00,
Messages: 0.00,
Megabytes: 0.00,
ExtraMinutes: 0.00,
ExtraMessages: 0.00,
ExtraMegabytes: 0.00,
Fees: 0.00,
}
if err := toml.NewEncoder(f).Encode(newBill); err != nil {
log.Fatalf("Error encoding TOML: %s", err)
}
}
// For a fileName string, return true if it contains the nameTerm anywhere.
// If an empty string is provided for `ext`, no extension matching is performed.
// Otherwise additional file extension matching is performed.
// TODO LATER - maybe use path/filepath.Match
func isFileMatch(fileName string, nameTerm string, ext string) bool {
r := regexp.MustCompile(`(?i)^[\w-]*` + nameTerm + `[\w-]*$`)
if ext != "" {
r = regexp.MustCompile(`(?i)^[\w-]*` + nameTerm + `[\w-]*(\.` + ext + `)$`)
}
return r.MatchString(fileName)
}
func parseDir(path string) {
var billFile *os.File
var minFile *os.File
var msgFile *os.File
var megFile *os.File
files, err := ioutil.ReadDir(path)
if err != nil {
log.Fatal(err)
}
for _, file := range files {
if file.IsDir() {
fmt.Printf("Directory \"%v\" found, continuing...\n", file.Name())
continue
}
if billFile == nil && isFileMatch(file.Name(), "bill", "toml") {
billFile, err = os.Open(filepath.Join(path, file.Name()))
if err != nil {
log.Fatal(err)
}
}
if minFile == nil && isFileMatch(file.Name(), "minutes", "csv") {
minFile, err = os.Open(filepath.Join(path, file.Name()))
if err != nil {
log.Fatal(err)
}
}
if msgFile == nil && isFileMatch(file.Name(), "messages", "csv") {
msgFile, err = os.Open(filepath.Join(path, file.Name()))
if err != nil {
log.Fatal(err)
}
}
if megFile == nil && isFileMatch(file.Name(), "megabytes", "csv") {
megFile, err = os.Open(filepath.Join(path, file.Name()))
if err != nil {
log.Fatal(err)
}
}
}
if billFile == nil || minFile == nil || msgFile == nil || megFile == nil {
fmt.Println("Unable to open necessary files.")
if billFile == nil {
fmt.Println("Bill file not found.")
return
}
if minFile == nil {
fmt.Println("Minutes file not found.")
return
}
if msgFile == nil {
fmt.Println("Messages file not found.")
return
}
if megFile == nil {
fmt.Println("Megabytes file not found.")
return
}
} else {
fmt.Printf("\nRunning calculations based on files in directory: %s\n\n", path)
billData, err := tingparse.ParseBill(billFile)
if err != nil {
log.Fatal(err)
}
minMap, err := tingparse.ParseMinutes(minFile)
if err != nil {
log.Fatal(err)
}
msgMap, err := tingparse.ParseMessages(msgFile)
if err != nil {
log.Fatal(err)
}
megMap, err := tingparse.ParseMegabytes(megFile)
if err != nil {
log.Fatal(err)
}
split, err := tingparse.CalculateSplit(minMap, msgMap, megMap, billData)
if err != nil {
log.Fatal(err)
}
pdfFilePath := filepath.Join(path, billData.Description+".pdf")
invoiceName, err := tingpdf.GeneratePDF(split, billData, pdfFilePath)
if err != nil {
fmt.Printf("Failed to generate PDF invoice at path: %v\n\n", pdfFilePath)
log.Fatal(err)
}
fmt.Printf("PDF invoice generation complete: %s\n", invoiceName)
csvFilePath := filepath.Join(path, billData.Description+"_report.csv")
invoiceName, err = tingcsv.GenerateCSV(split, billData, csvFilePath)
if err != nil {
fmt.Printf("Failed to generate CSV record at path: %v\n\n", csvFilePath)
log.Fatal(err)
}
fmt.Printf("CSV invoice generation complete: %s\n\n", invoiceName)
}
}
func printUsageHelp() {
fmt.Println("Use `tingbill new` or `tingbill new <billing-directory>` to create a new billing directory")
fmt.Println("\nUse `tingbill dir <billing-directory>` to run on a directory containing a `bill.toml`, and CSV files for minutes, messages, and megabytes usage.")
fmt.Println(" Each of these files must contain their type somewhere in the filename - i.e. `YYYYMMDD-messages.csv` or `messages-potatosalad.csv` or whatever.")
}
func main() {
fmt.Printf("\nTING BILL SPLIT\n")
fmt.Println("***************")
billPtr := flag.String("bill", "", "filename for bill toml - ex: -bill=\"bill.toml\"")
minPtr := flag.String("minutes", "", "filename for minutes csv - ex: -minutes=\"minutes.csv\"")
msgPtr := flag.String("messages", "", "filename for messages csv - ex: -messages=\"messages.csv\"")
megPtr := flag.String("megabytes", "", "filename for megabytes csv - ex: -megabytes=\"megabytes.csv\"")
flag.Parse()
args := flag.Args()
targetDir := "."
if len(args) == 0 {
fmt.Printf("`help`: usage guide for running batch mode against a single directory (recommended)\n")
fmt.Printf("`-h`: usage guide for running with individual file flags\n\n")
}
if len(args) > 0 {
fmt.Println("BATCH MODE")
command := args[0]
switch command {
case "new":
createNewBillingDir(args)
case "dir":
workingDir, err := os.Getwd()
if err != nil {
fmt.Println("Could not get working directory")
log.Fatal(err)
}
if len(args) > 1 {
targetDir = args[1]
}
fullTargetDir := ""
// Handle absolute and relative paths, respectively
if filepath.IsAbs(targetDir) {
fullTargetDir = targetDir
} else {
fullTargetDir = filepath.Join(workingDir, targetDir)
}
if filepath.IsAbs(fullTargetDir) {
parseDir(fullTargetDir)
// TODO - make parseDir return a split, since non-dir parsing uses a split
// then handle all actions after the if/else. Maybe?
} else {
fmt.Printf("Bill directory %v is invalid\n\n", fullTargetDir)
}
case "help":
printUsageHelp()
default:
fmt.Printf("\nInvalid arguments provided\n")
printUsageHelp()
}
} else {
badParam := false
paramMap := map[string]*string{
"bill": billPtr,
"minutes": minPtr,
"messages": msgPtr,
"megabytes": megPtr,
}
flagUsed := false
for _, v := range paramMap {
if *v != "" {
flagUsed = true
}
}
if flagUsed {
fmt.Println("RUNNING WITH INDIVIDUAL FILE FLAGS")
for k, v := range paramMap {
checkParam(k, v, &badParam)
}
if badParam {
os.Exit(1)
}
billFile, err := os.Open(*billPtr)
if err != nil {
log.Fatal(err)
}
billData, err := tingparse.ParseBill(billFile)
if err != nil {
log.Fatal(err)
}
minFile, err := os.Open(*minPtr)
if err != nil {
log.Fatal(err)
}
msgFile, err := os.Open(*msgPtr)
if err != nil {
log.Fatal(err)
}
megFile, err := os.Open(*megPtr)
if err != nil {
log.Fatal(err)
}
minMap, err := tingparse.ParseMinutes(minFile)
if err != nil {
log.Fatal(err)
}
msgMap, err := tingparse.ParseMessages(msgFile)
if err != nil {
log.Fatal(err)
}
megMap, err := tingparse.ParseMegabytes(megFile)
if err != nil {
log.Fatal(err)
}
split, err := tingparse.CalculateSplit(minMap, msgMap, megMap, billData)
if err != nil {
log.Fatal(err)
}
fmt.Println(split)
}
}
}