2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from datetime import date, datetime
6 from urllib.parse import urlencode
7 from django.conf import settings
8 from django.contrib.sites.models import Site
9 from django.core.mail import send_mail
10 from django.db import models
11 from django.dispatch import receiver
12 from django.template.loader import render_to_string
13 from django.urls import reverse
14 from django.utils.html import mark_safe
15 from django.utils.timezone import utc
16 from django.utils.translation import gettext_lazy as _, override
17 from catalogue.models import Book
18 from catalogue.utils import get_random_hash
19 from polls.models import Poll
20 import club.payu.models
21 from wolnelektury.utils import cached_render, clear_cached_renders
22 from . import app_settings
26 class Offer(models.Model):
27 """ A fundraiser for a particular book. """
28 author = models.CharField(_('author'), max_length=255)
29 title = models.CharField(_('title'), max_length=255)
30 slug = models.SlugField(_('slug'))
31 description = models.TextField(_('description'), blank=True)
32 target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
33 start = models.DateField(_('start'), db_index=True)
34 end = models.DateField(_('end'), db_index=True)
35 redakcja_url = models.URLField(_('redakcja URL'), blank=True)
36 book = models.ForeignKey(Book, models.PROTECT, null=True, blank=True, help_text=_('Published book.'))
37 cover = models.ImageField(_('Cover'), upload_to='funding/covers')
38 poll = models.ForeignKey(Poll, help_text=_('Poll'), null=True, blank=True, on_delete=models.SET_NULL)
40 notified_near = models.DateTimeField(_('Near-end notifications sent'), blank=True, null=True)
41 notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True)
43 def cover_img_tag(self):
44 return mark_safe('<img src="%s" />' % self.cover.url)
45 cover_img_tag.short_description = _('Cover preview')
48 verbose_name = _('offer')
49 verbose_name_plural = _('offers')
53 return "%s - %s" % (self.author, self.title)
55 def get_absolute_url(self):
56 return reverse('funding_offer', args=[self.slug])
58 def save(self, *args, **kw):
60 self.book_id is not None and self.pk is not None and
61 type(self).objects.values('book').get(pk=self.pk)['book'] != self.book_id)
62 retval = super(Offer, self).save(*args, **kw)
65 self.notify_published()
68 def get_payu_payment_title(self):
69 return utils.sanitize_payment_title(str(self))
71 def clear_cache(self):
72 clear_cached_renders(self.top_bar)
73 clear_cached_renders(self.top_bar_2022)
74 clear_cached_renders(self.list_bar)
75 clear_cached_renders(self.detail_bar)
76 clear_cached_renders(self.detail_bar_2022)
77 clear_cached_renders(self.status)
78 clear_cached_renders(self.status_more)
81 return self.start <= date.today() <= self.end and self == self.current()
84 return self.sum() >= self.target
90 return self.sum() - self.target
96 """ Returns current fundraiser or None.
98 Current fundraiser is the one that:
99 - has already started,
101 - if there's more than one of those, it's the one that ends last.
105 objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end')
113 """ QuerySet for all past fundraisers. """
114 objects = cls.public()
115 current = cls.current()
116 if current is not None:
117 objects = objects.exclude(pk=current.pk)
122 """ QuerySet for all current and past fundraisers. """
124 return cls.objects.filter(start__lte=today)
126 def get_perks(self, amount=None):
127 """ Finds all the perks for the offer.
129 If amount is provided, returns the perks you get for it.
132 perks = Perk.objects.filter(
133 models.Q(offer=self) | models.Q(offer=None)
134 ).exclude(end_date__lt=date.today())
135 if amount is not None:
136 perks = perks.filter(price__lte=amount)
139 def funding_payed(self):
140 """ QuerySet for all completed payments for the offer. """
141 return Funding.payed().filter(offer=self)
144 return self.funding_payed().order_by('-amount', 'completed_at')
147 """ The money gathered. """
148 return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
150 def notify_all(self, subject, template_name, extra_context=None):
151 Funding.notify_funders(
152 subject, template_name, extra_context,
153 query_filter=models.Q(offer=self)
156 def notify_end(self, force=False):
157 if not force and self.notified_end:
159 assert not self.is_current()
161 _('The fundraiser has ended!'),
162 'funding/email/end.txt', {
164 'is_win': self.is_win(),
165 'remaining': self.remaining(),
166 'current': self.current(),
168 self.notified_end = datetime.utcnow().replace(tzinfo=utc)
171 def notify_near(self, force=False):
172 if not force and self.notified_near:
174 assert self.is_current()
176 need = self.target - sum_
178 _('The fundraiser will end soon!'),
179 'funding/email/near.txt', {
180 'days': (self.end - date.today()).days + 1,
182 'is_win': self.is_win(),
186 self.notified_near = datetime.utcnow().replace(tzinfo=utc)
189 def notify_published(self):
190 assert self.book is not None
192 _('The book you helped fund has been published.'),
193 'funding/email/published.txt', {
196 'author': self.book.pretty_title(),
197 'current': self.current(),
200 def basic_info(self):
201 offer_sum = self.sum()
205 'is_current': self.is_current(),
206 'is_win': offer_sum >= self.target,
207 'missing': self.target - offer_sum,
208 'percentage': min(100, 100 * offer_sum / self.target),
211 'show_title_calling': True,
214 @cached_render('funding/includes/funding.html')
216 ctx = self.basic_info()
220 'add_class': 'funding-top-header',
224 @cached_render('funding/includes/funding.html')
226 ctx = self.basic_info()
229 'show_title_calling': False,
233 @cached_render('funding/includes/funding.html')
234 def detail_bar(self):
235 ctx = self.basic_info()
241 @cached_render('funding/includes/offer_status.html')
243 return {'offer': self}
245 @cached_render('funding/includes/offer_status_more.html')
246 def status_more(self):
247 return {'offer': self}
249 @cached_render('funding/2022/includes/funding.html')
250 def top_bar_2022(self):
251 ctx = self.basic_info()
255 'add_class': 'funding-top-header',
259 @cached_render('funding/2022/includes/funding.html')
260 def detail_bar_2022(self):
261 ctx = self.basic_info()
268 class Perk(models.Model):
271 If no attached to a particular Offer, applies to all.
274 offer = models.ForeignKey(Offer, models.CASCADE, verbose_name=_('offer'), null=True, blank=True)
275 price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
276 name = models.CharField(_('name'), max_length=255)
277 long_name = models.CharField(_('long name'), max_length=255)
278 end_date = models.DateField(_('end date'), null=True, blank=True)
281 verbose_name = _('perk')
282 verbose_name_plural = _('perks')
283 ordering = ['-price']
286 return "%s (%s%s)" % (self.name, self.price, " for %s" % self.offer if self.offer else "")
289 class Funding(club.payu.models.Order):
290 """ A person paying in a fundraiser.
292 The payment was completed if and only if completed_at is set.
295 offer = models.ForeignKey(Offer, models.PROTECT, verbose_name=_('offer'))
296 customer_ip = models.GenericIPAddressField(_('customer IP'), null=True)
298 name = models.CharField(_('name'), max_length=127, blank=True)
299 email = models.EmailField(_('email'), blank=True, db_index=True)
300 user = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True)
301 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
302 perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
303 language_code = models.CharField(max_length=2, null=True, blank=True)
304 notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
305 notify_key = models.CharField(max_length=32)
308 verbose_name = _('funding')
309 verbose_name_plural = _('fundings')
310 ordering = ['-completed_at', 'pk']
314 """ QuerySet for all completed payments. """
315 return cls.objects.exclude(completed_at=None)
318 return str(self.offer)
320 def get_amount(self):
326 "language": self.language_code,
329 def get_description(self):
330 return self.offer.get_payu_payment_title()
332 def get_thanks_url(self):
333 return reverse('funding_thanks')
335 def status_updated(self):
336 if self.status == 'COMPLETED':
339 _('Thank you for your support!'),
340 'funding/email/thanks.txt'
343 def get_notify_url(self):
344 return "https://{}{}".format(
345 Site.objects.get_current().domain,
346 reverse('funding_payu_notify', args=[self.pk]))
348 def perk_names(self):
349 return ", ".join(perk.name for perk in self.perks.all())
351 def get_disable_notifications_url(self):
353 reverse("funding_disable_notifications"),
356 'key': self.notify_key,
359 def wl_optout_url(self):
360 return 'https://wolnelektury.pl' + self.get_disable_notifications_url()
362 def save(self, *args, **kwargs):
363 if self.email and not self.notify_key:
364 self.notify_key = get_random_hash(self.email)
365 ret = super(Funding, self).save(*args, **kwargs)
366 self.offer.clear_cache()
370 def notify_funders(cls, subject, template_name, extra_context=None, query_filter=None, payed_only=True):
371 funders = cls.objects.exclude(email="").filter(notifications=True)
373 funders = funders.exclude(completed_at=None)
374 if query_filter is not None:
375 funders = funders.filter(query_filter)
377 for funder in funders:
378 if funder.email in emails:
380 emails.add(funder.email)
381 funder.notify(subject, template_name, extra_context)
383 def notify(self, subject, template_name, extra_context=None):
386 'site': Site.objects.get_current(),
389 context.update(extra_context)
390 with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
392 subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
395 def disable_notifications(self):
396 """Disables all notifications for this e-mail address."""
397 type(self).objects.filter(email=self.email).update(notifications=False)
400 class PayUNotification(club.payu.models.Notification):
401 order = models.ForeignKey(Funding, models.CASCADE, related_name='notification_set')
404 class Spent(models.Model):
405 """ Some of the remaining money spent on a book. """
406 book = models.ForeignKey(Book, models.PROTECT)
407 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
408 timestamp = models.DateField(_('when'))
411 verbose_name = _('money spent on a book')
412 verbose_name_plural = _('money spent on books')
413 ordering = ['-timestamp']
416 return "Spent: %s" % str(self.book)