from django.shortcuts import render from django.db import transaction from django.contrib.auth import get_user_model from rest_framework import viewsets, permissions, status from rest_framework.response import Response from rest_framework.decorators import action import json from .models import * from .serializers import * from datetime import datetime import uncloud_pay.stripe as uncloud_stripe ### # Standard user views: class BalanceViewSet(viewsets.ViewSet): # here we return a number # number = sum(payments) - sum(bills) #bills = Bill.objects.filter(owner=self.request.user) #payments = Payment.objects.filter(owner=self.request.user) # sum_paid = sum([ amount for amount payments..,. ]) # you get the picture # sum_to_be_paid = sum([ amount for amount bills..,. ]) # you get the picture pass class BillViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = BillSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Bill.objects.filter(owner=self.request.user) class PaymentViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = PaymentSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Payment.objects.filter(owner=self.request.user) class OrderViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = OrderSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Order.objects.filter(owner=self.request.user) class PaymentMethodViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated] def get_serializer_class(self): if self.action == 'create': return CreatePaymentMethodSerializer elif self.action == 'charge': return ChargePaymentMethodSerializer else: return PaymentMethodSerializer def get_queryset(self): return PaymentMethod.objects.filter(owner=self.request.user) # XXX: Handling of errors is far from great down there. @transaction.atomic def create(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # Retrieve Stripe customer ID for user. customer_id = uncloud_stripe.get_customer_id_for(request.user) if customer_id == None: return Response( {'error': 'Could not resolve customer stripe ID.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) # Register card under stripe customer. credit_card = uncloud_stripe.CreditCard(**serializer.validated_data.pop('credit_card')) card_request = uncloud_stripe.create_card(customer_id, credit_card) if card_request['error']: return Response({'stripe_error': card_request['error']}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) card_id = card_request['response_object']['id'] # Save payment method locally. serializer.validated_data['stripe_card_id'] = card_request['response_object']['id'] payment_method = PaymentMethod.objects.create(owner=request.user, **serializer.validated_data) # We do not want to return the credit card details sent with the POST # request. output_serializer = PaymentMethodSerializer(payment_method) return Response(output_serializer.data) @action(detail=True, methods=['post']) def charge(self, request, pk=None): payment_method = self.get_object() serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) amount = serializer.validated_data['amount'] try: payment = payment_method.charge(amount) output_serializer = PaymentSerializer(payment) return Response(output_serializer.data) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) ### # Admin views. class AdminPaymentViewSet(viewsets.ModelViewSet): serializer_class = PaymentSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Payment.objects.all() def create(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(timestamp=datetime.now()) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) class AdminBillViewSet(viewsets.ModelViewSet): serializer_class = BillSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Bill.objects.all() def unpaid(self, request): return Bill.objects.filter(owner=self.request.user, paid=False) def create(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(creation_date=datetime.now()) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) class AdminOrderViewSet(viewsets.ModelViewSet): serializer_class = OrderSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Order.objects.all() # PDF tests from django.views.generic import TemplateView from hardcopy.views import PDFViewMixin, PNGViewMixin class MyPDFView(PDFViewMixin, TemplateView): template_name = "bill.html" # def get_filename(self): # return "my_file_{}.pdf".format(now().strftime('Y-m-d'))