-
Notifications
You must be signed in to change notification settings - Fork 0
/
tt.go
105 lines (94 loc) · 2.2 KB
/
tt.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
package tt
import (
"fmt"
"time"
"github.com/google/uuid"
)
func List(filter Filter, orderBy OrderBy) (Timers, error) {
var timers Timers
err := GetDB().GetTimers(filter, orderBy, &timers)
if err != nil {
return nil, fmt.Errorf("list: %w", err)
}
return timers, nil
}
func Start(project, task string, tags []string, timestamp time.Time, copy int) (Timer, error) {
db := GetDB()
c := GetConfig()
orderBy := OrderBy{
Field: FieldStart,
Order: OrderDsc,
}
var timers Timers
err := db.GetTimers(EmptyFilter, orderBy, &timers)
if err != nil {
return Timer{}, fmt.Errorf("start: %w", err)
}
if c.GetRoundStartTime() > 0 {
timestamp = timestamp.Round(c.GetRoundStartTime())
}
if len(timers) > 0 && timers[0].Stop == nil {
if c.AutoStop {
_, err = Stop(timestamp)
if err != nil {
return Timer{}, fmt.Errorf("start: auto-stop: %w", err)
}
} else {
return Timer{}, fmt.Errorf("start: %w: running timer exists", ErrOperationNotPermitted)
}
}
var baseTimer Timer
if copy > 0 {
if len(timers) < copy {
return Timer{}, fmt.Errorf("start: copy from timer: %w", ErrNotFound)
}
baseTimer = timers[copy-1]
}
t := Timer{
ID: uuid.Must(uuid.NewRandom()).String(),
Start: timestamp,
Project: project,
Task: task,
Tags: tags,
}
// copy values if they haven't been provided, and we should copy
if copy > 0 && t.Project == "" {
t.Project = baseTimer.Project
}
if copy > 0 && t.Task == "" {
t.Task = baseTimer.Task
}
if copy > 0 && len(t.Tags) == 0 {
t.Tags = baseTimer.Tags
}
err = t.Validate()
if err != nil {
return Timer{}, fmt.Errorf("start: %w", err)
}
err = db.SaveTimer(t)
if err != nil {
return Timer{}, fmt.Errorf("start: %w", err)
}
return t, nil
}
func Stop(timestamp time.Time) (Timer, error) {
db := GetDB()
orderBy := OrderBy{
Field: FieldStart,
Order: OrderDsc,
}
var timer Timer
err := db.GetTimer(EmptyFilter, orderBy, &timer)
if err != nil {
return Timer{}, fmt.Errorf("stop: %w", err)
}
if !timer.Running() {
return Timer{}, fmt.Errorf("stop: %w: running timer", ErrNotFound)
}
timer.Stop = ×tamp
err = db.UpdateTimer(timer)
if err != nil {
return Timer{}, fmt.Errorf("stop: %w", err)
}
return timer, nil
}