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