uncloud-mravi/uncloud/ungleich_service/views.py

61 lines
2 KiB
Python

from rest_framework import viewsets, permissions
from rest_framework.response import Response
from django.db import transaction
from .models import MatrixServiceProduct
from .serializers import MatrixServiceProductSerializer
from uncloud_pay.helpers import ProductViewSet
from uncloud_pay.models import Order
from uncloud_vm.models import VMProduct
class MatrixServiceProductViewSet(ProductViewSet):
permission_classes = [permissions.IsAuthenticated]
serializer_class = MatrixServiceProductSerializer
def get_queryset(self):
return MatrixServiceProduct.objects.filter(owner=self.request.user)
@transaction.atomic
def create(self, request):
# Extract serializer data.
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
order_recurring_period = serializer.validated_data.pop("recurring_period")
# Create base order.
order = Order.objects.create(
recurring_period=order_recurring_period,
owner=request.user
)
order.save()
# Create unerderlying VM.
# TODO: move this logic to a method for use with other
# products.
vm_data = serializer.validated_data.pop('vm')
vm_data['owner'] = request.user
vm_data['order'] = order
vm = VMProduct.objects.create(**vm_data)
# XXX: Move this to some kind of on_create hook in parent
# Product class?
order.add_record(
vm.one_time_price,
vm.recurring_price(order.recurring_period),
vm.description)
# Create service.
service = serializer.save(
order=order,
owner=self.request.user,
vm=vm)
# XXX: Move this to some kind of on_create hook in parent
# Product class?
order.add_record(
service.one_time_price,
service.recurring_price(order.recurring_period),
service.description)
return Response(serializer.data)