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.core.urlresolvers import reverse
8 from django.core.mail import send_mail
9 from django.conf import settings
10 from django.template.loader import render_to_string
11 from django.db import models
12 from django.utils.translation import ugettext_lazy as _, ugettext, override
14 from catalogue.models import Book
15 from catalogue.utils import get_random_hash
16 from polls.models import Poll
17 from django.contrib.sites.models import Site
20 class Offer(models.Model):
21 """ A fundraiser for a particular book. """
22 author = models.CharField(_('author'), max_length=255)
23 title = models.CharField(_('title'), max_length=255)
24 slug = models.SlugField(_('slug'))
25 description = models.TextField(_('description'), blank=True)
26 target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
27 start = models.DateField(_('start'), db_index=True)
28 end = models.DateField(_('end'), db_index=True)
29 due = models.DateField(_('due'),
30 help_text=_('When will it be published if the money is raised.'))
31 redakcja_url = models.URLField(_('redakcja URL'), blank=True)
32 book = models.ForeignKey(Book, null=True, blank=True,
33 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 def cover_img_tag(self):
38 return u'<img src="%s" />' % self.cover.url
39 cover_img_tag.short_description = _('Cover preview')
40 cover_img_tag.allow_tags = True
43 verbose_name = _('offer')
44 verbose_name_plural = _('offers')
47 def __unicode__(self):
48 return u"%s - %s" % (self.author, self.title)
50 def get_absolute_url(self):
51 return reverse('funding_offer', args=[self.slug])
53 def save(self, *args, **kw):
54 published_now = (self.book_id is not None and
55 self.pk is not None and
56 type(self).objects.values('book').get(pk=self.pk)['book'] != self.book_id)
57 retval = super(Offer, self).save(*args, **kw)
59 self.notify_published()
63 return self.start <= date.today() <= self.end
66 return self.sum() >= self.target
72 return self.sum() - self.target
78 """ Returns current fundraiser or None. """
80 objects = cls.objects.filter(start__lte=today, end__gte=today)
88 """ QuerySet for all current and past fundraisers. """
90 return cls.objects.filter(end__lt=today)
94 """ QuerySet for all current and past fundraisers. """
96 return cls.objects.filter(start__lte=today)
98 def get_perks(self, amount=None):
99 """ Finds all the perks for the offer.
101 If amount is provided, returns the perks you get for it.
104 perks = Perk.objects.filter(
105 models.Q(offer=self) | models.Q(offer=None)
106 ).exclude(end_date__lt=date.today())
107 if amount is not None:
108 perks = perks.filter(price__lte=amount)
111 def funding_payed(self):
112 """ QuerySet for all completed payments for the offer. """
113 return Funding.payed().filter(offer=self)
116 """ The money gathered. """
117 return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
119 def notify_all(self, subject, template_name, extra_context=None):
120 Funding.notify_funders(
121 subject, template_name, extra_context,
122 query_filter=models.Q(offer=self)
125 def notify_end(self):
126 assert not self.is_current()
128 _('The fundraiser has ended!'),
129 'funding/email/end.txt', {
131 'is_win': self.is_win(),
132 'remaining': self.remaining(),
133 'current': self.current(),
136 def notify_near(self):
137 assert self.is_current()
139 need = self.target - sum_
141 _('The fundraiser will end soon!'),
142 'funding/email/near.txt', {
143 'days': (self.end - date.today()).days + 1,
145 'is_win': self.is_win(),
150 def notify_published(self):
151 assert self.book is not None
153 _('The book you helped fund has been published.'),
154 'funding/email/published.txt', {
157 'author': ", ".join(a[0] for a in self.book.related_info()['tags']['author']),
158 'current': self.current(),
162 class Perk(models.Model):
165 If no attached to a particular Offer, applies to all.
168 offer = models.ForeignKey(Offer, verbose_name=_('offer'), null=True, blank=True)
169 price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
170 name = models.CharField(_('name'), max_length=255)
171 long_name = models.CharField(_('long name'), max_length=255)
172 end_date = models.DateField(_('end date'), null=True, blank=True)
175 verbose_name = _('perk')
176 verbose_name_plural = _('perks')
177 ordering = ['-price']
179 def __unicode__(self):
180 return "%s (%s%s)" % (self.name, self.price, u" for %s" % self.offer if self.offer else "")
183 class Funding(models.Model):
184 """ A person paying in a fundraiser.
186 The payment was completed if and only if payed_at is set.
189 offer = models.ForeignKey(Offer, verbose_name=_('offer'))
190 name = models.CharField(_('name'), max_length=127, blank=True)
191 email = models.EmailField(_('email'), blank=True, db_index=True)
192 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
193 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
194 perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
195 language_code = models.CharField(max_length = 2, null = True, blank = True)
196 notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
197 notify_key = models.CharField(max_length=32)
200 verbose_name = _('funding')
201 verbose_name_plural = _('fundings')
202 ordering = ['-payed_at']
206 """ QuerySet for all completed payments. """
207 return cls.objects.exclude(payed_at=None)
209 def __unicode__(self):
210 return unicode(self.offer)
212 def get_absolute_url(self):
213 return reverse('funding_funding', args=[self.pk])
215 def get_disable_notifications_url(self):
216 return "%s?%s" % (reverse("funding_disable_notifications"),
219 'key': self.notify_key,
222 def save(self, *args, **kwargs):
223 if self.email and not self.notify_key:
224 self.notify_key = get_random_hash(self.email)
225 return super(Funding, self).save(*args, **kwargs)
228 def notify_funders(cls, subject, template_name, extra_context=None,
229 query_filter=None, payed_only=True):
230 funders = cls.objects.exclude(email="").filter(notifications=True)
232 funders = funders.exclude(payed_at=None)
233 if query_filter is not None:
234 funders = funders.filter(query_filter)
236 for funder in funders:
237 if funder.email in emails:
239 emails.add(funder.email)
240 funder.notify(subject, template_name, extra_context)
242 def notify(self, subject, template_name, extra_context=None):
245 'site': Site.objects.get_current(),
247 context.update(extra_context)
248 with override(self.language_code or 'pl'):
250 render_to_string(template_name, context),
251 getattr(settings, 'CONTACT_EMAIL', 'wolnelektury@nowoczesnapolska.org.pl'),
256 def disable_notifications(self):
257 """Disables all notifications for this e-mail address."""
258 type(self).objects.filter(email=self.email).update(notifications=False)
261 # Register the Funding model with django-getpaid for payments.
262 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
265 class Spent(models.Model):
266 """ Some of the remaining money spent on a book. """
267 book = models.ForeignKey(Book)
268 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
269 timestamp = models.DateField(_('when'))
272 verbose_name = _('money spent on a book')
273 verbose_name_plural = _('money spent on books')
274 ordering = ['-timestamp']
276 def __unicode__(self):
277 return u"Spent: %s" % unicode(self.book)
280 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
281 """ Set payment details for getpaid. """
282 payment.amount = order.amount
283 payment.currency = 'PLN'
284 getpaid.signals.new_payment_query.connect(new_payment_query_listener)
287 def user_data_query_listener(sender, order, user_data, **kwargs):
288 """ Set user data for payment. """
289 user_data['email'] = order.email
290 getpaid.signals.user_data_query.connect(user_data_query_listener)
292 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
293 """ React to status changes from getpaid. """
294 if old_status != 'paid' and new_status == 'paid':
295 instance.order.payed_at = datetime.now()
296 instance.order.save()
297 if instance.order.email:
298 instance.order.notify(
299 _('Thank you for your support!'),
300 'funding/email/thanks.txt'
302 getpaid.signals.payment_status_changed.connect(payment_status_changed_listener)