forked from uncloud/uncloud
77 lines
2.5 KiB
Python
77 lines
2.5 KiB
Python
from django.contrib.auth import get_user_model
|
|
from rest_framework import serializers
|
|
from .models import *
|
|
|
|
from functools import reduce
|
|
from uncloud_vm.serializers import VMProductSerializer
|
|
from uncloud_vm.models import VMProduct
|
|
|
|
class BillSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = Bill
|
|
fields = ['owner', 'amount', 'due_date', 'creation_date',
|
|
'starting_date', 'ending_date', 'paid']
|
|
|
|
class PaymentSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = Payment
|
|
fields = ['owner', 'amount', 'source', 'timestamp']
|
|
|
|
class PaymentMethodSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = PaymentMethod
|
|
fields = ['owner', 'primary', 'source', 'description']
|
|
|
|
class ProductSerializer(serializers.Serializer):
|
|
vms = VMProductSerializer(many=True, required=False)
|
|
|
|
def create(self, validated_data):
|
|
owner = validated_data.pop('owner')
|
|
order = validated_data.pop('order')
|
|
|
|
vms = validated_data.pop('vms')
|
|
for vm in vms:
|
|
VMProduct.objects.create(owner=owner, order=order, **vm)
|
|
|
|
return True # FIXME: shoudl return created objects
|
|
|
|
|
|
class OrderSerializer(serializers.ModelSerializer):
|
|
products = ProductSerializer()
|
|
class Meta:
|
|
model = Order
|
|
fields = '__all__'
|
|
|
|
def create(self, validated_data):
|
|
products_data = validated_data.pop('products')
|
|
validated_data['owner'] = self.context["request"].user
|
|
|
|
# FIXME: find something to do with this:
|
|
validated_data['recurring_price'] = 0
|
|
validated_data['one_time_price'] = 0
|
|
|
|
order = Order.objects.create(**validated_data)
|
|
|
|
# Forward product creation to ProductSerializer.
|
|
products = ProductSerializer(data=products_data)
|
|
products.is_valid(raise_exception=True)
|
|
products.save(order=order,owner=order.owner)
|
|
|
|
return order
|
|
|
|
class UserSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = get_user_model()
|
|
fields = ['username', 'email', 'balance']
|
|
|
|
# Display current 'balance'
|
|
balance = serializers.SerializerMethodField('get_balance')
|
|
def __sum_balance(self, entries):
|
|
return reduce(lambda acc, entry: acc + entry.amount, entries, 0)
|
|
|
|
def get_balance(self, user):
|
|
bills = self.__sum_balance(Bill.objects.filter(owner=user))
|
|
payments = self.__sum_balance(Payment.objects.filter(owner=user))
|
|
balance = payments - bills
|
|
|
|
return balance
|