From 39f6a9e71bcbbc2cbbbaa187bbb96a95a68521c9 Mon Sep 17 00:00:00 2001 From: Dmitriy Shesterkin Date: Mon, 17 Jul 2017 12:59:50 +0300 Subject: [PATCH] add bonus system --- src/commons/management/commands/clearcache.py | 9 +++++++ src/customer/consts.py | 1 + src/customer/emails.py | 17 +++++++++++++ src/customer/models.py | 11 ++++++++ src/customer/utils.py | 25 +++++++++++++++++++ src/customer/views/license.py | 2 +- src/dokumentor/settings/common.py | 7 +++++- src/dokumentor/settings/local.py | 7 +++++- src/dokumentor/settings/stage.py | 2 +- src/dokumentor/settings/testing.py | 5 +++- templates/customer/profile/orders_list.html | 6 ++++- templates/emails/issued_bonus_license.txt | 12 +++++++++ .../emails/license_successful_purchased.txt | 2 +- 13 files changed, 99 insertions(+), 7 deletions(-) create mode 100644 src/commons/management/commands/clearcache.py create mode 100644 templates/emails/issued_bonus_license.txt diff --git a/src/commons/management/commands/clearcache.py b/src/commons/management/commands/clearcache.py new file mode 100644 index 0000000..27bb18f --- /dev/null +++ b/src/commons/management/commands/clearcache.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- +from django.core.management.base import BaseCommand +from django.core.cache import cache + + +class Command(BaseCommand): + def handle(self, *args, **kwargs): + cache.clear() + self.stdout.write('Cleared cache\n') diff --git a/src/customer/consts.py b/src/customer/consts.py index 28662ce..51db476 100644 --- a/src/customer/consts.py +++ b/src/customer/consts.py @@ -25,6 +25,7 @@ LICENSE_STATUSES = ( ) PAYFORMS = ( + (-2, 'Бонусная'), (-1, 'Бесплатно'), (0, 'Безналичный расчёт'), (1, 'Банковская карта'), diff --git a/src/customer/emails.py b/src/customer/emails.py index b495b3f..3db4948 100644 --- a/src/customer/emails.py +++ b/src/customer/emails.py @@ -37,3 +37,20 @@ def send_license_successful_purchased(user_email, order_number, lic_term, activa email_body = render_to_string(template_name, dict_context) email = EmailMessage(subject=subject, to=(user_email,), body=email_body) return email.send() + + +@task +def send_bonus_license_issued(user_email, lic_number, lic_term, bonus_lic_term, activate_date): + template_name = 'emails/issued_bonus_license.txt' + subject = 'Документор: Выдана бонусная лицензия' + dict_context = {'user_email': user_email, + 'support_email': settings.SUPPORT_EMAIL, + 'site_url': get_site_url(), + 'lic_number': lic_number, + 'lic_term': lic_term, + 'bonus_lic_term': bonus_lic_term, + 'activate_date': activate_date + } + email_body = render_to_string(template_name, dict_context) + email = EmailMessage(subject=subject, to=(user_email,), body=email_body) + return email.send() diff --git a/src/customer/models.py b/src/customer/models.py index 1a395e8..348e9e2 100644 --- a/src/customer/models.py +++ b/src/customer/models.py @@ -18,6 +18,7 @@ from django.utils.deconstruct import deconstructible from django.conf import settings from customer import consts, managers, utils +from customer.utils import create_bonus_license from myauth.models import DokUser from commons.utils import only_numerics from robokassa.signals import result_received, success_page_visited @@ -778,6 +779,16 @@ def confirmed_purchase(**kwargs): lic.date_from.date() ) + bonus_license = create_bonus_license(lic) + if bonus_license: + emails.send_bonus_license_issued.delay( + payment.user.email, + lic.pk, + lic.get_term(), + bonus_license.get_term(), + bonus_license.date_from.date() + ) + except Payment.DoesNotExist: log.info(f"payment with id={kwargs['InvId']} not found") except License.DoesNotExist: diff --git a/src/customer/utils.py b/src/customer/utils.py index 5b5e398..dedc993 100644 --- a/src/customer/utils.py +++ b/src/customer/utils.py @@ -1,11 +1,14 @@ # -*- coding: utf-8 -*- from datetime import timedelta + +from dateutil.relativedelta import relativedelta from pytils import numeral from django.utils import timezone from django.conf import settings from django.core.mail import EmailMessage from django.template.loader import render_to_string +from django.core.cache import cache from commons.utils import get_site_url @@ -154,3 +157,25 @@ def get_display_message_for_bonus(day_count): f'чтобы получить бонус' return message + + +def create_bonus_license(lic): + if check_confirm_bonus_to_user(lic.company.get_first_user()) and lic.term >= 12: + bonus_term = 0 + if lic.term == 12: + bonus_term = 2, + if lic.term == 24: + bonus_term = 3 + bonus_license = lic._meta.model.objects.create( + company=lic.company, + term=bonus_term, + payform=-2, + status=1, + order_date=timezone.now().date(), + date_from=lic.date_to + timedelta(1), + date_to=lic.date_to + timedelta(1) + relativedelta(months=bonus_term, days=-1), + pay_sum=0 + ) + cache.set(f'confirm_bonus_days_{lic.company.get_first_user().username}', -1, 3600) + return bonus_license + return False diff --git a/src/customer/views/license.py b/src/customer/views/license.py index 2f950e0..743c219 100644 --- a/src/customer/views/license.py +++ b/src/customer/views/license.py @@ -158,7 +158,7 @@ def orders_list(request): accounts_list = License.objects.filter( company=request.user.profile, deleted=False, - status__gt=-1).\ + status__gt=-1).exclude(payform=-2).\ annotate(type=Count('status')).order_by('-id') licenses_list = License.objects.filter( diff --git a/src/dokumentor/settings/common.py b/src/dokumentor/settings/common.py index 20080d9..fe44e67 100644 --- a/src/dokumentor/settings/common.py +++ b/src/dokumentor/settings/common.py @@ -4,7 +4,6 @@ import os import sys from datetime import timedelta -import raven import envvars as e @@ -368,3 +367,9 @@ LOGGING = { } }, } + +if DEBUG: + LOGGING['loggers']['raven'] = { + 'handlers': ['null'], + 'level': 'ERROR', + } diff --git a/src/dokumentor/settings/local.py b/src/dokumentor/settings/local.py index 78d865a..06ae4d2 100644 --- a/src/dokumentor/settings/local.py +++ b/src/dokumentor/settings/local.py @@ -22,9 +22,14 @@ if DEBUG: } DATABASES = { - 'default': dj_database_url.parse(e.get('DJANGO_DB')), + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'), + } } +RAVEN_CONFIG = {} + EMAIL_BACKEND = 'eml_email_backend.EmailBackend' EMAIL_FILE_PATH = os.path.join(ROOT_DIR, 'tmp_emails') diff --git a/src/dokumentor/settings/stage.py b/src/dokumentor/settings/stage.py index 8b8e6d0..90d7e24 100644 --- a/src/dokumentor/settings/stage.py +++ b/src/dokumentor/settings/stage.py @@ -1,6 +1,6 @@ # flake8: noqa # coding: utf-8 - +import raven import dj_database_url from src.dokumentor.settings.common import * diff --git a/src/dokumentor/settings/testing.py b/src/dokumentor/settings/testing.py index 0b8cef5..4d4df03 100644 --- a/src/dokumentor/settings/testing.py +++ b/src/dokumentor/settings/testing.py @@ -13,7 +13,10 @@ EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher', ) DATABASES = { - 'default': dj_database_url.parse(e.get('DJANGO_TEST_DB')), + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(ROOT_DIR, 'db_test.sqlite3'), + } } diff --git a/templates/customer/profile/orders_list.html b/templates/customer/profile/orders_list.html index d758bcb..9fa11b4 100644 --- a/templates/customer/profile/orders_list.html +++ b/templates/customer/profile/orders_list.html @@ -22,7 +22,11 @@ {% else %}

Лицензия № {{object.id}} на {{ object.get_term }}, - {% if object.pay_sum > 0 %}{{ object.pay_sum|get_plural:"рубль,рубля,рублей" }}{% else %}бесплатно{% endif %}

+ {% if object.pay_sum > 0 %}{{ object.pay_sum|get_plural:"рубль,рубля,рублей" }}{% else %} + {% if object.payform == -1 %} + бесплатно{% else %}бонусная + {% endif %} + {% endif %}

{% if object.term > 0 %}{{ object.get_action_link|safe }}{% else %}Пробный период{% endif %}

{% endif %} diff --git a/templates/emails/issued_bonus_license.txt b/templates/emails/issued_bonus_license.txt new file mode 100644 index 0000000..8233865 --- /dev/null +++ b/templates/emails/issued_bonus_license.txt @@ -0,0 +1,12 @@ +Здравствуйте! + +Спасибо Вам за доверие сайту Документор и за покупку лицензии No {{ lic_number }} на {{ lic_term }}. + +Как договаривались, мы создали Вам бесплатную бонусную лицензию на {{ bonus_lic_term }}. Она автоматически начнёт работать {{ activate_date|date:"d.m.Y" }}, когда закончится срок других Ваших лицензий. + + +Ещё раз, спасибо Вам! {{ site_url }} + +-- + +Это письмо отправлено роботом. Пожалуйста не отвечайте на него. По всем вопросам пишите на {{ support_email }} diff --git a/templates/emails/license_successful_purchased.txt b/templates/emails/license_successful_purchased.txt index 2222f0f..213bca6 100644 --- a/templates/emails/license_successful_purchased.txt +++ b/templates/emails/license_successful_purchased.txt @@ -2,7 +2,7 @@ Спасибо Вам за оплату счёта {{ order_number }} -Для Вас была создана лицензия No {{ order_number }} на {{ lic_term }} месяцев, которая будет автоматически активирована {{ activate_date }}. +Для Вас была создана лицензия No {{ order_number }} на {{ lic_term }} месяцев, которая будет автоматически активирована {{ activate_date|date:"d.m.Y" }}. Акт выполненных работ будет создан в момент активации лицензии. Вы сможете скачать его на этой странице {{ site_url }}{{ url }} Если Вы согласны, купите лицензию здесь {{ site_url }}{{ url }}. Если нет - ничего страшного ;)