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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
package graphqlapp

import (
	context "context"
	"database/sql"
	"time"

	"github.com/google/uuid"
	"github.com/target/goalert/assignment"
	"github.com/target/goalert/event"
	"github.com/target/goalert/graphql2"
	"github.com/target/goalert/permission"
	"github.com/target/goalert/schedule/rotation"
	"github.com/target/goalert/search"
	"github.com/target/goalert/user"
	"github.com/target/goalert/util"
	"github.com/target/goalert/util/timeutil"
	"github.com/target/goalert/validation"
	"github.com/target/goalert/validation/validate"

	"github.com/pkg/errors"
)

type Rotation App

func (a *App) Rotation() graphql2.RotationResolver { return (*Rotation)(a) }

func (q *Query) Rotation(ctx context.Context, id string) (*rotation.Rotation, error) {
	return (*App)(q).FindOneRotation(ctx, id)
}

func (m *Mutation) CreateRotation(ctx context.Context, input graphql2.CreateRotationInput) (result *rotation.Rotation, err error) {
	loc, err := util.LoadLocation(input.TimeZone)
	if err != nil {
		return nil, validation.NewFieldError("TimeZone", err.Error())
	}
	err = withContextTx(ctx, m.DB, func(ctx context.Context, tx *sql.Tx) error {
		rot := &rotation.Rotation{
			Name:  input.Name,
			Type:  input.Type,
			Start: input.Start.In(loc),
		}
		if input.Description != nil {
			rot.Description = *input.Description
		}
		if input.ShiftLength != nil {
			rot.ShiftLength = *input.ShiftLength
		}

		result, err = m.RotationStore.CreateRotationTx(ctx, tx, rot)
		if err != nil {
			return err
		}

		if input.Favorite != nil && *input.Favorite {
			err = m.FavoriteStore.Set(ctx, tx, permission.UserID(ctx), assignment.RotationTarget(result.ID))
			if err != nil {
				return err
			}
		}

		if input.UserIDs != nil {
			err := m.RotationStore.AddRotationUsersTx(ctx, tx, result.ID, input.UserIDs)
			if err != nil {
				return err
			}
		}
		return err
	})

	return result, err
}

func (r *Rotation) TimeZone(ctx context.Context, rot *rotation.Rotation) (string, error) {
	return rot.Start.Location().String(), nil
}

func (r *Rotation) IsFavorite(ctx context.Context, rot *rotation.Rotation) (bool, error) {
	return rot.IsUserFavorite(), nil
}

func (r *Rotation) NextHandoffTimes(ctx context.Context, rot *rotation.Rotation, num *int) ([]time.Time, error) {
	var n int
	if num != nil {
		n = *num
	} else {
		count, err := r.RotationStore.FindParticipantCount(ctx, rot.ID)
		if err != nil {
			return nil, errors.Wrap(err, "retrieving participant count")
		}
		if count > 50 {
			// setting to max limit for validation
			n = 50
		} else {
			n = count
		}
	}

	err := validate.Range("num", n, 0, 50)
	if err != nil {
		return nil, err
	}

	s, err := r.RotationStore.State(ctx, rot.ID)
	if errors.Is(err, rotation.ErrNoState) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	result := make([]time.Time, n)
	t := s.ShiftStart
	for i := range result {
		t = rot.EndTime(t)
		result[i] = t
	}

	return result, nil
}

func (r *Rotation) UserIDs(ctx context.Context, rot *rotation.Rotation) ([]string, error) {
	parts, err := r.RotationStore.FindAllParticipants(ctx, rot.ID)
	if err != nil {
		return nil, err
	}

	ids := make([]string, len(parts))
	for i, p := range parts {
		ids[i] = p.Target.TargetID()
	}

	return ids, nil
}

func (r *Rotation) Users(ctx context.Context, rot *rotation.Rotation) ([]user.User, error) {
	userIDs, err := r.UserIDs(ctx, rot)
	if err != nil {
		return nil, err
	}

	users := make([]user.User, len(userIDs))
	errCh := make(chan error, len(userIDs))
	for i := range userIDs {
		// TODO: does this need to be bounded?
		// The max number = the max number of unique users in the current rotation,
		// which can be bounded by the config_limit participants_per_rotation (but isn't by default).
		go func(idx int) {
			u, err := (*App)(r).FindOneUser(ctx, userIDs[idx])
			if err == nil {
				users[idx] = *u
			}
			errCh <- err
		}(i)
	}

	for range userIDs {
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		case err := <-errCh:
			if err != nil {
				return nil, err
			}
		}
	}

	return users, nil
}

