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