2020-02-28 13:46:33 +00:00
|
|
|
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
|
2020-02-28 13:46:33 +00:00
|
|
|
|
|
|
|
from .models import MatrixServiceProduct
|
|
|
|
from .serializers import MatrixServiceProductSerializer
|
|
|
|
|
2020-02-28 13:57:45 +00:00
|
|
|
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
|
2020-02-28 13:57:45 +00:00
|
|
|
|
|
|
|
class MatrixServiceProductViewSet(ProductViewSet):
|
2020-02-28 13:46:33 +00:00
|
|
|
permission_classes = [permissions.IsAuthenticated]
|
|
|
|
serializer_class = MatrixServiceProductSerializer
|
|
|
|
|
|
|
|
def get_queryset(self):
|
|
|
|
return MatrixServiceProduct.objects.filter(owner=self.request.user)
|
2020-02-28 13:57:45 +00:00
|
|
|
|
2020-03-03 09:51:16 +00:00
|
|
|
@transaction.atomic
|
2020-02-28 13:46:33 +00:00
|
|
|
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(
|
2020-03-03 10:27:35 +00:00
|
|
|
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(
|
2020-03-03 10:27:35 +00:00
|
|
|
service.one_time_price,
|
2020-03-03 09:51:16 +00:00
|
|
|
service.recurring_price(order.recurring_period),
|
|
|
|
service.description)
|
|
|
|
|
|
|
|
return Response(serializer.data)
|