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