-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcourse_outcomes.go
More file actions
742 lines (688 loc) · 25 KB
/
course_outcomes.go
File metadata and controls
742 lines (688 loc) · 25 KB
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
package httpserver
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/lextures/lextures/server/internal/apierr"
"github.com/lextures/lextures/server/internal/courseroles"
"github.com/lextures/lextures/server/internal/models/courseoutcomesapi"
"github.com/lextures/lextures/server/internal/repos/course"
"github.com/lextures/lextures/server/internal/repos/courseoutcomes"
"github.com/lextures/lextures/server/internal/repos/enrollment"
outcomessvc "github.com/lextures/lextures/server/internal/service/outcomes"
)
type courseOutcomesListResponse struct {
EnrolledLearners int `json:"enrolledLearners"`
Outcomes []courseOutcomeAPI `json:"outcomes"`
}
type courseOutcomeAPI struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
SortOrder int `json:"sortOrder"`
RollupAvgScorePercent *float64 `json:"rollupAvgScorePercent"`
Links []courseOutcomeLinkAPI `json:"links"`
}
type courseOutcomeLinkAPI struct {
ID string `json:"id"`
SubOutcomeID *string `json:"subOutcomeId,omitempty"`
StructureItemID string `json:"structureItemId"`
TargetKind string `json:"targetKind"`
QuizQuestionID string `json:"quizQuestionId"`
MeasurementLevel string `json:"measurementLevel"`
IntensityLevel string `json:"intensityLevel"`
ItemTitle string `json:"itemTitle"`
ItemKind string `json:"itemKind"`
Progress courseOutcomeLinkProgress `json:"progress"`
}
type courseOutcomeLinkProgress struct {
AvgScorePercent *float64 `json:"avgScorePercent"`
GradedLearners int `json:"gradedLearners"`
EnrolledLearners int `json:"enrolledLearners"`
}
type courseOutcomeSubOutcomeAPI struct {
ID string `json:"id"`
OutcomeID string `json:"outcomeId"`
Title string `json:"title"`
Description string `json:"description"`
SortOrder int `json:"sortOrder"`
}
func learningOutcomeRowToAPI(row courseoutcomes.LearningOutcomeRow) courseOutcomeAPI {
return courseOutcomeAPI{
ID: row.ID.String(),
Title: row.Title,
Description: row.Description,
SortOrder: int(row.SortOrder),
RollupAvgScorePercent: nil,
Links: []courseOutcomeLinkAPI{},
}
}
func outcomeLinkProgress(ctx context.Context, pool *pgxpool.Pool, courseID uuid.UUID, enrolled int32, link courseoutcomes.OutcomeLinkWithItemRow) (courseoutcomes.OutcomeLinkProgress, error) {
switch link.TargetKind {
case "quiz_question":
qid := strings.TrimSpace(link.QuizQuestionID)
return courseoutcomes.ProgressForQuizQuestion(ctx, pool, courseID, link.StructureItemID, qid, enrolled)
case "quiz", "assignment":
return courseoutcomes.ProgressForGradedItem(ctx, pool, courseID, link.StructureItemID, link.ItemKind, enrolled)
default:
return courseoutcomes.OutcomeLinkProgress{
GradedLearners: 0,
EnrolledLearners: enrolled,
}, nil
}
}
func courseOutcomeLinkHTTP(link courseoutcomes.OutcomeLinkWithItemRow, prog courseoutcomes.OutcomeLinkProgress) courseOutcomeLinkAPI {
var sub *string
if link.SubOutcomeID != nil {
s := link.SubOutcomeID.String()
sub = &s
}
var avg *float64
if prog.AvgScorePercent != nil {
v := float64(*prog.AvgScorePercent)
avg = &v
}
return courseOutcomeLinkAPI{
ID: link.ID.String(),
SubOutcomeID: sub,
StructureItemID: link.StructureItemID.String(),
TargetKind: link.TargetKind,
QuizQuestionID: link.QuizQuestionID,
MeasurementLevel: link.MeasurementLevel,
IntensityLevel: link.IntensityLevel,
ItemTitle: link.ItemTitle,
ItemKind: link.ItemKind,
Progress: courseOutcomeLinkProgress{
AvgScorePercent: avg,
GradedLearners: int(prog.GradedLearners),
EnrolledLearners: int(prog.EnrolledLearners),
},
}
}
func courseOutcomeLinkModel(link courseoutcomes.OutcomeLinkWithItemRow, prog courseoutcomes.OutcomeLinkProgress) courseoutcomesapi.CourseOutcomeLinkAPI {
return courseoutcomesapi.CourseOutcomeLinkAPI{
ID: link.ID,
SubOutcomeID: link.SubOutcomeID,
StructureItemID: link.StructureItemID,
TargetKind: link.TargetKind,
QuizQuestionID: link.QuizQuestionID,
MeasurementLevel: link.MeasurementLevel,
IntensityLevel: link.IntensityLevel,
ItemTitle: link.ItemTitle,
ItemKind: link.ItemKind,
Progress: courseoutcomes.ProgressToMapJSON(prog),
}
}
func buildCourseOutcomeAPI(
ctx context.Context,
pool *pgxpool.Pool,
courseID uuid.UUID,
row courseoutcomes.LearningOutcomeRow,
links []courseoutcomes.OutcomeLinkWithItemRow,
enrolled int32,
) (courseOutcomeAPI, error) {
modelLinks := make([]courseoutcomesapi.CourseOutcomeLinkAPI, 0, len(links))
httpLinks := make([]courseOutcomeLinkAPI, 0, len(links))
for i := range links {
prog, err := outcomeLinkProgress(ctx, pool, courseID, enrolled, links[i])
if err != nil {
return courseOutcomeAPI{}, err
}
modelLinks = append(modelLinks, courseOutcomeLinkModel(links[i], prog))
httpLinks = append(httpLinks, courseOutcomeLinkHTTP(links[i], prog))
}
api := learningOutcomeRowToAPI(row)
api.Links = httpLinks
if rollup := outcomessvc.RollupAvgForOutcomeLinks(modelLinks); rollup != nil {
v := float64(*rollup)
api.RollupAvgScorePercent = &v
}
return api, nil
}
func groupOutcomeLinksByOutcome(links []courseoutcomes.OutcomeLinkWithItemRow) map[uuid.UUID][]courseoutcomes.OutcomeLinkWithItemRow {
by := make(map[uuid.UUID][]courseoutcomes.OutcomeLinkWithItemRow)
for i := range links {
id := links[i].OutcomeID
by[id] = append(by[id], links[i])
}
return by
}
func outcomeSubOutcomeRowToAPI(row courseoutcomes.OutcomeSubOutcomeRow) courseOutcomeSubOutcomeAPI {
return courseOutcomeSubOutcomeAPI{
ID: row.ID.String(),
OutcomeID: row.OutcomeID.String(),
Title: row.Title,
Description: row.Description,
SortOrder: int(row.SortOrder),
}
}
func parseCourseOutcomePatchInput(raw map[string]json.RawMessage) (courseoutcomes.UpdateOutcomeInput, error) {
var in courseoutcomes.UpdateOutcomeInput
if v, ok := raw["title"]; ok {
var s string
if err := json.Unmarshal(v, &s); err != nil {
return in, err
}
t := strings.TrimSpace(s)
if t == "" {
return in, errOutcomePatchEmptyTitle{}
}
in.Title = &t
}
if v, ok := raw["description"]; ok {
var s string
if err := json.Unmarshal(v, &s); err != nil {
return in, err
}
in.Description = &s
}
if v, ok := raw["moduleStructureItemId"]; ok {
s := strings.TrimSpace(string(v))
if s == "null" {
var nilModule *uuid.UUID
in.ModuleStructureItemID = &nilModule
} else {
var sid string
if err := json.Unmarshal(v, &sid); err != nil {
return in, err
}
sid = strings.TrimSpace(sid)
if sid == "" {
return in, errOutcomePatchInvalidModuleID{}
}
id, err := uuid.Parse(sid)
if err != nil {
return in, errOutcomePatchInvalidModuleID{}
}
pid := id
pp := &pid
in.ModuleStructureItemID = &pp
}
}
return in, nil
}
type errOutcomePatchEmptyTitle struct{}
func (errOutcomePatchEmptyTitle) Error() string { return "title cannot be empty" }
type errOutcomePatchInvalidModuleID struct{}
func (errOutcomePatchInvalidModuleID) Error() string { return "invalid moduleStructureItemId" }
// handleCourseOutcomePatch is PATCH /api/v1/courses/{course_code}/outcomes/{outcome_id}.
func (d Deps) handleCourseOutcomePatch() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method != http.MethodPatch {
w.Header().Set("Allow", http.MethodPatch+","+http.MethodOptions)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
courseCode, viewer, ok := d.requireCourseAccess(w, r)
if !ok {
return
}
perm := "course:" + courseCode + ":item:create"
hasPerm, err := courseroles.UserHasPermission(r.Context(), d.Pool, viewer, perm)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to verify permissions.")
return
}
if !hasPerm {
apierr.WriteJSON(w, http.StatusForbidden, apierr.CodeForbidden, "You do not have permission to edit outcomes.")
return
}
outcomeID, err := uuid.Parse(chi.URLParam(r, "outcome_id"))
if err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid outcome id.")
return
}
var raw map[string]json.RawMessage
if err := json.NewDecoder(r.Body).Decode(&raw); err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid JSON body.")
return
}
if len(raw) == 0 {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Provide at least one field to update.")
return
}
in, err := parseCourseOutcomePatchInput(raw)
if err != nil {
switch err.(type) {
case errOutcomePatchEmptyTitle:
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Title cannot be empty.")
case errOutcomePatchInvalidModuleID:
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid moduleStructureItemId.")
default:
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid patch payload.")
}
return
}
ctx := r.Context()
cid, err := course.GetIDByCourseCode(ctx, d.Pool, courseCode)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load course.")
return
}
if cid == nil {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Course not found.")
return
}
updated, err := courseoutcomes.UpdateOutcome(ctx, d.Pool, *cid, outcomeID, in)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to update outcome.")
return
}
if updated == nil {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Outcome not found.")
return
}
students, err := enrollment.ListStudentUsersForCourseCode(ctx, d.Pool, courseCode, nil)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load enrollments.")
return
}
enrolled := int32(len(students))
linkRows, err := courseoutcomes.ListLinksForOutcome(ctx, d.Pool, *cid, outcomeID)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load outcome links.")
return
}
out, err := buildCourseOutcomeAPI(ctx, d.Pool, *cid, *updated, linkRows, enrolled)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to build outcome response.")
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(out)
}
}
// handleCourseOutcomesPost is POST /api/v1/courses/{course_code}/outcomes.
func (d Deps) handleCourseOutcomesPost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost+","+http.MethodOptions)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
courseCode, viewer, ok := d.requireCourseAccess(w, r)
if !ok {
return
}
perm := "course:" + courseCode + ":item:create"
hasPerm, err := courseroles.UserHasPermission(r.Context(), d.Pool, viewer, perm)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to verify permissions.")
return
}
if !hasPerm {
apierr.WriteJSON(w, http.StatusForbidden, apierr.CodeForbidden, "You do not have permission to edit outcomes.")
return
}
var body struct {
Title string `json:"title"`
Description string `json:"description"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid JSON body.")
return
}
title := strings.TrimSpace(body.Title)
if title == "" {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Title is required.")
return
}
desc := strings.TrimSpace(body.Description)
ctx := r.Context()
cid, err := course.GetIDByCourseCode(ctx, d.Pool, courseCode)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load course.")
return
}
if cid == nil {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Course not found.")
return
}
row, err := courseoutcomes.InsertOutcome(ctx, d.Pool, *cid, title, desc)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to create outcome.")
return
}
out := learningOutcomeRowToAPI(*row)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(out)
}
}
// handleCourseOutcomesList is GET /api/v1/courses/{course_code}/outcomes.
func (d Deps) handleCourseOutcomesList() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet+","+http.MethodOptions)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
courseCode, viewer, ok := d.requireCourseAccess(w, r)
if !ok {
return
}
perm := "course:" + courseCode + ":item:create"
hasPerm, err := courseroles.UserHasPermission(r.Context(), d.Pool, viewer, perm)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to verify permissions.")
return
}
if !hasPerm {
apierr.WriteJSON(w, http.StatusForbidden, apierr.CodeForbidden, "You do not have permission to view outcomes.")
return
}
ctx := r.Context()
cid, err := course.GetIDByCourseCode(ctx, d.Pool, courseCode)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load course.")
return
}
if cid == nil {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Course not found.")
return
}
rows, err := courseoutcomes.ListOutcomes(ctx, d.Pool, *cid)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load outcomes.")
return
}
students, err := enrollment.ListStudentUsersForCourseCode(ctx, d.Pool, courseCode, nil)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load enrollments.")
return
}
enrolled := int32(len(students))
allLinks, err := courseoutcomes.ListLinksForCourse(ctx, d.Pool, *cid)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load outcome links.")
return
}
byOutcome := groupOutcomeLinksByOutcome(allLinks)
outcomes := make([]courseOutcomeAPI, 0, len(rows))
for i := range rows {
linksForO := byOutcome[rows[i].ID]
apiO, err := buildCourseOutcomeAPI(ctx, d.Pool, *cid, rows[i], linksForO, enrolled)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to build outcomes response.")
return
}
outcomes = append(outcomes, apiO)
}
out := courseOutcomesListResponse{
EnrolledLearners: len(students),
Outcomes: outcomes,
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(out)
}
}
// handleCourseOutcomeSubOutcomesPost is POST /api/v1/courses/{course_code}/outcomes/{outcome_id}/sub-outcomes.
func (d Deps) handleCourseOutcomeSubOutcomesPost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost+","+http.MethodOptions)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
courseCode, viewer, ok := d.requireCourseAccess(w, r)
if !ok {
return
}
perm := "course:" + courseCode + ":item:create"
hasPerm, err := courseroles.UserHasPermission(r.Context(), d.Pool, viewer, perm)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to verify permissions.")
return
}
if !hasPerm {
apierr.WriteJSON(w, http.StatusForbidden, apierr.CodeForbidden, "You do not have permission to edit outcomes.")
return
}
outcomeID, err := uuid.Parse(chi.URLParam(r, "outcome_id"))
if err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid outcome id.")
return
}
var body struct {
Title string `json:"title"`
Description string `json:"description"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid JSON body.")
return
}
title := strings.TrimSpace(body.Title)
if title == "" {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Title is required.")
return
}
desc := strings.TrimSpace(body.Description)
ctx := r.Context()
cid, err := course.GetIDByCourseCode(ctx, d.Pool, courseCode)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load course.")
return
}
if cid == nil {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Course not found.")
return
}
row, err := courseoutcomes.InsertSubOutcome(ctx, d.Pool, *cid, outcomeID, title, desc)
if err != nil {
if errors.Is(err, courseoutcomes.ErrLearningOutcomeNotInCourse) {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Outcome not found.")
return
}
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to create sub-outcome.")
return
}
out := outcomeSubOutcomeRowToAPI(*row)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(out)
}
}
// handleCourseOutcomeLinksPost is POST /api/v1/courses/{course_code}/outcomes/{outcome_id}/links.
func (d Deps) handleCourseOutcomeLinksPost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost+","+http.MethodOptions)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
courseCode, viewer, ok := d.requireCourseAccess(w, r)
if !ok {
return
}
perm := "course:" + courseCode + ":item:create"
hasPerm, err := courseroles.UserHasPermission(r.Context(), d.Pool, viewer, perm)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to verify permissions.")
return
}
if !hasPerm {
apierr.WriteJSON(w, http.StatusForbidden, apierr.CodeForbidden, "You do not have permission to edit outcomes.")
return
}
outcomeID, err := uuid.Parse(chi.URLParam(r, "outcome_id"))
if err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid outcome id.")
return
}
var req courseoutcomesapi.PostCourseOutcomeLinkRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid JSON body.")
return
}
if req.StructureItemID == uuid.Nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "structureItemId is required.")
return
}
ctx := r.Context()
cid, err := course.GetIDByCourseCode(ctx, d.Pool, courseCode)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load course.")
return
}
if cid == nil {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Course not found.")
return
}
apiLink, err := outcomessvc.AddOutcomeLink(ctx, d.Pool, *cid, courseCode, outcomeID, &req)
if err != nil {
var se *outcomessvc.ServiceError
if errors.As(err, &se) {
switch se.Kind {
case outcomessvc.ErrorKindInvalidInput:
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, se.Message)
case outcomessvc.ErrorKindNotFound:
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, se.Message)
default:
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, se.Message)
}
return
}
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to create outcome link.")
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(apiLink)
}
}
// handleCourseOutcomeDelete is DELETE /api/v1/courses/{course_code}/outcomes/{outcome_id}.
func (d Deps) handleCourseOutcomeDelete() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method != http.MethodDelete {
w.Header().Set("Allow", http.MethodDelete+","+http.MethodOptions)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
courseCode, viewer, ok := d.requireCourseAccess(w, r)
if !ok {
return
}
perm := "course:" + courseCode + ":item:create"
hasPerm, err := courseroles.UserHasPermission(r.Context(), d.Pool, viewer, perm)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to verify permissions.")
return
}
if !hasPerm {
apierr.WriteJSON(w, http.StatusForbidden, apierr.CodeForbidden, "You do not have permission to edit outcomes.")
return
}
outcomeID, err := uuid.Parse(chi.URLParam(r, "outcome_id"))
if err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid outcome id.")
return
}
ctx := r.Context()
cid, err := course.GetIDByCourseCode(ctx, d.Pool, courseCode)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load course.")
return
}
if cid == nil {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Course not found.")
return
}
deleted, err := courseoutcomes.DeleteOutcome(ctx, d.Pool, *cid, outcomeID)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to delete outcome.")
return
}
if !deleted {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Outcome not found.")
return
}
w.WriteHeader(http.StatusNoContent)
}
}
// handleCourseOutcomeLinkDelete is DELETE /api/v1/courses/{course_code}/outcomes/{outcome_id}/links/{link_id}.
func (d Deps) handleCourseOutcomeLinkDelete() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method != http.MethodDelete {
w.Header().Set("Allow", http.MethodDelete+","+http.MethodOptions)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
courseCode, viewer, ok := d.requireCourseAccess(w, r)
if !ok {
return
}
perm := "course:" + courseCode + ":item:create"
hasPerm, err := courseroles.UserHasPermission(r.Context(), d.Pool, viewer, perm)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to verify permissions.")
return
}
if !hasPerm {
apierr.WriteJSON(w, http.StatusForbidden, apierr.CodeForbidden, "You do not have permission to edit outcomes.")
return
}
outcomeID, err := uuid.Parse(chi.URLParam(r, "outcome_id"))
if err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid outcome id.")
return
}
linkID, err := uuid.Parse(chi.URLParam(r, "link_id"))
if err != nil {
apierr.WriteJSON(w, http.StatusBadRequest, apierr.CodeInvalidInput, "Invalid link id.")
return
}
ctx := r.Context()
cid, err := course.GetIDByCourseCode(ctx, d.Pool, courseCode)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to load course.")
return
}
if cid == nil {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Course not found.")
return
}
deleted, err := courseoutcomes.DeleteLink(ctx, d.Pool, *cid, outcomeID, linkID)
if err != nil {
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.CodeInternal, "Failed to delete outcome link.")
return
}
if !deleted {
apierr.WriteJSON(w, http.StatusNotFound, apierr.CodeNotFound, "Link not found.")
return
}
w.WriteHeader(http.StatusNoContent)
}
}