uncloud-mravi/uncloud_django_based/uncloud/ungleich_service/views.py

62 lines
2 KiB
Python
Raw Normal View History

from rest_framework import viewsets, permissions
2020-03-03 09:51:16 +00:00
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
2020-03-03 09:51:16 +00:00
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)
2020-03-03 09:51:16 +00:00
@transaction.atomic
def create(self, request):
2020-03-03 09:51:16 +00:00
# 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,
2020-03-03 09:51:16 +00:00
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,
2020-03-03 09:51:16 +00:00
service.recurring_price(order.recurring_period),
service.description)
return Response(serializer.data)