# -*- coding: utf-8 -*- from __future__ import absolute_import from datetime import datetime, timedelta from django.conf import settings from django.template.loader import render_to_string from django.core.mail import EmailMessage from celery import shared_task from .models import License, UserProfile SUPPORT_EMAIL = getattr(settings, 'SUPPORT_EMAIL', '') @shared_task def check_license(): profiles = UserProfile.objects.all() now = datetime.now() licenses = License.objects.filter(date_to__lt=now, status__in=[-1, 2], deleted=False) licenses.update(status=3) licenses = License.objects.filter(order_date__lt=now - timedelta(10), status=0, deleted=False) licenses.update(status=4) for profile in profiles: licenses = License.objects.filter(user=profile.user, date_from__lte=now, date_to__gte=now, status__in=[-1, 1, 2], deleted=False) if licenses: profile.active = True else: profile.active = False profile.save() licenses.filter(status=1).update(status=2) licenses = License.objects.filter(user=profile.user, date_to=now + timedelta(1), status__in=[-1, 2], deleted=False) licenses_remain = License.objects.filter(user=profile.user, date_from__gt=now + timedelta(1), status=1, deleted=False) licenses_to_pay = License.objects.filter(user=profile.user, status=0, deleted=False) if licenses and not licenses_remain: template_name = 'myauth/license_ends.txt' subject = u'Документор: окончание срока действия лицензии' dict_context = {'user_email': licenses[0].user, 'support_email': SUPPORT_EMAIL, 'license_ends': licenses[0].date_to, 'licenses_to_pay': licenses_to_pay, } email_body = render_to_string(template_name, dict_context) email = EmailMessage(subject=subject, to=(licenses[0].user.email,), body=email_body) return email.send() return None