-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmodels.py
More file actions
1582 lines (1388 loc) · 51.3 KB
/
models.py
File metadata and controls
1582 lines (1388 loc) · 51.3 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
import math
import uuid
from textwrap import dedent
import phonenumbers
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models, transaction
from django.db.models import OuterRef, Q, Subquery, UniqueConstraint
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from PennCourses.settings.base import FIRST_BANNER_SEM, PRE_NGSS_PERMIT_REQ_RESTRICTION_CODES
from review.annotations import review_averages
User = get_user_model()
def string_dict_to_html(dictionary):
html = ["<table width=100%>"]
for key, value in dictionary.items():
html.append("<tr>")
html.append('<td>"{0}"</td>'.format(key))
html.append('<td>"{0}"</td>'.format(value))
html.append("</tr>")
html.append("</table>")
return "".join(html)
"""
Core Course Models
==================
The Instructor, Course and Section models define the core course information
used in Alert and Plan.
The StatusUpdate model holds changes to the "status" field over time, recording how course
availability changes over time.
"""
class Instructor(models.Model):
"""
An academic instructor at Penn, e.g. Swapneel Sheth.
"""
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
name = models.CharField(
max_length=255, db_index=True, help_text="The full name of the instructor."
)
user = models.ForeignKey(
User,
null=True,
blank=True,
on_delete=models.SET_NULL,
help_text="The instructor's Penn Labs Accounts User object.",
)
def __str__(self):
return self.name
class Department(models.Model):
"""
An academic department at Penn, such as the CIS (Computer and Information Sci) department.
"""
code = models.CharField(
max_length=8,
unique=True,
db_index=True,
help_text="The department code, e.g. `CIS` for the CIS department.",
)
name = models.CharField(
max_length=255,
help_text=dedent(
"""
The name of the department, e.g. 'Computer and Information Sci' for the CIS department.
"""
),
)
def __str__(self):
return self.code
def sections_with_reviews(queryset):
from review.views import section_filters_pcr
# ^ imported here to avoid circular imports
# get all the reviews for instructors in the Section.instructors many-to-many
instructors_subquery = Subquery(
Instructor.objects.filter(section__id=OuterRef(OuterRef("id"))).values("id")
)
return review_averages(
queryset,
reviewbit_subfilters=(
Q(review__section__course__topic=OuterRef("course__topic"))
& Q(review__instructor__in=instructors_subquery)
),
section_subfilters=(
section_filters_pcr
& Q(course__topic=OuterRef("course__topic"))
& Q(instructors__in=instructors_subquery)
),
extra_metrics=False,
).order_by("code")
def course_reviews(queryset):
from review.views import section_filters_pcr
# ^ imported here to avoid circular imports
return review_averages(
queryset,
reviewbit_subfilters=(Q(review__section__course__topic=OuterRef("topic"))),
section_subfilters=(section_filters_pcr & Q(course__topic=OuterRef("topic"))),
extra_metrics=False,
)
class CourseManager(models.Manager):
def get_queryset(self):
return course_reviews(super().get_queryset())
class Course(models.Model):
"""
A course at Penn, e.g. CIS-120 (Programming Languages and Techniques I)
"""
objects = models.Manager()
with_reviews = CourseManager()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
department = models.ForeignKey(
Department,
on_delete=models.CASCADE,
related_name="courses",
help_text=dedent(
"""
The Department object to which the course belongs, e.g. the CIS Department object
for CIS-120.
"""
),
)
code = models.CharField(
max_length=8,
db_index=True,
help_text="The course code, e.g. `120` for CIS-120.",
)
semester = models.CharField(
max_length=5,
db_index=True,
help_text=dedent(
"""
The semester of the course (of the form YYYYx where x is A [for spring],
B [summer], or C [fall]), e.g. `2019C` for fall 2019.
"""
),
)
title = models.TextField(
help_text=dedent(
"""
The title of the course, e.g. 'Programming Languages and Techniques I' for CIS-120.
"""
)
)
description = models.TextField(
blank=True,
help_text=dedent(
"""
The description of the course, e.g. 'A fast-paced introduction to the fundamental concepts
of programming... [etc.]' for CIS-120.
"""
),
)
syllabus_url = models.TextField(
blank=True,
null=True,
help_text=dedent(
"""
A URL for the syllabus of the course, if available.
Not available for courses offered in or before spring 2022.
"""
),
)
full_code = models.CharField(
max_length=16,
blank=True,
db_index=True,
help_text="The dash-joined department and code of the course, e.g. `CIS-120` for CIS-120.",
)
credits = models.DecimalField(
max_digits=4, # some course for 2019C is 14 CR...
decimal_places=2,
null=True,
blank=True,
db_index=True,
help_text="The number of credits this course takes. This is precomputed for efficiency.",
)
prerequisites = models.TextField(
blank=True,
help_text="Text describing the prereqs for a course, e.g. 'CIS 120, 160' for CIS-121.",
)
topic = models.ForeignKey(
"Topic",
related_name="courses",
on_delete=models.SET_NULL,
null=True,
blank=True,
help_text="The Topic of this course (computed from the `parent_course` graph).",
)
parent_course = models.ForeignKey(
"Course",
related_name="children",
on_delete=models.SET_NULL,
null=True,
blank=True,
help_text=dedent(
"""
The parent of this course (the most recent offering of this course in a previous semester).
The graph of parent relationships is used to determine course topics. Any manual changes
to this field should be denoted with `manually_set_parent_course=True`, so they are not
overwritten by our automatic script.
"""
),
)
manually_set_parent_course = models.BooleanField(
default=False,
help_text=dedent(
"""
A flag indicating whether the `parent_course` field of this course was confirmed/set
manually or from a University-provided crosswalk,
rather than inferred by an automatic script.
"""
),
)
primary_listing = models.ForeignKey(
"Course",
related_name="listing_set",
on_delete=models.CASCADE,
blank=True, # So you can leave blank for a self-reference on course creation forms
help_text=dedent(
"""
The primary Course object with which this course is crosslisted. The set of crosslisted
courses to which this course belongs can thus be accessed with the related field
`listing_set` on the `primary_listing` course. If a course doesn't have any crosslistings,
its `primary_listing` foreign key will point to itself. If you call `.save()` on a course
without setting its `primary_listing` field, the overridden `Course.save()` method will
automatically set its `primary_listing` to a self-reference.
"""
),
)
num_activities = models.IntegerField(
default=0,
help_text=dedent(
"""
The number of distinct activities belonging to this course (precomputed for efficiency).
Maintained by the registrar import / recomputestats script.
"""
),
)
class Meta:
unique_together = (
("department", "code", "semester"),
("full_code", "semester"),
("topic", "semester"),
)
def __str__(self):
return "%s %s" % (self.full_code, self.semester)
def full_str(self):
return f"{self.full_code} ({self.semester}): {self.title}\n{self.description}"
@property
def is_primary(self):
"""
Returns True iff this is the primary course among its crosslistings.
"""
return self.primary_listing.id == self.id
@property
def from_new_banner_api(self):
"""
This property is used to determine whether the course was imported from the new
OpenData API based on Banner, the university's new course data management system
(docs: https://app.swaggerhub.com/apis-docs/UPennISC/open-data/prod),
as opposed to the old OpenData API
(docs: https://esb.isc-seo.upenn.edu/8091/documentation).
"""
return self.semester >= FIRST_BANNER_SEM
@property
def crosslistings(self):
"""
A QuerySet (list on frontend) of the Course objects which are crosslisted with this
course (not including this course).
"""
return self.primary_listing.listing_set.exclude(id=self.id)
@property
def pre_ngss_requirements(self):
"""
A QuerySet (list on frontend) of all the PreNGSSRequirement objects this course fulfills.
Note that a course fulfills a requirement if and only if it is not in the requirement's
overrides set (related name nonrequirements_set), and is in the requirement's
courses set (related name requirement_set) or its department is in the requirement's
departments set (related name requirements).
"""
return (
PreNGSSRequirement.objects.exclude(id__in=self.pre_ngss_nonrequirement_set.all())
.filter(semester=self.semester)
.filter(
Q(id__in=self.pre_ngss_requirement_set.all())
| Q(id__in=self.department.pre_ngss_requirements.all())
)
)
def save(self, *args, **kwargs):
"""
This overridden `.save()` method enforces the following invariants on the course:
- The course's full code equals the dash-joined department and code
- If a course doesn't have crosslistings, its `primary_listing` is a self-reference
"""
from courses.util import get_set_id, is_fk_set # avoid circular imports
self.full_code = f"{self.department.code}-{self.code}"
with transaction.atomic():
# Set primary_listing to self if not set
if not is_fk_set(self, "primary_listing"):
self.primary_listing_id = self.id or get_set_id(self)
super().save(*args, **kwargs)
class Topic(models.Model):
"""
A grouping of courses of the same topic (to accomodate course code changes).
Topics are SOFT STATE, meaning they are not the source of truth for course groupings.
They are recomputed nightly from the `parent_course` graph
(in the recompute_soft_state cron job).
"""
most_recent = models.ForeignKey(
"Course",
related_name="+",
on_delete=models.PROTECT,
help_text=dedent(
"""
The most recent course (by semester) of this topic. You must change the corresponding
`Topic` object's `most_recent` field before deleting a Course if it is the
`most_recent` course (`on_delete=models.PROTECT`).
"""
),
)
historical_probabilities_spring = models.FloatField(
default=0,
help_text=dedent(
"""
The historical probability of a student taking a course in this topic in the spring
semester, based on historical data. This field is recomputed nightly from the
`parent_course` graph (in the recompute_soft_state cron job).
"""
),
)
historical_probabilities_summer = models.FloatField(
default=0,
help_text=dedent(
"""
The historical probability of a student taking a course in this topic in the summer
semester, based on historical data. This field is recomputed nightly from the
`parent_course` graph (in the recompute_soft_state cron job).
"""
),
)
historical_probabilities_fall = models.FloatField(
default=0,
help_text=dedent(
"""
The historical probability of a student taking a course in this topic in the fall
semester, based on historical data. This field is recomputed nightly from the
`parent_course` graph (in the recompute_soft_state cron job).
"""
),
)
branched_from = models.ForeignKey(
"Topic",
related_name="branched_to",
on_delete=models.SET_NULL,
null=True,
blank=True,
help_text=dedent(
"""
When relevant, the Topic from which this Topic was branched (this will likely only be
useful for the spring 2022 NGSS course code changes, where some courses were split into
multiple new courses of different topics).
"""
),
)
def __str__(self):
return f"Topic {self.id} ({self.most_recent.full_code} most recently)"
class Attribute(models.Model):
"""
A post-NGSS registration attribute, which is used to
mark courses which students in a program/major should take.
e.g. WUOM for the "Wharton OIDD Operation" track
Note that Attributes (like Restrictions) do not have an associated
semester.
"""
code = models.CharField(
max_length=10,
unique=True,
db_index=True,
help_text=dedent(
"""
A registration attribute code, for instance 'WUOM' for Wharton OIDD Operations track.
"""
),
)
description = models.TextField(
help_text=dedent(
"""
The registration attribute description, e.g. 'Wharton OIDD Operation'
for the WUOM attribute.
"""
)
)
SCHOOL_CHOICES = (
("SAS", "School of Arts and Sciences"),
("LPS", "College of Liberal and Professional Studies"),
("SEAS", "Engineering"),
("DSGN", "Design"),
("GSE", "Graduate School of Education"),
("LAW", "Law School"),
("MED", "School of Medicine"),
("MODE", "Grade Mode"),
("VET", "School of Veterinary Medicine"),
("NUR", "Nursing"),
("WH", "Wharton"),
)
school = models.CharField(
max_length=5,
choices=SCHOOL_CHOICES,
db_index=True,
null=True,
help_text=dedent(
"""
What school/program this attribute belongs to, e.g. `SAS` for `ASOC` restriction
or `WH` for `WUOM` or `MODE` for `QP`. Options and meanings:
"""
+ string_dict_to_html(dict(SCHOOL_CHOICES))
),
)
courses = models.ManyToManyField(
Course,
related_name="attributes",
blank=True,
help_text=dedent(
"""
Course objects which have this attribute
"""
),
)
def __str__(self):
return f"{self.code} @ {self.school} - {self.description}"
class NGSSRestriction(models.Model):
"""
A restriction on who can register for this course.
Note that Restrictions (like Attributes) do not have an associated
semester.
"""
code = models.CharField(
max_length=16,
unique=True,
db_index=True,
help_text=dedent(
"""
The code of the restriction.
"""
),
)
restriction_type = models.CharField(
max_length=25,
db_index=True,
help_text=dedent(
"""
What the restriction is based on (e.g., Campus).
"""
),
)
inclusive = models.BooleanField(
help_text=dedent(
"""
Whether this is an include or exclude restriction. Corresponds to the `incl_excl_ind`
response field. `True` if include (ie, `incl_excl_ind` is "I") and `False`
if exclude ("E").
"""
)
)
description = models.TextField(
help_text=dedent(
"""
The registration restriction description.
"""
)
)
@staticmethod
def special_approval():
return NGSSRestriction.objects.filter(restriction_type="Special Approval")
def __str__(self):
return f"{self.code} - {self.restriction_type} - {self.description}"
class SectionManager(models.Manager):
def get_queryset(self):
return sections_with_reviews(super().get_queryset()).distinct()
class PreNGSSRestriction(models.Model):
"""
A pre-NGSS (deprecated since 2022B) registration restriction,
e.g. PDP (permission needed from department)
"""
code = models.CharField(
max_length=10,
unique=True,
help_text=dedent(
"""
A registration restriction control code, for instance 'PDP' for CIS-121 (permission
required from dept for registration). See [bit.ly/3eu17m2](https://bit.ly/3eu17m2)
for all options.
"""
),
)
description = models.TextField(
help_text=dedent(
"""
The registration restriction description, e.g. 'Permission Needed From Department'
for the PDP restriction (on CIS-121, for example). See
[bit.ly/3eu17m2](https://bit.ly/3eu17m2) for all options.
"""
)
)
@property
def permit_required(self):
"""
True if permission is required from the department for registration, false otherwise.
"""
return "permission" in self.description.lower()
@staticmethod
def special_approval():
return PreNGSSRestriction.objects.filter(code__in=PRE_NGSS_PERMIT_REQ_RESTRICTION_CODES)
def __str__(self):
return f"{self.code} - {self.description}"
class Section(models.Model):
"""
This model represents a section of a course at Penn, e.g. CIS-120-001 for the CIS-120 course.
"""
objects = models.Manager()
with_reviews = SectionManager()
STATUS_CHOICES = (
("O", "Open"),
("C", "Closed"),
("X", "Cancelled"),
("", "Unlisted"),
)
ACTIVITY_CHOICES = (
("", "Undefined"),
("CLN", "Clinic"),
("CRT", "Clinical Rotation"),
("DAB", "Dissertation Abroad"),
("DIS", "Dissertation"),
("DPC", "Doctoral Program Exchange"),
("FLD", "Field Work"),
("HYB", "Hybrid"),
("IND", "Independent Study"),
("LAB", "Lab"),
("LEC", "Lecture"),
("MST", "Masters Thesis"),
("ONL", "Online"),
("PRC", "Practicum"),
("REC", "Recitation"),
("SEM", "Seminar"),
("SRT", "Senior Thesis"),
("STU", "Studio"),
)
class Meta:
unique_together = (("code", "course"),)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
code = models.CharField(
max_length=16,
db_index=True,
help_text="The section code, e.g. `001` for the section CIS-120-001.",
)
course = models.ForeignKey(
Course,
on_delete=models.CASCADE,
related_name="sections",
help_text=dedent(
"""
The Course object to which this section belongs, e.g. the CIS-120 Course object for
CIS-120-001.
"""
),
)
full_code = models.CharField(
max_length=32,
blank=True,
db_index=True,
help_text=dedent(
"""
The full code of the section, in the form '{dept code}-{course code}-{section code}',
e.g. `CIS-120-001` for the 001 section of CIS-120.
"""
),
)
crn = models.CharField(
max_length=8,
db_index=True,
blank=True,
null=True,
help_text=dedent(
"""
The CRN ID of the section.
Only available on sections after spring 2022 (i.e. after the NGSS transition).
"""
),
)
status = models.CharField(
max_length=4,
choices=STATUS_CHOICES,
db_index=True,
help_text="The registration status of the section. Options and meanings: "
+ string_dict_to_html(dict(STATUS_CHOICES)),
)
code_specific_enrollment = models.IntegerField(
default=0,
help_text=dedent(
"""
The number students enrolled in this specific section as of our last registrarimport,
NOT including crosslisted sections. Comparable with `.code_specific_capacity`.
This field is not usable for courses before 2022B
(first semester after the Path transition).
"""
),
)
code_specific_capacity = models.IntegerField(
default=0,
help_text=dedent(
"""
The max allowed enrollment for this specific section,
NOT including crosslisted sections.
This field is not usable for courses before 2022B
(first semester after the Path transition).
"""
),
)
enrollment = models.IntegerField(
default=0,
help_text=dedent(
"""
The number students enrolled in all crosslistings of this section,
as of our last registrarimport. Comparable with `.capacity`.
SOFT STATE, recomputed by `recompute_soft_state` after each registrarimport as
the sum of `.code_specific_enrollment` across all crosslisted sections.
This field is not usable for courses before 2022B
(first semester after the Path transition).
"""
),
)
capacity = models.IntegerField(
default=0,
help_text="The max allowed enrollment across all crosslistings of this section.",
)
activity = models.CharField(
max_length=50,
choices=ACTIVITY_CHOICES,
db_index=True,
help_text="The section activity, e.g. `LEC` for CIS-120-001 (2020A). Options and meanings: "
+ string_dict_to_html(dict(ACTIVITY_CHOICES)),
)
meeting_times = models.TextField(
blank=True,
help_text=dedent(
"""
A JSON-stringified list of meeting times of the form
`{days code} {start time} - {end time}`, e.g.
`["MWF 09:00 AM - 10:00 AM","F 11:00 AM - 12:00 PM","T 05:00 PM - 06:00 PM"]` for
PHYS-151-001 (2020A). Each letter of the days code is of the form M, T, W, R, F for each
day of the work week, respectively (and multiple days are combined with concatenation).
To access the Meeting objects for this section, the related field `meetings` can be used.
"""
),
)
num_meetings = models.IntegerField(
default=0,
help_text=dedent(
"""
The number of meetings belonging to this section (precomputed for efficiency).
Maintained by the registrar import / recompute_soft_state script.
"""
),
)
instructors = models.ManyToManyField(
Instructor,
help_text="The Instructor object(s) of the instructor(s) teaching the section.",
)
associated_sections = models.ManyToManyField(
"Section",
help_text=dedent(
"""
A list of all sections associated with the Course which this section belongs to; e.g. for
CIS-120-001, all of the lecture and recitation sections for CIS-120 (including CIS-120-001)
in the same semester.
"""
),
)
ngss_restrictions = models.ManyToManyField(
NGSSRestriction,
related_name="sections",
blank=True,
help_text=(
"All NGSS registration Restriction objects to which this section is subject. "
"This field will be empty for sections in 2022B or later."
),
)
pre_ngss_restrictions = models.ManyToManyField(
PreNGSSRestriction,
related_name="sections",
blank=True,
help_text=(
"All pre-NGSS (deprecated since 2022B) registration Restriction objects to which "
"this section is subject. This field will be empty for sections "
"in 2022B or later."
),
)
credits = models.DecimalField(
max_digits=4, # some course for 2019C is 14 CR...
decimal_places=2,
null=True,
blank=True,
db_index=True,
help_text="The number of credits this section is worth.",
)
has_reviews = models.BooleanField(
default=False,
help_text=dedent(
"""
A flag indicating whether this section has reviews (precomputed for efficiency).
"""
),
)
has_status_updates = models.BooleanField(
default=False,
help_text=dedent(
"""
A flag indicating whether this section has Status Updates (precomputed for efficiency).
"""
),
)
registration_volume = models.PositiveIntegerField(
default=0,
help_text="The number of active PCA registrations watching this section.",
) # For the set of PCA registrations for this section, use the related field `registrations`.
def __str__(self):
return "%s %s" % (self.full_code, self.course.semester)
@property
def semester(self):
"""
The semester of the course (of the form YYYYx where x is A [for spring],
B [summer], or C [fall]), e.g. `2019C` for fall 2019.
"""
return self.course.semester
@property
def is_open(self):
"""
True if self.status == "O", False otherwise
"""
return self.status == "O"
percent_open = models.FloatField(
default=0,
validators=[MinValueValidator(0), MaxValueValidator(1)],
help_text=dedent(
"""
If this section is from the current semester, this is the percentage (expressed as a
decimal number between 0 and 1) of the period between the beginning of its
add/drop period and its last status update that this section was open
(or 0 if it has had no status updates strictly within its add/drop period).
If this section is from a previous semester, this is the percentage of its
whole add/drop period that it was open.
"""
),
)
@property
def current_percent_open(self):
"""
The percentage (expressed as a decimal number between 0 and 1) of the period between
the beginning of its add/drop period and min[the current time, the end of its
registration period] that this section was open. If this section's registration
period hasn't started yet, this property is null (None in Python).
"""
from courses.util import get_current_semester, get_or_create_add_drop_period
# ^ imported here to avoid circular imports
if self.semester == get_current_semester():
add_drop = get_or_create_add_drop_period(self.semester)
add_drop_start = add_drop.estimated_start
add_drop_end = add_drop.estimated_end
current_time = timezone.now()
if current_time <= add_drop_start:
return None
try:
last_status_update = StatusUpdate.objects.filter(
section=self,
created_at__gt=add_drop_start,
created_at__lt=add_drop_end,
).latest("created_at")
except StatusUpdate.DoesNotExist:
last_status_update = None
last_update_dt = last_status_update.created_at if last_status_update else add_drop_start
period_seconds = float(
(min(current_time, add_drop_end) - add_drop_start).total_seconds()
)
percent_after_update = (
float(self.is_open)
* float((current_time - last_update_dt).total_seconds())
/ period_seconds
)
if last_status_update is None:
return percent_after_update
percent_before_update = (
float(self.percent_open)
* float((last_update_dt - add_drop_start).total_seconds())
/ period_seconds
)
return percent_before_update + percent_after_update
else:
return self.percent_open
@property
def last_status_update(self):
"""
Returns the last StatusUpdate object for this section, or None if no status updates
have occured for this section yet.
"""
try:
return StatusUpdate.objects.filter(section=self).latest("created_at")
except StatusUpdate.DoesNotExist:
return None
def save(self, *args, **kwargs):
self.full_code = f"{self.course.full_code}-{self.code}"
super().save(*args, **kwargs)
class StatusUpdate(models.Model):
"""
A registration status update for a specific section (e.g. CIS-120-001 went from open to close)
"""
STATUS_CHOICES = (
("O", "Open"),
("C", "Closed"),
("X", "Cancelled"),
("", "Unlisted"),
)
section = models.ForeignKey(
Section,
related_name="status_updates",
on_delete=models.CASCADE,
help_text="The section which this status update applies to.",
)
old_status = models.CharField(
max_length=16,
choices=STATUS_CHOICES,
help_text="The old status code (from which the section changed). Options and meanings: "
+ string_dict_to_html(dict(STATUS_CHOICES)),
)
new_status = models.CharField(
max_length=16,
choices=STATUS_CHOICES,
help_text="The new status code (to which the section changed). Options and meanings: "
+ string_dict_to_html(dict(STATUS_CHOICES)),
)
created_at = models.DateTimeField(default=timezone.now)
alert_sent = models.BooleanField(
help_text="Was an alert was sent to a User as a result of this status update?"
)
# ^^^ alert_sent is true iff alert_for_course was called in accept_webhook in alert/views.py
request_body = models.TextField()
percent_through_add_drop_period = models.FloatField(
null=True,
blank=True,
help_text="The percentage through the add/drop period at which this status update occurred."
"This percentage is constrained within the range [0,1].",
) # This field is maintained in the save() method of alerts.models.AddDropPeriod,
# and the save() method of StatusUpdate
in_add_drop_period = models.BooleanField(
default=False,
help_text="Was this status update created during the add/drop period?",
) # This field is maintained in the save() method of alerts.models.AddDropPeriod,
# and the save() method of StatusUpdate
def __str__(self):
d = dict(self.STATUS_CHOICES)
return (
f"{str(self.section)} - {d[self.old_status]} to {d[self.new_status]} "
f"@ {str(self.created_at)}"
)
def save(self, *args, **kwargs):
"""
This overridden save method first gets the add/drop period object for the semester of this
StatusUpdate object (either by using the get_or_create_add_drop_period method or by using
a passed-in add_drop_period kwarg, which can be used for efficiency in bulk operations
over many StatusUpdate objects). Then it calls the overridden save method, and after that
it sets the percent_through_add_drop_period field.
"""
from alert.models import validate_add_drop_semester
from alert.tasks import section_demand_change
from courses.util import get_or_create_add_drop_period
# ^ imported here to avoid circular imports
add_drop_period = None
if "add_drop_period" in kwargs:
add_drop_period = kwargs["add_drop_period"]
del kwargs["add_drop_period"]