1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. 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 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('minimalna kwota')
29 min_for_year = models.IntegerField('minimalna kwota na rok')
30 default_single_amount = models.IntegerField('domyślna kwota dla pojedynczej wpłaty')
31 default_monthly_amount = models.IntegerField('domyślna kwota dla miesięcznych wpłat')
34 verbose_name = 'towarzystwo'
35 verbose_name_plural = 'towarzystwa'
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('klucz', max_length=255, unique=True)
118 email = models.EmailField('e-mail')
119 membership = models.ForeignKey(
120 'Membership', verbose_name='członkostwo',
121 null=True, blank=True, on_delete=models.SET_NULL)
122 amount = models.DecimalField('kwota', max_digits=10, decimal_places=2)
123 method = models.CharField('metoda płatności', max_length=32, choices=[
124 (m.slug, m.name) for m in methods
126 monthly = models.BooleanField('miesięcznie', default=True)
127 yearly = models.BooleanField('rocznie', default=False)
129 source = models.CharField('źródło', max_length=255, blank=True)
131 is_cancelled = models.BooleanField('anulowany', default=False)
132 payed_at = models.DateTimeField('opłacona', null=True, blank=True)
133 started_at = models.DateTimeField('start', auto_now_add=True)
134 expires_at = models.DateTimeField('wygasa', null=True, blank=True)
135 email_sent = models.BooleanField(default=False)
137 first_name = models.CharField(max_length=255, blank=True)
138 last_name = models.CharField(max_length=255, blank=True)
139 phone = models.CharField(max_length=255, blank=True)
140 postal = models.CharField(max_length=255, blank=True)
141 postal_code = models.CharField(max_length=255, blank=True)
142 postal_town = models.CharField(max_length=255, blank=True)
143 postal_country = CountryField(default='PL', blank=True)
145 consent = models.ManyToManyField(Consent)
148 verbose_name = 'harmonogram'
149 verbose_name_plural = 'harmonogramy'
154 def save(self, *args, **kwargs):
156 self.key = get_random_hash(self.email)
157 super(Schedule, self).save(*args, **kwargs)
158 self.update_contact()
160 def get_description(self):
161 club = Club.objects.first()
162 return club.get_description_for_amount(self.amount, self.monthly)
164 def initiate_payment(self, request):
165 return self.get_payment_method().initiate(request, self)
167 def pay(self, request):
168 return self.get_payment_method().pay(request, self)
170 def get_absolute_url(self):
171 return reverse('club_schedule', args=[self.key])
173 def get_thanks_url(self):
174 return reverse('club_thanks', args=[self.key])
176 def get_payment_method(self):
177 return [m for m in methods if m.slug == self.method][0]
179 def get_payment_methods(self):
180 for method in methods:
181 if (self.monthly or self.yearly) and method.is_recurring:
183 elif not (self.monthly or self.yearly) and method.is_onetime:
186 def is_expired(self):
187 return self.expires_at is not None and self.expires_at <= now()
190 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
192 def is_recurring(self):
193 return self.monthly or self.yearly
196 since = self.expires_at
198 if since is None or since < n:
200 new_exp = self.get_next_installment(since)
201 if self.payed_at is None:
203 if self.expires_at is None or self.expires_at < new_exp:
204 self.expires_at = new_exp
207 if not self.email_sent:
210 def get_next_installment(self, date):
212 return utils.add_year(date)
214 return utils.add_month(date)
215 club = Club.objects.first()
216 if club is not None and self.amount >= club.min_for_year:
217 return utils.add_year(date)
218 return utils.add_month(date)
220 def get_other_active_recurring(self):
221 schedules = type(self).objects.exclude(
222 monthly=False, yearly=False
223 ).filter(is_cancelled=False, expires_at__gt=now()).exclude(pk=self.pk)
224 mine_q = models.Q(email=self.email)
225 if self.membership is not None:
226 mine_q |= models.Q(membership__user=self.membership.user)
227 schedules = schedules.filter(mine_q)
228 return schedules.order_by('-expires_at').first()
230 def send_email(self):
231 ctx = {'schedule': self}
233 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
234 template.loader.render_to_string('club/email/thanks.txt', ctx),
235 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
236 self.email_sent = True
239 def send_email_failed_recurring(self):
242 'other': self.get_other_active_recurring(),
245 'Darowizna na Wolne Lektury — problem z płatnością',
246 template.loader.render_to_string('club/email/failed_recurring.txt', ctx),
247 settings.CONTACT_EMAIL, [self.email], fail_silently=False
250 def update_contact(self):
251 Contact = apps.get_model('messaging', 'Contact')
252 if not self.payed_at:
254 since = self.started_at
256 since = self.payed_at
257 if self.is_recurring():
258 level = Level.RECURRING
261 Contact.update(self.email, level, since, self.expires_at)
267 class Membership(models.Model):
268 """ Represents a user being recognized as a member of the club. """
269 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name='użytkownik', on_delete=models.CASCADE)
270 created_at = models.DateTimeField('utworzone', auto_now_add=True)
271 name = models.CharField('nazwa', max_length=255, blank=True)
272 manual = models.BooleanField('ustawione ręcznie', default=False)
273 notes = models.CharField('notatki', max_length=2048, blank=True)
274 updated_at = models.DateField('aktualizacja', auto_now=True, blank=True)
277 verbose_name = 'członkostwo'
278 verbose_name_plural = 'członkostwa'
281 return str(self.user)
283 def save(self, *args, **kwargs):
284 super().save(*args, **kwargs)
285 self.update_contact()
287 def update_contact(self):
288 email = self.user.email
292 Contact = apps.get_model('messaging', 'Contact')
294 Contact.update(email, Level.MANUAL_MEMBER, datetime.combine(self.updated_at, datetime.min.time(), utc))
299 def is_active_for(cls, user):
300 if user.is_anonymous:
303 membership = user.membership
304 except cls.DoesNotExist:
306 if membership.manual:
308 return Schedule.objects.filter(
309 expires_at__gt=now(),
310 membership__user=user,
314 class ReminderEmail(models.Model):
315 days_before = models.SmallIntegerField('dni przed')
316 subject = models.CharField('temat', max_length=1024)
317 body = models.TextField('treść')
320 verbose_name = 'email z przypomnieniem'
321 verbose_name_plural = 'e-maile z przypomnieniem'
322 ordering = ['days_before']
325 if self.days_before >= 0:
326 return '%d dni przed wygaśnięciem' % self.days_before
328 return '%d dni po wygaśnięciu' % -self.days_before
331 class Ambassador(models.Model):
332 name = models.CharField('imię i nazwisko', max_length=255)
333 photo = models.ImageField('zdjęcie', blank=True)
334 text = models.CharField('tekst', max_length=1024)
337 verbose_name = 'ambasador'
338 verbose_name_plural = 'ambasadorowie'
351 class PayUOrder(payu_models.Order):
352 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
354 def get_amount(self):
355 return self.schedule.amount
359 "email": self.schedule.email,
360 "language": get_language(),
363 def get_description(self):
364 return 'Wolne Lektury'
366 def is_recurring(self):
367 return self.schedule.get_payment_method().is_recurring
369 def get_card_token(self):
370 return self.schedule.payucardtoken_set.order_by('-created_at').first()
372 def get_notify_url(self):
373 return "https://{}{}".format(
374 Site.objects.get_current().domain,
375 reverse('club_payu_notify', args=[self.pk]))
377 def get_thanks_url(self):
378 return self.schedule.get_thanks_url()
380 def status_updated(self):
381 if self.status == 'COMPLETED':
382 self.schedule.set_payed()
384 elif self.status == 'CANCELED' or self.status.startswith('ERR-'):
385 if self.is_recurring() and self.schedule.expires_at:
386 self.schedule.send_email_failed_recurring()
388 self.report_activity()
391 def updated_at(self):
393 return self.notification_set.all().order_by('-received_at')[0].received_at
397 def report_activity(self):
398 if self.status not in ['COMPLETED', 'CANCELED', 'REJECTED']:
401 if self.status != 'COMPLETED':
402 name = settings.CIVICRM_ACTIVITIES['Failed contribution']
403 elif self.is_recurring():
404 name = settings.CIVICRM_ACTIVITIES['Recurring contribution']
406 name = settings.CIVICRM_ACTIVITIES['Contribution']
408 report_activity.delay(
415 'kwota': self.schedule.amount,
420 def send_receipt(cls, email, year, resend=False):
421 Contact = apps.get_model('messaging', 'Contact')
422 Funding = apps.get_model('funding', 'Funding')
423 BillingAgreement = apps.get_model('paypal', 'BillingAgreement')
424 DirectDebit = apps.get_model('pz', 'DirectDebit')
425 Payment = apps.get_model('pz', 'Payment')
431 contact = Contact.objects.get(email=email)
432 except Contact.DoesNotExist:
433 funding = Funding.objects.filter(
435 completed_at__year=year,
436 notifications=True).order_by('completed_at').first()
438 print('no notifications')
439 if not DirectDebit.objects.filter(email=email, optout=False).exists():
442 optout = funding.wl_optout_url()
444 if contact.level == Level.OPT_OUT:
447 optout = contact.wl_optout_url()
449 qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
452 'timestamp': order.completed_at,
453 'amount': order.get_amount(),
456 for ba in BillingAgreement.objects.filter(schedule__email=email):
457 payments.extend(ba.get_donations(year))
459 fundings = Funding.objects.filter(
461 completed_at__year=year
462 ).order_by('completed_at')
463 for funding in fundings:
465 'timestamp': funding.completed_at,
466 'amount': funding.amount,
469 for pa in Payment.objects.filter(
473 booking_date__year=year
476 'timestamp': datetime(pa.booking_date.year, pa.booking_date.month, pa.booking_date.day, tzinfo=utc),
477 'amount': Decimal(str(pa.debit.amount) + '.00')
481 if not payments: return
483 payments.sort(key=lambda x: x['timestamp'])
488 "next_year": year + 1,
489 "total": sum(x['amount'] for x in payments),
490 "payments": payments,
494 temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
496 render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
497 "wl.eps": os.path.join(settings.STATIC_ROOT, "img/wl.eps"),
500 message = EmailMessage(
501 'Odlicz darowiznę na Wolne Lektury od podatku',
502 template.loader.render_to_string('club/receipt_email.txt', ctx),
503 settings.CLUB_CONTACT_EMAIL, [email]
505 with open(temp.name, 'rb') as f:
506 message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
511 class PayUCardToken(payu_models.CardToken):
512 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
515 class PayUNotification(payu_models.Notification):
516 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')