-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathadmin.py
582 lines (495 loc) · 17.4 KB
/
admin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
from pycon.constants import UTC
from custom_admin.admin import validate_single_conference_selection
from import_export.resources import ModelResource
from datetime import timedelta
from typing import Dict, List, Optional
from countries.filters import CountryFilter
from django import forms
from django.contrib import admin, messages
from django.db.models.query import QuerySet
from django.utils import timezone
from import_export.admin import ExportMixin
from import_export.fields import Field
from django.utils.crypto import get_random_string
from users.admin_mixins import ConferencePermissionMixin
from countries import countries
from grants.tasks import (
send_grant_reply_approved_email,
send_grant_reply_waiting_list_email,
send_grant_reply_waiting_list_update_email,
send_grant_reply_rejected_email,
send_grant_voucher_email,
)
from pretix import create_voucher
from schedule.models import ScheduleItem
from submissions.models import Submission
from .models import Grant, AidCategory, CountryAidAmount, GrantAllocation
from django.db.models import Exists, OuterRef
from django.contrib.admin import SimpleListFilter
EXPORT_GRANTS_FIELDS = (
"name",
"full_name",
"gender",
"occupation",
"grant_type",
"python_usage",
"been_to_other_events",
"interested_in_volunteering",
"needs_funds_for_travel",
"why",
"notes",
"travelling_from",
"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
@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,):
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)
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)
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)
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
send_grant_reply_approved_email.delay(grant_id=grant.id, is_reminder=True)
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)
messages.info(request, f"Sent Waiting List update reply email to {grant.name}")
@admin.action(description="Send voucher via email")
@validate_single_conference_selection
def send_voucher_via_email(modeladmin, request, queryset):
count = 0
for grant in queryset.filter(pretix_voucher_id__isnull=False):
send_grant_voucher_email.delay(grant_id=grant.id)
count = count + 1
messages.success(request, f"{count} Voucher emails scheduled!")
def _generate_voucher_code(prefix: str) -> str:
charset = list("ABCDEFGHKLMNPQRSTUVWXYZ23456789")
random_string = get_random_string(length=20, allowed_chars=charset)
return f"{prefix}-{random_string}"
@admin.action(description="Create grant vouchers on Pretix")
@validate_single_conference_selection
def create_grant_vouchers_on_pretix(modeladmin, request, queryset):
conference = queryset.first().conference
if not conference.pretix_conference_voucher_quota_id:
messages.error(
request,
"Please configure the grant voucher quota ID in the conference settings",
)
return
count = 0
for grant in queryset.filter(pretix_voucher_id__isnull=True).order_by("id"):
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
voucher_code = _generate_voucher_code("GRANT")
pretix_voucher = create_voucher(
conference=grant.conference,
code=voucher_code,
comment=f"Voucher for user_id={grant.user_id}",
tag="grants",
quota_id=grant.conference.pretix_conference_voucher_quota_id,
price_mode="set",
value="0.00",
)
pretix_voucher_id = pretix_voucher["id"]
grant.pretix_voucher_id = pretix_voucher_id
grant.voucher_code = voucher_code
grant.save()
count += 1
messages.success(request, f"{count} Vouchers created on Pretix!")
@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:
grant.status = Grant.Status.rejected
grant.save()
send_grant_reply_rejected_email.delay(grant_id=grant.id)
messages.info(request, f"Sent Rejected reply email to {grant.name}")
class GrantAdminForm(forms.ModelForm):
class Meta:
model = Grant
fields = (
"id",
"name",
"status",
"full_name",
"conference",
"user",
"age_group",
"gender",
"occupation",
"grant_type",
"python_usage",
"been_to_other_events",
"interested_in_volunteering",
"needs_funds_for_travel",
"why",
"notes",
"travelling_from",
"applicant_reply_sent_at",
"applicant_reply_deadline",
)
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(AidCategory)
class AidCategoryAdmin(admin.ModelAdmin):
list_display = (
"name",
"conference",
"category",
"max_amount",
"included_by_default",
)
list_filter = ("conference", "category")
search_fields = ("name", "description", "conference", "max_amount")
@admin.register(CountryAidAmount)
class CountryAidAmountAdmin(admin.ModelAdmin):
list_display = ("conference", "_country", "max_amount")
def _country(self, obj):
if obj.country:
country = countries.get(code=obj.country)
if country:
return f"{country.name} {country.emoji}"
return ""
class GrantAllocationFormSet:
pass
class GrantAllocationInline(admin.StackedInline):
model = GrantAllocation
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == "category":
grant_id = request.resolver_match.kwargs.get("object_id")
if grant_id:
grant = Grant.objects.get(pk=grant_id)
kwargs["queryset"] = AidCategory.objects.filter(
conference=grant.conference
)
else:
kwargs["queryset"] = AidCategory.objects.none()
return super().formfield_for_foreignkey(db_field, request, **kwargs)
@admin.register(Grant)
class GrantAdmin(ExportMixin, ConferencePermissionMixin, admin.ModelAdmin):
change_list_template = "admin/grants/grant/change_list.html"
resource_class = GrantResource
form = GrantAdminForm
list_display = (
"user_display_name",
"country",
"is_proposed_speaker",
"is_confirmed_speaker",
"emoji_gender",
"conference",
"status",
"applicant_reply_sent_at",
"applicant_reply_deadline",
"voucher_code",
"voucher_email_sent_at",
"created",
)
list_filter = (
"conference",
"status",
"occupation",
"interested_in_volunteering",
"needs_funds_for_travel",
"need_visa",
"need_accommodation",
IsProposedSpeakerFilter,
IsConfirmedSpeakerFilter,
("travelling_from", CountryFilter),
"user__gender",
)
search_fields = (
"email",
"name",
"full_name",
"travelling_from",
"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_on_pretix,
send_voucher_via_email,
mark_rejected_and_send_email,
"delete_selected",
]
autocomplete_fields = ("user",)
fieldsets = (
(
"Manage the Grant",
{
"fields": (
"status",
"applicant_reply_sent_at",
"applicant_reply_deadline",
"pretix_voucher_id",
"voucher_code",
"voucher_email_sent_at",
"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",
"travelling_from",
"why",
"python_usage",
"been_to_other_events",
"community_contribution",
"interested_in_volunteering",
"notes",
"website",
"twitter_handle",
"github_handle",
"linkedin_url",
"mastodon_handle",
)
},
),
)
inlines = [GrantAllocationInline]
@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="C",
)
def country(self, obj):
if obj.travelling_from:
country = countries.get(code=obj.travelling_from)
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]
def get_queryset(self, request):
qs = (
super()
.get_queryset(request)
.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"),
)
),
)
)
return qs
class Media:
js = ["admin/js/jquery.init.js"]