1 from datetime import datetime, timedelta
2 from django.conf import settings
3 from django.contrib.sites.models import Site
4 from django.urls import reverse
5 from django.db import models
6 from django.utils.timezone import now
7 from django.utils.translation import ugettext_lazy as _, ungettext, ugettext, get_language
8 from catalogue.utils import get_random_hash
9 from .payment_methods import methods, method_by_slug
10 from .payu import models as payu_models
13 class Plan(models.Model):
14 """ Plans are set up by administrators. """
19 (MONTH, _('a month')),
21 (PERPETUAL, _('in perpetuity')),
24 interval = models.SmallIntegerField(_('inteval'), choices=intervals)
25 min_amount = models.DecimalField(_('min amount'), max_digits=10, decimal_places=2)
26 default_amount = models.DecimalField(_('default amount'), max_digits=10, decimal_places=2)
27 allow_recurring = models.BooleanField(_('allow recurring'))
28 allow_one_time = models.BooleanField(_('allow one time'))
29 active = models.BooleanField(_('active'), default=True)
32 verbose_name = _('plan')
33 verbose_name_plural = _('plans')
36 return "%s %s" % (self.min_amount, self.get_interval_display())
39 ordering = ('interval',)
41 def payment_methods(self):
42 for method in methods:
43 if self.allow_recurring and method.is_recurring or self.allow_one_time and not method.is_recurring:
46 def get_next_installment(self, date):
47 if self.interval == self.PERPETUAL:
48 return datetime.max - timedelta(1)
49 elif self.interval == self.YEAR:
50 return date.replace(year=date.year + 1)
51 elif self.interval == self.MONTH:
53 date = (date.replace(day=1) + timedelta(31)).replace(day=1) + timedelta(day - 1)
55 date = date.replace(day=1)
59 class Schedule(models.Model):
60 """ Represents someone taking up a plan. """
61 key = models.CharField(_('key'), max_length=255, unique=True)
62 email = models.EmailField(_('email'))
63 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.PROTECT)
64 plan = models.ForeignKey(Plan, verbose_name=_('plan'), on_delete=models.PROTECT)
65 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
66 method = models.CharField(_('method'), max_length=255, choices=[(method.slug, method.name) for method in methods])
67 is_cancelled = models.BooleanField(_('cancelled'), default=False)
68 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
69 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
72 verbose_name = _('schedule')
73 verbose_name_plural = _('schedules')
78 def save(self, *args, **kwargs):
80 self.key = get_random_hash(self.email)
81 return super(Schedule, self).save(*args, **kwargs)
83 def initiate_payment(self, request):
84 return self.get_payment_method().initiate(request, self)
86 def pay(self, request):
87 return self.get_payment_method().pay(request, self)
89 def get_absolute_url(self):
90 return reverse('club_schedule', args=[self.key])
92 def get_payment_method(self):
93 return method_by_slug[self.method]
96 return self.expires_at is not None and self.expires_at <= now()
99 return self.expires_at is not None and self.expires_at > now()
102 class Membership(models.Model):
103 """ Represents a user being recognized as a member of the club. """
104 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
105 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
106 name = models.CharField(max_length=255, blank=True)
107 honorary = models.BooleanField(default=False)
110 verbose_name = _('membership')
111 verbose_name_plural = _('memberships')
114 return u'tow. ' + str(self.user)
117 def is_active_for(cls, user):
118 if user.is_anonymous:
121 membership = user.membership
122 except cls.DoesNotExist:
124 if membership.honorary:
126 return Schedule.objects.filter(
127 expires_at__gt=now(),
128 membership__user=user,
132 class ReminderEmail(models.Model):
133 days_before = models.SmallIntegerField(_('days before'))
134 subject = models.CharField(_('subject'), max_length=1024)
135 body = models.TextField(_('body'))
138 verbose_name = _('reminder email')
139 verbose_name_plural = _('reminder emails')
140 ordering = ['days_before']
143 if self.days_before >= 0:
144 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
146 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
155 class PayUOrder(payu_models.Order):
156 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
158 def get_amount(self):
159 return self.schedule.amount
163 "email": self.schedule.email,
164 "language": get_language(),
167 def get_continue_url(self):
168 return "https://{}{}".format(
169 Site.objects.get_current().domain,
170 self.schedule.get_absolute_url())
172 def get_description(self):
173 return ugettext('Towarzystwo Wolnych Lektur')
175 def is_recurring(self):
176 return self.schedule.get_payment_method().is_recurring
178 def get_card_token(self):
179 return self.schedule.payucardtoken_set.order_by('-created_at').first()
181 def get_notify_url(self):
182 return "https://{}{}".format(
183 Site.objects.get_current().domain,
184 reverse('club_payu_notify', args=[self.pk]))
186 def status_updated(self):
187 if self.status == 'COMPLETED':
188 since = self.schedule.expires_at or now()
189 new_exp = self.schedule.plan.get_next_installment(since)
190 if self.schedule.expires_at is None or self.schedule.expires_at < new_exp:
191 self.schedule.expires_at = new_exp
195 class PayUCardToken(payu_models.CardToken):
196 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
199 class PayUNotification(payu_models.Notification):
200 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')