-
-
Notifications
You must be signed in to change notification settings - Fork 672
Expand file tree
/
Copy pathadmin.py
More file actions
1368 lines (1151 loc) · 49.7 KB
/
admin.py
File metadata and controls
1368 lines (1151 loc) · 49.7 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
"""Django admin configuration for the sponsors app."""
import contextlib
from textwrap import dedent
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from django.contrib.contenttypes.models import ContentType
from django.contrib.humanize.templatetags.humanize import intcomma
from django.contrib.sites.models import Site
from django.db.models import Subquery
from django.forms import ModelForm
from django.template import Context, Template
from django.urls import path, reverse
from django.utils.functional import cached_property
from django.utils.html import format_html, format_html_join, mark_safe
from import_export import resources
from import_export.admin import ImportExportActionModelAdmin
from import_export.fields import Field
from ordered_model.admin import OrderedModelAdmin
from polymorphic.admin import (
PolymorphicChildModelAdmin,
PolymorphicInlineSupportMixin,
PolymorphicParentModelAdmin,
StackedPolymorphicInline,
)
from apps.cms.admin import ContentManageableModelAdmin
from apps.mailing.admin import BaseEmailTemplateAdmin
from apps.sponsors import views_admin
from apps.sponsors.forms import (
CloneApplicationConfigForm,
RequiredImgAssetConfigurationForm,
SponsorBenefitAdminInlineForm,
SponsorshipBenefitAdminForm,
SponsorshipReviewAdminForm,
)
from apps.sponsors.models import (
SPONSOR_TEMPLATE_HELP_TEXT,
BenefitFeature,
BenefitFeatureConfiguration,
Contract,
EmailTargetableConfiguration,
FileAsset,
GenericAsset,
ImgAsset,
LegalClause,
LogoPlacementConfiguration,
ProvidedFileAssetConfiguration,
ProvidedTextAssetConfiguration,
RequiredImgAssetConfiguration,
RequiredResponseAssetConfiguration,
RequiredTextAssetConfiguration,
ResponseAsset,
Sponsor,
SponsorBenefit,
SponsorContact,
SponsorEmailNotificationTemplate,
Sponsorship,
SponsorshipBenefit,
SponsorshipCurrentYear,
SponsorshipPackage,
SponsorshipProgram,
TextAsset,
TieredBenefitConfiguration,
)
def get_url_base_name(model_class):
"""Return the admin URL base name for the given model class."""
return f"{model_class._meta.app_label}_{model_class._meta.model_name}" # noqa: SLF001 - Django _meta API access is standard
class AssetsInline(GenericTabularInline):
"""Inline for displaying generic assets in read-only mode."""
model = GenericAsset
extra = 0
max_num = 0
def has_delete_permission(self, request, obj):
"""Prevent deletion of assets from the inline."""
return False
readonly_fields = ["internal_name", "user_submitted_info", "value"]
@admin.display(description="Submitted information")
def value(self, obj=None):
"""Return the asset value or empty string if not set."""
if not obj or not obj.value:
return ""
return obj.value
@admin.display(
description="Fullfilled data?",
boolean=True,
)
def user_submitted_info(self, obj=None):
"""Return True if the asset has a submitted value."""
return bool(self.value(obj))
@admin.register(SponsorshipProgram)
class SponsorshipProgramAdmin(OrderedModelAdmin):
"""Admin for managing sponsorship programs with ordering support."""
ordering = ("order",)
list_display = [
"name",
"move_up_down_links",
]
class MultiPartForceForm(ModelForm):
"""ModelForm that always reports as multipart to support file uploads."""
def is_multipart(self):
"""Return True to force multipart encoding for file upload support."""
return True
class BenefitFeatureConfigurationInline(StackedPolymorphicInline):
"""Polymorphic inline for managing benefit feature configurations."""
form = MultiPartForceForm
class LogoPlacementConfigurationInline(StackedPolymorphicInline.Child):
"""Inline for logo placement configuration."""
model = LogoPlacementConfiguration
class TieredBenefitConfigurationInline(StackedPolymorphicInline.Child):
"""Inline for tiered benefit configuration."""
model = TieredBenefitConfiguration
class EmailTargetableConfigurationInline(StackedPolymorphicInline.Child):
"""Inline for email targetable configuration."""
model = EmailTargetableConfiguration
readonly_fields = ["display"]
def display(self, obj):
"""Return the enabled status label."""
return "Enabled"
class RequiredImgAssetConfigurationInline(StackedPolymorphicInline.Child):
"""Inline for required image asset configuration."""
model = RequiredImgAssetConfiguration
form = RequiredImgAssetConfigurationForm
class RequiredTextAssetConfigurationInline(StackedPolymorphicInline.Child):
"""Inline for required text asset configuration."""
model = RequiredTextAssetConfiguration
class RequiredResponseAssetConfigurationInline(StackedPolymorphicInline.Child):
"""Inline for required response asset configuration."""
model = RequiredResponseAssetConfiguration
class ProvidedTextAssetConfigurationInline(StackedPolymorphicInline.Child):
"""Inline for provided text asset configuration."""
model = ProvidedTextAssetConfiguration
class ProvidedFileAssetConfigurationInline(StackedPolymorphicInline.Child):
"""Inline for provided file asset configuration."""
model = ProvidedFileAssetConfiguration
model = BenefitFeatureConfiguration
child_inlines = [
LogoPlacementConfigurationInline,
TieredBenefitConfigurationInline,
EmailTargetableConfigurationInline,
RequiredImgAssetConfigurationInline,
RequiredTextAssetConfigurationInline,
RequiredResponseAssetConfigurationInline,
ProvidedTextAssetConfigurationInline,
ProvidedFileAssetConfigurationInline,
]
@admin.register(SponsorshipBenefit)
class SponsorshipBenefitAdmin(PolymorphicInlineSupportMixin, OrderedModelAdmin):
"""Admin for managing sponsorship benefits with polymorphic feature configurations."""
change_form_template = "sponsors/admin/sponsorshipbenefit_change_form.html"
inlines = [BenefitFeatureConfigurationInline]
ordering = ("-year", "program", "order")
list_display = [
"program",
"year",
"short_name",
"package_only",
"internal_value",
"unavailable",
"move_up_down_links",
]
list_filter = ["program", "year", "package_only", "packages", "new", "standalone", "unavailable"]
search_fields = ["name"]
form = SponsorshipBenefitAdminForm
fieldsets = [
(
"Public",
{
"fields": (
"name",
"description",
"program",
"year",
"packages",
"package_only",
"new",
"unavailable",
"standalone",
),
},
),
(
"Internal",
{
"fields": (
"internal_description",
"internal_value",
"capacity",
"soft_capacity",
"legal_clauses",
"conflicts",
)
},
),
]
def get_urls(self):
"""Register custom URL for updating related sponsorships."""
urls = super().get_urls()
base_name = get_url_base_name(self.model)
my_urls = [
path(
"<int:pk>/update-related-sponsorships",
self.admin_site.admin_view(self.update_related_sponsorships),
name=f"{base_name}_update_related",
),
]
return my_urls + urls
def update_related_sponsorships(self, *args, **kwargs):
"""Delegate to the update_related_sponsorships admin view."""
return views_admin.update_related_sponsorships(self, *args, **kwargs)
@admin.register(SponsorshipPackage)
class SponsorshipPackageAdmin(OrderedModelAdmin):
"""Admin for managing sponsorship packages with ordering and revenue split display."""
ordering = (
"-year",
"order",
)
list_display = ["name", "year", "advertise", "allow_a_la_carte", "get_benefit_split", "move_up_down_links"]
list_filter = ["advertise", "year", "allow_a_la_carte"]
search_fields = ["name"]
def get_readonly_fields(self, request, obj=None):
"""Return readonly fields based on object state and user permissions."""
readonly = ["get_benefit_split"]
if obj:
readonly.append("slug")
if not request.user.is_superuser:
readonly.append("logo_dimension")
return readonly
def get_prepopulated_fields(self, request, obj=None):
"""Prepopulate slug from name only when creating new packages."""
if not obj:
return {"slug": ["name"]}
return {}
@admin.display(description="Revenue split")
def get_benefit_split(self, obj: SponsorshipPackage) -> str:
"""Render a stacked bar chart showing the revenue split across programs."""
colors = [
"#ffde57", # Python Gold
"#4584b6", # Python Blue
"#646464", # Python Grey
]
split = obj.get_default_revenue_split()
# rotate colors through our available palette
if len(split) > len(colors):
colors = colors * (1 + (len(split) // len(colors)))
# build some span elements to show the percentages and have the program name in the title (to show on hover)
widths, spans = [], []
for i, (name, pct) in enumerate(split):
pct_str = f"{pct:.0f}%"
widths.append(pct_str)
spans.append((name, colors[i], pct_str))
# define a style that will show our span elements like a single horizontal stacked bar chart
style = f"color:#fff;text-align:center;cursor:pointer;display:grid;grid-template-columns:{' '.join(widths)}"
split_bar = format_html_join("", "<span title='{}' style='background-color:{}'>{}</span>", spans)
# wrap it all up and put a bow on it
return format_html("<div style='{}'>{}</div>", style, split_bar)
class SponsorContactInline(admin.TabularInline):
"""Inline for managing sponsor contacts."""
model = SponsorContact
raw_id_fields = ["user"]
extra = 0
class SponsorshipsInline(admin.TabularInline):
"""Read-only inline for displaying sponsorships on the sponsor admin page."""
model = Sponsorship
fields = ["link", "status", "year", "applied_on", "start_date", "end_date"]
readonly_fields = ["link", "status", "year", "applied_on", "start_date", "end_date"]
can_delete = False
extra = 0
@admin.display(description="ID")
def link(self, obj):
"""Return a link to the sponsorship change page."""
url = reverse("admin:sponsors_sponsorship_change", args=[obj.id])
return format_html("<a href='{}'>{}</a>", url, obj.id)
@admin.register(Sponsor)
class SponsorAdmin(ContentManageableModelAdmin):
"""Admin for managing sponsors with contacts, sponsorships, and assets inlines."""
inlines = [SponsorContactInline, SponsorshipsInline, AssetsInline]
search_fields = ["name"]
class SponsorBenefitInline(admin.TabularInline):
"""Inline for managing individual sponsor benefits within a sponsorship."""
model = SponsorBenefit
form = SponsorBenefitAdminInlineForm
fields = ["sponsorship_benefit", "benefit_internal_value"]
extra = 0
def has_add_permission(self, request, obj=None):
"""Allow adding benefits only when the sponsorship is open for editing."""
has_add_permission = super().has_add_permission(request, obj=obj)
match = request.resolver_match
if match.url_name == "sponsors_sponsorship_change":
sponsorship = self.parent_model.objects.get(pk=match.kwargs["object_id"])
has_add_permission = has_add_permission and sponsorship.open_for_editing
return has_add_permission
def get_readonly_fields(self, request, obj=None):
"""Make benefit fields readonly when the sponsorship is not open for editing."""
if obj and not obj.open_for_editing:
return ["sponsorship_benefit", "benefit_internal_value"]
return []
def has_delete_permission(self, request, obj=None):
"""Allow deletion only when the sponsorship is open for editing."""
if not obj:
return True
return obj.open_for_editing
def get_queryset(self, request):
"""Filter benefits to only those matching the sponsorship's year."""
# filters the available benefits by the benefits for the year of the sponsorship
match = request.resolver_match
sponsorship = self.parent_model.objects.get(pk=match.kwargs["object_id"])
year = sponsorship.year
return super().get_queryset(request).filter(sponsorship_benefit__year=year)
class TargetableEmailBenefitsFilter(admin.SimpleListFilter):
"""Filter sponsorships by email-targetable benefits for the current year."""
title = "targetable email benefits"
parameter_name = "email_benefit"
@cached_property
def benefits(self):
"""Return a dict mapping benefit IDs to email-targetable benefits."""
qs = EmailTargetableConfiguration.objects.all().values_list("benefit_id", flat=True)
benefits = SponsorshipBenefit.objects.filter(id__in=Subquery(qs), year=SponsorshipCurrentYear.get_year())
return {str(b.id): b for b in benefits}
def lookups(self, request, model_admin):
"""Return filter choices as benefit ID and name pairs."""
return [(k, b.name) for k, b in self.benefits.items()]
def queryset(self, request, queryset):
"""Filter sponsorships to those having the selected email-targetable benefit."""
benefit = self.benefits.get(self.value())
if not benefit:
return queryset
# all sponsors benefit related with such sponsorship benefit
qs = SponsorBenefit.objects.filter(sponsorship_benefit_id=benefit.id).values_list("sponsorship_id", flat=True)
return queryset.filter(id__in=Subquery(qs))
class SponsorshipStatusListFilter(admin.SimpleListFilter):
"""Filter sponsorships by status, excluding rejected by default."""
title = "status"
parameter_name = "status"
def lookups(self, request, model_admin):
"""Return sponsorship status choices."""
return Sponsorship.STATUS_CHOICES
def queryset(self, request, queryset):
"""Filter by status or exclude rejected sponsorships when no filter is selected."""
status = self.value()
# exclude rejected ones by default
if not status:
return queryset.exclude(status=Sponsorship.REJECTED)
return queryset.filter(status=status)
def choices(self, changelist):
"""Replace the default 'All' label with a descriptive status label."""
choices = list(super().choices(changelist))
# replaces django default "All" text by a custom text
choices[0]["display"] = "Applied / Approved / Finalized"
return choices
class SponsorshipResource(resources.ModelResource):
"""Import/export resource for exporting sponsorship data."""
sponsor_name = Field(attribute="sponsor__name", column_name="Company Name")
contact_name = Field(column_name="Contact Name(s)")
contact_email = Field(column_name="Contact Email(s)")
contact_phone = Field(column_name="Contact phone number")
contact_type = Field(column_name="Contact Type(s)")
start_date = Field(attribute="start_date", column_name="Start Date")
end_date = Field(attribute="end_date", column_name="End Date")
web_logo = Field(column_name="Logo")
landing_page_url = Field(attribute="sponsor__landing_page_url", column_name="Webpage link")
level = Field(attribute="package__name", column_name="Sponsorship Level")
cost = Field(attribute="sponsorship_fee", column_name="Sponsorship Cost")
admin_url = Field(attribute="admin_url", column_name="Admin Link")
class Meta:
"""Meta configuration for SponsorshipResource."""
model = Sponsorship
fields = (
"sponsor_name",
"contact_name",
"contact_email",
"contact_phone",
"contact_type",
"start_date",
"end_date",
"web_logo",
"landing_page_url",
"level",
"cost",
"admin_url",
)
export_order = (
"sponsor_name",
"contact_name",
"contact_email",
"contact_phone",
"contact_type",
"start_date",
"end_date",
"web_logo",
"landing_page_url",
"level",
"cost",
"admin_url",
)
def get_sponsorship_url(self, sponsorship):
"""Return the full admin URL for the given sponsorship."""
domain = Site.objects.get_current().domain
url = reverse("admin:sponsors_sponsorship_change", args=[sponsorship.id])
return f"https://{domain}{url}"
def dehydrate_web_logo(self, sponsorship):
"""Return the sponsor's web logo URL for export."""
return sponsorship.sponsor.web_logo.url
def dehydrate_contact_type(self, sponsorship):
"""Return newline-separated contact types for export."""
return "\n".join([contact.type for contact in sponsorship.sponsor.contacts.all()])
def dehydrate_contact_name(self, sponsorship):
"""Return newline-separated contact names for export."""
return "\n".join([contact.name for contact in sponsorship.sponsor.contacts.all()])
def dehydrate_contact_email(self, sponsorship):
"""Return newline-separated contact emails for export."""
return "\n".join([contact.email for contact in sponsorship.sponsor.contacts.all()])
def dehydrate_contact_phone(self, sponsorship):
"""Return newline-separated contact phone numbers for export."""
return "\n".join([contact.phone for contact in sponsorship.sponsor.contacts.all()])
def dehydrate_admin_url(self, sponsorship):
"""Return the admin URL for the sponsorship for export."""
return self.get_sponsorship_url(sponsorship)
@admin.register(Sponsorship)
class SponsorshipAdmin(ImportExportActionModelAdmin, admin.ModelAdmin):
"""Admin for managing sponsorships with approval workflow and contract handling."""
change_form_template = "sponsors/admin/sponsorship_change_form.html"
form = SponsorshipReviewAdminForm
inlines = [SponsorBenefitInline, AssetsInline]
search_fields = ["sponsor__name"]
list_display = [
"sponsor",
"status",
"package",
"year",
"applied_on",
"approved_on",
"start_date",
"end_date",
]
list_filter = [SponsorshipStatusListFilter, "package", "year", TargetableEmailBenefitsFilter]
actions = ["send_notifications"]
resource_class = SponsorshipResource
fieldsets = [
(
"Sponsorship Data",
{
"fields": (
"for_modified_package",
"sponsor_link",
"status",
"package",
"sponsorship_fee",
"year",
"get_estimated_cost",
"start_date",
"end_date",
"get_contract",
"level_name",
"renewal",
"overlapped_by",
),
},
),
(
"Sponsor Detailed Information",
{
"fields": (
"get_sponsor_name",
"get_sponsor_description",
"get_sponsor_landing_page_url",
"get_sponsor_web_logo",
"get_sponsor_white_logo",
"get_sponsor_print_logo",
"get_sponsor_primary_phone",
"get_sponsor_mailing_address",
"get_sponsor_contacts",
),
},
),
(
"User Customizations",
{
"fields": (
"get_custom_benefits_added_by_user",
"get_custom_benefits_removed_by_user",
),
"classes": ["collapse"],
},
),
(
"Events dates",
{
"fields": (
"applied_on",
"approved_on",
"rejected_on",
"finalized_on",
),
"classes": ["collapse"],
},
),
]
def get_fieldsets(self, request, obj=None):
"""Expand the User Customizations section when customizations exist."""
fieldsets = []
for title, cfg in super().get_fieldsets(request, obj):
# disable collapse option in case of sponsorships with customizations
if (
title == "User Customizations"
and obj
and (obj.user_customizations["added_by_user"] or obj.user_customizations["removed_by_user"])
):
cfg["classes"] = []
fieldsets.append((title, cfg))
return fieldsets
def get_queryset(self, *args, **kwargs):
"""Optimize queryset with select_related for sponsor, package, and submitter."""
qs = super().get_queryset(*args, **kwargs)
return qs.select_related("sponsor", "package", "submited_by")
@admin.action(description="Send notifications to selected")
def send_notifications(self, request, queryset):
"""Delegate to the send_sponsorship_notifications_action admin view."""
return views_admin.send_sponsorship_notifications_action(self, request, queryset)
def get_readonly_fields(self, request, obj):
"""Return readonly fields based on sponsorship editing state and year."""
readonly_fields = [
"for_modified_package",
"sponsor_link",
"status",
"applied_on",
"rejected_on",
"approved_on",
"finalized_on",
"level_name",
"get_estimated_cost",
"get_sponsor_name",
"get_sponsor_description",
"get_sponsor_landing_page_url",
"get_sponsor_web_logo",
"get_sponsor_white_logo",
"get_sponsor_print_logo",
"get_sponsor_primary_phone",
"get_sponsor_mailing_address",
"get_sponsor_contacts",
"get_contract",
"get_added_by_user",
"get_custom_benefits_added_by_user",
"get_custom_benefits_removed_by_user",
]
if obj and not obj.open_for_editing:
extra = ["start_date", "end_date", "package", "level_name", "sponsorship_fee"]
readonly_fields.extend(extra)
if obj.year:
readonly_fields.append("year")
return readonly_fields
@admin.display(description="Sponsor")
def sponsor_link(self, obj):
"""Return an HTML link to the sponsor's admin change page."""
url = reverse("admin:sponsors_sponsor_change", args=[obj.sponsor.id])
return format_html("<a href='{}'>{}</a>", url, obj.sponsor.name)
@admin.display(description="Estimated cost")
def get_estimated_cost(self, obj):
"""Return the estimated cost HTML for customized sponsorships."""
html = "This sponsorship has not customizations so there's no estimated cost"
if obj.for_modified_package:
msg = "This sponsorship has customizations and this cost is a sum of all benefit's internal values from when this sponsorship was created"
cost = intcomma(obj.estimated_cost)
html = format_html("{} USD <br/><b>Important: </b> {}", cost, msg)
return html
@admin.display(description="Contract")
def get_contract(self, obj):
"""Return an HTML link to the contract or a placeholder."""
if not obj.contract:
return "---"
url = reverse("admin:sponsors_contract_change", args=[obj.contract.pk])
return format_html("<a href='{}' target='_blank'>{}</a>", url, obj.contract)
def get_urls(self):
"""Register custom admin URLs for sponsorship workflow actions."""
urls = super().get_urls()
base_name = get_url_base_name(self.model)
my_urls = [
path(
"<int:pk>/reject",
# TODO: maybe it would be better to create a specific
# group or permission to review sponsorship applications
self.admin_site.admin_view(self.reject_sponsorship_view),
name=f"{base_name}_reject",
),
path(
"<int:pk>/approve-existing",
self.admin_site.admin_view(self.approve_signed_sponsorship_view),
name=f"{base_name}_approve_existing_contract",
),
path(
"<int:pk>/approve",
self.admin_site.admin_view(self.approve_sponsorship_view),
name=f"{base_name}_approve",
),
path(
"<int:pk>/enable-edit",
self.admin_site.admin_view(self.rollback_to_editing_view),
name=f"{base_name}_rollback_to_edit",
),
path(
"<int:pk>/list-assets",
self.admin_site.admin_view(self.list_uploaded_assets_view),
name=f"{base_name}_list_uploaded_assets",
),
path(
"<int:pk>/unlock",
self.admin_site.admin_view(self.unlock_view),
name=f"{base_name}_unlock",
),
path(
"<int:pk>/lock",
self.admin_site.admin_view(self.lock_view),
name=f"{base_name}_lock",
),
]
return my_urls + urls
@admin.display(description="Name")
def get_sponsor_name(self, obj):
"""Return the sponsor's name."""
return obj.sponsor.name
@admin.display(description="Description")
def get_sponsor_description(self, obj):
"""Return the sponsor's description."""
return obj.sponsor.description
@admin.display(description="Landing Page URL")
def get_sponsor_landing_page_url(self, obj):
"""Return the sponsor's landing page URL."""
return obj.sponsor.landing_page_url
@admin.display(description="Web Logo")
def get_sponsor_web_logo(self, obj):
"""Render and return the sponsor's web logo as a thumbnail image."""
img = obj.sponsor.web_logo
if not img:
return "---"
if img.name and img.name.lower().endswith(".svg"):
return format_html(
'<img src="{}" style="max-width:150px;max-height:150px"/>',
img.url,
)
html = "{% load thumbnail %}{% thumbnail img '150x150' format='PNG' quality=100 as im %}<img src='{{ im.url}}'/>{% endthumbnail %}"
template = Template(html)
context = Context({"img": img})
return mark_safe(template.render(context)) # noqa: S308
@admin.display(description="White Logo")
def get_sponsor_white_logo(self, obj):
"""Render and return the sponsor's white logo as a thumbnail image."""
img = obj.sponsor.white_logo
if not img:
return "---"
if img.name and img.name.lower().endswith(".svg"):
return format_html(
'<img src="{}" style="max-width:150px;max-height:150px;background:#333"/>',
img.url,
)
html = "{% load thumbnail %}{% thumbnail img '150x150' format='PNG' quality=100 as im %}<img src='{{ im.url}}' style='background:#333'/>{% endthumbnail %}"
template = Template(html)
context = Context({"img": img})
return mark_safe(template.render(context)) # noqa: S308
@admin.display(description="Print Logo")
def get_sponsor_print_logo(self, obj):
"""Render and return the sponsor's print logo as a thumbnail image."""
img = obj.sponsor.print_logo
if not img:
return "---"
if img.name and img.name.lower().endswith(".svg"):
return format_html(
'<img src="{}" style="max-width:150px;max-height:150px"/>',
img.url,
)
template = Template(
"{% load thumbnail %}{% thumbnail img '150x150' format='PNG' quality=100 as im %}<img src='{{ im.url}}'/>{% endthumbnail %}"
)
context = Context({"img": img})
return mark_safe(template.render(context)) # noqa: S308
@admin.display(description="Primary Phone")
def get_sponsor_primary_phone(self, obj):
"""Return the sponsor's primary phone number."""
return obj.sponsor.primary_phone
@admin.display(description="Mailing/Billing Address")
def get_sponsor_mailing_address(self, obj):
"""Return the sponsor's formatted mailing address as HTML."""
sponsor = obj.sponsor
if sponsor.state:
city_row_html = format_html(
"<p>{} - {} - {} ({})</p>", sponsor.city, sponsor.state, sponsor.get_country_display(), sponsor.country
)
else:
city_row_html = format_html(
"<p>{} - {} ({})</p>", sponsor.city, sponsor.get_country_display(), sponsor.country
)
if sponsor.mailing_address_line_2:
mail_row_html = format_html(
"<p>{} - {}</p>", sponsor.mailing_address_line_1, sponsor.mailing_address_line_2
)
else:
mail_row_html = format_html("<p>{}</p>", sponsor.mailing_address_line_1)
postal_code_row = format_html("<p>{}</p>", sponsor.postal_code)
return city_row_html + mail_row_html + postal_code_row
@admin.display(description="Contacts")
def get_sponsor_contacts(self, obj):
"""Return the sponsor's contacts formatted as an HTML list."""
html = ""
contacts = obj.sponsor.contacts.all()
primary = [c for c in contacts if c.primary]
not_primary = [c for c in contacts if not c.primary]
if primary:
html = mark_safe("<b>Primary contacts</b><ul>")
html += format_html_join("", "<li>{}: {} / {}</li>", [(c.name, c.email, c.phone) for c in primary])
html += mark_safe("</ul>")
if not_primary:
html += mark_safe("<b>Other contacts</b><ul>")
html += format_html_join("", "<li>{}: {} / {}</li>", [(c.name, c.email, c.phone) for c in not_primary])
html += mark_safe("</ul>")
return html
@admin.display(description="Added by User")
def get_custom_benefits_added_by_user(self, obj):
"""Return benefits added by the user as HTML paragraphs."""
benefits = obj.user_customizations["added_by_user"]
if not benefits:
return "---"
return format_html_join("", "<p>{}</p>", ((b,) for b in benefits))
@admin.display(description="Removed by User")
def get_custom_benefits_removed_by_user(self, obj):
"""Return benefits removed by the user as HTML paragraphs."""
benefits = obj.user_customizations["removed_by_user"]
if not benefits:
return "---"
return format_html_join("", "<p>{}</p>", ((b,) for b in benefits))
def rollback_to_editing_view(self, request, pk):
"""Delegate to the rollback_to_editing admin view."""
return views_admin.rollback_to_editing_view(self, request, pk)
def reject_sponsorship_view(self, request, pk):
"""Delegate to the reject_sponsorship admin view."""
return views_admin.reject_sponsorship_view(self, request, pk)
def approve_sponsorship_view(self, request, pk):
"""Delegate to the approve_sponsorship admin view."""
return views_admin.approve_sponsorship_view(self, request, pk)
def approve_signed_sponsorship_view(self, request, pk):
"""Delegate to the approve_signed_sponsorship admin view."""
return views_admin.approve_signed_sponsorship_view(self, request, pk)
def list_uploaded_assets_view(self, request, pk):
"""Delegate to the list_uploaded_assets admin view."""
return views_admin.list_uploaded_assets(self, request, pk)
def unlock_view(self, request, pk):
"""Delegate to the unlock admin view."""
return views_admin.unlock_view(self, request, pk)
def lock_view(self, request, pk):
"""Delegate to the lock admin view."""
return views_admin.lock_view(self, request, pk)
@admin.register(SponsorshipCurrentYear)
class SponsorshipCurrentYearAdmin(admin.ModelAdmin):
"""Admin for managing the current sponsorship year and cloning configurations."""
list_display = ["year", "links", "other_years"]
change_list_template = "sponsors/admin/sponsors_sponsorshipcurrentyear_changelist.html"
def has_add_permission(self, *args, **kwargs):
"""Prevent adding new current year records."""
return False
def has_delete_permission(self, *args, **kwargs):
"""Prevent deleting the current year record."""
return False
def get_urls(self):
"""Register the clone configuration URL."""
urls = super().get_urls()
base_name = get_url_base_name(self.model)
my_urls = [
path(
"clone-year-config",
self.admin_site.admin_view(self.clone_application_config),
name=f"{base_name}_clone",
),
]
return my_urls + urls
@admin.display(description="Links")
def links(self, obj):
"""Return HTML links to application preview and benefit/package lists."""
application_url = reverse("select_sponsorship_application_benefits")
benefits_url = reverse("admin:sponsors_sponsorshipbenefit_changelist")
preview_label = "View sponsorship application"
year = obj.year
preview_querystring = f"config_year={year}"
preview_url = f"{application_url}?{preview_querystring}"
filter_querystring = f"year={year}"
year_benefits_url = f"{benefits_url}?{filter_querystring}"
year_packages_url = f"{benefits_url}?{filter_querystring}"
return format_html(
dedent("""
<ul>
<li><a target='_blank' href='{year_packages_url}'>List packages</a>
<li><a target='_blank' href='{year_benefits_url}'>List benefits</a>
<li><a target='_blank' href='{preview_url}'>{preview_label}</a>
</ul>
"""),
year_packages_url=year_packages_url,
year_benefits_url=year_benefits_url,
preview_url=preview_url,
preview_label=preview_label,
)
@admin.display(description="Other configured years")
def other_years(self, obj):
"""Return HTML links for all configured years except the current one."""
clone_form = CloneApplicationConfigForm()
configured_years = clone_form.configured_years
with contextlib.suppress(ValueError):
configured_years.remove(obj.year)
if not configured_years:
return "---"
application_url = reverse("select_sponsorship_application_benefits")
benefits_url = reverse("admin:sponsors_sponsorshipbenefit_changelist")
preview_label = "View sponsorship application form for this year"
html = mark_safe("<ul>")
for year in configured_years:
preview_querystring = f"config_year={year}"
preview_url = f"{application_url}?{preview_querystring}"
filter_querystring = f"year={year}"
year_benefits_url = f"{benefits_url}?{filter_querystring}"
year_packages_url = f"{benefits_url}?{filter_querystring}"
html += format_html(
dedent("""
<li><b>{year}</b>:"
<ul>
<li><a target='_blank' href='{year_packages_url}'>List packages</a>
<li><a target='_blank' href='{year_benefits_url}'>List benefits</a>
<li><a target='_blank' href='{preview_url}'>{preview_label}</a>
</ul>
</li>
"""),
year=year,
year_packages_url=year_packages_url,
year_benefits_url=year_benefits_url,
preview_url=preview_url,
preview_label=preview_label,
)
html += mark_safe("</ul>")
return html
def clone_application_config(self, request):
"""Delegate to the clone_application_config admin view."""
return views_admin.clone_application_config(self, request)
@admin.register(LegalClause)
class LegalClauseModelAdmin(OrderedModelAdmin):
"""Admin for managing legal clauses with ordering support."""
list_display = ["internal_name"]
@admin.register(Contract)
class ContractModelAdmin(admin.ModelAdmin):
"""Admin for managing sponsorship contracts with workflow actions."""
change_form_template = "sponsors/admin/contract_change_form.html"
list_filter = ["sponsorship__year"]
list_display = [
"id",
"sponsorship",
"created_on",
"last_update",
"status",
"get_revision",
"document_link",
]