X-Git-Url: https://git.mdrn.pl/wolnelektury.git/blobdiff_plain/b412f294aa668eab3295a058f6c66845ef23ada7..ab81d95154bd35a67078cc6c926b5b9fbdd9011b:/apps/funding/models.py diff --git a/apps/funding/models.py b/apps/funding/models.py index f88659997..e36b73255 100644 --- a/apps/funding/models.py +++ b/apps/funding/models.py @@ -4,17 +4,20 @@ # from datetime import date, datetime from urllib 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.conf import settings -from django.template.loader import render_to_string from django.db import models -from django.utils.translation import ugettext_lazy as _, ugettext, override +from django.template.loader import render_to_string +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 django.contrib.sites.models import Site +from . import app_settings class Offer(models.Model): @@ -29,14 +32,17 @@ class Offer(models.Model): 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) - + 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) + def cover_img_tag(self): return u'' % 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') @@ -49,16 +55,33 @@ class Offer(models.Model): return reverse('funding_offer', args=[self.slug]) def save(self, *args, **kw): - published_now = (self.book_id 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() 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 is_current(self): - return self.start <= date.today() <= self.end + return self.start <= date.today() <= self.end and self == self.current() def is_win(self): return self.sum() >= self.target @@ -73,9 +96,16 @@ class Offer(models.Model): @classmethod def current(cls): - """ Returns current fundraiser or None. """ + """ Returns current fundraiser or None. + + Current fundraiser is the one that: + - has already started, + - hasn't yet ended, + - if there's more than one of those, it's the one that ends last. + + """ today = date.today() - objects = cls.objects.filter(start__lte=today, end__gte=today) + objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end') try: return objects[0] except IndexError: @@ -83,9 +113,12 @@ class Offer(models.Model): @classmethod def past(cls): - """ QuerySet for all current and past fundraisers. """ - today = date.today() - return cls.objects.filter(end__lt=today) + """ QuerySet for all past fundraisers. """ + objects = cls.public() + current = cls.current() + if current is not None: + objects = objects.exclude(pk=current.pk) + return objects @classmethod def public(cls): @@ -95,7 +128,7 @@ class Offer(models.Model): def get_perks(self, amount=None): """ Finds all the perks for the offer. - + If amount is provided, returns the perks you get for it. """ @@ -110,6 +143,9 @@ class Offer(models.Model): """ QuerySet for all completed payments for the offer. """ return Funding.payed().filter(offer=self) + def funders(self): + return self.funding_payed().order_by('-amount', 'payed_at') + def sum(self): """ The money gathered. """ return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0 @@ -120,7 +156,8 @@ class Offer(models.Model): query_filter=models.Q(offer=self) ) - def notify_end(self): + def notify_end(self, force=False): + if not force and self.notified_end: return assert not self.is_current() self.notify_all( _('The fundraiser has ended!'), @@ -130,8 +167,11 @@ class Offer(models.Model): 'remaining': self.remaining(), 'current': self.current(), }) + self.notified_end = datetime.utcnow().replace(tzinfo=utc) + self.save() - def notify_near(self): + def notify_near(self, force=False): + if not force and self.notified_near: return assert self.is_current() sum_ = self.sum() need = self.target - sum_ @@ -144,6 +184,8 @@ class Offer(models.Model): 'sum': sum_, 'need': need, }) + self.notified_near = datetime.utcnow().replace(tzinfo=utc) + self.save() def notify_published(self): assert self.book is not None @@ -152,14 +194,14 @@ class Offer(models.Model): 'funding/email/published.txt', { 'offer': self, 'book': self.book, - 'author': ", ".join(a[0] for a in self.book.related_info()['tags']['author']), + 'author': self.book.pretty_title(), 'current': self.current(), }) class Perk(models.Model): """ A perk offer. - + If no attached to a particular Offer, applies to all. """ @@ -190,7 +232,7 @@ class Funding(models.Model): 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) + 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) @@ -210,6 +252,9 @@ class Funding(models.Model): def get_absolute_url(self): return reverse('funding_funding', args=[self.pk]) + def perk_names(self): + return ", ".join(perk.name for perk in self.perks.all()) + def get_disable_notifications_url(self): return "%s?%s" % (reverse("funding_disable_notifications"), urlencode({ @@ -220,7 +265,9 @@ class Funding(models.Model): 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) + ret = super(Funding, self).save(*args, **kwargs) + self.offer.flush_includes() + return ret @classmethod def notify_funders(cls, subject, template_name, extra_context=None, @@ -242,11 +289,12 @@ class Funding(models.Model): 'funding': self, 'site': Site.objects.get_current(), } - context.update(extra_context) - with override(self.language_code or 'pl'): + 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), - getattr(settings, 'CONTACT_EMAIL', 'wolnelektury@nowoczesnapolska.org.pl'), + settings.CONTACT_EMAIL, [self.email], fail_silently=False ) @@ -290,7 +338,7 @@ 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.payed_at = datetime.utcnow().replace(tzinfo=utc) instance.order.save() if instance.order.email: instance.order.notify(