Status update emails.
[wolnelektury.git] / apps / funding / models.py
index 31e2757..ac652b1 100644 (file)
@@ -3,11 +3,18 @@
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 from datetime import date, datetime
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 from datetime import date, datetime
+from urllib import urlencode
 from django.core.urlresolvers import reverse
 from django.core.urlresolvers import reverse
+from django.core.mail import send_mail
+from django.conf import settings
+from django.template.loader import render_to_string
 from django.db import models
 from django.db import models
-from django.utils.translation import ugettext_lazy as _, ugettext as __
+from django.utils.translation import ugettext_lazy as _, ugettext, override
 import getpaid
 from catalogue.models import Book
 import getpaid
 from catalogue.models import Book
+from catalogue.utils import get_random_hash
+from polls.models import Poll
+from django.contrib.sites.models import Site
 
 
 class Offer(models.Model):
 
 
 class Offer(models.Model):
@@ -15,29 +22,57 @@ class Offer(models.Model):
     author = models.CharField(_('author'), max_length=255)
     title = models.CharField(_('title'), max_length=255)
     slug = models.SlugField(_('slug'))
     author = models.CharField(_('author'), max_length=255)
     title = models.CharField(_('title'), max_length=255)
     slug = models.SlugField(_('slug'))
-    book = models.ForeignKey(Book, null=True, blank=True,
-        help_text=_('Published book.'))
-    redakcja_url = models.URLField(_('redakcja URL'), blank=True)
+    description = models.TextField(_('description'), blank=True)
     target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
     target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
-    start = models.DateField(_('start'))
-    end = models.DateField(_('end'))
+    start = models.DateField(_('start'), db_index=True)
+    end = models.DateField(_('end'), db_index=True)
     due = models.DateField(_('due'),
         help_text=_('When will it be published if the money is raised.'))
     due = models.DateField(_('due'),
         help_text=_('When will it be published if the money is raised.'))
-
+    redakcja_url = models.URLField(_('redakcja URL'), blank=True)
+    book = models.ForeignKey(Book, null=True, blank=True,
+        help_text=_('Published book.'))
+    cover = models.ImageField(_('Cover'), upload_to = 'funding/covers')
+    poll = models.ForeignKey(Poll, help_text = _('Poll'),  null = True, blank = True, on_delete = models.SET_NULL)
+        
+    def cover_img_tag(self):
+        return u'<img src="%s" />' % self.cover.url
+    cover_img_tag.short_description = _('Cover preview')
+    cover_img_tag.allow_tags = True
+        
     class Meta:
         verbose_name = _('offer')
         verbose_name_plural = _('offers')
         ordering = ['-end']
 
     def __unicode__(self):
     class Meta:
         verbose_name = _('offer')
         verbose_name_plural = _('offers')
         ordering = ['-end']
 
     def __unicode__(self):
-        return u"%s  %s" % (self.author, self.title)
+        return u"%s - %s" % (self.author, self.title)
 
     def get_absolute_url(self):
         return reverse('funding_offer', args=[self.slug])
 
 
     def get_absolute_url(self):
         return reverse('funding_offer', args=[self.slug])
 
+    def save(self, *args, **kw):
+        published_now = (self.book_id is not None and 
+            self.pk is not None and
+            type(self).objects.values('book').get(pk=self.pk)['book'] != self.book_id)
+        retval = super(Offer, self).save(*args, **kw)
+        if published_now:
+            self.notify_published()
+        return retval
+
     def is_current(self):
         return self.start <= date.today() <= self.end
 
     def is_current(self):
         return self.start <= date.today() <= self.end
 
+    def is_win(self):
+        return self.sum() >= self.target
+
+    def remaining(self):
+        if self.is_current():
+            return None
+        if self.is_win():
+            return self.sum() - self.target
+        else:
+            return self.sum()
+
     @classmethod
     def current(cls):
         """ Returns current fundraiser or None. """
     @classmethod
     def current(cls):
         """ Returns current fundraiser or None. """
