services.py 1.94 KB
Newer Older
1
2
3
4
import os

from django.conf import settings
from django.template.loader import get_template
5
from django.utils import translation, timezone
6

7
from events.models import Event
8
from newsletters import emails
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from partners.models import Partner


def write_to_file(pk, lang, html_message):
    """
    Write newsletter to a file
    """
    cache_dir = os.path.join(settings.MEDIA_ROOT, 'newsletters')
    if not os.path.isdir(cache_dir):
        os.makedirs(cache_dir)

    with open(os.path.join(
        cache_dir,
        f'{pk}_{lang}.html'
    ), 'w+') as cache_file:
        cache_file.write(html_message)


def save_to_disk(newsletter, request):
    """
    Writes the newsletter as HTML to file (in all languages)
    """
    partners = Partner.objects.filter(is_main_partner=True)
    main_partner = partners[0] if len(partners) > 0 else None

    html_template = get_template('newsletters/email.html')

    for language in settings.LANGUAGES:
        translation.activate(language[0])

        context = {
            'newsletter': newsletter,
            'agenda_events': (
                newsletter.newslettercontent_set
                .filter(newsletteritem=None)
                .order_by('newsletterevent__start_datetime')
            ),
            'main_partner': main_partner,
            'lang_code': language[0],
            'request': request
        }

        html_message = html_template.render(context)

        write_to_file(newsletter.pk, language[0], html_message)
54
55
56
57
58
59
60
61
62
63


def get_agenda(start_date):
    end_date = start_date + timezone.timedelta(weeks=2)
    base_events = Event.objects.filter(
        start__gte=start_date, end__lt=end_date).order_by('start')
    if base_events.count() < 10:
        more_events = Event.objects.filter(end__gte=end_date).order_by('start')
        return [*base_events, *more_events][:10]
    return base_events
64
65
66
67
68
69


def send_newsletter(newsletter):
    emails.send_newsletter(newsletter)
    newsletter.sent = True
    newsletter.save()