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.top_bar_2022)
73 clear_cached_renders(self.list_bar)
74 clear_cached_renders(self.detail_bar)
75 clear_cached_renders(self.detail_bar_2022)
76 clear_cached_renders(self.status)
77 clear_cached_renders(self.status_more)
80 return self.start <= date.today() <= self.end and self == self.current()
83 return self.sum() >= self.target
89 return self.sum() - self.target
95 """ Returns current fundraiser or None.
97 Current fundraiser is the one that:
98 - has already started,
100 - if there's more than one of those, it's the one that ends last.
104 objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end')
112 """ QuerySet for all past fundraisers. """
113 objects = cls.public()
114 current = cls.current()
115 if current is not None:
116 objects = objects.exclude(pk=current.pk)
121 """ QuerySet for all current and past fundraisers. """
123 return cls.objects.filter(start__lte=today)
125 def get_perks(self, amount=None):
126 """ Finds all the perks for the offer.
128 If amount is provided, returns the perks you get for it.
131 perks = Perk.objects.filter(
132 models.Q(offer=self) | models.Q(offer=None)
133 ).exclude(end_date__lt=date.today())
134 if amount is not None:
135 perks = perks.filter(price__lte=amount)
138 def funding_payed(self):
139 """ QuerySet for all completed payments for the offer. """
140 return Funding.payed().filter(offer=self)
143 return self.funding_payed().order_by('-amount', 'completed_at')
146 """ The money gathered. """
147 return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
149 def notify_all(self, subject, template_name, extra_context=None):
150 Funding.notify_funders(
151 subject, template_name, extra_context,
152 query_filter=models.Q(offer=self)
155 def notify_end(self, force=False):
156 if not force and self.notified_end:
158 assert not self.is_current()
160 _('The fundraiser has ended!'),
161 'funding/email/end.txt', {
163 'is_win': self.is_win(),
164 'remaining': self.remaining(),
165 'current': self.current(),
167 self.notified_end = datetime.utcnow().replace(tzinfo=utc)
170 def notify_near(self, force=False):
171 if not force and self.notified_near:
173 assert self.is_current()
175 need = self.target - sum_
177 _('The fundraiser will end soon!'),
178 'funding/email/near.txt', {
179 'days': (self.end - date.today()).days + 1,
181 'is_win': self.is_win(),
185 self.notified_near = datetime.utcnow().replace(tzinfo=utc)
188 def notify_published(self):
189 assert self.book is not None
191 _('The book you helped fund has been published.'),
192 'funding/email/published.txt', {
195 'author': self.book.pretty_title(),
196 'current': self.current(),
199 def basic_info(self):
200 offer_sum = self.sum()
204 'is_current': self.is_current(),
205 'is_win': offer_sum >= self.target,
206 'missing': self.target - offer_sum,
207 'percentage': 100 * offer_sum / self.target,
210 'show_title_calling': True,
213 @cached_render('funding/includes/funding.html')
215 ctx = self.basic_info()
219 'add_class': 'funding-top-header',
223 @cached_render('funding/includes/funding.html')
225 ctx = self.basic_info()
228 'show_title_calling': False,
232 @cached_render('funding/includes/funding.html')
233 def detail_bar(self):
234 ctx = self.basic_info()
240 @cached_render('funding/includes/offer_status.html')
242 return {'offer': self}
244 @cached_render('funding/includes/offer_status_more.html')
245 def status_more(self):
246 return {'offer': self}
248 @cached_render('funding/2022/includes/funding.html')
249 def top_bar_2022(self):
250 ctx = self.basic_info()
254 'add_class': 'funding-top-header',
258 @cached_render('funding/2022/includes/funding.html')
259 def detail_bar_2022(self):
260 ctx = self.basic_info()
267 class Perk(models.Model):
270 If no attached to a particular Offer, applies to all.
273 offer = models.ForeignKey(Offer, models.CASCADE, verbose_name=_('offer'), null=True, blank=True)
274 price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
275 name = models.CharField(_('name'), max_length=255)
276 long_name = models.CharField(_('long name'), max_length=255)
277 end_date = models.DateField(_('end date'), null=True, blank=True)
280 verbose_name = _('perk')
281 verbose_name_plural = _('perks')
282 ordering = ['-price']
285 return "%s (%s%s)" % (self.name, self.price, " for %s" % self.offer if self.offer else "")
288 class Funding(club.payu.models.Order):
289 """ A person paying in a fundraiser.
291 The payment was completed if and only if completed_at is set.
294 offer = models.ForeignKey(Offer, models.PROTECT, verbose_name=_('offer'))
295 customer_ip = models.GenericIPAddressField(_('customer IP'), null=True)
297 name = models.CharField(_('name'), max_length=127, blank=True)
298 email = models.EmailField(_('email'), blank=True, db_index=True)
299 user = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True)
300 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
301 perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
302 language_code = models.CharField(max_length=2, null=True, blank=True)
303 notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
304 notify_key = models.CharField(max_length=32)
307 verbose_name = _('funding')
308 verbose_name_plural = _('fundings')
309 ordering = ['-completed_at', 'pk']
313 """ QuerySet for all completed payments. """
314 return cls.objects.exclude(completed_at=None)
317 return str(self.offer)
319 def get_amount(self):
325 "language": self.language_code,
328 def get_description(self):
329 return self.offer.get_payu_payment_title()
331 def get_thanks_url(self):
332 return reverse('funding_thanks')
334 def status_updated(self):
335 if self.status == 'COMPLETED':
338 _('Thank you for your support!'),
339 'funding/email/thanks.txt'
342 def get_notify_url(self):
343 return "https://{}{}".format(
344 Site.objects.get_current().domain,
345 reverse('funding_payu_notify', args=[self.pk]))
347 def perk_names(self):
348 return ", ".join(perk.name for perk in self.perks.all())
350 def get_disable_notifications_url(self):
352 reverse("funding_disable_notifications"),
355 'key': self.notify_key,
358 def wl_optout_url(self):
359 return 'https://wolnelektury.pl' + self.get_disable_notifications_url()
361 def save(self, *args, **kwargs):
362 if self.email and not self.notify_key:
363 self.notify_key = get_random_hash(self.email)
364 ret = super(Funding, self).save(*args, **kwargs)
365 self.offer.clear_cache()
369 def notify_funders(cls, subject, template_name, extra_context=None, query_filter=None, payed_only=True):
370 funders = cls.objects.exclude(email="").filter(notifications=True)
372 funders = funders.exclude(completed_at=None)
373 if query_filter is not None:
374 funders = funders.filter(query_filter)
376 for funder in funders:
377 if funder.email in emails:
379 emails.add(funder.email)
380 funder.notify(subject, template_name, extra_context)
382 def notify(self, subject, template_name, extra_context=None):
385 'site': Site.objects.get_current(),
388 context.update(extra_context)
389 with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
391 subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
394 def disable_notifications(self):
395 """Disables all notifications for this e-mail address."""
396 type(self).objects.filter(email=self.email).update(notifications=False)
399 class PayUNotification(club.payu.models.Notification):
400 order = models.ForeignKey(Funding, models.CASCADE, related_name='notification_set')
403 class Spent(models.Model):
404 """ Some of the remaining money spent on a book. """
405 book = models.ForeignKey(Book, models.PROTECT)
406 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
407 timestamp = models.DateField(_('when'))
410 verbose_name = _('money spent on a book')
411 verbose_name_plural = _('money spent on books')
412 ordering = ['-timestamp']
415 return "Spent: %s" % str(self.book)