-
Notifications
You must be signed in to change notification settings - Fork 173
/
models.py
4606 lines (3880 loc) · 179 KB
/
models.py
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 datetime
import itertools
import logging
import re
from collections import Counter, defaultdict
from urllib.parse import urljoin
from uuid import uuid4
import pytz
import requests
import waffle # lint-amnesty, pylint: disable=invalid-django-waffle-import
from config_models.models import ConfigurationModel
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.validators import FileExtensionValidator, MaxValueValidator, MinValueValidator, RegexValidator
from django.db import IntegrityError, models, transaction
from django.db.models import F, Q, UniqueConstraint
from django.db.models.query import Prefetch
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from django_countries import countries as COUNTRIES
from django_elasticsearch_dsl.registries import registry
from django_extensions.db.fields import AutoSlugField
from django_extensions.db.models import TimeStampedModel
from edx_django_utils.cache import RequestCache, get_cache_key
from elasticsearch.exceptions import RequestError
from elasticsearch_dsl.query import Q as ESDSLQ
from localflavor.us.us_states import CONTIGUOUS_STATES
from model_utils import FieldTracker
from multi_email_field.fields import MultiEmailField
from multiselectfield import MultiSelectField
from opaque_keys.edx.keys import CourseKey
from parler.models import TranslatableModel, TranslatedFieldsModel
from simple_history.models import HistoricalRecords
from slugify import slugify as uslugify
from solo.models import SingletonModel
from sortedm2m.fields import SortedManyToManyField
from stdimage.models import StdImageField
from taggit_autosuggest.managers import TaggableManager
from taxonomy.signals.signals import UPDATE_PROGRAM_SKILLS
from course_discovery.apps.core.models import Currency, Partner
from course_discovery.apps.course_metadata import emails
from course_discovery.apps.course_metadata.choices import (
CertificateType, CourseLength, CourseRunPacing, CourseRunRestrictionType, CourseRunStatus,
ExternalCourseMarketingType, ExternalProductStatus, PayeeType, ProgramStatus, ReportingType
)
from course_discovery.apps.course_metadata.constants import SUBDIRECTORY_SLUG_FORMAT_REGEX, PathwayType
from course_discovery.apps.course_metadata.fields import AutoSlugWithSlashesField, HtmlField, NullHtmlField
from course_discovery.apps.course_metadata.managers import DraftManager
from course_discovery.apps.course_metadata.people import MarketingSitePeople
from course_discovery.apps.course_metadata.publishers import (
CourseRunMarketingSitePublisher, ProgramMarketingSitePublisher
)
from course_discovery.apps.course_metadata.query import CourseQuerySet, CourseRunQuerySet, ProgramQuerySet
from course_discovery.apps.course_metadata.toggles import (
IS_SUBDIRECTORY_SLUG_FORMAT_ENABLED, IS_SUBDIRECTORY_SLUG_FORMAT_FOR_BOOTCAMP_ENABLED,
IS_SUBDIRECTORY_SLUG_FORMAT_FOR_EXEC_ED_ENABLED
)
from course_discovery.apps.course_metadata.utils import (
UploadToFieldNamePath, clean_query, clear_slug_request_cache_for_course, custom_render_variations,
get_course_run_statuses, get_slug_for_course, is_ocm_course, push_to_ecommerce_for_course_run,
push_tracks_to_lms_for_course_run, set_official_state, subtract_deadline_delta
)
from course_discovery.apps.ietf_language_tags.models import LanguageTag
from course_discovery.apps.ietf_language_tags.utils import serialize_language
from course_discovery.apps.publisher.utils import VALID_CHARS_IN_COURSE_NUM_AND_ORG_KEY
logger = logging.getLogger(__name__)
class ManageHistoryMixin(models.Model):
"""
Manages the history creation of the models based on the actual changes rather than saving without changes.
"""
def has_model_changed(self, external_keys=None, excluded_fields=None):
"""
Returns True if the model has changed, False otherwise.
Args:
external_keys (list): Names of the Foreign Keys to check
excluded_fields (list): Names of fields to exclude
Returns:
Boolean indicating if model or associated keys have changed.
"""
external_keys = external_keys if external_keys else []
excluded_fields = excluded_fields if excluded_fields else []
changed = self.field_tracker.changed()
for field in excluded_fields:
changed.pop(field, None)
return len(changed) or any(
item.has_changed for item in external_keys if hasattr(item, 'has_changed')
)
def save(self, *args, **kwargs):
"""
Sets the parameter 'skip_history_on_save' if the object is not changed
"""
if not self.has_changed:
setattr(self, 'skip_history_when_saving', True) # pylint: disable=literal-used-as-attribute
super().save(*args, **kwargs)
if hasattr(self, 'skip_history_when_saving'):
delattr(self, 'skip_history_when_saving') # pylint: disable=literal-used-as-attribute
class Meta:
abstract = True
class DraftModelMixin(models.Model):
"""
Defines a draft boolean field and an object manager to make supporting drafts more transparent.
This defines two managers. The 'everything' manager will return all rows. The 'objects' manager will exclude
draft versions by default unless you also define the 'objects' manager.
Remember to add 'draft' to your unique_together clauses.
Django doesn't allow real model mixins, but since everything has to inherit from models.Model, we shouldn't be
stepping on anyone's toes. This is the best advice I could find (at time of writing for Django 1.11).
.. no_pii:
"""
draft = models.BooleanField(default=False, help_text='Is this a draft version?')
draft_version = models.OneToOneField('self', models.SET_NULL, null=True, blank=True,
related_name='_official_version', limit_choices_to={'draft': True})
everything = models.Manager()
objects = DraftManager()
@property
def official_version(self):
"""
Related name fields will return an exception when there is no connection. In that case we want to return None
Returns:
None: if there is no Official Version
"""
try:
return self._official_version
except ObjectDoesNotExist:
return None
class Meta:
abstract = True
class CachedMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._cache = dict(self.__dict__)
def refresh_from_db(self, using=None, fields=None, **kwargs):
super().refresh_from_db(using, fields, **kwargs)
self.__dict__.pop('_cache', None)
self._cache = dict(self.__dict__)
def save(self, **kwargs):
super().save(**kwargs)
self.__dict__.pop('_cache', None)
self._cache = dict(self.__dict__)
def did_change(self, field):
return field in self.__dict__ and (field not in self._cache or getattr(self, field) != self._cache[field])
class AbstractNamedModel(TimeStampedModel):
""" Abstract base class for models with only a name field. """
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class Meta:
abstract = True
class AbstractValueModel(TimeStampedModel):
""" Abstract base class for models with only a value field. """
value = models.CharField(max_length=255)
def __str__(self):
return self.value
class Meta:
abstract = True
class AbstractMediaModel(TimeStampedModel):
""" Abstract base class for media-related (e.g. image, video) models. """
src = models.URLField(max_length=255, unique=True)
description = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.src
class Meta:
abstract = True
class AbstractTitleDescriptionModel(TimeStampedModel):
""" Abstract base class for models with a title and description pair. """
title = models.CharField(max_length=255, blank=True, null=True)
description = models.TextField(blank=True, null=True)
def __str__(self):
if self.title:
return self.title
return self.description
class Meta:
abstract = True
class AbstractHeadingBlurbModel(TimeStampedModel):
""" Abstract base class for models with a heading and html blurb pair. """
heading = models.CharField(max_length=255, blank=True, null=False)
blurb = NullHtmlField()
def __str__(self):
return self.heading if self.heading else f"{self.blurb}"
class Meta:
abstract = True
class Organization(ManageHistoryMixin, CachedMixin, TimeStampedModel):
""" Organization model. """
partner = models.ForeignKey(Partner, models.CASCADE, null=True, blank=False)
uuid = models.UUIDField(blank=False, null=False, default=uuid4, editable=True, verbose_name=_('UUID'))
key = models.CharField(max_length=255, help_text=_('Please do not use any spaces or special characters other '
'than period, underscore or hyphen. This key will be used '
'in the course\'s course key.'))
name = models.CharField(max_length=255)
certificate_name = models.CharField(
max_length=255, null=True, blank=True, help_text=_('If populated, this field will overwrite name in platform.')
)
slug = AutoSlugField(populate_from='key', editable=False, slugify_function=uslugify)
description = models.TextField(null=True, blank=True)
description_es = models.TextField(
verbose_name=_('Spanish Description'),
help_text=_('For seo, this field allows for alternate spanish description to be manually inputted'),
blank=True,
)
homepage_url = models.URLField(max_length=255, null=True, blank=True)
logo_image = models.ImageField(
upload_to=UploadToFieldNamePath(populate_from='uuid', path='organization/logos'),
blank=True,
null=True,
validators=[FileExtensionValidator(['png'])]
)
certificate_logo_image = models.ImageField(
upload_to=UploadToFieldNamePath(populate_from='uuid', path='organization/certificate_logos'),
blank=True,
null=True,
validators=[FileExtensionValidator(['png'])]
)
banner_image = models.ImageField(
upload_to=UploadToFieldNamePath(populate_from='uuid', path='organization/banner_images'),
blank=True,
null=True,
)
salesforce_id = models.CharField(max_length=255, null=True, blank=True) # Publisher_Organization__c in Salesforce
tags = TaggableManager(
blank=True,
help_text=_('Pick a tag from the suggestions. To make a new tag, add a comma after the tag name.'),
)
auto_generate_course_run_keys = models.BooleanField(
default=True,
verbose_name=_('Automatically generate course run keys'),
help_text=_(
"When this flag is enabled, the key of a new course run will be auto"
" generated. When this flag is disabled, the key can be manually set."
)
)
enterprise_subscription_inclusion = models.BooleanField(
default=False,
help_text=_('This field signifies if any of this org\'s courses are in the enterprise subscription catalog'),
)
organization_hex_color = models.CharField(
help_text=_("""The 6 character-hex-value of the orgnization theme color,
all related course under same organization will use this color as theme color.
(e.g. "#ff0000" which equals red) No need to provide the `#`"""),
validators=[RegexValidator(
regex=r'^(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$',
message='Hex color must be 3 or 6 A-F or numeric form',
code='invalid_hex_color'
)],
blank=True,
null=True,
max_length=6,
)
data_modified_timestamp = models.DateTimeField(
default=None,
null=True,
blank=True,
help_text=_('The timestamp of the last time the organization data was modified.'),
)
# Do not record the slug field in the history table because AutoSlugField is not compatible with
# django-simple-history. Background: https://github.com/openedx/course-discovery/pull/332
history = HistoricalRecords(excluded_fields=['slug'])
field_tracker = FieldTracker()
@property
def has_changed(self):
if not self.pk:
return False
return self.has_model_changed(excluded_fields=['data_modified_timestamp'])
def clean(self):
if not VALID_CHARS_IN_COURSE_NUM_AND_ORG_KEY.match(self.key):
raise ValidationError(_('Please do not use any spaces or special characters other than period, '
'underscore or hyphen in the key field.'))
class Meta:
unique_together = (
('partner', 'key'),
('partner', 'uuid'),
)
ordering = ['created']
def __str__(self):
if self.name and self.name != self.key:
return f'{self.key}: {self.name}'
else:
return self.key
@property
def marketing_url(self):
if self.slug and self.partner:
return urljoin(self.partner.marketing_site_url_root, 'school/' + self.slug)
return None
@classmethod
def user_organizations(cls, user):
return cls.objects.filter(organization_extension__group__in=user.groups.all())
def update_data_modified_timestamp(self):
"""
Update the data_modified_timestamp field to the current time if the organization data has changed.
"""
if not self.data_modified_timestamp or self.has_changed:
self.data_modified_timestamp = datetime.datetime.now(pytz.UTC)
def save(self, *args, **kwargs):
"""
We cache the key here before saving the record so that we can hit the correct
endpoint in lms.
"""
key = self._cache['key']
self.update_data_modified_timestamp()
super().save(*args, **kwargs)
key = key or self.key
partner = self.partner
data = {
'name': self.certificate_name or self.name,
'short_name': self.key,
'description': self.description,
}
logo = self.certificate_logo_image
if logo:
base_url = getattr(settings, 'ORG_BASE_LOGO_URL', None)
logo_url = f'{base_url}{logo}' if base_url else logo.url
data['logo_url'] = logo_url
organizations_url = f'{partner.organizations_api_url}organizations/{key}/'
try:
partner.oauth_api_client.put(organizations_url, json=data)
except requests.exceptions.ConnectionError as e:
logger.error('[%s]: Unable to push organization [%s] to lms.', e, self.uuid)
except Exception as e:
raise e
class OrganizationMapping(models.Model):
"""
Model to map external/third party organization codes to organizations internal to Discovery.
"""
organization = models.ForeignKey('Organization', models.CASCADE)
source = models.ForeignKey('Source', models.CASCADE)
organization_external_key = models.CharField(
max_length=255,
help_text=_('Corresponding organization code in an external product source')
)
def __str__(self):
return f'{self.source.name} - {self.organization_external_key} -> {self.organization.name}'
class Meta:
"""
Meta options.
"""
unique_together = ('source', 'organization_external_key')
class Image(AbstractMediaModel):
""" Image model. """
height = models.IntegerField(null=True, blank=True)
width = models.IntegerField(null=True, blank=True)
class Video(ManageHistoryMixin, AbstractMediaModel):
""" Video model. """
image = models.ForeignKey(Image, models.CASCADE, null=True, blank=True)
field_tracker = FieldTracker()
@property
def has_changed(self):
if not self.pk:
return False
return self.has_model_changed()
def __str__(self):
return f'{self.src}: {self.description}'
class LevelType(TranslatableModel, TimeStampedModel):
""" LevelType model. """
# This field determines ordering by which level types are presented in the
# Publisher tool, by virtue of the order in which the level types are
# returned by the serializer, and in turn the OPTIONS requests against the
# course and courserun view sets.
name = models.CharField(max_length=255)
sort_value = models.PositiveSmallIntegerField(default=0, db_index=True)
def __str__(self):
return self.name_t
class Meta:
ordering = ('sort_value',)
class LevelTypeTranslation(TranslatedFieldsModel):
master = models.ForeignKey(LevelType, models.CASCADE, related_name='translations', null=True)
name_t = models.CharField('name', max_length=255)
class Meta:
unique_together = (('language_code', 'name_t'), ('language_code', 'master'))
verbose_name = _('LevelType model translations')
class SeatType(TimeStampedModel):
name = models.CharField(max_length=64)
slug = AutoSlugField(populate_from='name', slugify_function=uslugify, unique=True)
def __str__(self):
return self.name
class ProgramType(TranslatableModel, TimeStampedModel):
XSERIES = 'xseries'
MICROMASTERS = 'micromasters'
PROFESSIONAL_CERTIFICATE = 'professional-certificate'
PROFESSIONAL_PROGRAM_WL = 'professional-program-wl'
MASTERS = 'masters'
BACHELORS = 'bachelors'
DOCTORATE = 'doctorate'
LICENSE = 'license'
CERTIFICATE = 'certificate'
MICROBACHELORS = 'microbachelors'
name = models.CharField(max_length=32, blank=False)
applicable_seat_types = models.ManyToManyField(
SeatType, help_text=_('Seat types that qualify for completion of programs of this type. Learners completing '
'associated courses, but enrolled in other seat types, will NOT have their completion '
'of the course counted toward the completion of the program.'),
)
logo_image = StdImageField(
upload_to=UploadToFieldNamePath(populate_from='name', path='media/program_types/logo_images/'),
blank=True,
null=True,
variations={
'large': (256, 256),
'medium': (128, 128),
'small': (64, 64),
'x-small': (32, 32),
},
help_text=_('Please provide an image file with transparent background'),
)
slug = AutoSlugField(populate_from='name_t', editable=True, unique=True, slugify_function=uslugify,
help_text=_('Leave this field blank to have the value generated automatically.'))
uuid = models.UUIDField(default=uuid4, editable=False, verbose_name=_('UUID'), unique=True)
coaching_supported = models.BooleanField(default=False)
# Do not record the slug field in the history table because AutoSlugField is not compatible with
# django-simple-history. Background: https://github.com/openedx/course-discovery/pull/332
history = HistoricalRecords(excluded_fields=['slug'])
def __str__(self):
return self.name_t
@staticmethod
def get_program_type_data(pub_course_run, program_model):
slug = None
name = None
program_type = None
if pub_course_run.is_micromasters:
slug = ProgramType.MICROMASTERS
name = pub_course_run.micromasters_name
elif pub_course_run.is_professional_certificate:
slug = ProgramType.PROFESSIONAL_CERTIFICATE
name = pub_course_run.professional_certificate_name
elif pub_course_run.is_xseries:
slug = ProgramType.XSERIES
name = pub_course_run.xseries_name
if slug:
program_type = program_model.objects.get(slug=slug)
return program_type, name
@classmethod
def is_enterprise_catalog_program_type(cls, program_type):
return program_type.slug in [
cls.XSERIES, cls.MICROMASTERS, cls.PROFESSIONAL_CERTIFICATE, cls.PROFESSIONAL_PROGRAM_WL, cls.MICROBACHELORS
]
class Source(TimeStampedModel):
"""
Source Model to find where a course or program originated from.
"""
name = models.CharField(max_length=255, help_text=_('Name of the external source.'))
slug = AutoSlugField(
populate_from='name', editable=True, slugify_function=uslugify, overwrite_on_add=False,
help_text=_('Leave this field blank to have the value generated automatically.')
)
description = models.CharField(max_length=255, blank=True, help_text=_('Description of the external source.'))
ofac_restricted_program_types = SortedManyToManyField(
ProgramType,
blank=True,
related_name='ofac_restricted_source',
help_text=_('Programs of these types will be OFAC restricted')
)
def __str__(self):
return self.name
class ProgramTypeTranslation(TranslatedFieldsModel):
master = models.ForeignKey(ProgramType, models.CASCADE, related_name='translations', null=True)
name_t = models.CharField("name", max_length=32, blank=False, null=False)
class Meta:
unique_together = (('language_code', 'master'), ('name_t', 'language_code'))
verbose_name = _('ProgramType model translations')
class Mode(TimeStampedModel):
"""
This model is similar to the LMS CourseMode model.
It holds several fields that (one day will) control logic for handling enrollments in this mode.
Examples of names would be "Verified", "Credit", or "Masters"
See docs/decisions/0009-LMS-types-in-course-metadata.rst for more information.
"""
name = models.CharField(max_length=64)
slug = models.CharField(max_length=64, unique=True)
is_id_verified = models.BooleanField(default=False, help_text=_('This mode requires ID verification.'))
is_credit_eligible = models.BooleanField(
default=False,
help_text=_('Completion can grant credit toward an organization’s degree.'),
)
certificate_type = models.CharField(
max_length=64, choices=CertificateType.choices, blank=True,
help_text=_('Certificate type granted if this mode is eligible for a certificate, or blank if not.'),
)
payee = models.CharField(
max_length=64, choices=PayeeType.choices, default='', blank=True,
help_text=_('Who gets paid for the course? Platform is the site owner, Organization is the school.'),
)
history = HistoricalRecords()
def __str__(self):
return self.name
@property
def is_certificate_eligible(self):
"""
Returns True if completion can impart any kind of certificate to the learner.
"""
return bool(self.certificate_type)
class Track(TimeStampedModel):
"""
This model ties a Mode (an LMS concept) with a SeatType (an E-Commerce concept)
Basically, a track is all the metadata for a single enrollment type, with both the course logic and product sides.
See docs/decisions/0009-LMS-types-in-course-metadata.rst for more information.
"""
seat_type = models.ForeignKey(SeatType, models.CASCADE, null=True, blank=True)
mode = models.ForeignKey(Mode, models.CASCADE)
history = HistoricalRecords()
def __str__(self):
return self.mode.name
class CourseRunType(TimeStampedModel):
"""
This model defines the enrollment options (Tracks) for a given course run.
A single course might have runs with different enrollment options. Like a course that has a
"Masters, Verified, and Audit" CourseType might contain CourseRunTypes named
- "Masters, Verified, and Audit" (pointing to three different tracks)
- "Verified and Audit"
- "Audit only"
- "Masters only"
See docs/decisions/0009-LMS-types-in-course-metadata.rst for more information.
"""
AUDIT = 'audit'
VERIFIED_AUDIT = 'verified-audit'
PROFESSIONAL = 'professional'
CREDIT_VERIFIED_AUDIT = 'credit-verified-audit'
HONOR = 'honor'
VERIFIED_HONOR = 'verified-honor'
VERIFIED_AUDIT_HONOR = 'verified-audit-honor'
EMPTY = 'empty'
PAID_EXECUTIVE_EDUCATION = 'paid-executive-education'
UNPAID_EXECUTIVE_EDUCATION = 'unpaid-executive-education'
PAID_BOOTCAMP = 'paid-bootcamp'
UNPAID_BOOTCAMP = 'unpaid-bootcamp'
uuid = models.UUIDField(default=uuid4, editable=False, verbose_name=_('UUID'), unique=True)
name = models.CharField(max_length=64)
slug = models.CharField(max_length=64, unique=True)
tracks = models.ManyToManyField(Track)
is_marketable = models.BooleanField(default=True)
history = HistoricalRecords()
def __str__(self):
return self.name
@property
def empty(self):
""" Empty types are special - they are the default type used when we don't know a real type """
return self.slug == self.EMPTY
class CourseType(TimeStampedModel):
"""
This model defines the permissible types of enrollments provided by a whole course.
It holds a list of permissible entitlement options and a list of permissible CourseRunTypes.
Examples of names would be "Masters, Verified, and Audit" or "Verified and Audit"
"""
AUDIT = 'audit'
VERIFIED_AUDIT = 'verified-audit'
PROFESSIONAL = 'professional'
CREDIT_VERIFIED_AUDIT = 'credit-verified-audit'
EMPTY = 'empty'
EXECUTIVE_EDUCATION_2U = 'executive-education-2u'
BOOTCAMP_2U = 'bootcamp-2u'
uuid = models.UUIDField(default=uuid4, editable=False, verbose_name=_('UUID'), unique=True)
name = models.CharField(max_length=64)
slug = models.CharField(max_length=64, unique=True)
entitlement_types = models.ManyToManyField(SeatType, blank=True)
course_run_types = SortedManyToManyField(
CourseRunType, help_text=_('Sets the order for displaying Course Run Types.')
)
white_listed_orgs = models.ManyToManyField(Organization, blank=True, help_text=_(
'Leave this blank to allow all orgs. Otherwise, specifies which orgs can see this course type in Publisher.'
))
history = HistoricalRecords()
def __str__(self):
return self.name
@property
def empty(self):
""" Empty types are special - they are the default type used when we don't know a real type """
return self.slug == self.EMPTY
class Subject(TranslatableModel, TimeStampedModel):
""" Subject model. """
uuid = models.UUIDField(blank=False, null=False, default=uuid4, editable=False, verbose_name=_('UUID'))
banner_image_url = models.URLField(blank=True, null=True)
card_image_url = models.URLField(blank=True, null=True)
slug = AutoSlugField(populate_from='name', editable=True, blank=True, slugify_function=uslugify,
help_text=_('Leave this field blank to have the value generated automatically.'))
partner = models.ForeignKey(Partner, models.CASCADE)
def __str__(self):
return self.name
class Meta:
unique_together = (
('partner', 'slug'),
('partner', 'uuid'),
)
ordering = ['created']
def validate_unique(self, *args, **kwargs):
super().validate_unique(*args, **kwargs)
qs = Subject.objects.filter(partner=self.partner_id)
if qs.filter(translations__name=self.name).exclude(pk=self.pk).exists():
raise ValidationError({'name': ['Subject with this Name and Partner already exists', ]})
class SubjectTranslation(TranslatedFieldsModel):
master = models.ForeignKey(Subject, models.CASCADE, related_name='translations', null=True)
name = models.CharField(max_length=255, blank=False, null=False)
subtitle = models.CharField(max_length=255, blank=True, null=True)
description = models.TextField(blank=True, null=True)
class Meta:
unique_together = ('language_code', 'master')
verbose_name = _('Subject model translations')
class Topic(ManageHistoryMixin, TranslatableModel, TimeStampedModel):
""" Topic model. """
uuid = models.UUIDField(blank=False, null=False, default=uuid4, editable=False, verbose_name=_('UUID'))
banner_image_url = models.URLField(blank=True, null=True)
slug = AutoSlugField(populate_from='name', editable=True, blank=True, slugify_function=uslugify,
help_text=_('Leave this field blank to have the value generated automatically.'))
partner = models.ForeignKey(Partner, models.CASCADE)
def __str__(self):
return self.name
class Meta:
unique_together = (
('partner', 'slug'),
('partner', 'uuid'),
)
ordering = ['created']
field_tracker = FieldTracker()
@property
def has_changed(self):
if not self.pk:
return False
return self.has_model_changed()
def validate_unique(self, *args, **kwargs):
super().validate_unique(*args, **kwargs)
qs = Topic.objects.filter(partner=self.partner_id)
if qs.filter(translations__name=self.name).exclude(pk=self.pk).exists():
raise ValidationError({'name': ['Topic with this Name and Partner already exists', ]})
class TopicTranslation(TranslatedFieldsModel):
master = models.ForeignKey(Topic, models.CASCADE, related_name='translations', null=True)
name = models.CharField(max_length=255, blank=False, null=False)
subtitle = models.CharField(max_length=255, blank=True, null=True)
description = models.TextField(blank=True, null=True)
long_description = models.TextField(blank=True, null=True)
class Meta:
unique_together = ('language_code', 'master')
verbose_name = _('Topic model translations')
class Fact(ManageHistoryMixin, AbstractHeadingBlurbModel):
""" Fact Model """
field_tracker = FieldTracker()
@property
def has_changed(self):
if not self.pk:
return False
return self.has_model_changed()
def update_product_data_modified_timestamp(self):
if self.has_changed:
logger.info(
f"Fact update_product_data_modified_timestamp triggered for {self.pk}."
f"Updating timestamp for related courses."
)
Course.everything.filter(additional_metadata__facts__pk=self.pk).update(
data_modified_timestamp=datetime.datetime.now(pytz.UTC)
)
class CertificateInfo(ManageHistoryMixin, AbstractHeadingBlurbModel):
""" Certificate Information Model """
field_tracker = FieldTracker()
@property
def has_changed(self):
if not self.pk:
return False
return self.has_model_changed()
def update_product_data_modified_timestamp(self):
if self.has_changed:
logger.info(f"Changes detected in CertificateInfo {self.pk}, updating related courses")
Course.everything.filter(additional_metadata__certificate_info__pk=self.pk).update(
data_modified_timestamp=datetime.datetime.now(pytz.UTC)
)
class ProductMeta(ManageHistoryMixin, TimeStampedModel):
"""
Model to contain SEO/Meta information for a product.
"""
title = models.CharField(
max_length=200, default='', null=True, blank=True,
help_text="Product title that will appear in meta tag for search engine ranking"
)
description = models.CharField(
max_length=255, default='', null=True, blank=True,
help_text="Product description that will appear in meta tag for search engine ranking"
)
keywords = TaggableManager(
blank=True,
related_name='product_metas',
help_text=_('SEO Meta tags for Products'),
)
field_tracker = FieldTracker()
@property
def has_changed(self):
if not self.pk:
return False
return self.has_model_changed()
def update_product_data_modified_timestamp(self, bypass_has_changed=False):
if self.has_changed or bypass_has_changed:
logger.info(
f"ProductMeta update_product_data_modified_timestamp triggered for {self.pk}."
f"Updating timestamp for related courses."
)
Course.everything.filter(additional_metadata__product_meta__pk=self.pk).update(
data_modified_timestamp=datetime.datetime.now(pytz.UTC)
)
def __str__(self):
return self.title
class TaxiForm(ManageHistoryMixin, TimeStampedModel):
"""
Represents the data needed for a single Taxi (2U form library) lead capture form.
"""
form_id = models.CharField(
help_text=_('The ID of the Taxi Form (by 2U) that would be rendered in place of the hubspot capture form'),
max_length=75,
blank=True,
default='',
)
grouping = models.CharField(
help_text=_('The grouping of the Taxi Form (by 2U) that would be rendered instead of the hubspot capture form'),
max_length=50,
blank=True,
default='',
)
title = models.CharField(max_length=255, default=None, null=True, blank=True)
subtitle = models.CharField(max_length=255, default=None, null=True, blank=True)
post_submit_url = models.URLField(null=True, blank=True)
field_tracker = FieldTracker()
@property
def has_changed(self):
if not self.pk:
return False
return self.has_model_changed()
def __str__(self):
return f"{self.title}({self.form_id})"
class AdditionalMetadata(ManageHistoryMixin, TimeStampedModel):
"""
This model holds 2U related additional fields.
"""
external_url = models.URLField(
blank=False, null=False, max_length=511,
help_text=_('The URL of the paid landing page on external site')
)
external_identifier = models.CharField(max_length=255, blank=True, null=False)
lead_capture_form_url = models.URLField(blank=True, null=False, max_length=511)
organic_url = models.URLField(
blank=True, null=False, max_length=511,
help_text=_('The URL of the organic landing page on external site')
)
facts = models.ManyToManyField(
Fact, blank=True, related_name='related_course_additional_metadata',
)
certificate_info = models.ForeignKey(
CertificateInfo, models.CASCADE, default=None, null=True, blank=True,
related_name='related_course_additional_metadata',
)
start_date = models.DateTimeField(
default=None, blank=True, null=True,
help_text=_('The start date of the external course offering for marketing purpose')
)
end_date = models.DateTimeField(
default=None, blank=True, null=True,
help_text=_('The ends date of the external course offering for marketing purpose')
)
registration_deadline = models.DateTimeField(
default=None, blank=True, null=True,
help_text=_('The suggested deadline for enrollment for marketing purpose')
)
variant_id = models.UUIDField(
blank=False, null=True, editable=False,
help_text=_('The identifier for a product variant.')
)
course_term_override = models.CharField(
max_length=20,
verbose_name=_('Course override'),
help_text=_('This field allows for override the default course term'),
blank=True,
null=True,
default=None,
)
product_meta = models.OneToOneField(
ProductMeta,
on_delete=models.DO_NOTHING,
blank=True,
null=True,
default=None,
related_name="product_additional_metadata"
)
taxi_form = models.OneToOneField(
TaxiForm,
on_delete=models.DO_NOTHING,
blank=True,
null=True,
default=None,
related_name='additional_metadata',
)
product_status = models.CharField(
default=ExternalProductStatus.Published, max_length=50, null=False, blank=False,
choices=ExternalProductStatus.choices
)
external_course_marketing_type = models.CharField(
help_text=_('This field contain external course marketing type specific to product lines'),
max_length=50,
blank=True,
null=True,
default=None,
choices=ExternalCourseMarketingType.choices,
)
display_on_org_page = models.BooleanField(
null=False, default=True,
help_text=_('Determines weather the course should be displayed on the owning organization\'s page')
)
field_tracker = FieldTracker()
@property
def has_changed(self):
if not self.pk:
return False
external_keys = [self.product_meta,]
return self.has_model_changed(external_keys=external_keys)
def update_product_data_modified_timestamp(self, bypass_has_changed=False):
if self.has_changed or bypass_has_changed:
logger.info(
f"AdditionalMetadata update_product_data_modified_timestamp triggered for {self.external_identifier}."
f"Updating data modified timestamp for related courses."
)
self.related_courses.all().update(
data_modified_timestamp=datetime.datetime.now(pytz.UTC)
)
def __str__(self):
return f"{self.external_url} - {self.external_identifier}"
class Prerequisite(AbstractNamedModel):
""" Prerequisite model. """
class ExpectedLearningItem(AbstractValueModel):
""" ExpectedLearningItem model. """
class JobOutlookItem(AbstractValueModel):
""" JobOutlookItem model. """