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