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 catalogue.utils import get_random_hash
17 from messaging.states import Level
18 from reporting.utils import render_to_pdf
19 from .payment_methods import methods
20 from .payu import models as payu_models
24 class Club(models.Model):
25 min_amount = models.IntegerField(_('minimum amount'))
26 min_for_year = models.IntegerField(_('minimum amount for year'))
27 single_amounts = models.CharField(_('proposed amounts for single payment'), max_length=255)
28 default_single_amount = models.IntegerField(_('default single amount'))
29 monthly_amounts = models.CharField(_('proposed amounts for monthly payments'), max_length=255)
30 default_monthly_amount = models.IntegerField(_('default monthly amount'))
33 verbose_name = _('club')
34 verbose_name_plural = _('clubs')
39 def proposed_single_amounts(self):
40 return [int(x) for x in self.single_amounts.split(',')]
42 def proposed_monthly_amounts(self):
43 return [int(x) for x in self.monthly_amounts.split(',')]
46 class Schedule(models.Model):
47 """ Represents someone taking up a plan. """
48 key = models.CharField(_('key'), max_length=255, unique=True)
49 email = models.EmailField(_('email'))
50 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.SET_NULL)
51 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
52 method = models.CharField(_('method'), max_length=32, choices=[
53 (m.slug, m.name) for m in methods
55 monthly = models.BooleanField(_('monthly'), default=True)
56 yearly = models.BooleanField(_('yearly'), default=False)
58 source = models.CharField(_('source'), max_length=255, blank=True)
60 is_cancelled = models.BooleanField(_('cancelled'), default=False)
61 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
62 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
63 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
64 email_sent = models.BooleanField(default=False)
67 verbose_name = _('schedule')
68 verbose_name_plural = _('schedules')
73 def save(self, *args, **kwargs):
75 self.key = get_random_hash(self.email)
76 super(Schedule, self).save(*args, **kwargs)
79 def initiate_payment(self, request):
80 return self.get_payment_method().initiate(request, self)
82 def pay(self, request):
83 return self.get_payment_method().pay(request, self)
85 def get_absolute_url(self):
86 return reverse('club_schedule', args=[self.key])
88 def get_thanks_url(self):
89 return reverse('club_thanks', args=[self.key])
91 def get_payment_method(self):
92 return [m for m in methods if m.slug == self.method][0]
95 return self.expires_at is not None and self.expires_at <= now()
98 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
100 def is_recurring(self):
101 return self.monthly or self.yearly
104 since = self.expires_at
106 if since is None or since < n:
108 new_exp = self.get_next_installment(since)
109 if self.payed_at is None:
111 if self.expires_at is None or self.expires_at < new_exp:
112 self.expires_at = new_exp
115 if not self.email_sent:
118 def get_next_installment(self, date):
120 return utils.add_year(date)
122 return utils.add_month(date)
123 club = Club.objects.first()
124 if club is not None and self.amount >= club.min_for_year:
125 return utils.add_year(date)
126 return utils.add_month(date)
128 def send_email(self):
129 ctx = {'schedule': self}
131 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
132 template.loader.render_to_string('club/email/thanks.txt', ctx),
133 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
134 self.email_sent = True
137 def update_contact(self):
138 Contact = apps.get_model('messaging', 'Contact')
139 if not self.payed_at:
141 since = self.started_at
143 since = self.payed_at
144 if self.is_recurring():
145 level = Level.RECURRING
148 Contact.update(self.email, level, since, self.expires_at)
151 class Membership(models.Model):
152 """ Represents a user being recognized as a member of the club. """
153 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
154 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
155 name = models.CharField(_('name'), max_length=255, blank=True)
156 manual = models.BooleanField(_('manual'), default=False)
157 notes = models.CharField(_('notes'), max_length=2048, blank=True)
158 updated_at = models.DateField(_('updated at'), auto_now=True, blank=True)
161 verbose_name = _('membership')
162 verbose_name_plural = _('memberships')
165 return str(self.user)
167 def save(self, *args, **kwargs):
168 super().save(*args, **kwargs)
169 self.update_contact()
171 def update_contact(self):
172 email = self.user.email
176 Contact = apps.get_model('messaging', 'Contact')
178 Contact.update(email, Level.MANUAL_MEMBER, self.updated_at)
183 def is_active_for(cls, user):
184 if user.is_anonymous:
187 membership = user.membership
188 except cls.DoesNotExist:
190 if membership.manual:
192 return Schedule.objects.filter(
193 expires_at__gt=now(),
194 membership__user=user,
198 class ReminderEmail(models.Model):
199 days_before = models.SmallIntegerField(_('days before'))
200 subject = models.CharField(_('subject'), max_length=1024)
201 body = models.TextField(_('body'))
204 verbose_name = _('reminder email')
205 verbose_name_plural = _('reminder emails')
206 ordering = ['days_before']
209 if self.days_before >= 0:
210 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
212 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
215 class Ambassador(models.Model):
216 name = models.CharField(_('name'), max_length=255)
217 photo = models.ImageField(_('photo'), blank=True)
218 text = models.CharField(_('text'), max_length=1024)
221 verbose_name = _('ambassador')
222 verbose_name_plural = _('ambassadors')
235 class PayUOrder(payu_models.Order):
236 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
238 def get_amount(self):
239 return self.schedule.amount
243 "email": self.schedule.email,
244 "language": get_language(),
247 def get_continue_url(self):
248 return "https://{}{}".format(
249 Site.objects.get_current().domain,
250 self.schedule.get_thanks_url())
252 def get_description(self):
253 return ugettext('Towarzystwo Przyjaciół Wolnych Lektur')
255 def is_recurring(self):
256 return self.schedule.get_payment_method().is_recurring
258 def get_card_token(self):
259 return self.schedule.payucardtoken_set.order_by('-created_at').first()
261 def get_notify_url(self):
262 return "https://{}{}".format(
263 Site.objects.get_current().domain,
264 reverse('club_payu_notify', args=[self.pk]))
266 def status_updated(self):
267 if self.status == 'COMPLETED':
268 self.schedule.set_payed()
272 def send_receipt(cls, email, year):
273 Contact = apps.get_model('messaging', 'Contact')
274 Funding = apps.get_model('funding', 'Funding')
278 contact = Contact.objects.get(email=email)
279 except Contact.DoesNotExist:
280 funding = Funding.objects.filter(
283 notifications=True).order_by('payed_at').first()
285 print('no notifications')
287 optout = funding.wl_optout_url()
289 if contact.level == Level.OPT_OUT:
292 optout = contact.wl_optout_url()
294 qs = cls.objects.filter(status='COMPLETED', schedule__email=email, completed_at__year=year).order_by('completed_at')
297 'timestamp': order.completed_at,
298 'amount': order.get_amount(),
301 fundings = Funding.objects.filter(
304 ).order_by('payed_at')
305 for funding in fundings:
307 'timestamp': funding.payed_at,
308 'amount': funding.amount,
311 if not payments: return
313 payments.sort(key=lambda x: x['timestamp'])
318 "next_year": year + 1,
319 "total": sum(x['amount'] for x in payments),
320 "payments": payments,
323 temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
325 render_to_pdf(temp.name, 'club/receipt.texml', ctx, {
326 "fnp.eps": os.path.join(settings.STATIC_ROOT, "img/fnp.eps"),
329 message = EmailMessage(
330 f'Odlicz od podatku swoje darowizny przekazane dla Wolnych Lektur',
331 template.loader.render_to_string('club/receipt_email.txt', ctx),
332 settings.CONTACT_EMAIL, [email]
334 with open(temp.name, 'rb') as f:
335 message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
340 class PayUCardToken(payu_models.CardToken):
341 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
344 class PayUNotification(payu_models.Notification):
345 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')
348 class DirectDebit(models.Model):
349 first_name = models.CharField(_('first name'), max_length=255, blank=True)
350 last_name = models.CharField(_('last name'), max_length=255, blank=True)
351 sex = models.CharField(_('sex'), max_length=1, blank=True, choices=[
355 date_of_birth = models.DateField(_('date of birth'), null=True, blank=True)
356 street = models.CharField(_('street'), max_length=255, blank=True)
357 building = models.CharField(_('building'), max_length=255, blank=True)
358 flat = models.CharField(_('flat'), max_length=255, blank=True)
359 town = models.CharField(_('town'), max_length=255, blank=True)
360 postal_code = models.CharField(_('postal code'), max_length=255, blank=True)
361 phone = models.CharField(_('phone'), max_length=255, blank=True)
362 email = models.CharField(_('e-mail'), max_length=255, blank=True)
363 iban = models.CharField(_('IBAN'), max_length=255, blank=True)
364 payment_id = models.CharField(_('payment identifier'), max_length=255, blank=True)
365 agree_newsletter = models.BooleanField(_('agree newsletter'))
366 date = models.DateField(_('date'))
367 amount = models.IntegerField(_('amount'))
370 verbose_name = _('direct debit')
371 verbose_name_plural = _('direct debits')