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