diff --git a/apps/notification/tasks.py b/apps/notification/tasks.py index 714392ba..462e22bc 100644 --- a/apps/notification/tasks.py +++ b/apps/notification/tasks.py @@ -3,12 +3,14 @@ from datetime import datetime, date, timedelta from PIL import Image from PIL import ImageFont from PIL import ImageDraw +from unidecode import unidecode from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.contrib.staticfiles.storage import staticfiles_storage from django.utils.timezone import now from django.conf import settings +from django.utils.text import slugify from apps.notification.models import UserNotification from apps.notification.utils import send_email @@ -16,6 +18,7 @@ from apps.payment.models import SchoolPayment, CoursePayment, Payment, UserGiftC from project.celery import app from project.utils.db import format_sql, execute_sql from project.sengrid import get_sendgrid_client +from apps.user.models import Child User = get_user_model() @@ -36,7 +39,11 @@ def draw_cert(path, email, first_name, last_name, x=None, y=900, color=(29, 115, os.mkdir(fn) except: pass - fn = os.path.join(fn, '%scertificate-for-%s.jpg' % (fn_prefix, email)) + if first_name: + name = '-'.join(filter(None, [first_name, last_name])) + fn = os.path.join(fn, '%scertificate-for-%s-%s.jpg' % (fn_prefix, email, slugify(unidecode(name)))) + else: + fn = os.path.join(fn, '%scertificate-for-%s.jpg' % (fn_prefix, email)) img.save(fn) img.close() return fn @@ -76,25 +83,30 @@ def send_certificates(email=None, date_end=None, dry_run=False): if dry_run: continue + file_names = [] un.certificate_number = un.certificate_number + 1 \ if un.certificate_number and staticfiles_storage.exists(path_pattern % (un.certificate_number + 1)) \ else 1 - if un.user.child_first_name: + if un.user.child_filled: fn = staticfiles_storage.path(signed_path_pattern % un.certificate_number) - fn = draw_cert(fn, un.user.email, un.user.child_first_name, un.user.child_last_name) + for child in un.user.childs.all(): + file_names.append(draw_cert(fn, un.user.email, child.first_name, child.last_name)) else: - fn = staticfiles_storage.path(path_pattern % un.certificate_number) - file = open(fn, 'rb') + file_names.append(staticfiles_storage.path(path_pattern % un.certificate_number)) + files = [open(fn, 'rb') for fn in file_names] try: send_email('Грамота от Lil School', un.user.email, 'notification/email/certificate.html', - attachments=[(file.name, file.read(), 'image/jpeg')], user_notification=un) + attachments=[(f.name, f.read(), 'image/jpeg') for f in files], user_notification=un, + many_childs=un.user.childs.all().count() > 1) except: print('Not OK') continue finally: - file.close() - if un.user.child_first_name: - os.remove(fn) + for f in files: + f.close() + if un.user.child_filled: + for fn in file_names: + os.remove(fn) un.certificate_last_email = now() un.save() @@ -148,19 +160,20 @@ def send_gift_certificate(user_gift_certificate): @app.task def send_child_birthday_email_and_bonuses(): - for u in User.objects.exclude(child_first_name='', child_last_name='',).filter(child_birthday=now().date()): - if not UserBonus.objects.filter(user=u, is_service=True, action_name=UserBonus.ACTION_CHILD_BIRTHDAY).count(): - print('user', u.email) - UserBonus.objects.create(user=u, amount=UserBonus.AMOUNT_CHILD_BIRTHDAY, is_service=True, + for user_id, email in set(Child.objects.filter(birthday=now().date()).select_related('user') + .values_list('user_id', 'user__email')): + print('user', email) + if not UserBonus.objects.filter(user=user_id, is_service=True, action_name=UserBonus.ACTION_CHILD_BIRTHDAY).count(): + UserBonus.objects.create(user=user_id, amount=UserBonus.AMOUNT_CHILD_BIRTHDAY, is_service=True, action_name=UserBonus.ACTION_CHILD_BIRTHDAY) - try: - fn = staticfiles_storage.path('img/birthday_postcard.jpg') - file = open(fn, 'rb') - send_email('С Днем Рождения!', u.email, 'notification/email/birthday_postcard.html', - attachments=[(file.name, file.read(), 'image/jpeg')],) - print('email has been sent') - finally: - file.close() + try: + fn = staticfiles_storage.path('img/birthday_postcard.jpg') + file = open(fn, 'rb') + send_email('С Днем Рождения!', email, 'notification/email/birthday_postcard.html', + attachments=[(file.name, file.read(), 'image/jpeg')],) + print('email has been sent') + finally: + file.close() @app.task def send_camp_certificates(email=None, dry_run=False, certificate_number=None): @@ -178,7 +191,6 @@ def send_camp_certificates(email=None, dry_run=False, certificate_number=None): font_size=120, y=1000, color=color) file = open(fn, 'rb') try: - pass send_email('Грамота от Lil School', email, 'notification/email/camp_certificate.html', attachments=[(file.name, file.read(), 'image/jpeg')], certificate_number=certificate_number) except: @@ -205,23 +217,27 @@ def send_camp_certificates(email=None, dry_run=False, certificate_number=None): if dry_run: continue - if un.user.child_first_name: + file_names = [] + if un.user.child_filled: fn = staticfiles_storage.path(signed_path_pattern % certificate_number) - fn = draw_cert(fn, un.user.email, un.user.child_first_name, un.user.child_last_name, - font_size=120, y=1000, color=color) + for child in un.user.childs.all(): + file_names.append(draw_cert(fn, un.user.email, child.first_name, child.last_name, + font_size=120, y=1000, color=color)) else: - fn = staticfiles_storage.path(path_pattern % certificate_number) - file = open(fn, 'rb') + file_names.append(staticfiles_storage.path(path_pattern % certificate_number)) + files = [open(fn, 'rb') for fn in file_names] try: send_email('Грамота от Lil School', un.user.email, 'notification/email/camp_certificate.html', - attachments=[(file.name, file.read(), 'image/jpeg')], user_notification=un, - certificate_number=certificate_number) + attachments=[(f.name, f.read(), 'image/jpeg') for f in files], user_notification=un, + certificate_number=certificate_number, many_childs=un.user.childs.all().count() > 1) except: print('Not OK') continue finally: - file.close() - if un.user.child_first_name: - os.remove(fn) + for f in files: + f.close() + if un.user.child_filled: + for fn in file_names: + os.remove(fn) un.camp_certificate_last_email = date_end un.save() diff --git a/apps/notification/templates/notification/email/camp_certificate.html b/apps/notification/templates/notification/email/camp_certificate.html index 98f83bbf..d3fcd858 100644 --- a/apps/notification/templates/notification/email/camp_certificate.html +++ b/apps/notification/templates/notification/email/camp_certificate.html @@ -6,13 +6,13 @@ {% if certificate_number == 1 %}
Поздравляем! Вы прошли месяц обучения в лагере Lil School.
-К письму прикреплена грамота. Распечатайте её и вручите вашим детям.
+К письму {% if many_childs %}прикреплены грамоты. Распечатайте их{% else %}прикреплена грамота. Распечатайте её{% endif %} и вручите вашим детям.
Ждём вас в следующем месяце на наших творческих занятиях!
-Вы помните, что каждый месяц вам приходит грамота за прекрасную учебу в рсиовальном лагере?
+Вы помните, что каждый месяц вам {% if many_childs %}приходят грамоты{% else %}приходит грамота{% endif %} за прекрасную учебу в рисовальном лагере?
Скачивайте. Распечатывайте. И соберите свою коллекцию!
Поздравляем! Вы прошли месяц обучения в Lil School.
-К письму прикреплена грамота. Распечатайте её и вручите вашим детям.
+К письму {% if many_childs %}прикреплены грамоты. Распечатайте их{% else %}прикреплена грамота. Распечатайте её{% endif %} и вручите вашим детям.
Ждём вас в следующем месяце на наших творческих занятиях!
- Вы помните, что каждый месяц вам приходит грамота за прекрасную учебу в нашей творческой школе?
+ Вы помните, что каждый месяц вам {% if many_childs %}приходят грамоты{% else %}приходит грамота{% endif %} за прекрасную учебу в нашей творческой школе?
Скачивайте. Распечатывайте. И соберите свою коллекцию!
Вам понравился наш творческий месяц?
-В письме вы найдёте грамоту, она для вашей семьи.
+В письме вы найдёте {% if many_childs %}грамоты, они{% else %}грамоту, она{% endif %} для вашей семьи.
Как здорово, что у нас есть такие ученики!
Ждём вас в следующем месяце.
Прошёл целый месяц обучения на платформе Lil School - месяц творчества, креатива и невероятных идей.
-Во вложении вас ждёт грамота.
+Во вложении вас {% if many_childs %}ждут грамоты{% else %}ждёт грамота{% endif %}.
До встречи на занятиях!
+ {% if many_childs %}
+ Ваши грамоты за успехи в учебе в Lil School ждут вас во вложении.
+ Скорее распечатайте их!
+ {% else %}
Ваша грамота за успехи в учебе в Lil School ждёт вас во вложении.
-Скорее распечатайте её!
-Вам есть чем гордится!
-До встречи в следующем месяце!
+ Скорее распечатайте её!
+ {% endif %}
+ Вам есть чем гордится!
+ До встречи в следующем месяце!
Как здорово вы потрудились на занятиях в этом месяце!
-И наша грамота уже ждёт вас!
+И {% if many_childs %}наши грамоты уже ждут{% else %}наша грамота уже ждёт{% endif %} вас!
Спасибо за творчество и креатив.
Ждём вас в следующем месяце!
Какой классный месяц у нас был! Вместе мы очень здорово и креативно потрудились.
-Во вложении вас ждёт заслуженная грамота!
+Во вложении вас {% if many_childs %}ждут заслуженные грамоты{% else %}ждёт заслуженная грамота{% endif %}!
До встречи на уроках!
Месяц творчества и креатива пролетел как один миг! А как много работ мы вместе сделали!
Вы - большие молодцы.
-Во вложении ваш ждёт грамота!
+Во вложении вас {% if many_childs %}ждут грамоты{% else %}ждёт грамота{% endif %}!
До встречи на занятиях.
{% endif %}