/
day.go
319 lines (277 loc) · 7.54 KB
/
day.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
package main
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"time"
"github.com/boltdb/bolt"
)
// MinDayKey is the BoltDB key of the minimum day
var MinDayKey = []byte("0:0000")
// MaxDayKey is the BoldDB key of the maximum day
var MaxDayKey = []byte("6:1440")
// daysBucket is the name of the Days bucket in
// BoltDB
var daysBucket = []byte("days")
// Day represents a template schedule for a day of the week.
// Days are stored in _local_ time, for the associated group.
type Day struct {
Group string // The group identifier
Target string // The target number
Day time.Weekday // Day or date
Start time.Duration // Time from 00:00
Duration time.Duration // Length of shift
Location string // Location for this schedule
}
// GetLocation gets the location attached to the day
func (d *Day) GetLocation() (*time.Location, error) {
return time.LoadLocation(d.Location)
}
// TimeToDayKey returns the BoltDB "day" bucket key for the current time
func TimeToDayKey(t time.Time) []byte {
minutes := t.Hour()*60 + t.Minute()
return []byte(fmt.Sprintf("%d:%02.f", t.Day(), float64(minutes)))
}
// DayRangeFor returns the BoltDB "day" bucket keys for
// the start and stop range filters to find Days which
// may be applicable for the given time.
// We return -48hours and current.
func DayRangeFor(t time.Time) (from, to []byte) {
start := t.Add(-48 * time.Hour)
return TimeToDayKey(start), TimeToDayKey(t)
}
// DaysForGroup returns all Days for the provided group
func DaysForGroup(db *bolt.DB, g *Group) (ret []Day, err error) {
err = db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(g.Key())
if b == nil {
return errors.New("Group bucket not found")
}
b = b.Bucket(daysBucket)
if b == nil {
return errors.New("Days bucket not found")
}
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
var d Day
err = decodeDay(v, &d)
if err != nil {
Log.Error("Failed to decode day", "raw", v, "error", err)
continue
}
ret = append(ret, d)
}
return nil
})
return
}
// ActiveDay returns the currently-active Day in the
// schedule.
func ActiveDay(db *bolt.DB, g *Group, t time.Time) *Day {
var err error
var d Day
if g == nil {
Log.Error("No group supplied")
return nil
}
// Walk through the database until we find the first
// active Day
err = db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(g.Key())
if b == nil {
return err
}
b = b.Bucket(daysBucket)
if b == nil {
return err
}
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
err = decodeDay(v, &d)
if err != nil {
fmt.Println("Failed to decode day", v, err)
continue
}
if d.ActiveAt(t) {
Log.Info("Day is active", "day", d)
return nil
}
}
return fmt.Errorf("No active day found")
})
if err != nil {
Log.Error("No match", "error", err)
return nil
}
if d.Target == "" {
return nil
}
return &d
}
// Key returns the BoltDB key for this day
func (d *Day) Key() []byte {
return []byte(fmt.Sprintf("%d:%02.f", d.Day, d.Start.Minutes()))
}
// ToExternal exports a Day schedule to its external version
func (d *Day) ToExternal(now time.Time) *DayExternal {
var e DayExternal
start, stop := d.Times(now)
e.Group = d.Group
e.Target = d.Target
e.Day = d.Day.String()
e.Start = start.Format("15:04")
e.Stop = stop.Format("15:04")
return &e
}
// Times returns the start and stop time for
// the closest Day translation to now.
func (d *Day) Times(now time.Time) (closestStart time.Time, closestStop time.Time) {
if now.IsZero() {
Log.Error("Cannot find times without reference")
return
}
if loc, err := d.GetLocation(); loc != nil && err == nil {
now = now.In(loc)
}
// find nearest start time of this slot
if now.Weekday() == d.Day && todayAt(now, d.Start).Before(now) {
// if the schedule is for today
// and we are after that scheduled time,
// then we have found the closest start
closestStart = todayAt(now, d.Start)
} else {
// Step back a day at a time until we find
// the most recent day that matches the day
// of the week of our Day.
for i := 1; i < 8; i++ {
sTime := now.Add(-time.Duration(i) * 24 * time.Hour)
if sTime.Weekday() == d.Day {
closestStart = todayAt(sTime, d.Start)
break
}
}
}
// closestStop is just the closests start plus
// the duration
closestStop = closestStart.Add(d.Duration)
return
}
// Save stores the Day in the database
func (d *Day) Save(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte(d.Group))
if err != nil {
return err
}
b, err = b.CreateBucketIfNotExists(daysBucket)
if err != nil {
return err
}
data, err := encodeDay(d)
if err != nil {
return err
}
return b.Put(d.Key(), data)
}
// timeSinceMidnight returns the difference in
// the given time from the previous midnight
func timeSinceMidnight(t time.Time) time.Duration {
t = t.Truncate(time.Minute)
return time.Duration(t.Hour())*time.Hour +
time.Duration(t.Minute())*time.Minute
}
// timeOfLastMidnight returns the time of the most
// recent midnight
func timeOfLastMidnight(t time.Time) time.Time {
t = t.Truncate(time.Minute)
return t.Add(-timeSinceMidnight(t))
}
// todayAt returns the time for today
// at the given difference in time from midnight.
func todayAt(t time.Time, diff time.Duration) time.Time {
base := timeOfLastMidnight(t)
return base.Add(diff)
}
// ActiveAt says whether the given time is
// wihtin the schedule of this Day schedule.
func (d *Day) ActiveAt(t time.Time) bool {
if loc, err := d.GetLocation(); loc != nil && err == nil {
t = t.In(loc)
}
start, stop := d.Times(t)
return t.After(start) && t.Before(stop)
}
// NewDayFromCSVRow takes a slice of strings (from a CSV), and
// parses them into a Unit.
// Format:
// `groupId, dayOfWeek, startTime, stopTime, cell/target`
func NewDayFromCSVRow(d []string) (*Day, error) {
if len(d) != 5 {
return nil, fmt.Errorf("CSV not in Group,Day,Time,Cell format")
}
e := DayExternal{
Group: d[0],
Day: d[1],
Start: d[2],
Stop: d[3],
Target: d[4],
}
return e.ToDay()
}
// DayExternal represents a Day schedule unit
// suitable for import and export
type DayExternal struct {
Group string `json:"group"` // Group ID
Target string `json:"target"` // Target cell phone
Day string `json:"day"` // Day of the Week
Start string `json:"start"` // Start time
Stop string `json:"stop"` // Stop time
}
// ToDay converts an exported day schedule to a
// proper Day schedule.
func (e *DayExternal) ToDay() (*Day, error) {
var ret Day
// Short-circuit if the day has no target
if e.Target == "" {
return nil, ErrNilTarget
}
// 0: group
ret.Group = e.Group
// 1: Day of week
dow, err := parseDay(e.Day)
if err != nil {
return nil, fmt.Errorf("Failed to parse day of the week: %s", err.Error())
}
ret.Day = dow
// 2: Start time
start, err := parseTime(e.Start)
if err != nil {
return nil, fmt.Errorf("Failed to parse time range: %s", err.Error())
}
ret.Start = start
// 3: Stop time
stop, err := parseTime(e.Stop)
if err != nil {
return nil, fmt.Errorf("Failed to parse time range: %s", err.Error())
}
diff := stop - start
if diff < 0 {
// If the time is negative, we wrapped to the next day
diff += 24 * time.Hour
}
ret.Duration = diff
// 3: Cell / Target
ret.Target = e.Target
if ret.Target == "" {
return nil, fmt.Errorf("Target/Cell is mandatory")
}
return &ret, nil
}
func encodeDay(d *Day) ([]byte, error) {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(d)
return buf.Bytes(), err
}
func decodeDay(data []byte, d *Day) error {
return gob.NewDecoder(bytes.NewReader(data)).Decode(d)
}