Fix for carousel management.
[wolnelektury.git] / src / funding / models.py
index 3e20efc..838d2ab 100644 (file)
@@ -10,14 +10,16 @@ from django.db import models
 from django.dispatch import receiver
 from django.template.loader import render_to_string
 from django.urls import reverse
 from django.dispatch import receiver
 from django.template.loader import render_to_string
 from django.urls import reverse
+from django.utils.html import mark_safe
 from django.utils.timezone import utc
 from django.utils.timezone import utc
-from django.utils.translation import ugettext_lazy as _, override
-import getpaid
+from django.utils.translation import gettext_lazy as _, override
 from catalogue.models import Book
 from catalogue.utils import get_random_hash
 from polls.models import Poll
 from catalogue.models import Book
 from catalogue.utils import get_random_hash
 from polls.models import Poll
+import club.payu.models
 from wolnelektury.utils import cached_render, clear_cached_renders
 from . import app_settings
 from wolnelektury.utils import cached_render, clear_cached_renders
 from . import app_settings
+from . import utils
 
 
 class Offer(models.Model):
 
 
 class Offer(models.Model):
@@ -38,9 +40,8 @@ class Offer(models.Model):
     notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True)
 
     def cover_img_tag(self):
     notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True)
 
     def cover_img_tag(self):
-        return u'<img src="%s" />' % self.cover.url
+        return mark_safe('<img src="%s" />' % self.cover.url)
     cover_img_tag.short_description = _('Cover preview')
     cover_img_tag.short_description = _('Cover preview')
-    cover_img_tag.allow_tags = True
 
     class Meta:
         verbose_name = _('offer')
 
     class Meta:
         verbose_name = _('offer')
@@ -48,7 +49,7 @@ class Offer(models.Model):
         ordering = ['-end']
 
     def __str__(self):
         ordering = ['-end']
 
     def __str__(self):
-        return u"%s - %s" % (self.author, self.title)
+        return "%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])
@@ -63,6 +64,9 @@ class Offer(models.Model):
             self.notify_published()
         return retval
 
             self.notify_published()
         return retval
 
+    def get_payu_payment_title(self):
+        return utils.sanitize_payment_title(str(self))
+
     def clear_cache(self):
         clear_cached_renders(self.top_bar)
         clear_cached_renders(self.list_bar)
     def clear_cache(self):
         clear_cached_renders(self.top_bar)
         clear_cached_renders(self.list_bar)
@@ -134,7 +138,7 @@ class Offer(models.Model):
         return Funding.payed().filter(offer=self)
 
     def funders(self):
         return Funding.payed().filter(offer=self)
 
     def funders(self):
-        return self.funding_payed().order_by('-amount', 'payed_at')
+        return self.funding_payed().order_by('-amount', 'completed_at')
 
     def sum(self):
         """ The money gathered. """
 
     def sum(self):
         """ The money gathered. """
@@ -194,7 +198,7 @@ class Offer(models.Model):
         offer_sum = self.sum()
         return {
             'offer': self,
         offer_sum = self.sum()
         return {
             'offer': self,
-            'sum': offset_sum,
+            'sum': offer_sum,
             'is_current': self.is_current(),
             'is_win': offer_sum >= self.target,
             'missing': self.target - offer_sum,
             'is_current': self.is_current(),
             'is_win': offer_sum >= self.target,
             'missing': self.target - offer_sum,
@@ -258,20 +262,22 @@ class Perk(models.Model):
         ordering = ['-price']
 
     def __str__(self):
         ordering = ['-price']
 
     def __str__(self):
-        return "%s (%s%s)" % (self.name, self.price, u" for %s" % self.offer if self.offer else "")
+        return "%s (%s%s)" % (self.name, self.price, " for %s" % self.offer if self.offer else "")
 
 
 
 
-class Funding(models.Model):
+class Funding(club.payu.models.Order):
     """ A person paying in a fundraiser.
 
     """ A person paying in a fundraiser.
 
-    The payment was completed if and only if payed_at is set.
+    The payment was completed if and only if completed_at is set.
 
     """
     offer = models.ForeignKey(Offer, models.PROTECT, verbose_name=_('offer'))
 
     """
     offer = models.ForeignKey(Offer, models.PROTECT, verbose_name=_('offer'))
+    customer_ip = models.GenericIPAddressField(_('customer IP'), null=True)
+    
     name = models.CharField(_('name'), max_length=127, blank=True)
     email = models.EmailField(_('email'), blank=True, db_index=True)
     name = models.CharField(_('name'), max_length=127, blank=True)
     email = models.EmailField(_('email'), blank=True, db_index=True)
+    user = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=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, db_index=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)
     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)
