-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathmodels.py
More file actions
176 lines (147 loc) · 5.61 KB
/
Copy pathmodels.py
File metadata and controls
176 lines (147 loc) · 5.61 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import random
from django.conf import settings
from django.db import IntegrityError
from django.db import models
from django.dispatch import Signal
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from .settings import (
COUPON_TYPES,
CODE_LENGTH,
CODE_CHARS,
SEGMENTED_CODES,
SEGMENT_LENGTH,
SEGMENT_SEPARATOR,
)
try:
user_model = settings.AUTH_USER_MODEL
except AttributeError:
from django.contrib.auth.models import User as user_model
redeem_done = Signal(providing_args=["coupon"])
class CouponManager(models.Manager):
def create_coupon(self, type, value, users=[], valid_until=None, prefix="", campaign=None, user_limit=None):
coupon = self.create(
value=value,
code=Coupon.generate_code(prefix),
type=type,
valid_until=valid_until,
campaign=campaign,
)
if user_limit is not None: # otherwise use default value of model
coupon.user_limit = user_limit
try:
coupon.save()
except IntegrityError:
# Try again with other code
coupon = Coupon.objects.create_coupon(type, value, users, valid_until, prefix, campaign)
if not isinstance(users, list):
users = [users]
for user in users:
if user:
CouponUser(user=user, coupon=coupon).save()
return coupon
def create_coupons(self, quantity, type, value, valid_until=None, prefix="", campaign=None):
coupons = []
for i in range(quantity):
coupons.append(self.create_coupon(type, value, None, valid_until, prefix, campaign))
return coupons
def used(self):
return self.exclude(users__redeemed_at__isnull=True)
def unused(self):
return self.filter(users__redeemed_at__isnull=True)
def expired(self):
return self.filter(valid_until__lt=timezone.now())
@python_2_unicode_compatible
class Coupon(models.Model):
value = models.IntegerField(_("Value"), help_text=_("Arbitrary coupon value"))
code = models.CharField(
_("Code"), max_length=30, unique=True, blank=True,
help_text=_("Leaving this field empty will generate a random code."))
type = models.CharField(_("Type"), max_length=20, choices=COUPON_TYPES)
user_limit = models.PositiveIntegerField(_("User limit"), default=1)
created_at = models.DateTimeField(_("Created at"), auto_now_add=True)
valid_until = models.DateTimeField(
_("Valid until"), blank=True, null=True,
help_text=_("Leave empty for coupons that never expire"))
campaign = models.ForeignKey(
'Campaign',
on_delete=models.CASCADE,
verbose_name=_("Campaign"),
blank=True, null=True,
related_name='coupons',
)
objects = CouponManager()
class Meta:
ordering = ['created_at']
verbose_name = _("Coupon")
verbose_name_plural = _("Coupons")
def __str__(self):
return self.code
def save(self, *args, **kwargs):
if not self.code:
self.code = Coupon.generate_code()
super(Coupon, self).save(*args, **kwargs)
def expired(self):
return self.valid_until is not None and self.valid_until < timezone.now()
@property
def is_redeemed(self):
""" Returns true is a coupon is redeemed (completely for all users) otherwise returns false. """
return self.users.filter(
redeemed_at__isnull=False
).count() >= self.user_limit and self.user_limit != 0
@property
def redeemed_at(self):
try:
return self.users.filter(redeemed_at__isnull=False).order_by('redeemed_at').last().redeemed_at
except self.users.through.DoesNotExist:
return None
@classmethod
def generate_code(cls, prefix="", segmented=SEGMENTED_CODES):
code = "".join(random.choice(CODE_CHARS) for i in range(CODE_LENGTH))
if segmented:
code = SEGMENT_SEPARATOR.join([code[i:i + SEGMENT_LENGTH] for i in range(0, len(code), SEGMENT_LENGTH)])
return prefix + code
else:
return prefix + code
def redeem(self, user=None):
try:
coupon_user = self.users.get(user=user)
except CouponUser.DoesNotExist:
try: # silently fix unbouned or nulled coupon users
coupon_user = self.users.get(user__isnull=True)
coupon_user.user = user
except CouponUser.DoesNotExist:
coupon_user = CouponUser(coupon=self, user=user)
coupon_user.redeemed_at = timezone.now()
coupon_user.save()
redeem_done.send(sender=self.__class__, coupon=self)
@python_2_unicode_compatible
class Campaign(models.Model):
name = models.CharField(_("Name"), max_length=255, unique=True)
description = models.TextField(_("Description"), blank=True)
class Meta:
ordering = ['name']
verbose_name = _("Campaign")
verbose_name_plural = _("Campaigns")
def __str__(self):
return self.name
@python_2_unicode_compatible
class CouponUser(models.Model):
coupon = models.ForeignKey(
Coupon,
on_delete=models.CASCADE,
related_name='users',
)
user = models.ForeignKey(
user_model,
on_delete=models.CASCADE,
verbose_name=_("User"),
null=True,
blank=True,
)
redeemed_at = models.DateTimeField(_("Redeemed at"), blank=True, null=True)
class Meta:
unique_together = (('coupon', 'user'),)
def __str__(self):
return str(self.user)