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 django.core.urlresolvers import reverse
7 from django.db import models
8 from django.utils.translation import ugettext_lazy as _, ugettext as __
10 from catalogue.models import Book
11 from polls.models import Poll
14 class Offer(models.Model):
15 """ A fundraiser for a particular book. """
16 author = models.CharField(_('author'), max_length=255)
17 title = models.CharField(_('title'), max_length=255)
18 slug = models.SlugField(_('slug'))
19 description = models.TextField(_('description'), blank=True)
20 target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
21 start = models.DateField(_('start'), db_index=True)
22 end = models.DateField(_('end'), db_index=True)
23 due = models.DateField(_('due'),
24 help_text=_('When will it be published if the money is raised.'))
25 redakcja_url = models.URLField(_('redakcja URL'), blank=True)
26 book = models.ForeignKey(Book, null=True, blank=True,
27 help_text=_('Published book.'))
28 cover = models.ImageField(_('Cover'), upload_to = 'funding/covers')
29 poll = models.ForeignKey(Poll, help_text = _('Poll'), null = True, on_delete = models.SET_NULL)
31 def cover_img_tag(self):
32 return u'<img src="%s" />' % self.cover.url
33 cover_img_tag.short_description = _('Cover preview')
34 cover_img_tag.allow_tags = True
37 verbose_name = _('offer')
38 verbose_name_plural = _('offers')
41 def __unicode__(self):
42 return u"%s - %s" % (self.author, self.title)
44 def get_absolute_url(self):
45 return reverse('funding_offer', args=[self.slug])
48 return self.start <= date.today() <= self.end
51 return self.sum() >= self.target
57 return self.sum() - self.target
63 """ Returns current fundraiser or None. """
65 objects = cls.objects.filter(start__lte=today, end__gte=today)
73 """ QuerySet for all current and past fundraisers. """
75 return cls.objects.filter(end__lt=today)
79 """ QuerySet for all current and past fundraisers. """
81 return cls.objects.filter(start__lte=today)
83 def get_perks(self, amount=None):
84 """ Finds all the perks for the offer.
86 If amount is provided, returns the perks you get for it.
89 perks = Perk.objects.filter(
90 models.Q(offer=self) | models.Q(offer=None)
91 ).exclude(end_date__lt=date.today())
92 if amount is not None:
93 perks = perks.filter(price__lte=amount)
96 def funding_payed(self):
97 """ QuerySet for all completed payments for the offer. """
98 return Funding.payed().filter(offer=self)
101 """ The money gathered. """
102 return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
105 class Perk(models.Model):
108 If no attached to a particular Offer, applies to all.
111 offer = models.ForeignKey(Offer, verbose_name=_('offer'), null=True, blank=True)
112 price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
113 name = models.CharField(_('name'), max_length=255)
114 description = models.TextField(_('description'), blank=True)
115 end_date = models.DateField(_('end date'), null=True, blank=True)
118 verbose_name = _('perk')
119 verbose_name_plural = _('perks')
120 ordering = ['-price']
122 def __unicode__(self):
123 return "%s (%s%s)" % (self.name, self.price, u" for %s" % self.offer if self.offer else "")
126 class Funding(models.Model):
127 """ A person paying in a fundraiser.
129 The payment was completed if and only if payed_at is set.
132 offer = models.ForeignKey(Offer, verbose_name=_('offer'))
133 name = models.CharField(_('name'), max_length=127, blank=True)
134 email = models.EmailField(_('email'), blank=True)
135 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
136 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
137 perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
139 # Any additional info needed for perks?
143 """ QuerySet for all completed payments. """
144 return cls.objects.exclude(payed_at=None)
147 verbose_name = _('funding')
148 verbose_name_plural = _('fundings')
149 ordering = ['-payed_at']
151 def __unicode__(self):
152 return unicode(self.offer)
154 def get_absolute_url(self):
155 return reverse('funding_funding', args=[self.pk])
157 # Register the Funding model with django-getpaid for payments.
158 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
161 class Spent(models.Model):
162 """ Some of the remaining money spent on a book. """
163 book = models.ForeignKey(Book)
164 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
165 timestamp = models.DateField(_('when'))
168 verbose_name = _('money spent on a book')
169 verbose_name_plural = _('money spent on books')
170 ordering = ['-timestamp']
172 def __unicode__(self):
173 return u"Spent: %s" % unicode(self.book)
176 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
177 """ Set payment details for getpaid. """
178 payment.amount = order.amount
179 payment.currency = 'PLN'
180 getpaid.signals.new_payment_query.connect(new_payment_query_listener)
183 def user_data_query_listener(sender, order, user_data, **kwargs):
184 """ Set user data for payment. """
185 user_data['email'] = order.email
186 getpaid.signals.user_data_query.connect(user_data_query_listener)
188 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
189 """ React to status changes from getpaid. """
190 if old_status != 'paid' and new_status == 'paid':
191 instance.order.payed_at = datetime.now()
192 instance.order.save()
193 getpaid.signals.payment_status_changed.connect(payment_status_changed_listener)