func (r *Rotation) ActiveUserIndex(ctx context.Context, obj *rotation.Rotation) (int, error) {
	s, err := r.RotationStore.State(ctx, obj.ID)
	if errors.Is(err, rotation.ErrNoState) {
		return -1, nil
	}
	if err != nil {
		return -1, err
	}
	return s.Position, err
}

func (q *Query) Rotations(ctx context.Context, opts *graphql2.RotationSearchOptions) (conn *graphql2.RotationConnection, err error) {
	if opts == nil {
		opts = &graphql2.RotationSearchOptions{}
	}

	var searchOpts rotation.SearchOptions
	searchOpts.FavoritesUserID = permission.UserID(ctx)
	if opts.Search != nil {
		searchOpts.Search = *opts.Search
	}
	if opts.FavoritesFirst != nil {
		searchOpts.FavoritesFirst = *opts.FavoritesFirst
	}

	if opts.FavoritesOnly != nil {
		searchOpts.FavoritesOnly = *opts.FavoritesOnly
	}
	searchOpts.Omit = opts.Omit
	if opts.After != nil && *opts.After != "" {
		err = search.ParseCursor(*opts.After, &searchOpts)
		if err != nil {
			return nil, err
		}
	}
	if opts.First != nil {
		searchOpts.Limit = *opts.First
	}
	if searchOpts.Limit == 0 {
		searchOpts.Limit = 15
	}

	searchOpts.Limit++
	rots, err := q.RotationStore.Search(ctx, &searchOpts)
	if err != nil {
		return nil, err
	}
	conn = new(graphql2.RotationConnection)
	conn.PageInfo = &graphql2.PageInfo{}
	if len(rots) == searchOpts.Limit {
		rots = rots[:len(rots)-1]
		conn.PageInfo.HasNextPage = true
	}
	if len(rots) > 0 {
		last := rots[len(rots)-1]
		searchOpts.After.IsFavorite = last.IsUserFavorite()
		searchOpts.After.Name = last.Name

		cur, err := search.Cursor(searchOpts)
		if err != nil {
			return conn, err
		}
		conn.PageInfo.EndCursor = &cur
	}
	conn.Nodes = rots
	return conn, err
}

func (m *Mutation) updateRotationParticipants(ctx context.Context, tx *sql.Tx, rotationID string, userIDs []string, updateActive bool) (err error) {
	// Get current participants
	currentParticipants, err := m.RotationStore.FindAllParticipantsTx(ctx, tx, rotationID)
	if err != nil {
		return err
	}

	var participantIDsToRemove []string

	for i, c := range currentParticipants {
		if i >= len(userIDs) {
			participantIDsToRemove = append(participantIDsToRemove, c.ID)
			continue
		}

		if c.Target.TargetID() == userIDs[i] {
			// nothing to update
			continue
		}

		// Update
		err = m.RotationStore.UpdateParticipantUserIDTx(ctx, tx, c.ID, userIDs[i])
		if err != nil {
			return err
		}
	}

	if len(userIDs) > len(currentParticipants) {
		// Add users
		err = m.RotationStore.AddRotationUsersTx(ctx, tx, rotationID, userIDs[len(currentParticipants):])
		if err != nil {
			return err
		}
	}

	if len(participantIDsToRemove) == 0 {
		return nil
	}

	if len(userIDs) == 0 {
		// Delete rotation state if all users are going to be deleted as per new input
		err = m.RotationStore.DeleteStateTx(ctx, tx, rotationID)
		if err != nil {
			return err
		}
	} else if updateActive {
		// get current active participant
		s, err := m.RotationStore.StateTx(ctx, tx, rotationID)
		if errors.Is(err, rotation.ErrNoState) {
			return nil
		}
		if err != nil {
			return err
		}

		// if currently active user is going to be deleted
		// then set to first user before we actually delete any users
		if s.Position >= len(userIDs) {
			err = m.RotationStore.SetActiveIndexTx(ctx, tx, rotationID, 0)
			if err != nil {
				return err
			}
		}
	}

	err = m.RotationStore.DeleteRotationParticipantsTx(ctx, tx, participantIDsToRemove)
	if err != nil {
		return err
	}
	return nil
}

