forked from uncloud/uncloud
80 lines
2.6 KiB
Python
80 lines
2.6 KiB
Python
from django.shortcuts import render
|
|
|
|
from django.contrib.auth.models import User
|
|
from django.shortcuts import get_object_or_404
|
|
|
|
from rest_framework import viewsets, permissions
|
|
from rest_framework.response import Response
|
|
|
|
from .models import VMHost, VMProduct, VMSnapshotProduct
|
|
from uncloud_pay.models import Order, RecurringPeriod
|
|
from .serializers import VMHostSerializer, VMProductSerializer, VMSnapshotProductSerializer
|
|
from uncloud_pay.helpers import ProductViewSet
|
|
|
|
|
|
import datetime
|
|
|
|
class VMHostViewSet(viewsets.ModelViewSet):
|
|
serializer_class = VMHostSerializer
|
|
queryset = VMHost.objects.all()
|
|
permission_classes = [permissions.IsAdminUser]
|
|
|
|
|
|
class VMProductViewSet(ProductViewSet):
|
|
permission_classes = [permissions.IsAuthenticated]
|
|
serializer_class = VMProductSerializer
|
|
|
|
def get_queryset(self):
|
|
return VMProduct.objects.filter(owner=self.request.user)
|
|
|
|
def create(self, request):
|
|
# TODO: what if something blows-up midway?
|
|
# => need a transaction
|
|
|
|
# Create base order.
|
|
order = Order.objects.create(
|
|
recurring_period=RecurringPeriod.PER_MONTH,
|
|
owner=request.user
|
|
)
|
|
order.save()
|
|
|
|
# Create VM.
|
|
serializer = VMProductSerializer(data=request.data, context={'request': request})
|
|
serializer.is_valid(raise_exception=True)
|
|
vm = serializer.save(owner=request.user, order=order)
|
|
|
|
# Add Product record to order (VM is mutable, allows to keep history in order).
|
|
order.add_record(vm.setup_fee,
|
|
vm.recurring_price(order.recurring_period), vm.description)
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
|
class VMSnapshotProductViewSet(viewsets.ModelViewSet):
|
|
permission_classes = [permissions.IsAuthenticated]
|
|
serializer_class = VMSnapshotProductSerializer
|
|
|
|
def get_queryset(self):
|
|
return VMSnapshotProduct.objects.filter(owner=self.request.user)
|
|
|
|
def create(self, request):
|
|
serializer = VMSnapshotProductSerializer(data=request.data, context={'request': request})
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
# Create order
|
|
now = datetime.datetime.now()
|
|
order = Order(owner=request.user,
|
|
creation_date=now,
|
|
starting_date=now,
|
|
recurring_price=20,
|
|
one_time_price=0,
|
|
recurring_period="per_month")
|
|
order.save()
|
|
|
|
# FIXME: calculate the gb_* values
|
|
serializer.save(owner=request.user,
|
|
order=order,
|
|
gb_ssd=12,
|
|
gb_hdd=20)
|
|
|
|
return Response(serializer.data)
|