# -*- coding: utf-8 -*- import traceback from datetime import datetime, timedelta from django.core.cache import cache from django.core.mail import mail_admins from django.conf import settings from .models import License from . import consts DEBUG = getattr(settings, 'DEBUG', False) cache_duration = 3600 def license_check_soon_ends(request): try: license_cookie = request.COOKIES.get('close_message_license') license_15days = cache.get('license_15_%s' % (request.user.username,), None) days_left = cache.get('days_left_%s' % (request.user.username,), None) cur_license = cache.get('cur_license_%s' % (request.user.username,), None) now_ = datetime.today() if not days_left or not cur_license: cur_license = License.objects.filter( company=request.user.profile, date_from__lte=now_, date_to__gte=now_, status__in=[consts.LICENSE_TEST_PERIOD, consts.LICENSE_PAID, consts.LICENSE_ACTIVE], deleted=False ) if cur_license: cur_license = cur_license[0] days_left = (cur_license.date_to - now_.date()).days cache.set('days_left_%s' % (request.user.username,), days_left, cache_duration) cache.set('cur_license_%s' % (request.user.username,), cur_license, cache_duration) if not license_cookie: if license_15days is None: licenses_ends = License.objects.filter( company=request.user.profile, date_to__lte = now_ + timedelta(days=consts.LICENSE_LEFT_DAYS), status__in=[consts.LICENSE_TEST_PERIOD, consts.LICENSE_PAID, consts.LICENSE_ACTIVE], deleted=False ) next_licenses = License.objects.filter(company=request.user.profile, status=consts.LICENSE_PAID, deleted=False) if licenses_ends and not next_licenses: days_to_end = licenses_ends[0].date_to cache.set('license_15_%s' % (request.user.username,), days_to_end, cache_duration) license_15days = days_to_end else: license_15days = '' return { 'license_15days': license_15days, 'license_days': days_left, 'cur_license': cur_license, } except Exception as e: if DEBUG: raise e else: mail_admins(subject=u'customer: license_check_soon_ends error', message=u'Profile id=%s.\n\n%s' % (request.user.profile.pk, traceback.format_exc(e)) ) # return { }