File size: 4,907 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package rule

import (
	"database/sql"
	"errors"
	"fmt"
	"time"

	"github.com/target/goalert/assignment"
	"github.com/target/goalert/util/timeutil"
	"github.com/target/goalert/validation/validate"
)

type Rule struct {
	ID         string `json:"id"`
	ScheduleID string `json:"schedule_id"`
	timeutil.WeekdayFilter
	Start     timeutil.Clock `json:"start"`
	End       timeutil.Clock `json:"end"`
	CreatedAt time.Time      `json:"created_at"`
	Target    assignment.Target
}

func NewAlwaysActive(scheduleID string, tgt assignment.Target) *Rule {
	return &Rule{
		WeekdayFilter: timeutil.EveryDay(),
		ScheduleID:    scheduleID,
		Target:        tgt,
	}
}

func (r Rule) Normalize() (*Rule, error) {
	err := validate.UUID("ScheduleID", r.ScheduleID)
	if err != nil {
		return nil, err
	}
	r.Start = timeutil.Clock(time.Duration(r.Start).Truncate(time.Minute))
	r.End = timeutil.Clock(time.Duration(r.End).Truncate(time.Minute))
	return &r, nil
}

type scanner interface {
	Scan(...interface{}) error
}

var errNoKnownTarget = errors.New("rule had no known target set (user or rotation)")

func (r *Rule) scanFrom(s scanner) error {
	f := []interface{}{
		&r.ID,
		&r.ScheduleID,
		&r.WeekdayFilter,
		&r.Start,
		&r.End,
	}
	var usr, rot sql.NullString
	f = append(f, &usr, &rot)
	err := s.Scan(f...)
	if err != nil {
		return err
	}

	switch {
	case usr.Valid:
		r.Target = assignment.UserTarget(usr.String)
	case rot.Valid:
		r.Target = assignment.RotationTarget(rot.String)
	default:
		return errNoKnownTarget
	}
	return nil
}

func (r Rule) readFields() []interface{} {
	f := []interface{}{
		&r.ID,
		&r.ScheduleID,
		&r.WeekdayFilter,
		&r.Start,
		&r.End,
	}
	var usr, rot sql.NullString
	switch r.Target.TargetType() {
	case assignment.TargetTypeUser:
		usr.Valid = true
		usr.String = r.Target.TargetID()
	case assignment.TargetTypeRotation:
		rot.Valid = true
		rot.String = r.Target.TargetID()
	}
	return append(f, usr, rot)
}

// StartTime will return the next time the rule would be active.
// If the rule is currently active, it will return the time it
// became active (in the past).
//
// If the rule is NeverActive or AlwaysActive, zero time is returned.
//
// It may break when processing a timezone where daylight savings repeats or skips
// ahead at midnight.
func (r Rule) StartTime(t time.Time) time.Time {
	if r.NeverActive() {
		return time.Time{}
	}
	if r.AlwaysActive() {
		return time.Time{}
	}
	t = t.Truncate(time.Minute)

	w := t.Weekday()
	isTodayEnabled := r.Day(w)

	if isTodayEnabled && r.Start == r.End {
		return r.Start.FirstOfDay(r.WeekdayFilter.StartTime(t))
	}

	if r.Start < r.End {
		if !isTodayEnabled {
			return r.Start.FirstOfDay(r.NextActive(t))
		}

		// same-day shift, was active today
		// see if it's already ended
		end := r.End.LastOfDay(t)
		if t.Before(end) {
			return r.Start.FirstOfDay(t)
		}

		// shift has ended for the day, find the next start
		return r.Start.FirstOfDay(r.NextActive(t))
	}

	end := r.End.LastOfDay(t)
	if r.Day(w-1) && t.Before(end) {
		// yesterday's shift is still active
		return r.Start.FirstOfDay(t.AddDate(0, 0, -1))
	}

	if isTodayEnabled {
		// started or will start today
		return r.Start.FirstOfDay(t)
	}

	// find the next start time
	return r.Start.FirstOfDay(r.NextActive(t))
}

// EndTime will return the next time the rule would be inactive.
// If the rule is currently inactive, it will return the end
// of the next shift.
//
// If the rule is always active, or never active, it returns a zero time.
func (r Rule) EndTime(t time.Time) time.Time {
	start := r.StartTime(t)
	if start.IsZero() {
		return start
	}

	if r.Start < r.End {
		return r.End.LastOfDay(start)
	}
	if r.Start > r.End {
		// always the day after the start
		return r.End.LastOfDay(start.AddDate(0, 0, 1))
	}

	// 24-hour rule, end time of the next inactive day
	return r.End.LastOfDay(r.NextInactive(start))
}

// NeverActive returns true if the rule will never be active.
func (r Rule) NeverActive() bool { return r.IsNever() }

// AlwaysActive will return true if the rule will always be active.
func (r Rule) AlwaysActive() bool { return r.IsAlways() && r.Start == r.End }

// IsActive determines if the rule is active in the given moment in time, in the location of t.
func (r Rule) IsActive(t time.Time) bool {
	if r.NeverActive() {
		return false
	}
	if r.AlwaysActive() {
		return true
	}

	return !r.StartTime(t).After(t)
}

// String returns a human-readable string describing the rule
func (r Rule) String() string {
	if r.AlwaysActive() {
		return "Always"
	}
	if r.NeverActive() {
		return "Never"
	}

	var startStr, endStr string
	if r.Start.Minute() == 0 {
		startStr = r.Start.Format("3pm")
	} else {
		startStr = r.Start.Format("3:04pm")
	}

	if r.End.Minute() == 0 {
		endStr = r.End.Format("3pm")
	} else {
		endStr = r.End.Format("3:04pm")
	}

	return fmt.Sprintf("%s-%s %s", startStr, endStr, r.WeekdayFilter.String())
}