@@ -48,11 +83,17 @@ class Offer(models.Model):
         except IndexError:
             return None
 
         except IndexError:
             return None
 
+    @classmethod
+    def past(cls):
+        """ QuerySet for all current and past fundraisers. """
+        today = date.today()
+        return cls.objects.filter(end__lt=today)
+
     @classmethod
     def public(cls):
         """ QuerySet for all current and past fundraisers. """
         today = date.today()
     @classmethod
     def public(cls):
         """ QuerySet for all current and past fundraisers. """
         today = date.today()
-        return cls.objects.filter(start__lte=today)        
+        return cls.objects.filter(start__lte=today)
 
     def get_perks(self, amount=None):
         """ Finds all the perks for the offer.
 
     def get_perks(self, amount=None):
         """ Finds all the perks for the offer.
@@ -75,13 +116,47 @@ class Offer(models.Model):
         """ The money gathered. """
         return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
 
         """ The money gathered. """
         return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
 
-    def state(self):
-        if self.sum() >= self.target:
-            return 'win'
-        elif self.start <= date.today() <= self.end:
-            return 'running'
-        else:
-            return 'lose'
+    def notify_all(self, subject, template_name, extra_context=None):
+        Funding.notify_funders(
+            subject, template_name, extra_context,
+            query_filter=models.Q(offer=self)
+        )
+
+    def notify_end(self):
+        assert not self.is_current()
+        self.notify_all(
+            _('The fundraiser has ended!'),
+            'funding/email/end.txt', {
+                'offer': self,
+                'is_win': self.is_win(),
+                'remaining': self.remaining(),
+                'current': self.current(),
+            })
+
+    def notify_near(self):
+        assert self.is_current()
+        sum_ = self.sum()
+        need = self.target - sum_
+        self.notify_all(
+            _('The fundraiser will end soon!'),
+            'funding/email/near.txt', {
+                'days': (self.end - date.today()).days + 1,
+                'offer': self,
+                'is_win': self.is_win(),
+                'sum': sum_,
+                'need': need,
+            })
+
+    def notify_published(self):
+        assert self.book is not None
+        self.notify_all(
+            _('The book you helped fund has been published.'),
+            'funding/email/published.txt', {
+                'offer': self,
+                'book': self.book,
+                'author': ", ".join(a[0] for a in self.book.related_info()['tags']['author']),
+                'current': self.current(),
+            })
 
 
 class Perk(models.Model):
 
 
 class Perk(models.Model):
@@ -93,7 +168,7 @@ class Perk(models.Model):
     offer = models.ForeignKey(Offer, verbose_name=_('offer'), null=True, blank=True)
     price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
     name = models.CharField(_('name'), max_length=255)
     offer = models.ForeignKey(Offer, verbose_name=_('offer'), null=True, blank=True)
     price = models.DecimalField(_('price'), decimal_places=2, max_digits=10)
     name = models.CharField(_('name'), max_length=255)
-    description = models.TextField(_('description'), blank=True)
+    long_name = models.CharField(_('long name'), max_length=255)
     end_date = models.DateField(_('end date'), null=True, blank=True)
 
     class Meta:
     end_date = models.DateField(_('end date'), null=True, blank=True)
 
     class Meta:
@@ -113,29 +188,76 @@ class Funding(models.Model):
     """
     offer = models.ForeignKey(Offer, verbose_name=_('offer'))
     name = models.CharField(_('name'), max_length=127, blank=True)
     """
     offer = models.ForeignKey(Offer, verbose_name=_('offer'))
     name = models.CharField(_('name'), max_length=127, blank=True)
-    email = models.EmailField(_('email'), blank=True)
+    email = models.EmailField(_('email'), blank=True, db_index=True)
     amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
     amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
-    payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
+    payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
     perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
     perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True)
