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 def paypal_enabled(self):
79 print("ENABLED?", settings.PAYPAL_ENABLED)
80 return settings.PAYPAL_ENABLED
83 class SingleAmount(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)
92 class MonthlyAmount(models.Model):
93 club = models.ForeignKey(Club, models.CASCADE)
94 amount = models.IntegerField()
95 description = models.TextField(blank=True)
96 wide = models.BooleanField(default=False)
102 class Consent(models.Model):
103 order = models.IntegerField()
104 active = models.BooleanField(default=True)
105 text = models.CharField(max_length=2048)
106 required = models.BooleanField()
115 class Schedule(models.Model):
116 """ Represents someone taking up a plan. """
117 key = models.CharField(_('key'), max_length=255, unique=True)
118 email = models.EmailField(_('email'))
119 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.SET_NULL)
120 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
121 method = models.CharField(_('method'), max_length=32, choices=[
122 (m.slug, m.name) for m in methods
124 monthly = models.BooleanField(_('monthly'), default=True)
125 yearly = models.BooleanField(_('yearly'), default=False)
127 source = models.CharField(_('source'), max_length=255, blank=True)
129 is_cancelled = models.BooleanField(_('cancelled'), default=False)
130 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
131 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
132 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
133 email_sent = models.BooleanField(default=False)
135 first_name = models.CharField(max_length=255, blank=True)
136 last_name = models.CharField(max_length=255, blank=True)
137 phone = models.CharField(max_length=255, blank=True)
138 postal = models.CharField(max_length=255, blank=True)
139 postal_code = models.CharField(max_length=255, blank=True)
140 postal_town = models.CharField(max_length=255, blank=True)
141 postal_country = CountryField(default='PL', blank=True)
143 consent = models.ManyToManyField(Consent)
146 verbose_name = _('schedule')
147 verbose_name_plural = _('schedules')
152 def save(self, *args, **kwargs):
154 self.key = get_random_hash(self.email)
155 super(Schedule, self).save(*args, **kwargs)
156 self.update_contact()
158 def get_description(self):
159 club = Club.objects.first()
160 return club.get_description_for_amount(self.amount, self.monthly)
162 def initiate_payment(self, request):
163 return self.get_payment_method().initiate(request, self)
165 def pay(self, request):
166 return self.get_payment_method().pay(request, self)
168 def get_absolute_url(self):
169 return reverse('club_schedule', args=[self.key])
171 def get_thanks_url(self):
172 return reverse('club_thanks', args=[self.key])
174 def get_payment_method(self):
175 return [m for m in methods if m.slug == self.method][0]
177 def get_payment_methods(self):
178 for method in methods:
179 if (self.monthly or self.yearly) and method.is_recurring:
181 elif not (self.monthly or self.yearly) and method.is_onetime:
184 def is_expired(self):
185 return self.expires_at is not None and self.expires_at <= now()
188 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
190 def is_recurring(self):
191 return self.monthly or self.yearly
194 since = self.expires_at
196 if since is None or since < n:
198 new_exp = self.get_next_installment(since)
199 if self.payed_at is None:
201 if self.expires_at is None or self.expires_at < new_exp:
202 self.expires_at = new_exp
205 if not self.email_sent:
208 def get_next_installment(self, date):
210 return utils.add_year(date)
212 return utils.add_month(date)
213 club = Club.objects.first()
214 if club is not None and self.amount >= club.min_for_year:
215 return utils.add_year(date)
216 return utils.add_month(date)
218 def get_other_active_recurring(self):
219 schedules = type(self).objects.exclude(
220 monthly=False, yearly=False
221 ).filter(is_cancelled=False, expires_at__gt=now()).exclude(pk=self.pk)
222 mine_q = models.Q(email=self.email)
223 if self.membership is not None:
224 mine_q |= models.Q(membership__user=self.membership.user)
225 schedules = schedules.filter(mine_q)
226 return schedules.order_by('-expires_at').first()
228 def send_email(self):
229 ctx = {'schedule': self}
231 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
232 template.loader.render_to_string('club/email/thanks.txt', ctx),
233 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
234 self.email_sent = True
237 def send_email_failed_recurring(self):
240 'other': self.get_other_active_recurring(),
243 'Darowizna na Wolne Lektury — problem z płatnością',
244 template.loader.render_to_string('club/email/failed_recurring.txt', ctx),
245 settings.CONTACT_EMAIL, [self.email], fail_silently=False
248 def update_contact(self):
249 Contact = apps.get_model('messaging', 'Contact')
250 if not self.payed_at:
252 since = self.started_at
254 since = self.payed_at
255 if self.is_recurring():
256 level = Level.RECURRING
259 Contact.update(self.email, level, since, self.expires_at)
265 class Membership(models.Model):
266 """ Represents a user being recognized as a member of the club. """
267 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
268 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
269 name = models.CharField(_('name'), max_length=255, blank=True)
270 manual = models.BooleanField(_('manual'), default=False)
271 notes = models.CharField(_('notes'), max_length=2048, blank=True)
272 updated_at = models.DateField(_('updated at'), auto_now=True, blank=True)
275 verbose_name = _('membership')
276 verbose_name_plural = _('memberships')
279 return str(self.user)
281 def save(self, *args, **kwargs):
282 super().save(*args, **kwargs)
283 self.update_contact()
285 def update_contact(self):
286 email = self.user.email
290 Contact = apps.get_model('messaging', 'Contact')
292 Contact.update(email, Level.MANUAL_MEMBER, datetime.combine(self.updated_at, datetime.min.time(), utc))
297 def is_active_for(cls, user):
298 if user.is_anonymous:
301 membership = user.membership
302 except cls.DoesNotExist:
304 if membership.manual:
306 return Schedule.objects.filter(
307 expires_at__gt=now(),
308 membership__user=user,
312 class ReminderEmail(models.Model):
313 days_before = models.SmallIntegerField(_('days before'))
314 subject = models.CharField(_('subject'), max_length=1024)
315 body = models.TextField(_('body'))
318 verbose_name = _('reminder email')
319 verbose_name_plural = _('reminder emails')
320 ordering = ['days_before']
323 if self.days_before >= 0:
324 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
326 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
329 class Ambassador(models.Model):
330 name = models.CharField(_('name'), max_length=255)
331 photo = models.ImageField(_('photo'), blank=True)
332 text = models.CharField(_('text'), max_length=1024)
335 verbose_name = _('ambassador')
336 verbose_name_plural = _('ambassadors')
349 class PayUOrder(payu_models.Order):
350 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
352 def get_amount(self):
353 return self.schedule.amount
357 "email": self.schedule.email,
358 "language": get_language(),
361 def get_description(self):
362 return 'Wolne Lektury'
364 def is_recurring(self):
365 return self.schedule.get_payment_method().is_recurring
367 def get_card_token(self):
368 return self.schedule.payucardtoken_set.order_by('-created_at').first()
370 def get_notify_url(self):
371 return "https://{}{}".format(
372 Site.objects.get_current().domain,
373 reverse('club_payu_notify', args=[self.pk]))
375 def get_thanks_url(self):
376 return self.schedule.get_thanks_url()
378 def status_updated(self):
379 if self.status == 'COMPLETED':
380 self.schedule.set_payed()
382 elif self.status == 'CANCELED' or self.status.startswith('ERR-'):
383 if self.is_recurring() and self.schedule.expires_at:
384 self.schedule.send_email_failed_recurring()
386 self.report_activity()
389 def updated_at(self):
391 return self.notification_set.all().order_by('-received_at')[0].received_at
395 def report_activity(self):
396 if self.status not in ['COMPLETED', 'CANCELED', 'REJECTED']:
399 if self.status != 'COMPLETED':
400 name = settings.CIVICRM_ACTIVITIES['Failed contribution']
401 elif self.is_recurring():
402 name = settings.CIVICRM_ACTIVITIES['Recurring contribution']
404 name = settings.CIVICRM_ACTIVITIES['Contribution']
406 report_activity.delay(
413 'kwota': self.schedule.amount,
418 def send_receipt(cls, email, year, resend=False):
419 Contact = apps.get_model('messaging', 'Contact')
420 Funding = apps.get_model('funding', 'Funding')
421 BillingAgreement = apps.get_model('paypal', 'BillingAgreement')
422 DirectDebit = apps.get_model('pz', 'DirectDebit')
423 Payment = apps.get_model('pz', 'Payment')
429 contact = Contact.objects.get(email=email)
430 except Contact.DoesNotExist:
431 funding = Funding.objects.filter(
433 completed_at__year=year,
434 notifications=True).order_by('completed_at').first()
436 print('no notifications')
437 if not DirectDebit.objects.filter(email=email, optout=False).exists():
440 optout = funding.wl_optout_url()
442 if contact.level == Level.OPT_OUT:
445 optout = contact.wl_optout_url()
447 qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
450 'timestamp': order.completed_at,
451 'amount': order.get_amount(),
454 for ba in BillingAgreement.objects.filter(schedule__email=email):
455 payments.extend(ba.get_donations(year))
457 fundings = Funding.objects.filter(
459 completed_at__year=year
460 ).order_by('completed_at')
461 for funding in fundings:
463 'timestamp': funding.completed_at,
464 'amount': funding.amount,
467 for pa in Payment.objects.filter(
471 booking_date__year=year
474 'timestamp': datetime(pa.booking_date.year, pa.booking_date.month, pa.booking_date.day, tzinfo=utc),
475 'amount': Decimal(str(pa.debit.amount) + '.00')
479 if not payments: return
481 payments.sort(key=lambda x: x['timestamp'])
486 "next_year": year + 1,
487 "total": sum(x['amount'] for x in payments),
488 "payments": payments,
492 temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
494 render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
495 "wl.eps": os.path.join(settings.STATIC_ROOT, "img/wl.eps"),
498 message = EmailMessage(
499 'Odlicz darowiznę na Wolne Lektury od podatku',
500 template.loader.render_to_string('club/receipt_email.txt', ctx),
501 settings.CLUB_CONTACT_EMAIL, [email]
503 with open(temp.name, 'rb') as f:
504 message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
509 class PayUCardToken(payu_models.CardToken):
510 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
513 class PayUNotification(payu_models.Notification):
514 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')