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 date, datetime
5 from urllib.parse import urlencode
6 from django.conf import settings
7 from django.contrib.sites.models import Site
8 from django.core.mail import send_mail
9 from django.db import models
10 from django.dispatch import receiver
11 from django.template.loader import render_to_string
12 from django.urls import reverse
13 from django.utils.html import mark_safe
14 from django.utils.timezone import utc
15 from django.utils.translation import gettext_lazy as _, override
16 from catalogue.models import Book
17 from catalogue.utils import get_random_hash
18 from polls.models import Poll
19 import club.payu.models
20 from wolnelektury.utils import cached_render, clear_cached_renders
21 from . import app_settings
25 class Offer(models.Model):
26 """ A fundraiser for a particular book. """
27 author = models.CharField(_('author'), max_length=255)
28 title = models.CharField(_('title'), max_length=255)
29 slug = models.SlugField(_('slug'))
30 description = models.TextField(_('description'), blank=True)
31 target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
32 start = models.DateField(_('start'), db_index=True)
33 end = models.DateField(_('end'), db_index=True)
34 redakcja_url = models.URLField(_('redakcja URL'), blank=True)
35 book = models.ForeignKey(Book, models.PROTECT, null=True, blank=True, help_text=_('Published book.'))
36 cover = models.ImageField(_('Cover'), upload_to='funding/covers')
37 poll = models.ForeignKey(Poll, help_text=_('Poll'), null=True, blank=True, on_delete=models.SET_NULL)
39 notified_near = models.DateTimeField(_('Near-end notifications sent'), blank=True, null=True)
40 notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True)
42 def cover_img_tag(self):
43 return mark_safe('<img src="%s" />' % self.cover.url)
44 cover_img_tag.short_description = _('Cover preview')
47 verbose_name = _('offer')
48 verbose_name_plural = _('offers')
52 return "%s - %s" % (self.author, self.title)
54 def get_absolute_url(self):
55 return reverse('funding_offer', args=[self.slug])
57 def save(self, *args, **kw):
59 self.book_id is not None and self.pk is not None and
60 type(self).objects.values('book').get(pk=self.pk)['book'] != self.book_id)
61 retval = super(Offer, self).save(*args, **kw)
64 self.notify_published()
67 def get_payu_payment_title(self):
68 return utils.sanitize_payment_title(str(self))
70 def clear_cache(self):
71 clear_cached_renders(self.top_bar)
72 clear_cached_renders(self.list_bar)
73 clear_cached_renders(self.detail_bar)
74 clear_cached_renders(self.status)
75 clear_cached_renders(self.status_more)
78 return self.start <= date.today() <= self.end and self == self.current()
81 return self.sum() >= self.target
87 return self.sum() - self.target
93 """ Returns current fundraiser or None.
95 Current fundraiser is the one that:
96 - has already started,
98 - if there's more than one of those, it's the one that ends last.
102 objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end')
110 """ QuerySet for all past fundraisers. """
111 objects = cls.public()
112 current = cls.current()
113 if current is not None:
114 objects = objects.exclude(pk=current.pk)
119 """ QuerySet for all current and past fundraisers. """
121 return cls.objects.filter(start__lte=today)
123 def get_perks(self, amount=None):
124 """ Finds all the perks for the offer.
126 If amount is provided, returns the perks you get for it.
129 perks = Perk.objects.filter(
130 models.Q(offer=self) | models.Q(offer=None)
131 ).exclude(end_date__lt=date.today())
132 if amount is not None:
133 perks = perks.filter(price__lte=amount)
136 def funding_payed(self):
137 """ QuerySet for all completed payments for the offer. """
138 return Funding.payed().filter(offer=self)
141 return self.funding_payed().order_by('-amount', 'completed_at')
144 """ The money gathered. """
145 return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
147 def notify_all(self, subject, template_name, extra_context=None):
148 Funding.notify_funders(
149 subject, template_name, extra_context,
150 query_filter=models.Q(offer=self)
153 def notify_end(self, force=False):
154 if not force and self.notified_end:
156 assert not self.is_current()
158 _('The fundraiser has ended!'),
159 'funding/email/end.txt', {
161 'is_win': self.is_win(),
162 'remaining': self.remaining(),
163 'current': self.current(),
165 self.notified_end = datetime.utcnow().replace(tzinfo=utc)
168 def notify_near(self, force=False):
169 if not force and self.notified_near:
171 assert self.is_current()
173 need = self.target - sum_
175 _('The fundraiser will end soon!'),
176 'funding/email/near.txt', {
177 'days': (self.end - date.today()).days + 1,
179 'is_win': self.is_win(),
183 self.notified_near = datetime.utcnow().replace(tzinfo=utc)
186 def notify_published(self):
187 assert self.book is not None
189 _('The book you helped fund has been published.'),
190 'funding/email/published.txt', {
193 'author': self.book.pretty_title(),
194 'current': self.current(),
197 def basic_info(self):
198 offer_sum = self.sum()
202 'is_current': self.is_current(),
203 'is_win': offer_sum >= self.target,
204 'missing': self.target - offer_sum,
205 'percentage': 100 * offer_sum / self.target,
208 'show_title_calling': True,
211 @cached_render('funding/includes/funding.html')
213 ctx = self.basic_info()
217 'add_class': 'funding-top-header',
221 @cached_render('funding/includes/funding.html')
223 ctx = self.basic_info()
226 'show_title_calling': False,
230 @cached_render('funding/includes/funding.html')
231 def detail_bar(self):
232 ctx = self.basic_info()
238 @cached_render('funding/includes/offer_status.html')
240 return {'offer': self}
242 @cached_render('funding/includes/offer_status_more.html')
243 def status_more(self):
244 return {'offer': self}
247 class Perk(models.Model):
250 If no attached to a particular Offer, applies to all.
253 offer = models.ForeignKey(Offer, models.CASCADE, verbose_name=_('offer'), null=True, blank=True)
254 price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
255 name = models.CharField(_('name'), max_length=255)
256 long_name = models.CharField(_('long name'), max_length=255)
257 end_date = models.DateField(_('end date'), null=True, blank=True)
260 verbose_name = _('perk')
261 verbose_name_plural = _('perks')
262 ordering = ['-price']
265 return "%s (%s%s)" % (self.name, self.price, " for %s" % self.offer if self.offer else "")
268 class Funding(club.payu.models.Order):
269 """ A person paying in a fundraiser.
271 The payment was completed if and only if completed_at is set.
274 offer = models.ForeignKey(Offer, models.PROTECT, verbose_name=_('offer'))
275 customer_ip = models.GenericIPAddressField(_('customer IP'), null=True)
277 name = models.CharField(_('name'), max_length=127, blank=True)
278 email = models.EmailField(_('email'), blank=True, db_index=True)
279 user = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True)
280 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
281 perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
282 language_code = models.CharField(max_length=2, null=True, blank=True)
283 notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
284 notify_key = models.CharField(max_length=32)
287 verbose_name = _('funding')
288 verbose_name_plural = _('fundings')
289 ordering = ['-completed_at', 'pk']
293 """ QuerySet for all completed payments. """
294 return cls.objects.exclude(completed_at=None)
297 return str(self.offer)
299 def get_amount(self):
305 "language": self.language_code,
308 def get_description(self):
309 return self.offer.get_payu_payment_title()
311 def get_thanks_url(self):
312 return reverse('funding_thanks')
314 def status_updated(self):
315 if self.status == 'COMPLETED':
318 _('Thank you for your support!'),
319 'funding/email/thanks.txt'
322 def get_notify_url(self):
323 return "https://{}{}".format(
324 Site.objects.get_current().domain,
325 reverse('funding_payu_notify', args=[self.pk]))
327 def perk_names(self):
328 return ", ".join(perk.name for perk in self.perks.all())
330 def get_disable_notifications_url(self):
332 reverse("funding_disable_notifications"),
335 'key': self.notify_key,
338 def wl_optout_url(self):
339 return 'https://wolnelektury.pl' + self.get_disable_notifications_url()
341 def save(self, *args, **kwargs):
342 if self.email and not self.notify_key:
343 self.notify_key = get_random_hash(self.email)
344 ret = super(Funding, self).save(*args, **kwargs)
345 self.offer.clear_cache()
349 def notify_funders(cls, subject, template_name, extra_context=None, query_filter=None, payed_only=True):
350 funders = cls.objects.exclude(email="").filter(notifications=True)
352 funders = funders.exclude(completed_at=None)
353 if query_filter is not None:
354 funders = funders.filter(query_filter)
356 for funder in funders:
357 if funder.email in emails:
359 emails.add(funder.email)
360 funder.notify(subject, template_name, extra_context)
362 def notify(self, subject, template_name, extra_context=None):
365 'site': Site.objects.get_current(),
368 context.update(extra_context)
369 with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
371 subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
374 def disable_notifications(self):
375 """Disables all notifications for this e-mail address."""
376 type(self).objects.filter(email=self.email).update(notifications=False)
379 class PayUNotification(club.payu.models.Notification):
380 order = models.ForeignKey(Funding, models.CASCADE, related_name='notification_set')
383 class Spent(models.Model):
384 """ Some of the remaining money spent on a book. """
385 book = models.ForeignKey(Book, models.PROTECT)
386 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
387 timestamp = models.DateField(_('when'))
390 verbose_name = _('money spent on a book')
391 verbose_name_plural = _('money spent on books')
392 ordering = ['-timestamp']
395 return "Spent: %s" % str(self.book)