diff --git a/apps/notification/management/commands/animail_logs.py b/apps/notification/management/commands/animail_logs.py index 57bac50f..ead02e4f 100644 --- a/apps/notification/management/commands/animail_logs.py +++ b/apps/notification/management/commands/animail_logs.py @@ -1,9 +1,10 @@ from email.utils import format_datetime import requests -from datetime import datetime +from datetime import datetime, timedelta from django.core.management.base import BaseCommand from django.conf import settings +from django.utils import timezone def get_logs(limit, date, subject): @@ -43,9 +44,14 @@ class Command(BaseCommand): help='Limit', ) parser.add_argument( - '--date', - dest='date', - help='Date', + '--date_start', + dest='date_start', + help='Date start', + ) + parser.add_argument( + '--date_end', + dest='date_end', + help='Date end', ) parser.add_argument( '--subject', @@ -55,11 +61,14 @@ class Command(BaseCommand): def handle(self, *args, **options): emails = [] - end_dt = datetime(2019, 7, 11) - current_dt = options.get('date') - while current_dt <= end_dt: - e, current_dt = get_logs(options.get('limit'), current_dt, options.get('subject')) + date_start = datetime.strptime(options.get('date_start'), '%Y-%m-%d') + date_end = datetime.strptime(options.get('date_end'), '%Y-%m-%d') + timedelta(hours=23, minutes=59) \ + if options.get('date_end') else timezone.now() + while date_start <= date_end: + e, date_start = get_logs(options.get('limit') or 300, date_start, options.get('subject')) + if not e: + break emails += e print(set(emails)) - print(current_dt) + print(date_start) diff --git a/apps/notification/tasks.py b/apps/notification/tasks.py index 9b2173fa..477e9a94 100644 --- a/apps/notification/tasks.py +++ b/apps/notification/tasks.py @@ -49,26 +49,24 @@ def draw_cert(path, email, first_name, last_name, x=None, y=900, color=(29, 115, return fn @app.task -def send_certificates(email=None, date_end=None, dry_run=False): +def send_certificates(email=None, date_end=None, dry_run=False, users=None, subject='Грамота от Lil School', + template='notification/email/certificate.html'): signed_path_pattern = 'signed-user-certificates/%d.jpg' if email: - fn = draw_cert(os.path.join(settings.RESOURCES_ROOT, signed_path_pattern % 1), email, 'Имя', 'Фамилия') - file = open(fn, 'rb') try: send_email('Грамота от Lil School', email, 'notification/email/certificate.html', - attachments=[(file.name, file.read(), 'image/jpeg')]) + childs=[], certificate_number=1, many_childs=False, child_filled=False) except: pass else: print('Email has been sent') finally: - file.close() - os.remove(fn) return date_end = datetime.strptime(date_end, '%d-%m-%Y').date() if date_end else now().date() today = now().date() - users = set(list(SchoolPayment.objects.paid().filter(date_end=date_end, add_days=False).values_list('user_id', flat=True))) + if users is None: + users = set(list(SchoolPayment.objects.paid().filter(date_end=date_end, add_days=False).values_list('user_id', flat=True))) user_notifications_qs = UserNotification.objects.filter(user_id__in=users) user_notifications = {un.user_id: un for un in user_notifications_qs} notified_users = user_notifications_qs.filter(certificate_last_email__date=today).values_list( @@ -88,8 +86,8 @@ def send_certificates(email=None, date_end=None, dry_run=False): else 1 un.save() try: - send_email('Грамота от Lil School', un.user.email, 'notification/email/certificate.html', - childs=un.user.childs.all(), user_notification=un, + send_email(subject, un.user.email, template, + childs=un.user.childs.all(), certificate_number=un.certificate_number, many_childs=un.user.childs.all().count() > 1, child_filled=un.user.child_filled) except Exception as e: print('Not OK') diff --git a/apps/notification/templates/notification/email/certificate.html b/apps/notification/templates/notification/email/certificate.html index 9b396841..32e60547 100644 --- a/apps/notification/templates/notification/email/certificate.html +++ b/apps/notification/templates/notification/email/certificate.html @@ -4,7 +4,7 @@ {% block content %}

Привет!

- {% if not user_notification or user_notification.certificate_number == 1 %} + {% if certificate_number == 1 %}

Поздравляем! Вы прошли месяц обучения в Lil School.
В письме {% if many_childs %}ссылки на грамоты. Распечатайте их и вручите вашим детям. @@ -12,13 +12,13 @@ Ждём вас в следующем месяце на наших творческих занятиях!

{% endif %} - {% if user_notification and user_notification.certificate_number == 2 %} + {% if certificate_number == 2 %}

Вы помните, что каждый месяц вам {% if many_childs %}приходят грамоты{% else %}приходит грамота{% endif %} за прекрасную учебу в нашей творческой школе?
Скачивайте. Распечатывайте. И соберите свою коллекцию!

{% endif %} - {% if user_notification and user_notification.certificate_number == 3 %} + {% if certificate_number == 3 %}

Вам понравился наш творческий месяц?
В письме вы найдёте {% if many_childs %}ссылки на грамоты, они{% else %}ссылку на грамоту, она{% endif %} для вашей семьи.
@@ -26,14 +26,14 @@ Ждём вас в следующем месяце.

{% endif %} - {% if user_notification and user_notification.certificate_number == 4 %} + {% if certificate_number == 4 %}

Прошёл целый месяц обучения на платформе Lil School - месяц творчества, креатива и невероятных идей.
Во письме вас {% if many_childs %}ждут ссылки на грамоты{% else %}ждёт ссылка на грамоту{% endif %}.
До встречи на занятиях!

{% endif %} - {% if user_notification and user_notification.certificate_number == 5 %} + {% if certificate_number == 5 %}

{% if many_childs %} Ваши грамоты за успехи в учебе в Lil School ждут вас.
@@ -46,7 +46,7 @@ До встречи в следующем месяце!

{% endif %} - {% if user_notification and user_notification.certificate_number == 6 %} + {% if certificate_number == 6 %}

Как здорово вы потрудились на занятиях в этом месяце!
И {% if many_childs %}наши грамоты уже ждут{% else %}наша грамота уже ждёт{% endif %} вас!
@@ -54,14 +54,14 @@ Ждём вас в следующем месяце!

{% endif %} - {% if user_notification and user_notification.certificate_number == 7 %} + {% if certificate_number == 7 %}

Какой классный месяц у нас был! Вместе мы очень здорово и креативно потрудились.
В письме вас {% if many_childs %}ждут ссылки на заслуженные грамоты{% else %}ждёт ссылка на заслуженную грамоту{% endif %}!
До встречи на уроках!

{% endif %} - {% if user_notification and user_notification.certificate_number == 8 %} + {% if certificate_number == 8 %}

Месяц творчества и креатива пролетел как один миг! А как много работ мы вместе сделали!
Вы - большие молодцы.
@@ -73,11 +73,11 @@ {% if many_childs %} Ссылки на грамоты:
{% for child in childs %} - Грамота ({{ child.full_name }})
+ Грамота ({{ child.full_name }})
{% endfor %} {% else %} Ссылка на грамоту:
- Скачать грамоту + Скачать грамоту {% endif %}