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
7 from django.apps import apps
8 from django.conf import settings
9 from django.contrib.sites.models import Site
10 from django.core.mail import send_mail, EmailMessage
11 from django.urls import reverse
12 from django.db import models
13 from django import template
14 from django.utils.timezone import now
15 from django.utils.translation import ugettext_lazy as _, ungettext, ugettext, get_language
16 from django_countries.fields import CountryField
17 from catalogue.utils import get_random_hash
18 from messaging.states import Level
19 from reporting.utils import render_to_pdf
20 from .payment_methods import methods
21 from .payu import models as payu_models
25 class Club(models.Model):
26 min_amount = models.IntegerField(_('minimum amount'))
27 min_for_year = models.IntegerField(_('minimum amount for year'))
28 single_amounts = models.CharField(_('proposed amounts for single payment'), max_length=255)
29 default_single_amount = models.IntegerField(_('default single amount'))
30 monthly_amounts = models.CharField(_('proposed amounts for monthly payments'), max_length=255)
31 default_monthly_amount = models.IntegerField(_('default monthly amount'))
34 verbose_name = _('club')
35 verbose_name_plural = _('clubs')
40 def proposed_single_amounts(self):
41 return [int(x) for x in self.single_amounts.split(',')]
43 def proposed_monthly_amounts(self):
44 return [int(x) for x in self.monthly_amounts.split(',')]
47 class Consent(models.Model):
48 order = models.IntegerField()
49 active = models.BooleanField(default=True)
50 text = models.CharField(max_length=2048)
51 required = models.BooleanField()
60 class Schedule(models.Model):
61 """ Represents someone taking up a plan. """
62 key = models.CharField(_('key'), max_length=255, unique=True)
63 email = models.EmailField(_('email'))
64 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.SET_NULL)
65 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
66 method = models.CharField(_('method'), max_length=32, choices=[
67 (m.slug, m.name) for m in methods
69 monthly = models.BooleanField(_('monthly'), default=True)
70 yearly = models.BooleanField(_('yearly'), default=False)
72 source = models.CharField(_('source'), max_length=255, blank=True)
74 is_cancelled = models.BooleanField(_('cancelled'), default=False)
75 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
76 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
77 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
78 email_sent = models.BooleanField(default=False)
80 first_name = models.CharField(max_length=255, blank=True)
81 last_name = models.CharField(max_length=255, blank=True)
82 phone = models.CharField(max_length=255, blank=True)
83 postal = models.CharField(max_length=255, blank=True)
84 postal_code = models.CharField(max_length=255, blank=True)
85 postal_town = models.CharField(max_length=255, blank=True)
86 postal_country = CountryField(default='PL', blank=True)
88 consent = models.ManyToManyField(Consent)
91 verbose_name = _('schedule')
92 verbose_name_plural = _('schedules')
97 def save(self, *args, **kwargs):
99 self.key = get_random_hash(self.email)
100 super(Schedule, self).save(*args, **kwargs)
101 self.update_contact()
103 def initiate_payment(self, request):
104 return self.get_payment_method().initiate(request, self)
106 def pay(self, request):
107 return self.get_payment_method().pay(request, self)
109 def get_absolute_url(self):
110 return reverse('club_schedule', args=[self.key])
112 def get_thanks_url(self):
113 return reverse('club_thanks', args=[self.key])
115 def get_payment_method(self):
116 return [m for m in methods if m.slug == self.method][0]
118 def is_expired(self):
119 return self.expires_at is not None and self.expires_at <= now()
122 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
124 def is_recurring(self):
125 return self.monthly or self.yearly
128 since = self.expires_at
130 if since is None or since < n:
132 new_exp = self.get_next_installment(since)
133 if self.payed_at is None:
135 if self.expires_at is None or self.expires_at < new_exp:
136 self.expires_at = new_exp
139 if not self.email_sent:
142 def get_next_installment(self, date):
144 return utils.add_year(date)
146 return utils.add_month(date)
147 club = Club.objects.first()
148 if club is not None and self.amount >= club.min_for_year:
149 return utils.add_year(date)
150 return utils.add_month(date)
152 def send_email(self):
153 ctx = {'schedule': self}
155 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
156 template.loader.render_to_string('club/email/thanks.txt', ctx),
157 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
158 self.email_sent = True
161 def update_contact(self):
162 Contact = apps.get_model('messaging', 'Contact')
163 if not self.payed_at:
165 since = self.started_at
167 since = self.payed_at
168 if self.is_recurring():
169 level = Level.RECURRING
172 Contact.update(self.email, level, since, self.expires_at)
178 class Membership(models.Model):
179 """ Represents a user being recognized as a member of the club. """
180 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
181 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
182 name = models.CharField(_('name'), max_length=255, blank=True)
183 manual = models.BooleanField(_('manual'), default=False)
184 notes = models.CharField(_('notes'), max_length=2048, blank=True)
185 updated_at = models.DateField(_('updated at'), auto_now=True, blank=True)
188 verbose_name = _('membership')
189 verbose_name_plural = _('memberships')
192 return str(self.user)
194 def save(self, *args, **kwargs):
195 super().save(*args, **kwargs)
196 self.update_contact()
198 def update_contact(self):
199 email = self.user.email
203 Contact = apps.get_model('messaging', 'Contact')
205 Contact.update(email, Level.MANUAL_MEMBER, self.updated_at)
210 def is_active_for(cls, user):
211 if user.is_anonymous:
214 membership = user.membership
215 except cls.DoesNotExist:
217 if membership.manual:
219 return Schedule.objects.filter(
220 expires_at__gt=now(),
221 membership__user=user,
225 class ReminderEmail(models.Model):
226 days_before = models.SmallIntegerField(_('days before'))
227 subject = models.CharField(_('subject'), max_length=1024)
228 body = models.TextField(_('body'))
231 verbose_name = _('reminder email')
232 verbose_name_plural = _('reminder emails')
233 ordering = ['days_before']
236 if self.days_before >= 0:
237 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
239 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
242 class Ambassador(models.Model):
243 name = models.CharField(_('name'), max_length=255)
244 photo = models.ImageField(_('photo'), blank=True)
245 text = models.CharField(_('text'), max_length=1024)
248 verbose_name = _('ambassador')
249 verbose_name_plural = _('ambassadors')
262 class PayUOrder(payu_models.Order):
263 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
265 def get_amount(self):
266 return self.schedule.amount
270 "email": self.schedule.email,
271 "language": get_language(),
274 def get_continue_url(self):
275 return "https://{}{}".format(
276 Site.objects.get_current().domain,
277 self.schedule.get_thanks_url())
279 def get_description(self):
280 return ugettext('Towarzystwo Przyjaciół Wolnych Lektur')
282 def is_recurring(self):
283 return self.schedule.get_payment_method().is_recurring
285 def get_card_token(self):
286 return self.schedule.payucardtoken_set.order_by('-created_at').first()
288 def get_notify_url(self):
289 return "https://{}{}".format(
290 Site.objects.get_current().domain,
291 reverse('club_payu_notify', args=[self.pk]))
293 def status_updated(self):
294 if self.status == 'COMPLETED':
295 self.schedule.set_payed()
299 def send_receipt(cls, email, year):
300 Contact = apps.get_model('messaging', 'Contact')
301 Funding = apps.get_model('funding', 'Funding')
305 contact = Contact.objects.get(email=email)
306 except Contact.DoesNotExist:
307 funding = Funding.objects.filter(
310 notifications=True).order_by('payed_at').first()
312 print('no notifications')
314 optout = funding.wl_optout_url()
316 if contact.level == Level.OPT_OUT:
319 optout = contact.wl_optout_url()
321 qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
324 'timestamp': order.completed_at,
325 'amount': order.get_amount(),
328 fundings = Funding.objects.filter(
331 ).order_by('payed_at')
332 for funding in fundings:
334 'timestamp': funding.payed_at,
335 'amount': funding.amount,
338 if not payments: return
340 payments.sort(key=lambda x: x['timestamp'])
345 "next_year": year + 1,
346 "total": sum(x['amount'] for x in payments),
347 "payments": payments,
350 temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
352 render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
353 "fnp.eps": os.path.join(settings.STATIC_ROOT, "img/fnp.eps"),
356 message = EmailMessage(
357 f'Odlicz od podatku swoje darowizny przekazane dla Wolnych Lektur',
358 template.loader.render_to_string('club/receipt_email.txt', ctx),
359 settings.CONTACT_EMAIL, [email]
361 with open(temp.name, 'rb') as f:
362 message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
367 class PayUCardToken(payu_models.CardToken):
368 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
371 class PayUNotification(payu_models.Notification):
372 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')
375 class DirectDebit(models.Model):
376 first_name = models.CharField(_('first name'), max_length=255, blank=True)
377 last_name = models.CharField(_('last name'), max_length=255, blank=True)
378 sex = models.CharField(_('sex'), max_length=1, blank=True, choices=[
382 date_of_birth = models.DateField(_('date of birth'), null=True, blank=True)
383 street = models.CharField(_('street'), max_length=255, blank=True)
384 building = models.CharField(_('building'), max_length=255, blank=True)
385 flat = models.CharField(_('flat'), max_length=255, blank=True)
386 town = models.CharField(_('town'), max_length=255, blank=True)
387 postal_code = models.CharField(_('postal code'), max_length=255, blank=True)
388 phone = models.CharField(_('phone'), max_length=255, blank=True)
389 email = models.CharField(_('e-mail'), max_length=255, blank=True)
390 iban = models.CharField(_('IBAN'), max_length=255, blank=True)
391 payment_id = models.CharField(_('payment identifier'), max_length=255, blank=True)
392 agree_newsletter = models.BooleanField(_('agree newsletter'))
393 date = models.DateField(_('date'))
394 amount = models.IntegerField(_('amount'))
397 verbose_name = _('direct debit')
398 verbose_name_plural = _('direct debits')