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.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': min(100, 100 * offer_sum / self.target),
208 'show_title_calling': True,
211 @cached_render('funding/includes/offer_status.html')
213 return {'offer': self}
215 @cached_render('funding/includes/offer_status_more.html')
216 def status_more(self):
217 return {'offer': self}
219 @cached_render('funding/includes/funding.html')
221 ctx = self.basic_info()
225 'add_class': 'funding-top-header',
229 @cached_render('funding/includes/funding.html')
230 def detail_bar(self):
231 ctx = self.basic_info()
238 class Perk(models.Model):
241 If no attached to a particular Offer, applies to all.
244 offer = models.ForeignKey(Offer, models.CASCADE, verbose_name=_('offer'), null=True, blank=True)
245 price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
246 name = models.CharField(_('name'), max_length=255)
247 long_name = models.CharField(_('long name'), max_length=255)
248 end_date = models.DateField(_('end date'), null=True, blank=True)
251 verbose_name = _('perk')
252 verbose_name_plural = _('perks')
253 ordering = ['-price']
256 return "%s (%s%s)" % (self.name, self.price, " for %s" % self.offer if self.offer else "")
259 class Funding(club.payu.models.Order):
260 """ A person paying in a fundraiser.
262 The payment was completed if and only if completed_at is set.
265 offer = models.ForeignKey(Offer, models.PROTECT, verbose_name=_('offer'))
266 customer_ip = models.GenericIPAddressField(_('customer IP'), null=True)
268 name = models.CharField(_('name'), max_length=127, blank=True)
269 email = models.EmailField(_('email'), blank=True, db_index=True)
270 user = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True)
271 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
272 perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
273 language_code = models.CharField(max_length=2, null=True, blank=True)
274 notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
275 notify_key = models.CharField(max_length=32)
278 verbose_name = _('funding')
279 verbose_name_plural = _('fundings')
280 ordering = ['-completed_at', 'pk']
284 """ QuerySet for all completed payments. """
285 return cls.objects.exclude(completed_at=None)
288 return str(self.offer)
290 def get_amount(self):
296 "language": self.language_code,
299 def get_description(self):
300 return self.offer.get_payu_payment_title()
302 def get_thanks_url(self):
303 return reverse('funding_thanks')
305 def status_updated(self):
306 if self.status == 'COMPLETED':
309 _('Thank you for your support!'),
310 'funding/email/thanks.txt'
313 def get_notify_url(self):
314 return "https://{}{}".format(
315 Site.objects.get_current().domain,
316 reverse('funding_payu_notify', args=[self.pk]))
318 def perk_names(self):
319 return ", ".join(perk.name for perk in self.perks.all())
321 def get_disable_notifications_url(self):
323 reverse("funding_disable_notifications"),
326 'key': self.notify_key,
329 def wl_optout_url(self):
330 return 'https://wolnelektury.pl' + self.get_disable_notifications_url()
332 def save(self, *args, **kwargs):
333 if self.email and not self.notify_key:
334 self.notify_key = get_random_hash(self.email)
335 ret = super(Funding, self).save(*args, **kwargs)
336 self.offer.clear_cache()
340 def notify_funders(cls, subject, template_name, extra_context=None, query_filter=None, payed_only=True):
341 funders = cls.objects.exclude(email="").filter(notifications=True)
343 funders = funders.exclude(completed_at=None)
344 if query_filter is not None:
345 funders = funders.filter(query_filter)
347 for funder in funders:
348 if funder.email in emails:
350 emails.add(funder.email)
351 funder.notify(subject, template_name, extra_context)
353 def notify(self, subject, template_name, extra_context=None):
356 'site': Site.objects.get_current(),
359 context.update(extra_context)
360 with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
362 subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
365 def disable_notifications(self):
366 """Disables all notifications for this e-mail address."""
367 type(self).objects.filter(email=self.email).update(notifications=False)
370 class PayUNotification(club.payu.models.Notification):
371 order = models.ForeignKey(Funding, models.CASCADE, related_name='notification_set')
374 class Spent(models.Model):
375 """ Some of the remaining money spent on a book. """
376 book = models.ForeignKey(Book, models.PROTECT)
377 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
378 timestamp = models.DateField(_('when'))
381 verbose_name = _('money spent on a book')
382 verbose_name_plural = _('money spent on books')
383 ordering = ['-timestamp']
386 return "Spent: %s" % str(self.book)