forked from openedx/openedx-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_v2.py
More file actions
4667 lines (3957 loc) · 173 KB
/
api_v2.py
File metadata and controls
4667 lines (3957 loc) · 173 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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Instructor API v2 views.
This module contains the v2 API endpoints for instructor functionality.
These APIs are designed to be consumed by MFEs and other API clients.
"""
import csv
import io
import json
import logging
import re
from dataclasses import dataclass
from datetime import datetime
from typing import Optional, Tuple # noqa: UP035
import edx_api_doc_tools as apidocs
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.validators import validate_email
from django.db import transaction
from django.db.models import Q
from django.http import HttpResponse
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.html import strip_tags
from django.utils.translation import gettext as _
from django.views.decorators.cache import cache_control
from django_filters.rest_framework import DjangoFilterBackend
from edx_proctoring.api import (
add_allowance_for_user,
get_all_exam_attempts,
get_all_exams_for_course,
get_allowances_for_course,
get_exam_by_id,
get_filtered_exam_attempts,
get_user_attempts_by_exam_id,
remove_allowance_for_user,
remove_exam_attempt,
)
from edx_proctoring.exceptions import (
ProctoredBaseException,
ProctoredExamNotFoundException,
)
from edx_rest_framework_extensions.paginators import DefaultPagination
from edx_when import api as edx_when_api
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey, UsageKey
from pytz import UTC
from rest_framework import status
from rest_framework.exceptions import NotFound
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from submissions import api as sub_api
from common.djangoapps.student.api import is_user_enrolled_in_course
from common.djangoapps.student.models import (
ALLOWEDTOENROLL_TO_ENROLLED,
ALLOWEDTOENROLL_TO_UNENROLLED,
DEFAULT_TRANSITION_STATE,
ENROLLED_TO_ENROLLED,
ENROLLED_TO_UNENROLLED,
UNENROLLED_TO_ALLOWEDTOENROLL,
UNENROLLED_TO_ENROLLED,
UNENROLLED_TO_UNENROLLED,
CourseEnrollment,
ManualEnrollmentAudit,
)
from common.djangoapps.student.models.user import get_user_by_username_or_email
from common.djangoapps.student.roles import CourseBetaTesterRole
from common.djangoapps.util.json_request import JsonResponseBadRequest
from lms.djangoapps.certificates import api as certs_api
from lms.djangoapps.certificates.data import CertificateStatuses
from lms.djangoapps.certificates.models import (
CertificateAllowlist,
CertificateGenerationHistory,
CertificateInvalidation,
GeneratedCertificate,
)
from lms.djangoapps.course_home_api.toggles import course_home_mfe_progress_tab_is_active
from lms.djangoapps.courseware.access import has_access
from lms.djangoapps.courseware.courses import get_course_with_access
from lms.djangoapps.courseware.models import StudentModule
from lms.djangoapps.courseware.tabs import get_course_tab_list
from lms.djangoapps.instructor import enrollment, permissions
from lms.djangoapps.instructor.access import (
FORUM_ROLES,
INSTRUCTOR_DASHBOARD_ROLE_SORT_ORDER,
ROLE_DISPLAY_NAMES,
ROLES,
allow_access,
is_forum_role,
list_forum_members,
list_with_level,
revoke_access,
update_forum_role,
)
from lms.djangoapps.instructor.constants import ReportType
from lms.djangoapps.instructor.enrollment import (
enroll_email,
get_email_params,
get_user_email_language,
send_beta_role_email,
unenroll_email,
)
from lms.djangoapps.instructor.ora import get_open_response_assessment_list, get_ora_summary
from lms.djangoapps.instructor.views.api import _display_unit, get_student_from_identifier
from lms.djangoapps.instructor.views.instructor_task_helpers import extract_task_features
from lms.djangoapps.instructor_analytics import basic as instructor_analytics_basic
from lms.djangoapps.instructor_analytics import csvs as instructor_analytics_csvs
from lms.djangoapps.instructor_task import api as task_api
from lms.djangoapps.instructor_task.api_helper import AlreadyRunningError, QueueConnectionError
from lms.djangoapps.instructor_task.models import InstructorTask, ReportStore
from lms.djangoapps.instructor_task.tasks_helper.utils import upload_csv_file_to_report_store
from openedx.core.djangoapps.course_groups.cohorts import is_course_cohorted
from openedx.core.djangoapps.schedules.models import Schedule
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from openedx.core.lib.api.view_utils import DeveloperErrorViewMixin
from openedx.core.lib.courses import get_course_by_id
from openedx.features.course_experience.url_helpers import get_learning_mfe_home_url
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.exceptions import ItemNotFoundError
from .filters_v2 import CourseEnrollmentFilter
from .serializers_v2 import (
AsyncOperationResultSerializer,
BetaTesterModifyRequestSerializerV2,
BetaTesterModifyResponseSerializerV2,
BlockDueDateSerializerV2,
BulkAllowanceRequestSerializer,
CertificateExceptionSerializer,
CertificateGenerationHistorySerializer,
CertificateInvalidationSerializer,
CourseEnrollmentSerializerV2,
CourseInformationSerializerV2,
CourseTeamModifySerializer,
CourseTeamRevokeSerializer,
EnrollmentModifyRequestSerializerV2,
EnrollmentModifyResponseSerializerV2,
ExamAllowanceRequestSerializer,
ExamAllowanceSerializer,
ExamAttemptSerializer,
InstructorTaskListSerializer,
IssuedCertificateSerializer,
LearnerInputSerializer,
LearnerSerializer,
ORASerializer,
ORASummarySerializer,
ProblemSerializer,
ProctoringSettingsSerializer,
ProctoringSettingsUpdateSerializer,
RegenerateCertificatesSerializer,
RemoveCertificateExceptionSerializer,
RemoveCertificateInvalidationSerializer,
ScoreOverrideRequestSerializer,
SpecialExamSerializer,
SyncOperationResultSerializer,
TaskStatusSerializer,
ToggleCertificateGenerationSerializer,
UnitExtensionSerializer,
derive_exam_type,
)
from .tools import find_unit, get_units_with_due_date, keep_field_private, set_due_date_extension, title_or_url
User = get_user_model()
log = logging.getLogger(__name__)
VALID_TEAM_ROLES = frozenset(ROLES.keys()) | frozenset(FORUM_ROLES)
class CourseMetadataView(DeveloperErrorViewMixin, APIView):
"""
**Use Cases**
Retrieve comprehensive course metadata including enrollment counts, dashboard configuration,
permissions, and navigation sections.
"""
permission_classes = (IsAuthenticated, permissions.InstructorPermission)
permission_name = permissions.VIEW_DASHBOARD
@apidocs.schema(
parameters=[
apidocs.string_parameter(
'course_id',
apidocs.ParameterLocation.PATH,
description="Course key for the course.",
),
],
responses={
200: CourseInformationSerializerV2,
401: "The requesting user is not authenticated.",
403: "The requesting user lacks instructor access to the course.",
404: "The requested course does not exist.",
},
)
def get(self, request, course_id):
"""
Retrieve comprehensive course information including metadata, enrollment statistics,
dashboard configuration, and user permissions.
**Use Cases**
Retrieve comprehensive course metadata including enrollment counts, dashboard configuration,
permissions, and navigation sections.
**Example Requests**
GET /api/instructor/v2/courses/{course_id}
**Response Values**
{
"course_id": "course-v1:edX+DemoX+Demo_Course",
"display_name": "Demonstration Course",
"org": "edX",
"course_number": "DemoX",
"enrollment_start": "2013-02-05T00:00:00Z",
"enrollment_end": null,
"start": "2013-02-05T05:00:00Z",
"end": "2024-12-31T23:59:59Z",
"pacing": "instructor",
"has_started": true,
"has_ended": false,
"total_enrollment": 150,
"enrollment_counts": {
"total": 150,
"audit": 100,
"verified": 40,
"honor": 10
},
"num_sections": 12,
"grade_cutoffs": "A is 0.9, B is 0.8, C is 0.7, D is 0.6",
"course_errors": [],
"studio_url": "https://studio.example.com/course/course-v1:edX+DemoX+2024",
# May be null if user does not have access:
"admin_console_url": "http://apps.local.openedx.io:2025/admin-console/authz",
"permissions": {
"admin": false,
"instructor": true,
"finance_admin": false,
"sales_admin": false,
"staff": true,
"forum_admin": true,
"data_researcher": false
},
"tabs": [
{
"tab_id": "courseware",
"title": "Course",
"url": "INSTRUCTOR_MICROFRONTEND_URL/courses/course-v1:edX+DemoX+2024/courseware"
},
{
"tab_id": "progress",
"title": "Progress",
"url": "INSTRUCTOR_MICROFRONTEND_URL/courses/course-v1:edX+DemoX+2024/progress"
},
],
"disable_buttons": false,
"analytics_dashboard_message": "To gain insights into student enrollment and participation..."
}
**Parameters**
course_key: Course key for the course.
**Returns**
* 200: OK - Returns course metadata
* 401: Unauthorized - User is not authenticated
* 403: Forbidden - User lacks instructor permissions
* 404: Not Found - Course does not exist
"""
course_key = CourseKey.from_string(course_id)
course = get_course_by_id(course_key)
tabs = get_course_tab_list(request.user, course)
context = {
'tabs': tabs,
'course': course,
'user': request.user,
'request': request
}
serializer = CourseInformationSerializerV2(context)
return Response(serializer.data, status=status.HTTP_200_OK)
class InstructorTaskListView(DeveloperErrorViewMixin, APIView):
"""
**Use Cases**
List instructor tasks for a course.
**Example Requests**
GET /api/instructor/v2/courses/{course_key}/instructor_tasks
GET /api/instructor/v2/courses/{course_key}/instructor_tasks?problem_location_str=block-v1:...
GET /api/instructor/v2/courses/{course_key}/instructor_tasks?
problem_location_str=block-v1:...&[email protected]
**Response Values**
{
"tasks": [
{
"task_id": "2519ff31-22d9-4a62-91e2-55495895b355",
"task_type": "grade_problems",
"task_state": "PROGRESS",
"status": "Incomplete",
"created": "2019-01-15T18:00:15.902470+00:00",
"task_input": "{}",
"task_output": null,
"duration_sec": "unknown",
"task_message": "No status information available",
"requester": "staff"
}
]
}
**Parameters**
course_key: Course key for the course.
problem_location_str (optional): Filter tasks to a specific problem location.
unique_student_identifier (optional): Filter tasks to specific student (must be used with problem_location_str).
**Returns**
* 200: OK - Returns list of instructor tasks
* 400: Bad Request - Invalid parameters
* 401: Unauthorized - User is not authenticated
* 403: Forbidden - User lacks instructor permissions
* 404: Not Found - Course does not exist
"""
permission_classes = (IsAuthenticated, permissions.InstructorPermission)
permission_name = permissions.SHOW_TASKS
@apidocs.schema(
parameters=[
apidocs.string_parameter(
'course_id',
apidocs.ParameterLocation.PATH,
description="Course key for the course.",
),
apidocs.string_parameter(
'problem_location_str',
apidocs.ParameterLocation.QUERY,
description="Optional: Filter tasks to a specific problem location.",
),
apidocs.string_parameter(
'unique_student_identifier',
apidocs.ParameterLocation.QUERY,
description="Optional: Filter tasks to a specific student (requires problem_location_str).",
),
],
responses={
200: InstructorTaskListSerializer,
400: "Invalid parameters provided.",
401: "The requesting user is not authenticated.",
403: "The requesting user lacks instructor access to the course.",
404: "The requested course does not exist.",
},
)
def get(self, request, course_id):
"""
List instructor tasks for a course.
"""
course_key = CourseKey.from_string(course_id)
# Get query parameters
problem_location_str = request.query_params.get('problem_location_str', None)
unique_student_identifier = request.query_params.get('unique_student_identifier', None)
student = None
if unique_student_identifier:
try:
student = get_student_from_identifier(unique_student_identifier)
except Exception: # pylint: disable=broad-except
return Response(
{'error': 'Invalid student identifier'},
status=status.HTTP_400_BAD_REQUEST
)
# Validate parameters
if student and not problem_location_str:
return Response(
{'error': 'unique_student_identifier must be used with problem_location_str'},
status=status.HTTP_400_BAD_REQUEST
)
# Get tasks based on filters
if problem_location_str:
try:
module_state_key = UsageKey.from_string(problem_location_str).map_into_course(course_key)
except InvalidKeyError:
return Response(
{'error': 'Invalid problem location'},
status=status.HTTP_400_BAD_REQUEST
)
if student:
# Tasks for specific problem and student
tasks = task_api.get_instructor_task_history(course_key, module_state_key, student)
else:
# Tasks for specific problem
tasks = task_api.get_instructor_task_history(course_key, module_state_key)
else:
# All running tasks
tasks = task_api.get_running_instructor_tasks(course_key)
# Extract task features and serialize
tasks_data = [extract_task_features(task) for task in tasks]
serializer = InstructorTaskListSerializer({'tasks': tasks_data})
return Response(serializer.data, status=status.HTTP_200_OK)
@method_decorator(cache_control(no_cache=True, no_store=True, must_revalidate=True), name='dispatch')
class ChangeDueDateView(APIView):
"""
Grants a due date extension to a student for a particular unit.
this version works with a new payload that is JSON and more up to date.
"""
permission_classes = (IsAuthenticated, permissions.InstructorPermission)
permission_name = permissions.GIVE_STUDENT_EXTENSION
serializer_class = BlockDueDateSerializerV2
def post(self, request, course_id):
"""
Grants a due date extension to a learner for a particular unit.
params:
blockId (str): The URL related to the block that needs the due date update.
due_datetime (str): The new due date and time for the block.
email_or_username (str): The email or username of the learner whose access is being modified.
"""
serializer_data = self.serializer_class(data=request.data)
if not serializer_data.is_valid():
return JsonResponseBadRequest({'error': serializer_data.errors})
learner = serializer_data.validated_data.get('email_or_username')
due_date = serializer_data.validated_data.get('due_datetime')
course = get_course_by_id(CourseKey.from_string(course_id))
unit = find_unit(course, serializer_data.validated_data.get('block_id'))
reason = strip_tags(serializer_data.validated_data.get('reason', ''))
try:
set_due_date_extension(course, unit, learner, due_date, request.user, reason=reason)
except Exception as error: # pylint: disable=broad-except
return JsonResponseBadRequest({'error': str(error)})
return Response(
{
'message': _(
'Successfully changed due date for learner {0} for {1} '
'to {2}').
format(learner.profile.name, _display_unit(unit), due_date.strftime('%Y-%m-%d %H:%M')
)})
class GradedSubsectionsView(APIView):
"""View to retrieve graded subsections with due dates"""
permission_classes = (IsAuthenticated, permissions.InstructorPermission)
permission_name = permissions.VIEW_DASHBOARD
def get(self, request, course_id):
"""
Retrieves a list of graded subsections (units with due dates) within a specified course.
"""
course_key = CourseKey.from_string(course_id)
course = get_course_by_id(course_key)
graded_subsections = get_units_with_due_date(course)
formated_subsections = {"items": [
{
"display_name": title_or_url(unit),
"subsection_id": str(unit.location)
} for unit in graded_subsections]}
return Response(formated_subsections, status=status.HTTP_200_OK)
@dataclass(frozen=True)
class UnitDueDateExtension:
"""Dataclass representing a unit due date extension for a student."""
username: str
full_name: str
email: str
unit_title: str
unit_location: str
extended_due_date: Optional[str] # noqa: UP045
@classmethod
def from_block_tuple(cls, row: Tuple, unit): # noqa: UP006
username, full_name, due_date, email, location = row
unit_title = title_or_url(unit)
return cls(
username=username,
full_name=full_name,
email=email,
unit_title=unit_title,
unit_location=location,
extended_due_date=due_date,
)
@classmethod
def from_course_tuple(cls, row: Tuple, units_dict: dict): # noqa: UP006
username, full_name, email, location, due_date = row
unit_title = title_or_url(units_dict[str(location)])
return cls(
username=username,
full_name=full_name,
email=email,
unit_title=unit_title,
unit_location=location,
extended_due_date=due_date,
)
class UnitExtensionsView(ListAPIView):
"""
Retrieve a paginated list of due date extensions for units in a course.
**Example Requests**
GET /api/instructor/v2/courses/{course_id}/unit_extensions
GET /api/instructor/v2/courses/{course_id}/unit_extensions?page=2
GET /api/instructor/v2/courses/{course_id}/unit_extensions?page_size=50
GET /api/instructor/v2/courses/{course_id}/unit_extensions?email_or_username=john
GET /api/instructor/v2/courses/{course_id}/unit_extensions?block_id=block-v1:org@problem+block@unit1
**Response Values**
{
"count": 150,
"next": "http://example.com/api/instructor/v2/courses/course-v1:org+course+run/unit_extensions?page=2",
"previous": null,
"results": [
{
"username": "student1",
"full_name": "John Doe",
"email": "[email protected]",
"unit_title": "Unit 1: Introduction",
"unit_location": "block-v1:org+course+run+type@problem+block@unit1",
"extended_due_date": "2023-12-25T23:59:59Z"
},
...
]
}
**Parameters**
course_id: Course key for the course.
page (optional): Page number for pagination.
page_size (optional): Number of results per page.
**Returns**
* 200: OK - Returns paginated list of unit extensions
* 401: Unauthorized - User is not authenticated
* 403: Forbidden - User lacks instructor permissions
* 404: Not Found - Course does not exist
"""
permission_classes = (IsAuthenticated, permissions.InstructorPermission)
permission_name = permissions.VIEW_DASHBOARD
serializer_class = UnitExtensionSerializer
filter_backends = []
def _matches_email_or_username(self, unit_extension, filter_value):
"""
Check if the unit extension matches the email or username filter.
"""
return (
filter_value in unit_extension.username.lower()
or filter_value in unit_extension.email.lower()
)
def get_queryset(self):
"""
Returns the queryset of unit extensions for the specified course.
This method uses the core logic from get_overrides_for_course to retrieve
due date extension data and transforms it into a list of normalized objects
that can be paginated and serialized.
Supports filtering by:
- email_or_username: Filter by username or email address
- block_id: Filter by specific unit/subsection location
"""
course_id = self.kwargs["course_id"]
course_key = CourseKey.from_string(course_id)
course = get_course_by_id(course_key)
email_or_username_filter = self.request.query_params.get("email_or_username")
block_id_filter = self.request.query_params.get("block_id")
units = get_units_with_due_date(course)
units_dict = {str(u.location): u for u in units}
# Fetch and normalize overrides
if block_id_filter:
try:
unit = find_unit(course, block_id_filter)
query_data = edx_when_api.get_overrides_for_block(course.id, unit.location)
unit_due_date_extensions = [
UnitDueDateExtension.from_block_tuple(row, unit)
for row in query_data
]
except InvalidKeyError:
# If block_id is invalid, return empty list
unit_due_date_extensions = []
else:
query_data = edx_when_api.get_overrides_for_course(course.id)
unit_due_date_extensions = [
UnitDueDateExtension.from_course_tuple(row, units_dict)
for row in query_data
if str(row[3]) in units_dict # Ensure unit has due date
]
# TODO: This filtering should ideally live in edx-when get_overrides_for_block/get_overrides_for_course.
# See https://github.com/openedx/edx-when/issues/353
# Filter out reset extensions (None dates or dates matching the original due date)
if unit_due_date_extensions:
version = getattr(course, 'course_version', None)
schedule = Schedule(start_date=course.start)
base_dates = edx_when_api.get_dates_for_course(
course.id, schedule=schedule, published_version=version
)
relevant_locations = {str(ext.unit_location) for ext in unit_due_date_extensions}
original_due_dates = {
str(loc): date
for (loc, field), date in base_dates.items()
if field == 'due' and str(loc) in relevant_locations
}
unit_due_date_extensions = [
ext for ext in unit_due_date_extensions
if ext.extended_due_date is not None
and ext.extended_due_date != original_due_dates.get(str(ext.unit_location))
]
# Apply filters if any
filter_value = email_or_username_filter.lower() if email_or_username_filter else None
results = [
extension
for extension in unit_due_date_extensions
if self._matches_email_or_username(extension, filter_value)
] if filter_value else unit_due_date_extensions # if no filter, use all
# Sort for consistent ordering
results.sort(
key=lambda o: (
o.username,
o.unit_title,
)
)
return results
class ORAView(GenericAPIView):
"""
View to list all Open Response Assessments (ORAs) for a given course.
* Requires token authentication.
* Only instructors or staff for the course are able to access this view.
"""
permission_classes = [IsAuthenticated, permissions.InstructorPermission]
permission_name = permissions.VIEW_DASHBOARD
serializer_class = ORASerializer
def get_course(self):
"""
Retrieve the course object based on the course_id URL parameter.
Validates that the course exists and is not deprecated.
Raises NotFound if the course does not exist.
"""
course_id = self.kwargs.get("course_id")
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError as exc:
log.error("Unable to find course with course key %s while loading the Instructor Dashboard.", course_id)
raise NotFound("Course not found") from exc
if course_key.deprecated:
raise NotFound("Course not found")
course = get_course_by_id(course_key, depth=None)
return course
def get(self, request, *args, **kwargs):
"""
Return a list of all ORAs for the specified course.
"""
course = self.get_course()
items = get_open_response_assessment_list(course)
page = self.paginate_queryset(items)
if page is None:
# Pagination is required for this endpoint
return Response(
{"detail": "Pagination is required for this endpoint."},
status=status.HTTP_400_BAD_REQUEST,
)
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
class ReportDownloadsView(DeveloperErrorViewMixin, APIView):
"""
**Use Cases**
List all available report downloads for a course.
**Example Requests**
GET /api/instructor/v2/courses/{course_key}/reports
**Response Values**
{
"downloads": [
{
"report_name": "course-v1_edX_DemoX_Demo_Course_grade_report_2024-01-26-1030.csv",
"report_url":
"/grades/course-v1:edX+DemoX+Demo_Course/"
"course-v1_edX_DemoX_Demo_Course_grade_report_2024-01-26-1030.csv",
"date_generated": "2024-01-26T10:30:00Z",
"report_type": "grade" # Uses ReportType.GRADE.value
}
]
}
**Parameters**
course_key: Course key for the course.
**Returns**
* 200: OK - Returns list of available reports
* 401: Unauthorized - User is not authenticated
* 403: Forbidden - User lacks staff access to the course
* 404: Not Found - Course does not exist
"""
permission_classes = (IsAuthenticated, permissions.InstructorPermission)
# Use ENROLLMENT_REPORT permission which allows course staff and data researchers
# to view generated reports, aligning with the intended audience of instructors/course staff
permission_name = permissions.ENROLLMENT_REPORT
@apidocs.schema(
parameters=[
apidocs.string_parameter(
'course_id',
apidocs.ParameterLocation.PATH,
description="Course key for the course.",
),
],
responses={
200: "Returns list of available report downloads.",
401: "The requesting user is not authenticated.",
403: "The requesting user lacks instructor access to the course.",
404: "The requested course does not exist.",
},
)
def get(self, request, course_id):
"""
List all available report downloads for a course.
"""
course_key = CourseKey.from_string(course_id)
# Validate that the course exists
get_course_by_id(course_key)
report_store = ReportStore.from_config(config_name='GRADES_DOWNLOAD')
downloads = []
for name, url in report_store.links_for(course_key):
# Determine report type from filename using helper method
report_type = self._detect_report_type_from_filename(name)
# Extract date from filename if possible (format: YYYY-MM-DD-HHMM)
date_generated = self._extract_date_from_filename(name)
downloads.append({
'report_name': name,
'report_url': url,
'date_generated': date_generated,
'report_type': report_type,
})
return Response({'downloads': downloads}, status=status.HTTP_200_OK)
def _detect_report_type_from_filename(self, filename):
"""
Detect report type from filename using pattern matching.
Check more specific patterns first to avoid false matches.
Args:
filename: The name of the report file
Returns:
str: The report type identifier
"""
name_lower = filename.lower()
# Check more specific patterns first to avoid false matches
# Match exact report names from the filename format: {course_prefix}_{csv_name}_{timestamp}.csv
if 'inactive_enrolled' in name_lower:
return ReportType.PENDING_ACTIVATIONS.value
elif 'problem_grade_report' in name_lower:
return ReportType.PROBLEM_GRADE.value
elif 'ora2_submission' in name_lower or 'submission_files' in name_lower or 'ora_submission' in name_lower:
return ReportType.ORA2_SUBMISSION_FILES.value
elif 'ora2_summary' in name_lower or 'ora_summary' in name_lower:
return ReportType.ORA2_SUMMARY.value
elif 'ora2_data' in name_lower or 'ora_data' in name_lower:
return ReportType.ORA2_DATA.value
elif 'may_enroll' in name_lower:
return ReportType.PENDING_ENROLLMENTS.value
elif 'student_state' in name_lower or 'problem_responses' in name_lower:
return ReportType.PROBLEM_RESPONSES.value
elif 'anonymized_ids' in name_lower or 'anon' in name_lower:
return ReportType.ANONYMIZED_STUDENT_IDS.value
elif 'issued_certificates' in name_lower or 'certificate' in name_lower:
return ReportType.ISSUED_CERTIFICATES.value
elif 'cohort_results' in name_lower:
return ReportType.COHORT_RESULTS.value
elif 'grade_report' in name_lower:
return ReportType.GRADE.value
elif 'enrolled_students' in name_lower or 'profile' in name_lower:
return ReportType.ENROLLED_STUDENTS.value
return ReportType.UNKNOWN.value
def _extract_date_from_filename(self, filename):
"""
Extract date from filename (format: YYYY-MM-DD-HHMM).
Args:
filename: The name of the report file
Returns:
str: ISO formatted date string or None
"""
date_match = re.search(r'_(\d{4}-\d{2}-\d{2}-\d{4})', filename)
if date_match:
date_str = date_match.group(1)
try:
# Parse the date string (YYYY-MM-DD-HHMM) directly
dt = datetime.strptime(date_str, '%Y-%m-%d-%H%M')
# Format as ISO 8601 with UTC timezone
return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
except ValueError:
pass
return None
@method_decorator(transaction.non_atomic_requests, name='dispatch')
class GenerateReportView(DeveloperErrorViewMixin, APIView):
"""
**Use Cases**
Generate a specific type of report for a course.
**Example Requests**
POST /api/instructor/v2/courses/{course_key}/reports/enrolled_students/generate
POST /api/instructor/v2/courses/{course_key}/reports/grade/generate
POST /api/instructor/v2/courses/{course_key}/reports/problem_responses/generate
**Response Values**
{
"status": "The report is being created. Please check the data downloads section for the status."
}
**Parameters**
course_key: Course key for the course.
report_type: Type of report to generate. Valid values:
- enrolled_students: Enrolled Students Report
- pending_enrollments: Pending Enrollments Report
- pending_activations: Pending Activations Report (inactive users with enrollments)
- anonymized_student_ids: Anonymized Student IDs Report
- grade: Grade Report
- problem_grade: Problem Grade Report
- problem_responses: Problem Responses Report
- ora2_summary: ORA Summary Report
- ora2_data: ORA Data Report
- ora2_submission_files: ORA Submission Files Report
- issued_certificates: Issued Certificates Report
**Returns**
* 200: OK - Report generation task has been submitted
* 400: Bad Request - Task is already running or invalid report type
* 401: Unauthorized - User is not authenticated
* 403: Forbidden - User lacks instructor permissions
* 404: Not Found - Course does not exist
"""
permission_classes = (IsAuthenticated, permissions.InstructorPermission)
@property
def permission_name(self):
"""
Return the appropriate permission name based on the requested report type.
For the issued certificates report, mirror the v1 behavior by using
VIEW_ISSUED_CERTIFICATES (course-level staff access). For all other reports,
require CAN_RESEARCH.
"""
report_type = self.kwargs.get('report_type')
if report_type == ReportType.ISSUED_CERTIFICATES.value:
return permissions.VIEW_ISSUED_CERTIFICATES
return permissions.CAN_RESEARCH
@apidocs.schema(
parameters=[
apidocs.string_parameter(
'course_id',
apidocs.ParameterLocation.PATH,
description="Course key for the course.",
),
apidocs.string_parameter(
'report_type',
apidocs.ParameterLocation.PATH,
description=(
"Type of report to generate. Valid values: "
"enrolled_students, pending_enrollments, pending_activations, "
"anonymized_student_ids, grade, problem_grade, problem_responses, "
"ora2_summary, ora2_data, ora2_submission_files, issued_certificates"
),
),
],
responses={
200: "Report generation task has been submitted successfully.",
400: "The requested task is already running or invalid report type.",
401: "The requesting user is not authenticated.",
403: "The requesting user lacks instructor access to the course.",
404: "The requested course does not exist.",
},
)
def post(self, request, course_id, report_type):
"""
Generate a specific type of report for a course.
"""
course_key = CourseKey.from_string(course_id)
# Map report types to their submission functions
report_handlers = {
ReportType.ENROLLED_STUDENTS.value: self._generate_enrolled_students_report,
ReportType.PENDING_ENROLLMENTS.value: self._generate_pending_enrollments_report,
ReportType.PENDING_ACTIVATIONS.value: self._generate_pending_activations_report,
ReportType.ANONYMIZED_STUDENT_IDS.value: self._generate_anonymized_ids_report,
ReportType.GRADE.value: self._generate_grade_report,
ReportType.PROBLEM_GRADE.value: self._generate_problem_grade_report,
ReportType.PROBLEM_RESPONSES.value: self._generate_problem_responses_report,
ReportType.ORA2_SUMMARY.value: self._generate_ora2_summary_report,
ReportType.ORA2_DATA.value: self._generate_ora2_data_report,
ReportType.ORA2_SUBMISSION_FILES.value: self._generate_ora2_submission_files_report,
ReportType.ISSUED_CERTIFICATES.value: self._generate_issued_certificates_report,
}
handler = report_handlers.get(report_type)
if not handler:
return Response(
{'error': f'Invalid report type: {report_type}'},
status=status.HTTP_400_BAD_REQUEST
)
try:
success_message = handler(request, course_key)
except AlreadyRunningError as error:
log.warning("Task already running for %s report: %s", report_type, error)
return Response(
{'error': _('A report generation task is already running. Please wait for it to complete.')},
status=status.HTTP_400_BAD_REQUEST
)
except QueueConnectionError as error:
log.error("Queue connection error for %s report task: %s", report_type, error)
return Response(
{'error': _('Unable to connect to the task queue. Please try again later.')},
status=status.HTTP_503_SERVICE_UNAVAILABLE
)
except ValueError as error:
log.error("Error submitting %s report task: %s", report_type, error)
return Response(
{'error': str(error)},
status=status.HTTP_400_BAD_REQUEST
)
return Response({'status': success_message}, status=status.HTTP_200_OK)
def _generate_enrolled_students_report(self, request, course_key):
"""Generate enrolled students report."""
course = get_course_by_id(course_key)