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):
47 if p.description or p.wide:
51 amounts[i-1].narrow_wide = True
55 p.wide_not_wide = True
63 c[f'{tag}_wide_spot'] = wide_spot
68 class SingleAmount(models.Model):
69 club = models.ForeignKey(Club, models.CASCADE)
70 amount = models.IntegerField()
71 description = models.TextField(blank=True)
72 wide = models.BooleanField(default=False)
77 class MonthlyAmount(models.Model):
78 club = models.ForeignKey(Club, models.CASCADE)
79 amount = models.IntegerField()
80 description = models.TextField(blank=True)
81 wide = models.BooleanField(default=False)
87 class Consent(models.Model):
88 order = models.IntegerField()
89 active = models.BooleanField(default=True)
90 text = models.CharField(max_length=2048)
91 required = models.BooleanField()
100 class Schedule(models.Model):
101 """ Represents someone taking up a plan. """
102 key = models.CharField(_('key'), max_length=255, unique=True)
103 email = models.EmailField(_('email'))
104 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.SET_NULL)
105 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
106 method = models.CharField(_('method'), max_length=32, choices=[
107 (m.slug, m.name) for m in methods
109 monthly = models.BooleanField(_('monthly'), default=True)
110 yearly = models.BooleanField(_('yearly'), default=False)
112 source = models.CharField(_('source'), max_length=255, blank=True)
114 is_cancelled = models.BooleanField(_('cancelled'), default=False)
115 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
116 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
117 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
118 email_sent = models.BooleanField(default=False)
120 first_name = models.CharField(max_length=255, blank=True)
121 last_name = models.CharField(max_length=255, blank=True)
122 phone = models.CharField(max_length=255, blank=True)
123 postal = models.CharField(max_length=255, blank=True)
124 postal_code = models.CharField(max_length=255, blank=True)
125 postal_town = models.CharField(max_length=255, blank=True)
126 postal_country = CountryField(default='PL', blank=True)
128 consent = models.ManyToManyField(Consent)
131 verbose_name = _('schedule')
132 verbose_name_plural = _('schedules')
137 def save(self, *args, **kwargs):
139 self.key = get_random_hash(self.email)
140 super(Schedule, self).save(*args, **kwargs)
141 self.update_contact()
143 def initiate_payment(self, request):
144 return self.get_payment_method().initiate(request, self)
146 def pay(self, request):
147 return self.get_payment_method().pay(request, self)
149 def get_absolute_url(self):
150 return reverse('club_schedule', args=[self.key])
152 def get_thanks_url(self):
153 return reverse('club_thanks', args=[self.key])
155 def get_payment_method(self):
156 return [m for m in methods if m.slug == self.method][0]
158 def get_payment_methods(self):
159 for method in methods:
160 if (self.monthly or self.yearly) and method.is_recurring:
162 elif not (self.monthly or self.yearly) and method.is_onetime:
165 def is_expired(self):
166 return self.expires_at is not None and self.expires_at <= now()
169 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
171 def is_recurring(self):
172 return self.monthly or self.yearly
175 since = self.expires_at
177 if since is None or since < n:
179 new_exp = self.get_next_installment(since)
180 if self.payed_at is None:
182 if self.expires_at is None or self.expires_at < new_exp:
183 self.expires_at = new_exp
186 if not self.email_sent:
189 def get_next_installment(self, date):
191 return utils.add_year(date)
193 return utils.add_month(date)
194 club = Club.objects.first()
195 if club is not None and self.amount >= club.min_for_year:
196 return utils.add_year(date)
197 return utils.add_month(date)
199 def get_other_active_recurring(self):
200 schedules = type(self).objects.exclude(
201 monthly=False, yearly=False
202 ).filter(is_cancelled=False, expires_at__gt=now()).exclude(pk=self.pk)
203 mine_q = models.Q(email=self.email)
204 if self.membership is not None:
205 mine_q |= models.Q(membership__user=self.membership.user)
206 schedules = schedules.filter(mine_q)
207 return schedules.order_by('-expires_at').first()
209 def send_email(self):
210 ctx = {'schedule': self}
212 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
213 template.loader.render_to_string('club/email/thanks.txt', ctx),
214 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
215 self.email_sent = True
218 def send_email_failed_recurring(self):
221 'other': self.get_other_active_recurring(),
224 'Darowizna na Wolne Lektury — problem z płatnością',
225 template.loader.render_to_string('club/email/failed_recurring.txt', ctx),
226 settings.CONTACT_EMAIL, [self.email], fail_silently=False
229 def update_contact(self):
230 Contact = apps.get_model('messaging', 'Contact')
231 if not self.payed_at:
233 since = self.started_at
235 since = self.payed_at
236 if self.is_recurring():
237 level = Level.RECURRING
240 Contact.update(self.email, level, since, self.expires_at)
246 class Membership(models.Model):
247 """ Represents a user being recognized as a member of the club. """
248 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
249 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
250 name = models.CharField(_('name'), max_length=255, blank=True)
251 manual = models.BooleanField(_('manual'), default=False)
252 notes = models.CharField(_('notes'), max_length=2048, blank=True)
253 updated_at = models.DateField(_('updated at'), auto_now=True, blank=True)
256 verbose_name = _('membership')
257 verbose_name_plural = _('memberships')
260 return str(self.user)
262 def save(self, *args, **kwargs):
263 super().save(*args, **kwargs)
264 self.update_contact()
266 def update_contact(self):
267 email = self.user.email
271 Contact = apps.get_model('messaging', 'Contact')
273 Contact.update(email, Level.MANUAL_MEMBER, datetime.combine(self.updated_at, datetime.min.time(), utc))
278 def is_active_for(cls, user):
279 if user.is_anonymous:
282 membership = user.membership
283 except cls.DoesNotExist:
285 if membership.manual:
287 return Schedule.objects.filter(
288 expires_at__gt=now(),
289 membership__user=user,
293 class ReminderEmail(models.Model):
294 days_before = models.SmallIntegerField(_('days before'))
295 subject = models.CharField(_('subject'), max_length=1024)
296 body = models.TextField(_('body'))
299 verbose_name = _('reminder email')
300 verbose_name_plural = _('reminder emails')
301 ordering = ['days_before']
304 if self.days_before >= 0:
305 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
307 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
310 class Ambassador(models.Model):
311 name = models.CharField(_('name'), max_length=255)
312 photo = models.ImageField(_('photo'), blank=True)
313 text = models.CharField(_('text'), max_length=1024)
316 verbose_name = _('ambassador')
317 verbose_name_plural = _('ambassadors')
330 class PayUOrder(payu_models.Order):
331 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
333 def get_amount(self):
334 return self.schedule.amount
338 "email": self.schedule.email,
339 "language": get_language(),
342 def get_description(self):
343 return 'Wolne Lektury'
345 def is_recurring(self):
346 return self.schedule.get_payment_method().is_recurring
348 def get_card_token(self):
349 return self.schedule.payucardtoken_set.order_by('-created_at').first()
351 def get_notify_url(self):
352 return "https://{}{}".format(
353 Site.objects.get_current().domain,
354 reverse('club_payu_notify', args=[self.pk]))
356 def get_thanks_url(self):
357 return self.schedule.get_thanks_url()
359 def status_updated(self):
360 if self.status == 'COMPLETED':
361 self.schedule.set_payed()
363 elif self.status == 'CANCELED' or self.status.startswith('ERR-'):
364 if self.is_recurring() and self.schedule.expires_at:
365 self.schedule.send_email_failed_recurring()
367 self.report_activity()
370 def updated_at(self):
372 return self.notification_set.all().order_by('-received_at')[0].received_at
376 def report_activity(self):
377 if self.status not in ['COMPLETED', 'CANCELED', 'REJECTED']:
380 if self.status != 'COMPLETED':
381 name = settings.CIVICRM_ACTIVITIES['Failed contribution']
382 elif self.is_recurring():
383 name = settings.CIVICRM_ACTIVITIES['Recurring contribution']
385 name = settings.CIVICRM_ACTIVITIES['Contribution']
387 report_activity.delay(
394 'kwota': self.schedule.amount,
399 def send_receipt(cls, email, year, resend=False):
400 Contact = apps.get_model('messaging', 'Contact')
401 Funding = apps.get_model('funding', 'Funding')
402 BillingAgreement = apps.get_model('paypal', 'BillingAgreement')
403 DirectDebit = apps.get_model('pz', 'DirectDebit')
404 Payment = apps.get_model('pz', 'Payment')
410 contact = Contact.objects.get(email=email)
411 except Contact.DoesNotExist:
412 funding = Funding.objects.filter(
414 completed_at__year=year,
415 notifications=True).order_by('completed_at').first()
417 print('no notifications')
418 if not DirectDebit.objects.filter(email=email, optout=False).exists():
421 optout = funding.wl_optout_url()
423 if contact.level == Level.OPT_OUT:
426 optout = contact.wl_optout_url()
428 qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
431 'timestamp': order.completed_at,
432 'amount': order.get_amount(),
435 for ba in BillingAgreement.objects.filter(schedule__email=email):
436 payments.extend(ba.get_donations(year))
438 fundings = Funding.objects.filter(
440 completed_at__year=year
441 ).order_by('completed_at')
442 for funding in fundings:
444 'timestamp': funding.completed_at,
445 'amount': funding.amount,
448 for pa in Payment.objects.filter(
452 booking_date__year=year
455 'timestamp': datetime(pa.booking_date.year, pa.booking_date.month, pa.booking_date.day, tzinfo=utc),
456 'amount': Decimal(str(pa.debit.amount) + '.00')
460 if not payments: return
462 payments.sort(key=lambda x: x['timestamp'])
467 "next_year": year + 1,
468 "total": sum(x['amount'] for x in payments),
469 "payments": payments,
473 temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
475 render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
476 "wl.eps": os.path.join(settings.STATIC_ROOT, "img/wl.eps"),
479 message = EmailMessage(
480 'Odlicz darowiznę na Wolne Lektury od podatku',
481 template.loader.render_to_string('club/receipt_email.txt', ctx),
482 settings.CLUB_CONTACT_EMAIL, [email]
484 with open(temp.name, 'rb') as f:
485 message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
490 class PayUCardToken(payu_models.CardToken):
491 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
494 class PayUNotification(payu_models.Notification):
495 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')