X-Git-Url: https://git.mdrn.pl/wolnelektury.git/blobdiff_plain/0679f997bb4e0583f2425b0abd07186e44c26915..6c35cecacb910da6935d49110ea1cd502affe92d:/src/funding/models.py?ds=inline
diff --git a/src/funding/models.py b/src/funding/models.py
index b126c7681..81d439df8 100644
--- a/src/funding/models.py
+++ b/src/funding/models.py
@@ -1,55 +1,55 @@
-# -*- coding: utf-8 -*-
-# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
-# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
+# This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
+# Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
#
from datetime import date, datetime
-from urllib import urlencode
+from urllib.parse import urlencode
from django.conf import settings
from django.contrib.sites.models import Site
-from django.core.urlresolvers import reverse
from django.core.mail import send_mail
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.utils.html import mark_safe
from django.utils.timezone import utc
-from django.utils.translation import ugettext_lazy as _, override
-import getpaid
-from ssify import flush_ssi_includes
+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
+import club.payu.models
+from wolnelektury.utils import cached_render, clear_cached_renders
from . import app_settings
+from . import utils
class Offer(models.Model):
""" A fundraiser for a particular book. """
- author = models.CharField(_('author'), max_length=255)
- title = models.CharField(_('title'), max_length=255)
- slug = models.SlugField(_('slug'))
- description = models.TextField(_('description'), blank=True)
- target = models.DecimalField(_('target'), decimal_places=2, max_digits=10)
- start = models.DateField(_('start'), db_index=True)
- end = models.DateField(_('end'), db_index=True)
- 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)
-
- notified_near = models.DateTimeField(_('Near-end notifications sent'), blank=True, null=True)
- notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True)
+ author = models.CharField('autor', max_length=255)
+ title = models.CharField('tytuÅ', max_length=255)
+ slug = models.SlugField('slug')
+ description = models.TextField('opis', blank=True)
+ target = models.DecimalField('kwota docelowa', decimal_places=2, max_digits=10)
+ start = models.DateField('poczÄ
tek', db_index=True)
+ end = models.DateField('koniec', db_index=True)
+ redakcja_url = models.URLField('URL na Redakcji', blank=True)
+ book = models.ForeignKey(Book, models.PROTECT, null=True, blank=True, help_text='Opublikowana ksiÄ
żka.')
+ cover = models.ImageField('OkÅadka', upload_to='funding/covers')
+ poll = models.ForeignKey(Poll, help_text='Ankieta', null=True, blank=True, on_delete=models.SET_NULL)
+
+ notified_near = models.DateTimeField('WysÅano powiadomienia przed koÅcem', blank=True, null=True)
+ notified_end = models.DateTimeField('WysÅano powiadomienia o zakoÅczeniu', blank=True, null=True)
def cover_img_tag(self):
- return u'' % self.cover.url
- cover_img_tag.short_description = _('Cover preview')
- cover_img_tag.allow_tags = True
+ return mark_safe('' % self.cover.url)
+ cover_img_tag.short_description = 'PodglÄ
d okÅadki'
class Meta:
- verbose_name = _('offer')
- verbose_name_plural = _('offers')
+ verbose_name = 'zbiórka'
+ verbose_name_plural = 'zbiórki'
ordering = ['-end']
- def __unicode__(self):
- return u"%s - %s" % (self.author, self.title)
+ def __str__(self):
+ return "%s - %s" % (self.author, self.title)
def get_absolute_url(self):
return reverse('funding_offer', args=[self.slug])
@@ -59,26 +59,19 @@ class Offer(models.Model):
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)
- self.flush_includes()
+ self.clear_cache()
if published_now:
self.notify_published()
return retval
- def flush_includes(self):
- flush_ssi_includes([
- template % (self.pk, lang)
- for template in [
- '/wesprzyj/o/%d/top-bar.%s.html',
- '/wesprzyj/o/%d/detail-bar.%s.html',
- '/wesprzyj/o/%d/list-bar.%s.html',
- '/wesprzyj/o/%d/status.%s.html',
- '/wesprzyj/o/%d/status-more.%s.html',
- ] + [
- '/wesprzyj/o/%%d/fundings/%d.%%s.html' % page
- for page in range(1, len(self.funding_payed()) // 10 + 2)
- ]
- for lang in [lc for (lc, _ln) in settings.LANGUAGES]
- ])
+ 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.detail_bar)
+ clear_cached_renders(self.status)
+ clear_cached_renders(self.status_more)
def is_current(self):
return self.start <= date.today() <= self.end and self == self.current()
@@ -144,7 +137,7 @@ class Offer(models.Model):
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. """
@@ -161,7 +154,7 @@ class Offer(models.Model):
return
assert not self.is_current()
self.notify_all(
- _('The fundraiser has ended!'),
+ _('Zbiórka dobiegÅa koÅca!'),
'funding/email/end.txt', {
'offer': self,
'is_win': self.is_win(),
@@ -178,7 +171,7 @@ class Offer(models.Model):
sum_ = self.sum()
need = self.target - sum_
self.notify_all(
- _('The fundraiser will end soon!'),
+ _('Zbiórka niedÅugo siÄ zakoÅczy!'),
'funding/email/near.txt', {
'days': (self.end - date.today()).days + 1,
'offer': self,
@@ -192,7 +185,7 @@ class Offer(models.Model):
def notify_published(self):
assert self.book is not None
self.notify_all(
- _('The book you helped fund has been published.'),
+ _('KsiÄ
żka, którÄ
pomogÅeÅ/-aÅ ufundowaÄ, zostaÅa opublikowana.'),
'funding/email/published.txt', {
'offer': self,
'book': self.book,
@@ -200,6 +193,46 @@ class Offer(models.Model):
'current': self.current(),
})
+ def basic_info(self):
+ offer_sum = self.sum()
+ return {
+ 'offer': self,
+ 'sum': offer_sum,
+ 'is_current': self.is_current(),
+ 'is_win': offer_sum >= self.target,
+ 'missing': self.target - offer_sum,
+ 'percentage': min(100, 100 * offer_sum / self.target),
+
+ 'show_title': True,
+ 'show_title_calling': True,
+ }
+
+ @cached_render('funding/includes/offer_status.html')
+ def status(self):
+ return {'offer': self}
+
+ @cached_render('funding/includes/offer_status_more.html')
+ def status_more(self):
+ return {'offer': self}
+
+ @cached_render('funding/includes/funding.html')
+ def top_bar(self):
+ ctx = self.basic_info()
+ ctx.update({
+ 'link': True,
+ 'closeable': True,
+ 'add_class': 'funding-top-header',
+ })
+ return ctx
+
+ @cached_render('funding/includes/funding.html')
+ def detail_bar(self):
+ ctx = self.basic_info()
+ ctx.update({
+ 'show_title': False,
+ })
+ return ctx
+
class Perk(models.Model):
""" A perk offer.
@@ -207,52 +240,79 @@ class Perk(models.Model):
If no attached to a particular Offer, applies to all.
"""
- 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)
- long_name = models.CharField(_('long name'), max_length=255)
- end_date = models.DateField(_('end date'), null=True, blank=True)
+ offer = models.ForeignKey(Offer, models.CASCADE, verbose_name='zbiórka', null=True, blank=True)
+ price = models.DecimalField('cena', decimal_places=2, max_digits=10)
+ name = models.CharField('nazwa', max_length=255)
+ long_name = models.CharField('dÅuga nazwa', max_length=255)
+ end_date = models.DateField('data koÅcowa', null=True, blank=True)
class Meta:
- verbose_name = _('perk')
- verbose_name_plural = _('perks')
+ verbose_name = 'prezent'
+ verbose_name_plural = 'prezenty'
ordering = ['-price']
- def __unicode__(self):
- return "%s (%s%s)" % (self.name, self.price, u" for %s" % self.offer if self.offer else "")
+ def __str__(self):
+ 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.
- 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, verbose_name=_('offer'))
- name = models.CharField(_('name'), max_length=127, blank=True)
- email = models.EmailField(_('email'), blank=True, db_index=True)
- 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)
+ offer = models.ForeignKey(Offer, models.PROTECT, verbose_name='zbiórka')
+ customer_ip = models.GenericIPAddressField('adres IP', null=True, blank=True)
+
+ name = models.CharField('nazwa', max_length=127, blank=True)
+ email = models.EmailField('e-mail', blank=True, db_index=True)
+ user = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True)
+ amount = models.DecimalField('kwota', decimal_places=2, max_digits=10)
+ perks = models.ManyToManyField(Perk, verbose_name='prezenty', 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)
+ notifications = models.BooleanField('powiadomienia', default=True, db_index=True)
+ notify_key = models.CharField(max_length=32, blank=True)
class Meta:
- verbose_name = _('funding')
- verbose_name_plural = _('fundings')
- ordering = ['-payed_at', 'pk']
+ verbose_name = 'wpÅata'
+ verbose_name_plural = 'wpÅaty'
+ ordering = ['-completed_at', 'pk']
@classmethod
def payed(cls):
""" QuerySet for all completed payments. """
- return cls.objects.exclude(payed_at=None)
+ return cls.objects.exclude(completed_at=None)
- def __unicode__(self):
- return unicode(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())
@@ -265,18 +325,21 @@ class Funding(models.Model):
'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)
ret = super(Funding, self).save(*args, **kwargs)
- self.offer.flush_includes()
+ self.offer.clear_cache()
return ret
@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)
+ funders = funders.exclude(completed_at=None)
if query_filter is not None:
funders = funders.filter(query_filter)
emails = set()
@@ -303,46 +366,37 @@ class Funding(models.Model):
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):
""" Some of the remaining money spent on a book. """
- book = models.ForeignKey(Book)
- amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10)
- timestamp = models.DateField(_('when'))
+ book = models.ForeignKey(
+ Book, models.PROTECT, null=True, blank=True,
+ verbose_name='ksiÄ
żka',
+ help_text='KsiÄ
żka, na którÄ
zostaÅy wydatkowane Årodki. '
+ 'Powinny tu byÄ uwzglÄdnione zarówno ksiÄ
żki na które zbierano Årodki, jak i dodatkowe ksiÄ
żki '
+ 'sfinansowane z nadwyżek ze zbiórek.'
+ )
+ link = models.URLField(
+ blank=True,
+ help_text="JeÅli wydatek nie dotyczy pojedynczej ksiÄ
żki, to zamiast pola âKsiÄ
żkaâ "
+ "powinien zostaÄ uzupeÅniony link do sfinansowanego obiektu (np. kolekcji)."
+ )
+ amount = models.DecimalField('kwota', decimal_places=2, max_digits=10)
+ timestamp = models.DateField('kiedy')
+ annotation = models.CharField(
+ 'adnotacja', max_length=255, blank=True,
+ help_text="Adnotacja pojawi siÄ w nawiasie w rozliczeniu, by wyjaÅniÄ sytuacjÄ w której "
+ "do tej samej ksiÄ
żki może byÄ przypisany wiÄcej niż jeden wydatek. "
+ "Np. osobny wydatek na audiobook może mieÄ adnotacjÄ âaudiobookâ.")
class Meta:
- verbose_name = _('money spent on a book')
- verbose_name_plural = _('money spent on books')
+ verbose_name = 'pieniÄ
dze wydane na ksiÄ
żkÄ'
+ verbose_name_plural = 'pieniÄ
dze wydane na ksiÄ
żki'
ordering = ['-timestamp']
- def __unicode__(self):
- return u"Spent: %s" % unicode(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
-
+ def __str__(self):
+ return "Wydane na: %s" % str(self.book or self.link)
-@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'
- )