From eefc6dd4c1f0dbe8d3741d58cc7ac810b004966d Mon Sep 17 00:00:00 2001 From: Sayyid Hamid Mahdavi Date: Sun, 17 Aug 2025 21:15:54 +0330 Subject: [PATCH 01/16] wallet with category --- apps/wallet/models.py | 257 ++++++++++++++++++++++++++++--- apps/wallet/urls.py | 15 ++ apps/wallet/views/application.py | 177 ++++++++++++++++++++- utils/models.py | 15 ++ 4 files changed, 445 insertions(+), 19 deletions(-) create mode 100644 utils/models.py diff --git a/apps/wallet/models.py b/apps/wallet/models.py index a0de212..7f9660b 100755 --- a/apps/wallet/models.py +++ b/apps/wallet/models.py @@ -1,22 +1,48 @@ import datetime import uuid +from django.contrib.auth import get_user_model from django.core.validators import MinValueValidator from django.db import models from django.db import transaction from django.db.models import F from django.utils.translation import gettext_lazy as _ +from oauth2_provider.models import get_application_model from rest_framework.exceptions import APIException, ValidationError from django.conf import settings from oauth2_provider import settings as oauth2_settings from gooyal_accounts_client.models import PublicUser from utils.accounts_client import get_user_details, get_application_details +from utils.models import BaseModel from .constans import StateChoices, TypeChoices from apps.users.models import User from ..gooyal_oauth2.models import Application +class WalletQuerySet(models.QuerySet): + pass + +class Wallet(BaseModel): + owner_uuid = models.UUIDField(db_index=True, null=False) + category = models.ForeignKey('Category', on_delete=models.PROTECT, null=True) + owner_type = models.IntegerField(choices=TypeChoices.choices, db_index=True) + balance = models.BigIntegerField(_('balance'), default=0) + + objects = WalletQuerySet.as_manager() + + +class CategoryQuerySet(models.QuerySet): + pass + +class Category(BaseModel): + application = models.ForeignKey(oauth2_settings.APPLICATION_MODEL, on_delete=models.PROTECT, null=True) + + label = models.CharField(_('label'), max_length=255) + + objects = CategoryQuerySet.as_manager() + + # TODO: move DRF functionalities to view or serializers # class TransactionManager(models.Manager): # def create_transaction( @@ -47,36 +73,43 @@ from ..gooyal_oauth2.models import Application # return tr -class Transaction(models.Model): - uuid = models.UUIDField(primary_key=True, editable=True, default=uuid.uuid4, unique=True, - db_index=True) # reserve_code +class TransactionQuerySet(models.QuerySet): + pass + + +class Transaction(BaseModel): amount = models.PositiveBigIntegerField(_('amount'), blank=False, validators=[MinValueValidator(1)]) delay = models.PositiveIntegerField(default=0, blank=True) # number of days for delayed payments - payer_id = models.UUIDField(blank=True, null=True) - payer_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) - payee_id = models.UUIDField() - payee_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) + # payer_id = models.UUIDField(blank=True, null=True) + # payer_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) + # payee_id = models.UUIDField() + # payee_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) state = models.IntegerField(choices=StateChoices.choices, default=StateChoices.CREATED) - created_at = models.DateTimeField(auto_now_add=True, null=True, db_index=True) - updated_at = models.DateTimeField(auto_now=True, null=True, db_index=True) application = models.ForeignKey(oauth2_settings.APPLICATION_MODEL, on_delete=models.PROTECT, related_name='transactions', null=True) + payer_wallet = models.ForeignKey(Wallet, on_delete=models.PROTECT, null=True, + related_name='payer_wallet_transactions', + db_index=True) + payee_wallet = models.ForeignKey(Wallet, on_delete=models.PROTECT, null=True, + related_name='payee_wallet_transactions', + db_index=True) details = models.JSONField(null=True, blank=True, default=dict) - # detail = {'payer_name', 'payee_name', 'description', 'application_name', 'payer_avatar_url', 'payee_avatar_url', # 'reference_id', 'application_details_url'} - # objects = TransactionManager() + objects = TransactionQuerySet.as_manager() class Meta: ordering = ['-created_at'] + # unique_together = ('application', 'detail_id',) def withdraw_from_payer_balance(self): payer = self.get_payer() - payer_is_allowed_negative_balance = self.payer_type==TypeChoices.APPLICATION.value and str(self.payer_id) in settings.ALLOWED_NEGATIVE_BALANCE_APPLICATIONS - if self.amount > payer.balance and not payer_is_allowed_negative_balance : + payer_is_allowed_negative_balance = self.payer_type == TypeChoices.APPLICATION.value and str( + self.payer_id) in settings.ALLOWED_NEGATIVE_BALANCE_APPLICATIONS + if self.amount > payer.balance and not payer_is_allowed_negative_balance: raise APIException('not enough balance') payer.balance = F('balance') - self.amount payer.save(update_fields=['balance']) @@ -227,7 +260,7 @@ class Transaction(models.Model): else: payer_details = get_application_details(self.payer_id) self.details['payer_name'] = payer_details.name - #TODO: get avatar from details + # TODO: get avatar from details is_updated = True print("payer_details:", payer_details) print("is_updated:", is_updated) @@ -241,7 +274,7 @@ class Transaction(models.Model): else: payee_details = get_application_details(self.payee_id) self.details['payee_name'] = payee_details.name - #TODO: get avatar from details + # TODO: get avatar from details is_updated = True print("payee_details:", payee_details) @@ -253,7 +286,7 @@ class Transaction(models.Model): print('application_details:', application_details) try: self.details['application_name'] = application_details.name - # TODO: get avatar from details + # TODO: get avatar from details is_updated = True except Exception as e: @@ -264,9 +297,197 @@ class Transaction(models.Model): print('update details') self.save() - def __str__(self): try: return f"{self.get_payer()} -> {self.get_payee()} ({self.uuid}): {self.amount} - {self.get_state_display()}" except: - return str(self.uuid) \ No newline at end of file + return str(self.uuid) + + # def withdraw_from_payer_balance(self): + # payer = self.get_payer() + # payer_is_allowed_negative_balance = self.payer_type==TypeChoices.APPLICATION.value and str(self.payer_id) in settings.ALLOWED_NEGATIVE_BALANCE_APPLICATIONS + # if self.amount > payer.balance and not payer_is_allowed_negative_balance : + # raise APIException('not enough balance') + # payer.balance = F('balance') - self.amount + # payer.save(update_fields=['balance']) + # + # def deposit_to_payee_balance(self): + # payee = self.get_payee() + # payee.balance = F('balance') + self.amount + # payee.save(update_fields=['balance']) + # + # def get_pay_entity(self, entity_id, entity_type): + # if entity_type == TypeChoices.APPLICATION: + # entity: Application = Application.objects.get(pk=entity_id) + # else: + # entity: User = User.objects.get(pk=entity_id) + # + # return entity + # + # def get_payer(self): + # return self.get_pay_entity(self.payer_id, self.payer_type) + # + # def get_payee(self): + # return self.get_pay_entity(self.payee_id, self.payee_type) + # + # def change_state(self, from_state, to_state, error_message=None, **data): + # if self.state == from_state: + # updated = Transaction.objects.filter(pk=self.pk, state=from_state).update( + # state=to_state, + # **data + # ) + # if updated: # double check in db level + # self.state = to_state + # else: + # raise APIException(error_message) + # else: + # raise APIException(error_message) + # + # def pay(self, payer_id=None, payer_type=None): + # if not self.payer_id and not (payer_id and payer_type): + # raise APIException('payer identification error') + # + # if self.payer_id and payer_id and not (self.payer_id == payer_id and self.payer_type == payer_type): + # raise APIException('payer identification error') + # + # if not self.state == StateChoices.CREATED: + # raise APIException('this transaction is not ready to pay') + # + # if not self.payer_id: + # self.payer_id = payer_id + # self.payer_type = payer_type + # + # payer = self.get_payer() + # + # if payer.balance < self.amount: + # raise APIException('not enough balance') + # + # with transaction.atomic(): + # if self.delay: + # self.change_state( + # StateChoices.CREATED, + # StateChoices.DELAYED, + # error_message='this transaction is not ready to pay', + # payer_id=payer_id, + # payer_type=payer_type + # ) + # + # else: + # self.change_state( + # StateChoices.CREATED, + # StateChoices.SUCCESS, + # error_message='this transaction is not ready to pay', + # payer_id=payer_id, + # payer_type=payer_type + # ) + # self.deposit_to_payee_balance() + # + # self.withdraw_from_payer_balance() + # return self + # + # def receipt(self): + # if not self.state == StateChoices.DELAYED: + # raise APIException('this transaction is not delayed') + # + # with transaction.atomic(): + # self.change_state( + # StateChoices.DELAYED, + # StateChoices.SUCCESS, + # error_message='this transaction is not delayed' + # ) + # self.deposit_to_payee_balance() + # return self + # + # def submit(self): + # payer = self.get_payer() + # payee = self.get_payee() + # + # if not payer: + # raise APIException('payer identification error') + # + # if not payee: + # raise APIException('payee identification error') + # + # if not self.state == StateChoices.CREATED: + # raise APIException('this transaction is not ready to pay') + # + # with transaction.atomic(): + # self.withdraw_from_payer_balance() + # self.change_state( + # StateChoices.CREATED, + # StateChoices.PENDING, + # error_message='this transaction is not ready to pay' + # ) + # return self + # + # def verify(self): + # if not self.state == StateChoices.PENDING: + # raise APIException('this transaction is not pending') + # + # with transaction.atomic(): + # self.deposit_to_payee_balance() + # self.change_state( + # StateChoices.PENDING, + # StateChoices.SUCCESS, + # error_message='this transaction is not pending' + # ) + # return self + # + # def get_role(self, entity): + # + # if self.payer_id == entity.uuid: + # return 1 + # elif self.payee_id == entity.uuid: + # return 2 + # else: + # return 0 + # + # def update_details(self, force_update=False): + # if not isinstance(self.details, dict): + # self.details = {} + # self.save() + # # detail = {'payer_name', 'payee_name', 'application_name', 'payer_avatar_url', 'payee_avatar_url', 'application_avatar_url'} + # is_updated = False + # if not self.details.get('payer_name'): + # if self.payer_type == TypeChoices.USER.value: + # payer_details: PublicUser = get_user_details(self.payer_id) + # self.details['payer_name'] = payer_details.first_name + payer_details.last_name + # self.details['payer_avatar_url'] = payer_details.avatar + # else: + # payer_details = get_application_details(self.payer_id) + # self.details['payer_name'] = payer_details.name + # #TODO: get avatar from details + # + # is_updated = True + # + # if not self.details.get('payee_name'): + # if self.payee_type == TypeChoices.USER.value: + # payee_details: PublicUser = get_user_details(self.payee_id) + # self.details['payee_name'] = payee_details.first_name + payee_details.last_name + # self.details['payee_avatar_url'] = payee_details.avatar + # else: + # payee_details = get_application_details(self.payee_id) + # self.details['payee_name'] = payee_details.name + # #TODO: get avatar from details + # + # is_updated = True + # + # if not self.details.get('application_name'): + # application_details = get_application_details(self.application_id) + # try: + # self.details['application_name'] = application_details.name + # # TODO: get avatar from details + # + # is_updated = True + # except Exception as e: + # pass + # + # if is_updated: + # self.save() + # + # + # def __str__(self): + # try: + # return f"{self.get_payer()} -> {self.get_payee()} ({self.uuid}): {self.amount} - {self.get_state_display()}" + # except: + # return str(self.uuid) diff --git a/apps/wallet/urls.py b/apps/wallet/urls.py index dd98add..c0dd409 100644 --- a/apps/wallet/urls.py +++ b/apps/wallet/urls.py @@ -38,6 +38,21 @@ application_urlpatterns = [ path('api/application/', application_views.TransactionListAPIView.as_view(), name='application_transaction_list_api'), path('api/application//', application_views.TransactionDetailAPIView.as_view(), name='application_transaction_detail'), + + + path('api/application//balance', application_views.CategoryBalanceAPIView.as_view(), name='application_wallet_balance_api'), + + path('api/application//user_balance/', application_views.CategoryUserBalanceAPIView.as_view(), name='application_user_wallet_balance_api'), + + path('api/application//deposit/', application_views.CategoryDepositSubmitAPIView.as_view(), name='application_deposit_submit_api'), + path('api/application//deposit//verify', application_views.CategoryDepositVerifyAPIView.as_view(), name='application_deposit_verify_api'), + + path('api/application//withdraw/', application_views.CategoryWithdrawSubmitAPIView.as_view(), name='application_withdraw_submit_api'), + path('api/application//withdraw//verify', application_views.CategoryWithdrawVerifyAPIView.as_view(), name='application_withdraw_verify_api'), + + path('api/application//', application_views.CategoryTransactionListAPIView.as_view(), name='application_transaction_list_api'), + path('api/application///', application_views.CategoryTransactionDetailAPIView.as_view(), name='application_transaction_detail'), + ] urlpatterns = user_urlpatterns + application_urlpatterns \ No newline at end of file diff --git a/apps/wallet/views/application.py b/apps/wallet/views/application.py index 4f75456..61ca365 100755 --- a/apps/wallet/views/application.py +++ b/apps/wallet/views/application.py @@ -3,11 +3,12 @@ from oauth2_provider.contrib.rest_framework import TokenHasScope, IsAuthenticate from rest_framework import generics, permissions, mixins from rest_framework.exceptions import APIException from rest_framework.generics import get_object_or_404 +from rest_framework.request import Request from rest_framework.response import Response from apps.users.models import User from apps.wallet.constans import TypeChoices, StateChoices -from apps.wallet.models import Transaction +from apps.wallet.models import Transaction, Category, Wallet from apps.wallet.serializers import ApplicationDepositSerializer, ApplicationWithdrawSerializer, \ ApplicationTransactionSerializer, ApplicationBalanceSerializer, MyWalletSerializer @@ -20,6 +21,10 @@ def get_application(request): return application +def get_wallet_category(request: Request): + pass + + class BalanceAPIView(generics.RetrieveAPIView): ''' API for getting specified user or application balance. @@ -75,6 +80,7 @@ class TransactionListAPIView(generics.ListAPIView): Q(payee_id=application.pk, payee_type=TypeChoices.APPLICATION.value) ).all() + # from application to another entity # TODO: better name class DepositSubmitAPIView(generics.CreateAPIView): @@ -165,3 +171,172 @@ class WithdrawVerifyAPIView(generics.RetrieveAPIView): serializer = self.get_serializer(instance) return Response(serializer.data) + + +class CategoryBalanceAPIView(generics.RetrieveAPIView): + ''' + API for getting specified user or application balance. + ''' + permission_classes = [TokenHasScope] + serializer_class = ApplicationBalanceSerializer + required_scopes = ['wallet.application:get_balance'] + + def get_object(self): + category_uuid = self.kwargs.get('category_uuid') + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + application = get_application(self.request) + wallet, created = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, + category=category) + return wallet + + +class CategoryUserBalanceAPIView(generics.RetrieveAPIView): + ''' + API for getting specified user or application balance. + ''' + permission_classes = [IsAuthenticatedOrTokenHasScope] + serializer_class = MyWalletSerializer + required_scopes = ['wallet.application:get_user_balance'] + + def get_object(self): + category_uuid = self.kwargs.get('category_uuid') + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + user_uuid = self.kwargs.get('uuid') + user, created = User.objects.get_or_create(uuid=user_uuid) + application = get_application(self.request) + wallet, created = Wallet.objects.get_or_create(owner_uuid=user_uuid, owner_type=TypeChoices.USER, + category=category) + return wallet + + +class CategoryTransactionDetailAPIView(generics.RetrieveAPIView): + permission_classes = [TokenHasScope] + serializer_class = ApplicationTransactionSerializer + lookup_field = 'uuid' + required_scopes = ['wallet.application:get_transaction_detail'] + + def get_queryset(self): + application = get_application(self.request) + return Transaction.objects.filter(Q(application=application) | + Q(payer_wallet__owner_uuid=application.pk, + payer_wallet__owner_type=TypeChoices.APPLICATION) | + Q(payee_wallet__owner_uuid=application.pk, + payee_wallet__owner_type=TypeChoices.APPLICATION) + ).all() + + +class CategoryTransactionListAPIView(generics.ListAPIView): + permission_classes = [TokenHasScope] + serializer_class = ApplicationTransactionSerializer + lookup_field = 'uuid' + required_scopes = ['wallet.application:get_transaction_list'] + + def get_queryset(self): + application = get_application(self.request) + return Transaction.objects.filter(Q(application=application) | + Q(payer_wallet__owner_uuid=application.pk, + payer_wallet__owner_type=TypeChoices.APPLICATION) | + Q(payee_wallet__owner_uuid=application.pk, + payee_wallet__owner_type=TypeChoices.APPLICATION) + ).all() + + +# from application to another entity +# TODO: better name +class CategoryDepositSubmitAPIView(generics.CreateAPIView): + permission_classes = [IsAuthenticatedOrTokenHasScope] + serializer_class = ApplicationDepositSerializer + required_scopes = ['wallet.application.deposit:submit'] + + def get_queryset(self): + category_uuid = self.kwargs.get('category_uuid') + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + application = get_application(self.request) + wallet, created = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, + category=category) + return Transaction.objects.filter(application=application, + payer_wallet__owner_uuid=application.pk, + payer_wallet__owner_type=TypeChoices.APPLICATION).all() + + def perform_create(self, serializer): + # TODO: get_or_create instead of create if uuid given + # TODO: it is possible to merage create and submit in one step for improve performance + application = get_application(self.request) + category = get_object_or_404(Category.objects.all(), uuid=self.kwargs.get('category_uuid')) + wallet = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) + instance = serializer.save(payer_wallet=wallet, + application=application) + try: + instance.submit() + except Exception as e: + print(e) + APIException('Failed to submit deposit') + + +class CategoryDepositVerifyAPIView(generics.RetrieveAPIView): + permission_classes = [IsAuthenticatedOrTokenHasScope] + serializer_class = ApplicationDepositSerializer + lookup_field = 'uuid' + required_scopes = ['wallet.application.deposit:verify'] + + def get_queryset(self): + application = get_application(self.request) + category = get_object_or_404(Category.objects.all(), uuid=self.kwargs.get('category_uuid')) + wallet = Wallet.objects.get(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) + return Transaction.objects.filter(application=application, + payer_wallet=wallet).all() + + def retrieve(self, request, *args, **kwargs): + instance = self.get_object() + if instance.state == StateChoices.PENDING: + instance.verify() + + serializer = self.get_serializer(instance) + return Response(serializer.data) + + +# from another entity to application +class CategoryWithdrawSubmitAPIView(generics.CreateAPIView): + permission_classes = [TokenHasScope] + serializer_class = ApplicationWithdrawSerializer + required_scopes = ['wallet.application.withdraw:submit'] + + def get_queryset(self): + category_uuid = self.kwargs.get('category_uuid') + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + application = get_application(self.request) + wallet, created = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, + category=category) + return Transaction.objects.filter(application=application, wallet=wallet).all() + + def perform_create(self, serializer): + # TODO: get_or_create instead of create if uuid given + # TODO: it is possible to merage create and submit in one step for improve performance + application = get_application(self.request) + category = get_object_or_404(Category.objects.all(), uuid=self.kwargs.get('category_uuid')) + wallet = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) + instance = serializer.save(payee_wallet=wallet, application=application) + + instance.submit() + + +class CategoryWithdrawVerifyAPIView(generics.RetrieveAPIView): + permission_classes = [TokenHasScope] + serializer_class = ApplicationWithdrawSerializer + lookup_field = 'uuid' + required_scopes = ['wallet.application.withdraw:verify'] + + def get_queryset(self): + application = get_application(self.request) + category = get_object_or_404(Category.objects.all(), uuid=self.kwargs.get('category_uuid')) + wallet = Wallet.objects.get(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) + return Transaction.objects.filter(application=application, + payee_wallet=wallet).all() + + def retrieve(self, request, *args, **kwargs): + instance = self.get_object() + if instance.state == StateChoices.PENDING: + instance.verify() + + serializer = self.get_serializer(instance) + return Response(serializer.data) diff --git a/utils/models.py b/utils/models.py new file mode 100644 index 0000000..0c28a0d --- /dev/null +++ b/utils/models.py @@ -0,0 +1,15 @@ +import json +import uuid +from datetime import datetime + +from django.db import models +from django.utils.translation import gettext_lazy as _ + +class BaseModel(models.Model): + id = None + uuid = models.UUIDField(primary_key=True, editable=True, default=uuid.uuid4, unique=True, db_index=True) + created_at = models.DateTimeField(auto_now_add=True, db_index=True) + updated_at = models.DateTimeField(auto_now=True, db_index=True) + + class Meta: + abstract = True From 3a5dfb14484dd6f2b2c1a2dc31522cb0370c1b1f Mon Sep 17 00:00:00 2001 From: Sayyid Hamid Mahdavi Date: Tue, 19 Aug 2025 19:25:36 +0330 Subject: [PATCH 02/16] wallet with category --- apps/wallet/admin.py | 4 +- ...0008_alter_transaction_options_and_more.py | 71 ++++ apps/wallet/models.py | 374 +++++++++--------- apps/wallet/urls.py | 27 +- apps/wallet/views/application.py | 64 ++- apps/wallet/views/user.py | 60 ++- 6 files changed, 372 insertions(+), 228 deletions(-) create mode 100644 apps/wallet/migrations/0008_alter_transaction_options_and_more.py diff --git a/apps/wallet/admin.py b/apps/wallet/admin.py index 855802f..22cec1d 100755 --- a/apps/wallet/admin.py +++ b/apps/wallet/admin.py @@ -1,5 +1,5 @@ from django.contrib import admin -from .models import Transaction +from .models import Transaction, Wallet, Category class TransactionAdmin(admin.ModelAdmin): list_display = ['uuid', 'amount', 'created_at', 'updated_at', 'payer_id', 'payer_type', 'payee_id', 'payee_type', 'state', 'application'] @@ -7,3 +7,5 @@ class TransactionAdmin(admin.ModelAdmin): list_filter = ['state', 'payer_type', 'payee_type'] admin.site.register(Transaction, TransactionAdmin) +admin.site.register(Wallet) +admin.site.register(Category) diff --git a/apps/wallet/migrations/0008_alter_transaction_options_and_more.py b/apps/wallet/migrations/0008_alter_transaction_options_and_more.py new file mode 100644 index 0000000..62aa47d --- /dev/null +++ b/apps/wallet/migrations/0008_alter_transaction_options_and_more.py @@ -0,0 +1,71 @@ +# Generated by Django 5.1.4 on 2025-08-19 08:46 + +import django.db.models.deletion +import uuid +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('wallet', '0007_alter_transaction_created_at_and_more'), + migrations.swappable_dependency(settings.OAUTH2_PROVIDER_APPLICATION_MODEL), + ] + + operations = [ + migrations.AlterModelOptions( + name='transaction', + options={'ordering': ['-created_at']}, + ), + migrations.AlterField( + model_name='transaction', + name='created_at', + field=models.DateTimeField(auto_now_add=True, db_index=True, default=None), + preserve_default=False, + ), + migrations.AlterField( + model_name='transaction', + name='updated_at', + field=models.DateTimeField(auto_now=True, db_index=True, default=None), + preserve_default=False, + ), + migrations.CreateModel( + name='Category', + fields=[ + ('uuid', models.UUIDField(db_index=True, default=uuid.uuid4, primary_key=True, serialize=False, unique=True)), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True, db_index=True)), + ('label', models.CharField(max_length=255, verbose_name='label')), + ('application', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.OAUTH2_PROVIDER_APPLICATION_MODEL)), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='Wallet', + fields=[ + ('uuid', models.UUIDField(db_index=True, default=uuid.uuid4, primary_key=True, serialize=False, unique=True)), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True, db_index=True)), + ('owner_uuid', models.UUIDField(db_index=True)), + ('owner_type', models.IntegerField(choices=[(1, 'user'), (2, 'application')], db_index=True)), + ('balance', models.BigIntegerField(default=0, verbose_name='balance')), + ('category', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='wallet.category')), + ], + options={ + 'abstract': False, + }, + ), + migrations.AddField( + model_name='transaction', + name='payee_wallet', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='payee_wallet_transactions', to='wallet.wallet'), + ), + migrations.AddField( + model_name='transaction', + name='payer_wallet', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='payer_wallet_transactions', to='wallet.wallet'), + ), + ] diff --git a/apps/wallet/models.py b/apps/wallet/models.py index 7f9660b..9596b62 100755 --- a/apps/wallet/models.py +++ b/apps/wallet/models.py @@ -74,16 +74,23 @@ class Category(BaseModel): class TransactionQuerySet(models.QuerySet): - pass + def migrate(self): + for transaction in self: + payer = transaction.get_payer() + payee = transaction.get_payee() + payer_wallet, created = Wallet.objects.get_or_create(owner_uuid=transaction.payer_id, owner_type=transaction.payer_type, defaults={'balance': payer.balance}) + payee_wallet, created = Wallet.objects.get_or_create(owner_uuid=transaction.payee_id, owner_type=transaction.payee_type, defaults={'balance': payer.balance}) + transaction.payer_wallet = payer_wallet + transaction.payee_wallet = payee_wallet class Transaction(BaseModel): amount = models.PositiveBigIntegerField(_('amount'), blank=False, validators=[MinValueValidator(1)]) delay = models.PositiveIntegerField(default=0, blank=True) # number of days for delayed payments - # payer_id = models.UUIDField(blank=True, null=True) - # payer_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) - # payee_id = models.UUIDField() - # payee_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) + payer_id = models.UUIDField(blank=True, null=True) + payer_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) + payee_id = models.UUIDField() + payee_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) state = models.IntegerField(choices=StateChoices.choices, default=StateChoices.CREATED) application = models.ForeignKey(oauth2_settings.APPLICATION_MODEL, on_delete=models.PROTECT, related_name='transactions', null=True) @@ -103,6 +110,12 @@ class Transaction(BaseModel): class Meta: ordering = ['-created_at'] + def __str__(self): + try: + return f"{self.get_payer()} -> {self.get_payee()} ({self.uuid}): {self.amount} - {self.get_state_display()}" + except: + return str(self.uuid) + # unique_together = ('application', 'detail_id',) def withdraw_from_payer_balance(self): @@ -297,197 +310,162 @@ class Transaction(BaseModel): print('update details') self.save() - def __str__(self): - try: - return f"{self.get_payer()} -> {self.get_payee()} ({self.uuid}): {self.amount} - {self.get_state_display()}" - except: - return str(self.uuid) + ######################## category + def category_withdraw_from_payer_balance(self): + payer_is_allowed_negative_balance = self.payer_type == TypeChoices.APPLICATION.value and str( + self.payer_id) in settings.ALLOWED_NEGATIVE_BALANCE_APPLICATIONS + if self.amount > self.payer_wallet.balance and not payer_is_allowed_negative_balance: + raise APIException('not enough balance') + self.payer_wallet.balance = F('balance') - self.amount + self.payer_wallet.save(update_fields=['balance']) - # def withdraw_from_payer_balance(self): - # payer = self.get_payer() - # payer_is_allowed_negative_balance = self.payer_type==TypeChoices.APPLICATION.value and str(self.payer_id) in settings.ALLOWED_NEGATIVE_BALANCE_APPLICATIONS - # if self.amount > payer.balance and not payer_is_allowed_negative_balance : - # raise APIException('not enough balance') - # payer.balance = F('balance') - self.amount - # payer.save(update_fields=['balance']) - # - # def deposit_to_payee_balance(self): - # payee = self.get_payee() - # payee.balance = F('balance') + self.amount - # payee.save(update_fields=['balance']) - # - # def get_pay_entity(self, entity_id, entity_type): - # if entity_type == TypeChoices.APPLICATION: - # entity: Application = Application.objects.get(pk=entity_id) - # else: - # entity: User = User.objects.get(pk=entity_id) - # - # return entity - # - # def get_payer(self): - # return self.get_pay_entity(self.payer_id, self.payer_type) - # - # def get_payee(self): - # return self.get_pay_entity(self.payee_id, self.payee_type) - # - # def change_state(self, from_state, to_state, error_message=None, **data): - # if self.state == from_state: - # updated = Transaction.objects.filter(pk=self.pk, state=from_state).update( - # state=to_state, - # **data - # ) - # if updated: # double check in db level - # self.state = to_state - # else: - # raise APIException(error_message) - # else: - # raise APIException(error_message) - # - # def pay(self, payer_id=None, payer_type=None): - # if not self.payer_id and not (payer_id and payer_type): - # raise APIException('payer identification error') - # - # if self.payer_id and payer_id and not (self.payer_id == payer_id and self.payer_type == payer_type): - # raise APIException('payer identification error') - # - # if not self.state == StateChoices.CREATED: - # raise APIException('this transaction is not ready to pay') - # - # if not self.payer_id: - # self.payer_id = payer_id - # self.payer_type = payer_type - # - # payer = self.get_payer() - # - # if payer.balance < self.amount: - # raise APIException('not enough balance') - # - # with transaction.atomic(): - # if self.delay: - # self.change_state( - # StateChoices.CREATED, - # StateChoices.DELAYED, - # error_message='this transaction is not ready to pay', - # payer_id=payer_id, - # payer_type=payer_type - # ) - # - # else: - # self.change_state( - # StateChoices.CREATED, - # StateChoices.SUCCESS, - # error_message='this transaction is not ready to pay', - # payer_id=payer_id, - # payer_type=payer_type - # ) - # self.deposit_to_payee_balance() - # - # self.withdraw_from_payer_balance() - # return self - # - # def receipt(self): - # if not self.state == StateChoices.DELAYED: - # raise APIException('this transaction is not delayed') - # - # with transaction.atomic(): - # self.change_state( - # StateChoices.DELAYED, - # StateChoices.SUCCESS, - # error_message='this transaction is not delayed' - # ) - # self.deposit_to_payee_balance() - # return self - # - # def submit(self): - # payer = self.get_payer() - # payee = self.get_payee() - # - # if not payer: - # raise APIException('payer identification error') - # - # if not payee: - # raise APIException('payee identification error') - # - # if not self.state == StateChoices.CREATED: - # raise APIException('this transaction is not ready to pay') - # - # with transaction.atomic(): - # self.withdraw_from_payer_balance() - # self.change_state( - # StateChoices.CREATED, - # StateChoices.PENDING, - # error_message='this transaction is not ready to pay' - # ) - # return self - # - # def verify(self): - # if not self.state == StateChoices.PENDING: - # raise APIException('this transaction is not pending') - # - # with transaction.atomic(): - # self.deposit_to_payee_balance() - # self.change_state( - # StateChoices.PENDING, - # StateChoices.SUCCESS, - # error_message='this transaction is not pending' - # ) - # return self - # - # def get_role(self, entity): - # - # if self.payer_id == entity.uuid: - # return 1 - # elif self.payee_id == entity.uuid: - # return 2 - # else: - # return 0 - # - # def update_details(self, force_update=False): - # if not isinstance(self.details, dict): - # self.details = {} - # self.save() - # # detail = {'payer_name', 'payee_name', 'application_name', 'payer_avatar_url', 'payee_avatar_url', 'application_avatar_url'} - # is_updated = False - # if not self.details.get('payer_name'): - # if self.payer_type == TypeChoices.USER.value: - # payer_details: PublicUser = get_user_details(self.payer_id) - # self.details['payer_name'] = payer_details.first_name + payer_details.last_name - # self.details['payer_avatar_url'] = payer_details.avatar - # else: - # payer_details = get_application_details(self.payer_id) - # self.details['payer_name'] = payer_details.name - # #TODO: get avatar from details - # - # is_updated = True - # - # if not self.details.get('payee_name'): - # if self.payee_type == TypeChoices.USER.value: - # payee_details: PublicUser = get_user_details(self.payee_id) - # self.details['payee_name'] = payee_details.first_name + payee_details.last_name - # self.details['payee_avatar_url'] = payee_details.avatar - # else: - # payee_details = get_application_details(self.payee_id) - # self.details['payee_name'] = payee_details.name - # #TODO: get avatar from details - # - # is_updated = True - # - # if not self.details.get('application_name'): - # application_details = get_application_details(self.application_id) - # try: - # self.details['application_name'] = application_details.name - # # TODO: get avatar from details - # - # is_updated = True - # except Exception as e: - # pass - # - # if is_updated: - # self.save() - # - # - # def __str__(self): - # try: - # return f"{self.get_payer()} -> {self.get_payee()} ({self.uuid}): {self.amount} - {self.get_state_display()}" - # except: - # return str(self.uuid) + def category_deposit_to_payee_balance(self): + self.payee_wallet.balance = F('balance') + self.amount + self.payee_wallet.save(update_fields=['balance']) + + def pay(self, payer_id=None, payer_type=None): + if not self.payer_id and not (payer_id and payer_type): + raise APIException('payer identification error') + + if self.payer_id and payer_id and not (self.payer_id == payer_id and self.payer_type == payer_type): + raise APIException('payer identification error') + + if not self.state == StateChoices.CREATED: + raise APIException('this transaction is not ready to pay') + + if not self.payer_id: + self.payer_id = payer_id + self.payer_type = payer_type + + payer = self.get_payer() + + if payer.balance < self.amount: + raise APIException('not enough balance') + + with transaction.atomic(): + if self.delay: + self.change_state( + StateChoices.CREATED, + StateChoices.DELAYED, + error_message='this transaction is not ready to pay', + payer_id=payer_id, + payer_type=payer_type + ) + + else: + self.change_state( + StateChoices.CREATED, + StateChoices.SUCCESS, + error_message='this transaction is not ready to pay', + payer_id=payer_id, + payer_type=payer_type + ) + self.deposit_to_payee_balance() + + self.withdraw_from_payer_balance() + return self + + def receipt(self): + if not self.state == StateChoices.DELAYED: + raise APIException('this transaction is not delayed') + + with transaction.atomic(): + self.change_state( + StateChoices.DELAYED, + StateChoices.SUCCESS, + error_message='this transaction is not delayed' + ) + self.deposit_to_payee_balance() + return self + + def category_submit(self): + if not self.payer_wallet: + raise APIException('payer identification error') + + if not self.payee_wallet: + raise APIException('payee identification error') + + if not self.state == StateChoices.CREATED: + raise APIException('this transaction is not ready to pay') + + with transaction.atomic(): + self.category_withdraw_from_payer_balance() + self.change_state( + StateChoices.CREATED, + StateChoices.PENDING, + error_message=_('this transaction is not ready to pay') + ) + return self + + def category_verify(self): + if not self.state == StateChoices.PENDING: + raise APIException('this transaction is not pending') + + with transaction.atomic(): + self.category_deposit_to_payee_balance() + self.change_state( + StateChoices.PENDING, + StateChoices.SUCCESS, + error_message=_('this transaction is not pending') + ) + return self + + def category_get_role(self, entity): + if self.payer_wallet.owner_uuid == entity.uuid: + return 1 + elif self.payee_wallet.owner_uuid == entity.uuid: + return 2 + else: + return 0 + + def category_update_details(self, force_update=False): + if not isinstance(self.details, dict): + self.details = {} + self.save() + # detail = {'payer_name', 'payee_name', 'application_name', 'payer_avatar_url', 'payee_avatar_url', 'application_avatar_url'} + is_updated = False + if not self.details.get('payer_name'): + print('update payer') + if self.payer_wallet.owner_type == TypeChoices.USER: + payer_details: PublicUser = get_user_details(self.payer_wallet.owner_uuid) + self.details['payer_name'] = payer_details.first_name + payer_details.last_name + self.details['payer_avatar_url'] = payer_details.avatar + else: + payer_details = get_application_details(self.payer_id) + self.details['payer_name'] = payer_details.name + # TODO: get avatar from details + is_updated = True + print("payer_details:", payer_details) + print("is_updated:", is_updated) + + if not self.details.get('payee_name'): + print('update payee') + if self.payee_wallet.owner_type == TypeChoices.USER: + payee_details: PublicUser = get_user_details(self.payee_wallet.owner_uuid) + self.details['payee_name'] = payee_details.first_name + payee_details.last_name + self.details['payee_avatar_url'] = payee_details.avatar + else: + payee_details = get_application_details(self.payee_id) + self.details['payee_name'] = payee_details.name + # TODO: get avatar from details + + is_updated = True + print("payee_details:", payee_details) + print("is_updated:", is_updated) + + if not self.details.get('application_name'): + print('update application') + application_details = get_application_details(self.application_id) + print('application_details:', application_details) + try: + self.details['application_name'] = application_details.name + # TODO: get avatar from details + + is_updated = True + except Exception as e: + print("something went wrong") + print(e) + + if is_updated: + print('update details') + self.save() diff --git a/apps/wallet/urls.py b/apps/wallet/urls.py index c0dd409..654bb38 100644 --- a/apps/wallet/urls.py +++ b/apps/wallet/urls.py @@ -8,8 +8,13 @@ app_name = "wallet" user_urlpatterns = [ path('transactions/', user_views.TransactionListView.as_view(), name='user_transaction_list_page'), path('transactions/', user_views.TransactionDetailView.as_view(), name='user_transaction_detail_page'), - path('api/wallet/balance', user_views.MyWalletBalanceView.as_view(), name='user_wallet_balance_api'), - path('api/transactions/', user_views.TransactionList.as_view(), name='transaction_list_api'), + path('api/wallet/balance', user_views.CategoryMyWalletBalanceView.as_view(), name='user_wallet_balance_api'), + path('api/transactions/', user_views.CategoryTransactionListView.as_view(), name='transaction_list_api'), + + path('api/user//balance', user_views.CategoryMyWalletBalanceView.as_view(), name='user_wallet_balance_api'), + path('api/user//transactions/', user_views.CategoryTransactionListView.as_view(), name='transaction_list_api'), + + # path('api/transactions/', TransactionDetail.as_view(), name='transaction_detail_api'), # path('api/transactions//pay', TransactionPay.as_view(), name='transaction_pay_api'), # path('api/transactions//receipt', TransactionReceipt.as_view(), name='transaction_receipt_api'), @@ -25,24 +30,24 @@ user_urlpatterns = [ ] application_urlpatterns = [ - path('api/application/balance', application_views.BalanceAPIView.as_view(), name='application_wallet_balance_api'), + path('api/application/balance', application_views.CategoryBalanceAPIView.as_view(), name='application_wallet_balance_api'), - path('api/application/user_balance/', application_views.UserBalanceAPIView.as_view(), name='application_user_wallet_balance_api'), + path('api/application/user_balance/', application_views.CategoryUserBalanceAPIView.as_view(), name='application_user_wallet_balance_api'), - path('api/application/deposit/', application_views.DepositSubmitAPIView.as_view(), name='application_deposit_submit_api'), - path('api/application/deposit//verify', application_views.DepositVerifyAPIView.as_view(), name='application_deposit_verify_api'), + path('api/application/deposit/', application_views.CategoryDepositSubmitAPIView.as_view(), name='application_deposit_submit_api'), + path('api/application/deposit//verify', application_views.CategoryDepositVerifyAPIView.as_view(), name='application_deposit_verify_api'), - path('api/application/withdraw/', application_views.WithdrawSubmitAPIView.as_view(), name='application_withdraw_submit_api'), - path('api/application/withdraw//verify', application_views.WithdrawVerifyAPIView.as_view(), name='application_withdraw_verify_api'), + path('api/application/withdraw/', application_views.CategoryWithdrawSubmitAPIView.as_view(), name='application_withdraw_submit_api'), + path('api/application/withdraw//verify', application_views.CategoryWithdrawVerifyAPIView.as_view(), name='application_withdraw_verify_api'), - path('api/application/', application_views.TransactionListAPIView.as_view(), name='application_transaction_list_api'), - path('api/application//', application_views.TransactionDetailAPIView.as_view(), name='application_transaction_detail'), + path('api/application/', application_views.CategoryTransactionListAPIView.as_view(), name='application_transaction_list_api'), + path('api/application//', application_views.CategoryTransactionDetailAPIView.as_view(), name='application_transaction_detail'), path('api/application//balance', application_views.CategoryBalanceAPIView.as_view(), name='application_wallet_balance_api'), - path('api/application//user_balance/', application_views.CategoryUserBalanceAPIView.as_view(), name='application_user_wallet_balance_api'), + path('api/application//user//balance', application_views.CategoryUserBalanceAPIView.as_view(), name='application_user_wallet_balance_api'), path('api/application//deposit/', application_views.CategoryDepositSubmitAPIView.as_view(), name='application_deposit_submit_api'), path('api/application//deposit//verify', application_views.CategoryDepositVerifyAPIView.as_view(), name='application_deposit_verify_api'), diff --git a/apps/wallet/views/application.py b/apps/wallet/views/application.py index 61ca365..2e60387 100755 --- a/apps/wallet/views/application.py +++ b/apps/wallet/views/application.py @@ -183,7 +183,11 @@ class CategoryBalanceAPIView(generics.RetrieveAPIView): def get_object(self): category_uuid = self.kwargs.get('category_uuid') - category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None + application = get_application(self.request) wallet, created = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) @@ -200,7 +204,11 @@ class CategoryUserBalanceAPIView(generics.RetrieveAPIView): def get_object(self): category_uuid = self.kwargs.get('category_uuid') - category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None + user_uuid = self.kwargs.get('uuid') user, created = User.objects.get_or_create(uuid=user_uuid) application = get_application(self.request) @@ -216,6 +224,7 @@ class CategoryTransactionDetailAPIView(generics.RetrieveAPIView): required_scopes = ['wallet.application:get_transaction_detail'] def get_queryset(self): + # TODO: what about category application = get_application(self.request) return Transaction.objects.filter(Q(application=application) | Q(payer_wallet__owner_uuid=application.pk, @@ -232,6 +241,7 @@ class CategoryTransactionListAPIView(generics.ListAPIView): required_scopes = ['wallet.application:get_transaction_list'] def get_queryset(self): + # TODO: what about category? application = get_application(self.request) return Transaction.objects.filter(Q(application=application) | Q(payer_wallet__owner_uuid=application.pk, @@ -250,22 +260,27 @@ class CategoryDepositSubmitAPIView(generics.CreateAPIView): def get_queryset(self): category_uuid = self.kwargs.get('category_uuid') - category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None application = get_application(self.request) wallet, created = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) - return Transaction.objects.filter(application=application, - payer_wallet__owner_uuid=application.pk, - payer_wallet__owner_type=TypeChoices.APPLICATION).all() + return Transaction.objects.filter(application=application, payer_wallet=wallet).all() def perform_create(self, serializer): # TODO: get_or_create instead of create if uuid given # TODO: it is possible to merage create and submit in one step for improve performance application = get_application(self.request) - category = get_object_or_404(Category.objects.all(), uuid=self.kwargs.get('category_uuid')) - wallet = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) - instance = serializer.save(payer_wallet=wallet, - application=application) + category_uuid = self.kwargs.get('category_uuid') + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None + wallet = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, + category=category) + instance = serializer.save(payer_wallet=wallet, application=application) try: instance.submit() except Exception as e: @@ -281,7 +296,11 @@ class CategoryDepositVerifyAPIView(generics.RetrieveAPIView): def get_queryset(self): application = get_application(self.request) - category = get_object_or_404(Category.objects.all(), uuid=self.kwargs.get('category_uuid')) + category_uuid = self.kwargs.get('category_uuid') + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None wallet = Wallet.objects.get(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) return Transaction.objects.filter(application=application, payer_wallet=wallet).all() @@ -303,7 +322,10 @@ class CategoryWithdrawSubmitAPIView(generics.CreateAPIView): def get_queryset(self): category_uuid = self.kwargs.get('category_uuid') - category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None application = get_application(self.request) wallet, created = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) @@ -313,8 +335,13 @@ class CategoryWithdrawSubmitAPIView(generics.CreateAPIView): # TODO: get_or_create instead of create if uuid given # TODO: it is possible to merage create and submit in one step for improve performance application = get_application(self.request) - category = get_object_or_404(Category.objects.all(), uuid=self.kwargs.get('category_uuid')) - wallet = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) + category_uuid = self.kwargs.get('category_uuid') + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None + wallet = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, + category=category) instance = serializer.save(payee_wallet=wallet, application=application) instance.submit() @@ -328,10 +355,13 @@ class CategoryWithdrawVerifyAPIView(generics.RetrieveAPIView): def get_queryset(self): application = get_application(self.request) - category = get_object_or_404(Category.objects.all(), uuid=self.kwargs.get('category_uuid')) + category_uuid = self.kwargs.get('category_uuid') + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None wallet = Wallet.objects.get(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) - return Transaction.objects.filter(application=application, - payee_wallet=wallet).all() + return Transaction.objects.filter(application=application, payee_wallet=wallet).all() def retrieve(self, request, *args, **kwargs): instance = self.get_object() diff --git a/apps/wallet/views/user.py b/apps/wallet/views/user.py index 838f894..a235529 100755 --- a/apps/wallet/views/user.py +++ b/apps/wallet/views/user.py @@ -8,11 +8,12 @@ from django_filters.rest_framework import DjangoFilterBackend from oauth2_provider.contrib.rest_framework import TokenHasScope, IsAuthenticatedOrTokenHasScope from rest_framework import generics, permissions +from rest_framework.generics import get_object_or_404 from rest_framework.permissions import AllowAny from rest_framework.response import Response from apps.gooyal_oauth2.rest_framework import IsAuthenticatedOrTokenMatchesOASRequirements -from apps.wallet.models import Transaction +from apps.wallet.models import Transaction, Category, Wallet from apps.wallet.serializers import UserTransactionSerializer, DepositSerializer, WithdrawSerializer, \ MyWalletSerializer from ..constans import StateChoices, TypeChoices @@ -222,3 +223,60 @@ class TransactionDetailView(UpdateView): result = transaction.receipt() messages.error(self.request, _('success.')) return super().form_valid(form) + + + +class CategoryMyWalletBalanceView(generics.RetrieveAPIView): + ''' + API for getting authenticated user balance. + ''' + permission_classes = [IsAuthenticatedOrTokenHasScope] + serializer_class = MyWalletSerializer + required_scopes = ['wallet.wallet:get_balance'] + + def get_object(self): + user = self.request.user + category_uuid = self.kwargs.get('category_uuid') + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None + + wallet, created = Wallet.objects.get_or_create(owner_uuid=user.uuid, owner_type=TypeChoices.USER, + category=category) + return wallet + + +# this is application create invoice view +class CategoryTransactionListView(generics.ListAPIView): + ''' + GET: API for getting list of transactions for authenticated user + POST: API for creating transaction for transferring funds from authenticated user to application owner. (deprecated) + args: + - user: authenticated user + + ''' + permission_classes = [IsAuthenticatedOrTokenMatchesOASRequirements] + serializer_class = UserTransactionSerializer + required_alternate_scopes = { + "GET": [['wallet.user:transaction_list']], + # "POST": [['wallet.invoice:create']], + } + + filter_backends = (DjangoFilterBackend,) + filterset_class = UserTransactionFilter + + def get_queryset(self): + user = self.request.user + category_uuid = self.kwargs.get('category_uuid') + if category_uuid: + category = get_object_or_404(Category.objects.all(), uuid=category_uuid) + else: + category = None + + wallet, created = Wallet.objects.get_or_create(owner_uuid=user.uuid, owner_type=TypeChoices.USER, + category=category) + + return Transaction.objects.filter(Q(payee_wallet=wallet) | + Q(payer_wallet=wallet)).all() + From 9a5edac1ad141ef9da885254fa01608e4738b6c1 Mon Sep 17 00:00:00 2001 From: hgh Date: Sun, 31 Aug 2025 16:48:00 +0330 Subject: [PATCH 03/16] bugfix --- apps/wallet/views/application.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/wallet/views/application.py b/apps/wallet/views/application.py index 2e60387..0922115 100755 --- a/apps/wallet/views/application.py +++ b/apps/wallet/views/application.py @@ -278,7 +278,7 @@ class CategoryDepositSubmitAPIView(generics.CreateAPIView): category = get_object_or_404(Category.objects.all(), uuid=category_uuid) else: category = None - wallet = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, + wallet, _ = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) instance = serializer.save(payer_wallet=wallet, application=application) try: From 183947f0e8c4940d4eb3093091c5865dd689e778 Mon Sep 17 00:00:00 2001 From: hgh Date: Tue, 2 Sep 2025 12:45:50 +0330 Subject: [PATCH 04/16] make payee_id nullable --- .../0009_alter_transaction_payee_id.py | 18 ++++++++++++++++++ apps/wallet/models.py | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 apps/wallet/migrations/0009_alter_transaction_payee_id.py diff --git a/apps/wallet/migrations/0009_alter_transaction_payee_id.py b/apps/wallet/migrations/0009_alter_transaction_payee_id.py new file mode 100644 index 0000000..ca5d5e5 --- /dev/null +++ b/apps/wallet/migrations/0009_alter_transaction_payee_id.py @@ -0,0 +1,18 @@ +# Generated by Django 5.1.7 on 2025-09-02 09:14 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('wallet', '0008_alter_transaction_options_and_more'), + ] + + operations = [ + migrations.AlterField( + model_name='transaction', + name='payee_id', + field=models.UUIDField(null=True), + ), + ] diff --git a/apps/wallet/models.py b/apps/wallet/models.py index 9596b62..49d1b49 100755 --- a/apps/wallet/models.py +++ b/apps/wallet/models.py @@ -89,7 +89,7 @@ class Transaction(BaseModel): delay = models.PositiveIntegerField(default=0, blank=True) # number of days for delayed payments payer_id = models.UUIDField(blank=True, null=True) payer_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) - payee_id = models.UUIDField() + payee_id = models.UUIDField(null=True) payee_type = models.IntegerField(choices=TypeChoices.choices, blank=True, null=True) state = models.IntegerField(choices=StateChoices.choices, default=StateChoices.CREATED) application = models.ForeignKey(oauth2_settings.APPLICATION_MODEL, on_delete=models.PROTECT, From 1092884e1bdf502db8c486a1c860d32744fee795 Mon Sep 17 00:00:00 2001 From: hgh Date: Tue, 2 Sep 2025 13:54:24 +0330 Subject: [PATCH 05/16] make uuid required false to auto generate it --- apps/wallet/serializers.py | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/wallet/serializers.py b/apps/wallet/serializers.py index e8c63fb..3ba11f4 100755 --- a/apps/wallet/serializers.py +++ b/apps/wallet/serializers.py @@ -173,7 +173,6 @@ class ApplicationTransactionSerializer(BaseTransactionSerializer): pass class ApplicationDepositSerializer(serializers.ModelSerializer): - uuid = serializers.UUIDField(required=True) # TODO: details as fields class Meta: From b775e05039a462161aa80cc5df4f812c111432d1 Mon Sep 17 00:00:00 2001 From: hgh Date: Wed, 3 Sep 2025 09:58:47 +0330 Subject: [PATCH 06/16] creating both payer and payee wallets on deposit request --- apps/wallet/views/application.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/apps/wallet/views/application.py b/apps/wallet/views/application.py index 0922115..ff7c7d2 100755 --- a/apps/wallet/views/application.py +++ b/apps/wallet/views/application.py @@ -278,11 +278,15 @@ class CategoryDepositSubmitAPIView(generics.CreateAPIView): category = get_object_or_404(Category.objects.all(), uuid=category_uuid) else: category = None - wallet, _ = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, + payee_id = serializer.validated_data.pop('payee_id') + payee_type = serializer.validated_data.pop('payee_type') + payer_wallet, _ = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) - instance = serializer.save(payer_wallet=wallet, application=application) + payee_wallet, _ = Wallet.objects.get_or_create(owner_uuid=payee_id, owner_type=payee_type, category=category) + + instance = serializer.save(payer_wallet=payer_wallet, application=application, payee_wallet=payee_wallet) try: - instance.submit() + instance.category_submit() except Exception as e: print(e) APIException('Failed to submit deposit') @@ -308,7 +312,7 @@ class CategoryDepositVerifyAPIView(generics.RetrieveAPIView): def retrieve(self, request, *args, **kwargs): instance = self.get_object() if instance.state == StateChoices.PENDING: - instance.verify() + instance.category_verify() serializer = self.get_serializer(instance) return Response(serializer.data) From 8f28b2c9815168f01cd89d49fb0c8f45cec1e135 Mon Sep 17 00:00:00 2001 From: hgh Date: Wed, 3 Sep 2025 09:59:27 +0330 Subject: [PATCH 07/16] payee_id, payee_type, amount is required onf deposit request --- apps/wallet/serializers.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/wallet/serializers.py b/apps/wallet/serializers.py index 3ba11f4..e2aff55 100755 --- a/apps/wallet/serializers.py +++ b/apps/wallet/serializers.py @@ -173,6 +173,9 @@ class ApplicationTransactionSerializer(BaseTransactionSerializer): pass class ApplicationDepositSerializer(serializers.ModelSerializer): + payee_id = serializers.UUIDField(required=True) + payee_type = serializers.IntegerField(required=True) + amount = serializers.IntegerField(required=True) # TODO: details as fields class Meta: From 3274a5d0e6fca4f43bf26f3a402fee75c2bfdc82 Mon Sep 17 00:00:00 2001 From: hgh Date: Wed, 3 Sep 2025 10:22:48 +0330 Subject: [PATCH 08/16] wallet application api flows tests --- apps/wallet/tests.py | 3 - apps/wallet/tests/__init__.py | 0 apps/wallet/tests/application.py | 115 +++++++++++++++++++++++++++++++ 3 files changed, 115 insertions(+), 3 deletions(-) delete mode 100755 apps/wallet/tests.py create mode 100644 apps/wallet/tests/__init__.py create mode 100755 apps/wallet/tests/application.py diff --git a/apps/wallet/tests.py b/apps/wallet/tests.py deleted file mode 100755 index 7ce503c..0000000 --- a/apps/wallet/tests.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.test import TestCase - -# Create your tests here. diff --git a/apps/wallet/tests/__init__.py b/apps/wallet/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/wallet/tests/application.py b/apps/wallet/tests/application.py new file mode 100755 index 0000000..b6b8d85 --- /dev/null +++ b/apps/wallet/tests/application.py @@ -0,0 +1,115 @@ +import uuid +from datetime import timedelta + +from django.urls import reverse +from django.utils import timezone +from oauth2_provider.models import get_access_token_model, get_application_model +from rest_framework.test import APITestCase + +from apps.users.models import User +from apps.wallet.constans import TypeChoices +from apps.wallet.models import Wallet + +AccessToken = get_access_token_model() +Application = get_application_model() + + +class ApplicationApiFlowsTests(APITestCase): + access_token = 'u4naVsdKCbKNOhnElPyXcrwSnqqFbm' + payer_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470051') + payee_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470052') + application_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470053') + client_id = '4INGOCMoulE0fNY1SQlTbPtsWqqxGj2DdqjADq6u' + + def setUp(self): + self.application_user, _ = User.objects.get_or_create(pk=self.application_uuid) + self.application_wallet, _ = Wallet.objects.get_or_create(owner_uuid=self.application_uuid, owner_type=TypeChoices.APPLICATION, balance=300) + self.payee_wallet, _ = Wallet.objects.get_or_create(owner_uuid=self.payee_uuid, owner_type=1) + expire_datetime = timezone.now() + timedelta(seconds=3600) + expire_datetime.isoformat() + + scopes = [ + 'wallet.application.deposit:verify', + 'wallet.application:get_balance', + 'wallet.application.deposit:submit', + 'wallet.deposit:submit', + 'wallet.wallet:get_balance', + 'wallet.application:get_user_balance', + ] + + self.access_token, _created = AccessToken.objects.update_or_create( + token=self.access_token, + defaults={ + "user": self.application_user, + "client_id": self.client_id, + # "client_owner": owner, + "application_id": self.application_uuid, + "scope": ' '.join(scopes), + "expires": expire_datetime.isoformat(), + }, + ) + + self.application, _created = Application.objects.get_or_create( + client_id=self.client_id, + uuid=self.application_uuid, + ) + + def tearDown(self): + super().tearDown() + + def _create_authorization_header(self, token): + return "Bearer {0}".format(token) + + def test_authentication_allow(self): + auth = self._create_authorization_header(self.access_token.token) + response = self.client.get(reverse('wallet:user_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + + # def test_authentication_disallow(self): + # auth = self._create_authorization_header('fake_token') + # response = self.client.get(reverse('wallet:user_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + # self.assertEqual(response.status_code, 401) + + def test_deposit_flow_success(self): + auth = self._create_authorization_header(self.access_token.token) + + # Checking wallets initials values(application balance = 300 and payee balance = zero) + response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + params = { + 'uuid': self.payee_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 0) + + # Deposit process + data = { + 'amount': 100, + 'payee_id': self.payee_uuid, + 'payee_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_deposit_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 201) + json_response = response.json() + + params = { + 'uuid': json_response['uuid'] + } + response = self.client.get(reverse('wallet:application_deposit_verify_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()['state'], 5) + + # Desired results + response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 200) + + params = { + 'uuid': self.payee_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 100) + From ee5b7feb4a1044f617b3d83325084d171addf158 Mon Sep 17 00:00:00 2001 From: hgh Date: Wed, 3 Sep 2025 10:34:21 +0330 Subject: [PATCH 09/16] fix: wallet application api flows tests --- apps/wallet/tests/application.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/wallet/tests/application.py b/apps/wallet/tests/application.py index b6b8d85..89a2c52 100755 --- a/apps/wallet/tests/application.py +++ b/apps/wallet/tests/application.py @@ -24,7 +24,7 @@ class ApplicationApiFlowsTests(APITestCase): def setUp(self): self.application_user, _ = User.objects.get_or_create(pk=self.application_uuid) self.application_wallet, _ = Wallet.objects.get_or_create(owner_uuid=self.application_uuid, owner_type=TypeChoices.APPLICATION, balance=300) - self.payee_wallet, _ = Wallet.objects.get_or_create(owner_uuid=self.payee_uuid, owner_type=1) + self.payee_wallet, _ = Wallet.objects.get_or_create(owner_uuid=self.payee_uuid, owner_type=TypeChoices.USER) expire_datetime = timezone.now() + timedelta(seconds=3600) expire_datetime.isoformat() From dc3da1f9d47a332c5b5d434ffb4037865f9f278e Mon Sep 17 00:00:00 2001 From: hgh Date: Wed, 3 Sep 2025 14:17:09 +0330 Subject: [PATCH 10/16] wallet withdraw flows test --- apps/wallet/serializers.py | 4 +- apps/wallet/tests/application.py | 71 +++++++++++++++++++++++++++++--- apps/wallet/views/application.py | 20 +++++---- 3 files changed, 82 insertions(+), 13 deletions(-) diff --git a/apps/wallet/serializers.py b/apps/wallet/serializers.py index e2aff55..ecdff32 100755 --- a/apps/wallet/serializers.py +++ b/apps/wallet/serializers.py @@ -198,7 +198,9 @@ class ApplicationDepositSerializer(serializers.ModelSerializer): class ApplicationWithdrawSerializer(serializers.ModelSerializer): - uuid = serializers.UUIDField(required=True) + payer_id = serializers.UUIDField(required=True) + payer_type = serializers.IntegerField(required=True) + amount = serializers.IntegerField(required=True) class Meta: model = Transaction diff --git a/apps/wallet/tests/application.py b/apps/wallet/tests/application.py index 89a2c52..592a337 100755 --- a/apps/wallet/tests/application.py +++ b/apps/wallet/tests/application.py @@ -15,7 +15,8 @@ Application = get_application_model() class ApplicationApiFlowsTests(APITestCase): - access_token = 'u4naVsdKCbKNOhnElPyXcrwSnqqFbm' + application_access_token = 'u4naVsdKCbKNOhnElPyXcrwSnqqFbm' + payer_access_token = 'u4naVsdKCbKNOhnElPyXcrwSnqqFbm2' payer_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470051') payee_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470052') application_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470053') @@ -23,8 +24,10 @@ class ApplicationApiFlowsTests(APITestCase): def setUp(self): self.application_user, _ = User.objects.get_or_create(pk=self.application_uuid) + self.payer_user, _ = User.objects.get_or_create(pk=self.payer_uuid) self.application_wallet, _ = Wallet.objects.get_or_create(owner_uuid=self.application_uuid, owner_type=TypeChoices.APPLICATION, balance=300) self.payee_wallet, _ = Wallet.objects.get_or_create(owner_uuid=self.payee_uuid, owner_type=TypeChoices.USER) + self.payer_wallet, _ = Wallet.objects.get_or_create(owner_uuid=self.payer_uuid, owner_type=TypeChoices.USER, balance=300) expire_datetime = timezone.now() + timedelta(seconds=3600) expire_datetime.isoformat() @@ -35,10 +38,13 @@ class ApplicationApiFlowsTests(APITestCase): 'wallet.deposit:submit', 'wallet.wallet:get_balance', 'wallet.application:get_user_balance', + + 'wallet.application.withdraw:submit', + 'wallet.application.withdraw:verify', ] - self.access_token, _created = AccessToken.objects.update_or_create( - token=self.access_token, + self.application_access_token, _created = AccessToken.objects.update_or_create( + token=self.application_access_token, defaults={ "user": self.application_user, "client_id": self.client_id, @@ -49,6 +55,18 @@ class ApplicationApiFlowsTests(APITestCase): }, ) + self.payer_access_token, _created = AccessToken.objects.update_or_create( + token=self.payer_access_token, + defaults={ + "user": self.payer_user, + "client_id": self.client_id, + # "client_owner": owner, + "application_id": self.application_uuid, + "scope": ' '.join(scopes), + "expires": expire_datetime.isoformat(), + }, + ) + self.application, _created = Application.objects.get_or_create( client_id=self.client_id, uuid=self.application_uuid, @@ -61,7 +79,7 @@ class ApplicationApiFlowsTests(APITestCase): return "Bearer {0}".format(token) def test_authentication_allow(self): - auth = self._create_authorization_header(self.access_token.token) + auth = self._create_authorization_header(self.application_access_token.token) response = self.client.get(reverse('wallet:user_wallet_balance_api'), HTTP_AUTHORIZATION=auth) self.assertContains(response, 'balance') @@ -71,7 +89,7 @@ class ApplicationApiFlowsTests(APITestCase): # self.assertEqual(response.status_code, 401) def test_deposit_flow_success(self): - auth = self._create_authorization_header(self.access_token.token) + auth = self._create_authorization_header(self.application_access_token.token) # Checking wallets initials values(application balance = 300 and payee balance = zero) response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) @@ -113,3 +131,46 @@ class ApplicationApiFlowsTests(APITestCase): self.assertContains(response, 'balance') self.assertEqual(response.json()['balance'], 100) + def test_withdraw_flow_success(self): + auth = self._create_authorization_header(self.payer_access_token.token) + + # Checking wallets initials values(application balance = 300 and payee balance = zero) + response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + params = { + 'uuid': self.payer_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + + # Deposit process + data = { + 'amount': 100, + 'payer_id': self.payer_uuid, + 'payer_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_withdraw_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 201) + json_response = response.json() + + params = { + 'uuid': json_response['uuid'] + } + response = self.client.get(reverse('wallet:application_withdraw_verify_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()['state'], 5) + + # Desired results + response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 400) + + params = { + 'uuid': self.payer_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 200) + diff --git a/apps/wallet/views/application.py b/apps/wallet/views/application.py index ff7c7d2..9501d84 100755 --- a/apps/wallet/views/application.py +++ b/apps/wallet/views/application.py @@ -306,8 +306,7 @@ class CategoryDepositVerifyAPIView(generics.RetrieveAPIView): else: category = None wallet = Wallet.objects.get(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) - return Transaction.objects.filter(application=application, - payer_wallet=wallet).all() + return Transaction.objects.filter(application=application, payer_wallet=wallet).all() def retrieve(self, request, *args, **kwargs): instance = self.get_object() @@ -344,11 +343,18 @@ class CategoryWithdrawSubmitAPIView(generics.CreateAPIView): category = get_object_or_404(Category.objects.all(), uuid=category_uuid) else: category = None - wallet = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, - category=category) - instance = serializer.save(payee_wallet=wallet, application=application) + payer_id = serializer.validated_data.pop('payer_id') + payer_type = serializer.validated_data.pop('payer_type') + payee_wallet, _ = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, + category=category) + payer_wallet, _ = Wallet.objects.get_or_create(owner_uuid=payer_id, owner_type=TypeChoices.USER, category=category) + instance = serializer.save(payer_wallet=payer_wallet, application=application, payee_wallet=payee_wallet) - instance.submit() + try: + instance.category_submit() + except Exception as e: + print(e) + APIException('Failed to submit withdraw') class CategoryWithdrawVerifyAPIView(generics.RetrieveAPIView): @@ -370,7 +376,7 @@ class CategoryWithdrawVerifyAPIView(generics.RetrieveAPIView): def retrieve(self, request, *args, **kwargs): instance = self.get_object() if instance.state == StateChoices.PENDING: - instance.verify() + instance.category_verify() serializer = self.get_serializer(instance) return Response(serializer.data) From 400a0c710e796c86bbba7e79872bd2bc59d8f06e Mon Sep 17 00:00:00 2001 From: hgh Date: Wed, 3 Sep 2025 15:44:04 +0330 Subject: [PATCH 11/16] wallet withdraw and deposit different scenario flows test --- apps/wallet/tests/application.py | 99 ++++++++++++++++++++++++++++++++ apps/wallet/views/application.py | 15 +---- 2 files changed, 102 insertions(+), 12 deletions(-) diff --git a/apps/wallet/tests/application.py b/apps/wallet/tests/application.py index 592a337..f0c5edc 100755 --- a/apps/wallet/tests/application.py +++ b/apps/wallet/tests/application.py @@ -131,6 +131,55 @@ class ApplicationApiFlowsTests(APITestCase): self.assertContains(response, 'balance') self.assertEqual(response.json()['balance'], 100) + def test_deposit_flow_insufficient_balance(self): + auth = self._create_authorization_header(self.application_access_token.token) + + # Checking wallets initials values(application balance = 300 and payee balance = zero) + response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + params = { + 'uuid': self.payee_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 0) + + # Deposit process + data = { + 'amount': 500, + 'payee_id': self.payee_uuid, + 'payee_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_deposit_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 500) + + def test_deposit_flow_prevent_double_spending(self): + auth = self._create_authorization_header(self.application_access_token.token) + + # Checking wallets initials values(application balance = 300 and payee balance = zero) + response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + params = { + 'uuid': self.payee_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 0) + + # Deposit process + data = { + 'amount': 200, + 'payee_id': self.payee_uuid, + 'payee_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_deposit_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 201) + + response = self.client.post(reverse('wallet:application_deposit_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 500) + def test_withdraw_flow_success(self): auth = self._create_authorization_header(self.payer_access_token.token) @@ -174,3 +223,53 @@ class ApplicationApiFlowsTests(APITestCase): self.assertContains(response, 'balance') self.assertEqual(response.json()['balance'], 200) + def test_withdraw_flow_insufficient_balance(self): + auth = self._create_authorization_header(self.payer_access_token.token) + + # Checking wallets initials values(application balance = 300 and payee balance = zero) + response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + params = { + 'uuid': self.payer_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + + # Deposit process + data = { + 'amount': 500, + 'payer_id': self.payer_uuid, + 'payer_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_withdraw_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 500) + + def test_withdraw_flow_prevent_double_spending(self): + auth = self._create_authorization_header(self.payer_access_token.token) + + # Checking wallets initials values(application balance = 300 and payee balance = zero) + response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + params = { + 'uuid': self.payer_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + + # Deposit process + data = { + 'amount': 200, + 'payer_id': self.payer_uuid, + 'payer_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_withdraw_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 201) + + response = self.client.post(reverse('wallet:application_withdraw_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 500) + + diff --git a/apps/wallet/views/application.py b/apps/wallet/views/application.py index 9501d84..c580fed 100755 --- a/apps/wallet/views/application.py +++ b/apps/wallet/views/application.py @@ -285,11 +285,7 @@ class CategoryDepositSubmitAPIView(generics.CreateAPIView): payee_wallet, _ = Wallet.objects.get_or_create(owner_uuid=payee_id, owner_type=payee_type, category=category) instance = serializer.save(payer_wallet=payer_wallet, application=application, payee_wallet=payee_wallet) - try: - instance.category_submit() - except Exception as e: - print(e) - APIException('Failed to submit deposit') + instance.category_submit() class CategoryDepositVerifyAPIView(generics.RetrieveAPIView): @@ -347,14 +343,9 @@ class CategoryWithdrawSubmitAPIView(generics.CreateAPIView): payer_type = serializer.validated_data.pop('payer_type') payee_wallet, _ = Wallet.objects.get_or_create(owner_uuid=application.uuid, owner_type=TypeChoices.APPLICATION, category=category) - payer_wallet, _ = Wallet.objects.get_or_create(owner_uuid=payer_id, owner_type=TypeChoices.USER, category=category) + payer_wallet, _ = Wallet.objects.get_or_create(owner_uuid=payer_id, owner_type=payer_type, category=category) instance = serializer.save(payer_wallet=payer_wallet, application=application, payee_wallet=payee_wallet) - - try: - instance.category_submit() - except Exception as e: - print(e) - APIException('Failed to submit withdraw') + instance.category_submit() class CategoryWithdrawVerifyAPIView(generics.RetrieveAPIView): From 6c12f0b0165b9f5f1db4ac1f2eb69c76babe2eb9 Mon Sep 17 00:00:00 2001 From: hgh Date: Wed, 3 Sep 2025 16:58:05 +0330 Subject: [PATCH 12/16] wallet withdraw and deposit different scenario flows test --- apps/wallet/serializers.py | 5 +- apps/wallet/tests/application.py | 96 +++++++++++++++++++++++++++----- 2 files changed, 85 insertions(+), 16 deletions(-) diff --git a/apps/wallet/serializers.py b/apps/wallet/serializers.py index ecdff32..b019269 100755 --- a/apps/wallet/serializers.py +++ b/apps/wallet/serializers.py @@ -1,4 +1,5 @@ from django.db import IntegrityError +from django.core.validators import MinValueValidator from django.db.transaction import atomic from rest_framework import serializers from rest_framework.exceptions import APIException @@ -175,7 +176,7 @@ class ApplicationTransactionSerializer(BaseTransactionSerializer): class ApplicationDepositSerializer(serializers.ModelSerializer): payee_id = serializers.UUIDField(required=True) payee_type = serializers.IntegerField(required=True) - amount = serializers.IntegerField(required=True) + amount = serializers.IntegerField(required=True, validators=[MinValueValidator(1)]) # TODO: details as fields class Meta: @@ -200,7 +201,7 @@ class ApplicationDepositSerializer(serializers.ModelSerializer): class ApplicationWithdrawSerializer(serializers.ModelSerializer): payer_id = serializers.UUIDField(required=True) payer_type = serializers.IntegerField(required=True) - amount = serializers.IntegerField(required=True) + amount = serializers.IntegerField(required=True, validators=[MinValueValidator(1)]) class Meta: model = Transaction diff --git a/apps/wallet/tests/application.py b/apps/wallet/tests/application.py index f0c5edc..7b8b425 100755 --- a/apps/wallet/tests/application.py +++ b/apps/wallet/tests/application.py @@ -22,6 +22,18 @@ class ApplicationApiFlowsTests(APITestCase): application_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470053') client_id = '4INGOCMoulE0fNY1SQlTbPtsWqqxGj2DdqjADq6u' + scopes = [ + 'wallet.application.deposit:verify', + 'wallet.application:get_balance', + 'wallet.application.deposit:submit', + 'wallet.deposit:submit', + 'wallet.wallet:get_balance', + 'wallet.application:get_user_balance', + + 'wallet.application.withdraw:submit', + 'wallet.application.withdraw:verify', + ] + def setUp(self): self.application_user, _ = User.objects.get_or_create(pk=self.application_uuid) self.payer_user, _ = User.objects.get_or_create(pk=self.payer_uuid) @@ -31,18 +43,6 @@ class ApplicationApiFlowsTests(APITestCase): expire_datetime = timezone.now() + timedelta(seconds=3600) expire_datetime.isoformat() - scopes = [ - 'wallet.application.deposit:verify', - 'wallet.application:get_balance', - 'wallet.application.deposit:submit', - 'wallet.deposit:submit', - 'wallet.wallet:get_balance', - 'wallet.application:get_user_balance', - - 'wallet.application.withdraw:submit', - 'wallet.application.withdraw:verify', - ] - self.application_access_token, _created = AccessToken.objects.update_or_create( token=self.application_access_token, defaults={ @@ -50,7 +50,7 @@ class ApplicationApiFlowsTests(APITestCase): "client_id": self.client_id, # "client_owner": owner, "application_id": self.application_uuid, - "scope": ' '.join(scopes), + "scope": ' '.join(self.scopes), "expires": expire_datetime.isoformat(), }, ) @@ -62,7 +62,7 @@ class ApplicationApiFlowsTests(APITestCase): "client_id": self.client_id, # "client_owner": owner, "application_id": self.application_uuid, - "scope": ' '.join(scopes), + "scope": ' '.join(self.scopes), "expires": expire_datetime.isoformat(), }, ) @@ -83,6 +83,24 @@ class ApplicationApiFlowsTests(APITestCase): response = self.client.get(reverse('wallet:user_wallet_balance_api'), HTTP_AUTHORIZATION=auth) self.assertContains(response, 'balance') + + def test_authentication_expired_token(self): + access_token = 'u4naVsdKCbKNOhnElPyXcrwSnqqFbm23' + expired_access_token, _created = AccessToken.objects.update_or_create( + token=access_token, + defaults={ + "user": self.application_user, + "client_id": self.client_id, + # "client_owner": owner, + "application_id": self.application_uuid, + "scope": ' '.join(self.scopes), + "expires": (timezone.now() - timedelta(seconds=3600)).isoformat(), + }, + ) + auth = self._create_authorization_header(expired_access_token.token) + response = self.client.get(reverse('wallet:user_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 401) + # def test_authentication_disallow(self): # auth = self._create_authorization_header('fake_token') # response = self.client.get(reverse('wallet:user_wallet_balance_api'), HTTP_AUTHORIZATION=auth) @@ -154,6 +172,30 @@ class ApplicationApiFlowsTests(APITestCase): response = self.client.post(reverse('wallet:application_deposit_submit_api'), data=data, HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 500) + def test_deposit_flow_zero_amount(self): + auth = self._create_authorization_header(self.application_access_token.token) + + # Deposit process + data = { + 'amount': 0, + 'payee_id': self.payee_uuid, + 'payee_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_deposit_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 400) + + def test_deposit_flow_negative_amount(self): + auth = self._create_authorization_header(self.application_access_token.token) + + # Deposit process + data = { + 'amount': -100, + 'payee_id': self.payee_uuid, + 'payee_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_deposit_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 400) + def test_deposit_flow_prevent_double_spending(self): auth = self._create_authorization_header(self.application_access_token.token) @@ -246,6 +288,32 @@ class ApplicationApiFlowsTests(APITestCase): response = self.client.post(reverse('wallet:application_withdraw_submit_api'), data=data, HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 500) + def test_withdraw_flow_zero_amount(self): + auth = self._create_authorization_header(self.payer_access_token.token) + + # Deposit process + data = { + 'amount': 0, + 'payer_id': self.payer_uuid, + 'payer_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_withdraw_submit_api'), data=data, + HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 400) + + def test_withdraw_flow_negative_amount(self): + auth = self._create_authorization_header(self.payer_access_token.token) + + # Deposit process + data = { + 'amount': -500, + 'payer_id': self.payer_uuid, + 'payer_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_withdraw_submit_api'), data=data, + HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 400) + def test_withdraw_flow_prevent_double_spending(self): auth = self._create_authorization_header(self.payer_access_token.token) From bcc07f75d40d4941e089eed23e0be239a1233473 Mon Sep 17 00:00:00 2001 From: hgh Date: Sat, 6 Sep 2025 13:59:07 +0330 Subject: [PATCH 13/16] wallet deposit by category uuid and check its and other wallets desired balance --- apps/wallet/tests/application.py | 72 +++++++++++++++++++++++++++++--- 1 file changed, 67 insertions(+), 5 deletions(-) diff --git a/apps/wallet/tests/application.py b/apps/wallet/tests/application.py index 7b8b425..72296b9 100755 --- a/apps/wallet/tests/application.py +++ b/apps/wallet/tests/application.py @@ -9,18 +9,22 @@ from rest_framework.test import APITestCase from apps.users.models import User from apps.wallet.constans import TypeChoices from apps.wallet.models import Wallet +from apps.wallet.models import Category AccessToken = get_access_token_model() Application = get_application_model() class ApplicationApiFlowsTests(APITestCase): - application_access_token = 'u4naVsdKCbKNOhnElPyXcrwSnqqFbm' - payer_access_token = 'u4naVsdKCbKNOhnElPyXcrwSnqqFbm2' + client_id = '4INGOCMoulE0fNY1SQlTbPtsWqqxGj2DdqjADq6u' + application_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470053') + application_access_token = '14naVsdKCbKNOhnElPyXcrwSnqqFbm' + payer_access_token = '24naVsdKCbKNOhnElPyXcrwSnqqFbm' payer_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470051') payee_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470052') - application_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470053') - client_id = '4INGOCMoulE0fNY1SQlTbPtsWqqxGj2DdqjADq6u' + wallet_category1_uuid = uuid.UUID('114e8b86-8f4a-44d9-b29d-badceb470051') + wallet_category2_uuid = uuid.UUID('214e8b86-8f4a-44d9-b29d-badceb470051') + # application, _ = Application.objects.get_or_create(client_id=client_id, uuid=application_uuid) scopes = [ 'wallet.application.deposit:verify', @@ -71,6 +75,14 @@ class ApplicationApiFlowsTests(APITestCase): client_id=self.client_id, uuid=self.application_uuid, ) + self.wallet_category1, _ = Category.objects.get_or_create(application=self.application, uuid=self.wallet_category1_uuid) + self.wallet_category2, _ = Category.objects.get_or_create(application=self.application, uuid=self.wallet_category2_uuid) + self.application_wallet1, _ = Wallet.objects.get_or_create(owner_uuid=self.application_uuid, owner_type=TypeChoices.APPLICATION, balance=300, category=self.wallet_category1) + self.application_wallet2, _ = Wallet.objects.get_or_create(owner_uuid=self.application_uuid, owner_type=TypeChoices.APPLICATION, balance=300, category=self.wallet_category2) + self.payee_wallet1, _ = Wallet.objects.get_or_create(owner_uuid=self.payee_uuid, owner_type=TypeChoices.USER, category=self.wallet_category1) + self.payee_wallet2, _ = Wallet.objects.get_or_create(owner_uuid=self.payee_uuid, owner_type=TypeChoices.USER, category=self.wallet_category2) + self.payer_wallet1, _ = Wallet.objects.get_or_create(owner_uuid=self.payer_uuid, owner_type=TypeChoices.USER, balance=300, category=self.wallet_category1) + self.payer_wallet2, _ = Wallet.objects.get_or_create(owner_uuid=self.payer_uuid, owner_type=TypeChoices.USER, balance=300, category=self.wallet_category2) def tearDown(self): super().tearDown() @@ -85,7 +97,7 @@ class ApplicationApiFlowsTests(APITestCase): def test_authentication_expired_token(self): - access_token = 'u4naVsdKCbKNOhnElPyXcrwSnqqFbm23' + access_token = '34naVsdKCbKNOhnElPyXcrwSnqqFbm' expired_access_token, _created = AccessToken.objects.update_or_create( token=access_token, defaults={ @@ -149,6 +161,56 @@ class ApplicationApiFlowsTests(APITestCase): self.assertContains(response, 'balance') self.assertEqual(response.json()['balance'], 100) + def test_deposit_flow_category_success(self): + auth = self._create_authorization_header(self.application_access_token.token) + + # Checking wallets initials values(application balance = 300 and payee balance = zero) + kwargs_category_uuid = { + 'category_uuid': self.wallet_category1_uuid + } + response = self.client.get(reverse('wallet:application_wallet_balance_api', kwargs=kwargs_category_uuid), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + kwargs_category_uuid_payee_uuid = { + 'category_uuid': self.wallet_category1_uuid, + 'uuid': self.payee_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=kwargs_category_uuid_payee_uuid), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 0) + + # Deposit process + data = { + 'amount': 100, + 'payee_id': self.payee_uuid, + 'payee_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_deposit_submit_api', kwargs=kwargs_category_uuid), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 201) + json_response = response.json() + + kwargs_category_uuid_transaction_uuid = { + 'category_uuid': self.wallet_category1_uuid, + 'uuid': json_response['uuid'], + } + response = self.client.get(reverse('wallet:application_deposit_verify_api', kwargs=kwargs_category_uuid_transaction_uuid), HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()['state'], 5) + + # Desired results + response = self.client.get(reverse('wallet:application_wallet_balance_api', kwargs=kwargs_category_uuid), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 200) + + kwargs_category_uuid_payee_uuid = { + 'category_uuid': self.wallet_category2_uuid, + 'uuid': self.payee_uuid, + } + + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=kwargs_category_uuid_payee_uuid), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 0) + def test_deposit_flow_insufficient_balance(self): auth = self._create_authorization_header(self.application_access_token.token) From e4093ee4de447daf371628edacc76b5014c63661 Mon Sep 17 00:00:00 2001 From: hgh Date: Sat, 6 Sep 2025 14:12:09 +0330 Subject: [PATCH 14/16] wallet withdraw by category uuid and check its and other wallets desired balance --- apps/wallet/tests/application.py | 54 ++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/apps/wallet/tests/application.py b/apps/wallet/tests/application.py index 72296b9..1c58092 100755 --- a/apps/wallet/tests/application.py +++ b/apps/wallet/tests/application.py @@ -327,6 +327,60 @@ class ApplicationApiFlowsTests(APITestCase): self.assertContains(response, 'balance') self.assertEqual(response.json()['balance'], 200) + def test_withdraw_flow_category_success(self): + auth = self._create_authorization_header(self.payer_access_token.token) + + # Checking wallets initials values(application balance = 300 and payee balance = zero) + kwargs_category_uuid = { + 'category_uuid': self.wallet_category1_uuid + } + response = self.client.get(reverse('wallet:application_wallet_balance_api', kwargs=kwargs_category_uuid), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + kwargs_category_uuid_payer_uuid = { + 'category_uuid': self.wallet_category1_uuid, + 'uuid': self.payer_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=kwargs_category_uuid_payer_uuid), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + + # Deposit process + data = { + 'amount': 100, + 'payer_id': self.payer_uuid, + 'payer_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_withdraw_submit_api', kwargs=kwargs_category_uuid), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 201) + json_response = response.json() + + kwargs_category_uuid_transaction_uuid = { + 'category_uuid': self.wallet_category1_uuid, + 'uuid': json_response['uuid'], + } + response = self.client.get(reverse('wallet:application_withdraw_verify_api', kwargs=kwargs_category_uuid_transaction_uuid), HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()['state'], 5) + + # Desired results + response = self.client.get(reverse('wallet:application_wallet_balance_api', kwargs=kwargs_category_uuid), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 400) + + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=kwargs_category_uuid_payer_uuid), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 200) + + kwargs_category_uuid_payer_uuid = { + 'category_uuid': self.wallet_category2_uuid, + 'uuid': self.payer_uuid, + } + + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=kwargs_category_uuid_payer_uuid), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + def test_withdraw_flow_insufficient_balance(self): auth = self._create_authorization_header(self.payer_access_token.token) From 9de126d5859d779f1a5ec5d0c0d0b860238efce0 Mon Sep 17 00:00:00 2001 From: hgh Date: Sat, 6 Sep 2025 16:51:33 +0330 Subject: [PATCH 15/16] skip insufficient balance for allowed negative balance applications test --- apps/wallet/models.py | 4 +-- apps/wallet/tests/application.py | 49 ++++++++++++++++---------------- 2 files changed, 27 insertions(+), 26 deletions(-) diff --git a/apps/wallet/models.py b/apps/wallet/models.py index 49d1b49..4308c43 100755 --- a/apps/wallet/models.py +++ b/apps/wallet/models.py @@ -312,8 +312,8 @@ class Transaction(BaseModel): ######################## category def category_withdraw_from_payer_balance(self): - payer_is_allowed_negative_balance = self.payer_type == TypeChoices.APPLICATION.value and str( - self.payer_id) in settings.ALLOWED_NEGATIVE_BALANCE_APPLICATIONS + payer_is_allowed_negative_balance = self.payer_wallet.owner_type == TypeChoices.APPLICATION.value and str( + self.payer_wallet.owner_uuid) in settings.ALLOWED_NEGATIVE_BALANCE_APPLICATIONS if self.amount > self.payer_wallet.balance and not payer_is_allowed_negative_balance: raise APIException('not enough balance') self.payer_wallet.balance = F('balance') - self.amount diff --git a/apps/wallet/tests/application.py b/apps/wallet/tests/application.py index 1c58092..00e969d 100755 --- a/apps/wallet/tests/application.py +++ b/apps/wallet/tests/application.py @@ -4,7 +4,7 @@ from datetime import timedelta from django.urls import reverse from django.utils import timezone from oauth2_provider.models import get_access_token_model, get_application_model -from rest_framework.test import APITestCase +from rest_framework.test import APITestCase, override_settings from apps.users.models import User from apps.wallet.constans import TypeChoices @@ -234,6 +234,30 @@ class ApplicationApiFlowsTests(APITestCase): response = self.client.post(reverse('wallet:application_deposit_submit_api'), data=data, HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 500) + @override_settings(ALLOWED_NEGATIVE_BALANCE_APPLICATIONS=['b14e8b86-8f4a-44d9-b29d-badceb470053']) + def test_deposit_flow_skip_insufficient_balance_for_allowed_negative_balance_applications(self): + auth = self._create_authorization_header(self.application_access_token.token) + + # Checking wallets initials values(application balance = 300 and payee balance = zero) + response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 300) + params = { + 'uuid': self.payee_uuid, + } + response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) + self.assertContains(response, 'balance') + self.assertEqual(response.json()['balance'], 0) + + # Deposit process + data = { + 'amount': 500, + 'payee_id': self.payee_uuid, + 'payee_type': TypeChoices.USER + } + response = self.client.post(reverse('wallet:application_deposit_submit_api'), data=data, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, 201) + def test_deposit_flow_zero_amount(self): auth = self._create_authorization_header(self.application_access_token.token) @@ -381,29 +405,6 @@ class ApplicationApiFlowsTests(APITestCase): self.assertContains(response, 'balance') self.assertEqual(response.json()['balance'], 300) - def test_withdraw_flow_insufficient_balance(self): - auth = self._create_authorization_header(self.payer_access_token.token) - - # Checking wallets initials values(application balance = 300 and payee balance = zero) - response = self.client.get(reverse('wallet:application_wallet_balance_api'), HTTP_AUTHORIZATION=auth) - self.assertContains(response, 'balance') - self.assertEqual(response.json()['balance'], 300) - params = { - 'uuid': self.payer_uuid, - } - response = self.client.get(reverse('wallet:application_user_wallet_balance_api', kwargs=params), HTTP_AUTHORIZATION=auth) - self.assertContains(response, 'balance') - self.assertEqual(response.json()['balance'], 300) - - # Deposit process - data = { - 'amount': 500, - 'payer_id': self.payer_uuid, - 'payer_type': TypeChoices.USER - } - response = self.client.post(reverse('wallet:application_withdraw_submit_api'), data=data, HTTP_AUTHORIZATION=auth) - self.assertEqual(response.status_code, 500) - def test_withdraw_flow_zero_amount(self): auth = self._create_authorization_header(self.payer_access_token.token) From a491adbd81173d440bce79a874b313780d846b06 Mon Sep 17 00:00:00 2001 From: Sayyid Hamid Mahdavi Date: Thu, 18 Sep 2025 11:11:51 +0330 Subject: [PATCH 16/16] wallet with category --- apps/wallet/models.py | 175 +--------------------------------- apps/wallet/tests/__init__.py | 1 + 2 files changed, 4 insertions(+), 172 deletions(-) diff --git a/apps/wallet/models.py b/apps/wallet/models.py index 4308c43..2044c45 100755 --- a/apps/wallet/models.py +++ b/apps/wallet/models.py @@ -1,14 +1,9 @@ -import datetime -import uuid - -from django.contrib.auth import get_user_model from django.core.validators import MinValueValidator from django.db import models from django.db import transaction from django.db.models import F from django.utils.translation import gettext_lazy as _ -from oauth2_provider.models import get_application_model -from rest_framework.exceptions import APIException, ValidationError +from rest_framework.exceptions import APIException, NotAcceptable from django.conf import settings from oauth2_provider import settings as oauth2_settings @@ -79,9 +74,10 @@ class TransactionQuerySet(models.QuerySet): payer = transaction.get_payer() payee = transaction.get_payee() payer_wallet, created = Wallet.objects.get_or_create(owner_uuid=transaction.payer_id, owner_type=transaction.payer_type, defaults={'balance': payer.balance}) - payee_wallet, created = Wallet.objects.get_or_create(owner_uuid=transaction.payee_id, owner_type=transaction.payee_type, defaults={'balance': payer.balance}) + payee_wallet, created = Wallet.objects.get_or_create(owner_uuid=transaction.payee_id, owner_type=transaction.payee_type, defaults={'balance': payee.balance}) transaction.payer_wallet = payer_wallet transaction.payee_wallet = payee_wallet + transaction.save() class Transaction(BaseModel): @@ -118,20 +114,6 @@ class Transaction(BaseModel): # unique_together = ('application', 'detail_id',) - def withdraw_from_payer_balance(self): - payer = self.get_payer() - payer_is_allowed_negative_balance = self.payer_type == TypeChoices.APPLICATION.value and str( - self.payer_id) in settings.ALLOWED_NEGATIVE_BALANCE_APPLICATIONS - if self.amount > payer.balance and not payer_is_allowed_negative_balance: - raise APIException('not enough balance') - payer.balance = F('balance') - self.amount - payer.save(update_fields=['balance']) - - def deposit_to_payee_balance(self): - payee = self.get_payee() - payee.balance = F('balance') + self.amount - payee.save(update_fields=['balance']) - def get_pay_entity(self, entity_id, entity_type): if entity_type == TypeChoices.APPLICATION: entity: Application = Application.objects.get(pk=entity_id) @@ -159,157 +141,6 @@ class Transaction(BaseModel): else: raise APIException(error_message) - def pay(self, payer_id=None, payer_type=None): - if not self.payer_id and not (payer_id and payer_type): - raise APIException('payer identification error') - - if self.payer_id and payer_id and not (self.payer_id == payer_id and self.payer_type == payer_type): - raise APIException('payer identification error') - - if not self.state == StateChoices.CREATED: - raise APIException('this transaction is not ready to pay') - - if not self.payer_id: - self.payer_id = payer_id - self.payer_type = payer_type - - payer = self.get_payer() - - if payer.balance < self.amount: - raise APIException('not enough balance') - - with transaction.atomic(): - if self.delay: - self.change_state( - StateChoices.CREATED, - StateChoices.DELAYED, - error_message='this transaction is not ready to pay', - payer_id=payer_id, - payer_type=payer_type - ) - - else: - self.change_state( - StateChoices.CREATED, - StateChoices.SUCCESS, - error_message='this transaction is not ready to pay', - payer_id=payer_id, - payer_type=payer_type - ) - self.deposit_to_payee_balance() - - self.withdraw_from_payer_balance() - return self - - def receipt(self): - if not self.state == StateChoices.DELAYED: - raise APIException('this transaction is not delayed') - - with transaction.atomic(): - self.change_state( - StateChoices.DELAYED, - StateChoices.SUCCESS, - error_message='this transaction is not delayed' - ) - self.deposit_to_payee_balance() - return self - - def submit(self): - payer = self.get_payer() - payee = self.get_payee() - - if not payer: - raise APIException('payer identification error') - - if not payee: - raise APIException('payee identification error') - - if not self.state == StateChoices.CREATED: - raise APIException('this transaction is not ready to pay') - - with transaction.atomic(): - self.withdraw_from_payer_balance() - self.change_state( - StateChoices.CREATED, - StateChoices.PENDING, - error_message='this transaction is not ready to pay' - ) - return self - - def verify(self): - if not self.state == StateChoices.PENDING: - raise APIException('this transaction is not pending') - - with transaction.atomic(): - self.deposit_to_payee_balance() - self.change_state( - StateChoices.PENDING, - StateChoices.SUCCESS, - error_message='this transaction is not pending' - ) - return self - - def get_role(self, entity): - - if self.payer_id == entity.uuid: - return 1 - elif self.payee_id == entity.uuid: - return 2 - else: - return 0 - - def update_details(self, force_update=False): - if not isinstance(self.details, dict): - self.details = {} - self.save() - # detail = {'payer_name', 'payee_name', 'application_name', 'payer_avatar_url', 'payee_avatar_url', 'application_avatar_url'} - is_updated = False - if not self.details.get('payer_name'): - print('update payer') - if self.payer_type == TypeChoices.USER.value: - payer_details: PublicUser = get_user_details(self.payer_id) - self.details['payer_name'] = payer_details.first_name + payer_details.last_name - self.details['payer_avatar_url'] = payer_details.avatar - else: - payer_details = get_application_details(self.payer_id) - self.details['payer_name'] = payer_details.name - # TODO: get avatar from details - is_updated = True - print("payer_details:", payer_details) - print("is_updated:", is_updated) - - if not self.details.get('payee_name'): - print('update payee') - if self.payee_type == TypeChoices.USER.value: - payee_details: PublicUser = get_user_details(self.payee_id) - self.details['payee_name'] = payee_details.first_name + payee_details.last_name - self.details['payee_avatar_url'] = payee_details.avatar - else: - payee_details = get_application_details(self.payee_id) - self.details['payee_name'] = payee_details.name - # TODO: get avatar from details - - is_updated = True - print("payee_details:", payee_details) - print("is_updated:", is_updated) - - if not self.details.get('application_name'): - print('update application') - application_details = get_application_details(self.application_id) - print('application_details:', application_details) - try: - self.details['application_name'] = application_details.name - # TODO: get avatar from details - - is_updated = True - except Exception as e: - print("something went wrong") - print(e) - - if is_updated: - print('update details') - self.save() - ######################## category def category_withdraw_from_payer_balance(self): payer_is_allowed_negative_balance = self.payer_wallet.owner_type == TypeChoices.APPLICATION.value and str( diff --git a/apps/wallet/tests/__init__.py b/apps/wallet/tests/__init__.py index e69de29..f211395 100644 --- a/apps/wallet/tests/__init__.py +++ b/apps/wallet/tests/__init__.py @@ -0,0 +1 @@ +from .application import * \ No newline at end of file