From 03021ff3338ba1e5d9bd24bed3b49249fea8144f Mon Sep 17 00:00:00 2001 From: Seyed Alireza Hashemi Date: Tue, 5 Nov 2024 21:39:14 +0330 Subject: [PATCH] refactor: do some refactors about transferring funds to user --- apps/attributes/models/base.py | 15 ++-- .../attributes/models/intrinsic_attributes.py | 6 +- apps/attributes/urls.py | 6 +- apps/attributes/views/currency.py | 13 ---- apps/currency/views.py | 31 +++----- apps/fsm/utils.py | 4 +- proxies/bank_service/main.py | 77 ------------------- proxies/bank_service/utils.py | 18 +++++ 8 files changed, 41 insertions(+), 129 deletions(-) delete mode 100644 apps/attributes/views/currency.py delete mode 100644 proxies/bank_service/main.py create mode 100644 proxies/bank_service/utils.py diff --git a/apps/attributes/models/base.py b/apps/attributes/models/base.py index baa7227c..5240796b 100644 --- a/apps/attributes/models/base.py +++ b/apps/attributes/models/base.py @@ -1,10 +1,8 @@ from django.db import models from polymorphic.models import PolymorphicModel -from abc import abstractmethod from apps.attributes.models.utils import SumDict -from proxies.bank_service.bank import request_transfer -from proxies.website_service.main import get_website +from proxies.bank_service.utils import transfer_funds_to_user class Attribute(PolymorphicModel): @@ -62,15 +60,12 @@ def give_reward(self, *args, **kwargs): if total_reward.is_zero(): return - # Get website + # Process the transfer request = kwargs.get('request') website_name = request.headers.get('Website') - website = get_website(website_name) - - # Process the transfer - request_transfer( - sender_id=website.get('uuid'), - receiver_id=str(request.user.id), + transfer_funds_to_user( + website_name=website_name, + user_uuid=str(request.user.id), funds=total_reward, ) diff --git a/apps/attributes/models/intrinsic_attributes.py b/apps/attributes/models/intrinsic_attributes.py index b9c6df46..63fec85b 100644 --- a/apps/attributes/models/intrinsic_attributes.py +++ b/apps/attributes/models/intrinsic_attributes.py @@ -9,7 +9,7 @@ class Condition(IntrinsicAttribute): def is_true(self, *args, **kwargs): from apps.fsm.utils import AnswerSheetFacade - + player = kwargs.get('player') user = kwargs.get('user') value = self.value @@ -19,11 +19,11 @@ def is_true(self, *args, **kwargs): if not player: total_condition_result = False else: - expected_correct_choices_in_last_answer_count = value.get( + expected_count = value.get( 'expected_correct_choices_in_last_answer_count') facade = AnswerSheetFacade(player.answer_sheet) total_condition_result = facade.check_expected_correct_choices_in_last_answer_count( - expected_correct_choices_in_last_answer_count) + expected_count) if 'expected_choices' in value: if not player: diff --git a/apps/attributes/urls.py b/apps/attributes/urls.py index 63f496d0..a26125d4 100644 --- a/apps/attributes/urls.py +++ b/apps/attributes/urls.py @@ -1,12 +1,8 @@ from rest_framework.routers import DefaultRouter -from django.urls import path -from apps.attributes.views.currency import get_currencies router = DefaultRouter() -urlpatterns = [ - path('currencies/', get_currencies), -] +urlpatterns = [] urlpatterns += router.urls diff --git a/apps/attributes/views/currency.py b/apps/attributes/views/currency.py deleted file mode 100644 index f09f3c3c..00000000 --- a/apps/attributes/views/currency.py +++ /dev/null @@ -1,13 +0,0 @@ -from rest_framework import status -from rest_framework.response import Response -from rest_framework.decorators import api_view - -from proxies.bank_service.main import BankProxy - - -@api_view(["GET"]) -def get_currencies(request): - website = request.headers.get('Website', None) - bank_proxy = BankProxy(website) - currencies = bank_proxy.get_currencies() - return Response(currencies, status=status.HTTP_200_OK) diff --git a/apps/currency/views.py b/apps/currency/views.py index 57fa02b0..363ee0aa 100644 --- a/apps/currency/views.py +++ b/apps/currency/views.py @@ -1,12 +1,11 @@ -from django.conf import settings from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework import status from django.db import transaction from apps.fsm.models import Object -from proxies.bank_service.bank import get_user_balances, request_transfer -from proxies.website_service.main import get_website +from proxies.bank_service.bank import get_user_balances +from proxies.bank_service.utils import transfer_funds_to_user from .models import Spend from django.core.exceptions import ObjectDoesNotExist @@ -70,27 +69,21 @@ def spend_on_object(request): status=status.HTTP_400_BAD_REQUEST ) - # Get website - website_name = request.headers.get('Website') - website = get_website(website_name) - - # Process the transfer - transfer_response = request_transfer( - sender_id=user_uuid, - receiver_id=website.get('uuid'), - funds=funds - ) - - withdraw_transaction = transfer_response.get( - 'transactions').get('withdraw') - - # If transfer successful, create spend record with transaction.atomic(): + # Spending money + website_name = request.headers.get('Website') + response = transfer_funds_to_user( + website_name=website_name, + user_uuid=user_uuid, + funds=funds, + ) + + # If transfer successful, create spend record spend = Spend.objects.create( user=user_uuid, object=obj.id, fund=funds, - transaction_id=withdraw_transaction.get('id') + transaction_id=response.get('withdraw_transaction_id') ) return Response({ diff --git a/apps/fsm/utils.py b/apps/fsm/utils.py index 8270d541..3960e18e 100644 --- a/apps/fsm/utils.py +++ b/apps/fsm/utils.py @@ -235,7 +235,7 @@ def check_expected_choices_in_last_answer(self, expected_choice_ids: list[int]): except: return False - def check_expected_correct_choices_in_last_answer_count(self, expected_correct_choices_in_last_answer_count: int): + def check_expected_correct_choices_in_last_answer_count(self, expected_count: int): try: # Get the last multi-choice answer in a single query from apps.fsm.models.response import MultiChoiceAnswer @@ -252,6 +252,6 @@ def check_expected_correct_choices_in_last_answer_count(self, expected_correct_c if choice.is_correct ) - return correct_choices_count == expected_correct_choices_in_last_answer_count + return correct_choices_count == expected_count except: return False diff --git a/proxies/bank_service/main.py b/proxies/bank_service/main.py deleted file mode 100644 index 78e5511f..00000000 --- a/proxies/bank_service/main.py +++ /dev/null @@ -1,77 +0,0 @@ -from typing import Dict -from django.conf import settings -from utils.singleton_class import Singleton -import requests -import json - -import requests - - -class Currency: - name: str - display_name: str - logo: str - description: str - - -MoneyType = Dict[str, int] - - -class BankProxy(Singleton): - url = settings.BANK_URL + "graphql" - - def create_session_party(self): - data = { - "query": "mutation { createParty(name: \""+f"{self.website}"+"\") { name coins { name description } } }" - } - self._post(data=data) - - def __init__(self, website: str) -> None: - self.website = website - self.create_session_party() - - def create_currency(self, name, display_name, logo, description) -> None: - data = { - "query": "mutation { createCoin(partyName: \"" + f"{self.website}"+"\", name: \""+f"{name}"+"\", description: \""+f"{description}"+"\") { name coins { name description } } }" - } - self._post(data=data) - - def get_currencies(self) -> list[Currency]: - data = { - "query": "query { getParty(name: \""+f"{self.website}"+"\") { name coins { name description } } }" - } - return self._post(data=data) - - def get_balance(self, user): - data = { - 'query': "query { checkBalance(userUuid: \""+f"{user}"+"\", partyName: \""+f"{self.website}"+'\") { coinName amount } }"}' - } - return self._post(data=data) - - def deposit(self, user, money: MoneyType): - data = { - 'query': "mutation { createTransaction(transactionInput: { userUuid: \""+f"{user}"+"\", date: \"2024-08-19\", party: { name: \""+f"{self.website}"+"\" }, coins: [{"+f"{money}" + "}], type: PLUS }) }" - } - return self._post(data=data) - - def balance_inquiry(self, balance: MoneyType) -> bool: - # todo: Ehsan - pass - - def withdraw(self, user, money: MoneyType): - data = { - 'query': "mutation { createTransaction(transactionInput: { userUuid: \"" + f"{user}" + "\", date: \"2024-08-19\", party: { name: \"" + f"{self.website}" + "\" }, coins: [{" + f"{money}" + "}], type: MINUS }) }" - - } - return self._post(data=data) - - def transfer(self, sender, receiver, money: MoneyType): - pass - - def _post(self, data): - headers = { - "Content-Type": "application/json" - } - response = requests.post( - self.url, headers=headers, data=json.dumps(data)) - return response.json() diff --git a/proxies/bank_service/utils.py b/proxies/bank_service/utils.py new file mode 100644 index 00000000..dfab599d --- /dev/null +++ b/proxies/bank_service/utils.py @@ -0,0 +1,18 @@ +from proxies.bank_service.bank import request_transfer +from proxies.website_service.main import get_website +from typing import TypedDict + + +class TransferResponse(TypedDict): + withdraw_transaction_id: str + deposit_transaction_id: str + + +def transfer_funds_to_user(website_name, user_uuid, funds) -> TransferResponse: + website = get_website(website_name) + + return request_transfer( + sender_id=website.get('uuid'), + receiver_id=str(user_uuid), + funds=funds, + )