diff --git a/finance/models.py b/finance/models.py index ae56954..a881d33 100755 --- a/finance/models.py +++ b/finance/models.py @@ -20,6 +20,12 @@ class Bill(models.Model): def get_full_price(self): return sum([i.price for i in self.invoice_set.all() if not i.price is None]) + def check_validate(self): + return self.invoice_set.filter(is_open=True).count() == 1 + + def check_pay(self): + return self.invoice_set.filter(status="F").exists() + class Meta: verbose_name = 'Счет' verbose_name_plural = 'Счета' diff --git a/finance/serializers.py b/finance/serializers.py index a166c1c..6930f5a 100644 --- a/finance/serializers.py +++ b/finance/serializers.py @@ -32,7 +32,7 @@ class InvoiceSerializer(serializers.ModelSerializer): class Meta: model = Invoice - exclude = ('bill',) + fields = '__all__' @staticmethod def get_status(self): diff --git a/finance/views.py b/finance/views.py index 4a4de84..507c5fa 100644 --- a/finance/views.py +++ b/finance/views.py @@ -41,7 +41,6 @@ class BillListView(APIView): 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: user = get_user_model().objects.get(email=bill['user']) @@ -60,66 +59,102 @@ class BillListView(APIView): bill_obj.comment = comment bill_obj.save() - for i in children: - status = get_real_name(elem=i['status'], array=Invoice.BILL_STATUSES) - try: - invoice_id = i['id'] - except KeyError: - invoice_id = None - - try: - if not invoice_id is None: - invoice = Invoice.objects.get(id=i['id']) - if invoice.status == "P" or invoice.status == status: - continue - else: - raise Invoice.DoesNotExist - - except Invoice.DoesNotExist: - i['method'] = get_real_name(elem=i['method'], array=Invoice.BILL_METHOD) - i['status'] = status - i['bill'] = bill_obj - i['yandex_pay'] = None - invoice = Invoice.objects.create(**i) - - if i['method'] == 'Y' and invoice.yandex_pay is None: - yandex_pay = Payment.objects.create( - order_amount=i['price'], - shop_amount=0, - customer_number=bill_obj.user.id, - user=bill_obj.user, - cps_email=bill_obj.user.email, - ) - invoice.yandex_pay = yandex_pay - invoice.save() - - msg = EmailMessage( - 'Выставлен новый счёт.', - '''Менеджер %s выставил счёт пользователю %s на курс "%s".''' - % ( - invoice.bill.opener.get_full_name(), - invoice.bill.user.email, - Course.objects.get(token=invoice.bill.course_token).title, - ), - 'robo@skillbox.ru', - [invoice.bill.opener.email], - bcc=['dmitry.dolya@skillbox.ru'], - ) - - msg.send() - - 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(BillSerializer(bill_obj).data, status=200) return Response("Bill not set", status=400) return Response("Course detail access only for manager users", status=403) +class InvoiceDetailView(APIView): + renderer_classes = (JSONRenderer,) + + @staticmethod + def delete(request): + invoice_id = request.JSON.get('invoice_id', None) + if invoice_id is None: + return Response("invoice_id must be set", status=400) + + try: + i = Invoice.objects.get(id=invoice_id) + if not i.status == "F" and not (i.bill.check_pay() and i.is_open): + i.delete() + except Invoice.DoesNotExist: + pass + + return Response(status=204) + + @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): + invoice_data = request.JSON.get('invoice', None) + if invoice_data is None: + return Response("Invoice mast be set", status=400) + + try: + bill = Bill.objects.get(id=invoice_data.pop('bill')) + except (Bill.DoesNotExist, KeyError): + return Response('Bill id must be set', status=400) + + if bill.check_validate() and invoice_data['is_open']: + return Response("Уже есть платёж открывающий курс", status=400) + + try: + invoice = Invoice.objects.get(id=invoice_data['id']) + except (Invoice.DoesNotExist, KeyError): + if bill.check_pay(): + return Response( + "Нельзя добавить новый платёж, так как один из платежей по счёту уже оплачен", status=400) + invoice = Invoice.objects.create(**invoice_data) + + if invoice.status == "F": + return Response(InvoiceSerializer(invoice).data, status=200) + + invoice.real_price = None + invoice.method = invoice_data['method'] + invoice.status = invoice_data['status'] + if invoice.status == "F": + invoice.real_price = invoice_data['real_price'] + + if bill.check_pay() and (invoice.price < invoice_data['price']): + return Response("""Нельзя менять стоимость по счёту в большую сторону, + когда один из платежей оплачен""", status=400) + + invoice.price = invoice_data['price'] + invoice.is_open = invoice_data['is_open'] + + if invoice.method == 'Y' and invoice.yandex_pay is None: + yandex_pay = Payment.objects.create( + order_amount=invoice.price, + shop_amount=0, + customer_number=bill.user.id, + user=bill.user, + cps_email=bill.user.email, + ) + invoice.yandex_pay = yandex_pay + + msg = EmailMessage( + 'Выставлен новый счёт.', + '''Менеджер %s выставил счёт пользователю %s на курс "%s".''' + % ( + invoice.bill.opener.get_full_name(), + invoice.bill.user.email, + Course.objects.get(token=invoice.bill.course_token).title, + ), + 'robo@skillbox.ru', + [invoice.bill.opener.email], + bcc=['dmitry.dolya@skillbox.ru'], + ) + + msg.send() + invoice.save() + + return Response(InvoiceSerializer(invoice).data, status=200) + + return Response("Invoice detail access only for manager users", status=403) + + class BillDetailView(APIView): renderer_classes = (JSONRenderer,) status_code = 200 @@ -343,7 +378,6 @@ class YandexAvisoView(APIView): 'response': xml_res, }) - msg = EmailMessage( 'Успешная оплата.', '''Пользователь "%s", перевёл %s рублей. Номер платежа в яндекс кассе %s'''