get user from accounts

This commit is contained in:
Sayyid Hamid Mahdavi 2026-07-07 16:42:34 +03:30
parent 3320ff93e3
commit e7db91d1da
7 changed files with 76 additions and 48 deletions

View file

@ -65,7 +65,7 @@ class ApplicationApiFlowsTests(APITestCase):
application_uuid = uuid.UUID(application_uuid_hex)
application_access_token = '14naVsdKCbKNOhnElPyXcrwSnqqFbm'
user_access_token = '24naVsdKCbKNOhnElPyXcrwSnqqFbm'
user_1_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470051')
user_1_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb47005f')
user_2_uuid = uuid.UUID('b14e8b86-8f4a-44d9-b29d-badceb470052')
first_ad_view_reward_label = 'first_ad_view_reward_label'
referral_reward_label = 'referral_reward_label'
@ -650,8 +650,12 @@ class ApplicationApiFlowsTests(APITestCase):
'referral': self.user_2_uuid
}
}
url = reverse('promotions-application:plan-promote',
kwargs={"pk": self.referral_reward_plan.uuid, "user_uuid": self.user_1_uuid})
url = reverse('promotions-application:application-user-plan-promote',
kwargs={
"pk": str(self.referral_reward_plan.uuid),
"user_uuid": str(self.user_1_uuid)
}
)
response = self.client.post(url, event_create_data, HTTP_AUTHORIZATION=auth, format='json')
print(response.json())
self.referral_reward_plan.refresh_from_db()
@ -691,22 +695,18 @@ class ApplicationApiFlowsTests(APITestCase):
}
}
url_promote = reverse('promotions-application:plan-promote',
kwargs={"pk": self.first_ad_view_reward_plan.uuid, "user_uuid": self.user_1_uuid})
url_promote = reverse('promotions-application:application-user-plan-promote',
kwargs={"pk": self.first_ad_view_reward_plan.uuid, "user_uuid": '1f9c72e4-3cc3-420d-928b-b0a3d65a4612'})
response = self.client.post(url_promote, event_create_data, HTTP_AUTHORIZATION=auth, format='json')
print(response.json())
# print(response.json())
self.first_ad_view_reward_plan.refresh_from_db()
self.assertEqual(self.first_ad_view_reward_plan.balance, 10000 - 800)
# url_get_promotion = reverse('promotions-application:plan-list',
# kwargs={"pk": self.first_ad_view_reward_plan.uuid, "user_uuid": self.user_1_uuid})
url_get_promotion = reverse('promotions-application:plan-list',
kwargs={"user_uuid": self.user_1_uuid})
url_get_promotion = reverse('promotions-application:application-user-plan-detail',
kwargs={"pk": self.first_ad_view_reward_plan.uuid, "user_uuid": '1f9c72e4-3cc3-420d-928b-b0a3d65a4612'})
response = self.client.get(url_get_promotion, HTTP_AUTHORIZATION=auth, format='json')
print(response.json())

View file

@ -54,8 +54,8 @@ class ApplicationRouter(DefaultRouter):
router = DefaultRouter()
router.register('<user_uuid>/plan', views_application.ApplicationUserPlanViewSet, basename='plan')
router.register('plan', views_application.ApplicationPlanViewSet, basename='plan')
router.register('plan', views_application.ApplicationUserPlanViewSet, basename='application-user-plan')
# router.register('plan', views_application.ApplicationPlanViewSet, basename='application-plan')
router.register('event', views_application.ApplicationEventViewSet, basename='event')
urlpatterns = router.urls

View file

