Funding view
[wolnelektury.git] / src / funding / models.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
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
22 from . import utils
23
24
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)
38
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)
41
42     def cover_img_tag(self):
43         return mark_safe('<img src="%s" />' % self.cover.url)
44     cover_img_tag.short_description = _('Cover preview')
45
46     class Meta:
47         verbose_name = _('offer')
48         verbose_name_plural = _('offers')
49         ordering = ['-end']
50
51     def __str__(self):
52         return "%s - %s" % (self.author, self.title)
53
54     def get_absolute_url(self):
55         return reverse('funding_offer', args=[self.slug])
56
57     def save(self, *args, **kw):
58         published_now = (
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)
62         self.clear_cache()
63         if published_now:
64             self.notify_published()
65         return retval
66
67     def get_payu_payment_title(self):
68         return utils.sanitize_payment_title(str(self))
69
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)
78
79     def is_current(self):
80         return self.start <= date.today() <= self.end and self == self.current()
81
82     def is_win(self):
83         return self.sum() >= self.target
84
85     def remaining(self):
86         if self.is_current():
87             return None
88         if self.is_win():
89             return self.sum() - self.target
90         else:
91             return self.sum()
92
93     @classmethod
94     def current(cls):
95         """ Returns current fundraiser or None.
96
97         Current fundraiser is the one that:
98         - has already started,
99         - hasn't yet ended,
100         - if there's more than one of those, it's the one that ends last.
101
102         """
103         today = date.today()
104         objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end')
105         try:
106             return objects[0]
107         except IndexError:
108             return None
109
110     @classmethod
111     def past(cls):
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)
117         return objects
118
119     @classmethod
120     def public(cls):
121         """ QuerySet for all current and past fundraisers. """
122         today = date.today()
123         return cls.objects.filter(start__lte=today)
124
125     def get_perks(self, amount=None):
126         """ Finds all the perks for the offer.
127
128         If amount is provided, returns the perks you get for it.
129
130         """
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)
136         return perks
137
138     def funding_payed(self):
139         """ QuerySet for all completed payments for the offer. """
140         return Funding.payed().filter(offer=self)
141
142     def funders(self):
143         return self.funding_payed().order_by('-amount', 'completed_at')
144
145     def sum(self):
146         """ The money gathered. """
147         return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
148
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)
153         )
154
155     def notify_end(self, force=False):
156         if not force and self.notified_end:
157             return
158         assert not self.is_current()
159         self.notify_all(
160             _('The fundraiser has ended!'),
161             'funding/email/end.txt', {
162                 'offer': self,
163                 'is_win': self.is_win(),
164                 'remaining': self.remaining(),
165                 'current': self.current(),
166             })
167         self.notified_end = datetime.utcnow().replace(tzinfo=utc)
168         self.save()
169
170     def notify_near(self, force=False):
171         if not force and self.notified_near:
172             return
173         assert self.is_current()
174         sum_ = self.sum()
175         need = self.target - sum_
176         self.notify_all(
177             _('The fundraiser will end soon!'),
178             'funding/email/near.txt', {
179                 'days': (self.end - date.today()).days + 1,
180                 'offer': self,
181                 'is_win': self.is_win(),
182                 'sum': sum_,
183                 'need': need,
184             })
185         self.notified_near = datetime.utcnow().replace(tzinfo=utc)
186         self.save()
187
188     def notify_published(self):
189         assert self.book is not None
190         self.notify_all(
191             _('The book you helped fund has been published.'),
192             'funding/email/published.txt', {
193                 'offer': self,
194                 'book': self.book,
195                 'author': self.book.pretty_title(),
196                 'current': self.current(),
197             })
198
199     def basic_info(self):
200         offer_sum = self.sum()
201         return {
202             'offer': self,
203             'sum': offer_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,
208
209             'show_title': True,
210             'show_title_calling': True,
211         }
212
213     @cached_render('funding/includes/funding.html')
214     def top_bar(self):
215         ctx = self.basic_info()
216         ctx.update({
217             'link': True,
218             'closeable': True,
219             'add_class': 'funding-top-header',
220         })
221         return ctx
222
223     @cached_render('funding/includes/funding.html')
224     def list_bar(self):
225         ctx = self.basic_info()
226         ctx.update({
227             'link': True,
228             'show_title_calling': False,
229         })
230         return ctx
231
232     @cached_render('funding/includes/funding.html')
233     def detail_bar(self):
234         ctx = self.basic_info()
235         ctx.update({
236             'show_title': False,
237         })
238         return ctx
239
240     @cached_render('funding/includes/offer_status.html')
241     def status(self):
242         return {'offer': self}
243
244     @cached_render('funding/includes/offer_status_more.html')
245     def status_more(self):
246         return {'offer': self}
247
248     @cached_render('funding/2022/includes/funding.html')
249     def top_bar_2022(self):
250         ctx = self.basic_info()
251         ctx.update({
252             'link': True,
253             'closeable': True,
254             'add_class': 'funding-top-header',
255         })
256         return ctx
257
258     @cached_render('funding/2022/includes/funding.html')
259     def detail_bar_2022(self):
260         ctx = self.basic_info()
261         ctx.update({
262             'show_title': False,
263         })
264         return ctx
265
266
267 class Perk(models.Model):
268     """ A perk offer.
269
270     If no attached to a particular Offer, applies to all.
271
272     """
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)
278
279     class Meta:
280         verbose_name = _('perk')
281         verbose_name_plural = _('perks')
282         ordering = ['-price']
283
284     def __str__(self):
285         return "%s (%s%s)" % (self.name, self.price, " for %s" % self.offer if self.offer else "")
286
287
288 class Funding(club.payu.models.Order):
289     """ A person paying in a fundraiser.
290
291     The payment was completed if and only if completed_at is set.
292
293     """
294     offer = models.ForeignKey(Offer, models.PROTECT, verbose_name=_('offer'))
295     customer_ip = models.GenericIPAddressField(_('customer IP'), null=True)
296     
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)
305
306     class Meta:
307         verbose_name = _('funding')
308         verbose_name_plural = _('fundings')
309         ordering = ['-completed_at', 'pk']
310
311     @classmethod
312     def payed(cls):
313         """ QuerySet for all completed payments. """
314         return cls.objects.exclude(completed_at=None)
315
316     def __str__(self):
317         return str(self.offer)
318
319     def get_amount(self):
320         return self.amount
321
322     def get_buyer(self):
323         return {
324             "email": self.email,
325             "language": self.language_code,
326         }
327
328     def get_description(self):
329         return self.offer.get_payu_payment_title()
330
331     def get_thanks_url(self):
332         return reverse('funding_thanks')
333
334     def status_updated(self):
335         if self.status == 'COMPLETED':
336             if self.email:
337                 self.notify(
338                     _('Thank you for your support!'),
339                     'funding/email/thanks.txt'
340                 )
341
342     def get_notify_url(self):
343         return "https://{}{}".format(
344             Site.objects.get_current().domain,
345             reverse('funding_payu_notify', args=[self.pk]))
346
347     def perk_names(self):
348         return ", ".join(perk.name for perk in self.perks.all())
349
350     def get_disable_notifications_url(self):
351         return "%s?%s" % (
352             reverse("funding_disable_notifications"),
353             urlencode({
354                 'email': self.email,
355                 'key': self.notify_key,
356             }))
357
358     def wl_optout_url(self):
359         return 'https://wolnelektury.pl' + self.get_disable_notifications_url()
360
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()
366         return ret
367
368     @classmethod
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)
371         if payed_only:
372             funders = funders.exclude(completed_at=None)
373         if query_filter is not None:
374             funders = funders.filter(query_filter)
375         emails = set()
376         for funder in funders:
377             if funder.email in emails:
378                 continue
379             emails.add(funder.email)
380             funder.notify(subject, template_name, extra_context)
381
382     def notify(self, subject, template_name, extra_context=None):
383         context = {
384             'funding': self,
385             'site': Site.objects.get_current(),
386         }
387         if extra_context:
388             context.update(extra_context)
389         with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
390             send_mail(
391                 subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
392                 fail_silently=False)
393
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)
397
398
399 class PayUNotification(club.payu.models.Notification):
400     order = models.ForeignKey(Funding, models.CASCADE, related_name='notification_set')
401
402
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'))
408
409     class Meta:
410         verbose_name = _('money spent on a book')
411         verbose_name_plural = _('money spent on books')
412         ordering = ['-timestamp']
413
414     def __str__(self):
415         return "Spent: %s" % str(self.book)
416