X-Git-Url: https://git.mdrn.pl/wolnelektury.git/blobdiff_plain/357027375ff8867f42ca34bcbfb5a78b5b185fc3..0d652be22f4d6e5276e16f493ce58294655d7a0f:/src/funding/models.py?ds=sidebyside diff --git a/src/funding/models.py b/src/funding/models.py index e36b73255..79385a20d 100644 --- a/src/funding/models.py +++ b/src/funding/models.py @@ -1,22 +1,22 @@ -# -*- 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. # 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.timezone import utc from django.utils.translation import ugettext_lazy as _, override import getpaid -from ssify import flush_ssi_includes from catalogue.models import Book from catalogue.utils import get_random_hash from polls.models import Poll +from wolnelektury.utils import cached_render, clear_cached_renders from . import app_settings @@ -30,8 +30,7 @@ class Offer(models.Model): 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.')) + book = models.ForeignKey(Book, models.PROTECT, 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) @@ -39,7 +38,7 @@ class Offer(models.Model): notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True) def cover_img_tag(self): - return u'' % self.cover.url + return '' % self.cover.url cover_img_tag.short_description = _('Cover preview') cover_img_tag.allow_tags = True @@ -48,37 +47,28 @@ class Offer(models.Model): verbose_name_plural = _('offers') 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]) def save(self, *args, **kw): - published_now = (self.book_id is not None and - self.pk is not None and + 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) - 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 clear_cache(self): + clear_cached_renders(self.top_bar) + clear_cached_renders(self.list_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() @@ -157,7 +147,8 @@ class Offer(models.Model): ) def notify_end(self, force=False): - if not force and self.notified_end: return + if not force and self.notified_end: + return assert not self.is_current() self.notify_all( _('The fundraiser has ended!'), @@ -171,7 +162,8 @@ class Offer(models.Model): self.save() def notify_near(self, force=False): - if not force and self.notified_near: return + if not force and self.notified_near: + return assert self.is_current() sum_ = self.sum() need = self.target - sum_ @@ -198,6 +190,55 @@ 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': 100 * offer_sum / self.target, + + 'show_title': True, + 'show_title_calling': True, + } + + @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 list_bar(self): + ctx = self.basic_info() + ctx.update({ + 'link': True, + 'show_title_calling': False, + }) + return ctx + + @cached_render('funding/includes/funding.html') + def detail_bar(self): + ctx = self.basic_info() + ctx.update({ + 'show_title': False, + }) + return ctx + + @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} + class Perk(models.Model): """ A perk offer. @@ -205,7 +246,7 @@ 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) + offer = models.ForeignKey(Offer, models.CASCADE, 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) @@ -216,8 +257,8 @@ class Perk(models.Model): verbose_name_plural = _('perks') 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): @@ -226,7 +267,7 @@ class Funding(models.Model): The payment was completed if and only if payed_at is set. """ - offer = models.ForeignKey(Offer, verbose_name=_('offer')) + offer = models.ForeignKey(Offer, models.PROTECT, 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) @@ -239,15 +280,15 @@ class Funding(models.Model): class Meta: verbose_name = _('funding') verbose_name_plural = _('fundings') - ordering = ['-payed_at'] + ordering = ['-payed_at', 'pk'] @classmethod def payed(cls): """ QuerySet for all completed payments. """ return cls.objects.exclude(payed_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]) @@ -256,7 +297,8 @@ class Funding(models.Model): return ", ".join(perk.name for perk in self.perks.all()) def get_disable_notifications_url(self): - return "%s?%s" % (reverse("funding_disable_notifications"), + return "%s?%s" % ( + reverse("funding_disable_notifications"), urlencode({ 'email': self.email, 'key': self.notify_key, @@ -266,12 +308,11 @@ class Funding(models.Model): 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): + 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) @@ -292,12 +333,9 @@ class Funding(models.Model): if extra_context: context.update(extra_context) with override(self.language_code or app_settings.DEFAULT_LANGUAGE): - send_mail(subject, - render_to_string(template_name, context), - settings.CONTACT_EMAIL, - [self.email], - fail_silently=False - ) + send_mail( + subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email], + fail_silently=False) def disable_notifications(self): """Disables all notifications for this e-mail address.""" @@ -310,7 +348,7 @@ getpaid.register_to_payment(Funding, unique=False, related_name='payment') class Spent(models.Model): """ Some of the remaining money spent on a book. """ - book = models.ForeignKey(Book) + book = models.ForeignKey(Book, models.PROTECT) amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10) timestamp = models.DateField(_('when')) @@ -319,22 +357,24 @@ class Spent(models.Model): verbose_name_plural = _('money spent on books') ordering = ['-timestamp'] - def __unicode__(self): - return u"Spent: %s" % unicode(self.book) + def __str__(self): + return "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' -getpaid.signals.new_payment_query.connect(new_payment_query_listener) +@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 -getpaid.signals.user_data_query.connect(user_data_query_listener) + +@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': @@ -345,4 +385,3 @@ def payment_status_changed_listener(sender, instance, old_status, new_status, ** _('Thank you for your support!'), 'funding/email/thanks.txt' ) -getpaid.signals.payment_status_changed.connect(payment_status_changed_listener)