@@ -280,18 +286,43 @@ class Funding(models.Model):
     class Meta:
         verbose_name = _('funding')
         verbose_name_plural = _('fundings')
     class Meta:
         verbose_name = _('funding')
         verbose_name_plural = _('fundings')
-        ordering = ['-payed_at', 'pk']
+        ordering = ['-completed_at', 'pk']
 
     @classmethod
     def payed(cls):
         """ QuerySet for all completed payments. """
 
     @classmethod
     def payed(cls):
         """ QuerySet for all completed payments. """
-        return cls.objects.exclude(payed_at=None)
+        return cls.objects.exclude(completed_at=None)
 
     def __str__(self):
         return str(self.offer)
 
 
     def __str__(self):
         return str(self.offer)
 
-    def get_absolute_url(self):
-        return reverse('funding_funding', args=[self.pk])
+    def get_amount(self):
+        return self.amount
+
+    def get_buyer(self):
+        return {
+            "email": self.email,
+            "language": self.language_code,
+        }
+
+    def get_description(self):
+        return self.offer.get_payu_payment_title()
+
+    def get_thanks_url(self):
+        return reverse('funding_thanks')
+
+    def status_updated(self):
+        if self.status == 'COMPLETED':
+            if self.email:
+                self.notify(
+                    _('Thank you for your support!'),
+                    'funding/email/thanks.txt'
+                )
+
+    def get_notify_url(self):
+        return "https://{}{}".format(
+            Site.objects.get_current().domain,
+            reverse('funding_payu_notify', args=[self.pk]))
 
     def perk_names(self):
         return ", ".join(perk.name for perk in self.perks.all())
 
     def perk_names(self):
         return ", ".join(perk.name for perk in self.perks.all())
@@ -304,6 +335,9 @@ class Funding(models.Model):
                 'key': self.notify_key,
             }))
 
                 'key': self.notify_key,
             }))
 
+    def wl_optout_url(self):
+        return 'https://wolnelektury.pl' + self.get_disable_notifications_url()
+
     def save(self, *args, **kwargs):
         if self.email and not self.notify_key:
             self.notify_key = get_random_hash(self.email)
     def save(self, *args, **kwargs):
         if self.email and not self.notify_key:
             self.notify_key = get_random_hash(self.email)
@@ -315,7 +349,7 @@ class Funding(models.Model):
     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:
     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)
+            funders = funders.exclude(completed_at=None)
         if query_filter is not None:
             funders = funders.filter(query_filter)
         emails = set()
         if query_filter is not None:
             funders = funders.filter(query_filter)
         emails = set()
@@ -342,8 +376,8 @@ class Funding(models.Model):
         type(self).objects.filter(email=self.email).update(notifications=False)
 
 
         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')
+class PayUNotification(club.payu.models.Notification):
+    order = models.ForeignKey(Funding, models.CASCADE, related_name='notification_set')
 
 
 class Spent(models.Model):
 
 
 class Spent(models.Model):
@@ -358,30 +392,5 @@ class Spent(models.Model):
         ordering = ['-timestamp']
 
     def __str__(self):
         ordering = ['-timestamp']
 
     def __str__(self):
-        return u"Spent: %s" % str(self.book)
-
-
-@receiver(getpaid.signals.new_payment_query)
-def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
-    """ Set payment details for getpaid. """
-    payment.amount = order.amount
-    payment.currency = 'PLN'
-
-
-@receiver(getpaid.signals.user_data_query)
-def user_data_query_listener(sender, order, user_data, **kwargs):
-    """ Set user data for payment. """
-    user_data['email'] = order.email
-
+        return "Spent: %s" % str(self.book)
 
 
-@receiver(getpaid.signals.payment_status_changed)
-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.utcnow().replace(tzinfo=utc)
-        instance.order.save()
-        if instance.order.email:
-            instance.order.notify(
-                _('Thank you for your support!'),
-                'funding/email/thanks.txt'
-            )