-
-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathmodels.py
More file actions
3383 lines (2932 loc) · 116 KB
/
Copy pathmodels.py
File metadata and controls
3383 lines (2932 loc) · 116 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 re
import uuid
from collections.abc import Collection
from typing import Annotated, Any, Literal, Self, TypedDict, cast
from urllib.parse import quote
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin,
)
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.db import models, transaction
from django.db.models import (
Case,
Count,
F,
IntegerField,
Manager,
PositiveIntegerField,
Q,
QuerySet,
Sum,
When,
)
from django.db.models.aggregates import Aggregate
from django.db.models.functions import Coalesce, Greatest
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.text import format_lazy
from django_countries.fields import Country, CountryField
from django_stubs_ext import Annotations
from github import GithubException
from reversion import revisions as reversion
from reversion.models import Version
from social_django.models import UserSocialAuth
from src.trainings.models import Involvement
from src.workshops import github_auth
from src.workshops.consts import (
FEE_DETAILS_URL,
IATA_AIRPORTS,
STR_LONG,
STR_LONGEST,
STR_MED,
STR_REG_KEY,
STR_SHORT,
)
from src.workshops.fields import (
BlueSkyHandleField,
MastodonHandleField,
NullableGithubUsernameField,
OrcidField,
choice_field_with_other,
)
from src.workshops.mixins import (
ActiveMixin,
AssignmentMixin,
COCAgreementMixin,
CreatedUpdatedArchivedMixin,
CreatedUpdatedMixin,
DataPrivacyAgreementMixin,
EventLinkMixin,
GenderMixin,
HostResponsibilitiesMixin,
InstructorAvailabilityMixin,
SecondaryEmailMixin,
StateExtendedMixin,
StateMixin,
)
from src.workshops.signals import person_archived_signal
from src.workshops.utils.dates import human_daterange
from src.workshops.utils.emails import find_emails
from src.workshops.utils.reports import reports_link
# ------------------------------------------------------------
class OrganizationManager(models.Manager["Organization"]):
ADMIN_DOMAINS = [
"self-organized",
"software-carpentry.org",
"datacarpentry.org",
"librarycarpentry.org",
"hpccarpentry.org",
# Instructor Training organisation
"carpentries.org",
# Collaborative Lesson Development Training organisation
"carpentries.org/community-lessons/",
]
def administrators(self) -> QuerySet[Organization]:
return self.get_queryset().filter(domain__in=self.ADMIN_DOMAINS)
@reversion.register
class Organization(models.Model):
"""Represent an organization, academic or business."""
domain = models.CharField(max_length=STR_LONG, unique=True)
fullname = models.CharField(max_length=STR_LONG, unique=True)
country = CountryField(null=True, blank=True)
latitude = models.FloatField(null=True, blank=True)
longitude = models.FloatField(null=True, blank=True)
affiliated_organizations = models.ManyToManyField["Organization", Any]("Organization", blank=True, symmetrical=True)
objects = OrganizationManager()
def __str__(self) -> str:
return f"{self.fullname} <{self.domain}>"
@property
def domain_quoted(self) -> str:
return quote(self.domain, safe="")
def get_absolute_url(self) -> str:
return reverse("organization_details", args=[self.domain_quoted])
class Meta:
ordering = ("domain",)
class MemberRole(models.Model):
name = models.CharField(max_length=STR_MED)
verbose_name = models.CharField(max_length=STR_LONG, blank=True, default="")
def __str__(self) -> str:
return self.verbose_name if self.verbose_name else self.name
class Member(models.Model):
membership = models.ForeignKey("Membership", on_delete=models.CASCADE)
organization = models.ForeignKey(Organization, on_delete=models.PROTECT)
role = models.ForeignKey(MemberRole, on_delete=models.PROTECT)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["membership", "organization", "role"],
name="unique_member_role_in_membership",
)
]
class MembershipSeatUsage(TypedDict):
instructor_training_seats_total: int
instructor_training_seats_utilized: int
instructor_training_seats_remaining: int
class MembershipManager(models.Manager["Membership"]):
def annotate_with_seat_usage(self) -> QuerySet[Annotated[Membership, Annotations[MembershipSeatUsage]]]:
return self.get_queryset().annotate(
instructor_training_seats_total=(
# Public
F("public_instructor_training_seats")
+ F("additional_public_instructor_training_seats")
# Coalesce returns first non-NULL value
+ Coalesce("public_instructor_training_seats_rolled_from_previous", 0)
# Inhouse
+ F("inhouse_instructor_training_seats")
+ F("additional_inhouse_instructor_training_seats")
+ Coalesce("inhouse_instructor_training_seats_rolled_from_previous", 0)
),
instructor_training_seats_utilized=(Count("task", filter=Q(task__role__name="learner"))),
instructor_training_seats_remaining=(
# Public
F("public_instructor_training_seats")
+ F("additional_public_instructor_training_seats")
# Coalesce returns first non-NULL value
+ Coalesce("public_instructor_training_seats_rolled_from_previous", 0)
- Count("task", filter=Q(task__role__name="learner", task__seat_public=True))
- Coalesce("public_instructor_training_seats_rolled_over", 0)
# Inhouse
+ F("inhouse_instructor_training_seats")
+ F("additional_inhouse_instructor_training_seats")
+ Coalesce("inhouse_instructor_training_seats_rolled_from_previous", 0)
- Count(
"task",
filter=Q(task__role__name="learner", task__seat_public=False),
)
- Coalesce("inhouse_instructor_training_seats_rolled_over", 0)
),
)
@reversion.register
class Membership(models.Model):
"""Represent a details of Organization's membership."""
name = models.CharField(max_length=STR_LONG)
MEMBERSHIP_CHOICES = (
("partner", "Partner"),
("affiliate", "Affiliate"),
("sponsor", "Sponsor"),
("bronze", "Bronze"),
("silver", "Silver"),
("gold", "Gold"),
("platinum", "Platinum"),
("titanium", "Titanium"),
("alacarte", "A la carte"),
)
variant = models.CharField(
max_length=STR_MED,
null=False,
blank=False,
choices=MEMBERSHIP_CHOICES,
)
agreement_start = models.DateField()
agreement_end = models.DateField(
help_text="If an extension is being granted, do not manually edit the end date."
' Use the "Extend" button on membership details page instead.'
)
extensions = ArrayField(
models.PositiveIntegerField(),
help_text="Number of days the agreement was extended. The field stores "
"multiple extensions. The agreement end date has been moved by a cumulative "
"number of days from this field.",
default=list,
)
CONTRIBUTION_CHOICES = (
("financial", "Financial"),
("person-days", "Person-days"),
("other", "Other"),
)
contribution_type = models.CharField(
max_length=STR_MED,
null=False,
blank=False,
choices=CONTRIBUTION_CHOICES,
)
workshops_without_admin_fee_per_agreement = models.PositiveIntegerField(
null=True,
blank=True,
help_text="Acceptable number of workshops without admin fee per agreement duration",
)
workshops_without_admin_fee_rolled_from_previous = models.PositiveIntegerField(
null=True,
blank=True,
help_text="Workshops without admin fee rolled over from previous membership.",
)
workshops_without_admin_fee_rolled_over = models.PositiveIntegerField(
null=True,
blank=True,
help_text="Workshops without admin fee rolled over into next membership.",
)
# according to Django docs, PositiveIntegerFields accept 0 as valid as well
public_instructor_training_seats = models.PositiveIntegerField(
null=False,
blank=False,
default=0,
verbose_name="Public instructor training seats",
help_text="Number of public seats in instructor trainings",
)
additional_public_instructor_training_seats = models.PositiveIntegerField(
null=False,
blank=False,
default=0,
verbose_name="Additional public instructor training seats",
help_text="Use this field if you want to grant more public seats than the agreement provides for.",
)
public_instructor_training_seats_rolled_from_previous = models.PositiveIntegerField(
null=True,
blank=True,
help_text="Public instructor training seats rolled over from previous membership.",
)
public_instructor_training_seats_rolled_over = models.PositiveIntegerField(
null=True,
blank=True,
help_text="Public instructor training seats rolled over into next membership.",
)
inhouse_instructor_training_seats = models.PositiveIntegerField(
null=False,
blank=False,
default=0,
verbose_name="In-house instructor training seats",
help_text="Number of in-house seats in instructor trainings",
)
additional_inhouse_instructor_training_seats = models.PositiveIntegerField(
null=False,
blank=False,
default=0,
verbose_name="Additional in-house instructor training seats",
help_text="Use this field if you want to grant more in-house seats than the agreement provides for.",
)
inhouse_instructor_training_seats_rolled_from_previous = models.PositiveIntegerField( # noqa
null=True,
blank=True,
help_text="In-house instructor training seats rolled over from previous membership.", # noqa
)
inhouse_instructor_training_seats_rolled_over = models.PositiveIntegerField(
null=True,
blank=True,
help_text="In-house instructor training seats rolled over into next membership.", # noqa
)
organizations = models.ManyToManyField(
Organization,
blank=False,
related_name="memberships",
through=Member,
)
registration_code = models.CharField(
max_length=STR_MED,
null=True,
blank=True,
unique=True,
verbose_name="Registration Code",
help_text="Unique registration code used for Eventbrite and trainee application.",
)
agreement_link = models.URLField(
blank=False,
default="",
verbose_name="Link to member agreement",
help_text="Link to member agreement document or folder in Google Drive",
)
PUBLIC_STATUS_CHOICES = (
("public", "Public"),
("private", "Private"),
)
public_status = models.CharField(
max_length=20,
choices=PUBLIC_STATUS_CHOICES,
default=PUBLIC_STATUS_CHOICES[1][0],
verbose_name="Can this membership be publicized on The carpentries websites?",
help_text="Public memberships may be listed on any of The Carpentries websites.",
)
emergency_contact = models.TextField(blank=True)
consortium = models.BooleanField(
default=False,
help_text="Determines whether this is a group of organisations working together under a consortium.",
)
persons = models.ManyToManyField["Person", Any](
"Person",
blank=True,
related_name="memberships",
through="fiscal.MembershipTask",
)
rolled_to_membership = models.OneToOneField(
"Membership",
on_delete=models.SET_NULL,
related_name="rolled_from_membership",
null=True,
)
objects = MembershipManager()
def __str__(self) -> str:
dates = human_daterange(self.agreement_start, self.agreement_end)
variant = self.variant.title()
if self.consortium:
return f"{self.name} {variant} membership {dates} (consortium)"
else:
return f"{self.name} {variant} membership {dates}"
def get_absolute_url(self) -> str:
return reverse("membership_details", args=[self.id])
def active_on_date(self, date: datetime.date, grace_before: int = 0, grace_after: int = 0) -> bool:
"""Returns True if the date is within the membership agreement dates,
with an optional grace period (in days) at the start and/or end of the
agreement.
"""
start_date = self.agreement_start - datetime.timedelta(days=grace_before)
end_date = self.agreement_end + datetime.timedelta(days=grace_after)
return start_date <= date <= end_date
def _base_queryset(self) -> QuerySet[Event]:
"""Provide universal queryset for looking up workshops for this membership."""
cancelled = Q(tags__name="cancelled") | Q(tags__name="stalled")
return Event.objects.filter(membership=self).exclude(cancelled).distinct()
def _workshops_without_admin_fee_queryset(self) -> QuerySet[Event]:
"""Provide universal queryset for looking up centrally-organised workshops for
this membership."""
return (
self._base_queryset()
.filter(administrator__in=Organization.objects.administrators())
.exclude(administrator__domain="self-organized")
)
def _workshops_without_admin_fee_completed_queryset(self) -> QuerySet[Event]:
return self._workshops_without_admin_fee_queryset().filter(start__lt=datetime.date.today())
def _workshops_without_admin_fee_planned_queryset(self) -> QuerySet[Event]:
return self._workshops_without_admin_fee_queryset().filter(start__gte=datetime.date.today())
@property
def workshops_without_admin_fee_total_allowed(self) -> int:
"""Available for counting, "contracted" centrally-organised workshops.
This number represents the real number of available workshops for counting
completed / planned / remaining no-fee workshops.
Because the data may be entered incorrectly, a sharp cutoff at 0 was introduced,
meaning this value won't be ever negative."""
a = self.workshops_without_admin_fee_per_agreement or 0
b = self.workshops_without_admin_fee_rolled_from_previous or 0
return a + b
@property
def workshops_without_admin_fee_available(self) -> int:
"""Available for counting, "contracted" centrally-organised workshops.
This number represents the real number of available workshops for counting
completed / planned / remaining no-fee workshops.
Because the data may be entered incorrectly, a sharp cutoff at 0 was introduced,
meaning this value won't be ever negative."""
a = self.workshops_without_admin_fee_total_allowed
b = self.workshops_without_admin_fee_rolled_over or 0
return max(a - b, 0)
@cached_property
def workshops_without_admin_fee_completed(self) -> int:
"""Count centrally-organised workshops already hosted by this membership.
This value must not be higher than "contracted" (or available for counting)
no-fee workshops.
Excess is counted towards discounted-fee completed workshops."""
return min(
self._workshops_without_admin_fee_completed_queryset().count(),
self.workshops_without_admin_fee_available,
)
@cached_property
def workshops_without_admin_fee_planned(self) -> int:
"""Count centrally-organised workshops hosted in future by this membership.
This value must not be higher than "contracted" (or available for counting)
no-fee workshops reduced by already completed no-fee workshops.
Excess is counted towards discounted-fee planned workshops."""
return min(
self._workshops_without_admin_fee_planned_queryset().count(),
self.workshops_without_admin_fee_available - self.workshops_without_admin_fee_completed,
)
@property
def workshops_without_admin_fee_remaining(self) -> int:
"""Count remaining centrally-organised workshops for the agreement."""
a = self.workshops_without_admin_fee_available
b = self.workshops_without_admin_fee_completed
c = self.workshops_without_admin_fee_planned
# can't get below 0, that's when discounted workshops kick in
return max(a - b - c, 0)
@cached_property
def workshops_discounted_completed(self) -> int:
"""Any centrally-organised workshops exceeding the workshops without fee allowed
number - already completed."""
return max(
self._workshops_without_admin_fee_completed_queryset().count() - self.workshops_without_admin_fee_available,
0,
)
@cached_property
def workshops_discounted_planned(self) -> int:
"""Any centrally-organised workshops exceeding the workshops without fee allowed
number - to happen in future."""
return max(
self._workshops_without_admin_fee_planned_queryset().count() - self.workshops_without_admin_fee_available,
0,
)
def _self_organized_workshops_queryset(self) -> QuerySet[Event]:
"""Provide universal queryset for looking up self-organised events for this
membership."""
self_organized = Q(administrator=None) | Q(administrator__domain="self-organized")
return self._base_queryset().filter(self_organized)
@cached_property
def self_organized_workshops_completed(self) -> int:
"""Count self-organized workshops hosted the year agreement started (completed,
ie. in past)."""
return self._self_organized_workshops_queryset().filter(start__lt=datetime.date.today()).count()
@cached_property
def self_organized_workshops_planned(self) -> int:
"""Count self-organized workshops hosted the year agreement started (planned,
ie. in future)."""
return self._self_organized_workshops_queryset().filter(start__gte=datetime.date.today()).count()
@property
def public_instructor_training_seats_total(self) -> int:
"""Calculate combined public instructor training seats total.
Unlike workshops w/o admin fee, instructor training seats have two numbers
combined to calculate total of allowed instructor training seats in ITT events.
"""
a = self.public_instructor_training_seats
b = self.additional_public_instructor_training_seats
c = self.public_instructor_training_seats_rolled_from_previous or 0
return a + b + c
@cached_property
def public_instructor_training_seats_utilized(self) -> int:
"""Count number of learner tasks that point to this membership."""
return self.task_set.filter(role__name="learner", seat_public=True).count()
@property
def public_instructor_training_seats_remaining(self) -> int:
"""Count remaining public seats for instructor training."""
a = self.public_instructor_training_seats_total
b = self.public_instructor_training_seats_utilized
c = self.public_instructor_training_seats_rolled_over or 0
return a - b - c
@property
def inhouse_instructor_training_seats_total(self) -> int:
"""Calculate combined in-house instructor training seats total.
Unlike workshops w/o admin fee, instructor training seats have two numbers
combined to calculate total of allowed instructor training seats in ITT events.
"""
a = self.inhouse_instructor_training_seats
b = self.additional_inhouse_instructor_training_seats
c = self.inhouse_instructor_training_seats_rolled_from_previous or 0
return a + b + c
@cached_property
def inhouse_instructor_training_seats_utilized(self) -> int:
"""Count number of learner tasks that point to this membership."""
return self.task_set.filter(role__name="learner", seat_public=False).count()
@property
def inhouse_instructor_training_seats_remaining(self) -> int:
"""Count remaining in-house seats for instructor training."""
a = self.inhouse_instructor_training_seats_total
b = self.inhouse_instructor_training_seats_utilized
c = self.inhouse_instructor_training_seats_rolled_over or 0
return a - b - c
# ------------------------------------------------------------
# TODO: Can be removed since #2816
@reversion.register
class Airport(models.Model):
"""Represent an airport (used to locate instructors)."""
iata = models.CharField(
max_length=STR_SHORT,
unique=True,
verbose_name="IATA code",
help_text='<a href="https://www.world-airport-codes.com/">Look up code</a>',
)
fullname = models.CharField(max_length=STR_LONG, unique=True, verbose_name="Airport name")
country = CountryField()
latitude = models.FloatField()
longitude = models.FloatField()
def __str__(self) -> str:
return f"{self.iata}: {self.fullname}"
def get_absolute_url(self) -> str:
return reverse("airport_details", args=[str(self.iata)])
class Meta:
ordering = ("iata",)
# ------------------------------------------------------------
class PersonInstructorEligibility(TypedDict):
passed_training: int
passed_get_involved: int
passed_welcome: int
passed_demo: int
instructor_eligible: int
class PersonRoleCount(TypedDict):
num_instructor: int
num_trainer: int
num_helper: int
num_learner: int
num_supporting: int
num_organizer: int
class PersonManager(BaseUserManager["Person"]):
"""
Create users and superusers from command line.
For example:
$ python manage.py createsuperuser
"""
def create_user(self, username: str, personal: str, family: str, email: str, password: str | None = None) -> Person:
"""
Create and save a normal (not-super) user.
"""
user = self.model(
username=username,
personal=personal,
family=family,
email=self.normalize_email(email),
is_superuser=False,
is_active=True,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(
self, username: str, personal: str, family: str, email: str, airport_iata: str, password: str
) -> Person:
"""
Create and save a superuser.
"""
user = self.model(
username=username,
personal=personal,
family=family,
email=self.normalize_email(email),
is_superuser=True,
is_active=True,
airport_iata=airport_iata,
)
user.set_password(password)
user.save(using=self._db)
return user
def get_by_natural_key(self, username: str | None) -> Person:
"""Let's make this command so that it gets user by *either* username or
email. Original behavior is to get user by USERNAME_FIELD."""
if isinstance(username, str) and "@" in username:
return self.get(email=username)
else:
return super().get_by_natural_key(username)
def annotate_with_instructor_eligibility(
self,
) -> QuerySet[Annotated[Person, Annotations[PersonInstructorEligibility]]]:
def passed(requirement: str) -> Aggregate:
return Sum(
Case(
When(
trainingprogress__requirement__name=requirement,
trainingprogress__state="p",
then=1,
),
default=0,
output_field=IntegerField(),
)
)
def passed_either(*reqs: str) -> Aggregate:
return Sum(
Case(
*[
When(
trainingprogress__requirement__name=req,
trainingprogress__state="p",
then=1,
)
for req in reqs
],
default=0,
output_field=IntegerField(),
)
)
return self.annotate(
passed_training=passed("Training"),
passed_get_involved=passed("Get Involved"),
passed_welcome=passed("Welcome Session"),
passed_demo=passed("Demo"),
).annotate(
# We're using Maths to calculate "binary" score for a person to
# be instructor badge eligible. Legend:
# * means "AND"
# + means "OR"
instructor_eligible=(
F("passed_training") * F("passed_welcome") * F("passed_get_involved") * F("passed_demo")
)
)
def annotate_with_role_count(self) -> QuerySet[Annotated[Person, Annotations[PersonRoleCount]]]:
return self.annotate(
num_instructor=Count(
"task",
filter=(Q(task__role__name="instructor") & ~Q(task__event__administrator__domain="carpentries.org")),
distinct=True,
),
num_trainer=Count(
"task",
filter=(Q(task__role__name="instructor") & Q(task__event__administrator__domain="carpentries.org")),
distinct=True,
),
num_helper=Count("task", filter=Q(task__role__name="helper"), distinct=True),
num_learner=Count("task", filter=Q(task__role__name="learner"), distinct=True),
num_supporting=Count(
"task",
filter=Q(task__role__name="supporting-instructor"),
distinct=True,
),
num_organizer=Count("task", filter=Q(task__role__name="organizer"), distinct=True),
)
def duplication_review_expired(self) -> QuerySet[Person]:
return self.filter(
Q(duplication_reviewed_on__isnull=True)
| Q(last_updated_at__gte=F("duplication_reviewed_on") + datetime.timedelta(minutes=1))
)
@reversion.register
class Person(
AbstractBaseUser,
PermissionsMixin,
CreatedUpdatedArchivedMixin,
GenderMixin,
SecondaryEmailMixin,
):
"""Represent a single person."""
# These attributes should always contain field names of Person
PERSON_UPLOAD_FIELDS: set[Literal["personal", "family", "email"]] = {"personal", "family", "email"}
PERSON_TASK_EXTRA_FIELDS: set[Literal["airport_iata", "event", "role"]] = {"airport_iata", "event", "role"}
PERSON_TASK_UPLOAD_FIELDS = ("personal", "family", "email", "airport_iata", "event", "role")
USERNAME_FIELD = "username"
REQUIRED_FIELDS = [
"personal",
"family",
"email",
]
personal = models.CharField(
max_length=STR_LONG,
verbose_name="Personal (first) name",
)
middle = models.CharField(
max_length=STR_LONG,
blank=True,
default="",
verbose_name="Middle name",
)
family = models.CharField(
max_length=STR_LONG,
blank=True,
default="",
verbose_name="Family (last) name",
)
email = models.EmailField(
unique=True,
null=True,
blank=True,
verbose_name="Email address",
help_text="Primary email address, used for communication and as a login.",
)
airport_iata = models.CharField(
max_length=STR_SHORT,
null=False,
blank=True,
default="",
help_text="Nearest major airport (IATA code: https://www.world-airport-codes.com/)",
)
airport_country = CountryField(
null=False,
blank=True,
default="",
help_text="Airport country (copied from airport data package)",
)
airport_lat = models.FloatField(default=0.0, help_text="Airport latitude (copied from airport data package)")
airport_lon = models.FloatField(default=0.0, help_text="Airport longitude (copied from airport data package)")
airport_timezone = models.CharField(
default="", help_text="Airport timezone (copied from airport data package)", blank=True
)
country = CountryField(
null=False,
blank=True,
default="",
help_text="Override country of the airport.",
)
timezone = models.CharField(
null=False,
blank=True,
default="",
help_text="Override timezone of the airport.",
)
github = NullableGithubUsernameField(
unique=True,
null=True,
blank=True,
verbose_name="GitHub username",
help_text="Please put only a single username here.",
)
twitter = models.CharField(
max_length=STR_LONG,
unique=True,
null=True,
blank=True,
verbose_name="Twitter username",
)
bluesky = BlueSkyHandleField(
unique=True,
null=True,
blank=True,
verbose_name="BlueSky username",
)
mastodon = MastodonHandleField(
unique=True,
null=True,
blank=True,
verbose_name="Mastodon username",
)
url = models.CharField(
max_length=STR_LONG,
blank=True,
verbose_name="Personal website",
)
username = models.CharField(
max_length=STR_LONG,
unique=True,
validators=[RegexValidator(r"^[\w\-_]+$", flags=re.A)],
)
user_notes = models.TextField(
default="",
blank=True,
verbose_name="Notes provided by the user in update profile form.",
)
affiliation = models.CharField(
max_length=STR_LONG,
default="",
blank=True,
help_text="What university, company, lab, or other organization are you affiliated with (if any)?",
)
badges = models.ManyToManyField["Badge", "Award"]("Badge", through="Award", through_fields=("person", "badge"))
lessons = models.ManyToManyField["Lesson", "Qualification"](
"Lesson",
through="Qualification",
verbose_name="Topic and lessons you're comfortable teaching",
help_text="Please check all that apply.",
blank=True,
)
domains = models.ManyToManyField["KnowledgeDomain", Any](
"KnowledgeDomain",
limit_choices_to=~Q(name__startswith="Don't know yet"),
verbose_name="Areas of expertise",
help_text="Please check all that apply.",
blank=True,
)
languages = models.ManyToManyField["Language", Any](
"Language",
blank=True,
)
# new people will be inactive by default
is_active = models.BooleanField(default=False)
occupation = models.CharField(
max_length=STR_LONG,
verbose_name="Current occupation/career stage",
blank=True,
default="",
)
orcid = OrcidField(
verbose_name="ORCID ID",
blank=True,
default="",
)
duplication_reviewed_on = models.DateTimeField(
null=True,
blank=True,
verbose_name="Timestamp of duplication review by admin",
help_text="Set this to a newer / actual timestamp when Person is reviewed by admin.",
)
objects = PersonManager()
class Meta:
ordering = ["family", "personal"]
# additional permissions
permissions = [
(
"can_access_restricted_API",
"Can this user access the restricted API endpoints?",
),
]
@cached_property
def full_name(self) -> str:
middle = ""
if self.middle:
middle = f" {self.middle}"
return f"{self.personal}{middle} {self.family}"
def get_full_name(self) -> str:
return self.full_name
def get_short_name(self) -> str:
return self.personal
def __str__(self) -> str:
result = self.full_name
if self.email:
result += " <" + self.email + ">"
return result
def get_absolute_url(self) -> str:
return reverse("person_details", args=[str(self.id)])
@property
def github_usersocialauth(self) -> QuerySet[UserSocialAuth]:
"""List of all associated GitHub accounts with this Person. Returns
list of UserSocialAuth."""
return self.social_auth.filter(provider="github")
def get_github_uid(self) -> int | None:
"""Return UID (int) of GitHub account for username == `Person.github`.
Return `None` in case of errors or missing GitHub account.
May raise ValueError in the case of IO issues."""
if self.github and self.is_active:
try:
# if the username is incorrect, this will throw ValidationError
github_auth.validate_github_username(self.github)
github_uid = github_auth.github_username_to_uid(self.github)
except (ValidationError, ValueError, GithubException):
github_uid = None
else:
github_uid = None
return github_uid
def synchronize_usersocialauth(self) -> UserSocialAuth | bool:
"""Disconnect all GitHub account associated with this Person and
associates the account with username == `Person.github`, if there is
such GitHub account.
May raise GithubException in the case of IO issues."""
github_uid = self.get_github_uid()
if github_uid is not None:
self.github_usersocialauth.delete()
return cast(
UserSocialAuth,
UserSocialAuth.objects.create(provider="github", user=self, uid=github_uid, extra_data={}),
)
else:
return False
@property
def is_staff(self) -> bool:
"""Required for logging into admin panel."""
return self.is_superuser
@property
def is_admin(self) -> bool:
return self._is_admin()
ADMIN_GROUPS = ("administrators", "steering committee", "invoicing", "trainers")
def _is_admin(self) -> bool:
try:
if self.is_anonymous:
return False
else:
return self.is_superuser or self.groups.filter(name__in=self.ADMIN_GROUPS).exists()
except AttributeError:
return False
def get_missing_instructor_requirements(self) -> list[str]:
"""Returns set of requirements' names (list of strings) that are not
passed yet by the trainee and are mandatory to become an Instructor.
"""
fields = [
("passed_training", "Training"),
("passed_get_involved", "Get Involved"),
("passed_welcome", "Welcome Session"),
("passed_demo", "Demo"),
]
try: