Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import datetime
import logging
from django import forms
from django.forms import ModelForm
from django.utils import timezone
from web.algorithm import VerhoeffAlgorithm
from web.forms.forms import DATEPICKER_DATE_ATTRS
from web.models import VoucherType, VoucherTypePrice, Voucher
from web.models.constants import VOUCHER_STATUS_NEW, VOUCHER_STATUS_USED
logger = logging.getLogger(__name__)
class VoucherTypeForm(ModelForm):
class Meta:
model = VoucherType
exclude = ['study']
class VoucherTypePriceForm(ModelForm):
start_date = forms.DateField(label="Start date",
widget=forms.DateInput(DATEPICKER_DATE_ATTRS, "%Y-%m-%d")
)
end_date = forms.DateField(label="End date",
widget=forms.DateInput(DATEPICKER_DATE_ATTRS, "%Y-%m-%d")
)
class Meta:
model = VoucherTypePrice
exclude = ['voucher_type']
class VoucherForm(ModelForm):
class Meta:
model = Voucher
fields = '__all__'
def __init__(self, *args, **kwargs):
voucher_types = kwargs.pop('voucher_types', VoucherType.objects.all())
super(VoucherForm, self).__init__(*args, **kwargs)
self.fields['voucher_type'].queryset = voucher_types
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
self.fields['number'].widget.attrs['readonly'] = True
self.fields['number'].required = False
self.fields['issue_date'].widget.attrs['readonly'] = True
self.fields['issue_date'].required = False
self.fields['expiry_date'].widget.attrs['readonly'] = True
self.fields['expiry_date'].required = False
self.fields['use_date'].widget.attrs['readonly'] = True
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields['voucher_type'].widget.attrs['readonly'] = True
if instance.status != VOUCHER_STATUS_NEW:
self.fields['status'].widget.attrs['readonly'] = True
self.fields['feedback'].widget.attrs['readonly'] = True
self.fields['usage_partner'].widget.attrs['readonly'] = True
def clean(self):
if self.cleaned_data["status"] == VOUCHER_STATUS_USED and not self.cleaned_data["usage_partner"]:
self.add_error('usage_partner', "Partner must be defined for used voucher")
if self.cleaned_data["status"] != VOUCHER_STATUS_USED and self.cleaned_data["usage_partner"]:
self.add_error('status', "Status must be used for voucher with defined partner")
def save(self, commit=True):
instance = super(VoucherForm, self).save(commit=False)
if not instance.id:
instance.issue_date = timezone.now()
instance.expiry_date = instance.issue_date + datetime.timedelta(days=92)
max_id = str(0).zfill(5)
if Voucher.objects.all().count() > 0:
max_id = str(Voucher.objects.latest('id').id).zfill(5)
instance.number = max_id + VerhoeffAlgorithm.calculate_verhoeff_check_sum(max_id)
if instance.status == VOUCHER_STATUS_USED and not instance.use_date:
instance.use_date = timezone.now()
if commit:
instance.save()