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() +