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
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 ''
78 class SingleAmount(models.Model):
79 club = models.ForeignKey(Club, models.CASCADE)
80 amount = models.IntegerField()
81 description = models.TextField(blank=True)
82 wide = models.BooleanField(default=False)
87 class MonthlyAmount(models.Model):
88 club = models.ForeignKey(Club, models.CASCADE)
89 amount = models.IntegerField()
90 description = models.TextField(blank=True)
91 wide = models.BooleanField(default=False)
97 class Consent(models.Model):
98 order = models.IntegerField()
99 active = models.BooleanField(default=True)
100 text = models.CharField(max_length=2048)
101 required = models.BooleanField()
110 class Schedule(models.Model):
111 """ Represents someone taking up a plan. """
112 key = models.CharField(_('key'), max_length=255, unique=True)
113 email = models.EmailField(_('email'))
114 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.SET_NULL)
115 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
116 method = models.CharField(_('method'), max_length=32, choices=[
117 (m.slug, m.name) for m in methods
119 monthly = models.BooleanField(_('monthly'), default=True)
120 yearly = models.BooleanField(_('yearly'), default=False)
122 source = models.CharField(_('source'), max_length=255, blank=True)
124 is_cancelled = models.BooleanField(_('cancelled'), default=False)
125 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
126 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
127 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
128 email_sent = models.BooleanField(default=False)
130 first_name = models.CharField(max_length=255, blank=True)
131 last_name = models.CharField(max_length=255, blank=True)
132 phone = models.CharField(max_length=255, blank=True)
133 postal = models.CharField(max_length=255, blank=True)
134 postal_code = models.CharField(max_length=255, blank=True)
135 postal_town = models.CharField(max_length=255, blank=True)
136 postal_country = CountryField(default='PL', blank=True)
138 consent = models.ManyToManyField(Consent)
141 verbose_name = _('schedule')
142 verbose_name_plural = _('schedules')
147 def save(self, *args, **kwargs):
149 self.key = get_random_hash(self.email)
150 super(Schedule, self).save(*args, **kwargs)
151 self.update_contact()
153 def get_description(self):
154 club = Club.objects.first()
155 return club.get_description_for_amount(self.amount, self.monthly)
157 def initiate_payment(self, request):
158 return self.get_payment_method().initiate(request, self)
160 def pay(self, request):
161 return self.get_payment_method().pay(request, self)
163 def get_absolute_url(self):
164 return reverse('club_schedule', args=[self.key])
166 def get_thanks_url(self):
167 return reverse('club_thanks', args=[self.key])
169 def get_payment_method(self):
170 return [m for m in methods if m.slug == self.method][0]
172 def get_payment_methods(self):
173 for method in methods:
174 if (self.monthly or self.yearly) and method.is_recurring:
176 elif not (self.monthly or self.yearly) and method.is_onetime:
179 def is_expired(self):
180 return self.expires_at is not None and self.expires_at <= now()
183 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
185 def is_recurring(self):
186 return self.monthly or self.yearly
189 since = self.expires_at
191 if since is None or since < n:
193 new_exp = self.get_next_installment(since)
194 if self.payed_at is None:
196 if self.expires_at is None or self.expires_at < new_exp:
197 self.expires_at = new_exp
200 if not self.email_sent:
203 def get_next_installment(self, date):
205 return utils.add_year(date)
207 return utils.add_month(date)
208 club = Club.objects.first()
209 if club is not None and self.amount >= club.min_for_year:
210 return utils.add_year(date)
211 return utils.add_month(date)
213 def get_other_active_recurring(self):
214 schedules = type(self).objects.exclude(
215 monthly=False, yearly=False
216 ).filter(is_cancelled=False, expires_at__gt=now()).exclude(pk=self.pk)
217 mine_q = models.Q(email=self.email)
218 if self.membership is not None:
219 mine_q |= models.Q(membership__user=self.membership.user)
220 schedules = schedules.filter(mine_q)
221 return schedules.order_by('-expires_at').first()
223 def send_email(self):
224 ctx = {'schedule': self}
226 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
227 template.loader.render_to_string('club/email/thanks.txt', ctx),
228 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
229 self.email_sent = True
232 def send_email_failed_recurring(self):
235 'other': self.get_other_active_recurring(),
238 'Darowizna na Wolne Lektury — problem z płatnością',
239 template.loader.render_to_string('club/email/failed_recurring.txt', ctx),
240 settings.CONTACT_EMAIL, [self.email], fail_silently=False
243 def update_contact(self):
244 Contact = apps.get_model('messaging', 'Contact')
245 if not self.payed_at:
247 since = self.started_at
249 since = self.payed_at
250 if self.is_recurring():
251 level = Level.RECURRING
254 Contact.update(self.email, level, since, self.expires_at)
260 class Membership(models.Model):
261 """ Represents a user being recognized as a member of the club. """
262 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
263 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
264 name = models.CharField(_('name'), max_length=255, blank=True)
265 manual = models.BooleanField(_('manual'), default=False)
266 notes = models.CharField(_('notes'), max_length=2048, blank=True)
267 updated_at = models.DateField(_('updated at'), auto_now=True, blank=True)
270 verbose_name = _('membership')
271 verbose_name_plural = _('memberships')
274 return str(self.user)
276 def save(self, *args, **kwargs):
277 super().save(*args, **kwargs)
278 self.update_contact()
280 def update_contact(self):
281 email = self.user.email
285 Contact = apps.get_model('messaging', 'Contact')
287 Contact.update(email, Level.MANUAL_MEMBER, datetime.combine(self.updated_at, datetime.min.time(), utc))
292 def is_active_for(cls, user):
293 if user.is_anonymous:
296 membership = user.membership
297 except cls.DoesNotExist:
299 if membership.manual:
301 return Schedule.objects.filter(
302 expires_at__gt=now(),
303 membership__user=user,
307 class ReminderEmail(models.Model):
308 days_before = models.SmallIntegerField(_('days before'))
309 subject = models.CharField(_('subject'), max_length=1024)
310 body = models.TextField(_('body'))
313 verbose_name = _('reminder email')
314 verbose_name_plural = _('reminder emails')
315 ordering = ['days_before']
318 if self.days_before >= 0:
319 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
321 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
324 class Ambassador(models.Model):
325 name = models.CharField(_('name'), max_length=255)
326 photo = models.ImageField(_('photo'), blank=True)
327 text = models.CharField(_('text'), max_length=1024)
330 verbose_name = _('ambassador')
331 verbose_name_plural = _('ambassadors')
344 class PayUOrder(payu_models.Order):
345 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
347 def get_amount(self):
348 return self.schedule.amount
352 "email": self.schedule.email,
353 "language": get_language(),
356 def get_description(self):
357 return 'Wolne Lektury'
359 def is_recurring(self):
360 return self.schedule.get_payment_method().is_recurring
362 def get_card_token(self):
363 return self.schedule.payucardtoken_set.order_by('-created_at').first()
365 def get_notify_url(self):
366 return "https://{}{}".format(
367 Site.objects.get_current().domain,
368 reverse('club_payu_notify', args=[self.pk]))
370 def get_thanks_url(self):
371 return self.schedule.get_thanks_url()
373 def status_updated(self):
374 if self.status == 'COMPLETED':
375 self.schedule.set_payed()
377 elif self.status == 'CANCELED' or self.status.startswith('ERR-'):
378 if self.is_recurring() and self.schedule.expires_at:
379 self.schedule.send_email_failed_recurring()
381 self.report_activity()
384 def updated_at(self):
386 return self.notification_set.all().order_by('-received_at')[0].received_at
390 def report_activity(self):
391 if self.status not in ['COMPLETED', 'CANCELED', 'REJECTED']:
394 if self.status != 'COMPLETED':
395 name = settings.CIVICRM_ACTIVITIES['Failed contribution']
396 elif self.is_recurring():
397 name = settings.CIVICRM_ACTIVITIES['Recurring contribution']
399 name = settings.CIVICRM_ACTIVITIES['Contribution']
401 report_activity.delay(
408 'kwota': self.schedule.amount,
413 def send_receipt(cls, email, year, resend=False):
414 Contact = apps.get_model('messaging', 'Contact')
415 Funding = apps.get_model('funding', 'Funding')
416 BillingAgreement = apps.get_model('paypal', 'BillingAgreement')
417 DirectDebit = apps.get_model('pz', 'DirectDebit')
418 Payment = apps.get_model('pz', 'Payment')
424 contact = Contact.objects.get(email=email)
425 except Contact.DoesNotExist:
426 funding = Funding.objects.filter(
428 completed_at__year=year,
429 notifications=True).order_by('completed_at').first()
431 print('no notifications')
432 if not DirectDebit.objects.filter(email=email, optout=False).exists():
435 optout = funding.wl_optout_url()
437 if contact.level == Level.OPT_OUT:
440 optout = contact.wl_optout_url()
442 qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
445 'timestamp': order.completed_at,
446 'amount': order.get_amount(),
449 for ba in BillingAgreement.objects.filter(schedule__email=email):
450 payments.extend(ba.get_donations(year))
452 fundings = Funding.objects.filter(
454 completed_at__year=year
455 ).order_by('completed_at')
456 for funding in fundings:
458 'timestamp': funding.completed_at,
459 'amount': funding.amount,
462 for pa in Payment.objects.filter(
466 booking_date__year=year
469 'timestamp': datetime(pa.booking_date.year, pa.booking_date.month, pa.booking_date.day, tzinfo=utc),
470 'amount': Decimal(str(pa.debit.amount) + '.00')
474 if not payments: return
476 payments.sort(key=lambda x: x['timestamp'])
481 "next_year": year + 1,
482 "total": sum(x['amount'] for x in payments),
483 "payments": payments,
487 temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
489 render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
490 "wl.eps": os.path.join(settings.STATIC_ROOT, "img/wl.eps"),
493 message = EmailMessage(
494 'Odlicz darowiznę na Wolne Lektury od podatku',
495 template.loader.render_to_string('club/receipt_email.txt', ctx),
496 settings.CLUB_CONTACT_EMAIL, [email]
498 with open(temp.name, 'rb') as f:
499 message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
504 class PayUCardToken(payu_models.CardToken):
505 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
508 class PayUNotification(payu_models.Notification):
509 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')