Add django-getpaid
[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 django.core.urlresolvers import reverse
7 from django.db import models
8 from django.utils.translation import ugettext_lazy as _, ugettext as __
9 import getpaid
10 from catalogue.models import Book
11
12
13 class Offer(models.Model):
14     """ A fundraiser for a particular book. """
15     author = models.CharField(_('author'), max_length=255)
16     title = models.CharField(_('title'), max_length=255)
17     slug = models.SlugField(_('slug'))
18     book = models.ForeignKey(Book, null=True, blank=True,
19         help_text=_('Published book.'))
20     redakcja_url = models.URLField(_('redakcja URL'), blank=True)
21     target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
22     start = models.DateField(_('start'))
23     end = models.DateField(_('end'))
24     due = models.DateField(_('due'),
25         help_text=_('When will it be published if the money is raised.'))
26
27     class Meta:
28         verbose_name = _('offer')
29         verbose_name_plural = _('offers')
30         ordering = ['-end']
31
32     def __unicode__(self):
33         return u"%s – %s" % (self.author, self.title)
34
35     def get_absolute_url(self):
36         return reverse('funding_offer', args=[self.slug])
37
38     def is_current(self):
39         return self.start <= date.today() <= self.end
40
41     @classmethod
42     def current(cls):
43         """ Returns current fundraiser or None. """
44         today = date.today()
45         objects = cls.objects.filter(start__lte=today, end__gte=today)
46         try:
47             return objects[0]
48         except IndexError:
49             return None
50
51     @classmethod
52     def public(cls):
53         """ QuerySet for all current and past fundraisers. """
54         today = date.today()
55         return cls.objects.filter(start__lte=today)        
56
57     def get_perks(self, amount=None):
58         """ Finds all the perks for the offer.
59         
60         If amount is provided, returns the perks you get for it.
61
62         """
63         perks = Perk.objects.filter(
64                 models.Q(offer=self) | models.Q(offer=None)
65             )
66         if amount is not None:
67             perks = perks.filter(price__lte=amount)
68         return perks
69
70     def funding_payed(self):
71         """ QuerySet for all completed payments for the offer. """
72         return Funding.payed().filter(offer=self)
73
74     def sum(self):
75         """ The money gathered. """
76         return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
77
78     def state(self):
79         if self.sum() >= self.target:
80             return 'win'
81         elif self.start <= date.today() <= self.end:
82             return 'running'
83         else:
84             return 'lose'
85
86
87 class Perk(models.Model):
88     """ A perk offer.
89     
90     If no attached to a particular Offer, applies to all.
91
92     """
93     offer = models.ForeignKey(Offer, verbose_name=_('offer'), null=True, blank=True)
94     price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
95     name = models.CharField(_('name'), max_length=255)
96     description = models.TextField(_('description'), blank=True)
97
98     class Meta:
99         verbose_name = _('perk')
100         verbose_name_plural = _('perks')
101         ordering = ['-price']
102
103     def __unicode__(self):
104         return "%s (%s%s)" % (self.name, self.price, u" for %s" % self.offer if self.offer else "")
105
106
107 class Funding(models.Model):
108     """ A person paying in a fundraiser.
109
110     The payment was completed if and only if payed_at is set.
111
112     """
113     offer = models.ForeignKey(Offer, verbose_name=_('offer'))
114     name = models.CharField(_('name'), max_length=127, blank=True)
115     email = models.EmailField(_('email'), blank=True)
116     amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
117     payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
118     perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
119     anonymous = models.BooleanField(_('anonymous'))
120
121     @classmethod
122     def payed(cls):
123         """ QuerySet for all completed payments. """
124         return cls.objects.exclude(payed_at=None)
125
126     class Meta:
127         verbose_name = _('funding')
128         verbose_name_plural = _('fundings')
129         ordering = ['-payed_at']
130
131     def __unicode__(self):
132         return "%s payed %s for %s" % (self.name, self.amount, self.offer)
133
134     def get_absolute_url(self):
135         return reverse('funding_funding', args=[self.pk])
136
137 # Register the Funding model with django-getpaid for payments.
138 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
139
140
141 class Spent(models.Model):
142     """ Some of the remaining money spent on a book. """
143     amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
144     timestamp = models.DateField(_('when'))
145     book = models.ForeignKey(Book)
146
147     class Meta:
148         verbose_name = _('money spent on a book')
149         verbose_name_plural = _('money spent on books')
150         ordering = ['-timestamp']
151
152     def __unicode__(self):
153         return u"Spent: %s" % unicode(self.book)
154
155
156 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
157     """ Set payment details for getpaid. """
158     payment.amount = order.amount
159     payment.currency = 'PLN'
160 getpaid.signals.new_payment_query.connect(new_payment_query_listener)
161
162
163 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
164     """ React to status changes from getpaid. """
165     if old_status != 'paid' and new_status == 'paid':
166         instance.order.payed_at = datetime.now()
167         instance.order.save()
168 getpaid.signals.payment_status_changed.connect(payment_status_changed_listener)