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.
 
 
 
 
 
 

95 lines
3.6 KiB

from django.contrib.auth import get_user_model
from courses.models import Course
from lms.global_decorators import transaction_decorator
from rest_framework.views import APIView
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from django.db.models import Q
from yandex_money.models import Payment
from finance.models import Bill, Invoice
from finance.serializers import BillSerializer, InvoiceSerializer
from lms.tools import get_real_name
class BillListView(APIView):
renderer_classes = (JSONRenderer,)
@staticmethod
def get(request):
if request.user.is_authenticated:
return Response(
[BillSerializer(i).data for i in Bill.objects.filter(Q(user=request.user) | Q(opener=request.user))],
status=200,
)
return Response("Permission denied", status=403)
@transaction_decorator
def post(self, request):
if request.user.is_authenticated and (request.user.groups.filter(name__in=['managers','lead_managers']).exists()
or request.user.is_superuser):
bill = request.JSON.get('bill')
children = request.JSON.get('children', [])
if bill:
bill['user'] = get_user_model().objects.get(email=bill['user'])
bill['opener'] = get_user_model().objects.get(email=bill['opener'])
bill['course'] = Course.objects.get(title=bill['course'][0])
bill_obj, is_create = Bill.objects.update_or_create(**bill)
invoices = bill_obj.invoice_set.all()
for i in children:
i['method'] = get_real_name(elem=i['method'][0], array=Invoice.BILL_METHOD)
i['status'] = get_real_name(elem=i['status'][0], array=Invoice.BILL_STATUSES)
i['bill'] = bill_obj
i['yandex_pay'] = None
if i['method'] == 'Y' and i['status'] == 'P':
i['yandex_pay'], _is_create = Payment.objects.get_or_create(
order_amount=i['price'].price,
order_number=bill_obj.id,
customer_number=bill_obj.user.id,
user=bill_obj.user,
cps_email=bill_obj.user.email,
)
invoice, _is_create = Invoice.objects.update_or_create(**i)
invoices = [j for j in invoices if not j.id == invoice.id]
[i.delete() for i in invoices]
res = {
"bill": BillSerializer(bill_obj).data,
"children": [InvoiceSerializer(i).data for i in bill_obj.invoice_set.all()],
}
return Response(res, status=200)
return Response("Bill not set", status=400)
return Response("Course detail access only for manager users", status=403)
class BillDetailView(APIView):
renderer_classes = (JSONRenderer,)
status_code = 200
def get(self, request, pk):
if request.user.is_authenticated:
try:
bill = Bill.objects.get(id=pk)
except Bill.DoesNotExist:
return Response("Bill not found", status=404)
res = {
"bill": BillSerializer(bill).data,
"children": [InvoiceSerializer(i).data for i in bill.invoice_set.all()],
}
return Response(
res,
status=self.status_code,
)
return Response("Permission denied", status=403)