From 75f46a1065a6a5eea8a71fa6b1f451879feeeb28 Mon Sep 17 00:00:00 2001 From: gzbender Date: Thu, 6 Sep 2018 19:48:56 +0500 Subject: [PATCH] lil-583 --- apps/payment/models.py | 28 +++++++--- apps/payment/views.py | 30 ++++++----- apps/user/models.py | 2 +- apps/user/templates/user/bonus-history.html | 28 ++++++---- apps/user/templates/user/payment-history.html | 26 ++++----- project/templates/blocks/lil_store_js.html | 2 +- project/templates/blocks/popup_auth.html | 18 ++----- web/src/js/modules/common.js | 4 +- web/src/sass/_common.sass | 54 +++++++++++-------- 9 files changed, 113 insertions(+), 79 deletions(-) diff --git a/apps/payment/models.py b/apps/payment/models.py index c200dc26..69eaf54c 100644 --- a/apps/payment/models.py +++ b/apps/payment/models.py @@ -103,6 +103,7 @@ class Payment(PolymorphicModel): roistat_visit = models.PositiveIntegerField('Номер визита Roistat', null=True, editable=False) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) + bonus = models.ForeignKey('payment.UserBonus', null=True, on_delete=models.SET_NULL, related_name='purchase_payments') objects = PaymentManger() @@ -111,6 +112,15 @@ class Payment(PolymorphicModel): verbose_name_plural = 'Платежи' ordering = ('created_at',) + @classmethod + def add_months(cls, sourcedate, months=1): + result = arrow.get(sourcedate, settings.TIME_ZONE).shift(months=months) + if months == 1: + if (sourcedate.month == 2 and sourcedate.day >= 28) or (sourcedate.day == 31 and result.day <= 30)\ + or (sourcedate.month == 1 and sourcedate.day >= 29 and result.day == 28): + result = result.replace(day=1, month=result.month + 1) + return result.datetime + @classmethod def calc_amount(cls, payment=None, user=None, course=None, weekdays=None): if isinstance(payment, CoursePayment): @@ -134,7 +144,6 @@ class Payment(PolymorphicModel): user=user, date_start__lte=now().date(), date_end__gte=now().date(), - add_days=False, status__in=[ Pingback.PINGBACK_TYPE_REGULAR, Pingback.PINGBACK_TYPE_GOODWILL, @@ -144,8 +153,8 @@ class Payment(PolymorphicModel): school_schedules_purchased = school_payments.annotate( joined_weekdays=Func(F('weekdays'), function='unnest', ) ).values_list('joined_weekdays', flat=True).distinct() - weekdays = set(map(int, weekdays)) - set(school_schedules_purchased) - prev_school_payment = school_payments.last() + weekdays = list(set(map(int, weekdays)) - set(school_schedules_purchased)) + prev_school_payment = school_payments.filter(add_days=False).last() add_days = bool(prev_school_payment) else: add_days = False @@ -173,6 +182,7 @@ class Payment(PolymorphicModel): 'referral_bonus': referral_bonus, 'referrer_bonus': referrer_bonus, 'discount': discount, + 'weekdays': weekdays, } def calc_commission(self): @@ -197,10 +207,14 @@ class Payment(PolymorphicModel): def save(self, *args, **kwargs): amount_data = Payment.calc_amount(payment=self) self.amount = amount_data.get('amount') + if isinstance(self, SchoolPayment): + self.weekdays = amount_data.get('weekdays') super().save(*args, **kwargs) + paid = self.status in [Pingback.PINGBACK_TYPE_REGULAR, Pingback.PINGBACK_TYPE_GOODWILL, + Pingback.PINGBACK_TYPE_RISK_REVIEWED_ACCEPTED,] if isinstance(self, CoursePayment): author_balance = getattr(self, 'authorbalance', None) - if not author_balance: + if not author_balance and paid: AuthorBalance.objects.create( author=self.course.author, amount=self.amount, @@ -210,9 +224,7 @@ class Payment(PolymorphicModel): author_balance.amount = self.amount author_balance.save() # Если юзер реферал и нет платежа, где применялась скидка - if hasattr(self.user, 'referral') and not self.user.referral.payment\ - and self.status in [Pingback.PINGBACK_TYPE_REGULAR, Pingback.PINGBACK_TYPE_GOODWILL, - Pingback.PINGBACK_TYPE_RISK_REVIEWED_ACCEPTED,]: + if hasattr(self.user, 'referral') and not self.user.referral.payment and paid: # Платеж - как сигнал, что скидка применилась self.user.referral.payment = self self.user.referral.save() @@ -258,3 +270,5 @@ class UserBonus(models.Model): referral = models.ForeignKey('user.Referral', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) + class Meta: + ordering = ('created_at',) diff --git a/apps/payment/views.py b/apps/payment/views.py index 975d1eec..abca9736 100644 --- a/apps/payment/views.py +++ b/apps/payment/views.py @@ -25,7 +25,7 @@ from apps.course.models import Course from apps.school.models import SchoolSchedule from apps.payment.tasks import transaction_to_mixpanel, product_payment_to_mixpanel, transaction_to_roistat -from .models import AuthorBalance, CoursePayment, SchoolPayment +from .models import AuthorBalance, CoursePayment, SchoolPayment, Payment, UserBonus logger = logging.getLogger('django') @@ -118,7 +118,7 @@ class SchoolBuyView(TemplateView): Pingback.PINGBACK_TYPE_GOODWILL, Pingback.PINGBACK_TYPE_RISK_REVIEWED_ACCEPTED, ], - ).first() # ??? first? + ).last() add_days = bool(prev_school_payment) if add_days: school_payment = SchoolPayment.objects.create( @@ -129,6 +129,7 @@ class SchoolBuyView(TemplateView): add_days=True, roistat_visit=roistat_visit, ) + # Если произойдет ошибка и оплату бонусами повторят еще раз на те же дни, то вернет ошибку if school_payment.amount <= 0: messages.error(request, 'Выбранные дни отсутствуют в оставшемся периоде подписки') return redirect(reverse_lazy('school:school')) @@ -138,6 +139,19 @@ class SchoolBuyView(TemplateView): weekdays=weekdays, roistat_visit=roistat_visit, ) + if use_bonuses: + if request.user.bonus >= school_payment.amount: + bonus = UserBonus.objects.create(amount=- school_payment.amount, user=request.user, payment=school_payment) + school_payment.status = Pingback.PINGBACK_TYPE_REGULAR + school_payment.bonus = bonus + if not add_days: + school_payment.date_start = now().date() + school_payment.date_end = Payment.add_months(school_payment.date_start) + school_payment.save() + return redirect(reverse_lazy('payment-success')) + else: + messages.error(request, 'Недостаточно бонусов для оплаты') + return redirect(reverse_lazy('school:school')) product = Product( f'school_{school_payment.id}', school_payment.amount, @@ -163,14 +177,6 @@ class SchoolBuyView(TemplateView): @method_decorator(csrf_exempt, name='dispatch') class PaymentwallCallbackView(View): - def add_months(self, sourcedate, months=1): - result = arrow.get(sourcedate, settings.TIME_ZONE).shift(months=months) - if months == 1: - if (sourcedate.month == 2 and sourcedate.day >= 28) or (sourcedate.day == 31 and result.day <= 30)\ - or (sourcedate.month == 1 and sourcedate.day >= 29 and result.day == 28): - result = result.replace(day=1, month=result.month + 1) - return result.datetime - def get_request_ip(self): x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: @@ -234,10 +240,10 @@ class PaymentwallCallbackView(View): date_end = school_payment.date_end else: date_start = arrow.get(school_payment.date_end, settings.TIME_ZONE).shift(days=1).datetime - date_end = self.add_months(date_start) + date_end = Payment.add_months(date_start) else: date_start = now().date() - date_end = self.add_months(date_start) + date_end = Payment.add_months(date_start) payment.date_start = date_start payment.date_end = date_end if product_type_name == 'course': diff --git a/apps/user/models.py b/apps/user/models.py index 887167ad..3320adb2 100644 --- a/apps/user/models.py +++ b/apps/user/models.py @@ -107,7 +107,7 @@ class User(AbstractUser): @cached_property def bonus(self): - return int(self.bonuses.aggregate(models.Sum('amount')).get('amount__sum')) or 0 + return int(self.bonuses.aggregate(models.Sum('amount')).get('amount__sum') or 0) @receiver(post_save, sender=User) diff --git a/apps/user/templates/user/bonus-history.html b/apps/user/templates/user/bonus-history.html index b5461970..91dea322 100644 --- a/apps/user/templates/user/bonus-history.html +++ b/apps/user/templates/user/bonus-history.html @@ -23,25 +23,35 @@
-
+
История бонусов
-
+
+
+
Продукт
+
Сумма покупки
+
Реферал
+
Сумма бонусов
+
{% for bonus in bonuses %}
{% with payment=bonus.payment %} {% if payment.course %} -
Курс. {{ payment.course.title }}
+
Курс. {{ payment.course.title }}
{% else %} -
+
+ {% if request.user_agent.is_mobile %} + Школа. {% if payment.date_start and payment.date_end %}{{ payment.date_start|date:"" }} - {{ payment.date_end }}{% endif %} + {% else %} Школа. {% if payment.date_start and payment.date_end %}{{ payment.date_start }} - {{ payment.date_end }}{% endif %} + {% endif %}
{% endif %} -
{{payment.amount }}
- {% if bonus.referral %} - - {% endif %} -
{{ bonus.amount|floatformat }}
+
{{payment.amount }}
+
+ {% if bonus.referral %}{{ bonus.referral.referral.get_full_name }}{% endif %} +
+
{{ bonus.amount|floatformat }}
{% endwith %}
{% empty %} diff --git a/apps/user/templates/user/payment-history.html b/apps/user/templates/user/payment-history.html index 8b7d332c..ab152901 100644 --- a/apps/user/templates/user/payment-history.html +++ b/apps/user/templates/user/payment-history.html @@ -65,42 +65,42 @@
История платежей
-
+
{% if request.user.payments.all.exists %} {% for payment in request.user.payments.all %}
{% if payment.course %} -
Курс. {{payment.course.title}}
+
Курс. {{payment.course.title}}
{% else %} -
+
Школа. {% if payment.date_start and payment.date_end %}{{ payment.date_start }} - {{ payment.date_end }}{% endif %}
{% endif %} {% if payment.balance %} -
{{payment.balance.amount}}
+
{{payment.balance.amount}}
{% else %} -
{{payment.amount}}
+
{{payment.amount}}
{% endif %} {% if payment.balance.type == 1 %} -
+
{% if payment.balance.status == 0 %} - Ожидается подтверждение выплаты + Ожидается подтверждение выплаты {% elif payment.balance.status == 1 %} - Выплачено + Выплачено {% else %} - Выплата отменена + Выплата отменена Причина: "{{ payment.balance.cause }} {% endif %}
{% else %} -
+
{% if payment.is_deliverable %} - Оплачено + Оплачено {% elif payment.is_under_review %} - Ожидается подтверждение оплаты + Ожидается подтверждение оплаты {% else %} - Ошибка оплаты + Ошибка оплаты {% endif %}
{% endif %} diff --git a/project/templates/blocks/lil_store_js.html b/project/templates/blocks/lil_store_js.html index 04f69e59..cb882e96 100644 --- a/project/templates/blocks/lil_store_js.html +++ b/project/templates/blocks/lil_store_js.html @@ -8,7 +8,7 @@ id: '{{ request.user.id|default:'' }}', }, flags: { - isReferralRegistration: '{{ is_referral_registration|yesno:"true,false" }}', + isReferralRegistration: {{ is_referral_registration|yesno:"true,false" }}, } }; diff --git a/project/templates/blocks/popup_auth.html b/project/templates/blocks/popup_auth.html index 3e6c5c75..e2064381 100644 --- a/project/templates/blocks/popup_auth.html +++ b/project/templates/blocks/popup_auth.html @@ -1,5 +1,5 @@ {% load static %} -