You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

179 lines
6.1 KiB

# -*- coding: utf-8 -*-
import json
import hashlib
from django.shortcuts import render, redirect, get_object_or_404
from django.http import Http404, HttpResponseRedirect, HttpResponseForbidden, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.http import urlquote
from django.contrib.auth.decorators import login_required
from django.template.response import TemplateResponse
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_protect
from django.db.models import Q
from django.conf import settings
from yandex_money.models import Payment
from project.customer import consts
from ..models import License, LicensePrice
from ..forms import LicenseForm, YaForm
from ..utils import raise_if_no_profile
@login_required
@csrf_protect
def yandex_pay(request, payment_id):
template_name = 'customer/profile/yandex.html'
payment = Payment.objects.get(pk=payment_id)
if payment.user != request.user:
raise Exception(u'[yandex_pay error] Different users! | payment.user_id = %d ; request.user_id = %d' % (payment.user_id, request.user.pk,))
form = YaForm(instance=payment)
return render(request, template_name, {'form': form, 'ya_url': settings.YANDEX_MONEY_PAYMENT_URL})
@login_required
@csrf_protect
def order_license(request):
"""заказ лицензии
"""
raise_if_no_profile(request)
template_name = 'customer/profile/license.html'
# срок лицензии. по умолчанию, 6 месяцев
# TODO don't use the magic index `1`. maybe add field to LicensePrice model to mark the default record via admin
term_default = LicensePrice.objects.all()[1]
form = LicenseForm(
request.POST or None,
initial = {
'term': term_default,
'payform': consts.PAYFORM_BEZNAL,
}
)
if form.is_valid():
_payform = int(form.cleaned_data['payform'])
new_license = License(
company = request.user.profile,
term = form.cleaned_data['term'].term,
payform = _payform,
pay_sum = form.cleaned_data['term'].price,
)
new_license.save()
if _payform == consts.PAYFORM_CARD:
payment, _ = Payment.objects.get_or_create(
order_amount = form.cleaned_data['term'].price,
payment_type = Payment.PAYMENT_TYPE.AC,
order_number = new_license.pk,
)
payment.user = request.user
# payment.cps_email = request.user.email
payment.customer_number = request.user.email
# payment.customer_number = request.user.profile.get_company_name().strip()
payment.save()
return redirect(reverse('yamoney_confirm', kwargs={'payment_id': payment.pk}))
return redirect(reverse('customer_license_list'))
return render(request, template_name, {'form': form})
@login_required
def license_list(request):
"""Список счетов на лицензии
"""
raise_if_no_profile(request)
template_name = 'customer/profile/license_list.html'
# TODO maybe explicitly list license statuses?
licenses = License.objects.filter(company=request.user.profile, status__gt=consts.LICENSE_TEST_PERIOD, deleted=False).order_by('-id')
return render(request, template_name, {'licenses': licenses})
@login_required
def paid_list(request):
"""Оплаченные лицензии
"""
raise_if_no_profile(request)
template_name = 'customer/profile/paid_list.html'
# TODO почему в оплаченных лицензиях выводится пробный период и замороженные?
licenses = (License.objects
.filter(company=request.user.profile, deleted=False)
.filter(Q(status__in = [consts.LICENSE_TEST_PERIOD, consts.LICENSE_ACTIVE, consts.LICENSE_EXPIRED]) |
Q(order_status__in=[consts.ORDER_PAID, consts.ORDER_SUSPENDED]))
.order_by('-id')
)
return render(request, template_name, {'licenses': licenses})
@login_required
def delete_license(request, pk):
if not request.is_ajax():
return HttpResponseBadRequest()
raise_if_no_profile(request)
try:
license = License.objects.get(pk=pk, company=request.user.profile,
order_status=consts.ORDER_UNPAID, payform__gt=consts.PAYFORM_FREE)
if request.method == 'POST':
license.deleted = True
license.save()
dictionary = {'res': 'Ok', 'id': pk}
except:
dictionary = {'res': 'fail'}
data = json.dumps(dictionary)
return HttpResponse(data, mimetype='application/json')
#@csrf_exempt
#def payment_result(request):
# if request.method == 'POST':
# try:
# nInvId = request.POST.get('InvId')
# nOutSum = request.POST.get('OutSum')
# sSignatureValue = request.POST.get('SignatureValue')
# SignatureValue = hashlib.md5('%s:%s:%s' % (nOutSum, nInvId, settings.ROBOKASSA_PASSWORD2)).hexdigest() # robokassa???
# if sSignatureValue.upper() == SignatureValue.upper():
# license = License.objects.get(pk=nInvId)
# license.set_paid()
# license.save()
# return HttpResponse('OK%s' % nInvId)
# else:
# return HttpResponse('bad sign')
# except License.DoesNotExist:
# return HttpResponseForbidden()
# else:
# return HttpResponseForbidden()
@csrf_exempt
def payment_success(request):
nInvId = request.GET.get('orderNumber')
order = get_object_or_404(License, pk=nInvId)
context = {'success': True, 'order_num': nInvId}
return TemplateResponse(request, 'customer/profile/end_order.html', context)
@csrf_exempt
def payment_fail(request):
message = u"Возникла проблема. Ваш Заказ не оплачен. Попробуйте оформить заявку снова, или позвоните по номеру."
return TemplateResponse(request, 'customer/profile/end_order.html', {'message': message, 'success': False})