from rest_framework import serializers from .models import Transaction from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model User = get_user_model() class CreateTransactionSerializer(serializers.ModelSerializer): user_id = serializers.PrimaryKeyRelatedField( queryset=User.objects.all(), source='user', write_only=True, help_text='User Id') def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(CreateTransactionSerializer, self).__init__(many=many, *args, **kwargs) def validate(self, data): """ Check the type is outflow or inflow Check the inflow is positive and outflow is negative """ if data['type'] not in ('outflow','inflow'): raise serializers.ValidationError({"type": _("Must be `outflow` or `inflow` ")}) if data['amount'] > 0 and data['type'] == 'outflow': raise serializers.ValidationError({"amount":_("Outflow type only allow negatives amount")}) if data['amount'] < 0 and data['type'] == 'inflow': raise serializers.ValidationError({"amount":_("Inflow type only allow positives amount")}) return data class Meta: model = Transaction fields = ('user_id', 'reference', 'account', 'type', 'amount', 'category','date') class BalanceByAccountSerializer(serializers.ModelSerializer): balance = serializers.FloatField(label='balance', read_only=True) total_inflow = serializers.FloatField(label='balance', read_only=True) total_outflow = serializers.FloatField(label='balance', read_only=True) class Meta: model = Transaction fields = ['account', 'balance','total_inflow','total_outflow']