pz fixes
[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 class BankPaymentInline(admin.TabularInline):
58     model = models.Payment
59     extra = 0
60
61 @admin.register(models.DirectDebit)
62 class DirectDebitAdmin(admin.ModelAdmin):
63     list_display = [
64         'payment_id', 'acquisition_date',
65         'iban_valid',
66         'latest_status',
67         'bank_submission_date',
68         'bank_acceptance_date',
69         'amount', 'first_name', 'last_name',
70     ]
71     date_hierarchy = 'acquisition_date'
72     search_fields = [
73         'payment_id', 'first_name', 'last_name', 'street', 'building', 'town', 'flat',
74         'phone', 'email', 'iban',
75         'notes',
76         'fundraiser_bill',
77     ]
78     list_filter = [
79         'iban_valid',
80         'agree_fundraising',
81         'agree_newsletter',
82         'fundraiser',
83         'campaign',
84         ('cancelled_at', EmptyFieldListFilter),
85         'latest_status',
86         'needs_redo',
87         'optout',
88         'amount',
89         'sex',
90         'is_consumer',
91         ('fundraiser_commission', EmptyFieldListFilter),
92         ('fundraiser_bonus', EmptyFieldListFilter),
93     ]
94     fieldsets = [
95         (None, {
96             "fields": [
97                 ('first_name', 'sex', 'date_of_birth'),
98                 'last_name',
99                 ('street', 'building'),
100                 ('town', 'flat'),
101                 ('postal_code', 'phone'),
102                 'email',
103                 ('iban', 'iban_valid', 'iban_warning'),
104                 ('payment_id', 'latest_status'),
105                 'agree_contact',
106                 'agree_fundraising',
107                 'agree_newsletter',
108                 ('acquisition_date', 'amount'),
109                 'is_consumer',
110                 'fundraiser',
111                 'campaign',
112             ]
113         }),
114         (_('Processing'), {"fields": [
115             ('cancelled_at', 'needs_redo', 'optout'),
116             'submission_date',
117             'fundraiser_commission',
118             'fundraiser_bonus',
119             'fundraiser_bill',
120             'bank_submission_date',
121             'bank_acceptance_date',
122             'notes',
123             ]
124         })
125     ]
126     readonly_fields = ['agree_contact', 'iban_valid', 'iban_warning', 'latest_status']
127     inlines = [BankExportFeedbackLineInline, BankPaymentInline]
128
129     def set_bank_submission(m, r, q):
130         q.update(bank_submission_date=now())
131
132     def create_bank_order(m, request, queryset):
133         bo = models.BankOrder.objects.create()
134         bo.debits.set(queryset)
135         messages.info(request, mark_safe(
136             '<a href="{}">Bank order</a> created.'.format(
137                 reverse('admin:pz_bankorder_change', args=[bo.pk])
138             )
139         ))
140
141
142     actions = [
143         bank.bank_export,
144         set_bank_submission,
145         create_bank_order,
146         export_as_csv_action(),
147     ]
148
149     def agree_contact(self, obj):
150         return _('obligatory')
151     agree_contact.short_description = _('agree contact')
152
153     def get_changeform_initial_data(self, request):
154         return {
155             'payment_id': models.DirectDebit.get_next_payment_id(),
156         }
157
158
159 @admin.register(models.BankExportFeedback)
160 class BankExportFeedbackAdmin(admin.ModelAdmin):
161     inlines = [BankExportFeedbackLineInline, BankPaymentInline]
162
163
164
165 @admin.register(models.BankOrder)
166 class BankOrderAdmin(admin.ModelAdmin):
167     fields = ['payment_date', 'debits', 'sent', 'download']
168     filter_horizontal = ['debits']
169
170     def get_readonly_fields(self, request, obj=None):
171         fields = ['download']
172         if obj is not None and obj.sent:
173             fields += ['debits', 'payment_date']
174         return fields
175
176     def download(self, obj):
177         if obj is not None and obj.pk:
178             return mark_safe('<a href="{}">Download</a>'.format(
179                 reverse('admin:pz_bankorder_download', args=[obj.pk])
180             ))
181         else:
182             return ''
183
184     def get_urls(self):
185         urls = super().get_urls()
186         my_urls = [
187             path(
188                 '<int:pk>/download/',
189                 self.admin_site.admin_view(self.download_view),
190                 name='pz_bankorder_download',
191             ),
192         ]
193         return my_urls + urls
194
195     def download_view(self, request, pk):
196         order = get_object_or_404(
197             models.BankOrder, pk=pk)
198         try:
199             return bank.bank_order(
200                 order.payment_date,
201                 order.sent,
202                 order.debits.all()
203             )
204         except Exception as e:
205             messages.error(request, str(e))
206             return redirect('admin:pz_bankorder_change', pk)