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 ugettext_lazy as _, override
 
  17 from catalogue.models import Book
 
  18 from catalogue.utils import get_random_hash
 
  19 from polls.models import Poll
 
  20 from wolnelektury.utils import cached_render, clear_cached_renders
 
  21 from . import app_settings
 
  24 class Offer(models.Model):
 
  25     """ A fundraiser for a particular book. """
 
  26     author = models.CharField(_('author'), max_length=255)
 
  27     title = models.CharField(_('title'), max_length=255)
 
  28     slug = models.SlugField(_('slug'))
 
  29     description = models.TextField(_('description'), blank=True)
 
  30     target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
 
  31     start = models.DateField(_('start'), db_index=True)
 
  32     end = models.DateField(_('end'), db_index=True)
 
  33     redakcja_url = models.URLField(_('redakcja URL'), blank=True)
 
  34     book = models.ForeignKey(Book, models.PROTECT, null=True, blank=True, help_text=_('Published book.'))
 
  35     cover = models.ImageField(_('Cover'), upload_to='funding/covers')
 
  36     poll = models.ForeignKey(Poll, help_text=_('Poll'), null=True, blank=True, on_delete=models.SET_NULL)
 
  38     notified_near = models.DateTimeField(_('Near-end notifications sent'), blank=True, null=True)
 
  39     notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True)
 
  41     def cover_img_tag(self):
 
  42         return mark_safe('<img src="%s" />' % self.cover.url)
 
  43     cover_img_tag.short_description = _('Cover preview')
 
  46         verbose_name = _('offer')
 
  47         verbose_name_plural = _('offers')
 
  51         return "%s - %s" % (self.author, self.title)
 
  53     def get_absolute_url(self):
 
  54         return reverse('funding_offer', args=[self.slug])
 
  56     def save(self, *args, **kw):
 
  58             self.book_id is not None and self.pk is not None and
 
  59             type(self).objects.values('book').get(pk=self.pk)['book'] != self.book_id)
 
  60         retval = super(Offer, self).save(*args, **kw)
 
  63             self.notify_published()
 
  66     def clear_cache(self):
 
  67         clear_cached_renders(self.top_bar)
 
  68         clear_cached_renders(self.list_bar)
 
  69         clear_cached_renders(self.detail_bar)
 
  70         clear_cached_renders(self.status)
 
  71         clear_cached_renders(self.status_more)
 
  74         return self.start <= date.today() <= self.end and self == self.current()
 
  77         return self.sum() >= self.target
 
  83             return self.sum() - self.target
 
  89         """ Returns current fundraiser or None.
 
  91         Current fundraiser is the one that:
 
  92         - has already started,
 
  94         - if there's more than one of those, it's the one that ends last.
 
  98         objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end')
 
 106         """ QuerySet for all past fundraisers. """
 
 107         objects = cls.public()
 
 108         current = cls.current()
 
 109         if current is not None:
 
 110             objects = objects.exclude(pk=current.pk)
 
 115         """ QuerySet for all current and past fundraisers. """
 
 117         return cls.objects.filter(start__lte=today)
 
 119     def get_perks(self, amount=None):
 
 120         """ Finds all the perks for the offer.
 
 122         If amount is provided, returns the perks you get for it.
 
 125         perks = Perk.objects.filter(
 
 126                 models.Q(offer=self) | models.Q(offer=None)
 
 127             ).exclude(end_date__lt=date.today())
 
 128         if amount is not None:
 
 129             perks = perks.filter(price__lte=amount)
 
 132     def funding_payed(self):
 
 133         """ QuerySet for all completed payments for the offer. """
 
 134         return Funding.payed().filter(offer=self)
 
 137         return self.funding_payed().order_by('-amount', 'payed_at')
 
 140         """ The money gathered. """
 
 141         return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
 
 143     def notify_all(self, subject, template_name, extra_context=None):
 
 144         Funding.notify_funders(
 
 145             subject, template_name, extra_context,
 
 146             query_filter=models.Q(offer=self)
 
 149     def notify_end(self, force=False):
 
 150         if not force and self.notified_end:
 
 152         assert not self.is_current()
 
 154             _('The fundraiser has ended!'),
 
 155             'funding/email/end.txt', {
 
 157                 'is_win': self.is_win(),
 
 158                 'remaining': self.remaining(),
 
 159                 'current': self.current(),
 
 161         self.notified_end = datetime.utcnow().replace(tzinfo=utc)
 
 164     def notify_near(self, force=False):
 
 165         if not force and self.notified_near:
 
 167         assert self.is_current()
 
 169         need = self.target - sum_
 
 171             _('The fundraiser will end soon!'),
 
 172             'funding/email/near.txt', {
 
 173                 'days': (self.end - date.today()).days + 1,
 
 175                 'is_win': self.is_win(),
 
 179         self.notified_near = datetime.utcnow().replace(tzinfo=utc)
 
 182     def notify_published(self):
 
 183         assert self.book is not None
 
 185             _('The book you helped fund has been published.'),
 
 186             'funding/email/published.txt', {
 
 189                 'author': self.book.pretty_title(),
 
 190                 'current': self.current(),
 
 193     def basic_info(self):
 
 194         offer_sum = self.sum()
 
 198             'is_current': self.is_current(),
 
 199             'is_win': offer_sum >= self.target,
 
 200             'missing': self.target - offer_sum,
 
 201             'percentage': 100 * offer_sum / self.target,
 
 204             'show_title_calling': True,
 
 207     @cached_render('funding/includes/funding.html')
 
 209         ctx = self.basic_info()
 
 213             'add_class': 'funding-top-header',
 
 217     @cached_render('funding/includes/funding.html')
 
 219         ctx = self.basic_info()
 
 222             'show_title_calling': False,
 
 226     @cached_render('funding/includes/funding.html')
 
 227     def detail_bar(self):
 
 228         ctx = self.basic_info()
 
 234     @cached_render('funding/includes/offer_status.html')
 
 236         return {'offer': self}
 
 238     @cached_render('funding/includes/offer_status_more.html')
 
 239     def status_more(self):
 
 240         return {'offer': self}
 
 243 class Perk(models.Model):
 
 246     If no attached to a particular Offer, applies to all.
 
 249     offer = models.ForeignKey(Offer, models.CASCADE, verbose_name=_('offer'), null=True, blank=True)
 
 250     price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
 
 251     name = models.CharField(_('name'), max_length=255)
 
 252     long_name = models.CharField(_('long name'), max_length=255)
 
 253     end_date = models.DateField(_('end date'), null=True, blank=True)
 
 256         verbose_name = _('perk')
 
 257         verbose_name_plural = _('perks')
 
 258         ordering = ['-price']
 
 261         return "%s (%s%s)" % (self.name, self.price, " for %s" % self.offer if self.offer else "")
 
 264 class Funding(models.Model):
 
 265     """ A person paying in a fundraiser.
 
 267     The payment was completed if and only if payed_at is set.
 
 270     offer = models.ForeignKey(Offer, models.PROTECT, verbose_name=_('offer'))
 
 271     name = models.CharField(_('name'), max_length=127, blank=True)
 
 272     email = models.EmailField(_('email'), blank=True, db_index=True)
 
 273     user = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True)
 
 274     amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
 
 275     payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
 
 276     perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
 
 277     language_code = models.CharField(max_length=2, null=True, blank=True)
 
 278     notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
 
 279     notify_key = models.CharField(max_length=32)
 
 282         verbose_name = _('funding')
 
 283         verbose_name_plural = _('fundings')
 
 284         ordering = ['-payed_at', 'pk']
 
 288         """ QuerySet for all completed payments. """
 
 289         return cls.objects.exclude(payed_at=None)
 
 292         return str(self.offer)
 
 294     def get_absolute_url(self):
 
 295         return reverse('funding_funding', args=[self.pk])
 
 297     def perk_names(self):
 
 298         return ", ".join(perk.name for perk in self.perks.all())
 
 300     def get_disable_notifications_url(self):
 
 302             reverse("funding_disable_notifications"),
 
 305                 'key': self.notify_key,
 
 308     def wl_optout_url(self):
 
 309         return 'https://wolnelektury.pl' + self.get_disable_notifications_url()
 
 311     def save(self, *args, **kwargs):
 
 312         if self.email and not self.notify_key:
 
 313             self.notify_key = get_random_hash(self.email)
 
 314         ret = super(Funding, self).save(*args, **kwargs)
 
 315         self.offer.clear_cache()
 
 319     def notify_funders(cls, subject, template_name, extra_context=None, query_filter=None, payed_only=True):
 
 320         funders = cls.objects.exclude(email="").filter(notifications=True)
 
 322             funders = funders.exclude(payed_at=None)
 
 323         if query_filter is not None:
 
 324             funders = funders.filter(query_filter)
 
 326         for funder in funders:
 
 327             if funder.email in emails:
 
 329             emails.add(funder.email)
 
 330             funder.notify(subject, template_name, extra_context)
 
 332     def notify(self, subject, template_name, extra_context=None):
 
 335             'site': Site.objects.get_current(),
 
 338             context.update(extra_context)
 
 339         with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
 
 341                 subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
 
 344     def disable_notifications(self):
 
 345         """Disables all notifications for this e-mail address."""
 
 346         type(self).objects.filter(email=self.email).update(notifications=False)
 
 349 # Register the Funding model with django-getpaid for payments.
 
 350 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
 
 353 class Spent(models.Model):
 
 354     """ Some of the remaining money spent on a book. """
 
 355     book = models.ForeignKey(Book, models.PROTECT)
 
 356     amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
 
 357     timestamp = models.DateField(_('when'))
 
 360         verbose_name = _('money spent on a book')
 
 361         verbose_name_plural = _('money spent on books')
 
 362         ordering = ['-timestamp']
 
 365         return "Spent: %s" % str(self.book)
 
 368 @receiver(getpaid.signals.new_payment_query)
 
 369 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
 
 370     """ Set payment details for getpaid. """
 
 371     payment.amount = order.amount
 
 372     payment.currency = 'PLN'
 
 375 @receiver(getpaid.signals.user_data_query)
 
 376 def user_data_query_listener(sender, order, user_data, **kwargs):
 
 377     """ Set user data for payment. """
 
 378     user_data['email'] = order.email
 
 381 @receiver(getpaid.signals.payment_status_changed)
 
 382 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
 
 383     """ React to status changes from getpaid. """
 
 384     if old_status != 'paid' and new_status == 'paid':
 
 385         instance.order.payed_at = datetime.utcnow().replace(tzinfo=utc)
 
 386         instance.order.save()
 
 387         if instance.order.email:
 
 388             instance.order.notify(
 
 389                 _('Thank you for your support!'),
 
 390                 'funding/email/thanks.txt'