license: no magic numbers

remotes/origin/license
Andrey 9 years ago
parent e320fc3348
commit ed39423772
  1. 41
      project/customer/consts.py
  2. 17
      project/customer/context_processors.py
  3. 27
      project/customer/models.py
  4. 9
      project/customer/tasks.py
  5. 23
      project/customer/utils.py

@ -8,22 +8,43 @@ PROFILE_TYPES = (
(ORG_PROFILE, u'Организация'), (ORG_PROFILE, u'Организация'),
) )
# лицензии
LICENSE_PAY_DAYS = 10 # дней на оплату счёта
LICENSE_LEFT_DAYS = 15 # осталось дней до конца лицензии
LICENSE_TEST_PERIOD_TERM = 0 # тип срока: пробный период. это особый тип, никак не связанный с моделью LicensePrice
LICENSE_TEST_PERIOD_DAYS = 45 # длительность пробного периода в днях
LICENSE_TEST_PERIOD = -1
LICENSE_UNPAID = 0
LICENSE_PAID = 1
LICENSE_ACTIVE = 2
LICENSE_EXPIRED = 3
LICENSE_SUSPENDED = 4
LICENSE_STATUSES = ( LICENSE_STATUSES = (
(-1, u'Пробный период'), (LICENSE_TEST_PERIOD, u'Пробный период'),
(0, u'Не оплачен'), (LICENSE_UNPAID, u'Не оплачен'),
(1, u'Оплачен'), (LICENSE_PAID, u'Оплачен'),
(2, u'Активирован'), (LICENSE_ACTIVE, u'Активирован'),
(3, u'Срок действия истёк'), (LICENSE_EXPIRED, u'Срок действия истёк'),
(4, u'Заморожен'), (LICENSE_SUSPENDED, u'Заморожен'),
) )
PAYFORM_FREE = -1
PAYFORM_BEZNAL = 0
PAYFORM_CARD = 1
# PAYFORM_SBER_KVITANZ = 2
PAYFORMS = ( PAYFORMS = (
(-1, u'Бесплатно'), (PAYFORM_FREE, u'Бесплатно'),
(0, u'Безналичный расчёт'), (PAYFORM_BEZNAL, u'Безналичный расчёт'),
(1, u'Банковская карта'), (PAYFORM_CARD, u'Банковская карта'),
# (2, u'Квитанция Сбербанка'), # (PAYFORM_SBER_KVITANZ, u'Квитанция Сбербанка'),
) )
# типы сроков для модели LicensePrice
TERMS = ( TERMS = (
(1, u'1 месяц'), (1, u'1 месяц'),
(6, u'6 месяцев'), (6, u'6 месяцев'),

@ -4,6 +4,9 @@ from django.core.cache import cache
from .models import License from .models import License
cache_duration = 3600
def license_check_soon_ends(request): def license_check_soon_ends(request):
try: try:
license_cookie = request.COOKIES.get('close_message_license') license_cookie = request.COOKIES.get('close_message_license')
@ -12,21 +15,23 @@ def license_check_soon_ends(request):
cur_license = cache.get('cur_license_%s' % (request.user.username,), None) cur_license = cache.get('cur_license_%s' % (request.user.username,), None)
if not days_left or not cur_license: if not days_left or not cur_license:
now = datetime.today() now = datetime.today()
cur_license = License.objects.filter(company=request.user.profile, date_from__lte=now, date_to__gte=now, status__in=[-1, 1, 2], deleted=False) 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: if cur_license:
cur_license = cur_license[0] cur_license = cur_license[0]
days_left = (cur_license.date_to - now.date()).days days_left = (cur_license.date_to - now.date()).days
cache.set('days_left_%s' % (request.user.username,), days_left, 3600) cache.set('days_left_%s' % (request.user.username,), days_left, cache_duration)
cache.set('cur_license_%s' % (request.user.username,), cur_license, 3600) cache.set('cur_license_%s' % (request.user.username,), cur_license, cache_duration)
if not license_cookie: if not license_cookie:
now = datetime.today() now = datetime.today()
if license_15days is None: if license_15days is None:
licenses_ends = License.objects.filter(company=request.user.profile, date_to__lte=now + timedelta(15), status__in=[-1, 1, 2], deleted=False) licenses_ends = License.objects.filter(company=request.user.profile, date_to__lte=now + timedelta(consts.LICENSE_LEFT_DAYS),
next_licenses = License.objects.filter(company=request.user.profile, status=1, deleted=False) 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: if licenses_ends and not next_licenses:
days_to_end = licenses_ends[0].date_to days_to_end = licenses_ends[0].date_to
cache.set('license_15_%s' % (request.user.username,), days_to_end, 3600) cache.set('license_15_%s' % (request.user.username,), days_to_end, cache_duration)
license_15days = days_to_end license_15days = days_to_end
else: else:
license_15days = '' license_15days = ''

@ -418,9 +418,9 @@ class License(models.Model):
date_from = models.DateField(u'дата начала', null=True, blank=True) date_from = models.DateField(u'дата начала', null=True, blank=True)
date_to = models.DateField(u'дата окончания', null=True, blank=True) date_to = models.DateField(u'дата окончания', null=True, blank=True)
payform = models.IntegerField(verbose_name=u'форма оплаты', payform = models.IntegerField(verbose_name=u'форма оплаты',
choices=consts.PAYFORMS, default=0) choices=consts.PAYFORMS, default=consts.PAYFORM_BEZNAL)
status = models.IntegerField(verbose_name=u'статус лицензии', status = models.IntegerField(verbose_name=u'статус лицензии',
choices=consts.LICENSE_STATUSES, default=0) choices=consts.LICENSE_STATUSES, default=consts.LICENSE_UNPAID)
order_date = models.DateField(verbose_name=u'дата заказа', auto_now_add=True) order_date = models.DateField(verbose_name=u'дата заказа', auto_now_add=True)
paid_date = models.DateField(verbose_name=u'дата оплаты', null=True, blank=True) paid_date = models.DateField(verbose_name=u'дата оплаты', null=True, blank=True)
pay_sum= models.IntegerField(verbose_name=u'сумма оплаты') pay_sum= models.IntegerField(verbose_name=u'сумма оплаты')
@ -449,7 +449,7 @@ class License(models.Model):
self.date_to = self.date_from + relativedelta(months=self.term, days=-1) self.date_to = self.date_from + relativedelta(months=self.term, days=-1)
self.company.active = True self.company.active = True
self.company.save() self.company.save()
self.status = 1 self.status = consts.LICENSE_PAID
utils.check_one_profile(self.company, License, datetime.now(), manual=True) utils.check_one_profile(self.company, License, datetime.now(), manual=True)
super(License, self).save(*args, **kwargs) super(License, self).save(*args, **kwargs)
@ -458,31 +458,30 @@ class License(models.Model):
return self.company.get_company_name() return self.company.get_company_name()
def get_action_link(self): def get_action_link(self):
if self.status == consts.LICENSE_UNPAID:
if self.status == 0: if self.payform == consts.PAYFORM_BEZNAL:
if self.payform == 0:
return u'<a href="%s">Скачать счёт</a>' % reverse('customer_license_get_doc', kwargs={'order_num': self.id}) return u'<a href="%s">Скачать счёт</a>' % reverse('customer_license_get_doc', kwargs={'order_num': self.id})
elif self.payform == 1: elif self.payform == consts.PAYFORM_CARD:
return u'Оплатить счёт' return u'Оплатить счёт'
elif self.payform == 2: elif self.payform == consts.PAYFORM_SBER_KVITANZ: # не используется. однако могут быть старые лицензии с данной формой оплаты
return u'<a href="%s">Скачать квитанцию</a>' % reverse('customer_license_get_doc', kwargs={'order_num': self.id}) return u'<a href="%s">Скачать квитанцию</a>' % reverse('customer_license_get_doc', kwargs={'order_num': self.id})
elif self.status in [1, 2]: elif self.status in [consts.LICENSE_PAID, consts.LICENSE_ACTIVE]:
return u'История операций' return u'История операций'
else: else:
return '' return ''
def get_term(self): def get_term(self):
if self.term == 0: if self.term == consts.LICENSE_TEST_PERIOD_TERM:
return u'45 дней' return u'%d дней' % consts.LICENSE_TEST_PERIOD_DAYS
else: else:
return u'%s %s' % (self.term, return u'%s %s' % (self.term,
numeral.choose_plural(self.term, u"месяц, месяца, месяцев"), numeral.choose_plural(self.term, u"месяц, месяца, месяцев"),
) )
def get_paid_status(self): def get_paid_status(self):
if self.status == 1: if self.status == consts.LICENSE_PAID:
return u'Лицензия оплачена, ещё не активирована' return u'Лицензия оплачена, ещё не активирована'
elif self.status in [2, -1]: elif self.status in [consts.LICENSE_ACTIVE, consts.LICENSE_TEST_PERIOD]:
left = relativedelta(self.date_to, datetime.today()) left = relativedelta(self.date_to, datetime.today())
if left.months: if left.months:
left_str = '%d %s %d %s' % (left.months, left_str = '%d %s %d %s' % (left.months,
@ -496,7 +495,7 @@ class License(models.Model):
numeral.choose_plural(left.days, u"день, дня, дней"), numeral.choose_plural(left.days, u"день, дня, дней"),
) )
return u'Лицензия активирована: осталось %s' % left_str return u'Лицензия активирована: осталось %s' % left_str
elif self.status == 3: elif self.status == consts.LICENSE_EXPIRED:
return u'Время истекло' return u'Время истекло'
else: else:
return None return None

@ -9,6 +9,7 @@ from celery import shared_task
from .models import License, UserProfile from .models import License, UserProfile
from .utils import check_one_profile from .utils import check_one_profile
from project.customer import consts
@shared_task @shared_task
@ -16,11 +17,11 @@ def check_license():
profiles = UserProfile.objects.all() profiles = UserProfile.objects.all()
now = datetime.today() now = datetime.today()
#licenses = License.objects.filter(date_to__lt=now, status__in=[-1, 2], deleted=False) #licenses = License.objects.filter(date_to__lt=now, status__in=[consts.LICENSE_TEST_PERIOD, consts.LICENSE_ACTIVE], deleted=False)
#licenses.update(status=3) #licenses.update(status=consts.LICENSE_EXPIRED)
licenses = License.objects.filter(order_date__lte=now - timedelta(10), status=0, deleted=False) licenses = License.objects.filter(order_date__lte=now - timedelta(consts.LICENSE_PAY_DAYS), status=consts.LICENSE_UNPAID, deleted=False)
licenses.update(status=4) licenses.update(status=consts.LICENSE_SUSPENDED)
for profile in profiles: for profile in profiles:
try: try:

@ -5,14 +5,17 @@ from django.conf import settings
from django.core.mail import EmailMessage from django.core.mail import EmailMessage
from django.template.loader import render_to_string from django.template.loader import render_to_string
from project.customer import consts
SUPPORT_EMAIL = getattr(settings, 'SUPPORT_EMAIL') SUPPORT_EMAIL = getattr(settings, 'SUPPORT_EMAIL')
def check_one_profile(profile, License, now, manual=False): def check_one_profile(profile, License, now, manual=False):
profile_is_active = profile.active profile_is_active = profile.active
licenses = License.objects.filter(company=profile, date_from__lte=now, date_to__gte=now, status__in=[-1, 1, 2], deleted=False) licenses = License.objects.filter(company=profile, date_from__lte=now, date_to__gte=now,
licenses.filter(status=1).update(status=2) status__in=[consts.LICENSE_TEST_PERIOD, consts.LICENSE_PAID, consts.LICENSE_ACTIVE], deleted=False)
licenses.filter(status=consts.LICENSE_PAID).update(status=consts.LICENSE_ACTIVE)
if licenses: if licenses:
profile.active = True profile.active = True
@ -34,12 +37,14 @@ def check_one_profile(profile, License, now, manual=False):
email = EmailMessage(subject=subject, to=(user_email,), body=email_body) email = EmailMessage(subject=subject, to=(user_email,), body=email_body)
email.send() email.send()
licenses_remain = License.objects.filter(company=profile, date_from__gt=now + timedelta(1), status=1, deleted=False) licenses_remain = License.objects.filter(company=profile, date_from__gt=now + timedelta(1),
licenses_to_pay = License.objects.filter(company=profile, status=0, deleted=False) status=consts.LICENSE_PAID, deleted=False)
licenses_to_pay = License.objects.filter(company=profile, status=consts.LICENSE_UNPAID, deleted=False)
if not licenses_remain and not manual: if not licenses_remain and not manual:
licenses = License.objects.filter(company=profile, date_to__lt=now, status__in=[-1, 2], deleted=False) licenses = License.objects.filter(company=profile, date_to__lt=now,
licenses.update(status=3) status__in=[consts.LICENSE_TEST_PERIOD, consts.LICENSE_ACTIVE], deleted=False)
licenses.update(status=status=consts.LICENSE_EXPIRED)
if licenses: if licenses:
template_name = 'myauth/license_ended.txt' template_name = 'myauth/license_ended.txt'
@ -53,7 +58,8 @@ def check_one_profile(profile, License, now, manual=False):
email = EmailMessage(subject=subject, to=(user_email,), body=email_body) email = EmailMessage(subject=subject, to=(user_email,), body=email_body)
email.send() email.send()
licenses = License.objects.filter(company=profile, date_to=now + timedelta(1), status__in=[-1, 2], deleted=False) licenses = License.objects.filter(company=profile, date_to=now + timedelta(1),
status__in=[consts.LICENSE_TEST_PERIOD, consts.LICENSE_ACTIVE], deleted=False)
if licenses: if licenses:
template_name = 'myauth/license_ends.txt' template_name = 'myauth/license_ends.txt'
@ -68,7 +74,8 @@ def check_one_profile(profile, License, now, manual=False):
email.send() email.send()
if not manual: if not manual:
licenses = License.objects.filter(company=profile, order_date=now - timedelta(9), status=0, deleted=False) licenses = License.objects.filter(company=profile, order_date=now - timedelta(consts.LICENSE_PAY_DAYS-1),
status=status=consts.LICENSE_UNPAID, deleted=False)
if licenses: if licenses:
template_name = 'myauth/license_to_pay.txt' template_name = 'myauth/license_to_pay.txt'

Loading…
Cancel
Save