Funding: behave nicer with time conflicts.
[wolnelektury.git] / apps / funding / models.py
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.
4 #
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
13 import getpaid
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
18 from . import app_settings
19
20
21 class Offer(models.Model):
22     """ A fundraiser for a particular book. """
23     author = models.CharField(_('author'), max_length=255)
24     title = models.CharField(_('title'), max_length=255)
25     slug = models.SlugField(_('slug'))
26     description = models.TextField(_('description'), blank=True)
27     target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
28     start = models.DateField(_('start'), db_index=True)
29     end = models.DateField(_('end'), db_index=True)
30     redakcja_url = models.URLField(_('redakcja URL'), blank=True)
31     book = models.ForeignKey(Book, null=True, blank=True,
32         help_text=_('Published book.'))
33     cover = models.ImageField(_('Cover'), upload_to = 'funding/covers')
34     poll = models.ForeignKey(Poll, help_text = _('Poll'),  null = True, blank = True, on_delete = models.SET_NULL)
35
36     notified_near = models.DateTimeField(_('Near-end notifications sent'), blank=True, null=True)
37     notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True)
38
39     def cover_img_tag(self):
40         return u'<img src="%s" />' % self.cover.url
41     cover_img_tag.short_description = _('Cover preview')
42     cover_img_tag.allow_tags = True
43         
44     class Meta:
45         verbose_name = _('offer')
46         verbose_name_plural = _('offers')
47         ordering = ['-end']
48
49     def __unicode__(self):
50         return u"%s - %s" % (self.author, self.title)
51
52     def get_absolute_url(self):
53         return reverse('funding_offer', args=[self.slug])
54
55     def save(self, *args, **kw):
56         published_now = (self.book_id is not None and 
57             self.pk is not None and
58             type(self).objects.values('book').get(pk=self.pk)['book'] != self.book_id)
59         retval = super(Offer, self).save(*args, **kw)
60         if published_now:
61             self.notify_published()
62         return retval
63
64     def is_current(self):
65         return self.start <= date.today() <= self.end and self == self.current()
66
67     def is_win(self):
68         return self.sum() >= self.target
69
70     def remaining(self):
71         if self.is_current():
72             return None
73         if self.is_win():
74             return self.sum() - self.target
75         else:
76             return self.sum()
77
78     @classmethod
79     def current(cls):
80         """ Returns current fundraiser or None.
81
82         Current fundraiser is the one that:
83         - has already started,
84         - hasn't yet ended,
85         - if there's more than one of those, it's the one that ends last.
86
87         """
88         today = date.today()
89         objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end')
90         try:
91             return objects[0]
92         except IndexError:
93             return None
94
95     @classmethod
96     def past(cls):
97         """ QuerySet for all past fundraisers. """
98         objects = cls.public()
99         current = cls.current()
100         if current is not None:
101             objects = objects.exclude(pk=current.pk)
102         return objects
103
104     @classmethod
105     def public(cls):
106         """ QuerySet for all current and past fundraisers. """
107         today = date.today()
108         return cls.objects.filter(start__lte=today)
109
110     def get_perks(self, amount=None):
111         """ Finds all the perks for the offer.
112         
113         If amount is provided, returns the perks you get for it.
114
115         """
116         perks = Perk.objects.filter(
117                 models.Q(offer=self) | models.Q(offer=None)
118             ).exclude(end_date__lt=date.today())
119         if amount is not None:
120             perks = perks.filter(price__lte=amount)
121         return perks
122
123     def funding_payed(self):
124         """ QuerySet for all completed payments for the offer. """
125         return Funding.payed().filter(offer=self)
126
127     def sum(self):
128         """ The money gathered. """
129         return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
130
131     def notify_all(self, subject, template_name, extra_context=None):
132         Funding.notify_funders(
133             subject, template_name, extra_context,
134             query_filter=models.Q(offer=self)
135         )
136
137     def notify_end(self, force=False):
138         if not force and self.notified_end: return
139         assert not self.is_current()
140         self.notify_all(
141             _('The fundraiser has ended!'),
142             'funding/email/end.txt', {
143                 'offer': self,
144                 'is_win': self.is_win(),
145                 'remaining': self.remaining(),
146                 'current': self.current(),
147             })
148         self.notified_end = datetime.now()
149         self.save()
150
151     def notify_near(self, force=False):
152         if not force and self.notified_near: return
153         assert self.is_current()
154         sum_ = self.sum()
155         need = self.target - sum_
156         self.notify_all(
157             _('The fundraiser will end soon!'),
158             'funding/email/near.txt', {
159                 'days': (self.end - date.today()).days + 1,
160                 'offer': self,
161                 'is_win': self.is_win(),
162                 'sum': sum_,
163                 'need': need,
164             })
165         self.notified_near = datetime.now()
166         self.save()
167
168     def notify_published(self):
169         assert self.book is not None
170         self.notify_all(
171             _('The book you helped fund has been published.'),
172             'funding/email/published.txt', {
173                 'offer': self,
174                 'book': self.book,
175                 'author': ", ".join(a[0] for a in self.book.related_info()['tags']['author']),
176                 'current': self.current(),
177             })
178
179
180 class Perk(models.Model):
181     """ A perk offer.
182     
183     If no attached to a particular Offer, applies to all.
184
185     """
186     offer = models.ForeignKey(Offer, verbose_name=_('offer'), null=True, blank=True)
187     price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
188     name = models.CharField(_('name'), max_length=255)
189     long_name = models.CharField(_('long name'), max_length=255)
190     end_date = models.DateField(_('end date'), null=True, blank=True)
191
192     class Meta:
193         verbose_name = _('perk')
194         verbose_name_plural = _('perks')
195         ordering = ['-price']
196
197     def __unicode__(self):
198         return "%s (%s%s)" % (self.name, self.price, u" for %s" % self.offer if self.offer else "")
199
200
201 class Funding(models.Model):
202     """ A person paying in a fundraiser.
203
204     The payment was completed if and only if payed_at is set.
205
206     """
207     offer = models.ForeignKey(Offer, verbose_name=_('offer'))
208     name = models.CharField(_('name'), max_length=127, blank=True)
209     email = models.EmailField(_('email'), blank=True, db_index=True)
210     amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
211     payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
212     perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
213     language_code = models.CharField(max_length = 2, null = True, blank = True)
214     notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
215     notify_key = models.CharField(max_length=32)
216
217     class Meta:
218         verbose_name = _('funding')
219         verbose_name_plural = _('fundings')
220         ordering = ['-payed_at']
221
222     @classmethod
223     def payed(cls):
224         """ QuerySet for all completed payments. """
225         return cls.objects.exclude(payed_at=None)
226
227     def __unicode__(self):
228         return unicode(self.offer)
229
230     def get_absolute_url(self):
231         return reverse('funding_funding', args=[self.pk])
232
233     def get_disable_notifications_url(self):
234         return "%s?%s" % (reverse("funding_disable_notifications"),
235             urlencode({
236                 'email': self.email,
237                 'key': self.notify_key,
238             }))
239
240     def save(self, *args, **kwargs):
241         if self.email and not self.notify_key:
242             self.notify_key = get_random_hash(self.email)
243         return super(Funding, self).save(*args, **kwargs)
244
245     @classmethod
246     def notify_funders(cls, subject, template_name, extra_context=None,
247                 query_filter=None, payed_only=True):
248         funders = cls.objects.exclude(email="").filter(notifications=True)
249         if payed_only:
250             funders = funders.exclude(payed_at=None)
251         if query_filter is not None:
252             funders = funders.filter(query_filter)
253         emails = set()
254         for funder in funders:
255             if funder.email in emails:
256                 continue
257             emails.add(funder.email)
258             funder.notify(subject, template_name, extra_context)
259
260     def notify(self, subject, template_name, extra_context=None):
261         context = {
262             'funding': self,
263             'site': Site.objects.get_current(),
264         }
265         if extra_context:
266             context.update(extra_context)
267         with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
268             send_mail(subject,
269                 render_to_string(template_name, context),
270                 getattr(settings, 'CONTACT_EMAIL', 'wolnelektury@nowoczesnapolska.org.pl'),
271                 [self.email],
272                 fail_silently=False
273             )
274
275     def disable_notifications(self):
276         """Disables all notifications for this e-mail address."""
277         type(self).objects.filter(email=self.email).update(notifications=False)
278
279
280 # Register the Funding model with django-getpaid for payments.
281 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
282
283
284 class Spent(models.Model):
285     """ Some of the remaining money spent on a book. """
286     book = models.ForeignKey(Book)
287     amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
288     timestamp = models.DateField(_('when'))
289
290     class Meta:
291         verbose_name = _('money spent on a book')
292         verbose_name_plural = _('money spent on books')
293         ordering = ['-timestamp']
294
295     def __unicode__(self):
296         return u"Spent: %s" % unicode(self.book)
297
298
299 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
300     """ Set payment details for getpaid. """
301     payment.amount = order.amount
302     payment.currency = 'PLN'
303 getpaid.signals.new_payment_query.connect(new_payment_query_listener)
304
305
306 def user_data_query_listener(sender, order, user_data, **kwargs):
307     """ Set user data for payment. """
308     user_data['email'] = order.email
309 getpaid.signals.user_data_query.connect(user_data_query_listener)
310
311 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
312     """ React to status changes from getpaid. """
313     if old_status != 'paid' and new_status == 'paid':
314         instance.order.payed_at = datetime.now()
315         instance.order.save()
316         if instance.order.email:
317             instance.order.notify(
318                 _('Thank you for your support!'),
319                 'funding/email/thanks.txt'
320             )
321 getpaid.signals.payment_status_changed.connect(payment_status_changed_listener)