|
1 | | -from datetime import timedelta |
| 1 | +import csv |
| 2 | +from datetime import date, timedelta |
| 3 | + |
| 4 | +from django.contrib.auth.base_user import AbstractBaseUser |
| 5 | +from django.contrib.auth.models import AnonymousUser |
| 6 | +from django.db.models import Q |
| 7 | +from django.http import HttpResponse |
2 | 8 |
|
3 | 9 | from ..models.allocation import Allocation, Period |
4 | | -from ..models.students import Student |
| 10 | +from ..models.students import LongRebate, Student |
5 | 11 |
|
6 | 12 |
|
7 | 13 | def fill_periods(email, start_date, end_date): |
@@ -29,3 +35,52 @@ def fill_periods(email, start_date, end_date): |
29 | 35 | print(f"{period_no}: {days} days") |
30 | 36 |
|
31 | 37 | return days_per_period |
| 38 | + |
| 39 | + |
| 40 | +def map_periods_to_long_rebate( |
| 41 | + longRebate: list[LongRebate], user: AbstractBaseUser | AnonymousUser |
| 42 | +): |
| 43 | + periods = Period.objects.filter(semester__name="Autumn 2024") |
| 44 | + period_to_long_rebate_map = {period.Sno: {} for period in periods} |
| 45 | + periods_to_email = {period.Sno: [] for period in periods} |
| 46 | + for rebate in longRebate: |
| 47 | + for period in periods: |
| 48 | + if ( |
| 49 | + rebate.start_date <= period.end_date |
| 50 | + and rebate.end_date > period.start_date |
| 51 | + ): |
| 52 | + start_date: date = max(rebate.start_date, period.start_date) |
| 53 | + end_date: date = min(rebate.end_date, period.end_date) |
| 54 | + if period_to_long_rebate_map[period.Sno].get(rebate.email) is None: |
| 55 | + period_to_long_rebate_map[period.Sno][rebate.email] = 0 |
| 56 | + period_to_long_rebate_map[period.Sno][rebate.email] += ( |
| 57 | + end_date - start_date |
| 58 | + ).days + 1 |
| 59 | + periods_to_email[period.Sno].append(rebate.email) |
| 60 | + |
| 61 | + response = HttpResponse(content_type="text/csv") |
| 62 | + response["Content-Disposition"] = 'attachment; filename="Rebate.csv"' |
| 63 | + |
| 64 | + writer = csv.writer(response) |
| 65 | + writer.writerow(["Email", "Period", "caterer", "Days"]) |
| 66 | + |
| 67 | + for period_no, emails in periods_to_email.items(): |
| 68 | + period = periods[period_no - 1] |
| 69 | + allocations = Allocation.objects.filter(Q(email__in=emails), period=period) |
| 70 | + for allocation in allocations: |
| 71 | + if ( |
| 72 | + not user.is_superuser |
| 73 | + and not user.groups.filter(name="College Administration") |
| 74 | + and not user.username == allocation.caterer.name |
| 75 | + ): |
| 76 | + continue |
| 77 | + writer.writerow( |
| 78 | + [ |
| 79 | + allocation.email, |
| 80 | + period_no, |
| 81 | + allocation.caterer.name, |
| 82 | + period_to_long_rebate_map[period_no][allocation.email], |
| 83 | + ] |
| 84 | + ) |
| 85 | + |
| 86 | + return response |
0 commit comments