Skip to content
Snippets Groups Projects
voucher_forms.py 3.34 KiB
Newer Older
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, Worker
from web.models.constants import VOUCHER_STATUS_USED, VOUCHER_STATUS_EXPIRED
from web.models.worker_study_role import WORKER_VOUCHER_PARTNER

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
        self.fields['usage_partner'].queryset = Worker.get_workers_by_worker_type(WORKER_VOUCHER_PARTNER)
        self.fields['number'].widget.attrs['readonly'] = True
        self.fields['number'].required = False
        self.fields['issue_worker'].widget.attrs['readonly'] = True

        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
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            self.fields['voucher_type'].widget.attrs['readonly'] = True
            self.fields['hours'].widget.attrs['readonly'] = True
            self.fields['usage_partner'].widget.attrs['readonly'] = True
            if instance.status in [VOUCHER_STATUS_USED, VOUCHER_STATUS_EXPIRED]:
                self.fields['status'].widget.attrs['readonly'] = True
                self.fields['feedback'].widget.attrs['readonly'] = True

    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=90)
            if Voucher.objects.all().count() > 0:
                max_id = str(Voucher.objects.latest('id').id + 1).zfill(4)
            # number in format  {ND_NUMBER}-{DATE}-{VOUCHER_TYPE_CODE}-{VOUCHER_TYPE}-{SEQ_NUMBER}{CHECKSUM}
            instance.number = instance.study_subject.nd_number + "-" + \
                              datetime.datetime.now().strftime("%Y%m%d") + "-" + \
                              instance.voucher_type.code + "-" + \
                              instance.usage_partner.voucher_partner_code + "-" + \
                              max_id + VerhoeffAlgorithm.calculate_verhoeff_check_sum(max_id)
        if commit:
            instance.save()