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.core.mail import send_mail
8 from django.conf import settings
9 from django.template.loader import render_to_string
10 from django.db import models
11 from django.utils.translation import ugettext_lazy as _, ugettext as __, override
13 from catalogue.models import Book
14 from polls.models import Poll
17 class Offer(models.Model):
18 """ A fundraiser for a particular book. """
19 author = models.CharField(_('author'), max_length=255)
20 title = models.CharField(_('title'), max_length=255)
21 slug = models.SlugField(_('slug'))
22 description = models.TextField(_('description'), blank=True)
23 target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
24 start = models.DateField(_('start'), db_index=True)
25 end = models.DateField(_('end'), db_index=True)
26 due = models.DateField(_('due'),
27 help_text=_('When will it be published if the money is raised.'))
28 redakcja_url = models.URLField(_('redakcja URL'), blank=True)
29 book = models.ForeignKey(Book, null=True, blank=True,
30 help_text=_('Published book.'))
31 cover = models.ImageField(_('Cover'), upload_to = 'funding/covers')
32 poll = models.ForeignKey(Poll, help_text = _('Poll'), null = True, blank = True, on_delete = models.SET_NULL)
34 def cover_img_tag(self):
35 return u'<img src="%s" />' % self.cover.url
36 cover_img_tag.short_description = _('Cover preview')
37 cover_img_tag.allow_tags = True
40 verbose_name = _('offer')
41 verbose_name_plural = _('offers')
44 def __unicode__(self):
45 return u"%s - %s" % (self.author, self.title)
47 def get_absolute_url(self):
48 return reverse('funding_offer', args=[self.slug])
51 return self.start <= date.today() <= self.end
54 return self.sum() >= self.target
60 return self.sum() - self.target
66 """ Returns current fundraiser or None. """
68 objects = cls.objects.filter(start__lte=today, end__gte=today)
76 """ QuerySet for all current and past fundraisers. """
78 return cls.objects.filter(end__lt=today)
82 """ QuerySet for all current and past fundraisers. """
84 return cls.objects.filter(start__lte=today)
86 def get_perks(self, amount=None):
87 """ Finds all the perks for the offer.
89 If amount is provided, returns the perks you get for it.
92 perks = Perk.objects.filter(
93 models.Q(offer=self) | models.Q(offer=None)
94 ).exclude(end_date__lt=date.today())
95 if amount is not None:
96 perks = perks.filter(price__lte=amount)
99 def funding_payed(self):
100 """ QuerySet for all completed payments for the offer. """
101 return Funding.payed().filter(offer=self)
104 """ The money gathered. """
105 return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
108 class Perk(models.Model):
111 If no attached to a particular Offer, applies to all.
114 offer = models.ForeignKey(Offer, verbose_name=_('offer'), null=True, blank=True)
115 price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
116 name = models.CharField(_('name'), max_length=255)
117 long_name = models.CharField(_('long name'), max_length=255)
118 end_date = models.DateField(_('end date'), null=True, blank=True)
121 verbose_name = _('perk')
122 verbose_name_plural = _('perks')
123 ordering = ['-price']
125 def __unicode__(self):
126 return "%s (%s%s)" % (self.name, self.price, u" for %s" % self.offer if self.offer else "")
129 class Funding(models.Model):
130 """ A person paying in a fundraiser.
132 The payment was completed if and only if payed_at is set.
135 offer = models.ForeignKey(Offer, verbose_name=_('offer'))
136 name = models.CharField(_('name'), max_length=127, blank=True)
137 email = models.EmailField(_('email'), blank=True)
138 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
139 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
140 perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
141 language_code = models.CharField(max_length = 2, null = True, blank = True)
143 # Any additional info needed for perks?
147 """ QuerySet for all completed payments. """
148 return cls.objects.exclude(payed_at=None)
151 verbose_name = _('funding')
152 verbose_name_plural = _('fundings')
153 ordering = ['-payed_at']
155 def __unicode__(self):
156 return unicode(self.offer)
158 def get_absolute_url(self):
159 return reverse('funding_funding', args=[self.pk])
161 # Register the Funding model with django-getpaid for payments.
162 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
165 class Spent(models.Model):
166 """ Some of the remaining money spent on a book. """
167 book = models.ForeignKey(Book)
168 amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
169 timestamp = models.DateField(_('when'))
172 verbose_name = _('money spent on a book')
173 verbose_name_plural = _('money spent on books')
174 ordering = ['-timestamp']
176 def __unicode__(self):
177 return u"Spent: %s" % unicode(self.book)
180 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
181 """ Set payment details for getpaid. """
182 payment.amount = order.amount
183 payment.currency = 'PLN'
184 getpaid.signals.new_payment_query.connect(new_payment_query_listener)
187 def user_data_query_listener(sender, order, user_data, **kwargs):
188 """ Set user data for payment. """
189 user_data['email'] = order.email
190 getpaid.signals.user_data_query.connect(user_data_query_listener)
192 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
193 """ React to status changes from getpaid. """
194 if old_status != 'paid' and new_status == 'paid':
195 instance.order.payed_at = datetime.now()
196 instance.order.save()
197 if instance.order.email:
198 send_thank_you_email(instance.order.name, instance.order.email, instance.order.language_code)
199 getpaid.signals.payment_status_changed.connect(payment_status_changed_listener)
201 def send_thank_you_email(name, address, language_code):
202 with override(language_code or 'pl'):
203 send_mail(_('Thank you for your support!'),
204 render_to_string('funding/email.txt', dict(name = name)),
205 getattr(settings, 'CONTACT_EMAIL', 'wolnelektury@nowoczesnapolska.org.pl'),