| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- """
- Transactions app serializer
- """
- from rest_framework import serializers
- from django.utils.translation import ugettext_lazy as _
- from django.contrib.auth import get_user_model
- from .models import Transaction
- User = get_user_model()
- class CreateTransactionSerializer(serializers.ModelSerializer):
- """
- Create transaction serializer
- """
- 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().__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:
- """
- Meta class definitions
- """
- model = Transaction
- fields = ('user_id', 'reference',
- 'account', 'type', 'amount',
- 'category', 'date')
- class BalanceByAccountSerializer(serializers.ModelSerializer):
- """
- Balanced by account serializer
- """
- 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:
- """
- Meta class definitions
- """
- model = Transaction
- fields = ['account', 'balance', 'total_inflow', 'total_outflow']
|