1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from datetime import datetime, timedelta
5 from decimal import Decimal
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
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'))
34 verbose_name = _('club')
35 verbose_name_plural = _('clubs')
40 def get_amounts(self):
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):
48 # Do we have space for xl?
53 p.box_variant = 'card'
57 p.box_variant = 'card'
59 amounts[i-1].box_variant = 'bar'
63 p.box_variant = 'half'
69 c[f'{tag}_wide_spot'] = wide_spot
74 class SingleAmount(models.Model):
75 club = models.ForeignKey(Club, models.CASCADE)
76 amount = models.IntegerField()
77 description = models.TextField(blank=True)
78 wide = models.BooleanField(default=False)
83 class MonthlyAmount(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)
93 class Consent(models.Model):
94 order = models.IntegerField()
95 active = models.BooleanField(default=True)
96 text = models.CharField(max_length=2048)
97 required = models.BooleanField()
106 class Schedule(models.Model):
107 """ Represents someone taking up a plan. """
108 key = models.CharField(_('key'), max_length=255, unique=True)
109 email = models.EmailField(_('email'))
110 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.SET_NULL)
111 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
112 method = models.CharField(_('method'), max_length=32, choices=[
113 (m.slug, m.name) for m in methods
115 monthly = models.BooleanField(_('monthly'), default=True)
116 yearly = models.BooleanField(_('yearly'), default=False)
118 source = models.CharField(_('source'), max_length=255, blank=True)
120 is_cancelled = models.BooleanField(_('cancelled'), default=False)
121 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
122 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
123 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
124 email_sent = models.BooleanField(default=False)
126 first_name = models.CharField(max_length=255, blank=True)
127 last_name = models.CharField(max_length=255, blank=True)
128 phone = models.CharField(max_length=255, blank=True)
129 postal = models.CharField(max_length=255, blank=True)
130 postal_code = models.CharField(max_length=255, blank=True)
131 postal_town = models.CharField(max_length=255, blank=True)
132 postal_country = CountryField(default='PL', blank=True)
134 consent = models.ManyToManyField(Consent)
137 verbose_name = _('schedule')
138 verbose_name_plural = _('schedules')
143 def save(self, *args, **kwargs):
145 self.key = get_random_hash(self.email)
146 super(Schedule, self).save(*args, **kwargs)
147 self.update_contact()
149 def initiate_payment(self, request):
150 return self.get_payment_method().initiate(request, self)
152 def pay(self, request):
153 return self.get_payment_method().pay(request, self)
155 def get_absolute_url(self):
156 return reverse('club_schedule', args=[self.key])
158 def get_thanks_url(self):
159 return reverse('club_thanks', args=[self.key])
161 def get_payment_method(self):
162 return [m for m in methods if m.slug == self.method][0]
164 def get_payment_methods(self):
165 for method in methods:
166 if (self.monthly or self.yearly) and method.is_recurring:
168 elif not (self.monthly or self.yearly) and method.is_onetime:
171 def is_expired(self):
172 return self.expires_at is not None and self.expires_at <= now()
175 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
177 def is_recurring(self):
178 return self.monthly or self.yearly
181 since = self.expires_at
183 if since is None or since < n:
185 new_exp = self.get_next_installment(since)
186 if self.payed_at is None:
188 if self.expires_at is None or self.expires_at < new_exp:
189 self.expires_at = new_exp
192 if not self.email_sent:
195 def get_next_installment(self, date):
197 return utils.add_year(date)
199 return utils.add_month(date)
200 club = Club.objects.first()
201 if club is not None and self.amount >= club.min_for_year:
202 return utils.add_year(date)
203 return utils.add_month(date)
205 def get_other_active_recurring(self):
206 schedules = type(self).objects.exclude(
207 monthly=False, yearly=False
208 ).filter(is_cancelled=False, expires_at__gt=now()).exclude(pk=self.pk)
209 mine_q = models.Q(email=self.email)
210 if self.membership is not None:
211 mine_q |= models.Q(membership__user=self.membership.user)
212 schedules = schedules.filter(mine_q)
213 return schedules.order_by('-expires_at').first()
215 def send_email(self):
216 ctx = {'schedule': self}
218 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
219 template.loader.render_to_string('club/email/thanks.txt', ctx),
220 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
221 self.email_sent = True
224 def send_email_failed_recurring(self):
227 'other': self.get_other_active_recurring(),
230 'Darowizna na Wolne Lektury — problem z płatnością',
231 template.loader.render_to_string('club/email/failed_recurring.txt', ctx),
232 settings.CONTACT_EMAIL, [self.email], fail_silently=False
235 def update_contact(self):
236 Contact = apps.get_model('messaging', 'Contact')
237 if not self.payed_at:
239 since = self.started_at
241 since = self.payed_at
242 if self.is_recurring():
243 level = Level.RECURRING
246 Contact.update(self.email, level, since, self.expires_at)
252 class Membership(models.Model):
253 """ Represents a user being recognized as a member of the club. """
254 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
255 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
256 name = models.CharField(_('name'), max_length=255, blank=True)
257 manual = models.BooleanField(_('manual'), default=False)
258 notes = models.CharField(_('notes'), max_length=2048, blank=True)
259 updated_at = models.DateField(_('updated at'), auto_now=True, blank=True)
262 verbose_name = _('membership')
263 verbose_name_plural = _('memberships')
266 return str(self.user)
268 def save(self, *args, **kwargs):
269 super().save(*args, **kwargs)
270 self.update_contact()
272 def update_contact(self):
273 email = self.user.email
277 Contact = apps.get_model('messaging', 'Contact')
279 Contact.update(email, Level.MANUAL_MEMBER, datetime.combine(self.updated_at, datetime.min.time(), utc))
284 def is_active_for(cls, user):
285 if user.is_anonymous:
288 membership = user.membership
289 except cls.DoesNotExist:
291 if membership.manual:
293 return Schedule.objects.filter(
294 expires_at__gt=now(),
295 membership__user=user,
299 class ReminderEmail(models.Model):
300 days_before = models.SmallIntegerField(_('days before'))
301 subject = models.CharField(_('subject'), max_length=1024)
302 body = models.TextField(_('body'))
305 verbose_name = _('reminder email')
306 verbose_name_plural = _('reminder emails')
307 ordering = ['days_before']
310 if self.days_before >= 0:
311 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
313 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
316 class Ambassador(models.Model):
317 name = models.CharField(_('name'), max_length=255)
318 photo = models.ImageField(_('photo'), blank=True)
319 text = models.CharField(_('text'), max_length=1024)
322 verbose_name = _('ambassador')
323 verbose_name_plural = _('ambassadors')
336 class PayUOrder(payu_models.Order):
337 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
339 def get_amount(self):
340 return self.schedule.amount
344 "email": self.schedule.email,
345 "language": get_language(),
348 def get_description(self):
349 return 'Wolne Lektury'
351 def is_recurring(self):
352 return self.schedule.get_payment_method().is_recurring
354 def get_card_token(self):
355 return self.schedule.payucardtoken_set.order_by('-created_at').first()
357 def get_notify_url(self):
358 return "https://{}{}".format(
359 Site.objects.get_current().domain,
360 reverse('club_payu_notify', args=[self.pk]))
362 def get_thanks_url(self):
363 return self.schedule.get_thanks_url()
365 def status_updated(self):
366 if self.status == 'COMPLETED':
367 self.schedule.set_payed()
369 elif self.status == 'CANCELED' or self.status.startswith('ERR-'):
370 if self.is_recurring() and self.schedule.expires_at:
371 self.schedule.send_email_failed_recurring()
373 self.report_activity()
376 def updated_at(self):
378 return self.notification_set.all().order_by('-received_at')[0].received_at
382 def report_activity(self):
383 if self.status not in ['COMPLETED', 'CANCELED', 'REJECTED']:
386 if self.status != 'COMPLETED':
387 name = settings.CIVICRM_ACTIVITIES['Failed contribution']
388 elif self.is_recurring():
389 name = settings.CIVICRM_ACTIVITIES['Recurring contribution']
391 name = settings.CIVICRM_ACTIVITIES['Contribution']
393 report_activity.delay(
400 'kwota': self.schedule.amount,
405 def send_receipt(cls, email, year, resend=False):
406 Contact = apps.get_model('messaging', 'Contact')
407 Funding = apps.get_model('funding', 'Funding')
408 BillingAgreement = apps.get_model('paypal', 'BillingAgreement')
409 DirectDebit = apps.get_model('pz', 'DirectDebit')
410 Payment = apps.get_model('pz', 'Payment')
416 contact = Contact.objects.get(email=email)
417 except Contact.DoesNotExist:
418 funding = Funding.objects.filter(
420 completed_at__year=year,
421 notifications=True).order_by('completed_at').first()
423 print('no notifications')
424 if not DirectDebit.objects.filter(email=email, optout=False).exists():
427 optout = funding.wl_optout_url()
429 if contact.level == Level.OPT_OUT:
432 optout = contact.wl_optout_url()
434 qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
437 'timestamp': order.completed_at,
438 'amount': order.get_amount(),
441 for ba in BillingAgreement.objects.filter(schedule__email=email):
442 payments.extend(ba.get_donations(year))
444 fundings = Funding.objects.filter(
446 completed_at__year=year
447 ).order_by('completed_at')
448 for funding in fundings:
450 'timestamp': funding.completed_at,
451 'amount': funding.amount,
454 for pa in Payment.objects.filter(
458 booking_date__year=year
461 'timestamp': datetime(pa.booking_date.year, pa.booking_date.month, pa.booking_date.day, tzinfo=utc),
462 'amount': Decimal(str(pa.debit.amount) + '.00')
466 if not payments: return
468 payments.sort(key=lambda x: x['timestamp'])
473 "next_year": year + 1,
474 "total": sum(x['amount'] for x in payments),
475 "payments": payments,
479 temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
481 render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
482 "wl.eps": os.path.join(settings.STATIC_ROOT, "img/wl.eps"),
485 message = EmailMessage(
486 'Odlicz darowiznę na Wolne Lektury od podatku',
487 template.loader.render_to_string('club/receipt_email.txt', ctx),
488 settings.CLUB_CONTACT_EMAIL, [email]
490 with open(temp.name, 'rb') as f:
491 message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
496 class PayUCardToken(payu_models.CardToken):
497 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
500 class PayUNotification(payu_models.Notification):
501 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')