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 allow_recurring = models.BooleanField(_('allow recurring'))
27 allow_one_time = models.BooleanField(_('allow one time'))
28 active = models.BooleanField(_('active'), default=True)
31 verbose_name = _('plan')
32 verbose_name_plural = _('plans')
35 return "%s %s" % (self.min_amount, self.get_interval_display())
38 ordering = ('interval',)
40 def payment_methods(self):
41 for method in methods:
42 if self.allow_recurring and method.is_recurring or self.allow_one_time and not method.is_recurring:
45 def get_next_installment(self, date):
46 if self.interval == self.PERPETUAL:
47 return datetime.max - timedelta(1)
48 elif self.interval == self.YEAR:
49 return date.replace(year=date.year + 1)
50 elif self.interval == self.MONTH:
52 date = (date.replace(day=1) + timedelta(31)).replace(day=1) + timedelta(day - 1)
54 date = date.replace(day=1)
58 class Schedule(models.Model):
59 """ Represents someone taking up a plan. """
60 key = models.CharField(_('key'), max_length=255, unique=True)
61 email = models.EmailField(_('email'))
62 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.PROTECT)
63 plan = models.ForeignKey(Plan, verbose_name=_('plan'), on_delete=models.PROTECT)
64 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
65 method = models.CharField(_('method'), max_length=255, choices=[(method.slug, method.name) for method in methods])
66 is_cancelled = models.BooleanField(_('cancelled'), default=False)
67 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
68 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
71 verbose_name = _('schedule')
72 verbose_name_plural = _('schedules')
77 def save(self, *args, **kwargs):
79 self.key = get_random_hash(self.email)
80 return super(Schedule, self).save(*args, **kwargs)
82 def initiate_payment(self, request):
83 return self.get_payment_method().initiate(request, self)
85 def pay(self, request):
86 return self.get_payment_method().pay(request, self)
88 def get_absolute_url(self):
89 return reverse('club_schedule', args=[self.key])
91 def get_payment_method(self):
92 return method_by_slug[self.method]
95 return self.expires_at is not None and self.expires_at <= now()
98 return self.expires_at is not None and self.expires_at > now()
101 class Membership(models.Model):
102 """ Represents a user being recognized as a member of the club. """
103 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
104 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
105 name = models.CharField(max_length=255, blank=True)
106 honorary = models.BooleanField(default=False)
109 verbose_name = _('membership')
110 verbose_name_plural = _('memberships')
113 return u'tow. ' + str(self.user)
116 def is_active_for(cls, user):
117 if user.is_anonymous:
120 membership = user.membership
121 except cls.DoesNotExist:
123 if membership.honorary:
125 return Schedule.objects.filter(
126 expires_at__gt=now(),
127 membership__user=user,
131 class ReminderEmail(models.Model):
132 days_before = models.SmallIntegerField(_('days before'))
133 subject = models.CharField(_('subject'), max_length=1024)
134 body = models.TextField(_('body'))
137 verbose_name = _('reminder email')
138 verbose_name_plural = _('reminder emails')
139 ordering = ['days_before']
142 if self.days_before >= 0:
143 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
145 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
154 class PayUOrder(payu_models.Order):
155 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
157 def get_amount(self):
158 return self.schedule.amount
162 "email": self.schedule.email,
163 "language": get_language(),
166 def get_continue_url(self):
167 return "https://{}{}".format(
168 Site.objects.get_current().domain,
169 self.schedule.get_absolute_url())
171 def get_description(self):
172 return ugettext('Towarzystwo Wolnych Lektur')
174 def is_recurring(self):
175 return self.schedule.get_payment_method().is_recurring
177 def get_card_token(self):
178 return self.schedule.payucardtoken_set.order_by('-created_at').first()
180 def get_notify_url(self):
181 return "https://{}{}".format(
182 Site.objects.get_current().domain,
183 reverse('club_payu_notify', args=[self.pk]))
185 def status_updated(self):
186 if self.status == 'COMPLETED':
187 since = self.schedule.expires_at or now()
188 new_exp = self.schedule.plan.get_next_installment(since)
189 if self.schedule.expires_at is None or self.schedule.expires_at < new_exp:
190 self.schedule.expires_at = new_exp
194 class PayUCardToken(payu_models.CardToken):
195 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
198 class PayUNotification(payu_models.Notification):
199 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')