Files

78 lines
2.9 KiB
Python

from adrf.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from user.models import Invitation, FUser
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from chunyu_project.common_schemas import success_response, error_response, unauthorized_response
class InviteCodeAPIView(APIView):
permission_classes = [IsAuthenticated]
@swagger_auto_schema(
tags=['邀请'],
operation_summary='获取邀请码',
operation_description='获取当前用户的邀请码和邀请链接',
responses={200: success_response, 401: unauthorized_response},
)
async def get(self, request):
user = request.user
# Generate or get existing invite code
invite_code = f"CY{str(user.id).zfill(6)}"
# Ensure the invitation record exists
await Invitation.objects.aget_or_create(
inviter=user,
invite_code=invite_code,
defaults={'is_used': False}
)
return Response({
'invite_code': invite_code,
'invite_url': f'https://chunyu.dev/invite/{invite_code}',
})
class InviteStatsAPIView(APIView):
permission_classes = [IsAuthenticated]
@swagger_auto_schema(
tags=['邀请'],
operation_summary='获取邀请统计',
operation_description='获取当前用户的邀请统计信息,包括已邀请人数、获得积分和待使用邀请数',
responses={200: success_response, 401: unauthorized_response},
)
async def get(self, request):
user = request.user
used_count = await Invitation.objects.filter(inviter=user, is_used=True).acount()
total_points = used_count * 500 # 500 points per invite
pending_count = await Invitation.objects.filter(inviter=user, is_used=False).acount()
return Response({
'invited_count': used_count,
'total_points': total_points,
'pending_count': pending_count,
})
class InviteRecordsAPIView(APIView):
permission_classes = [IsAuthenticated]
@swagger_auto_schema(
tags=['邀请'],
operation_summary='获取邀请记录',
operation_description='获取当前用户的所有邀请记录列表',
responses={200: success_response, 401: unauthorized_response},
)
async def get(self, request):
user = request.user
records = Invitation.objects.filter(inviter=user).order_by('-created_at')
data = []
async for r in records:
data.append({
'id': r.id,
'invite_code': r.invite_code,
'invitee_username': r.invitee.username if r.invitee else None,
'invitee_email': r.invitee.email if r.invitee else None,
'is_used': r.is_used,
'created_at': r.created_at.strftime('%Y-%m-%d %H:%M'),
})
return Response(data)