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