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