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