fix
[wolnelektury.git] / src / pz / admin.py
1 from django.contrib import admin
2 from django.contrib.admin.filters import FieldListFilter
3 from django.contrib import messages
4 from django.db.models import Q
5 from django.shortcuts import get_object_or_404, redirect
6 from django.urls import path, reverse
7 from django.utils.safestring import mark_safe
8 from django.utils.translation import gettext_lazy as _
9 from django.utils.timezone import now
10 from fnpdjango.actions import export_as_csv_action
11 from . import bank
12 from . import models
13
14
15 admin.site.register(models.Fundraiser)
16 admin.site.register(models.Campaign)
17
18
19 # Backport from Django 3.1.
20 class EmptyFieldListFilter(FieldListFilter):
21     def __init__(self, field, request, params, model, model_admin, field_path):
22         self.lookup_kwarg = '%s__isempty' % field_path
23         self.lookup_val = params.get(self.lookup_kwarg)
24         super().__init__(field, request, params, model, model_admin, field_path)
25
26     def queryset(self, request, queryset):
27         if self.lookup_kwarg not in self.used_parameters:
28             return queryset
29         if self.lookup_val not in ('0', '1'):
30             raise IncorrectLookupParameters
31
32         lookup_condition = Q(**{'%s__isnull' % self.field_path: True})
33         if self.lookup_val == '1':
34             return queryset.filter(lookup_condition)
35         return queryset.exclude(lookup_condition)
36
37     def expected_parameters(self):
38         return [self.lookup_kwarg]
39
40     def choices(self, changelist):
41         for lookup, title in (
42             (None, _('All')),
43             ('1', _('Empty')),
44             ('0', _('Not empty')),
45         ):
46             yield {
47                 'selected': self.lookup_val == lookup,
48                 'query_string': changelist.get_query_string({self.lookup_kwarg: lookup}),
49                 'display': title,
50             }
51
52
53 class BankExportFeedbackLineInline(admin.TabularInline):
54     model = models.BankExportFeedbackLine
55     extra = 0
56
57
58 @admin.register(models.DirectDebit)
59 class DirectDebitAdmin(admin.ModelAdmin):
60     list_display = [
61         'payment_id', 'acquisition_date',
62         'iban_valid',
63         'latest_status',
64         'bank_submission_date',
65         'bank_acceptance_date',
66         'amount', 'first_name', 'last_name',
67     ]
68     date_hierarchy = 'acquisition_date'
69     search_fields = [
70         'payment_id', 'first_name', 'last_name', 'street', 'building', 'town', 'flat',
71         'phone', 'email', 'iban',
72         'notes',
73         'fundraiser_bill',
74     ]
75     list_filter = [
76         'iban_valid',
77         'agree_fundraising',
78         'agree_newsletter',
79         'fundraiser',
80         'campaign',
81         ('cancelled_at', EmptyFieldListFilter),
82         'latest_status',
83         'needs_redo',
84         'optout',
85         'amount',
86         'sex',
87         'is_consumer',
88         ('fundraiser_commission', EmptyFieldListFilter),
89         ('fundraiser_bonus', EmptyFieldListFilter),
90     ]
91     fieldsets = [
92         (None, {
93             "fields": [
94                 ('first_name', 'sex', 'date_of_birth'),
95                 'last_name',
96                 ('street', 'building'),
97                 ('town', 'flat'),
98                 ('postal_code', 'phone'),
99                 'email',
100                 ('iban', 'iban_valid', 'iban_warning'),
101                 ('payment_id', 'latest_status'),
102                 'agree_contact',
103                 'agree_fundraising',
104                 'agree_newsletter',
105                 ('acquisition_date', 'amount'),
106                 'is_consumer',
107                 'fundraiser',
108                 'campaign',
109             ]
110         }),
111         (_('Processing'), {"fields": [
112             ('cancelled_at', 'needs_redo', 'optout'),
113             'submission_date',
114             'fundraiser_commission',
115             'fundraiser_bonus',
116             'fundraiser_bill',
117             'bank_submission_date',
118             'bank_acceptance_date',
119             'notes',
120             ]
121         })
122     ]
123     readonly_fields = ['agree_contact', 'iban_valid', 'iban_warning', 'latest_status']
124     inlines = [BankExportFeedbackLineInline]
125
126     def set_bank_submission(m, r, q):
127         q.update(bank_submission_date=now())
128
129     def create_bank_order(m, request, queryset):
130         bo = models.BankOrder.objects.create()
131         bo.debits.set(queryset)
132         messages.info(request, mark_safe(
133             '<a href="{}">Bank order</a> created.'.format(
134                 reverse('admin:pz_bankorder_change', args=[bo.pk])
135             )
136         ))
137
138
139     actions = [
140         bank.bank_export,
141         set_bank_submission,
142         create_bank_order,
143         export_as_csv_action(),
144     ]
145
146     def agree_contact(self, obj):
147         return _('obligatory')
148     agree_contact.short_description = _('agree contact')
149
150     def get_changeform_initial_data(self, request):
151         return {
152             'payment_id': models.DirectDebit.get_next_payment_id(),
153         }
154
155
156 @admin.register(models.BankExportFeedback)
157 class BankExportFeedbackAdmin(admin.ModelAdmin):
158     inlines = [BankExportFeedbackLineInline]
159
160
161
162 @admin.register(models.BankOrder)
163 class BankOrderAdmin(admin.ModelAdmin):
164     fields = ['payment_date', 'debits', 'sent', 'download']
165     filter_horizontal = ['debits']
166
167     def get_readonly_fields(self, request, obj=None):
168         fields = ['download']
169         if obj is not None and obj.sent:
170             fields += ['debits', 'payment_date']
171         return fields
172
173     def download(self, obj):
174         if obj is not None and obj.pk:
175             return mark_safe('<a href="{}">Download</a>'.format(
176                 reverse('admin:pz_bankorder_download', args=[obj.pk])
177             ))
178         else:
179             return ''
180
181     def get_urls(self):
182         urls = super().get_urls()
183         my_urls = [
184             path(
185                 '<int:pk>/download/',
186                 self.admin_site.admin_view(self.download_view),
187                 name='pz_bankorder_download',
188             ),
189         ]
190         return my_urls + urls
191
192     def download_view(self, request, pk):
193         order = get_object_or_404(
194             models.BankOrder, pk=pk)
195         try:
196             return bank.bank_order(
197                 order.payment_date,
198                 order.sent,
199                 order.debits.all()
200             )
201         except Exception as e:
202             messages.error(request, str(e))
203             return redirect('admin:pz_bankorder_change', pk)