b8ec095c29003221dc7355d87621effa92287662
[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 catalogue.utils import get_random_hash
17 from messaging.states import Level
18 from reporting.utils import render_to_pdf
19 from .payment_methods import recurring_payment_method, single_payment_method
20 from .payu import models as payu_models
21 from . import utils
22
23
24 class Club(models.Model):
25     min_amount = models.IntegerField(_('minimum amount'))
26     min_for_year = models.IntegerField(_('minimum amount for year'))
27     single_amounts = models.CharField(_('proposed amounts for single payment'), max_length=255)
28     default_single_amount = models.IntegerField(_('default single amount'))
29     monthly_amounts = models.CharField(_('proposed amounts for monthly payments'), max_length=255)
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     def proposed_single_amounts(self):
40         return [int(x) for x in self.single_amounts.split(',')]
41
42     def proposed_monthly_amounts(self):
43         return [int(x) for x in self.monthly_amounts.split(',')]
44
45
46 class Schedule(models.Model):
47     """ Represents someone taking up a plan. """
48     key = models.CharField(_('key'), max_length=255, unique=True)
49     email = models.EmailField(_('email'))
50     membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.PROTECT)
51     amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
52     monthly = models.BooleanField(_('monthly'), default=True)
53     yearly = models.BooleanField(_('yearly'), default=False)
54     
55     is_cancelled = models.BooleanField(_('cancelled'), default=False)
56     payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
57     started_at = models.DateTimeField(_('started at'), auto_now_add=True)
58     expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
59     email_sent = models.BooleanField(default=False)
60
61     class Meta:
62         verbose_name = _('schedule')
63         verbose_name_plural = _('schedules')
64
65     def __str__(self):
66         return self.key
67
68     def save(self, *args, **kwargs):
69         if not self.key:
70             self.key = get_random_hash(self.email)
71         super(Schedule, self).save(*args, **kwargs)
72         self.update_contact()
73
74     def initiate_payment(self, request):
75         return self.get_payment_method().initiate(request, self)
76
77     def pay(self, request):
78         return self.get_payment_method().pay(request, self)
79
80     def get_absolute_url(self):
81         return reverse('club_schedule', args=[self.key])
82
83     def get_thanks_url(self):
84         return reverse('club_thanks', args=[self.key])
85
86     def get_payment_method(self):
87         return recurring_payment_method if self.monthly or self.yearly else single_payment_method
88
89     def is_expired(self):
90         return self.expires_at is not None and self.expires_at <= now()
91
92     def is_active(self):
93         return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
94
95     def is_recurring(self):
96         return self.monthly or self.yearly
97
98     def get_next_installment(self, date):
99         if self.yearly:
100             return utils.add_year(date)
101         if self.monthly:
102             return utils.add_month(date)
103         club = Club.objects.first()
104         if club is not None and self.amount >= club.min_for_year:
105             return utils.add_year(date)
106         return utils.add_month(date)
107
108     def send_email(self):
109         ctx = {'schedule': self}
110         send_mail(
111             template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
112             template.loader.render_to_string('club/email/thanks.txt', ctx),
113             settings.CONTACT_EMAIL, [self.email], fail_silently=False)
114         self.email_sent = True
115         self.save()
116
117     def update_contact(self):
118         Contact = apps.get_model('messaging', 'Contact')
119         if not self.payed_at:
120             level = Level.TRIED
121             since = self.started_at
122         else:
123             since = self.payed_at
124             if self.is_recurring():
125                 level = Level.RECURRING
126             else:
127                 level = Level.SINGLE
128         Contact.update(self.email, level, since, self.expires_at)
129
130
131 class Membership(models.Model):
132     """ Represents a user being recognized as a member of the club. """
133     user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
134     created_at = models.DateTimeField(_('created at'), auto_now_add=True)
135     name = models.CharField(_('name'), max_length=255, blank=True)
136     manual = models.BooleanField(_('manual'), default=False)
137     notes = models.CharField(_('notes'), max_length=2048, blank=True)
138     updated_at = models.DateField(_('updated at'), auto_now=True, blank=True)
139
140     class Meta:
141         verbose_name = _('membership')
142         verbose_name_plural = _('memberships')
143
144     def __str__(self):
145         return str(self.user)
146
147     def save(self, *args, **kwargs):
148         super().save(*args, **kwargs)
149         self.update_contact()
150
151     def update_contact(self):
152         email = self.user.email
153         if not email:
154             return
155
156         Contact = apps.get_model('messaging', 'Contact')
157         if self.manual:
158             Contact.update(email, Level.MANUAL_MEMBER, self.updated_at)
159         else:
160             Contact.reset(email)
161
162     @classmethod
163     def is_active_for(cls, user):
164         if user.is_anonymous:
165             return False
166         try:
167             membership = user.membership
168         except cls.DoesNotExist:
169             return False
170         if membership.manual:
171             return True
172         return Schedule.objects.filter(
173                 expires_at__gt=now(),
174                 membership__user=user,
175             ).exists()
176
177
178 class ReminderEmail(models.Model):
179     days_before = models.SmallIntegerField(_('days before'))
180     subject = models.CharField(_('subject'), max_length=1024)
181     body = models.TextField(_('body'))
182
183     class Meta:
184         verbose_name = _('reminder email')
185         verbose_name_plural = _('reminder emails')
186         ordering = ['days_before']
187
188     def __str__(self):
189         if self.days_before >= 0:
190             return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
191         else:
192             return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
193
194
195 class Ambassador(models.Model):
196     name = models.CharField(_('name'), max_length=255)
197     photo = models.ImageField(_('photo'), blank=True)
198     text = models.CharField(_('text'), max_length=1024)
199
200     class Meta:
201         verbose_name = _('ambassador')
202         verbose_name_plural = _('ambassadors')
203         ordering = ['name']
204     
205     def __str__(self):
206         return self.name
207
208         
209 ########
210 #      #
211 # PayU #
212 #      #
213 ########
214
215 class PayUOrder(payu_models.Order):
216     schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
217
218     def get_amount(self):
219         return self.schedule.amount
220
221     def get_buyer(self):
222         return {
223             "email": self.schedule.email,
224             "language": get_language(),
225         }
226
227     def get_continue_url(self):
228         return "https://{}{}".format(
229             Site.objects.get_current().domain,
230             self.schedule.get_thanks_url())
231
232     def get_description(self):
233         return ugettext('Towarzystwo Przyjaciół Wolnych Lektur')
234
235     def is_recurring(self):
236         return self.schedule.get_payment_method().is_recurring
237
238     def get_card_token(self):
239         return self.schedule.payucardtoken_set.order_by('-created_at').first()
240
241     def get_notify_url(self):
242         return "https://{}{}".format(
243             Site.objects.get_current().domain,
244             reverse('club_payu_notify', args=[self.pk]))
245
246     def status_updated(self):
247         if self.status == 'COMPLETED':
248             since = self.schedule.expires_at
249             n = now()
250             if since is None or since < n:
251                 since = n
252             new_exp = self.schedule.get_next_installment(since)
253             if self.schedule.payed_at is None:
254                 self.schedule.payed_at = n
255             if self.schedule.expires_at is None or self.schedule.expires_at < new_exp:
256                 self.schedule.expires_at = new_exp
257                 self.schedule.save()
258
259             if not self.schedule.email_sent:
260                 self.schedule.send_email()
261
262     @classmethod
263     def send_receipt(cls, email, year):
264         Contact = apps.get_model('messaging', 'Contact')
265         Funding = apps.get_model('funding', 'Funding')
266         payments = []
267
268         try:
269             contact = Contact.objects.get(email=email)
270         except Contact.DoesNotExist:
271             funding = Funding.objects.filter(
272                 email=email,
273                 payed_at__year=year,
274                 notifications=True).order_by('payed_at').first()
275             if funding is None:
276                 print('no notifications')
277                 return
278             optout = funding.wl_optout_url()
279         else:
280             if contact.level == Level.OPT_OUT:
281                 print('opt-out')
282                 return
283             optout = contact.wl_optout_url()
284
285         qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
286         for order in qs:
287             payments.append({
288                 'timestamp': order.completed_at,
289                 'amount': order.get_amount(),
290             })
291
292         fundings = Funding.objects.filter(
293             email=email,
294             payed_at__year=year
295         ).order_by('payed_at')
296         for funding in fundings:
297             payments.append({
298                 'timestamp': funding.payed_at,
299                 'amount': funding.amount,
300             })
301
302         if not payments: return
303
304         payments.sort(key=lambda x: x['timestamp'])
305
306         ctx = {
307             "email": email,
308             "year": year,
309             "next_year": year + 1,
310             "total": sum(x['amount'] for x in payments),
311             "payments": payments,
312             "optout": optout,
313         }
314         temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
315         temp.close()
316         render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
317             "fnp.eps": os.path.join(settings.STATIC_ROOT, "img/fnp.eps"),
318             })
319
320         message = EmailMessage(
321                 f'Odlicz od podatku swoje darowizny przekazane dla Wolnych Lektur',
322                 template.loader.render_to_string('club/receipt_email.txt', ctx),
323                 settings.CONTACT_EMAIL, [email]
324             )
325         with open(temp.name, 'rb') as f:
326             message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
327         message.send()
328         os.unlink(f.name)
329
330
331 class PayUCardToken(payu_models.CardToken):
332     schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
333
334
335 class PayUNotification(payu_models.Notification):
336     order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')
337
338