-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathforms.py
More file actions
69 lines (59 loc) · 3.01 KB
/
Copy pathforms.py
File metadata and controls
69 lines (59 loc) · 3.01 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Coupon, CouponUser, Campaign
from .settings import COUPON_TYPES
class CouponGenerationForm(forms.Form):
quantity = forms.IntegerField(label=_("Quantity"))
value = forms.IntegerField(label=_("Value"))
type = forms.ChoiceField(label=_("Type"), choices=COUPON_TYPES)
valid_until = forms.SplitDateTimeField(
label=_("Valid until"), required=False,
help_text=_("Leave empty for coupons that never expire")
)
prefix = forms.CharField(label="Prefix", required=False)
campaign = forms.ModelChoiceField(
label=_("Campaign"), queryset=Campaign.objects.all(), required=False
)
class CouponForm(forms.Form):
code = forms.CharField(label=_("Coupon code"))
def __init__(self, *args, **kwargs):
self.user = None
self.types = None
if 'user' in kwargs:
self.user = kwargs['user']
del kwargs['user']
if 'types' in kwargs:
self.types = kwargs['types']
del kwargs['types']
super(CouponForm, self).__init__(*args, **kwargs)
def clean_code(self):
code = self.cleaned_data['code']
try:
coupon = Coupon.objects.get(code=code)
except Coupon.DoesNotExist:
raise forms.ValidationError(_("This code is not valid."))
self.coupon = coupon
if self.user is None and coupon.user_limit != 1:
# coupons with can be used only once can be used without tracking the user, otherwise there is no chance
# of excluding an unknown user from multiple usages.
raise forms.ValidationError(_(
"The server must provide an user to this form to allow you to use this code. Maybe you need to sign in?"
))
if coupon.is_redeemed:
raise forms.ValidationError(_("This code has already been used."))
try: # check if there is a user bound coupon existing
user_coupon = coupon.users.get(user=self.user)
if user_coupon.redeemed_at is not None:
raise forms.ValidationError(_("This code has already been used by your account."))
except CouponUser.DoesNotExist:
if coupon.user_limit != 0: # zero means no limit of user count
# only user bound coupons left and you don't have one
if coupon.user_limit is coupon.users.filter(user__isnull=False).count():
raise forms.ValidationError(_("This code is not valid for your account."))
if coupon.user_limit is coupon.users.filter(redeemed_at__isnull=False).count(): # all coupons redeemed
raise forms.ValidationError(_("This code has already been used."))
if self.types is not None and coupon.type not in self.types:
raise forms.ValidationError(_("This code is not meant to be used here."))
if coupon.expired():
raise forms.ValidationError(_("This code is expired."))
return code