-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmodels.py
More file actions
2106 lines (1712 loc) · 67.2 KB
/
models.py
File metadata and controls
2106 lines (1712 loc) · 67.2 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 datetime
import os
import re
import uuid
import warnings
from email.mime.image import MIMEImage
from io import BytesIO
from smtplib import SMTPAuthenticationError, SMTPServerDisconnected
from urllib.parse import urlparse
import pytz
import qrcode
import requests
import yaml
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives
from django.core.validators import validate_email
from django.db import models, transaction
from django.db.models import Sum
from django.db.models.deletion import ProtectedError
from django.dispatch import receiver
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.functional import cached_property
from ics import Calendar
from jinja2 import Environment, meta
from model_clone.models import CloneModel
from phonenumber_field.modelfields import PhoneNumberField
from simple_history.models import HistoricalRecords
from urlextract import URLExtract
from clubs.utils import clean, get_django_minified_image, get_domain, html_to_text
subject_regex = re.compile(r"\s*<!--\s*SUBJECT:\s*(.*?)\s*-->", re.I)
types_regex = re.compile(r"\s*<!--\s*TYPES:\s*(.*?)\s*-->", re.DOTALL)
def get_mail_type_annotation(name):
"""
Given a template name, return the type annotation metadata.
"""
prefix = {"fyh": "fyh_emails"}.get(settings.BRANDING, "emails")
path = os.path.join(settings.BASE_DIR, "templates", prefix, f"{name}.html")
with open(path, "r") as f:
contents = f.read()
match = types_regex.search(contents)
if match is not None:
return yaml.safe_load(match.group(1).strip())
return None
def send_mail_helper(
name, subject, emails, context, attachment=None, reply_to=None, num_retries=2
):
"""
A helper to send out an email given the template name, subject, to emails,
and context. Returns true if an email was sent out, or false if no emails
were sent out.
All emails should go through this function.
"""
if not all(isinstance(email, str) for email in emails):
raise ValueError("The to email argument must be a list of strings!")
# emulate django behavior of silently returning without recipients
emails = [email for email in emails if email]
if not emails:
return False
# load email template
prefix = {"fyh": "fyh_emails"}.get(settings.BRANDING, "emails")
html_content = render_to_string(f"{prefix}/{name}.html", context)
# use subject from template if it exists
# subject should match: <!-- SUBJECT: (subject) --> and be the first line
match = subject_regex.search(html_content)
if match is not None:
subject = match.group(1)
html_content = subject_regex.sub("", html_content, count=1)
# remove type annotation comment
match = types_regex.search(html_content)
if match is not None:
html_content = types_regex.sub("", html_content, count=1)
else:
warnings.warn(
f"There is no type annotation information for the template '{name}'! "
"Email previews may work incorrectly without type information.",
SyntaxWarning,
)
if subject is None:
raise ValueError(
"You must specify a email subject as an argument or in the template! \n"
f"The following output was generated from the template:\n\n{html_content}"
)
# generate text alternative
text_content = html_to_text(html_content)
msg = EmailMultiAlternatives(
subject, text_content, settings.FROM_EMAIL, list(set(emails)), reply_to=reply_to
)
if attachment is not None:
if "filename" in attachment and "path" in attachment:
with open(attachment["path"], "rb") as file:
msg.attach(
attachment["filename"],
file.read(),
"application/vnd.openxmlformats-officedocument."
+ "wordprocessingml.document",
)
else: # assumes attachment is an image
image = MIMEImage(attachment["content"], _subtype=attachment["mimetype"])
image.add_header("Content-ID", f'<{context["cid"]}>')
image.add_header(
"Content-Disposition", "inline", filename=attachment["filename"]
)
msg.attach(image)
msg.mixed_subtype = "related"
msg.attach_alternative(html_content, "text/html")
# Retry to avoid one-off SMTP errors
for attempt in range(num_retries + 1):
try:
msg.send(fail_silently=False)
return True
except (SMTPServerDisconnected, SMTPAuthenticationError) as e:
if attempt == num_retries:
raise e
def get_asset_file_name(instance, fname):
return os.path.join("assets", uuid.uuid4().hex, fname)
def get_club_file_name(instance, fname):
return os.path.join(
"clubs", "{}.{}".format(instance.code, fname.rsplit(".", 1)[-1])
)
def get_club_small_file_name(instance, fname):
return os.path.join(
"clubs_small", "{}.{}".format(instance.code, fname.rsplit(".", 1)[-1])
)
def get_event_file_name(instance, fname):
return os.path.join("events", "{}.{}".format(instance.id, fname.rsplit(".", 1)[-1]))
def get_event_small_file_name(instance, fname):
return os.path.join(
"events_small", "{}.{}".format(instance.id, fname.rsplit(".", 1)[-1])
)
def get_membership_image_file_name(instance, fname):
return os.path.join(
"membership",
"{}.{}.{}".format(
instance.club.code, instance.person.username, fname.rsplit(".", 1)[-1]
),
)
def get_user_file_name(instance, fname):
return os.path.join(
"users", "{}.{}".format(instance.user.username, fname.rsplit(".", 1)[-1])
)
class Report(models.Model):
"""
Represents a report generated by the reporting feature.
"""
name = models.TextField()
creator = models.ForeignKey(get_user_model(), on_delete=models.SET_NULL, null=True)
description = models.TextField(blank=True)
parameters = models.TextField(blank=True)
public = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Meta:
ordering = ["name"]
permissions = [
("generate_reports", "Can generate reports"),
]
def create_thumbnail_helper(self, request, height):
"""
Helper to create thumbnail on "image_small" given "image" exists on the model.
"""
if not self.image:
return False
image_url = self.image.url
# can't minify svgs
if image_url.endswith(".svg"):
return False
# fix path for development
if not image_url.startswith("http"):
if request is not None:
image_url = request.build_absolute_uri(image_url)
else:
return False
# if failed to download image, ignore
try:
self.image_small = get_django_minified_image(image_url, height=height)
self.skip_history_when_saving = True
self.save(update_fields=["image_small"])
except requests.exceptions.RequestException:
return False
return True
class Club(models.Model):
"""
Represents a club at the University of Pennsylvania.
"""
RECRUITING_UNKNOWN = 1
RECRUITING_FALL = 2
RECRUITING_SPRING = 3
RECRUITING_BOTH = 4
RECRUITING_OPEN = 5
RECRUITING_CYCLES = (
(RECRUITING_UNKNOWN, "Unknown"),
(RECRUITING_FALL, "Fall"),
(RECRUITING_SPRING, "Spring"),
(RECRUITING_BOTH, "Both"),
(RECRUITING_OPEN, "Open"),
)
SIZE_SMALL = 1
SIZE_MEDIUM = 2
SIZE_LARGE = 3
SIZE_VERY_LARGE = 4
SIZE_CHOICES = (
(SIZE_SMALL, "1-20"),
(SIZE_MEDIUM, "21-50"),
(SIZE_LARGE, "51-100"),
(SIZE_VERY_LARGE, "101+"),
)
OPEN_MEMBERSHIP = 1
TRYOUT = 2
AUDITION = 3
APPLICATION = 4
APPLICATION_AND_INTERVIEW = 5
APPLICATION_CHOICES = (
(OPEN_MEMBERSHIP, "Open Membership"),
(AUDITION, "Audition Required"),
(TRYOUT, "Tryout Required"),
(APPLICATION, "Application Required"),
(APPLICATION_AND_INTERVIEW, "Application and Interview Required"),
)
approved = models.BooleanField(null=True, default=None)
approved_by = models.ForeignKey(
get_user_model(),
null=True,
on_delete=models.SET_NULL,
related_name="approved_clubs",
blank=True,
)
approved_comment = models.TextField(null=True, blank=True)
approved_on = models.DateTimeField(null=True, blank=True, db_index=True)
archived = models.BooleanField(default=False)
archived_by = models.ForeignKey(
get_user_model(),
null=True,
on_delete=models.SET_NULL,
related_name="archived_clubs",
blank=True,
)
archived_on = models.DateTimeField(null=True, blank=True)
code = models.SlugField(max_length=255, unique=True, db_index=True)
active = models.BooleanField(default=False)
beta = models.BooleanField(default=False) # opts club into all beta features
name = models.CharField(max_length=255)
subtitle = models.CharField(blank=True, max_length=255)
terms = models.CharField(blank=True, max_length=1024)
description = models.TextField(blank=True) # rich html
address = models.TextField(blank=True)
founded = models.DateField(blank=True, null=True)
size = models.IntegerField(choices=SIZE_CHOICES, default=SIZE_SMALL)
email = models.EmailField(blank=True, null=True)
email_public = models.BooleanField(default=True)
facebook = models.URLField(blank=True, null=True)
website = models.URLField(blank=True, null=True)
twitter = models.URLField(blank=True, null=True)
instagram = models.URLField(blank=True, null=True)
linkedin = models.URLField(blank=True, null=True)
github = models.URLField(blank=True, null=True)
youtube = models.URLField(blank=True, null=True)
how_to_get_involved = models.TextField(blank=True) # html
application_required = models.IntegerField(
choices=APPLICATION_CHOICES, default=APPLICATION
)
accepting_members = models.BooleanField(default=False)
student_types = models.ManyToManyField("StudentType", through="TargetStudentType")
recruiting_cycle = models.IntegerField(
choices=RECRUITING_CYCLES, default=RECRUITING_UNKNOWN
)
enables_subscription = models.BooleanField(default=True)
listserv = models.CharField(blank=True, max_length=255)
ics_import_url = models.URLField(max_length=200, blank=True, null=True)
image = models.ImageField(upload_to=get_club_file_name, null=True, blank=True)
image_small = models.ImageField(
upload_to=get_club_small_file_name, null=True, blank=True
)
tags = models.ManyToManyField("Tag")
members = models.ManyToManyField(get_user_model(), through="Membership")
# Represents which organizations this club is directly under in the org structure.
# For example, SAC is a parent of PAC, which is a parent of TAC-E which is a parent
# of Penn Players.
parent_orgs = models.ManyToManyField(
"Club", related_name="children_orgs", blank=True
)
badges = models.ManyToManyField("Badge", blank=True)
target_years = models.ManyToManyField("Year", through="TargetYear")
target_schools = models.ManyToManyField("School", through="TargetSchool")
target_majors = models.ManyToManyField("Major", through="TargetMajor")
# Hub@Penn fields
available_virtually = models.BooleanField(default=False)
appointment_needed = models.BooleanField(default=False)
signature_events = models.TextField(blank=True) # html
# cache club aggregation counts
favorite_count = models.IntegerField(default=0)
membership_count = models.IntegerField(default=0)
# cache club rankings
rank = models.IntegerField(default=0, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
ghost = models.BooleanField(default=False)
history = HistoricalRecords(cascade_delete_history=True)
def __str__(self):
return self.name
def create_thumbnail(self, request=None):
return create_thumbnail_helper(self, request, 200)
@cached_property
def is_wharton(self):
return any(badge.label == "Wharton Council" for badge in self.badges.all())
def add_ics_events(self):
"""
Fetch the ICS events from the club's calendar URL
and return the number of modified events.
"""
# random but consistent uuid used to generate uuid5s from invalid uuids
ics_import_uuid_namespace = uuid.UUID("8f37c140-3775-42e8-91d4-fda7a2e44152")
extractor = URLExtract()
url = self.ics_import_url
if url:
calendar = Calendar(requests.get(url).text)
event_list = Event.objects.filter(is_ics_event=True, club=self)
modified_events = []
for event in calendar.events:
tries = [
Event.objects.filter(
club=self,
start_time=event.begin.datetime,
end_time=event.end.datetime,
).first(),
Event(),
]
# try matching using uuid if it is valid
if event.uid:
try:
event_uuid = uuid.UUID(event.uid[:36])
except ValueError:
# generate uuid from malformed/invalid uuids
event_uuid = uuid.uuid5(ics_import_uuid_namespace, event.uid)
tries.insert(0, Event.objects.filter(ics_uuid=event_uuid).first())
else:
event_uuid = None
for ev in tries:
if ev:
ev.club = self
ev.name = event.name.strip()
ev.start_time = event.begin.datetime
ev.end_time = event.end.datetime
ev.description = clean(event.description.strip())
ev.location = event.location
ev.is_ics_event = True
# very simple type detection, only perform on first time
if ev.pk is None:
ev.type = Event.OTHER
for val, lbl in Event.TYPES:
if val in {Event.FAIR}:
continue
if (
lbl.lower() in ev.name.lower()
or lbl.lower() in ev.description.lower()
):
ev.type = val
break
# extract urls from description
if ev.description:
urls = extractor.find_urls(ev.description)
urls.sort(
key=lambda url: any(
domain in url
for domain in {
"zoom.us",
"bluejeans.com",
"hangouts.google.com",
}
),
reverse=True,
)
if urls:
ev.url = urls[0]
# extract url from url or location
if event.url:
ev.url = event.url
elif ev.location:
location_urls = extractor.find_urls(ev.location)
if location_urls:
ev.url = location_urls[0]
# format url properly with schema
if ev.url:
parsed = urlparse(ev.url)
if not parsed.netloc:
parsed = parsed._replace(netloc=parsed.path, path="")
if not parsed.scheme:
parsed = parsed._replace(scheme="https")
ev.url = parsed.geturl()
# add uuid if it exists, otherwise will be autogenerated
if event_uuid:
ev.ics_uuid = event_uuid
# ensure length limits are met before saving
if ev.location:
ev.location = ev.location[:255]
if ev.name:
ev.name = ev.name[:255]
if ev.code:
ev.code = ev.code[:255]
if ev.url:
ev.url = ev.url[:2048]
ev.save()
modified_events.append(ev)
break
event_list.exclude(pk__in=[e.pk for e in modified_events]).delete()
return len(modified_events)
return 0
def send_virtual_fair_email(
self, request=None, email="setup", fair=None, emails=None, extra=False
):
"""
Send an email to all club officers about setting
up their club for the virtual fair.
If no list of emails is specified, the officer emails for the club will be used.
If no fair is specified, the closest upcoming fair will be used.
"""
domain = get_domain(request)
now = timezone.now()
if fair is None:
fair = (
ClubFair.objects.filter(start_time__gte=now)
.order_by("start_time")
.first()
)
eastern = pytz.timezone("America/New_York")
events = self.events.filter(
start_time__gte=fair.start_time,
end_time__lte=fair.end_time,
type=Event.FAIR,
).order_by("start_time")
event = events.first()
fstr = "%B %d, %Y %I:%M %p"
events = [
{
"time": f"{timezone.localtime(start, eastern).strftime(fstr)} - "
f"{timezone.localtime(end, eastern).strftime(fstr)} ET"
}
for start, end in events.values_list("start_time", "end_time")
]
prefix = (
"ACTION REQUIRED"
if event is None or not event.url or "zoom.us" not in event.url
else "REMINDER"
)
# if one day before fair, change prefix to urgent
if fair.start_time - datetime.timedelta(days=1) < now:
prefix = "URGENT"
# if no emails specified, send to officers
if emails is None:
emails = self.get_officer_emails()
fair_str = fair.id if fair is not None else ""
context = {
"name": self.name,
"prefix": prefix,
"guide_url": f"https://{domain}/guides/fair",
"media_guide_url": f"https://{domain}/guides/media",
"zoom_url": f"https://{domain}/zoom",
"fair_url": f"https://{domain}/fair?fair={fair_str}",
"subscriptions_url": f"https://{domain}/club/{self.code}/edit/recruitment",
"num_subscriptions": self.subscribe_set.count(),
"fair": fair,
"events": events,
"extra": extra,
}
if emails:
return send_mail_helper(
name={
"setup": "fair_info",
"urgent": "fair_reminder",
"post": "fair_feedback_officers",
}[email],
subject=None,
emails=emails,
context=context,
)
return False
def send_renewal_email(self, request=None):
"""
Send an email notifying all club officers about renewing their approval with the
Office of Student Affairs and registering for the SAC fair.
"""
domain = get_domain(request)
context = {
"name": self.name,
"url": settings.RENEWAL_URL.format(domain=domain, club=self.code),
}
emails = self.get_officer_emails()
if emails:
send_mail_helper(
name="renew",
subject="[ACTION REQUIRED] Renew {} and SAC Fair Registration".format(
self.name
),
emails=emails,
context=context,
reply_to=settings.OSA_EMAILS + [settings.BRANDING_SITE_EMAIL],
)
def send_renewal_reminder_email(self, request=None):
"""
Send a reminder email to clubs about renewing their approval
with the approval authority and registering for activities fairs.
"""
domain = get_domain(request)
context = {
"name": self.name,
"url": settings.RENEWAL_URL.format(domain=domain, club=self.code),
"year": timezone.now().year,
}
emails = self.get_officer_emails()
if emails:
send_mail_helper(
name="renewal_reminder",
subject="[ACTION REQUIRED] Renew {} and SAC Fair Registration".format(
self.name
),
emails=emails,
context=context,
reply_to=settings.OSA_EMAILS + [settings.BRANDING_SITE_EMAIL],
)
def get_officer_emails(self):
"""
Return a list of club officer emails, including the contact email for the club.
"""
emails = []
# Add club contact email if valid
if self.email:
try:
validate_email(self.email)
emails.append(self.email)
except ValidationError:
pass
# Add email for all active officers and above
emails.extend(
self.membership_set.filter(
role__lte=Membership.ROLE_OFFICER, active=True
).values_list("person__email", flat=True)
)
# Remove whitespace, empty emails, and duplicates, then sort
return sorted(set(email.strip() for email in emails if email.strip()))
def send_confirmation_email(self, request=None):
"""
Send an email to the club officers confirming that
their club has been queued for approval.
"""
domain = get_domain(request)
emails = self.get_officer_emails()
context = {
"name": self.name,
"view_url": settings.VIEW_URL.format(domain=domain, club=self.code),
}
if emails:
send_mail_helper(
name="confirmation",
subject=f"{self.name} has been queued for approval",
emails=emails,
context=context,
reply_to=settings.OSA_EMAILS + [settings.BRANDING_SITE_EMAIL],
)
def send_approval_email(self, request=None, change=False):
"""
Send either an approval or rejection email to the club officers
after their club has been reviewed.
"""
domain = get_domain(request)
context = {
"name": self.name,
"year": timezone.now().year,
"approved": self.approved,
"approved_comment": self.approved_comment,
"view_url": settings.VIEW_URL.format(domain=domain, club=self.code),
"edit_url": settings.EDIT_URL.format(domain=domain, club=self.code),
"change": change,
"reply_emails": settings.OSA_EMAILS + [settings.BRANDING_SITE_EMAIL],
}
emails = self.get_officer_emails()
if emails:
send_mail_helper(
name="approval_status",
subject="{} status update on {}".format(
self.name,
settings.BRANDING_SITE_NAME,
),
emails=emails,
context=context,
reply_to=settings.OSA_EMAILS + [settings.BRANDING_SITE_EMAIL],
)
class Meta:
ordering = ["name"]
permissions = [
("approve_club", "Can approve pending clubs"),
("see_pending_clubs", "View pending clubs that are not one's own"),
(
"see_fair_status",
"See whether or not a club has registered for the SAC fair",
),
("manage_club", "Manipulate club object and related objects"),
]
class TargetStudentType(models.Model):
club = models.ForeignKey(Club, on_delete=models.CASCADE)
target_student_types = models.ForeignKey(
"StudentType", blank=True, on_delete=models.CASCADE
)
program = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return "{}: {}({})".format(
self.club.name, self.target_student_types, self.program
)
class TargetYear(models.Model):
club = models.ForeignKey(Club, on_delete=models.CASCADE)
target_years = models.ForeignKey("Year", blank=True, on_delete=models.CASCADE)
program = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return "{}: {}({})".format(self.club.name, self.target_years, self.program)
class TargetSchool(models.Model):
club = models.ForeignKey(Club, on_delete=models.CASCADE)
target_schools = models.ForeignKey("School", blank=True, on_delete=models.CASCADE)
program = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return "{}: {}({})".format(self.club.name, self.target_schools, self.program)
class TargetMajor(models.Model):
club = models.ForeignKey(Club, on_delete=models.CASCADE)
target_majors = models.ForeignKey("Major", blank=True, on_delete=models.CASCADE)
program = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return "{}: {}({})".format(self.club.name, self.target_majors, self.program)
class QuestionAnswer(models.Model):
"""
Represents a question asked by a prospective member to a club
and the club's corresponding answer.
"""
club = models.ForeignKey(Club, on_delete=models.CASCADE, related_name="questions")
author = models.ForeignKey(
get_user_model(), on_delete=models.SET_NULL, null=True, related_name="questions"
)
responder = models.ForeignKey(
get_user_model(), on_delete=models.SET_NULL, null=True, related_name="answers"
)
approved = models.BooleanField(default=False)
is_anonymous = models.BooleanField(default=False)
question = models.TextField()
answer = models.TextField(null=True) # html
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
users_liked = models.ManyToManyField(get_user_model(), related_name="likes")
def __str__(self):
return "{}: {}".format(self.club.name, self.question)
def send_question_mail(self, request=None):
domain = get_domain(request)
emails = self.club.get_officer_emails()
context = {
"name": self.club.name,
"question": self.question,
"url": settings.QUESTION_URL.format(domain=domain, club=self.club.code),
}
if emails:
send_mail_helper(
name="question",
subject="Question for {}".format(self.club.name),
emails=emails,
context=context,
)
class Testimonial(models.Model):
"""
Represents a testimonial for a club.
"""
club = models.ForeignKey(
Club, on_delete=models.CASCADE, related_name="testimonials"
)
text = models.TextField()
def __str__(self):
return self.text
class ClubFair(models.Model):
"""
Represents an activities fair with multiple clubs as participants.
"""
name = models.TextField()
organization = models.TextField()
contact = models.TextField()
time = models.TextField(blank=True)
virtual = models.BooleanField(default=False)
# these fields are rendered as raw html
information = models.TextField(blank=True)
registration_information = models.TextField(blank=True)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
registration_start_time = models.DateTimeField(null=True, blank=True)
registration_end_time = models.DateTimeField()
questions = models.TextField(default="[]")
participating_clubs = models.ManyToManyField(
Club, through="ClubFairRegistration", blank=True
)
def create_events(
self, start_time=None, end_time=None, filter=None, suffix="default"
):
"""
Create activities fair events for all registered clubs.
Does not create event if it already exists.
Returns a list of activities fair events.
This method should only be used for testing purposes in development.
"""
start_time = start_time or self.start_time
end_time = end_time or self.end_time
club_query = self.participating_clubs.all()
if filter is not None:
club_query = club_query.filter(filter)
events = []
with transaction.atomic():
for club in club_query:
obj, _ = Event.objects.get_or_create(
code=f"fair-{club.code}-{self.id}-{suffix}",
club=club,
type=Event.FAIR,
defaults={
"name": self.name,
"start_time": start_time,
"end_time": end_time,
},
)
events.append(obj)
return events
def __str__(self):
fmt = "%b %d, %Y"
return (
f"{self.name} "
f"({self.start_time.strftime(fmt)} - {self.end_time.strftime(fmt)})"
)
class ClubFairRegistration(models.Model):
"""
Represents a registration between a club and a club fair.
"""
club = models.ForeignKey(Club, on_delete=models.CASCADE)
fair = models.ForeignKey(ClubFair, on_delete=models.CASCADE)
registrant = models.ForeignKey(
get_user_model(), on_delete=models.SET_NULL, null=True
)
answers = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.club.name} registration for {self.fair.name}"
class RecurringEvent(models.Model):
"""
Represents a recurring event hosted by a club.
"""
def __str__(self):
events = self.event_set.all()
if events.exists():
first_event = events.first()
last_event = events.last()
name = first_event.name
return (
f"{name}: "
f"{first_event.start_time} - {last_event.end_time} "
f"({events.count()} times)"
)
return "empty recurring event object"
class Event(models.Model):
"""
Represents an event hosted by a club.
If the club is null, this is a global event.
"""
code = models.SlugField(max_length=255, db_index=True)
creator = models.ForeignKey(get_user_model(), on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=255)
club = models.ForeignKey(
Club, on_delete=models.CASCADE, related_name="events", null=True
)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
location = models.CharField(max_length=255, null=True, blank=True)
url = models.URLField(max_length=2048, null=True, blank=True)
image = models.ImageField(upload_to=get_event_file_name, null=True, blank=True)
image_small = models.ImageField(
upload_to=get_event_small_file_name, null=True, blank=True
)
description = models.TextField(blank=True) # rich html
ics_uuid = models.UUIDField(default=uuid.uuid4)
is_ics_event = models.BooleanField(default=False, blank=True)
parent_recurring_event = models.ForeignKey(
RecurringEvent, on_delete=models.CASCADE, blank=True, null=True
)
OTHER = 0
RECRUITMENT = 1
GBM = 2
SPEAKER = 3
FAIR = 4
SOCIAL = 5
CAREER = 6
TYPES = (
(OTHER, "Other"),
(RECRUITMENT, "Recruitment"),
(GBM, "GBM"),
(SPEAKER, "Speaker"),
(FAIR, "Activities Fair"),
(SOCIAL, "Social"),
(CAREER, "Career"),
)
type = models.IntegerField(choices=TYPES, default=RECRUITMENT)
pinned = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def create_thumbnail(self, request=None):
return create_thumbnail_helper(self, request, 400)
@property
def has_tickets(self):
return self.tickets.exists()
def __str__(self):
return self.name
class Favorite(models.Model):
"""
Used when people favorite a club to keep track of which clubs were favorited.
"""
person = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
club = models.ForeignKey(Club, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return "<Favorite: {} for {}>".format(self.person.username, self.club.code)
class Meta:
unique_together = (("person", "club"),)
class Subscribe(models.Model):
"""
Used when people subscribe to a club and clubs
will be able to see the users' email addresses.
"""