Harden auth, AI tutor, payments, and subscriptions

This commit is contained in:
2026-08-22 04:42:36 +03:30
parent f945f960c9
commit cb18c93a3e
41 changed files with 2202 additions and 595 deletions

View File

@@ -1,4 +1,5 @@
from django.db import transaction
from django.db.models import F
from django.shortcuts import get_object_or_404
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
@@ -6,6 +7,7 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from payment.models import Order
from payment.services import create_order
from .models import Plan, Subscription
@@ -18,7 +20,7 @@ from .serializers import (
class PlansListView(APIView):
"""GET /api/subscription/plans — لیست پلن‌ها"""
"""GET /api/subscription/plans — list available plans."""
@extend_schema(responses=PlansListResponseSerializer, tags=['Subscription (subscription)'])
def get(self, request):
@@ -41,18 +43,13 @@ class PlansListView(APIView):
class PurchaseView(APIView):
"""
POST /api/subscription/purchase — شروع خرید (با هدر Idempotency-Key)
یک Subscription در وضعیت pending می‌سازه/به‌روز می‌کنه، بعد مستقیماً
تابع سرویس اپ Payment رو صدا می‌زنه تا Order بسازه (همون «فراخوانی
سرور-به-سرور» سند API که در این مونولیت به شکل import مستقیم پیاده‌سازی
شده، نه یک HTTP call جدا به خودمون).
"""
"""POST /api/subscription/purchase — starts a purchase (Idempotency-Key
header supported). Creates/updates a pending Subscription, then calls
the payment app's service directly (in-process, not a separate HTTP call)
to create an Order."""
permission_classes = [IsAuthenticated]
# ⚠️ افزوده شده: مستندسازی هدر Idempotency-Key که قبلاً در Swagger UI
# قابل تنظیم/تست نبود.
@extend_schema(
request=PurchaseRequestSerializer,
responses=PurchaseResponseSerializer,
@@ -74,33 +71,86 @@ class PurchaseView(APIView):
user = request.user
plan = get_object_or_404(Plan, pk=v['planId'])
idempotency_key = request.headers.get('Idempotency-Key')
# ⚠️ اصلاح: قبلاً اگه create_order (مثلاً به‌خاطر IdempotencyKeyConflict)
# خطا می‌داد، Subscription که یک خط بالاتر update_or_create شده بود
# نیمه‌کاره (status='pending' ولی بدون order_id معتبر) در دیتابیس
# باقی می‌موند. حالا کل عملیات در یک تراکنش اتمیک انجام می‌شه.
with transaction.atomic():
subscription, _created = Subscription.objects.update_or_create(
# Three-phase flow so create_order (which may call an external payment
# gateway) never runs inside a DB transaction/lock: phase 1 creates/updates
# the pending Subscription, phase 2 calls create_order and restores the
# prior state on failure, phase 3 attaches order_id atomically.
existing_order = None
if idempotency_key:
existing_order = Order.objects.filter(idempotency_key=idempotency_key).first()
prior_subscription = Subscription.objects.filter(user_id=user.id).first()
prior_snapshot = None
if prior_subscription is not None:
prior_snapshot = {
'status': prior_subscription.status,
'plan_id': prior_subscription.plan_id,
'order_id': prior_subscription.order_id,
}
if existing_order is not None:
# Retry path: leave an existing subscription untouched, only
# create one if it's genuinely missing.
if prior_subscription is None:
# Fresh row: version starts at 1 to give it a CAS token.
subscription = Subscription.objects.create(
user_id=user.id, plan=plan, status='pending', version=1,
)
subscription_is_new = True
else:
subscription = prior_subscription
subscription_is_new = False
else:
subscription, subscription_is_new = Subscription.objects.update_or_create(
user_id=user.id,
defaults={'plan': plan, 'status': 'pending'},
)
# Two concurrent requests can reach an identical intermediate state,
# so version is bumped atomically here to give this write a unique
# CAS token the cleanup below can match against.
Subscription.objects.filter(pk=subscription.pk).update(version=F('version') + 1)
subscription.refresh_from_db(fields=['version'])
try:
order, payment_url = create_order(
user_id=user.id,
amount=plan.price,
currency=plan.currency,
subscription_id=subscription.id,
idempotency_key=request.headers.get('Idempotency-Key'),
idempotency_key=idempotency_key,
)
subscription.order_id = order.id
subscription.save(update_fields=['order_id'])
except Exception:
# Guard by pk+status+plan_id+order_id+version so this cleanup only
# matches the exact row state phase 1 wrote; any concurrent writer
# (another request, a payment webhook, etc.) changes the match and
# the delete/update below becomes a no-op instead of clobbering it.
guard = {
'pk': subscription.pk,
'status': subscription.status,
'plan_id': subscription.plan_id,
'order_id': subscription.order_id,
'version': subscription.version,
}
with transaction.atomic():
if subscription_is_new:
Subscription.objects.filter(**guard).delete()
elif prior_snapshot is not None:
Subscription.objects.filter(**guard).update(**prior_snapshot)
raise
if subscription.order_id != order.id:
with transaction.atomic():
subscription.order_id = order.id
subscription.save(update_fields=['order_id'])
data = {'orderId': str(order.id), 'paymentUrl': payment_url}
return Response(PurchaseResponseSerializer(data).data)
class SubscriptionStatusView(APIView):
"""GET /api/subscription/status — وضعیت فعلی اشتراک"""
"""GET /api/subscription/status — current subscription status."""
permission_classes = [IsAuthenticated]