+    language_code = models.CharField(max_length = 2, null = True, blank = True)
+    notifications = models.BooleanField(_('notifications'), default=True, db_index=True)
+    notify_key = models.CharField(max_length=32)
 
 
-    # Any additional info needed for perks?
+    class Meta:
+        verbose_name = _('funding')
+        verbose_name_plural = _('fundings')
+        ordering = ['-payed_at']
 
     @classmethod
     def payed(cls):
         """ QuerySet for all completed payments. """
         return cls.objects.exclude(payed_at=None)
 
 
     @classmethod
     def payed(cls):
         """ QuerySet for all completed payments. """
         return cls.objects.exclude(payed_at=None)
 
-    class Meta:
-        verbose_name = _('funding')
-        verbose_name_plural = _('fundings')
-        ordering = ['-payed_at']
-
     def __unicode__(self):
         return unicode(self.offer)
 
     def get_absolute_url(self):
         return reverse('funding_funding', args=[self.pk])
 
     def __unicode__(self):
         return unicode(self.offer)
 
     def get_absolute_url(self):
         return reverse('funding_funding', args=[self.pk])
 
+    def get_disable_notifications_url(self):
+        return "%s?%s" % (reverse("funding_disable_notifications"),
+            urlencode({
+                'email': self.email,
+                'key': self.notify_key,
+            }))
+
+    def save(self, *args, **kwargs):
+        if self.email and not self.notify_key:
+            self.notify_key = get_random_hash(self.email)
+        return super(Funding, self).save(*args, **kwargs)
+
+    @classmethod
+    def notify_funders(cls, subject, template_name, extra_context=None,
+                query_filter=None, payed_only=True):
+        funders = cls.objects.exclude(email="").filter(notifications=True)
+        if payed_only:
+            funders = funders.exclude(payed_at=None)
+        if query_filter is not None:
+            funders = funders.filter(query_filter)
+        emails = set()
+        for funder in funders:
+            if funder.email in emails:
+                continue
+            emails.add(funder.email)
+            funder.notify(subject, template_name, extra_context)
+
+    def notify(self, subject, template_name, extra_context=None):
+        context = {
+            'funding': self,
+            'site': Site.objects.get_current(),
+        }
+        context.update(extra_context)
+        with override(self.language_code or 'pl'):
+            send_mail(subject,
+                render_to_string(template_name, context),
+                getattr(settings, 'CONTACT_EMAIL', 'wolnelektury@nowoczesnapolska.org.pl'),
+                [self.email],
+                fail_silently=False
+            )
+
+    def disable_notifications(self):
+        """Disables all notifications for this e-mail address."""
+        type(self).objects.filter(email=self.email).update(notifications=False)
+
+
 # Register the Funding model with django-getpaid for payments.
 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
 
 # Register the Funding model with django-getpaid for payments.
 getpaid.register_to_payment(Funding, unique=False, related_name='payment')
 
@@ -162,9 +284,19 @@ def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
 getpaid.signals.new_payment_query.connect(new_payment_query_listener)
 
 
 getpaid.signals.new_payment_query.connect(new_payment_query_listener)
 
 
+def user_data_query_listener(sender, order, user_data, **kwargs):
+    """ Set user data for payment. """
+    user_data['email'] = order.email
+getpaid.signals.user_data_query.connect(user_data_query_listener)
+
 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
     """ React to status changes from getpaid. """
     if old_status != 'paid' and new_status == 'paid':
         instance.order.payed_at = datetime.now()
         instance.order.save()
 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
     """ React to status changes from getpaid. """
     if old_status != 'paid' and new_status == 'paid':
         instance.order.payed_at = datetime.now()
         instance.order.save()
+        if instance.order.email:
+            instance.order.notify(
+                _('Thank you for your support!'),
+                'funding/email/thanks.txt'
+            )
 getpaid.signals.payment_status_changed.connect(payment_status_changed_listener)
 getpaid.signals.payment_status_changed.connect(payment_status_changed_listener)