# -*- coding: utf-8 -*- from datetime import datetime, timedelta from django.db.models import Q from django.core.cache import cache from django.conf import settings from project.commons.utils import mail_exception 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: current_licenses = (License.objects .filter(company=request.user.profile, date_from__lte=now_, date_to__gte=now_, deleted=False) .filter(Q(status__in = [consts.LICENSE_TEST_PERIOD, consts.LICENSE_ACTIVE]) | Q(order_status=consts.ORDER_PAID)) ) if current_licenses: cur_license = current_licenses[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_DAYS_BEFORE_EXPIRE), deleted=False) .filter(Q(status__in = [consts.LICENSE_TEST_PERIOD, consts.LICENSE_ACTIVE]) | Q(order_status=consts.ORDER_PAID)) ) next_licenses = License.objects.filter(company=request.user.profile, order_status=consts.ORDER_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 else: mail_exception(u'customer: license_check_soon_ends error', u'Profile id=%d.' % request.user.profile.pk, e) # return { }