-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathadmin.py
More file actions
790 lines (681 loc) · 24.3 KB
/
admin.py
File metadata and controls
790 lines (681 loc) · 24.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
import logging
from datetime import timedelta
from typing import Dict, List, Optional
from django.contrib import admin, messages
from django.contrib.admin import SimpleListFilter
from django.db import transaction
from django.db.models import Exists, OuterRef
from django.db.models.query import QuerySet
from django.urls import reverse
from django.utils import timezone
from django.utils.safestring import mark_safe
from import_export.admin import ExportMixin
from import_export.fields import Field
from import_export.resources import ModelResource
from conferences.models.conference_voucher import ConferenceVoucher
from conferences.vouchers import create_conference_voucher
from countries import countries
from countries.filters import CountryFilter
from custom_admin.admin import (
confirm_pending_status,
reset_pending_status_back_to_status,
validate_single_conference_selection,
)
from custom_admin.audit import (
create_addition_admin_log_entry,
create_change_admin_log_entry,
)
from grants.tasks import (
send_grant_reply_approved_email,
send_grant_reply_rejected_email,
send_grant_reply_waiting_list_email,
send_grant_reply_waiting_list_update_email,
)
from participants.models import Participant
from pretix import user_has_admission_ticket
from pycon.constants import UTC
from schedule.models import ScheduleItem
from submissions.models import Submission
from users.admin_mixins import ConferencePermissionMixin
from visa.models import InvitationLetterRequest
from .models import (
Grant,
GrantConfirmPendingStatusProxy,
GrantReimbursement,
GrantReimbursementCategory,
)
logger = logging.getLogger(__name__)
EXPORT_GRANTS_FIELDS = (
"name",
"full_name",
"gender",
"occupation",
"grant_type",
"python_usage",
"been_to_other_events",
"needs_funds_for_travel",
"why",
"notes",
"departure_country",
"conference__code",
"created",
)
class GrantResource(ModelResource):
search_field = "user_id"
age_group = Field()
email = Field()
has_sent_submission = Field()
submission_title = Field()
submission_tags = Field()
submission_admin_link = Field()
submission_pycon_link = Field()
grant_admin_link = Field()
USERS_SUBMISSIONS: Dict[int, List[Submission]] = {}
def dehydrate_email(self, obj: Grant):
if obj.user_id:
return obj.user.email
# old grants have email in the model.
return obj.email
def dehydrate_age_group(self, obj: Grant):
if not obj.age_group:
return ""
return Grant.AgeGroup(obj.age_group).label
def dehydrate_has_sent_submission(self, obj: Grant) -> str:
return "TRUE" if obj.user_id in self.USERS_SUBMISSIONS else "FALSE"
def _get_submissions(self, obj: Grant) -> Optional[List[Submission]]:
if not obj.user_id:
return
return self.USERS_SUBMISSIONS.get(obj.user_id)
def dehydrate_submission_title(self, obj: Grant):
submissions = self._get_submissions(obj)
if not submissions:
return
return "\n".join([s.title.localize("en") for s in submissions])
def dehydrate_submission_tags(self, obj: Grant):
submissions = self._get_submissions(obj)
if not submissions:
return
return "\n".join(
[
", ".join(
[
f"{r.tag.name}: {r.rank} / {r.total_submissions_per_tag}"
for r in s.rankings.all()
]
)
for s in submissions
]
)
def dehydrate_submission_pycon_link(self, obj):
submissions = self.USERS_SUBMISSIONS.get(obj.user_id)
if not submissions:
return
return "\n".join(
[f"https://pycon.it/submission/{s.hashid}" for s in submissions]
)
def dehydrate_submission_admin_link(self, obj):
submissions = self.USERS_SUBMISSIONS.get(obj.user_id)
if not submissions:
return
return "\n".join(
[
f"https://admin.pycon.it/admin/submissions/submission/{s.id}/change/"
for s in submissions
]
)
def dehydrate_grant_admin_link(self, obj: Grant):
return f"https://admin.pycon.it/admin/grants/grant/?q={'+'.join(obj.full_name.split(' '))}" # noqa: E501
def before_export(self, queryset: QuerySet, *args, **kwargs):
super().before_export(queryset, *args, **kwargs)
conference_id = queryset.values_list("conference_id").first()
submissions = Submission.objects.prefetch_related(
"rankings__tag", "rankings__submission"
).filter(
speaker_id__in=queryset.values_list("user_id", flat=True),
conference_id=conference_id,
)
self.USERS_SUBMISSIONS = {}
for submission in submissions:
self.USERS_SUBMISSIONS.setdefault(submission.speaker_id, [])
self.USERS_SUBMISSIONS[submission.speaker_id].append(submission)
return queryset
class Meta:
model = Grant
fields = EXPORT_GRANTS_FIELDS
export_order = EXPORT_GRANTS_FIELDS
def _check_amounts_are_not_empty(grant: Grant, request):
if grant.total_allocated_amount == 0:
messages.error(
request,
f"Grant for {grant.name} is missing 'Total Amount'!",
)
return False
return True
@admin.action(description="Send Approved/Waiting List/Rejected reply emails")
@validate_single_conference_selection
def send_reply_emails(modeladmin, request, queryset):
queryset = queryset.filter(
status__in=(
Grant.Status.approved,
Grant.Status.waiting_list,
Grant.Status.waiting_list_maybe,
Grant.Status.rejected,
),
)
if not queryset:
messages.add_message(
request, messages.WARNING, "No grants found in the selection"
)
return
for grant in queryset:
if grant.status in (Grant.Status.approved,):
if not grant.reimbursements.exists():
messages.error(
request,
f"Grant for {grant.name} is missing reimbursement categories!",
)
return
if not _check_amounts_are_not_empty(grant, request):
return
now = timezone.now()
grant.applicant_reply_deadline = timezone.datetime(
now.year, now.month, now.day, 23, 59, 59, tzinfo=UTC
) + timedelta(days=14)
grant.save()
send_grant_reply_approved_email.delay(grant_id=grant.id, is_reminder=False)
create_change_admin_log_entry(
request.user,
grant,
change_message="Sent Approved reply email to applicant.",
)
messages.info(request, f"Sent Approved reply email to {grant.name}")
if (
grant.status == Grant.Status.waiting_list
or grant.status == Grant.Status.waiting_list_maybe
):
send_grant_reply_waiting_list_email.delay(grant_id=grant.id)
create_change_admin_log_entry(
request.user,
grant,
change_message="Sent Waiting List reply email to applicant.",
)
messages.info(request, f"Sent Waiting List reply email to {grant.name}")
if grant.status == Grant.Status.rejected:
send_grant_reply_rejected_email.delay(grant_id=grant.id)
create_change_admin_log_entry(
request.user,
grant,
change_message="Sent Rejected reply email to applicant.",
)
messages.info(request, f"Sent Rejected reply email to {grant.name}")
@admin.action(description="Send reminder to waiting confirmation grants")
@validate_single_conference_selection
def send_grant_reminder_to_waiting_for_confirmation(modeladmin, request, queryset):
queryset = queryset.filter(
status__in=(Grant.Status.waiting_for_confirmation,),
)
for grant in queryset:
if not grant.grant_type:
messages.add_message(
request,
messages.ERROR,
f"Grant for {grant.name} is missing 'Grant Approved Type'!",
)
return
_check_amounts_are_not_empty(grant, request)
send_grant_reply_approved_email.delay(grant_id=grant.id, is_reminder=True)
create_change_admin_log_entry(
request.user,
grant,
change_message="Sent Approved reminder email to applicant.",
)
messages.info(request, f"Grant reminder sent to {grant.name}")
@admin.action(description="Send Waiting List update email")
@validate_single_conference_selection
def send_reply_email_waiting_list_update(modeladmin, request, queryset):
queryset = queryset.filter(
status__in=(
Grant.Status.waiting_list,
Grant.Status.waiting_list_maybe,
),
)
for grant in queryset:
send_grant_reply_waiting_list_update_email.delay(grant_id=grant.id)
create_change_admin_log_entry(
request.user,
grant,
change_message="Sent Waiting List update reply email to applicant.",
)
messages.info(request, f"Sent Waiting List update reply email to {grant.name}")
@admin.action(description="Create grant vouchers")
@validate_single_conference_selection
@transaction.atomic
def create_grant_vouchers(modeladmin, request, queryset):
grants_ordered = list(queryset.order_by("id").select_related("user", "conference"))
conference_id = grants_ordered[0].conference_id if grants_ordered else None
user_ids = {g.user_id for g in grants_ordered if g.user_id}
existing_by_user: Dict[int, ConferenceVoucher] = {}
if conference_id is not None and user_ids:
for voucher in ConferenceVoucher.objects.filter(
conference_id=conference_id,
user_id__in=user_ids,
):
existing_by_user[voucher.user_id] = voucher
for grant in grants_ordered:
if grant.status != Grant.Status.confirmed:
messages.error(
request,
f"Grant for {grant.name} is not confirmed, "
"we can't generate voucher for it.",
)
continue
if not grant.user_id:
messages.error(
request,
f"Grant for {grant.name} has no user linked; can't create a voucher.",
)
continue
existing = existing_by_user.get(grant.user_id)
if not existing:
new_voucher = create_conference_voucher(
conference=grant.conference,
user=grant.user,
voucher_type=ConferenceVoucher.VoucherType.GRANT,
)
existing_by_user[grant.user_id] = new_voucher
create_addition_admin_log_entry(
request.user,
grant,
change_message="Created voucher for this grant.",
)
continue
if existing.voucher_type in (
ConferenceVoucher.VoucherType.GRANT,
ConferenceVoucher.VoucherType.SPEAKER,
):
continue
if existing.voucher_type == ConferenceVoucher.VoucherType.CO_SPEAKER:
messages.warning(
request,
f"Grant for {grant.name} already has a Co-Speaker voucher. "
"Upgrading to a Grant voucher.",
)
create_change_admin_log_entry(
request.user,
existing,
change_message="Upgraded Co-Speaker voucher to Grant voucher.",
)
create_change_admin_log_entry(
request.user,
grant,
change_message="Updated existing Co-Speaker voucher to grant.",
)
existing.voucher_type = ConferenceVoucher.VoucherType.GRANT
existing.voucher_email_sent_at = None
existing.save(update_fields=["voucher_type", "voucher_email_sent_at"])
messages.success(request, "Vouchers created!")
@admin.action(description="Mark grants as Rejected and send email")
@validate_single_conference_selection
def mark_rejected_and_send_email(modeladmin, request, queryset):
queryset = queryset.filter(
status__in=(
Grant.Status.waiting_list,
Grant.Status.waiting_list_maybe,
),
)
for grant in queryset:
old_status = grant.status
grant.status = Grant.Status.rejected
grant.save()
create_change_admin_log_entry(
request.user,
grant,
change_message=f"Status changed from '{old_status}' to 'rejected' and rejection email sent.",
)
send_grant_reply_rejected_email.delay(grant_id=grant.id)
messages.info(request, f"Sent Rejected reply email to {grant.name}")
class IsProposedSpeakerFilter(SimpleListFilter):
title = "Is Proposed Speaker"
parameter_name = "is_proposed_speaker"
def lookups(self, request, model_admin):
return (
(True, "Yes"),
(False, "No"),
)
def queryset(self, request, queryset):
if self.value() is not None:
return queryset.filter(is_proposed_speaker=self.value())
return queryset
class IsConfirmedSpeakerFilter(SimpleListFilter):
title = "Is Confirmed Speaker"
parameter_name = "is_confirmed_speaker"
def lookups(self, request, model_admin):
return (
(True, "Yes"),
(False, "No"),
)
def queryset(self, request, queryset):
if self.value() is not None:
return queryset.filter(is_confirmed_speaker=self.value())
return queryset
@admin.register(GrantReimbursementCategory)
class GrantReimbursementCategoryAdmin(ConferencePermissionMixin, admin.ModelAdmin):
list_display = ("__str__", "max_amount", "category", "included_by_default")
list_filter = ("conference", "category", "included_by_default")
search_fields = ("category", "name")
@admin.register(GrantReimbursement)
class GrantReimbursementAdmin(ConferencePermissionMixin, admin.ModelAdmin):
list_display = (
"grant",
"category",
"granted_amount",
)
list_filter = ("grant__conference", "category")
search_fields = ("grant__full_name", "grant__email")
autocomplete_fields = ("grant",)
def delete_model(self, request, obj):
create_change_admin_log_entry(
request.user,
obj.grant,
change_message=f"Reimbursement removed: {obj.category.name}.",
)
super().delete_model(request, obj)
class GrantReimbursementInline(admin.TabularInline):
model = GrantReimbursement
extra = 0
autocomplete_fields = ["category"]
fields = ["category", "granted_amount"]
def delete_model(self, request, obj):
create_change_admin_log_entry(
request.user,
obj.grant,
change_message=f"Reimbursement removed: {obj.category.name}.",
)
super().delete_model(request, obj)
@admin.register(Grant)
class GrantAdmin(ExportMixin, ConferencePermissionMixin, admin.ModelAdmin):
change_list_template = "admin/grants/grant/change_list.html"
resource_class = GrantResource
list_display = (
"user_display_name",
"country",
"is_proposed_speaker",
"is_confirmed_speaker",
"has_sent_invitation_letter_request",
"emoji_gender",
"conference",
"current_or_pending_status",
"total_amount_display",
"approved_amounts_display",
"country_type",
"user_has_ticket",
"has_voucher",
"applicant_reply_sent_at",
"applicant_reply_deadline",
"created",
)
list_filter = (
"conference",
"status",
"pending_status",
"country_type",
"occupation",
"needs_funds_for_travel",
"need_visa",
"need_accommodation",
IsProposedSpeakerFilter,
IsConfirmedSpeakerFilter,
("departure_country", CountryFilter),
"user__gender",
)
search_fields = (
"email",
"full_name",
"departure_country",
"been_to_other_events",
"why",
"notes",
)
actions = [
send_reply_emails,
send_grant_reminder_to_waiting_for_confirmation,
send_reply_email_waiting_list_update,
create_grant_vouchers,
mark_rejected_and_send_email,
"delete_selected",
]
autocomplete_fields = ("user",)
inlines = [GrantReimbursementInline]
fieldsets = (
(
"Manage the Grant",
{
"fields": (
"status",
"pending_status",
"country_type",
"applicant_reply_sent_at",
"applicant_reply_deadline",
"internal_notes",
)
},
),
(
"About the Applicant",
{
"fields": (
"name",
"full_name",
"conference",
"user",
"age_group",
"gender",
"occupation",
)
},
),
(
"The Grant",
{
"fields": (
"grant_type",
"needs_funds_for_travel",
"need_visa",
"need_accommodation",
"nationality",
"departure_country",
"departure_city",
"why",
"python_usage",
"been_to_other_events",
"community_contribution",
"notes",
)
},
),
)
def save_model(self, request, obj, form, change):
"""
Override to log admin actions when status is changed.
"""
if change:
if obj.status != obj._original_status:
create_change_admin_log_entry(
request.user,
obj,
change_message=f"Status changed from '{obj._original_status}' to '{obj.status}'.",
)
if obj.pending_status != obj._original_pending_status:
create_change_admin_log_entry(
request.user,
obj,
change_message=f"Pending status changed from '{obj._original_pending_status}' to '{obj.pending_status}'.",
)
else:
create_addition_admin_log_entry(
request.user,
obj,
change_message="Grant created.",
)
super().save_model(request, obj, form, change)
def change_view(self, request, object_id, form_url="", extra_context=None):
extra_context = extra_context or {}
grant = self.model.objects.get(id=object_id)
owner_id = grant.user_id
extra_context["participant"] = Participant.objects.filter(
user_id=owner_id,
conference_id=grant.conference_id,
).first()
return super().change_view(
request,
object_id,
form_url,
extra_context=extra_context,
)
@admin.display(description="User", ordering="user__full_name")
def user_display_name(self, obj):
if obj.user_id:
return obj.user.display_name
return obj.email
@admin.display(description="Status")
def current_or_pending_status(self, obj):
return obj.current_or_pending_status
@admin.display(
description="C",
)
def country(self, obj):
if obj.departure_country:
country = countries.get(code=obj.departure_country)
if country:
return country.emoji
return ""
@admin.display(description="✍️")
def is_proposed_speaker(self, obj):
if obj.is_proposed_speaker:
return "✍️"
return ""
@admin.display(description="🗣️")
def is_confirmed_speaker(self, obj):
if obj.is_confirmed_speaker:
return "🗣️"
return ""
@admin.display(description="⚤")
def emoji_gender(self, obj):
gender = obj.user.gender if obj.user else ""
emoji = {
"": "",
"male": "👨🏻💻",
"female": "👩🏼💻",
"other": "🧑🏻🎤",
"not_say": "⛔️",
}
return emoji[gender]
@admin.display(
boolean=True,
)
def user_has_ticket(self, obj: Grant) -> bool:
if not obj.user_id:
return None
try:
return user_has_admission_ticket(
email=obj.user.email,
event_organizer=obj.conference.pretix_organizer_id,
event_slug=obj.conference.pretix_event_id,
)
except Exception as e:
logger.error(e)
return None
@admin.display(
boolean=True,
)
def has_voucher(self, obj: Grant) -> bool:
return obj.has_voucher
@admin.display(description="📧")
def has_sent_invitation_letter_request(self, obj: Grant) -> bool:
if obj.has_invitation_letter_request:
return "📧"
return ""
@admin.display(description="Total")
def total_amount_display(self, obj: Grant) -> str:
return f"{obj.total_allocated_amount:.0f}"
@admin.display(description="Included reimbursements")
def approved_amounts_display(self, obj: Grant) -> str:
text = ", ".join(
f"{r.category.name}: {r.granted_amount:.0f}"
for r in obj.reimbursements.all()
)
return text or "—"
def get_queryset(self, request):
qs = (
super()
.get_queryset(request)
.select_related("user")
.prefetch_related("reimbursements__category")
.annotate(
is_proposed_speaker=Exists(
Submission.objects.non_cancelled().filter(
conference_id=OuterRef("conference_id"),
speaker_id=OuterRef("user_id"),
)
),
is_confirmed_speaker=Exists(
ScheduleItem.objects.filter(
conference_id=OuterRef("conference_id"),
submission__speaker_id=OuterRef("user_id"),
)
),
has_voucher=Exists(
ConferenceVoucher.objects.for_conference(
OuterRef("conference_id"),
).filter(
user_id=OuterRef("user_id"),
)
),
has_invitation_letter_request=Exists(
InvitationLetterRequest.objects.filter(
conference_id=OuterRef("conference_id"),
requester_id=OuterRef("user_id"),
)
),
)
)
return qs
class Media:
js = ["admin/js/jquery.init.js"]
@admin.register(GrantConfirmPendingStatusProxy)
class GrantConfirmPendingStatusProxyAdmin(admin.ModelAdmin):
list_display = (
"id",
"full_name",
"status",
"to",
"pending_status",
"open_grant",
"conference",
)
list_filter = ("status", "pending_status", "conference")
search_fields = ("full_name", "user__email")
list_display_links = None
actions = [
confirm_pending_status,
reset_pending_status_back_to_status,
]
def to(self, obj):
return "➡️"
def has_delete_permission(self, request, obj=None):
return False
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def get_queryset(self, request):
return (
super()
.get_queryset(request)
.filter(
pending_status__isnull=False,
)
)
def open_grant(self, obj):
url = reverse("admin:grants_grant_change", args=[obj.id])
return mark_safe(f'<a href="{url}">Open Grant</a>')