@ -9,6 +9,7 @@ from rest_framework.viewsets import GenericViewSet
from apps.gooyal_oauth2.rest_framework import IsAuthenticatedOrTokenMatchesOASRequirements, TokenMatchesViewSetActions
from apps.gooyal_oauth2.utils import get_application
from utils.clients.accounts_client import get_user_info
from utils.exceptions import UnprocessableEntity
from .models import Plan, Promotion, EventSaver
from .serializers import PlanSerializer, PromotionSerializer, EventSerializer, PromoteSerializer, UserPlanSerializer
@ -35,7 +36,15 @@ class ApplicationUserPlanViewSet(
application = get_application(self.request)
# TODO: get user from accounts
user_uuid = self.kwargs.get('user_uuid')
if not self.request.user:
user_uuid = self.kwargs.get('user_uuid')
user = User.objects.filter(uuid=user_uuid).first()
if not user:
user_info = get_user_info(user_uuid)
if user_info:
user, created = User.objects.update_or_create(uuid=user_uuid)
self.request.user = user
# return Promotion.objects.filter(application=application)
return Plan.objects.all()
@ -65,7 +74,7 @@ class ApplicationUserPlanViewSet(
# TODO
# try:
event = event_saver.save_event(user=user_uuid, application=application, **serializer.validated_data)
event = event_saver.save_event(user=self.request.user.pk, application=application, **serializer.validated_data)
# except Exception as e:
# raise exceptions.ValidationError(str(e))

View file

@ -382,6 +382,8 @@ CELERY_TASK_TIME_LIMIT = 30 * 60
CELERY_BROKER_URL = REDIS_BASE_URL
CELERY_RESULT_BACKEND = REDIS_BASE_URL
ACCOUNTS_BASE_PUBLIC_URL = config('ACCOUNTS_BASE_PUBLIC_URL', default=None, cast=str)
WALLET_BASE_PUBLIC_URL = config('WALLET_BASE_PUBLIC_URL', default=None, cast=str)
WALLET_RIAL = config('WALLET_RIAL', cast=str)
WALLET_REWARD = config('WALLET_REWARD', cast=str)

View file

@ -29,7 +29,7 @@ urlpatterns = [
path('', include('utils.urls')),
path('oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')),
path('promotions/', include('apps.promotions.urls_user', namespace='promotions')),
path('api/v2/promotions/application/', include('apps.promotions.urls_application', namespace='promotions-application')),
path('api/v2/promotions/application/<user_uuid>/', include('apps.promotions.urls_application', namespace='promotions-application')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

View file

@ -3,17 +3,18 @@ import time
import requests
from django.conf import settings
from django.core.cache import cache
from httpx import Request
from gooyal_accounts_client import AuthenticatedClient
from gooyal_accounts_client.models import PublicUser, Application
from gooyal_accounts_client.api.users import users_api_users_retrieve
from gooyal_accounts_client.api.oauth2 import oauth2_apis_applications_retrieve
from gooyal_accounts_client.models import Account
from gooyal_accounts_client.api.users import (users_api_users_details_retrieve)
from utils.clients.gooyal_accounts_client import AuthenticatedClient
from utils.clients.gooyal_accounts_client.models import PublicUser, Application
from utils.clients.gooyal_accounts_client.api.users import users_api_users_retrieve
from utils.clients.gooyal_accounts_client.api.oauth2 import oauth2_apis_applications_retrieve
from utils.clients.gooyal_accounts_client.models import Account
from utils.clients.gooyal_accounts_client.api.users import (users_api_users_details_retrieve)
def login_as_client_credentials():
access_token = cache.get('wallet_access_token')
access_token = cache.get('promotions_access_token')
# expires_in = self.auth_data.get('expires_in')
# created_at = self.auth_data.get('created_at')
#
@ -27,39 +28,50 @@ def login_as_client_credentials():
data = {
"grant_type": 'client_credentials',
"scope": settings.SCOPES,
"scope": settings.OAUTH2_SCOPES,
}
auth = (settings.CLIENT_ID, settings.CLIENT_SECRET)
auth = (settings.OAUTH2_CLIENT_ID, settings.OAUTH2_CLIENT_SECRET)
response = requests.post(f'{settings.BASE_OAUTH2_PROVIDER_PUBLIC_URL}/token/',
response = requests.post(f'{settings.OAUTH2_PROVIDER_PUBLIC_URL}/token/',
data=data,
auth=auth)
auth_data = response.json()
print(auth_data)
if 'access_token' in auth_data:
auth_data['created_at'] = time.time()
cache.set('wallet_access_token', auth_data, timeout=auth_data.get('expires_in')-5)
cache.set('promotions_access_token', auth_data, timeout=auth_data.get('expires_in') - 5)
return auth_data
def log_request(request: Request):
print(request.headers['authorization'])
print(
f"Request event hook: {request.method} {request.url} {request.method} {request.headers} - Waiting for response")
def log_response(response):
request = response.request
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")
def get_client():
access_token = login_as_client_credentials()['access_token']
# TODO: url
client = AuthenticatedClient(base_url="http://accounts:8000", token=access_token)
client = AuthenticatedClient(base_url=settings.ACCOUNTS_BASE_PUBLIC_URL, token=access_token,
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}}
)
return client
def get_user_details(uuid):
def get_user_info(uuid):
client = get_client()
data: PublicUser = users_api_users_retrieve.sync(client=client, uuid=uuid)
print(data)
# or if you need more info (e.g. status_code)
# response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client)
response: PublicUser = users_api_users_retrieve.sync(client=client, uuid=uuid)
print(response)
return response
return data
def get_user_detailed_info(uuid):
client = get_client()
@ -68,6 +80,7 @@ def get_user_detailed_info(uuid):
return response
def get_application_details(uuid):
client = get_client()
data: Application = oauth2_apis_applications_retrieve.sync(client=client, id=uuid)

View file

@ -6,7 +6,8 @@ from django.core.cache import cache
from httpx import Request
from utils.clients.gooyal_wallet_client import AuthenticatedClient
from utils.clients.gooyal_wallet_client.models import Transaction, Account, ApplicationDeposit, ApplicationWithdraw, PaginatedAccountList
from utils.clients.gooyal_wallet_client.models import Transaction, Account, ApplicationDeposit, ApplicationWithdraw, \
PaginatedAccountList
from utils.clients.gooyal_wallet_client.api.wallet import (wallet_api_application_deposit_create,
wallet_api_application_deposit_verify_retrieve,
wallet_api_application_withdraw_create,
@ -14,10 +15,8 @@ from utils.clients.gooyal_wallet_client.api.wallet import (wallet_api_applicatio
wallet_api_application_user_wallets_list)
def login_as_client_credentials():
access_token = cache.get('settlement_access_token')
access_token = cache.get('promotions_access_token')
# expires_in = self.auth_data.get('expires_in')
# created_at = self.auth_data.get('created_at')
#
@ -38,12 +37,13 @@ def login_as_client_credentials():
response = requests.post(f'{settings.OAUTH2_PROVIDER_PUBLIC_URL}/token/',
data=data,
auth=auth)
print(response.content)
auth_data = response.json()
if 'access_token' in auth_data:
auth_data['created_at'] = time.time()
cache.set('settlement_access_token', auth_data, timeout=auth_data.get('expires_in') - 5)
cache.set('promotions_access_token', auth_data, timeout=auth_data.get('expires_in') - 5)
return auth_data
@ -75,15 +75,16 @@ def deposit_to_user_wallet_submit(payer_wallet, data):
deposit_data = Tmp()
client = get_client()
response: ApplicationDeposit = wallet_api_application_deposit_create.sync(payer_wallet=payer_wallet,
client=client,
body=deposit_data)
client=client,
body=deposit_data)
print(response)
return response
def deposit_to_user_wallet_verify(payer_wallet, uuid):
client = get_client()
response: ApplicationDeposit = wallet_api_application_deposit_verify_retrieve.sync(payer_wallet=payer_wallet, uuid=uuid, client=client)
response: ApplicationDeposit = wallet_api_application_deposit_verify_retrieve.sync(payer_wallet=payer_wallet,
uuid=uuid, client=client)
print(response)
return response
@ -95,14 +96,16 @@ def withdraw_from_user_wallet_submit(payee_wallet, data):
withdraw_data = Tmp()
client = get_client()
response: ApplicationWithdraw = wallet_api_application_withdraw_create.sync(payee_wallet=payee_wallet, client=client, body=withdraw_data)
response: ApplicationWithdraw = wallet_api_application_withdraw_create.sync(payee_wallet=payee_wallet,
client=client, body=withdraw_data)
print(response)
return response
def withdraw_from_user_wallet_verify(payee_wallet, uuid):
client = get_client()
response: ApplicationWithdraw = wallet_api_application_withdraw_verify_retrieve.sync(payee_wallet=payee_wallet, uuid=uuid, client=client)
response: ApplicationWithdraw = wallet_api_application_withdraw_verify_retrieve.sync(payee_wallet=payee_wallet,
uuid=uuid, client=client)
print(response)
return response
@ -110,7 +113,8 @@ def withdraw_from_user_wallet_verify(payee_wallet, uuid):
def get_user_wallets(owner, wallets):
client = get_client()
# by pass several wallet query params: [','.join([str(i) for i in wallets])]
response: PaginatedAccountList = wallet_api_application_user_wallets_list.sync(owner=owner, wallet=[','.join([str(i) for i in wallets])], client=client)
response: PaginatedAccountList = wallet_api_application_user_wallets_list.sync(owner=owner, wallet=[
','.join([str(i) for i in wallets])], client=client)
print(response)
balances = dict(map(lambda result: (str(result.wallet), result.balance), response.results))
return balances