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