-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathforms.py
More file actions
1395 lines (1167 loc) · 48.3 KB
/
Copy pathforms.py
File metadata and controls
1395 lines (1167 loc) · 48.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import csv
import io
from datetime import date
from django import forms
from django.core import validators
from django.forms.renderers import DjangoTemplates
from django.urls import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.core.validators import MaxLengthValidator
from django.core.validators import MinLengthValidator
from django.core.validators import MinValueValidator
from django.db import transaction
from django.db.models import Exists, OuterRef
from django.http import HttpResponse
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from accounts.models import CustomUser
from home.constants import DATE_INPUT_FORMAT
from home.constants import SURVEY_FIELD_VALIDATORS
from home.models import (
Question,
Team,
SessionMembership,
ProjectPreference,
Waitlist,
Testimonial,
Session,
)
from home.models import Survey
from home.models import TypeField
from home.models import UserQuestionResponse
from home.models import UserSurveyResponse
from home.availability import (
calculate_overlap,
calculate_team_overlap,
format_slots_as_ranges,
)
from home.validators import RatingValidator
from home.widgets import CheckboxSelectMultipleSurvey
from home.widgets import DateSurvey
from home.widgets import RadioSelectSurvey
from home.widgets import RatingSurvey
def make_choices(question: Question) -> list[tuple[str, str]]:
choices = []
for choice in question.choices.split(","):
choice = choice.strip()
choices.append((choice.replace(" ", "_").lower(), choice))
return choices
def to_field_name(question: Question) -> str:
"""Convert a question to the response field name key."""
return f"field_survey_{question.id}"
def get_response_value(data: dict, question: Question) -> str:
"""
Fetch the question's value from the data dictionary,
typically a cleaned_data.
"""
field_name = to_field_name(question)
return (
",".join(data[field_name])
if question.type_field == TypeField.MULTI_SELECT
else data[field_name]
)
class BaseSurveyForm(forms.Form):
def __init__(self, *args, survey, user, **kwargs):
self.survey = survey
self.user = user if user.is_authenticated else None
self.field_names = []
self.questions = self.survey.questions.all().order_by("ordering")
super().__init__(*args, **kwargs)
# Add all question fields first
for question in self.questions:
# to generate field name
field_name = to_field_name(question)
if question.type_field == TypeField.MULTI_SELECT:
choices = make_choices(question)
self.fields[field_name] = forms.MultipleChoiceField(
choices=choices,
label=question.label,
widget=CheckboxSelectMultipleSurvey,
)
elif question.type_field == TypeField.RADIO:
choices = make_choices(question)
self.fields[field_name] = forms.ChoiceField(
choices=choices, label=question.label, widget=RadioSelectSurvey
)
elif question.type_field == TypeField.SELECT:
choices = make_choices(question)
empty_choice = [("", _("Choose"))]
choices = empty_choice + choices
self.fields[field_name] = forms.ChoiceField(
choices=choices, label=question.label
)
elif question.type_field == TypeField.NUMBER:
self.fields[field_name] = forms.IntegerField(label=question.label)
elif question.type_field == TypeField.URL:
self.fields[field_name] = forms.URLField(
label=question.label,
validators=[
MaxLengthValidator(SURVEY_FIELD_VALIDATORS["max_length"]["url"])
],
)
elif question.type_field == TypeField.EMAIL:
self.fields[field_name] = forms.EmailField(
label=question.label,
validators=[
MaxLengthValidator(
SURVEY_FIELD_VALIDATORS["max_length"]["email"]
)
],
)
elif question.type_field == TypeField.DATE:
self.fields[field_name] = forms.DateField(
label=question.label,
widget=DateSurvey(),
input_formats=DATE_INPUT_FORMAT,
)
elif question.type_field == TypeField.TEXT_AREA:
self.fields[field_name] = forms.CharField(
label=question.label,
widget=forms.Textarea,
validators=[
MinLengthValidator(
SURVEY_FIELD_VALIDATORS["min_length"]["text_area"]
),
MaxLengthValidator(
SURVEY_FIELD_VALIDATORS["max_length"]["text_area"]
),
],
)
elif question.type_field == TypeField.RATING:
self.fields[field_name] = forms.CharField(
label=question.label,
widget=RatingSurvey,
validators=[
MaxLengthValidator(len(str(int(question.choices)))),
RatingValidator(int(question.choices)),
],
)
self.fields[field_name].widget.num_ratings = int(question.choices)
else:
self.fields[field_name] = forms.CharField(
label=question.label,
validators=[
MinLengthValidator(
SURVEY_FIELD_VALIDATORS["min_length"]["text"]
),
MaxLengthValidator(
SURVEY_FIELD_VALIDATORS["max_length"]["text"]
),
],
)
self.fields[field_name].required = question.required
self.fields[field_name].help_text = question.help_text
self.field_names.append(field_name)
# Add project preference field if survey is associated with a session
self.session = None
try:
app_session = self.survey.application_session
except ObjectDoesNotExist:
pass
else:
if app_session.is_accepting_applications():
self.session = app_session
# Add project preference field if session has available projects
project_choices = [
(
project.id,
mark_safe(
f'<div><a href="{project.url}" target="_blank">{project.name}</a>'
f"<p>{project.description}</p></div>"
),
)
for project in self.session.available_projects.all()
]
if project_choices:
self.fields["project_preferences"] = forms.MultipleChoiceField(
choices=project_choices,
label=_("Project Preferences"),
help_text=_(
"Select the projects you would like to work on. "
"Leave blank if you're okay with any project."
),
widget=CheckboxSelectMultipleSurvey,
required=False,
)
# Add GitHub username field for application sessions
self.fields["github_username"] = forms.CharField(
max_length=39,
label=_("GitHub Username"),
help_text=_("Your GitHub username (required for participation)"),
required=True,
initial=(
self.user.profile.github_username
if hasattr(self.user, "profile")
else ""
),
)
def clean(self):
cleaned_data = super().clean()
for field_name in self.field_names:
try:
field = cleaned_data[field_name]
except KeyError:
raise forms.ValidationError("You must enter valid data")
if self.fields[field_name].required and not field:
self.add_error(field_name, "This field is required")
return cleaned_data
class CreateUserSurveyResponseForm(BaseSurveyForm):
def clean(self):
cleaned_data = super().clean()
if UserSurveyResponse.objects.filter(
survey=self.survey, user=self.user
).exists():
self.add_error(
None,
"You have already submitted a response. Please edit the other instead.",
)
return cleaned_data
@transaction.atomic
def save(self):
cleaned_data = super().clean()
user_survey_response = UserSurveyResponse.objects.create(
survey=self.survey, user=self.user
)
question_responses = [
UserQuestionResponse(
question=question,
user_survey_response=user_survey_response,
value=get_response_value(cleaned_data, question),
)
for question in self.questions
]
UserQuestionResponse.objects.bulk_create(
question_responses,
update_conflicts=True,
update_fields=("value",),
unique_fields=("question", "user_survey_response"),
)
# Save project preferences if provided and session exists
if self.session and (
project_preferences := cleaned_data.get("project_preferences")
):
preferences = [
ProjectPreference(
user=self.user,
session=self.session,
project_id=project_id,
)
for project_id in project_preferences
]
ProjectPreference.objects.bulk_create(preferences, ignore_conflicts=True)
# Save GitHub username to user profile
if self.session and (github_username := cleaned_data.get("github_username")):
self.user.profile.github_username = github_username
self.user.profile.save(update_fields=["github_username"])
return user_survey_response
class EditUserSurveyResponseForm(BaseSurveyForm):
def __init__(self, *args, instance: UserSurveyResponse, **kwargs):
self.user_survey_response = instance
super().__init__(*args, survey=instance.survey, user=instance.user, **kwargs)
self._set_initial_data()
def _set_initial_data(self):
question_responses = self.user_survey_response.userquestionresponse_set.all()
for question_response in question_responses:
field_name = to_field_name(question_response.question)
if question_response.question.type_field == TypeField.MULTI_SELECT:
self.fields[field_name].initial = question_response.value.split(",")
else:
self.fields[field_name].initial = question_response.value
# Set initial data for project preferences
if self.session and "project_preferences" in self.fields:
existing_prefs = ProjectPreference.objects.for_user_session(
user=self.user_survey_response.user, session=self.session
).values_list("project_id", flat=True)
self.fields["project_preferences"].initial = list(existing_prefs)
def clean(self):
cleaned_data = super().clean()
if not self.user_survey_response.is_editable():
self.add_error(None, "You are no longer able to edit this.")
return cleaned_data
@transaction.atomic
def save(self):
cleaned_data = super().clean()
self.user_survey_response.updated_at = timezone.now()
self.user_survey_response.save(update_fields=["updated_at"])
question_responses = [
UserQuestionResponse(
question=question,
user_survey_response=self.user_survey_response,
value=get_response_value(cleaned_data, question),
)
for question in self.questions
]
UserQuestionResponse.objects.bulk_create(
question_responses,
update_conflicts=True,
update_fields=("value",),
unique_fields=("question", "user_survey_response"),
)
# Update project preferences if session exists
if self.session and (
project_preferences := cleaned_data.get("project_preferences")
):
# Delete existing preferences for this user/session
ProjectPreference.objects.for_user_session(
user=self.user_survey_response.user, session=self.session
).exclude(project_id__in=project_preferences).delete()
# Create new preferences if projects were selected
preferences = [
ProjectPreference(
user=self.user_survey_response.user,
session=self.session,
project_id=project_id,
)
for project_id in project_preferences
]
ProjectPreference.objects.bulk_create(preferences, ignore_conflicts=True)
# Update GitHub username in user profile
if self.session and (github_username := cleaned_data.get("github_username")):
self.user_survey_response.user.profile.github_username = github_username
self.user_survey_response.user.profile.save(
update_fields=["github_username"]
)
return self.user_survey_response
class SurveyCSVExportForm(forms.Form):
"""Form for generating CSV export with scorer columns"""
scorer_names = forms.CharField(
label=_("Scorer Names"),
widget=forms.Textarea(attrs={"rows": 5, "cols": 40}),
required=False,
help_text=_(
"Enter one scorer name per line. These will be added as "
"empty columns in the CSV for external scoring."
),
)
def clean_scorer_names(self) -> list[str]:
"""Parse scorer names from textarea input"""
scorer_names_text = self.cleaned_data.get("scorer_names", "")
if not scorer_names_text.strip():
return []
# Split by newlines and strip whitespace
scorers = [
name.strip() for name in scorer_names_text.split("\n") if name.strip()
]
return scorers
def generate_csv(self, survey: Survey, request_data: dict) -> HttpResponse:
"""
Generate CSV based on which button was clicked.
Args:
survey: The survey to export
request_data: POST data to check which button was clicked
Returns:
HttpResponse with CSV file
"""
if "generate_scorer_csv" in request_data:
return self.generate_single_scorer_csv(survey)
else:
return self.generate_full_csv(survey)
def generate_full_csv(self, survey: Survey) -> HttpResponse:
"""Generate CSV file with survey responses and scorer columns"""
scorer_names = self.cleaned_data.get("scorer_names", [])
# Get all responses for this survey with related data
responses = (
UserSurveyResponse.objects.filter(survey=survey)
.select_related("user")
.prefetch_related("userquestionresponse_set__question")
.order_by("id")
)
# Get all questions for this survey
questions = survey.questions.all().order_by("ordering")
# Create the HTTP response with CSV headers (UTF-8 encoded)
response = HttpResponse(content_type="text/csv; charset=utf-8")
response["Content-Disposition"] = (
f'attachment; filename="survey_{survey.slug}_responses.csv"'
)
# Add UTF-8 BOM to ensure Excel and other tools properly recognize UTF-8
response.write("\ufeff")
writer = csv.writer(response)
# Write header row
header = ["Response ID", "Submitter Name"]
# Add question labels as columns
header.extend([q.label for q in questions])
# Add scorer columns
header.extend([f"{name} score" for name in scorer_names])
# Add Score and Selection Rank columns
header.append("Score")
header.append("Selection Rank")
writer.writerow(header)
# Write data rows
for response_obj in responses:
row = [
response_obj.id,
f"{response_obj.user.first_name} {response_obj.user.last_name}".strip()
or response_obj.user.email,
]
# Get all question responses for this survey response
question_responses = {
qr.question_id: qr.value
for qr in response_obj.userquestionresponse_set.all()
}
# Add question responses in order
for question in questions:
row.append(question_responses.get(question.id, ""))
# Add empty scorer columns
row.extend([""] * len(scorer_names))
# Add empty Score and Selection Rank columns
row.append("")
row.append("")
writer.writerow(row)
return response
def generate_single_scorer_csv(self, survey: Survey) -> HttpResponse:
"""
Generate anonymized Single Scorer CSV with only TEXT_AREA questions.
Suitable for session organizers to score anonymously.
"""
# Get all responses for this survey with related data
responses = (
UserSurveyResponse.objects.filter(survey=survey)
.select_related("user")
.prefetch_related("userquestionresponse_set__question")
.order_by("id")
)
# Get only TEXT_AREA questions
questions = survey.questions.filter(type_field=TypeField.TEXT_AREA).order_by(
"ordering"
)
# Create the HTTP response with CSV headers (UTF-8 encoded)
response = HttpResponse(content_type="text/csv; charset=utf-8")
response["Content-Disposition"] = (
f'attachment; filename="survey_{survey.slug}_single_scorer.csv"'
)
# Add UTF-8 BOM to ensure Excel and other tools properly recognize UTF-8
response.write("\ufeff")
writer = csv.writer(response)
header = ["Response ID"]
for question in questions:
header.extend([question.label, f"{question.label} Score"])
writer.writerow(header)
# Write data rows
for response_obj in responses:
row = [response_obj.id]
response_map = {
qr.question_id: qr.value
for qr in response_obj.userquestionresponse_set.all()
}
for question in questions:
# Add the response and an empty cell for the score.
row.extend([response_map.get(question.id, ""), ""])
writer.writerow(row)
return response
class SurveyCSVImportForm(forms.Form):
"""Form for importing scores from a CSV file"""
csv_file = forms.FileField(
label=_("CSV File"),
validators=[validators.FileExtensionValidator(["csv"])],
required=True,
help_text=_(
"Upload a CSV file with 'Response ID', 'Score', and 'Selection Rank' columns. "
"Only these columns will be processed; all other columns will be ignored."
),
)
def clean_csv_file(self) -> list[tuple[int, int, int]]:
"""
Parse and validate the CSV file.
Returns:
List of tuples (response_id, score, selection_rank) for valid rows.
All three values are required integers.
Raises:
forms.ValidationError: If CSV is invalid or missing required columns
"""
csv_file = self.cleaned_data.get("csv_file")
if not csv_file:
raise forms.ValidationError(_("No file was uploaded."))
# Check file extension
if not csv_file.name.endswith(".csv"):
raise forms.ValidationError(_("File must be a CSV file."))
try:
# Read the file content and decode it
file_content = csv_file.read().decode("utf-8-sig") # utf-8-sig handles BOM
csv_file.seek(0) # Reset file pointer for potential re-reading
# Parse CSV
reader = csv.DictReader(io.StringIO(file_content))
# Validate required columns exist
if not reader.fieldnames:
raise forms.ValidationError(_("CSV file is empty or has no headers."))
required_columns = ["Response ID", "Score", "Selection Rank"]
for column in required_columns:
if column not in reader.fieldnames:
raise forms.ValidationError(
_(f"CSV file must contain a '{column}' column.")
)
# Parse and validate rows
updates = []
errors = []
row_number = 1 # Start at 1 for header, increment for data rows
for row in reader:
row_number += 1
response_id_str = row.get("Response ID", "").strip()
score_str = row.get("Score", "").strip()
selection_rank_str = row.get("Selection Rank", "").strip()
# Skip rows with empty Response ID, Score, or Selection Rank
if not response_id_str or not score_str or not selection_rank_str:
continue
# Validate Response ID is an integer
try:
response_id = int(response_id_str)
except ValueError:
errors.append(
_(
f"Row {row_number}: Invalid Response ID '{response_id_str}' "
"(must be an integer)"
)
)
continue
# Validate Score is an integer
try:
score = int(score_str)
except ValueError:
errors.append(
_(
f"Row {row_number}: Invalid Score '{score_str}' (must be an integer)"
)
)
continue
# Validate Selection Rank is an integer (required)
try:
selection_rank = int(selection_rank_str)
except ValueError:
errors.append(
_(
f"Row {row_number}: Invalid Selection Rank '{selection_rank_str}' "
"(must be an integer)"
)
)
continue
updates.append((response_id, score, selection_rank))
# Report errors if any
if errors:
raise forms.ValidationError(errors)
# Ensure we have at least one valid row
if not updates:
raise forms.ValidationError(
"No valid data rows found. Ensure the CSV has 'Response ID', "
"'Score', and 'Selection Rank' columns with valid integer values."
)
return updates
except UnicodeDecodeError:
raise forms.ValidationError(
"File encoding error. Please ensure the file is UTF-8 encoded."
)
except csv.Error as e:
raise forms.ValidationError(f"CSV parsing error: {e}")
def import_scores(self, survey: Survey) -> dict:
"""
Import scores from the validated CSV data.
Args:
survey: The survey to import scores for
Returns:
Dictionary with import statistics:
- updated: Number of responses updated
"""
updates = self.cleaned_data.get("csv_file")
if not updates:
return {"updated": 0}
response_ids = [response_id for response_id, _, _ in updates]
score_map = {response_id: score for response_id, score, _ in updates}
selection_rank_map = {
response_id: selection_rank for response_id, _, selection_rank in updates
}
# Fetch all relevant UserSurveyResponse objects for this survey only
existing_responses = UserSurveyResponse.objects.filter(
id__in=response_ids,
survey=survey,
)
# Update scores and selection_rank using a transaction
updated_count = 0
with transaction.atomic():
for response in existing_responses.select_for_update():
response.score = score_map[response.id]
response.selection_rank = selection_rank_map[response.id]
response.save(update_fields=["score", "selection_rank"])
updated_count += 1
return {"updated": updated_count}
# Team Formation Forms
class ApplicantFilterForm(forms.Form):
"""Form for filtering applicants by various criteria."""
score_min = forms.IntegerField(
label=_("Minimum Score"),
required=False,
widget=forms.NumberInput(
attrs={"class": "form-input", "placeholder": "e.g., 0"}
),
)
score_max = forms.IntegerField(
label=_("Maximum Score"),
required=False,
widget=forms.NumberInput(
attrs={"class": "form-input", "placeholder": "e.g., 10"}
),
)
rank_min = forms.IntegerField(
label=_("Minimum Selection Rank"),
required=False,
widget=forms.NumberInput(
attrs={"class": "form-input", "placeholder": "e.g., 1"}
),
)
rank_max = forms.IntegerField(
label=_("Maximum Selection Rank"),
required=False,
widget=forms.NumberInput(
attrs={"class": "form-input", "placeholder": "e.g., 50"}
),
)
team = forms.ModelChoiceField(
label=_("Team Assignment"),
queryset=None,
required=False,
empty_label=_("All"),
widget=forms.Select(attrs={"class": "form-select"}),
)
show_unassigned_only = forms.BooleanField(
label=_("Show only unassigned applicants"),
required=False,
widget=forms.CheckboxInput(attrs={"class": "form-checkbox"}),
)
overlap_with_navigators = forms.ModelChoiceField(
label=_("Has overlap with navigators"),
queryset=None,
required=False,
empty_label=_("All"),
widget=forms.Select(attrs={"class": "form-select"}),
help_text=_(
"Show only applicants with availability overlap with team navigators"
),
)
overlap_with_captain = forms.ModelChoiceField(
label=_("Has overlap with captain"),
queryset=None,
required=False,
empty_label=_("All"),
widget=forms.Select(attrs={"class": "form-select"}),
help_text=_("Show only applicants with availability overlap with team captain"),
)
def __init__(self, *args, session=None, **kwargs):
super().__init__(*args, **kwargs)
self.session = session
if session:
# Populate team choices for this session
team_queryset = session.teams.all().order_by("name")
self.fields["team"].queryset = team_queryset
self.fields["overlap_with_navigators"].queryset = team_queryset
self.fields["overlap_with_captain"].queryset = team_queryset
class BaseTeamForm(forms.Form):
"""
Base class for forms that require a session context
and accept a comma-delimited list of user IDs.
Provides:
- user_ids field (hidden input)
- clean_user_ids method with validation
- get_selected_users method to retrieve user objects
"""
user_ids = forms.CharField(
widget=forms.HiddenInput(),
required=True,
help_text=_("Comma-separated list of user IDs"),
)
def __init__(self, *args, session, **kwargs):
"""Initialize form with session context."""
super().__init__(*args, **kwargs)
self.session = session
def clean_user_ids(self) -> list[int]:
"""Parse and validate comma-delimited user IDs."""
user_ids_str = self.cleaned_data.get("user_ids", "")
if not user_ids_str:
raise forms.ValidationError(_("No users selected"))
try:
user_ids = [
int(uid.strip()) for uid in user_ids_str.split(",") if uid.strip()
]
except ValueError:
raise forms.ValidationError(_("Invalid user ID format"))
if not user_ids:
raise forms.ValidationError(_("No users selected"))
# Verify users exist
existing_count = CustomUser.objects.filter(id__in=user_ids).count()
if existing_count != len(user_ids):
raise forms.ValidationError(_("Some selected users do not exist"))
return user_ids
def get_selected_users(self) -> list[CustomUser]:
"""
Get selected users with prefetched availability.
Returns:
List of CustomUser instances with availability prefetched
"""
user_ids = self.cleaned_data["user_ids"]
return list(
CustomUser.objects.filter(id__in=user_ids).prefetch_related("availability")
)
class OverlapAnalysisForm(BaseTeamForm):
"""Form for analyzing availability overlap between selected users and team members."""
prefix = "overlap"
team = forms.ModelChoiceField(
label=_("Team"),
queryset=None,
required=True,
empty_label=_("Choose Team to check availability overlap"),
help_text=_("Team whose navigators/captain will be included in analysis"),
widget=forms.Select(attrs={"class": "form-select"}),
)
analysis_type = forms.ChoiceField(
label=_("Analysis Type"),
choices=[
("overlap-navigator", _("Check Navigator Overlap")),
("overlap-captain", _("Check Captain Overlap")),
],
initial="overlap-navigator",
widget=forms.RadioSelect(attrs={"class": "form-radio"}),
)
def __init__(self, *args, **kwargs):
"""Initialize form with session context for team queryset."""
super().__init__(*args, **kwargs)
self.fields["team"].queryset = self.session.teams.order_by("name")
def get_existing_members(self) -> list[CustomUser]:
"""
Get navigators and djangonauts from the selected team in a single query.
Returns:
Tuple of (navigators, existing_djangonauts) with availability prefetched
Raises:
forms.ValidationError: If team has no navigators
"""
team = self.cleaned_data["team"]
selected_users = self.cleaned_data["user_ids"]
team_memberships = (
SessionMembership.objects.for_team(team)
.filter(
role__in=[SessionMembership.NAVIGATOR, SessionMembership.DJANGONAUT]
)
.exclude(user_id__in=selected_users)
.select_related("user")
.prefetch_related("user__availability")
)
return [membership.user for membership in team_memberships]
def get_team_captain(self) -> CustomUser:
"""
Get captain from the selected team.
Returns:
Captain user with availability prefetched
Raises:
forms.ValidationError: If team has no captain
"""
team = self.cleaned_data["team"]
captain_memberships = (
SessionMembership.objects.for_team(team)
.captains()
.select_related("user")
.prefetch_related("user__availability")
)
captains = [m.user for m in captain_memberships]
if not captains:
raise forms.ValidationError(f"Team '{team.name}' has no captain assigned")
return captains[0] # Use first captain if multiple
def calculate_navigator_overlap_context(self) -> dict:
"""
Calculate navigator overlap (navigators + selected users).
Returns:
Context dictionary with overlap analysis results
"""
team = self.cleaned_data["team"]
existing_members = self.get_existing_members()
selected_users = self.get_selected_users()
# Calculate overlap (navigators + existing djangonauts + selected users)
all_users = existing_members + selected_users
slots, hours = calculate_overlap(all_users)
time_ranges = format_slots_as_ranges(slots)
# Generate comparison URL
user_ids = [str(u.id) for u in all_users]
compare_url = (
reverse("compare_availability")
+ f"?users={','.join(user_ids)}&session={self.session.id}"
)
return {
"team": team,
"analysis_type": "overlap-navigator",
"existing_members": existing_members,
"selected_users": selected_users,
"hour_blocks": hours,
"time_ranges": time_ranges,
"is_sufficient": hours >= 5,
"compare_availability_url": compare_url,
}
def calculate_captain_overlap_context(self) -> dict:
"""
Calculate captain overlaps (with each selected user).
Returns:
Context dictionary with overlap analysis results
"""
team = self.cleaned_data["team"]
captain = self.get_team_captain()
selected_users = self.get_selected_users()
# Calculate captain overlaps (with each selected user)
results = []
for user in selected_users:
slots, hours = calculate_overlap([captain, user])
time_ranges = format_slots_as_ranges(slots)
user_ids = [str(captain.id), str(user.id)]
compare_url = (
reverse("compare_availability")
+ f"?users={','.join(user_ids)}&session={self.session.id}"
)
results.append(
{
"user": user,
"hour_blocks": hours,
"time_ranges": time_ranges,
"is_sufficient": hours >= 2,
"compare_availability_url": compare_url,
}
)
return {
"team": team,
"analysis_type": "overlap-captain",
"captain": captain,
"results": results,
}
def get_overlap_context(self) -> dict:
"""
Get overlap analysis context based on analysis type.
Returns:
Context dictionary for template rendering
Raises:
forms.ValidationError: If team members are missing
"""
analysis_type = self.cleaned_data["analysis_type"]
if analysis_type == "overlap-navigator":
return self.calculate_navigator_overlap_context()
else: # captain
return self.calculate_captain_overlap_context()
class BulkTeamAssignmentForm(BaseTeamForm):
"""Form for bulk assignment of users to a team."""
prefix = "bulk_assign"
team = forms.ModelChoiceField(
label=_("Team"),