-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
race_weekend_handler.go
560 lines (433 loc) · 18.5 KB
/
race_weekend_handler.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package servermanager
import (
"encoding/json"
"fmt"
"net/http"
"time"
"4d63.com/tz"
"github.com/go-chi/chi"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
type RaceWeekendHandler struct {
*BaseHandler
raceWeekendManager *RaceWeekendManager
}
func NewRaceWeekendHandler(baseHandler *BaseHandler, raceWeekendManager *RaceWeekendManager) *RaceWeekendHandler {
return &RaceWeekendHandler{
BaseHandler: baseHandler,
raceWeekendManager: raceWeekendManager,
}
}
type raceWeekendListTemplateVars struct {
BaseTemplateVars
RaceWeekends []*RaceWeekend
}
func (rwh *RaceWeekendHandler) list(w http.ResponseWriter, r *http.Request) {
raceWeekends, err := rwh.raceWeekendManager.ListRaceWeekends()
if err != nil {
logrus.WithError(err).Errorf("couldn't list weekends")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
rwh.viewRenderer.MustLoadTemplate(w, r, "race-weekend/index.html", &raceWeekendListTemplateVars{
RaceWeekends: raceWeekends,
})
}
type raceWeekendViewTemplateVars struct {
BaseTemplateVars
RaceWeekend *RaceWeekend
Account *Account
}
func (rwh *RaceWeekendHandler) view(w http.ResponseWriter, r *http.Request) {
raceWeekend, err := rwh.raceWeekendManager.LoadRaceWeekend(chi.URLParam(r, "raceWeekendID"))
if err != nil {
logrus.WithError(err).Errorf("couldn't load race weekend")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
rwh.viewRenderer.MustLoadTemplate(w, r, "race-weekend/view.html", &raceWeekendViewTemplateVars{
BaseTemplateVars: BaseTemplateVars{
WideContainer: true,
},
RaceWeekend: raceWeekend,
Account: AccountFromRequest(r),
})
}
func (rwh *RaceWeekendHandler) createOrEdit(w http.ResponseWriter, r *http.Request) {
raceWeekendOpts, err := rwh.raceWeekendManager.BuildRaceWeekendTemplateOpts(r)
if err != nil {
logrus.WithError(err).Errorf("couldn't load race weekend")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
rwh.viewRenderer.MustLoadTemplate(w, r, "race-weekend/new.html", raceWeekendOpts)
}
func (rwh *RaceWeekendHandler) delete(w http.ResponseWriter, r *http.Request) {
err := rwh.raceWeekendManager.DeleteRaceWeekend(chi.URLParam(r, "raceWeekendID"))
if err != nil {
logrus.WithError(err).Errorf("couldn't delete race weekend")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
AddFlash(w, r, "Race Weekend successfully deleted!")
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
func (rwh *RaceWeekendHandler) submit(w http.ResponseWriter, r *http.Request) {
raceWeekend, edited, err := rwh.raceWeekendManager.SaveRaceWeekend(r)
if err != nil {
logrus.WithError(err).Errorf("couldn't create race weekend")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if edited {
AddFlash(w, r, "Race Weekend successfully edited!")
http.Redirect(w, r, "/race-weekend/"+raceWeekend.ID.String(), http.StatusFound)
} else {
AddFlash(w, r, "We've created the Race Weekend. Now you need to add some sessions!")
http.Redirect(w, r, "/race-weekend/"+raceWeekend.ID.String()+"/session", http.StatusFound)
}
}
func (rwh *RaceWeekendHandler) sessionConfiguration(w http.ResponseWriter, r *http.Request) {
raceWeekendSessionOpts, err := rwh.raceWeekendManager.BuildRaceWeekendSessionOpts(r)
if err != nil {
logrus.WithError(err).Errorf("couldn't build race weekend session")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
rwh.viewRenderer.MustLoadTemplate(w, r, "custom-race/new.html", raceWeekendSessionOpts)
}
func (rwh *RaceWeekendHandler) submitSessionConfiguration(w http.ResponseWriter, r *http.Request) {
raceWeekend, session, edited, err := rwh.raceWeekendManager.SaveRaceWeekendSession(r)
if err != nil {
logrus.WithError(err).Errorf("couldn't build race weekend session")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if edited {
AddFlash(w, r,
fmt.Sprintf(
"Race Weekend session at %s was successfully edited!",
prettifyName(session.RaceConfig.Track, false),
),
)
} else {
AddFlash(w, r,
fmt.Sprintf(
"Race Weekend session at %s was successfully added!",
prettifyName(session.RaceConfig.Track, false),
),
)
}
if r.FormValue("action") == "saveRaceWeekend" {
// end the race creation flow
http.Redirect(w, r, "/race-weekend/"+raceWeekend.ID.String(), http.StatusFound)
return
}
// add another session
http.Redirect(w, r, "/race-weekend/"+raceWeekend.ID.String()+"/session", http.StatusFound)
}
func (rwh *RaceWeekendHandler) startSession(w http.ResponseWriter, r *http.Request) {
err := rwh.raceWeekendManager.StartSession(chi.URLParam(r, "raceWeekendID"), chi.URLParam(r, "sessionID"), false)
if err != nil {
logrus.WithError(err).Errorf("Could not start Race Weekend session")
AddErrorFlash(w, r, "Couldn't start the Session")
} else {
AddFlash(w, r, "Session started successfully!")
time.Sleep(time.Second * 1)
}
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
func (rwh *RaceWeekendHandler) startPracticeSession(w http.ResponseWriter, r *http.Request) {
err := rwh.raceWeekendManager.StartPracticeSession(chi.URLParam(r, "raceWeekendID"), chi.URLParam(r, "sessionID"))
if err != nil {
logrus.WithError(err).Errorf("Could not start Race Weekend practice session")
AddErrorFlash(w, r, "Couldn't start the Session")
} else {
AddFlash(w, r, "Session started successfully!")
time.Sleep(time.Second * 1)
}
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
func (rwh *RaceWeekendHandler) restartSession(w http.ResponseWriter, r *http.Request) {
err := rwh.raceWeekendManager.RestartSession(chi.URLParam(r, "raceWeekendID"), chi.URLParam(r, "sessionID"))
if err != nil {
logrus.WithError(err).Errorf("Could not restart Race Weekend session")
AddErrorFlash(w, r, "Couldn't restart the Session")
} else {
AddFlash(w, r, "Session restarted successfully!")
time.Sleep(time.Second * 1)
}
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
func (rwh *RaceWeekendHandler) cancelSession(w http.ResponseWriter, r *http.Request) {
err := rwh.raceWeekendManager.CancelSession(chi.URLParam(r, "raceWeekendID"), chi.URLParam(r, "sessionID"))
if err != nil {
logrus.WithError(err).Errorf("Could not cancel Race Weekend session")
AddErrorFlash(w, r, "Couldn't cancel the Session")
} else {
AddFlash(w, r, "Session canceled successfully!")
time.Sleep(time.Second * 1)
}
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
func (rwh *RaceWeekendHandler) deleteSession(w http.ResponseWriter, r *http.Request) {
err := rwh.raceWeekendManager.DeleteSession(chi.URLParam(r, "raceWeekendID"), chi.URLParam(r, "sessionID"))
if err != nil {
logrus.WithError(err).Errorf("Could not delete Race Weekend session")
AddErrorFlash(w, r, "Couldn't delete the Session")
} else {
AddFlash(w, r, "Session deleted successfully!")
}
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
type raceWeekendSessionImportTemplateVars struct {
BaseTemplateVars
Results []SessionResults
RaceWeekendID string
Session *RaceWeekendSession
}
func (rwh *RaceWeekendHandler) importSessionResults(w http.ResponseWriter, r *http.Request) {
raceWeekendID := chi.URLParam(r, "raceWeekendID")
sessionID := chi.URLParam(r, "sessionID")
if r.Method == http.MethodPost {
err := rwh.raceWeekendManager.ImportSession(raceWeekendID, sessionID, r)
if err != nil {
logrus.WithError(err).Errorf("Could not import race weekend session")
AddErrorFlash(w, r, "Could not import race weekend session files")
} else {
AddFlash(w, r, "Successfully imported session files!")
http.Redirect(w, r, "/race-weekend/"+raceWeekendID, http.StatusFound)
return
}
}
session, results, err := rwh.raceWeekendManager.ListAvailableResultsFilesForSession(raceWeekendID, sessionID)
if err != nil {
logrus.WithError(err).Errorf("Couldn't load session files")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
rwh.viewRenderer.MustLoadTemplate(w, r, "race-weekend/import-session.html", &raceWeekendSessionImportTemplateVars{
Results: results,
RaceWeekendID: raceWeekendID,
Session: session,
})
}
type raceWeekendFilterTemplateVars struct {
BaseTemplateVars
RaceWeekend *RaceWeekend
ParentSession, ChildSession *RaceWeekendSession
ResultsAvailableForSorting []SessionResults
Filter *RaceWeekendSessionToSessionFilter
AvailableSorters []RaceWeekendEntryListSorterDescription
ParentSessionResults []*RaceWeekendSessionEntrant
ChampionshipClasses map[uuid.UUID]*ChampionshipClass
}
func (rwh *RaceWeekendHandler) manageFilters(w http.ResponseWriter, r *http.Request) {
raceWeekendID := chi.URLParam(r, "raceWeekendID")
parentSessionID := r.URL.Query().Get("parentSessionID")
childSessionID := r.URL.Query().Get("childSessionID")
raceWeekend, parentSession, childSession, err := rwh.raceWeekendManager.FindConnectedSessions(raceWeekendID, parentSessionID, childSessionID)
if err != nil {
logrus.WithError(err).Errorf("Couldn't load connected sessions")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
filter, err := raceWeekend.GetFilterOrUseDefault(parentSessionID, childSessionID)
if err != nil {
logrus.WithError(err).Errorf("Couldn't load session filters")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
sessionResults, err := rwh.raceWeekendManager.ListAvailableResultsFilesForSorting(raceWeekend, childSession)
if err != nil {
logrus.WithError(err).Error("Couldn't list results files for sorting")
}
parentSessionResults, err := parentSession.FinishingGrid(raceWeekend)
if err != nil {
logrus.WithError(err).Errorf("Couldn't load previous session results")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
var championshipClasses map[uuid.UUID]*ChampionshipClass
if raceWeekend.HasLinkedChampionship() {
championshipClasses = make(map[uuid.UUID]*ChampionshipClass)
for _, result := range parentSessionResults {
class := result.ChampionshipClass(raceWeekend)
championshipClasses[class.ID] = class
}
}
rwh.viewRenderer.MustLoadPartial(w, r, "race-weekend/popups/manage-filters.html", &raceWeekendFilterTemplateVars{
RaceWeekend: raceWeekend,
ParentSession: parentSession,
ChildSession: childSession,
ResultsAvailableForSorting: sessionResults,
Filter: filter,
AvailableSorters: RaceWeekendEntryListSorters,
ParentSessionResults: parentSessionResults,
ChampionshipClasses: championshipClasses,
})
}
func (rwh *RaceWeekendHandler) gridPreview(w http.ResponseWriter, r *http.Request) {
raceWeekendID := chi.URLParam(r, "raceWeekendID")
parentSessionID := r.URL.Query().Get("parentSessionID")
childSessionID := r.URL.Query().Get("childSessionID")
var filter *RaceWeekendSessionToSessionFilter
if err := json.NewDecoder(r.Body).Decode(&filter); err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
filter.IsPreview = true
previewResponse, err := rwh.raceWeekendManager.PreviewGrid(raceWeekendID, parentSessionID, childSessionID, filter)
if err != nil {
logrus.WithError(err).Errorf("Couldn't preview session grid")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(previewResponse)
}
func (rwh *RaceWeekendHandler) updateGrid(w http.ResponseWriter, r *http.Request) {
raceWeekendID := chi.URLParam(r, "raceWeekendID")
parentSessionID := r.URL.Query().Get("parentSessionID")
childSessionID := r.URL.Query().Get("childSessionID")
var filter *RaceWeekendSessionToSessionFilter
if err := json.NewDecoder(r.Body).Decode(&filter); err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
if err := rwh.raceWeekendManager.UpdateGrid(raceWeekendID, parentSessionID, childSessionID, filter); err != nil {
logrus.WithError(err).Errorf("Couldn't update session grid")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
type raceWeekendManageEntryListTemplateVars struct {
BaseTemplateVars
RaceWeekend *RaceWeekend
Session *RaceWeekendSession
AvailableSorters []RaceWeekendEntryListSorterDescription
}
func (rwh *RaceWeekendHandler) manageEntryList(w http.ResponseWriter, r *http.Request) {
raceWeekendID := chi.URLParam(r, "raceWeekendID")
sessionID := r.URL.Query().Get("sessionID")
raceWeekend, session, err := rwh.raceWeekendManager.FindSession(raceWeekendID, sessionID)
if err != nil {
logrus.WithError(err).Errorf("Couldn't load manage entry list popup")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
rwh.viewRenderer.MustLoadPartial(w, r, "race-weekend/popups/manage-entrylist.html", &raceWeekendManageEntryListTemplateVars{
RaceWeekend: raceWeekend,
Session: session,
AvailableSorters: RaceWeekendEntryListSorters,
})
}
func (rwh *RaceWeekendHandler) entryListPreview(w http.ResponseWriter, r *http.Request) {
raceWeekendID := chi.URLParam(r, "raceWeekendID")
sessionID := r.URL.Query().Get("sessionID")
sortType := r.URL.Query().Get("sortType")
reverseNumber := formValueAsInt(r.URL.Query().Get("reverseGrid"))
previewResponse, err := rwh.raceWeekendManager.PreviewSessionEntryList(raceWeekendID, sessionID, sortType, reverseNumber)
if err != nil {
logrus.WithError(err).Errorf("Couldn't preview session grid")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(previewResponse)
}
func (rwh *RaceWeekendHandler) updateEntryList(w http.ResponseWriter, r *http.Request) {
raceWeekendID := chi.URLParam(r, "raceWeekendID")
parentSessionID := r.URL.Query().Get("sessionID")
sortType := r.URL.Query().Get("sortType")
reverseNumber := formValueAsInt(r.URL.Query().Get("reverseGrid"))
if err := rwh.raceWeekendManager.UpdateSessionSorting(raceWeekendID, parentSessionID, sortType, reverseNumber); err != nil {
logrus.WithError(err).Errorf("Couldn't update session entrylist sorting")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func (rwh *RaceWeekendHandler) export(w http.ResponseWriter, r *http.Request) {
raceWeekend, err := rwh.raceWeekendManager.LoadRaceWeekend(chi.URLParam(r, "raceWeekendID"))
if err != nil {
logrus.WithError(err).Errorf("couldn't export race weeeknd")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if !AccountFromRequest(r).HasGroupPrivilege(GroupWrite) {
// if you don't have write access or above you can't see the replacement password
for _, session := range raceWeekend.Sessions {
session.ReplacementPassword = ""
}
}
w.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.json"`, raceWeekend.Name))
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
_ = enc.Encode(raceWeekend)
}
func (rwh *RaceWeekendHandler) importRaceWeekend(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
raceWeekendID, err := rwh.raceWeekendManager.ImportRaceWeekend(r.FormValue("import"))
if err != nil {
logrus.WithError(err).Error("could not import race weekend")
AddErrorFlash(w, r, "Sorry, we couldn't import that Race Weekend! Check your JSON formatting.")
} else {
AddFlash(w, r, "Race Weekend successfully imported!")
http.Redirect(w, r, "/race-weekend/"+raceWeekendID, http.StatusFound)
}
}
rwh.viewRenderer.MustLoadTemplate(w, r, "race-weekend/import-raceweekend.html", nil)
}
func (rwh *RaceWeekendHandler) scheduleSession(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
logrus.WithError(err).Errorf("couldn't parse schedule race form")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
championshipID := chi.URLParam(r, "raceWeekendID")
championshipEventID := chi.URLParam(r, "sessionID")
dateString := r.FormValue("session-schedule-date")
timeString := r.FormValue("session-schedule-time")
timezone := r.FormValue("session-schedule-timezone")
startWhenParentFinished := formValueAsInt(r.FormValue("session-start-after-parent")) == 1
var message string
var date time.Time
if !startWhenParentFinished {
var location *time.Location
location, err := tz.LoadLocation(timezone)
if err != nil {
logrus.WithError(err).Errorf("could not find location: %s", location)
location = time.Local
}
// Parse time in correct time zone
date, err = time.ParseInLocation("2006-01-02-15:04", dateString+"-"+timeString, location)
if err != nil {
logrus.WithError(err).Errorf("couldn't parse schedule race weekend session date")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
message = fmt.Sprintf("We have scheduled the Race Weekend Session to begin at %s", date.Format(time.RFC1123))
} else {
message = "We have scheduled the Race Weekend Session to begin after the parent session(s) complete."
}
err := rwh.raceWeekendManager.ScheduleSession(championshipID, championshipEventID, date, startWhenParentFinished)
if err != nil {
logrus.WithError(err).Errorf("couldn't schedule race weekend session")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
AddFlash(w, r, message)
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
func (rwh *RaceWeekendHandler) removeSessionSchedule(w http.ResponseWriter, r *http.Request) {
err := rwh.raceWeekendManager.DeScheduleSession(chi.URLParam(r, "raceWeekendID"), chi.URLParam(r, "sessionID"))
if err != nil {
logrus.WithError(err).Errorf("couldn't de-schedule race weekend session")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
http.Redirect(w, r, r.Referer(), http.StatusFound)
}