Add missing constraint.
[wolnelektury.git] / src / club / models.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from datetime import datetime, timedelta
5 from decimal import Decimal
6 import os
7 import tempfile
8 from django.apps import apps
9 from django.conf import settings
10 from django.contrib.sites.models import Site
11 from django.core.mail import send_mail, EmailMessage
12 from django.urls import reverse
13 from django.db import models
14 from django import template
15 from django.utils.timezone import now, utc
16 from django.utils.translation import gettext_lazy as _, ngettext, gettext, get_language
17 from django_countries.fields import CountryField
18 from catalogue.utils import get_random_hash
19 from messaging.states import Level
20 from reporting.utils import render_to_pdf
21 from .payment_methods import methods
22 from .payu import models as payu_models
23 from .civicrm import report_activity
24 from . import utils
25
26
27 class Club(models.Model):
28     min_amount = models.IntegerField(_('minimum amount'))
29     min_for_year = models.IntegerField(_('minimum amount for year'))
30     default_single_amount = models.IntegerField(_('default single amount'))
31     default_monthly_amount = models.IntegerField(_('default monthly amount'))
32
33     class Meta:
34         verbose_name = _('club')
35         verbose_name_plural = _('clubs')
36     
37     def __str__(self):
38         return 'Klub'
39
40     def get_amounts(self):
41         c = {}
42         single = list(self.singleamount_set.all())
43         monthly = list(self.monthlyamount_set.all())
44         for tag, amounts in ('single', single), ('monthly', monthly):
45             wide_spot = narrow_spot = 0
46             for i, p in enumerate(amounts):
47                 if p.wide:
48                     # Do we have space for xl?
49                     if wide_spot < 2:
50                         p.box_variant = 'xl'
51                         wide_spot += 2
52                     else:
53                         p.box_variant = 'card'
54                         wide_spot += 1
55                     narrow_spot = 0
56                 elif p.description:
57                     p.box_variant = 'card'
58                     if narrow_spot:
59                         amounts[i-1].box_variant = 'bar'
60                     wide_spot += 1
61                     narrow_spot = 0
62                 else:
63                     p.box_variant = 'half'
64                     wide_spot += 1
65                     narrow_spot += 1
66                 wide_spot %= 3
67                 narrow_spot %= 2
68             c[tag] = amounts
69             c[f'{tag}_wide_spot'] = wide_spot
70         return c
71
72     
73
74 class SingleAmount(models.Model):
75     club = models.ForeignKey(Club, models.CASCADE)
76     amount = models.IntegerField()
77     description = models.TextField(blank=True)
78     wide = models.BooleanField(default=False)
79
80     class Meta:
81         ordering = ['amount']
82
83 class MonthlyAmount(models.Model):
84     club = models.ForeignKey(Club, models.CASCADE)
85     amount = models.IntegerField()
86     description = models.TextField(blank=True)
87     wide = models.BooleanField(default=False)
88
89     class Meta:
90         ordering = ['amount']
91
92
93 class Consent(models.Model):
94     order = models.IntegerField()
95     active = models.BooleanField(default=True)
96     text = models.CharField(max_length=2048)
97     required = models.BooleanField()
98
99     class Meta:
100         ordering = ['order']
101     
102     def __str__(self):
103         return self.text
104
105
106 class Schedule(models.Model):
107     """ Represents someone taking up a plan. """
108     key = models.CharField(_('key'), max_length=255, unique=True)
109     email = models.EmailField(_('email'))
110     membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.SET_NULL)
111     amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
112     method = models.CharField(_('method'), max_length=32, choices=[
113         (m.slug, m.name) for m in methods
114         ])
115     monthly = models.BooleanField(_('monthly'), default=True)
116     yearly = models.BooleanField(_('yearly'), default=False)
117
118     source = models.CharField(_('source'), max_length=255, blank=True)
119
120     is_cancelled = models.BooleanField(_('cancelled'), default=False)
121     payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
122     started_at = models.DateTimeField(_('started at'), auto_now_add=True)
123     expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
124     email_sent = models.BooleanField(default=False)
125
126     first_name = models.CharField(max_length=255, blank=True)
127     last_name = models.CharField(max_length=255, blank=True)
128     phone = models.CharField(max_length=255, blank=True)
129     postal = models.CharField(max_length=255, blank=True)
130     postal_code = models.CharField(max_length=255, blank=True)
131     postal_town = models.CharField(max_length=255, blank=True)
132     postal_country = CountryField(default='PL', blank=True)
133
134     consent = models.ManyToManyField(Consent)
135     
136     class Meta:
137         verbose_name = _('schedule')
138         verbose_name_plural = _('schedules')
139
140     def __str__(self):
141         return self.key
142
143     def save(self, *args, **kwargs):
144         if not self.key:
145             self.key = get_random_hash(self.email)
146         super(Schedule, self).save(*args, **kwargs)
147         self.update_contact()
148
149     def initiate_payment(self, request):
150         return self.get_payment_method().initiate(request, self)
151
152     def pay(self, request):
153         return self.get_payment_method().pay(request, self)
154
155     def get_absolute_url(self):
156         return reverse('club_schedule', args=[self.key])
157
158     def get_thanks_url(self):
159         return reverse('club_thanks', args=[self.key])
160
161     def get_payment_method(self):
162         return [m for m in methods if m.slug == self.method][0]
163
164     def get_payment_methods(self):
165         for method in methods:
166             if (self.monthly or self.yearly) and method.is_recurring:
167                 yield method
168             elif not (self.monthly or self.yearly) and method.is_onetime:
169                 yield method
170
171     def is_expired(self):
172         return self.expires_at is not None and self.expires_at <= now()
173
174     def is_active(self):
175         return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
176
177     def is_recurring(self):
178         return self.monthly or self.yearly
179
180     def set_payed(self):
181         since = self.expires_at
182         n = now()
183         if since is None or since < n:
184             since = n
185         new_exp = self.get_next_installment(since)
186         if self.payed_at is None:
187             self.payed_at = n
188         if self.expires_at is None or self.expires_at < new_exp:
189             self.expires_at = new_exp
190             self.save()
191
192         if not self.email_sent:
193             self.send_email()
194     
195     def get_next_installment(self, date):
196         if self.yearly:
197             return utils.add_year(date)
198         if self.monthly:
199             return utils.add_month(date)
200         club = Club.objects.first()
201         if club is not None and self.amount >= club.min_for_year:
202             return utils.add_year(date)
203         return utils.add_month(date)
204
205     def get_other_active_recurring(self):
206         schedules = type(self).objects.exclude(
207             monthly=False, yearly=False
208         ).filter(is_cancelled=False, expires_at__gt=now()).exclude(pk=self.pk)
209         mine_q = models.Q(email=self.email)
210         if self.membership is not None:
211             mine_q |= models.Q(membership__user=self.membership.user)
212         schedules = schedules.filter(mine_q)
213         return schedules.order_by('-expires_at').first()
214     
215     def send_email(self):
216         ctx = {'schedule': self}
217         send_mail(
218             template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
219             template.loader.render_to_string('club/email/thanks.txt', ctx),
220             settings.CONTACT_EMAIL, [self.email], fail_silently=False)
221         self.email_sent = True
222         self.save()
223
224     def send_email_failed_recurring(self):
225         ctx = {
226             'schedule': self,
227             'other': self.get_other_active_recurring(),
228         }
229         send_mail(
230             'Darowizna na Wolne Lektury — problem z płatnością',
231             template.loader.render_to_string('club/email/failed_recurring.txt', ctx),
232             settings.CONTACT_EMAIL, [self.email], fail_silently=False
233         )
234         
235     def update_contact(self):
236         Contact = apps.get_model('messaging', 'Contact')
237         if not self.payed_at:
238             level = Level.TRIED
239             since = self.started_at
240         else:
241             since = self.payed_at
242             if self.is_recurring():
243                 level = Level.RECURRING
244             else:
245                 level = Level.SINGLE
246         Contact.update(self.email, level, since, self.expires_at)
247
248
249
250
251
252 class Membership(models.Model):
253     """ Represents a user being recognized as a member of the club. """
254     user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
255     created_at = models.DateTimeField(_('created at'), auto_now_add=True)
256     name = models.CharField(_('name'), max_length=255, blank=True)
257     manual = models.BooleanField(_('manual'), default=False)
258     notes = models.CharField(_('notes'), max_length=2048, blank=True)
259     updated_at = models.DateField(_('updated at'), auto_now=True, blank=True)
260
261     class Meta:
262         verbose_name = _('membership')
263         verbose_name_plural = _('memberships')
264
265     def __str__(self):
266         return str(self.user)
267
268     def save(self, *args, **kwargs):
269         super().save(*args, **kwargs)
270         self.update_contact()
271
272     def update_contact(self):
273         email = self.user.email
274         if not email:
275             return
276
277         Contact = apps.get_model('messaging', 'Contact')
278         if self.manual:
279             Contact.update(email, Level.MANUAL_MEMBER, datetime.combine(self.updated_at, datetime.min.time(), utc))
280         else:
281             Contact.reset(email)
282
283     @classmethod
284     def is_active_for(cls, user):
285         if user.is_anonymous:
286             return False
287         try:
288             membership = user.membership
289         except cls.DoesNotExist:
290             return False
291         if membership.manual:
292             return True
293         return Schedule.objects.filter(
294                 expires_at__gt=now(),
295                 membership__user=user,
296             ).exists()
297
298
299 class ReminderEmail(models.Model):
300     days_before = models.SmallIntegerField(_('days before'))
301     subject = models.CharField(_('subject'), max_length=1024)
302     body = models.TextField(_('body'))
303
304     class Meta:
305         verbose_name = _('reminder email')
306         verbose_name_plural = _('reminder emails')
307         ordering = ['days_before']
308
309     def __str__(self):
310         if self.days_before >= 0:
311             return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
312         else:
313             return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
314
315
316 class Ambassador(models.Model):
317     name = models.CharField(_('name'), max_length=255)
318     photo = models.ImageField(_('photo'), blank=True)
319     text = models.CharField(_('text'), max_length=1024)
320
321     class Meta:
322         verbose_name = _('ambassador')
323         verbose_name_plural = _('ambassadors')
324         ordering = ['name']
325     
326     def __str__(self):
327         return self.name
328
329         
330 ########
331 #      #
332 # PayU #
333 #      #
334 ########
335
336 class PayUOrder(payu_models.Order):
337     schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
338
339     def get_amount(self):
340         return self.schedule.amount
341
342     def get_buyer(self):
343         return {
344             "email": self.schedule.email,
345             "language": get_language(),
346         }
347
348     def get_description(self):
349         return 'Wolne Lektury'
350
351     def is_recurring(self):
352         return self.schedule.get_payment_method().is_recurring
353
354     def get_card_token(self):
355         return self.schedule.payucardtoken_set.order_by('-created_at').first()
356
357     def get_notify_url(self):
358         return "https://{}{}".format(
359             Site.objects.get_current().domain,
360             reverse('club_payu_notify', args=[self.pk]))
361
362     def get_thanks_url(self):
363         return self.schedule.get_thanks_url()
364
365     def status_updated(self):
366         if self.status == 'COMPLETED':
367             self.schedule.set_payed()
368
369         elif self.status == 'CANCELED' or self.status.startswith('ERR-'):
370             if self.is_recurring() and self.schedule.expires_at:
371                 self.schedule.send_email_failed_recurring()
372             
373         self.report_activity()
374
375     @property
376     def updated_at(self):
377         try:
378             return self.notification_set.all().order_by('-received_at')[0].received_at
379         except IndexError:
380             return None
381     
382     def report_activity(self):
383         if self.status not in ['COMPLETED', 'CANCELED', 'REJECTED']:
384             return
385
386         if self.status != 'COMPLETED':
387             name = settings.CIVICRM_ACTIVITIES['Failed contribution']
388         elif self.is_recurring():
389             name = settings.CIVICRM_ACTIVITIES['Recurring contribution']
390         else:
391             name = settings.CIVICRM_ACTIVITIES['Contribution']
392
393         report_activity.delay(
394             self.schedule.email,
395             self.schedule.key,
396             f'payu:{self.id}',
397             name,
398             self.updated_at,
399             {
400                 'kwota': self.schedule.amount,
401             }
402         )            
403
404     @classmethod
405     def send_receipt(cls, email, year, resend=False):
406         Contact = apps.get_model('messaging', 'Contact')
407         Funding = apps.get_model('funding', 'Funding')
408         BillingAgreement = apps.get_model('paypal', 'BillingAgreement')
409         DirectDebit = apps.get_model('pz', 'DirectDebit')
410         Payment = apps.get_model('pz', 'Payment')
411
412         payments = []
413
414         optout = None
415         try:
416             contact = Contact.objects.get(email=email)
417         except Contact.DoesNotExist:
418             funding = Funding.objects.filter(
419                 email=email,
420                 completed_at__year=year,
421                 notifications=True).order_by('completed_at').first()
422             if funding is None:
423                 print('no notifications')
424                 if not DirectDebit.objects.filter(email=email, optout=False).exists():
425                     return
426             else:
427                 optout = funding.wl_optout_url()
428         else:
429             if contact.level == Level.OPT_OUT:
430                 print('opt-out')
431                 return
432             optout = contact.wl_optout_url()
433
434         qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
435         for order in qs:
436             payments.append({
437                 'timestamp': order.completed_at,
438                 'amount': order.get_amount(),
439             })
440
441         for ba in BillingAgreement.objects.filter(schedule__email=email):
442             payments.extend(ba.get_donations(year))
443
444         fundings = Funding.objects.filter(
445             email=email,
446             completed_at__year=year
447         ).order_by('completed_at')
448         for funding in fundings:
449             payments.append({
450                 'timestamp': funding.completed_at,
451                 'amount': funding.amount,
452             })
453
454         for pa in Payment.objects.filter(
455                 debit__email=email,
456                 realised=True,
457                 is_dd=True,
458                 booking_date__year=year
459         ):
460             payments.append({
461                 'timestamp': datetime(pa.booking_date.year, pa.booking_date.month, pa.booking_date.day, tzinfo=utc),
462                 'amount': Decimal(str(pa.debit.amount) + '.00')
463             })
464
465     
466         if not payments: return
467
468         payments.sort(key=lambda x: x['timestamp'])
469
470         ctx = {
471             "email": email,
472             "year": year,
473             "next_year": year + 1,
474             "total": sum(x['amount'] for x in payments),
475             "payments": payments,
476             "optout": optout,
477             "resend": resend,
478         }
479         temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
480         temp.close()
481         render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
482             "wl.eps": os.path.join(settings.STATIC_ROOT, "img/wl.eps"),
483             })
484
485         message = EmailMessage(
486                 'Odlicz darowiznę na Wolne Lektury od podatku',
487                 template.loader.render_to_string('club/receipt_email.txt', ctx),
488                 settings.CLUB_CONTACT_EMAIL, [email]
489             )
490         with open(temp.name, 'rb') as f:
491             message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
492         message.send()
493         os.unlink(f.name)
494
495
496 class PayUCardToken(payu_models.CardToken):
497     schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
498
499
500 class PayUNotification(payu_models.Notification):
501     order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')