Skip to content

Flexible Grant categories #4420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 57 additions & 2 deletions backend/grants/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
create_addition_admin_log_entry,
create_change_admin_log_entry,
)
from django.db.models import Value, IntegerField

from django.db.models import Sum
from django.db.models.functions import Coalesce
from conferences.models.conference_voucher import ConferenceVoucher
from pycon.constants import UTC
from custom_admin.admin import (
Expand All @@ -30,7 +34,12 @@
)
from schedule.models import ScheduleItem
from submissions.models import Submission
from .models import Grant, GrantConfirmPendingStatusProxy
from .models import (
Grant,
GrantConfirmPendingStatusProxy,
GrantReimbursementCategory,
GrantReimbursement,
)
from django.db.models import Exists, OuterRef, F
from pretix import user_has_admission_ticket

Expand Down Expand Up @@ -393,23 +402,51 @@ def queryset(self, request, queryset):
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",)


class GrantReimbursementInline(admin.TabularInline):
model = GrantReimbursement
extra = 0
autocomplete_fields = ["category"]
fields = ["category", "granted_amount"]


@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",
"user",
"country",
"is_proposed_speaker",
"is_confirmed_speaker",
"emoji_gender",
"conference",
"status",
"approved_type",
"approved_amounts_display",
"ticket_amount",
"travel_amount",
"accommodation_amount",
"total_amount",
"total_amount_display",
"country_type",
"user_has_ticket",
"has_voucher",
Expand Down Expand Up @@ -449,6 +486,7 @@ class GrantAdmin(ExportMixin, ConferencePermissionMixin, admin.ModelAdmin):
"delete_selected",
]
autocomplete_fields = ("user",)
inlines = [GrantReimbursementInline]

fieldsets = (
(
Expand Down Expand Up @@ -584,10 +622,22 @@ def user_has_ticket(self, obj: Grant) -> bool:
def has_voucher(self, obj: Grant) -> bool:
return obj.has_voucher

@admin.display(description="Total")
def total_amount_display(self, obj):
return f"{obj.total_allocated:.2f}"

@admin.display(description="Approved Reimbursements")
def approved_amounts_display(self, obj):
return ", ".join(
f"{r.category.name}: {r.granted_amount}" for r in obj.reimbursements.all()
)

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(
Expand All @@ -608,6 +658,11 @@ def get_queryset(self, request):
user_id=OuterRef("user_id"),
)
),
total_allocated=Coalesce(
Sum("reimbursements__granted_amount"),
Value(0),
output_field=IntegerField(),
),
)
)

Expand Down
Empty file.
127 changes: 127 additions & 0 deletions backend/grants/management/commands/backfill_grant_reimbursements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
from decimal import Decimal

from django.core.management.base import BaseCommand
from grants.models import Grant, GrantReimbursement, GrantReimbursementCategory
from conferences.models import Conference


class Command(BaseCommand):
help = "Backfill GrantReimbursement entries from approved_type data on approved grants."

def handle(self, *args, **options):
self.stdout.write("🚀 Starting backfill of grant reimbursements...")

self._ensure_categories_exist()
self._migrate_grants()
self._validate_migration()

self.stdout.write(self.style.SUCCESS("✅ Backfill completed successfully."))

def _ensure_categories_exist(self):
for conference in Conference.objects.all():
GrantReimbursementCategory.objects.get_or_create(
conference=conference,
category="ticket",
defaults={
"name": "Ticket",
"description": "Conference ticket",
"max_amount": conference.grants_default_ticket_amount
or Decimal("0.00"),
"included_by_default": True,
},
)
GrantReimbursementCategory.objects.get_or_create(
conference=conference,
category="travel",
defaults={
"name": "Travel",
"description": "Travel support",
"max_amount": conference.grants_default_travel_from_extra_eu_amount
or Decimal("400.00"),
"included_by_default": False,
},
)
GrantReimbursementCategory.objects.get_or_create(
conference=conference,
category="accommodation",
defaults={
"name": "Accommodation",
"description": "Accommodation support",
"max_amount": conference.grants_default_accommodation_amount
or Decimal("300.00"),
"included_by_default": True,
},
)

