McDuck/users/views.py
2024-08-29 14:21:58 +05:00

167 lines
7.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from .models import User, DailyReward, DailyRewardsList, Balance, Levels
from .serializers import UserSerializer, DailyRewardSerializer, DailyRewardsListSerializer, BalanceSerializer, LevelsSerializer
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
@action(detail=True, methods=['get'])
def get_datetime(self, request):
# Получаем текущие дату и время
current_datetime = timezone.now()
return Response({'datetime': current_datetime})
@action(detail=True, methods=['get'])
def get_referrals(self, request, pk=None):
user = self.get_object()
# Процентные ставки для каждого уровня
referral_percentages = {
1: 0.10, # 10% за рефералы 1 уровня
2: 0.06, # 6% за рефералы 2 уровня
3: 0.03, # 3% за рефералы 3 уровня
4: 0.01, # 1% за рефералы 4 уровня
}
# Рефералы по уровням
level_1_referrals = user.referrals.all()
level_2_referrals = User.objects.filter(referred_by__in=level_1_referrals)
level_3_referrals = User.objects.filter(referred_by__in=level_2_referrals)
level_4_referrals = User.objects.filter(referred_by__in=level_3_referrals)
referral_levels = {
1: level_1_referrals,
2: level_2_referrals,
3: level_3_referrals,
4: level_4_referrals,
}
total_coins = 0
for level, referrals in referral_levels.items():
# Фильтруем баланс рефералов, у которых валюта 'MCDC'
coins = Balance.objects.filter(user__in=referrals, currency='MCDC').aggregate(total=Sum('balance'))['total'] or 0
bonus_coins = coins * referral_percentages[level]
total_coins += bonus_coins
# Вычитаем уже полученные бонусы
total_coins -= user.coins_for_referral
response_data = {
"total_coins": total_coins,
"level_1_referrals": list(level_1_referrals.values('tg_username', 'tg_id', 'name', 'photo', 'coins_for_referral')),
"level_2_referrals": list(level_2_referrals.values('tg_username', 'tg_id', 'name', 'photo', 'coins_for_referral')),
"level_3_referrals": list(level_3_referrals.values('tg_username', 'tg_id', 'name', 'photo', 'coins_for_referral')),
"level_4_referrals": list(level_4_referrals.values('tg_username', 'tg_id', 'name', 'photo', 'coins_for_referral')),
}
print(response_data) # TODOPROJECT remove it
return Response({'status': '200', 'data': response_data})
class DailyRewardViewSet(viewsets.ModelViewSet):
queryset = DailyReward.objects.all()
serializer_class = DailyRewardSerializer
class DailyRewardsListViewSet(viewsets.ModelViewSet):
queryset = DailyRewardsList.objects.all()
serializer_class = DailyRewardsListSerializer
class BalanceViewSet(viewsets.ModelViewSet):
queryset = Balance.objects.all()
serializer_class = BalanceSerializer
@action(detail=True, methods=['post'])
def add_for_balance(self, request, pk=None):
user = self.get_object().user
amount = request.data.get("amount")
currency = request.data.get("currency")
if not amount or not currency:
return Response({"status": "error", "message": "Пожалуйста, укажите сумму и валюту"}, status=status.HTTP_400_BAD_REQUEST)
# Создаем новую транзакцию в базе данных
with db_transaction.atomic():
transaction = Transaction.objects.create(
user=user,
amount=amount,
currency=currency,
status="Pending"
)
# Формирование данных для запроса
data = {
"amount": amount,
"currency": currency,
"user_id": user.id,
"transaction_id": transaction.id
}
# Отправка POST-запроса к API Turcode
try:
response = requests.post(
"https://api.turcode.cc/v1/payment",
json=data,
headers={"Authorization": f"Bearer {settings.TURCODE_API_KEY}"}
)
# Обработка ответа от API
if response.status_code == 200:
transaction.status = "Success"
transaction.save()
# Обновление баланса пользователя
user_balance = self.get_object()
user_balance.balance += int(amount)
user_balance.save()
return Response({"status": "success", "message": "Баланс успешно пополнен"}, status=status.HTTP_200_OK)
else:
transaction.status = "Failed"
transaction.save()
return Response({"status": "error", "message": "Не удалось выполнить платеж"}, status=status.HTTP_400_BAD_REQUEST)
except requests.RequestException as e:
transaction.status = "Error"
transaction.save()
return Response({"status": "error", "message": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class LevelsViewSet(viewsets.ModelViewSet):
queryset = Levels.objects.all()
serializer_class = LevelsSerializer
@action(detail=True, methods=['post'])
def create_new_levels(self, request, pk=None):
user = self.get_object()
levels = []
# Задаем названия и изображения для каждого уровня
level_data = [
{"name": "Huey", "coins": 0, "image": "static/media/levels/character1.jpg"},
{"name": "Dewey", "coins": 10000, "image": "static/media/levels/character2.jpg"},
{"name": "Donald Duck", "coins": 20000, "image": "static/media/levels/character3.jpg"},
{"name": "Launchpad", "coins": 30000, "image": "static/media/levels/character4.jpg"},
{"name": "Gearloose", "coins": 40000, "image": "static/media/levels/character5.jpg"},
{"name": "Magica", "coins": 50000, "image": "static/media/levels/character6.jpg"},
{"name": "Scrooge", "coins": 60000, "image": "static/media/levels/character7.jpg"},
]
for i, data in enumerate(level_data, start=1):
level = Levels(
user=user,
name=data["name"],
level=i,
photo=data["image"],
need_coins=data["coins"]
)
levels.append(level)
# Сохраняем все созданные объекты в базе данных
Levels.objects.bulk_create(levels)
return Response({'status': '200', 'message': f'Created {len(levels)} levels for user {user.username}.'})