You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
2.8 KiB
73 lines
2.8 KiB
from django.core.management.base import BaseCommand
|
|
from email.mime.image import MIMEImage
|
|
from django.contrib.staticfiles.storage import staticfiles_storage
|
|
from django.utils.timezone import now
|
|
from django.contrib.auth import get_user_model
|
|
|
|
from apps.notification.models import UserNotification
|
|
from apps.notification.utils import send_email
|
|
from apps.payment.models import Payment, SchoolPayment, CoursePayment
|
|
|
|
|
|
User = get_user_model()
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = 'Send certificates at the end of subscription'
|
|
|
|
def add_arguments(self, parser):
|
|
# Named (optional) arguments
|
|
parser.add_argument(
|
|
'--email',
|
|
dest='email',
|
|
help='Test email',
|
|
)
|
|
parser.add_argument(
|
|
'--dry-run',
|
|
action='store_true',
|
|
dest='dry_run',
|
|
help='Only display emails',
|
|
)
|
|
|
|
def handle(self, *args, **options):
|
|
path_pattern = 'img/user-certificates/%d.jpg'
|
|
if options.get('email'):
|
|
file = open(staticfiles_storage.path(path_pattern % 1), 'rb')
|
|
try:
|
|
send_email('Грамота от Lil School', options['email'], 'notification/email/certificate.html',
|
|
attachments=[(file.name, file.read(), 'image/jpeg')])
|
|
except:
|
|
pass
|
|
else:
|
|
print('Email has been sent')
|
|
finally:
|
|
file.close()
|
|
return
|
|
|
|
today = now().date()
|
|
users = SchoolPayment.objects.filter(date_end=today, 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('user_id', flat=True)
|
|
for user_id in users:
|
|
if user_id in notified_users:
|
|
continue
|
|
un = user_notifications.get(user_id, UserNotification(user_id=user_id))
|
|
print(un.user.email)
|
|
if options.get('dry_run'):
|
|
continue
|
|
|
|
un.certificate_number = un.certificate_number + 1 \
|
|
if un.certificate_number and staticfiles_storage.exists(path_pattern % (un.certificate_number + 1)) \
|
|
else 1
|
|
file = open(staticfiles_storage.path(path_pattern % un.certificate_number), 'rb')
|
|
try:
|
|
send_email('Грамота от Lil School', un.user.email, 'notification/email/certificate.html',
|
|
attachments=[(file.name, file.read(), 'image/jpeg')])
|
|
except:
|
|
print('Not OK')
|
|
continue
|
|
finally:
|
|
file.close()
|
|
un.certificate_last_email = now()
|
|
un.save()
|
|
|