add a filter
[wolnelektury.git] / src / club / forms.py
index 1906bc9..df92524 100644 (file)
@@ -1,50 +1,99 @@
-# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
-# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
+# This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
+# Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
 #
 from decimal import Decimal
 from django import forms
-from . import models
-from .payment_methods import method_by_slug, methods
+from newsletter.forms import NewsletterForm
+from . import models, payment_methods
 from .payu.forms import CardTokenForm
 
 
-class ScheduleForm(forms.ModelForm):
+class PayUCardTokenForm(CardTokenForm):
+    def get_queryset(self, view):
+        return view.get_schedule().payucardtoken_set
+
+
+
+class DonationStep1Form(forms.ModelForm):
+    switch = forms.CharField()
+    single_amount = forms.IntegerField(required=False)
+    monthly_amount = forms.IntegerField(required=False)
+    single_amount_selected = forms.IntegerField(required=False)
+    monthly_amount_selected = forms.IntegerField(required=False)
+    custom_amount = forms.IntegerField(required=False)
+
+    amount = forms.IntegerField(required=False) # hidden
+
     class Meta:
         model = models.Schedule
-        fields = ['plan', 'method', 'amount', 'email']
-        widgets = {
-            'plan': forms.RadioSelect,
-            'method': forms.RadioSelect,
-        }
+        fields = [
+            'amount',
+            'monthly'
+            ]
 
-    def __init__(self, *args, request=None, **kwargs):
-        super(ScheduleForm, self).__init__(*args, **kwargs)
-        self.request = request
-        self.plans = models.Plan.objects.all()
-        self.payment_methods = methods
-        self.fields['amount'].required = False
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        club = models.Club.objects.first()
+        if club is not None:
+            self.fields['custom_amount'].widget.attrs['min'] = club.min_amount
 
     def clean(self):
-        cleaned_data = super(ScheduleForm, self).clean()
+        state = {}
+        state['monthly'] = self.cleaned_data['switch'] == 'monthly'
+        which = 'monthly' if state['monthly'] else 'single'
+        state['amount'] = \
+            self.cleaned_data[f'{which}_amount'] or \
+            self.cleaned_data['custom_amount'] or \
+            self.cleaned_data[f'{which}_amount_selected']
+
+        return state
 
-        if 'plan' in cleaned_data:
-            cleaned_data['amount'] = self.fields['amount'].clean(
-                self.request.POST['amount-{}'.format(cleaned_data['plan'].id)]
+
+
+class DonationStep2Form(forms.ModelForm, NewsletterForm):
+    class Meta:
+        model = models.Schedule
+        fields = [
+            'first_name', 'last_name',
+            'email', 'phone',
+            'postal',
+            'postal_code', 'postal_town', 'postal_country',
+            ]
+        widgets = {
+            'amount': forms.HiddenInput,
+            'monthly': forms.HiddenInput,
+        }
+    
+    def __init__(self, referer=None, **kwargs):
+        self.referer = referer
+        super().__init__(**kwargs)
+
+        self.fields['first_name'].required = True
+        self.fields['last_name'].required = True
+        self.fields['phone'].required = True
+        
+        self.consent = []
+        for c in models.Consent.objects.filter(active=True).order_by('order'):
+            key = f'consent{c.id}'
+            self.fields[key] = forms.BooleanField(
+                label=c.text,
+                required=c.required
             )
+            self.consent.append((
+                c, key, (lambda k: lambda: self[k])(key)
+            ))
 
-            if cleaned_data['amount'] < cleaned_data['plan'].min_amount:
-                self.add_error(
-                    'amount',
-                    'Minimalna kwota dla tego planu to %d zł.' % cleaned_data['plan'].min_amount
-                )
 
-        if 'method' in cleaned_data:
-            method = method_by_slug[cleaned_data['method']]
-            if method not in cleaned_data['plan'].payment_methods():
-                self.add_error('method', 'Wybrana metoda płatności nie jest dostępna dla tego planu.')
 
+    def save(self, *args, **kwargs):
+        NewsletterForm.save(self, *args, **kwargs)
+        self.instance.source = self.referer or ''
+        instance = super().save(*args, **kwargs)
 
+        consents = []
+        for consent, key, consent_field in self.consent:
+            if self.cleaned_data[key]:
+                instance.consent.add(consent)
+
+        return instance
 
-class PayUCardTokenForm(CardTokenForm):
-    def get_queryset(self, view):
-        return view.get_schedule().payucardtoken_set