1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
4 from datetime import date, datetime
5 from urllib.parse import urlencode
6 from django.conf import settings
7 from django.contrib.sites.models import Site
8 from django.core.mail import send_mail
9 from django.db import models
10 from django.dispatch import receiver
11 from django.template.loader import render_to_string
12 from django.urls import reverse
13 from django.utils.html import mark_safe
14 from django.utils.timezone import utc
15 from django.utils.translation import gettext_lazy as _, override
16 from catalogue.models import Book
17 from catalogue.utils import get_random_hash
18 from polls.models import Poll
19 import club.payu.models
20 from wolnelektury.utils import cached_render, clear_cached_renders
21 from . import app_settings
25 class Offer(models.Model):
26 """ A fundraiser for a particular book. """
27 author = models.CharField('autor', max_length=255)
28 title = models.CharField('tytuł', max_length=255)
29 slug = models.SlugField('slug')
30 description = models.TextField('opis', blank=True)
31 target = models.DecimalField('kwota docelowa', decimal_places=2, max_digits=10)
32 start = models.DateField('początek', db_index=True)
33 end = models.DateField('koniec', db_index=True)
34 redakcja_url = models.URLField('URL na Redakcji', blank=True)
35 book = models.ForeignKey(Book, models.PROTECT, null=True, blank=True, help_text='Opublikowana książka.')
36 cover = models.ImageField('Okładka', upload_to='funding/covers')
37 poll = models.ForeignKey(Poll, help_text='Ankieta', null=True, blank=True, on_delete=models.SET_NULL)
39 notified_near = models.DateTimeField('Wysłano powiadomienia przed końcem', blank=True, null=True)
40 notified_end = models.DateTimeField('Wysłano powiadomienia o zakończeniu', blank=True, null=True)
42 def cover_img_tag(self):
43 return mark_safe('<img src="%s" />' % self.cover.url)
44 cover_img_tag.short_description = 'Podgląd okładki'
47 verbose_name = 'zbiórka'
48 verbose_name_plural = 'zbiórki'
52 return "%s - %s" % (self.author, self.title)
54 def get_absolute_url(self):
55 return reverse('funding_offer', args=[self.slug])
57 def save(self, *args, **kw):
59 self.book_id is not None and self.pk is not None and
60 type(self).objects.values('book').get(pk=self.pk)['book'] != self.book_id)
61 retval = super(Offer, self).save(*args, **kw)
64 self.notify_published()
67 def get_payu_payment_title(self):
68 return utils.sanitize_payment_title(str(self))
70 def clear_cache(self):
71 clear_cached_renders(self.top_bar)
72 clear_cached_renders(self.detail_bar)
73 clear_cached_renders(self.status)
74 clear_cached_renders(self.status_more)
77 return self.start <= date.today() <= self.end and self == self.current()
80 return self.sum() >= self.target
86 return self.sum() - self.target
92 """ Returns current fundraiser or None.
94 Current fundraiser is the one that:
95 - has already started,
97 - if there's more than one of those, it's the one that ends last.
101 objects = cls.objects.filter(start__lte=today, end__gte=today).order_by('-end')
109 """ QuerySet for all past fundraisers. """
110 objects = cls.public()
111 current = cls.current()
112 if current is not None:
113 objects = objects.exclude(pk=current.pk)
118 """ QuerySet for all current and past fundraisers. """
120 return cls.objects.filter(start__lte=today)
122 def get_perks(self, amount=None):
123 """ Finds all the perks for the offer.
125 If amount is provided, returns the perks you get for it.
128 perks = Perk.objects.filter(
129 models.Q(offer=self) | models.Q(offer=None)
130 ).exclude(end_date__lt=date.today())
131 if amount is not None:
132 perks = perks.filter(price__lte=amount)
135 def funding_payed(self):
136 """ QuerySet for all completed payments for the offer. """
137 return Funding.payed().filter(offer=self)
140 return self.funding_payed().order_by('-amount', 'completed_at')
143 """ The money gathered. """
144 return self.funding_payed().aggregate(s=models.Sum('amount'))['s'] or 0
146 def notify_all(self, subject, template_name, extra_context=None):
147 Funding.notify_funders(
148 subject, template_name, extra_context,
149 query_filter=models.Q(offer=self)
152 def notify_end(self, force=False):
153 if not force and self.notified_end:
155 assert not self.is_current()
157 _('Zbiórka dobiegła końca!'),
158 'funding/email/end.txt', {
160 'is_win': self.is_win(),
161 'remaining': self.remaining(),
162 'current': self.current(),
164 self.notified_end = datetime.utcnow().replace(tzinfo=utc)
167 def notify_near(self, force=False):
168 if not force and self.notified_near:
170 assert self.is_current()
172 need = self.target - sum_
174 _('Zbiórka niedługo się zakończy!'),
175 'funding/email/near.txt', {
176 'days': (self.end - date.today()).days + 1,
178 'is_win': self.is_win(),
182 self.notified_near = datetime.utcnow().replace(tzinfo=utc)
185 def notify_published(self):
186 assert self.book is not None
188 _('Książka, którą pomogłeś/-aś ufundować, została opublikowana.'),
189 'funding/email/published.txt', {
192 'author': self.book.pretty_title(),
193 'current': self.current(),
196 def basic_info(self):
197 offer_sum = self.sum()
201 'is_current': self.is_current(),
202 'is_win': offer_sum >= self.target,
203 'missing': self.target - offer_sum,
204 'percentage': min(100, 100 * offer_sum / self.target),
207 'show_title_calling': True,
210 @cached_render('funding/includes/offer_status.html')
212 return {'offer': self}
214 @cached_render('funding/includes/offer_status_more.html')
215 def status_more(self):
216 return {'offer': self}
218 @cached_render('funding/includes/funding.html')
220 ctx = self.basic_info()
224 'add_class': 'funding-top-header',
228 @cached_render('funding/includes/funding.html')
229 def detail_bar(self):
230 ctx = self.basic_info()
237 class Perk(models.Model):
240 If no attached to a particular Offer, applies to all.
243 offer = models.ForeignKey(Offer, models.CASCADE, verbose_name='zbiórka', null=True, blank=True)
244 price = models.DecimalField('cena', decimal_places=2, max_digits=10)
245 name = models.CharField('nazwa', max_length=255)
246 long_name = models.CharField('długa nazwa', max_length=255)
247 end_date = models.DateField('data końcowa', null=True, blank=True)
250 verbose_name = 'prezent'
251 verbose_name_plural = 'prezenty'
252 ordering = ['-price']
255 return "%s (%s%s)" % (self.name, self.price, " for %s" % self.offer if self.offer else "")
258 class Funding(club.payu.models.Order):
259 """ A person paying in a fundraiser.
261 The payment was completed if and only if completed_at is set.
264 offer = models.ForeignKey(Offer, models.PROTECT, verbose_name='zbiórka')
265 customer_ip = models.GenericIPAddressField('adres IP', null=True, blank=True)
267 name = models.CharField('nazwa', max_length=127, blank=True)
268 email = models.EmailField('e-mail', blank=True, db_index=True)
269 user = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True)
270 amount = models.DecimalField('kwota', decimal_places=2, max_digits=10)
271 perks = models.ManyToManyField(Perk, verbose_name='prezenty', blank=True)
272 language_code = models.CharField(max_length=2, null=True, blank=True)
273 notifications = models.BooleanField('powiadomienia', default=True, db_index=True)
274 notify_key = models.CharField(max_length=32, blank=True)
277 verbose_name = 'wpłata'
278 verbose_name_plural = 'wpłaty'
279 ordering = ['-completed_at', 'pk']
283 """ QuerySet for all completed payments. """
284 return cls.objects.exclude(completed_at=None)
287 return str(self.offer)
289 def get_amount(self):
295 "language": self.language_code,
298 def get_description(self):
299 return self.offer.get_payu_payment_title()
301 def get_thanks_url(self):
302 return reverse('funding_thanks')
304 def status_updated(self):
305 if self.status == 'COMPLETED':
308 _('Thank you for your support!'),
309 'funding/email/thanks.txt'
312 def get_notify_url(self):
313 return "https://{}{}".format(
314 Site.objects.get_current().domain,
315 reverse('funding_payu_notify', args=[self.pk]))
317 def perk_names(self):
318 return ", ".join(perk.name for perk in self.perks.all())
320 def get_disable_notifications_url(self):
322 reverse("funding_disable_notifications"),
325 'key': self.notify_key,
328 def wl_optout_url(self):
329 return 'https://wolnelektury.pl' + self.get_disable_notifications_url()
331 def save(self, *args, **kwargs):
332 if self.email and not self.notify_key:
333 self.notify_key = get_random_hash(self.email)
334 ret = super(Funding, self).save(*args, **kwargs)
335 self.offer.clear_cache()
339 def notify_funders(cls, subject, template_name, extra_context=None, query_filter=None, payed_only=True):
340 funders = cls.objects.exclude(email="").filter(notifications=True)
342 funders = funders.exclude(completed_at=None)
343 if query_filter is not None:
344 funders = funders.filter(query_filter)
346 for funder in funders:
347 if funder.email in emails:
349 emails.add(funder.email)
350 funder.notify(subject, template_name, extra_context)
352 def notify(self, subject, template_name, extra_context=None):
355 'site': Site.objects.get_current(),
358 context.update(extra_context)
359 with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
361 subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
364 def disable_notifications(self):
365 """Disables all notifications for this e-mail address."""
366 type(self).objects.filter(email=self.email).update(notifications=False)
369 class PayUNotification(club.payu.models.Notification):
370 order = models.ForeignKey(Funding, models.CASCADE, related_name='notification_set')
373 class Spent(models.Model):
374 """ Some of the remaining money spent on a book. """
375 book = models.ForeignKey(
376 Book, models.PROTECT, null=True, blank=True,
377 verbose_name='książka',
378 help_text='Książka, na którą zostały wydatkowane środki. '
379 'Powinny tu być uwzględnione zarówno książki na które zbierano środki, jak i dodatkowe książki '
380 'sfinansowane z nadwyżek ze zbiórek.'
382 link = models.URLField(
384 help_text="Jeśli wydatek nie dotyczy pojedynczej książki, to zamiast pola „Książka” "
385 "powinien zostać uzupełniony link do sfinansowanego obiektu (np. kolekcji)."
387 amount = models.DecimalField('kwota', decimal_places=2, max_digits=10)
388 timestamp = models.DateField('kiedy')
389 annotation = models.CharField(
390 'adnotacja', max_length=255, blank=True,
391 help_text="Adnotacja pojawi się w nawiasie w rozliczeniu, by wyjaśnić sytuację w której "
392 "do tej samej książki może być przypisany więcej niż jeden wydatek. "
393 "Np. osobny wydatek na audiobook może mieć adnotację „audiobook”.")
396 verbose_name = 'pieniądze wydane na książkę'
397 verbose_name_plural = 'pieniądze wydane na książki'
398 ordering = ['-timestamp']
401 return "Wydane na: %s" % str(self.book or self.link)