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