Fundraising in PDF.
[wolnelektury.git] / src / social / models.py
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.
3 #
4 from random import randint
5 from django.db import models
6 from django.conf import settings
7 from django.core.exceptions import ValidationError
8 from django.urls import reverse
9 from catalogue.models import Book
10 from wolnelektury.utils import cached_render, clear_cached_renders
11
12
13 class BannerGroup(models.Model):
14     name = models.CharField('nazwa', max_length=255, unique=True)
15     created_at = models.DateTimeField('utworzona', auto_now_add=True)
16
17     class Meta:
18         ordering = ('name',)
19         verbose_name = 'grupa bannerów'
20         verbose_name_plural = 'grupy bannerów'
21
22     def __str__(self):
23         return self.name
24
25     def get_absolute_url(self):
26         """This is used for testing."""
27         return "%s?banner_group=%d" % (reverse('main_page'), self.id)
28
29     def get_banner(self):
30         banners = self.cite_set.all()
31         count = banners.count()
32         if not count:
33             return None
34         return banners[randint(0, count-1)]
35
36
37 class Cite(models.Model):
38     book = models.ForeignKey(Book, models.CASCADE, verbose_name='książka', null=True, blank=True)
39     text = models.TextField('tekst', blank=True)
40     small = models.BooleanField(
41         'mały', default=False, help_text='Sprawia, że cytat wyświetla się mniejszym fontem.')
42     vip = models.CharField('VIP', max_length=128, null=True, blank=True)
43     link = models.URLField('odnośnik')
44     video = models.URLField('wideo', blank=True)
45     picture = models.ImageField('ilustracja', blank=True,
46             help_text='Najlepsze wymiary: 975 x 315 z tekstem, 487 x 315 bez tekstu.')
47     picture_alt = models.CharField('alternatywny tekst ilustracji', max_length=255, blank=True)
48     picture_title = models.CharField('tytuł ilustracji', max_length=255, null=True, blank=True)
49     picture_author = models.CharField('autor ilustracji', max_length=255, blank=True, null=True)
50     picture_link = models.URLField('link ilustracji', blank=True, null=True)
51     picture_license = models.CharField('nazwa licencji ilustracji', max_length=255, blank=True, null=True)
52     picture_license_link = models.URLField('adres licencji ilustracji', blank=True, null=True)
53
54     sticky = models.BooleanField('przyklejony', default=False, db_index=True,
55                                  help_text='Przyklejone cytaty mają pierwszeństwo.')
56     background_plain = models.BooleanField('jednobarwne tło', default=False)
57     background_color = models.CharField('kolor tła', max_length=32, blank=True)
58     image = models.ImageField(
59         'obraz tła', upload_to='social/cite', null=True, blank=True,
60         help_text='Najlepsze tło ma wielkość 975 x 315 px i waży poniżej 100kB.')
61     image_title = models.CharField('tytuł obrazu tła', max_length=255, null=True, blank=True)
62     image_author = models.CharField('autor obrazu tła', max_length=255, blank=True, null=True)
63     image_link = models.URLField('link obrazu tła', blank=True, null=True)
64     image_license = models.CharField('nazwa licencji obrazu tła', max_length=255, blank=True, null=True)
65     image_license_link = models.URLField('adres licencji obrazu tła', blank=True, null=True)
66
67     created_at = models.DateTimeField('utworzony', auto_now_add=True)
68     group = models.ForeignKey(BannerGroup, verbose_name='grupa', null=True, blank=True, on_delete=models.SET_NULL)
69
70     class Meta:
71         ordering = ('vip', 'text')
72         verbose_name = 'banner'
73         verbose_name_plural = 'bannery'
74
75     def __str__(self):
76         t = []
77         if self.text:
78             t.append(self.text[:60])
79         if self.book_id:
80             t.append('[ks.]'[:60])
81         t.append(self.link[:60])
82         if self.vip:
83             t.append('vip: ' + self.vip)
84         if self.picture:
85             t.append('[obr.]')
86         if self.video:
87             t.append('[vid.]')
88         return ', '.join(t)
89
90     def get_absolute_url(self):
91         """This is used for testing."""
92         return "%s?banner=%d" % (reverse('main_page'), self.id)
93
94     def has_box(self):
95         return self.video or self.picture
96
97     def has_body(self):
98         return self.vip or self.text or self.book
99
100     def layout(self):
101         pieces = []
102         if self.has_box():
103             pieces.append('box')
104         if self.has_body():
105             pieces.append('text')
106         return '-'.join(pieces)
107
108
109     def save(self, *args, **kwargs):
110         ret = super(Cite, self).save(*args, **kwargs)
111         self.clear_cache()
112         return ret
113
114     @cached_render('social/cite_promo.html')
115     def main_box(self):
116         return {
117             'cite': self,
118             'main': True,
119         }
120
121     def clear_cache(self):
122         clear_cached_renders(self.main_box)
123
124
125 class Carousel(models.Model):
126     placement = models.SlugField('miejsce', choices=[
127         ('main', 'main'),
128         ('main_2022', 'main 2022'),
129     ])
130     priority = models.SmallIntegerField('priorytet', default=0)
131     language = models.CharField('język', max_length=2, blank=True, default='', choices=settings.LANGUAGES)
132
133     class Meta:
134 #        ordering = ('placement', '-priority')
135         verbose_name = 'karuzela'
136         verbose_name_plural = 'karuzele'
137
138     def __str__(self):
139         return self.placement
140
141     @classmethod
142     def get(cls, placement):
143         carousel = cls.objects.filter(placement=placement).order_by('-priority', '?').first()
144         if carousel is None:
145             carousel = cls.objects.create(placement=placement)
146         return carousel
147
148
149 class CarouselItem(models.Model):
150     order = models.PositiveSmallIntegerField('kolejność')
151     carousel = models.ForeignKey(Carousel, models.CASCADE, verbose_name='karuzela')
152     banner = models.ForeignKey(
153         Cite, models.CASCADE, null=True, blank=True, verbose_name='banner')
154     banner_group = models.ForeignKey(
155         BannerGroup, models.CASCADE, null=True, blank=True, verbose_name='grupa bannerów')
156
157     class Meta:
158         ordering = ('order',)
159         verbose_name = 'element karuzeli'
160         verbose_name_plural = 'elementy karuzeli'
161
162     def __str__(self):
163         return str(self.banner or self.banner_group)
164
165     def clean(self):
166         if not self.banner and not self.banner_group:
167             raise ValidationError('Proszę wskazać banner albo grupę bannerów.')
168         elif self.banner and self.banner_group:
169             raise ValidationError('Proszę wskazać banner albo grupę bannerów.')
170
171     def get_banner(self):
172         return self.banner or self.banner_group.get_banner()