-
Notifications
You must be signed in to change notification settings - Fork 17
/
report.go
527 lines (437 loc) · 11.6 KB
/
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
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
517
518
519
520
521
522
523
524
525
526
527
package main
import (
"encoding/json"
"fmt"
"regexp"
"sort"
"strings"
"time"
"github.com/jason0x43/go-alfred"
)
// ReportFilter is a command
type ReportFilter struct{}
// About returns information about a command
func (c ReportFilter) About() alfred.CommandDef {
return alfred.CommandDef{
Keyword: "report",
Description: "Generate summary reports",
IsEnabled: config.APIKey != "",
}
}
// Items returns a list of filter items
func (c ReportFilter) Items(arg, data string) (items []alfred.Item, err error) {
if err = checkRefresh(); err != nil {
return
}
var cfg reportCfg
if data != "" {
if err = json.Unmarshal([]byte(data), &cfg); err != nil {
dlog.Printf("Error unmarshalling data: %v", err)
}
}
var span span
if cfg.Span != nil {
span = *cfg.Span
if span.Start.IsZero() {
if span, err = getSpan(span.Name); err != nil {
return
}
}
} else {
var spanArg string
spanArg, arg = alfred.SplitCmd(arg)
for _, value := range []string{"today", "yesterday", "week"} {
if alfred.FuzzyMatches(value, spanArg) {
span, _ := getSpan(value)
items = append(items, createReportMenuItem(span))
}
}
if matched, _ := regexp.MatchString(`^\d`, spanArg); matched {
if span, err = getSpan(spanArg); err == nil {
items = append(items, createReportMenuItem(span))
}
}
if len(items) == 0 {
items = append(items, alfred.Item{
Title: "Enter a valid date or range",
})
}
return
}
var reportItems []alfred.Item
if reportItems, err = createReportItems(arg, data, &cfg, span); err != nil {
return
}
items = append(items, reportItems...)
if len(items) == 0 {
cfg.Span = nil
item := alfred.Item{
Title: "No time entries for " + span.Name,
Arg: &alfred.ItemArg{
Keyword: "report",
Data: alfred.Stringify(&cfg),
},
}
items = append(items, item)
}
return items, nil
}
// support -------------------------------------------------------------------
type reportGrouping string
const (
groupByDay reportGrouping = "day"
groupByProject reportGrouping = "project"
)
type reportCfg struct {
Project *int `json:"project,omitempty"`
EntryTitle *string `json:"entrytitle,omitempty"`
Span *span `json:"span,omitempty"`
Grouping *reportGrouping `json:"grouping,omitempty"`
Previous *reportCfg `json:"previous,omitempty"`
}
type span struct {
Name string
Label string
Start time.Time
End time.Time
MultiDay bool
}
type dateEntry struct {
total int64
name string
entries map[string]*timeEntry
}
type projectEntry struct {
total int64
name string
id int
running bool
entries map[string]*timeEntry
}
type timeEntry struct {
total int64
running bool
description string
}
type summaryReport struct {
total int64
projects map[string]*projectEntry
dates map[string]*dateEntry
}
func createReportMenuItem(s span) (item alfred.Item) {
cfg := reportCfg{Span: &s}
subtitle := "Generate a report for "
if s.Label != "" {
subtitle += s.Label
} else {
subtitle += s.Name
}
item = alfred.Item{
Autocomplete: s.Name,
Title: s.Name,
Subtitle: subtitle,
Arg: &alfred.ItemArg{
Keyword: "report",
Data: alfred.Stringify(&cfg),
},
}
if s.MultiDay {
grouping := groupByDay
cfg.Grouping = &grouping
item.AddMod(alfred.ModAlt, alfred.ItemMod{
Subtitle: item.Subtitle + ", grouping entries by day",
Arg: &alfred.ItemArg{
Keyword: "report",
Data: alfred.Stringify(&cfg),
},
})
}
return
}
func createReportItems(
arg, data string,
cfg *reportCfg,
span span,
) (items []alfred.Item, err error) {
projectID := -1
if cfg.Project != nil {
projectID = *cfg.Project
}
entryTitle := ""
if cfg.EntryTitle != nil {
entryTitle = *cfg.EntryTitle
}
var grouping reportGrouping
if cfg.Grouping != nil {
grouping = *cfg.Grouping
}
var report *summaryReport
if report, err = generateReport(span.Start, span.End, projectID, entryTitle); err != nil {
return
}
dlog.Printf("creating report with data %#v", data)
newCfg := reportCfg{Span: &span, Previous: cfg}
var total int64
var totalName string
spanName := span.Name
if span.Label != "" {
spanName = span.Label
}
if grouping == groupByDay {
// By-day report
dlog.Printf("checking %d dates", len(report.dates))
for _, date := range report.dates {
totalName = "for " + spanName
if entryTitle != "" {
totalName += " for " + entryTitle
}
dateName := date.name
if alfred.FuzzyMatches(dateName, arg) {
if span, e := getSpan(date.name); e == nil {
newCfg.Span = &span
} else {
dlog.Printf("Error getting span for %s: %v", date.name, e)
}
items = append(items, alfred.Item{
Title: dateName,
Subtitle: formatDuration(date.total),
Arg: &alfred.ItemArg{
Keyword: "report",
Data: alfred.Stringify(&newCfg),
},
})
total += date.total
}
}
} else {
// By-project report
dlog.Printf("checking %d projects", len(report.projects))
for _, project := range report.projects {
if projectID != -1 {
// By-project report for a single project
dlog.Printf("have projectID: %d", projectID)
totalName = fmt.Sprintf("for %s for %s", spanName, project.name)
grouping := groupByDay
newCfg.Grouping = &grouping
for desc, entry := range project.entries {
dlog.Printf("getting info for %#v", entry)
entryTitle := desc
newCfg.EntryTitle = &entryTitle
if alfred.FuzzyMatches(entryTitle, arg) {
item := alfred.Item{
Title: entryTitle,
Subtitle: formatDuration(entry.total),
Arg: &alfred.ItemArg{
Keyword: "report",
Data: alfred.Stringify(&newCfg),
},
}
if entry.running {
item.Icon = "running.png"
}
items = append(items, item)
}
total += entry.total
}
} else {
// By-project report for all projects
totalName = "for " + spanName
if entryTitle != "" {
totalName += " for " + entryTitle
}
projectName := project.name
newCfg.Project = &project.id
dlog.Printf("checking if '%s' fuzzyMatches '%s'", arg, projectName)
if alfred.FuzzyMatches(projectName, arg) {
item := alfred.Item{
Title: projectName,
Subtitle: formatDuration(project.total),
Arg: &alfred.ItemArg{
Keyword: "report",
Data: alfred.Stringify(&newCfg),
},
}
if project.running {
item.Icon = "running.png"
}
items = append(items, item)
total += project.total
}
}
}
}
sort.Sort(alfred.ByTitle(items))
// Add the Total line at the top
if totalName != "" && arg == "" {
title := fmt.Sprintf("Total time %s: %s", totalName, formatDuration(total))
item := alfred.Item{
Title: title,
Subtitle: alfred.Line,
}
if newCfg.EntryTitle != nil {
newCfg.EntryTitle = nil
} else if newCfg.Project != nil {
newCfg.Project = nil
} else {
newCfg.Span = nil
}
if cfg.Previous != nil {
item.Arg = &alfred.ItemArg{
Keyword: "report",
Data: alfred.Stringify(cfg.Previous),
}
}
items = alfred.InsertItem(items, item, 0)
}
return
}
// expand fills in the start and end times for a span
func getSpan(arg string) (s span, err error) {
if arg == "today" {
s.Name = arg
s.Start = toDayStart(time.Now())
s.End = toDayEnd(s.Start)
} else if arg == "yesterday" {
s.Name = arg
s.Start = toDayStart(time.Now().AddDate(0, 0, -1))
s.End = toDayEnd(s.Start)
} else if arg == "week" {
s.Name = "week"
s.Label = "this week"
start := time.Now()
startOfWeek := cache.Account.BeginningOfWeek
startDay := int(start.Weekday())
delta := startDay - startOfWeek
if startDay < startOfWeek {
delta += 7
}
s.Start = toDayStart(start.AddDate(0, 0, -delta))
s.End = toDayEnd(time.Now())
dlog.Printf("Creating week span; weekStart=%d, today=%d, delta=%d, start=%v, end=%v",
startOfWeek, start.Weekday(), delta, s.Start, s.End)
s.MultiDay = true
} else {
if strings.Contains(arg, "..") {
parts := alfred.CleanSplitN(arg, "..", 2)
if len(parts) == 2 {
var span1 span
var span2 span
if span1, err = getSpan(parts[0]); err == nil {
if span2, err = getSpan(parts[1]); err == nil {
s.Name = arg
s.Start = span1.Start
s.End = span2.End
s.MultiDay = true
}
}
}
} else {
if layout := getDateLayout(arg); layout != "" {
if s.Start, err = time.Parse(layout, arg); err != nil {
return
}
year := s.Start.Year()
if year == 0 {
year = time.Now().Year()
}
s.Name = arg
s.Start = time.Date(year, s.Start.Month(), s.Start.Day(), 0, 0, 0, 0, time.Local)
s.End = time.Date(year, s.Start.Month(), s.Start.Day(), 23, 59, 59, 999999999, time.Local)
}
}
}
if err == nil && s.Name == "" {
err = fmt.Errorf("Unable to parse span '%s'", arg)
}
return
}
func generateReport(
since, until time.Time,
projectID int,
entryTitle string,
) (*summaryReport, error) {
dlog.Printf("Generating report from %s to %s for %d", since, until, projectID)
report := summaryReport{
projects: map[string]*projectEntry{},
dates: map[string]*dateEntry{},
}
projects := getProjectsByID()
for _, entry := range cache.Account.TimeEntries {
start := entry.StartTime()
if !start.Before(since) && !until.Before(start) {
if projectID != -1 && entry.Pid != nil && *entry.Pid != projectID {
continue
}
if entryTitle != "" && entry.Description != entryTitle {
continue
}
var projectName string
if entry.Pid == nil {
projectName = "<No project>"
} else {
proj, _ := projects[*entry.Pid]
projectName = proj.Name
}
if _, ok := report.projects[projectName]; !ok {
id := 0
if entry.Pid != nil {
id = *entry.Pid
}
report.projects[projectName] = &projectEntry{
name: projectName,
id: id,
entries: map[string]*timeEntry{}}
}
date := start.Format("1/2")
if _, ok := report.dates[date]; !ok {
report.dates[date] = &dateEntry{
name: date,
entries: map[string]*timeEntry{}}
}
project := report.projects[projectName]
dateEntry := report.dates[date]
duration := entry.Duration
if duration < 0 {
duration = round(time.Now().Sub(entry.StartTime()).Seconds())
project.running = true
}
duration = roundDuration(duration, false)
if _, ok := project.entries[entry.Description]; !ok {
project.entries[entry.Description] = &timeEntry{description: entry.Description}
}
if project.running {
project.entries[entry.Description].running = true
}
project.entries[entry.Description].total += duration
dateEntry.total += duration
project.total += duration
report.total += duration
}
}
return &report, nil
}
var dateFormats = map[string]*regexp.Regexp{
"1/2": regexp.MustCompile(`^\d\d?\/\d\d?$`),
"1/2/06": regexp.MustCompile(`^\d\d?\/\d\d?\/\d\d$`),
"1/2/2006": regexp.MustCompile(`^\d\d?\/\d\d?\/\d\d\d\d$`),
"2006-1-2": regexp.MustCompile(`^\d\d\d\d-\d\d?-\d\d$`),
}
// return true if the string can be parsed as a date
func getDateLayout(s string) string {
for layout, matcher := range dateFormats {
if matcher.MatchString(s) {
return layout
}
}
return ""
}
// return a datetime at the minimum time on the given date
func toDayStart(date time.Time) time.Time {
date = date.In(time.Local)
return time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.Local)
}
// return a datetime at the maximum time on the given date
func toDayEnd(date time.Time) time.Time {
date = date.In(time.Local)
return time.Date(date.Year(), date.Month(), date.Day(), 23, 59, 59, 999999999, time.Local)
}