1 # -*- coding: utf-8 -*-
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 import urlencode
7 from django.conf import settings
8 from django.contrib.sites.models import Site
9 from django.core.urlresolvers import reverse
10 from django.core.mail import send_mail
11 from django.db import models
12 from django.dispatch import receiver
13 from django.template.loader import render_to_string
14 from django.utils.timezone import utc
15 from django.utils.translation import ugettext_lazy as _, override
17 from ssify import flush_ssi_includes
18 from catalogue.models import Book
19 from catalogue.utils import get_random_hash
20 from polls.models import Poll
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, 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 u'<img src="%s" />' % self.cover.url
43 cover_img_tag.short_description = _('Cover preview')
44 cover_img_tag.allow_tags = True
47 verbose_name = _('offer')
48 verbose_name_plural = _('offers')
51 def __unicode__(self):
52 return u"%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 flush_includes(self):
69 template % (self.pk, lang)
71 '/wesprzyj/o/%d/top-bar.%s.html',
72 '/wesprzyj/o/%d/detail-bar.%s.html',
73 '/wesprzyj/o/%d/list-bar.%s.html',
74 '/wesprzyj/o/%d/status.%s.html',
75 '/wesprzyj/o/%d/status-more.%s.html',
77 '/wesprzyj/o/%%d/fundings/%d.%%s.html' % page
78 for page in range(1, len(self.funding_payed()) // 10 + 2)
80 for lang in [lc for (lc, _ln) in settings.LANGUAGES]
84 return self.start <= date.today() <= self.end and self == self.current()
87 return self.sum() >= self.target
93 return self.sum() - self.target
99 """ Returns current fundraiser or None.
101 Current fundraiser is the one that:
102 - has already started,
104 - if there's more than one of those, it's the one that ends last.
108 objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end')
116 """ QuerySet for all past fundraisers. """
117 objects = cls.public()
118 current = cls.current()
119 if current is not None:
120 objects = objects.exclude(pk=current.pk)
125 """ QuerySet for all current and past fundraisers. """
127 return cls.objects.filter(start__lte=today)
129 def get_perks(self, amount=None):
130 """ Finds all the perks for the offer.
132 If amount is provided, returns the perks you get for it.
135 perks = Perk.objects.filter(
136 models.Q(offer=self) | models.Q(offer=None)
137 ).exclude(end_date__lt=date.today())
138 if amount is not None:
139 perks = perks.filter(price__lte=amount)
142 def funding_payed(self):
143 """ QuerySet for all completed payments for the offer. """
144 return Funding.payed().filter(offer=self)
147 return self.funding_payed().order_by('-amount', 'payed_at')
150 """ The money gathered. """
151 return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
153 def notify_all(self, subject, template_name, extra_context=None):
154 Funding.notify_funders(
155 subject, template_name, extra_context,
156 query_filter=models.Q(offer=self)
159 def notify_end(self, force=False):
160 if not force and self.notified_end:
162 assert not self.is_current()
164 _('The fundraiser has ended!'),
165 'funding/email/end.txt', {
167 'is_win': self.is_win(),
168 'remaining': self.remaining(),
169 'current': self.current(),
171 self.notified_end = datetime.utcnow().replace(tzinfo=utc)
174 def notify_near(self, force=False):
175 if not force and self.notified_near:
177 assert self.is_current()
179 need = self.target - sum_
181 _('The fundraiser will end soon!'),
182 'funding/email/near.txt', {
183 'days': (self.end - date.today()).days + 1,
185 'is_win': self.is_win(),
189 self.notified_near = datetime.utcnow().replace(tzinfo=utc)
192 def notify_published(self):
193 assert self.book is not None
195 _('The book you helped fund has been published.'),
196 'funding/email/published.txt', {
199 'author': self.book.pretty_title(),
200 'current': self.current(),
204 class Perk(models.Model):
207 If no attached to a particular Offer, applies to all.
210 offer = models.ForeignKey(Offer, verbose_name=_('offer'), null=True, blank=True)
211 price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
212 name = models.CharField(_('name'), max_length=255)
213 long_name = models.CharField(_('long name'), max_length=255)
214 end_date = models.DateField(_('end date'), null=True, blank=True)
217 verbose_name = _('perk')
218 verbose_name_plural = _('perks')
219 ordering = ['-price']
221 def __unicode__(self):
222 return "%s (%s%s)" % (self.name, self.price, u" for %s" % self.offer if self.offer else "")
225 class Funding(models.Model):
226 """ A person paying in a fundraiser.
228 The payment was completed if and only if payed_at is set.
231 offer = models.ForeignKey(Offer, verbose_name=_('offer'))
232 name = models.CharField(_('name'), max_length=127, blank=True)
233 email = models.EmailField(_('email'), blank=True, db_index=True)
234 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
235 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
236 perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
237 language_code = models.CharField(max_length=2, null=True, blank=True)
238 notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
239 notify_key = models.CharField(max_length=32)
242 verbose_name = _('funding')
243 verbose_name_plural = _('fundings')
244 ordering = ['-payed_at']
248 """ QuerySet for all completed payments. """
249 return cls.objects.exclude(payed_at=None)
251 def __unicode__(self):
252 return unicode(self.offer)
254 def get_absolute_url(self):
255 return reverse('funding_funding', args=[self.pk])
257 def perk_names(self):
258 return ", ".join(perk.name for perk in self.perks.all())
260 def get_disable_notifications_url(self):
262 reverse("funding_disable_notifications"),
265 'key': self.notify_key,
268 def save(self, *args, **kwargs):
269 if self.email and not self.notify_key:
270 self.notify_key = get_random_hash(self.email)
271 ret = super(Funding, self).save(*args, **kwargs)
272 self.offer.flush_includes()
276 def notify_funders(cls, subject, template_name, extra_context=None, query_filter=None, payed_only=True):
277 funders = cls.objects.exclude(email="").filter(notifications=True)
279 funders = funders.exclude(payed_at=None)
280 if query_filter is not None:
281 funders = funders.filter(query_filter)
283 for funder in funders:
284 if funder.email in emails:
286 emails.add(funder.email)
287 funder.notify(subject, template_name, extra_context)
289 def notify(self, subject, template_name, extra_context=None):
292 'site': Site.objects.get_current(),
295 context.update(extra_context)
296 with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
298 subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
301 def disable_notifications(self):
302 """Disables all notifications for this e-mail address."""
303 type(self).objects.filter(email=self.email).update(notifications=False)
306 # Register the Funding model with django-getpaid for payments.
307 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
310 class Spent(models.Model):
311 """ Some of the remaining money spent on a book. """
312 book = models.ForeignKey(Book)
313 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
314 timestamp = models.DateField(_('when'))
317 verbose_name = _('money spent on a book')
318 verbose_name_plural = _('money spent on books')
319 ordering = ['-timestamp']
321 def __unicode__(self):
322 return u"Spent: %s" % unicode(self.book)
325 @receiver(getpaid.signals.new_payment_query)
326 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
327 """ Set payment details for getpaid. """
328 payment.amount = order.amount
329 payment.currency = 'PLN'
332 @receiver(getpaid.signals.user_data_query)
333 def user_data_query_listener(sender, order, user_data, **kwargs):
334 """ Set user data for payment. """
335 user_data['email'] = order.email
338 @receiver(getpaid.signals.payment_status_changed)
339 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
340 """ React to status changes from getpaid. """
341 if old_status != 'paid' and new_status == 'paid':
342 instance.order.payed_at = datetime.utcnow().replace(tzinfo=utc)
343 instance.order.save()
344 if instance.order.email:
345 instance.order.notify(
346 _('Thank you for your support!'),
347 'funding/email/thanks.txt'