-
Notifications
You must be signed in to change notification settings - Fork 1
/
time_report.go
454 lines (428 loc) · 10.5 KB
/
time_report.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
// -----------------------------------------------------------------------------
// CMDX Utilities Suite cmdx/[time_report.go]
// (c) [email protected] License: GPLv3
// -----------------------------------------------------------------------------
package main
// # Command Function
// timeReport(cmd Command, args []string)
//
// # Report Functions
// trMonthlySummary(minDate, maxDate interface{}, files []string)
// trSummaryByDateText(minDate, maxDate interface{}, files []string)
//
// # Functions
// trCalcSpent(ar []TimeItem, autoTime bool) []TimeItem
// trFilterDates(ar []TimeItem, minDate, maxDate interface{}) []TimeItem
// trGetTimeItems(lines []string) []TimeItem
// trIsTimeStart(s string) bool
// trMergeFiles(filenames []string) (lines []string)
// trPrintFaults(ar []TimeItem)
// trPrintTimeItems(entries []TimeItem)
// trSumByDate(items []TimeItem) (ret []TimeItem)
// trSumByDateText(items []TimeItem) (ret []TimeItem)
//
// # Helper Functions
// trDateStr(val time.Time) string
// trDateTimeStr(val time.Time) string
// For debugging, you can set "args:" in launch.json. E.g:
// "args": [
// "time-report",
// "2022-01-01",
// "2022-31-12",
// "=admin/",
// "/x/user/admin/timelog.txt",
// ]
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/balacode/zr"
fs "github.com/balacode/zr-fs"
)
const (
trAuto = 1
trManual = 2
)
// -----------------------------------------------------------------------------
// # Command Function
// timeReport _ _
func timeReport(cmd Command, args []string) {
var (
min = "1900-01-01"
max = "9999-12-31"
files = []string{}
contains = []string{}
dates = 0
dateRX = regexp.MustCompile(`^\d{4}-\d\d-\d\d$`)
)
for _, arg := range args {
switch {
case dateRX.MatchString(arg):
dates++
switch dates {
case 1:
min = arg
case 2:
max = arg
default:
fmt.Printf("Error: too many dates")
return
}
case strings.HasPrefix(arg, "="):
contains = append(contains, arg[1:])
case fs.FileExists(arg):
files = append(files, arg)
default:
fmt.Printf("Error: file %q doesn't exist\n", arg)
return
}
}
if len(files) < 1 {
files = []string{"timelog.txt"}
}
trMonthlySummary("MANUAL", trManual, min, max, files, contains)
}
// -----------------------------------------------------------------------------
// # Report Functions
// trMonthlySummary _ _
func trMonthlySummary(
caption string,
mode int,
minDate, maxDate interface{},
files []string,
contains []string,
) {
var (
lenLines = 0
items []TimeItem
cal zr.Calendar
)
{
lines := trMergeFiles(files, contains)
lenLines = len(lines)
items = trFilterDates(trGetTimeItems(lines), minDate, maxDate)
if mode == trAuto {
items = trCalcSpent(items, true)
} else if mode == trManual {
trPrintFaults(items)
items = trCalcSpent(items, false)
}
sums := trSumByDate(items)
cal.SetWeekTotals(true)
for _, itm := range sums {
if itm.Spent < 0 {
cal.Set(itm.Time, "** >24")
} else {
cal.Set(itm.Time, itm.Spent.Hours())
}
}
}
if caption != "" {
env.Println(caption)
}
env.Println("FROM:", minDate, "TO:", maxDate, "LINES:", lenLines)
env.Println(cal.String())
{
env.Println("Summary by category:")
var totalHours float64
for _, t := range trSumByCategory(items) {
hours := float64(int(t.Spent.Hours()*10)) / 10.0
env.Println(t.Text, hours)
totalHours += hours
}
env.Println("Total Hours:", totalHours)
}
env.Println()
}
/*UNUSED:
// trSummaryByDateText _ _
func trSummaryByDateText(minDate, maxDate interface{}, files []string) {
var items []TimeItem
{
lines := trMergeFiles(files)
items = trGetTimeItems(lines)
items = trFilterDates(items, minDate, maxDate)
//
env.Println("FROM:", minDate, "TO:", maxDate, "LINES:", len(lines))
}
items = trCalcSpent(items, true)
if true {
for _, itm := range items {
env.Println(trDateTimeStr(itm.Time), "->", itm.String())
}
}
sum := trSumByDateText(items)
sort.Sort(TimeItemsByDateAndDescSpent(sum))
trPrintTimeItems(sum)
}
:UNUSED*/
// -----------------------------------------------------------------------------
// # Functions
// trCalcSpent reads time entries from 'ar' and returns a
// copy with all time spent (Spent field) recalculated.
func trCalcSpent(ar []TimeItem, autoTime bool) []TimeItem {
var prev time.Time // previous time
var ret []TimeItem
//
// calculate total time spent on each item
for _, itm := range ar {
var spent time.Duration
if !prev.IsZero() {
spent = itm.Time.Sub(prev)
}
if autoTime && spent > 10*time.Minute {
spent = 0
}
if trIsTimeStart(itm.Text) {
spent = 0
}
prev = itm.Time
ret = append(ret, TimeItem{
Time: itm.Time,
Text: itm.Text,
Count: itm.Count,
Spent: spent,
})
}
return ret
}
// trFilterDates filters times in 'ar' and returns a new slice
// of times that fall within the specified date range.
func trFilterDates(ar []TimeItem, minDate, maxDate interface{}) []TimeItem {
//
min := parseTime(minDate).String()[:10]
max := parseTime(maxDate).String()[:10]
var ret []TimeItem
for _, t := range ar {
date := trDateStr(t.Time)
if date >= min && date <= max {
ret = append(ret, t)
}
}
return ret
}
// trGetTimeItems returns a TimeItem array from a string slice
// - entries in the result are in ascending order
// - each date+time is unique
//
func trGetTimeItems(lines []string) []TimeItem {
//
// read lines into a unique date+time map
m := map[string]string{}
for _, line := range lines {
//
// ignore lines without date/time
if len(line) < 20 {
continue
}
dt, err := time.Parse("2006-01-02 15:04:05", line[:19])
if err != nil || dt.IsZero() {
continue
}
// store each line in a unique date+time key
// (any previous entry with same date+time gets overwritten)
m[line[:19]] = strings.Trim(line[20:], Spaces+"/\\")
}
// create a sorted array of keys
times := make([]string, 0, len(m))
for key := range m {
times = append(times, key)
}
times = sortUniqueStrings(times)
//
var ret []TimeItem
for _, key := range times {
ret = append(ret, TimeItem{
Time: parseTime(key),
Text: m[key],
Count: 1,
Spent: 0,
})
}
return ret
}
// trIsTimeStart _ _
func trIsTimeStart(s string) bool {
if strings.TrimSpace(s) == "IN" ||
strings.HasPrefix(s, "IN ") ||
strings.Contains(s, " IN ") ||
strings.HasSuffix(s, " IN") {
return true
}
return false
}
// trMergeFiles reads and filters lines from the specified filenames and
// returns the combined lines as a slice of strings. If 'contains' is
// specified, only returns lines that contain the string(s) it contains.
// If 'contains' is zero-length, returns all lines.
func trMergeFiles(filenames, contains []string) (lines []string) {
for _, path := range filenames {
fileLines := env.ReadFileLines(path)
if len(contains) == 0 {
lines = append(lines, fileLines...)
continue
}
for _, ln := range fileLines {
nextLine:
for _, sub := range contains {
if strings.Contains(strings.ToLower(ln), strings.ToLower(sub)) {
lines = append(lines, ln)
continue nextLine
}
}
}
}
return lines
}
// trPrintFaults _ _
func trPrintFaults(ar []TimeItem) {
//
var prevDate string // previous date
var prevTime time.Time // previous date and time
//
for _, itm := range ar {
date := trDateStr(itm.Time)
if trIsTimeStart(itm.Text) {
prevDate = date
prevTime = itm.Time
continue
}
if date != prevDate {
env.Println("NO START:", trDateTimeStr(itm.Time), itm.Text)
}
var spent time.Duration
if !prevTime.IsZero() {
spent = itm.Time.Sub(prevTime)
}
if spent > 3*time.Hour {
s := fmt.Sprintf("(%s)", spent)
if !strings.Contains(itm.Text, s) {
env.Println("TOO LONG:", trDateTimeStr(itm.Time), itm.Text, s)
}
}
prevDate = date
prevTime = itm.Time
}
}
/*UNUSED:
// trPrintTimeItems _ _
func trPrintTimeItems(entries []TimeItem) {
var (
prev string
total time.Duration
grand time.Duration
)
prt := func(a ...interface{}) {
env.Printf("%s %7.2f %11s: %s\n", a...)
}
for _, t := range entries {
date := trDateStr(t.Time)
if date != prev {
if prev != "" {
env.Println(strings.Repeat("-", 35))
prt(prev, total.Hours(), total, "total")
}
env.Println()
prev = date
total = 0
}
prt(date, t.Spent.Hours(), t.Spent, t.Text)
grand += t.Spent
total += t.Spent
}
if prev != "" {
env.Println(strings.Repeat("-", 35))
prt(prev, total.Hours(), total, "total")
}
env.Println()
env.Println(strings.Repeat("=", 35))
prt(prev, grand.Hours(), grand, "grand total")
}
:UNUSED*/
// trSumByCategory _ _
func trSumByCategory(items []TimeItem) (ret []TimeItem) {
m := map[string]*TimeItem{}
for _, t := range items {
k := t.Text
i := strings.Index(k, ":")
if i > -1 {
k = k[:i]
}
if _, exist := m[k]; !exist {
m[k] = &TimeItem{Text: k}
}
m[k].Count += t.Count
m[k].Spent += t.Spent
}
// convert items map into slice
for _, t := range m {
ret = append(ret, *t)
}
return ret
}
// trSumByDate _ _
func trSumByDate(items []TimeItem) (ret []TimeItem) {
//
// grouping stage
m := map[string]*TimeItem{}
for _, t := range items {
dt := trDateStr(t.Time)
if _, exist := m[dt]; !exist {
m[dt] = &TimeItem{Time: parseTime(dt)}
}
if m[dt].Spent == -1 {
continue
}
m[dt].Count += t.Count
sum := m[dt].Spent + t.Spent
if t.Spent > time.Hour*24 {
env.Println("> 24 HRS:", dt, t.Spent)
m[dt].Spent = -1
} else {
m[dt].Spent = sum
}
}
// convert items map into slice
for _, t := range m {
ret = append(ret, *t)
}
return ret
}
/*UNUSED:
// trSumByDateText _ _
func trSumByDateText(items []TimeItem) (ret []TimeItem) {
//
// grouping stage
m := map[string]*TimeItem{}
for _, t := range items {
date := trDateStr(t.Time)
k := date + "\t" + t.Text
if _, exist := m[k]; !exist {
m[k] = &TimeItem{
Time: parseTime(date),
Text: t.Text,
}
}
m[k].Count += t.Count
m[k].Spent += t.Spent
}
// convert items map into slice
for _, t := range m {
ret = append(ret, *t)
}
return ret
}
:UNUSED*/
// -----------------------------------------------------------------------------
// # Helper Functions
// trDateStr returns a date-only string ("2006-01-02" format) from a Time value.
func trDateStr(val time.Time) string {
return val.Format("2006-01-02")
}
// trDateTimeStr returns a date-time string
// ("2006-01-02 15:04:05" format) from a Time value.
func trDateTimeStr(val time.Time) string {
return val.Format("2006-01-02 15:04:05")
}
// end