func (m *Mutation) UpdateRotation(ctx context.Context, input graphql2.UpdateRotationInput) (res bool, err error) {
	err = withContextTx(ctx, m.DB, func(ctx context.Context, tx *sql.Tx) error {
		result, err := m.RotationStore.FindRotationForUpdateTx(ctx, tx, input.ID)
		if errors.Is(err, sql.ErrNoRows) {
			return validation.NewFieldError("id", "Rotation not found")
		}
		if err != nil {
			return err
		}
		var update bool
		if input.Name != nil {
			update = true
			result.Name = *input.Name
		}
		if input.Description != nil {
			update = true
			result.Description = *input.Description
		}
		if input.Start != nil {
			update = true
			result.Start = *input.Start
		}
		if input.Type != nil {
			update = true
			result.Type = *input.Type
		}
		if input.ShiftLength != nil {
			update = true
			result.ShiftLength = *input.ShiftLength
		}

		if input.TimeZone != nil {
			update = true
			loc, err := util.LoadLocation(*input.TimeZone)
			if err != nil {
				return validation.NewFieldError("TimeZone", "invalid TimeZone: "+err.Error())
			}
			result.Start = result.Start.In(loc)
		}

		if update {
			err = m.RotationStore.UpdateRotationTx(ctx, tx, result)
			if err != nil {
				return err
			}
		}

		if input.UserIDs != nil {
			err = m.updateRotationParticipants(ctx, tx, input.ID, input.UserIDs, input.ActiveUserIndex == nil)
			if err != nil {
				return err
			}
		}

		// Update active participant (in rotation state) if specified by input
		// This should be applicable regardless of whether or not 'UserIDs' as an input has been specified.
		if input.ActiveUserIndex != nil {
			err = m.RotationStore.SetActiveIndexTx(ctx, tx, input.ID, *input.ActiveUserIndex)
			if err != nil {
				return err
			}
		}

		event.SendTx(ctx, m.EventBus, tx, rotation.Update{ID: uuid.MustParse(input.ID)})

		return nil
	})
	if err != nil {
		return false, err
	}
	return true, nil
}

func (a *Query) CalcRotationHandoffTimes(ctx context.Context, input *graphql2.CalcRotationHandoffTimesInput) ([]time.Time, error) {
	err := validate.Range("count", input.Count, 0, 20)
	if err != nil {
		return nil, err
	}

	loc, err := util.LoadLocation(input.TimeZone)
	if err != nil {
		return nil, validation.NewFieldError("timeZone", err.Error())
	}

	if input.ShiftLength != nil && input.ShiftLengthHours != nil {
		return nil, validation.NewFieldError("shiftLength", "only one of (shiftLength, shiftLengthHours) is allowed")
	}

	rot := rotation.Rotation{
		Start: input.Handoff.In(loc),
	}
	switch {
	case input.ShiftLength != nil:
		err = setRotationShiftFromISO(&rot, input.ShiftLength)
		if err != nil {
			return nil, err
		}
	case input.ShiftLengthHours != nil:
		err = validate.Range("hours", *input.ShiftLengthHours, 0, 99999)
		if err != nil {
			return nil, err
		}
		rot.Type = rotation.TypeHourly
		rot.ShiftLength = *input.ShiftLengthHours
	default:
		return nil, validation.NewFieldError("shiftLength", "must be specified")
	}

	t := time.Now()
	if input.From != nil {
		t = input.From.In(loc)
	}

	var result []time.Time
	for len(result) < input.Count {
		t = rot.EndTime(t)
		result = append(result, t)
	}

	return result, nil
}

// getRotationFromISO determines the rotation type based on the given ISODuration. An error is given if the unsupported year field or multiple non-zero fields are given.
func setRotationShiftFromISO(rot *rotation.Rotation, dur *timeutil.ISODuration) error {
	// validate only one time field (year, month, days, timepart) is non-zero
	nonZeroFields := 0

	if dur.YearPart > 0 {
		// These validation errors are only possible from direct api calls,
		// thus using ISO standard terminology "designator" to match the spec.
		return validation.NewFieldError("shiftLength", "year designator not allowed")
	}

	if dur.MonthPart > 0 {
		rot.Type = rotation.TypeMonthly
		rot.ShiftLength = dur.MonthPart
		nonZeroFields++
	}
	if dur.WeekPart > 0 {
		rot.Type = rotation.TypeWeekly
		rot.ShiftLength = dur.WeekPart
		nonZeroFields++
	}
	if dur.DayPart > 0 {
		rot.Type = rotation.TypeDaily
		rot.ShiftLength = dur.DayPart
		nonZeroFields++
	}
	if dur.HourPart > 0 {
		rot.Type = rotation.TypeHourly
		rot.ShiftLength = dur.HourPart
		nonZeroFields++
	}

	if nonZeroFields == 0 {
		return validation.NewFieldError("shiftLength", "must not be zero")
	}
	if nonZeroFields > 1 {
		// Same as above, this error is only possible from direct api calls.
		return validation.NewFieldError("shiftLength", "only one of (M, W, D, H) is allowed")
	}

	return nil
}