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.timezone import utc
14 from django.utils.translation import ugettext_lazy as _, override
16 from ssify import flush_ssi_includes
17 from catalogue.models import Book
18 from catalogue.utils import get_random_hash
19 from polls.models import Poll
20 from . import app_settings
23 class Offer(models.Model):
24 """ A fundraiser for a particular book. """
25 author = models.CharField(_('author'), max_length=255)
26 title = models.CharField(_('title'), max_length=255)
27 slug = models.SlugField(_('slug'))
28 description = models.TextField(_('description'), blank=True)
29 target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
30 start = models.DateField(_('start'), db_index=True)
31 end = models.DateField(_('end'), db_index=True)
32 redakcja_url = models.URLField(_('redakcja URL'), blank=True)
33 book = models.ForeignKey(Book, models.PROTECT, null=True, blank=True, help_text=_('Published book.'))
34 cover = models.ImageField(_('Cover'), upload_to='funding/covers')
35 poll = models.ForeignKey(Poll, help_text=_('Poll'), null=True, blank=True, on_delete=models.SET_NULL)
37 notified_near = models.DateTimeField(_('Near-end notifications sent'), blank=True, null=True)
38 notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True)
40 def cover_img_tag(self):
41 return u'<img src="%s" />' % self.cover.url
42 cover_img_tag.short_description = _('Cover preview')
43 cover_img_tag.allow_tags = True
46 verbose_name = _('offer')
47 verbose_name_plural = _('offers')
51 return u"%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 flush_includes(self):
68 template % (self.pk, lang)
70 '/wesprzyj/o/%d/top-bar.%s.html',
71 '/wesprzyj/o/%d/detail-bar.%s.html',
72 '/wesprzyj/o/%d/list-bar.%s.html',
73 '/wesprzyj/o/%d/status.%s.html',
74 '/wesprzyj/o/%d/status-more.%s.html',
76 '/wesprzyj/o/%%d/fundings/%d.%%s.html' % page
77 for page in range(1, len(self.funding_payed()) // 10 + 2)
79 for lang in [lc for (lc, _ln) in settings.LANGUAGES]
83 return self.start <= date.today() <= self.end and self == self.current()
86 return self.sum() >= self.target
92 return self.sum() - self.target
98 """ Returns current fundraiser or None.
100 Current fundraiser is the one that:
101 - has already started,
103 - if there's more than one of those, it's the one that ends last.
107 objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end')
115 """ QuerySet for all past fundraisers. """
116 objects = cls.public()
117 current = cls.current()
118 if current is not None:
119 objects = objects.exclude(pk=current.pk)
124 """ QuerySet for all current and past fundraisers. """
126 return cls.objects.filter(start__lte=today)
128 def get_perks(self, amount=None):
129 """ Finds all the perks for the offer.
131 If amount is provided, returns the perks you get for it.
134 perks = Perk.objects.filter(
135 models.Q(offer=self) | models.Q(offer=None)
136 ).exclude(end_date__lt=date.today())
137 if amount is not None:
138 perks = perks.filter(price__lte=amount)
141 def funding_payed(self):
142 """ QuerySet for all completed payments for the offer. """
143 return Funding.payed().filter(offer=self)
146 return self.funding_payed().order_by('-amount', 'payed_at')
149 """ The money gathered. """
150 return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
152 def notify_all(self, subject, template_name, extra_context=None):
153 Funding.notify_funders(
154 subject, template_name, extra_context,
155 query_filter=models.Q(offer=self)
158 def notify_end(self, force=False):
159 if not force and self.notified_end:
161 assert not self.is_current()
163 _('The fundraiser has ended!'),
164 'funding/email/end.txt', {
166 'is_win': self.is_win(),
167 'remaining': self.remaining(),
168 'current': self.current(),
170 self.notified_end = datetime.utcnow().replace(tzinfo=utc)
173 def notify_near(self, force=False):
174 if not force and self.notified_near:
176 assert self.is_current()
178 need = self.target - sum_
180 _('The fundraiser will end soon!'),
181 'funding/email/near.txt', {
182 'days': (self.end - date.today()).days + 1,
184 'is_win': self.is_win(),
188 self.notified_near = datetime.utcnow().replace(tzinfo=utc)
191 def notify_published(self):
192 assert self.book is not None
194 _('The book you helped fund has been published.'),
195 'funding/email/published.txt', {
198 'author': self.book.pretty_title(),
199 'current': self.current(),
203 class Perk(models.Model):
206 If no attached to a particular Offer, applies to all.
209 offer = models.ForeignKey(Offer, models.CASCADE, verbose_name=_('offer'), null=True, blank=True)
210 price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
211 name = models.CharField(_('name'), max_length=255)
212 long_name = models.CharField(_('long name'), max_length=255)
213 end_date = models.DateField(_('end date'), null=True, blank=True)
216 verbose_name = _('perk')
217 verbose_name_plural = _('perks')
218 ordering = ['-price']
221 return "%s (%s%s)" % (self.name, self.price, u" for %s" % self.offer if self.offer else "")
224 class Funding(models.Model):
225 """ A person paying in a fundraiser.
227 The payment was completed if and only if payed_at is set.
230 offer = models.ForeignKey(Offer, models.PROTECT, verbose_name=_('offer'))
231 name = models.CharField(_('name'), max_length=127, blank=True)
232 email = models.EmailField(_('email'), blank=True, db_index=True)
233 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
234 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
235 perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
236 language_code = models.CharField(max_length=2, null=True, blank=True)
237 notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
238 notify_key = models.CharField(max_length=32)
241 verbose_name = _('funding')
242 verbose_name_plural = _('fundings')
243 ordering = ['-payed_at', 'pk']
247 """ QuerySet for all completed payments. """
248 return cls.objects.exclude(payed_at=None)
251 return str(self.offer)
253 def get_absolute_url(self):
254 return reverse('funding_funding', args=[self.pk])
256 def perk_names(self):
257 return ", ".join(perk.name for perk in self.perks.all())
259 def get_disable_notifications_url(self):
261 reverse("funding_disable_notifications"),
264 'key': self.notify_key,
267 def save(self, *args, **kwargs):
268 if self.email and not self.notify_key:
269 self.notify_key = get_random_hash(self.email)
270 ret = super(Funding, self).save(*args, **kwargs)
271 self.offer.flush_includes()
275 def notify_funders(cls, subject, template_name, extra_context=None, query_filter=None, payed_only=True):
276 funders = cls.objects.exclude(email="").filter(notifications=True)
278 funders = funders.exclude(payed_at=None)
279 if query_filter is not None:
280 funders = funders.filter(query_filter)
282 for funder in funders:
283 if funder.email in emails:
285 emails.add(funder.email)
286 funder.notify(subject, template_name, extra_context)
288 def notify(self, subject, template_name, extra_context=None):
291 'site': Site.objects.get_current(),
294 context.update(extra_context)
295 with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
297 subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
300 def disable_notifications(self):
301 """Disables all notifications for this e-mail address."""
302 type(self).objects.filter(email=self.email).update(notifications=False)
305 # Register the Funding model with django-getpaid for payments.
306 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
309 class Spent(models.Model):
310 """ Some of the remaining money spent on a book. """
311 book = models.ForeignKey(Book, models.PROTECT)
312 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
313 timestamp = models.DateField(_('when'))
316 verbose_name = _('money spent on a book')
317 verbose_name_plural = _('money spent on books')
318 ordering = ['-timestamp']
321 return u"Spent: %s" % str(self.book)
324 @receiver(getpaid.signals.new_payment_query)
325 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
326 """ Set payment details for getpaid. """
327 payment.amount = order.amount
328 payment.currency = 'PLN'
331 @receiver(getpaid.signals.user_data_query)
332 def user_data_query_listener(sender, order, user_data, **kwargs):
333 """ Set user data for payment. """
334 user_data['email'] = order.email
337 @receiver(getpaid.signals.payment_status_changed)
338 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
339 """ React to status changes from getpaid. """
340 if old_status != 'paid' and new_status == 'paid':
341 instance.order.payed_at = datetime.utcnow().replace(tzinfo=utc)
342 instance.order.save()
343 if instance.order.email:
344 instance.order.notify(
345 _('Thank you for your support!'),
346 'funding/email/thanks.txt'