From 56d98cbb55523739375abc007bc89a96b6c288b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timoth=C3=A9e=20Floure?= Date: Thu, 7 May 2020 13:12:38 +0200 Subject: [PATCH] Implement Orders/Bills permissions, unpaid bill views --- uncloud_pay/views.py | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/uncloud_pay/views.py b/uncloud_pay/views.py index 8bb2280..bb73cfb 100644 --- a/uncloud_pay/views.py +++ b/uncloud_pay/views.py @@ -182,8 +182,13 @@ class BillViewSet(viewsets.ReadOnlyModelViewSet): def get_queryset(self): return Bill.objects.filter(owner=self.request.user) + + @action(detail=False, methods=['get']) def unpaid(self, request): - return Bill.objects.filter(owner=self.request.user, paid=False) + serializer = self.get_serializer( + Bill.get_unpaid_for(self.request.user), + many=True) + return Response(serializer.data) class OrderViewSet(viewsets.ReadOnlyModelViewSet): @@ -247,7 +252,7 @@ class BillingAddressViewSet(mixins.CreateModelMixin, class AdminPaymentViewSet(viewsets.ModelViewSet): serializer_class = PaymentSerializer - permission_classes = [permissions.IsAuthenticated] + permission_classes = [permissions.IsAdminUser] def get_queryset(self): return Payment.objects.all() @@ -260,25 +265,28 @@ class AdminPaymentViewSet(viewsets.ModelViewSet): headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) -class AdminBillViewSet(viewsets.ModelViewSet): +# Bills are generated from orders and should not be created or updated by hand. +class AdminBillViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = BillSerializer - permission_classes = [permissions.IsAuthenticated] + permission_classes = [permissions.IsAdminUser] def get_queryset(self): return Bill.objects.all() + @action(detail=False, methods=['get']) def unpaid(self, request): - return Bill.objects.filter(owner=self.request.user, paid=False) + unpaid_bills = [] + # XXX: works but we can do better than number of users + 1 SQL requests... + for user in get_user_model().objects.all(): + unpaid_bills = unpaid_bills + Bill.get_unpaid_for(self.request.user) - def create(self, request): - serializer = self.get_serializer(data=request.data) - serializer.is_valid(raise_exception=True) - serializer.save(creation_date=datetime.now()) + serializer = self.get_serializer(unpaid_bills, many=True) + return Response(serializer.data) - headers = self.get_success_headers(serializer.data) - return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) - -class AdminOrderViewSet(viewsets.ModelViewSet): +class AdminOrderViewSet(mixins.ListModelMixin, + mixins.RetrieveModelMixin, + mixins.CreateModelMixin, + viewsets.GenericViewSet): permission_classes = [permissions.IsAdminUser] def get_serializer(self, *args, **kwargs):