def _migrate_grants(self):
grants = Grant.objects.filter(approved_type__isnull=False).exclude(
approved_type=""
)

self.stdout.write(f"📦 Migrating {grants.count()} grants...")

for grant in grants:
categories = {
c.category: c
for c in GrantReimbursementCategory.objects.filter(
conference=grant.conference
)
}

def add_reimbursement(category_key, amount):
if category_key in categories and amount:
GrantReimbursement.objects.get_or_create(
grant=grant,
category=categories[category_key],
defaults={
"granted_amount": amount,
},
)

add_reimbursement("ticket", grant.ticket_amount)

if grant.approved_type in ("ticket_travel", "ticket_travel_accommodation"):
add_reimbursement("travel", grant.travel_amount)

if grant.approved_type in (
"ticket_accommodation",
"ticket_travel_accommodation",
):
add_reimbursement("accommodation", grant.accommodation_amount)

def _validate_migration(self):
errors = []
grants = Grant.objects.filter(approved_type__isnull=False).exclude(
approved_type=""
)

for grant in grants:
original_total = sum(
filter(
None,
[
grant.ticket_amount,
grant.travel_amount,
grant.accommodation_amount,
],
)
)
reimbursements_total = sum(
r.granted_amount for r in GrantReimbursement.objects.filter(grant=grant)
)

if abs(original_total - reimbursements_total) > Decimal("0.01"):
errors.append(
f"Grant ID {grant.id} total mismatch: expected {original_total}, got {reimbursements_total}"
)

if errors:
self.stdout.write(
self.style.ERROR(f"⚠️ Found {len(errors)} grants with mismatched totals")
)
for msg in errors:
self.stdout.write(self.style.WARNING(f" {msg}"))
else:
self.stdout.write(
self.style.SUCCESS("🧮 All grant totals match correctly.")
)
33 changes: 33 additions & 0 deletions backend/grants/migrations/0029_grantreimbursementcategory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Generated by Django 5.1.4 on 2025-06-04 15:20

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('conferences', '0054_conference_frontend_revalidate_secret_and_more'),
('grants', '0028_remove_grant_pretix_voucher_id_and_more'),
]

operations = [
migrations.CreateModel(
name='GrantReimbursementCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('description', models.TextField(blank=True, null=True)),
('max_amount', models.DecimalField(decimal_places=0, help_text='Maximum amount for this category', max_digits=6)),
('category', models.CharField(choices=[('travel', 'Travel'), ('ticket', 'Ticket'), ('accommodation', 'Accommodation'), ('other', 'Other')], max_length=20)),
('included_by_default', models.BooleanField(default=False, help_text='Automatically include this category in grants by default')),
('conference', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reimbursement_categories', to='conferences.conference')),
],
options={
'verbose_name': 'Grant Reimbursement Category',
'verbose_name_plural': 'Grant Reimbursement Categories',
'ordering': ['conference', 'category'],
'unique_together': {('conference', 'category')},
},
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Generated by Django 5.1.4 on 2025-06-04 16:50

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('grants', '0029_grantreimbursementcategory'),
]

operations = [
migrations.CreateModel(
name='GrantReimbursement',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('granted_amount', models.DecimalField(decimal_places=0, help_text='Actual amount granted for this category', max_digits=6, verbose_name='granted amount')),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='grants.grantreimbursementcategory', verbose_name='reimbursement category')),
('grant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reimbursements', to='grants.grant', verbose_name='grant')),
],
options={
'verbose_name': 'Grant Reimbursement',
'verbose_name_plural': 'Grant Reimbursements',
'ordering': ['grant', 'category'],
'unique_together': {('grant', 'category')},
},
),
migrations.AddField(
model_name='grant',
name='reimbursement_categories',
field=models.ManyToManyField(related_name='grants', through='grants.GrantReimbursement', to='grants.grantreimbursementcategory'),
),
]
Loading
Loading