Coverage for django_napse/api/wallets/serializers/wallet_serializers.py: 71%

21 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-03-12 13:49 +0000

1from django.db.models import Q 

2from rest_framework import serializers 

3 

4from django_napse.api.transactions.serializers import CreditSerializer, DebitSerializer, TransactionSerializer 

5from django_napse.api.wallets.serializers.currency_serializer import CurrencySerializer 

6from django_napse.core.models import Transaction, Wallet 

7 

8 

9class WalletSerializer(serializers.ModelSerializer): 

10 currencies = CurrencySerializer(many=True, read_only=True) 

11 value = serializers.SerializerMethodField(read_only=True) 

12 operations = serializers.SerializerMethodField(read_only=True) 

13 

14 class Meta: 

15 model = Wallet 

16 fields = [ 

17 "title", 

18 "value", 

19 "created_at", 

20 "currencies", 

21 "operations", 

22 ] 

23 read_only_fields = [ 

24 "value", 

25 "created_at", 

26 "currencies", 

27 "operations", 

28 ] 

29 

30 def get_value(self, instance) -> float: 

31 return instance.value_market() 

32 

33 def get_operations(self, instance) -> dict: 

34 transactions = Transaction.objects.filter(Q(from_wallet=instance) | Q(to_wallet=instance)).order_by("created_at") 

35 transactions_data = TransactionSerializer(transactions, many=True).data 

36 credits_data = CreditSerializer(instance.credits.all().order_by("created_at"), many=True).data 

37 debits_data = DebitSerializer(instance.debits.all().order_by("created_at"), many=True).data 

38 # return { 

39 # "credits": CreditSerializer(instance.credits.all().order_by("created_at"), many=True).data, 

40 # "debits": DebitSerializer(instance.debits.all().order_by("created_at"), many=True).data, 

41 # "transactions": TransactionSerializer(transactions, many=True).data, 

42 # } 

43 return credits_data + debits_data + transactions_data