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 is_custom_amount(self):
165 club = Club.objects.first()
169 return not club.monthlyamount_set.filter(amount=self.amount).exists()
171 return not club.singleamount_set.filter(amount=self.amount).exists()
173 def initiate_payment(self, request):
174 return self.get_payment_method().initiate(request, self)
176 def pay(self, request):
177 return self.get_payment_method().pay(request, self)
179 def get_absolute_url(self):
180 return reverse('club_schedule', args=[self.key])
182 def get_thanks_url(self):
183 return reverse('club_thanks', args=[self.key])
185 def get_payment_method(self):
186 return [m for m in methods if m.slug == self.method][0]
188 def get_payment_methods(self):
189 for method in methods:
190 if (self.monthly or self.yearly) and method.is_recurring:
192 elif not (self.monthly or self.yearly) and method.is_onetime:
195 def is_expired(self):
196 return self.expires_at is not None and self.expires_at <= now()
199 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
201 def is_recurring(self):
202 return self.monthly or self.yearly
205 since = self.expires_at
207 if since is None or since < n:
209 new_exp = self.get_next_installment(since)
210 if self.payed_at is None:
212 if self.expires_at is None or self.expires_at < new_exp:
213 self.expires_at = new_exp
216 if not self.email_sent:
219 def get_next_installment(self, date):
221 return utils.add_year(date)
223 return utils.add_month(date)
224 club = Club.objects.first()
225 if club is not None and self.amount >= club.min_for_year:
226 return utils.add_year(date)
227 return utils.add_month(date)
229 def get_other_active_recurring(self):
230 schedules = type(self).objects.exclude(
231 monthly=False, yearly=False
232 ).filter(is_cancelled=False, expires_at__gt=now()).exclude(pk=self.pk)
233 mine_q = models.Q(email=self.email)
234 if self.membership is not None:
235 mine_q |= models.Q(membership__user=self.membership.user)
236 schedules = schedules.filter(mine_q)
237 return schedules.order_by('-expires_at').first()
239 def send_email(self):
240 ctx = {'schedule': self}
242 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
243 template.loader.render_to_string('club/email/thanks.txt', ctx),
244 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
245 self.email_sent = True
248 def send_email_failed_recurring(self):
251 'other': self.get_other_active_recurring(),
254 'Darowizna na Wolne Lektury — problem z płatnością',
255 template.loader.render_to_string('club/email/failed_recurring.txt', ctx),
256 settings.CONTACT_EMAIL, [self.email], fail_silently=False
259 def update_contact(self):
260 Contact = apps.get_model('messaging', 'Contact')
261 if not self.payed_at:
263 since = self.started_at
265 since = self.payed_at
266 if self.is_recurring():
267 level = Level.RECURRING
270 Contact.update(self.email, level, since, self.expires_at)
276 class Membership(models.Model):
277 """ Represents a user being recognized as a member of the club. """
278 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name='użytkownik', on_delete=models.CASCADE)
279 created_at = models.DateTimeField('utworzone', auto_now_add=True)
280 name = models.CharField('nazwa', max_length=255, blank=True)
281 manual = models.BooleanField('ustawione ręcznie', default=False)
282 notes = models.CharField('notatki', max_length=2048, blank=True)
283 updated_at = models.DateField('aktualizacja', auto_now=True, blank=True)
286 verbose_name = 'członkostwo'
287 verbose_name_plural = 'członkostwa'
290 return str(self.user)
292 def save(self, *args, **kwargs):
293 super().save(*args, **kwargs)
294 self.update_contact()
296 def update_contact(self):
297 email = self.user.email
301 Contact = apps.get_model('messaging', 'Contact')
303 Contact.update(email, Level.MANUAL_MEMBER, datetime.combine(self.updated_at, datetime.min.time(), utc))
308 def is_active_for(cls, user):
309 if user.is_anonymous:
312 membership = user.membership
313 except cls.DoesNotExist:
315 if membership.manual:
317 return Schedule.objects.filter(
318 expires_at__gt=now(),
319 membership__user=user,
323 class ReminderEmail(models.Model):
324 days_before = models.SmallIntegerField('dni przed')
325 subject = models.CharField('temat', max_length=1024)
326 body = models.TextField('treść')
329 verbose_name = 'email z przypomnieniem'
330 verbose_name_plural = 'e-maile z przypomnieniem'
331 ordering = ['days_before']
334 if self.days_before >= 0:
335 return '%d dni przed wygaśnięciem' % self.days_before
337 return '%d dni po wygaśnięciu' % -self.days_before
340 class Ambassador(models.Model):
341 name = models.CharField('imię i nazwisko', max_length=255)
342 photo = models.ImageField('zdjęcie', blank=True)
343 text = models.CharField('tekst', max_length=1024)
346 verbose_name = 'ambasador'
347 verbose_name_plural = 'ambasadorowie'
360 class PayUOrder(payu_models.Order):
361 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
363 def get_amount(self):
364 return self.schedule.amount
368 "email": self.schedule.email,
369 "language": get_language(),
372 def get_description(self):
373 return 'Wolne Lektury'
375 def is_recurring(self):
376 return self.schedule.get_payment_method().is_recurring
378 def get_card_token(self):
379 return self.schedule.payucardtoken_set.order_by('-created_at').first()
381 def get_notify_url(self):
382 return "https://{}{}".format(
383 Site.objects.get_current().domain,
384 reverse('club_payu_notify', args=[self.pk]))
386 def get_thanks_url(self):
387 return self.schedule.get_thanks_url()
389 def status_updated(self):
390 if self.status == 'COMPLETED':
391 self.schedule.set_payed()
393 elif self.status == 'CANCELED' or self.status.startswith('ERR-'):
394 if self.is_recurring() and self.schedule.expires_at:
395 self.schedule.send_email_failed_recurring()
397 self.report_activity()
400 def updated_at(self):
402 return self.notification_set.all().order_by('-received_at')[0].received_at
406 def report_activity(self):
407 if self.status not in ['COMPLETED', 'CANCELED', 'REJECTED']:
410 if self.status != 'COMPLETED':
411 name = settings.CIVICRM_ACTIVITIES['Failed contribution']
412 elif self.is_recurring():
413 name = settings.CIVICRM_ACTIVITIES['Recurring contribution']
415 name = settings.CIVICRM_ACTIVITIES['Contribution']
417 report_activity.delay(
424 'kwota': self.schedule.amount,
429 def generate_receipt(cls, email, year):
431 Contact = apps.get_model('messaging', 'Contact')
432 Funding = apps.get_model('funding', 'Funding')
433 BillingAgreement = apps.get_model('paypal', 'BillingAgreement')
434 DirectDebit = apps.get_model('pz', 'DirectDebit')
435 Payment = apps.get_model('pz', 'Payment')
441 contact = Contact.objects.get(email=email)
442 except Contact.DoesNotExist:
443 funding = Funding.objects.filter(
445 completed_at__year=year,
446 notifications=True).order_by('completed_at').first()
448 print('no notifications')
449 if not DirectDebit.objects.filter(email=email, optout=False).exists():
452 optout = funding.wl_optout_url()
454 if contact.level == Level.OPT_OUT:
457 optout = contact.wl_optout_url()
459 qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
462 'timestamp': order.completed_at,
463 'amount': order.get_amount(),
466 for ba in BillingAgreement.objects.filter(schedule__email=email):
467 payments.extend(ba.get_donations(year))
469 fundings = Funding.objects.filter(
471 completed_at__year=year
472 ).order_by('completed_at')
473 for funding in fundings:
475 'timestamp': funding.completed_at,
476 'amount': funding.amount,
479 for pa in Payment.objects.filter(
483 booking_date__year=year
486 'timestamp': datetime(pa.booking_date.year, pa.booking_date.month, pa.booking_date.day, tzinfo=utc),
487 'amount': Decimal(str(pa.debit.amount) + '.00')
491 if not payments: return
493 payments.sort(key=lambda x: x['timestamp'])
498 "total": sum(x['amount'] for x in payments),
499 "payments": payments,
501 temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
503 render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
504 "wl.eps": os.path.join(settings.STATIC_ROOT, "img/wl.eps"),
507 with open(temp.name, 'rb') as f:
510 return content, optout, payments
513 def send_receipt(cls, email, year, resend=False):
514 receipt = cls.generate_receipt(email, year)
516 content, optout, payments = receipt
520 "next_year": year + 1,
521 "total": sum(x['amount'] for x in payments),
522 "payments": payments,
526 message = EmailMessage(
527 'Odlicz darowiznę na Wolne Lektury od podatku',
528 template.loader.render_to_string('club/receipt_email.txt', ctx),
529 settings.CLUB_CONTACT_EMAIL, [email]
531 message.attach('wolnelektury-darowizny.pdf', content, 'application/pdf')
535 class PayUCardToken(payu_models.CardToken):
536 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
539 class PayUNotification(payu_models.Notification):
540 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')