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