Payment events: one central payment_result row for every path (callback, reconcile, Bazaar, renewal, 100% code), discount_applied, no duplicate order_created; Bazaar token never stored

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-13 14:44:50 +03:30
parent 8d8665edf3
commit 44ad2eabf3
4 changed files with 50 additions and 5 deletions

View File

@@ -18,7 +18,6 @@ from rest_framework.exceptions import APIException
from statuslog.signals import status_changed
from . import events
from .models import Order, Transaction
from .providers import PROVIDERS, provider_for
@@ -111,6 +110,7 @@ def create_order(*, user_id: int, amount: int, currency: str = 'IRT',
from subscription.models import Plan
plan = Plan.objects.filter(pk=plan_id).first() if plan_id else None
created = False
try:
with db_transaction.atomic():
order = Order.objects.create(
@@ -127,6 +127,7 @@ def create_order(*, user_id: int, amount: int, currency: str = 'IRT',
bazaar_product_sku=bazaar_product_sku,
idempotency_key=idempotency_key,
)
created = True
except IntegrityError:
# درخواست هم‌زمان دیگری با همین کلید زودتر ساخت.
order = Order.objects.filter(idempotency_key=idempotency_key).first()
@@ -137,8 +138,9 @@ def create_order(*, user_id: int, amount: int, currency: str = 'IRT',
subscription_id=subscription_id, plan_id=plan_id, provider=provider,
)
events.record('order_created', order=order, plan_id=plan_id, amount=amount, currency=currency,
duration_days=order.duration_days, sku=bazaar_product_sku)
if created:
events.record('order_created', order=order, plan_id=plan_id, amount=amount, currency=currency,
duration_days=order.duration_days, sku=bazaar_product_sku)
# بازار paymentUrl ندارد (اپ با Poolakey می‌خرد)؛ زرین‌پال آدرسِ PaymentRedirectView را دارد (providers.py).
payment_url = provider_for(order.provider).payment_url(order)
return order, payment_url
@@ -223,6 +225,11 @@ def apply_order_payment_result(*, order: Order, gateway: str, gateway_ref_id: st
order.id, order.user_id, gateway, event, old_status, new_status,
gateway_ref_id or '-', is_duplicate,
)
# همان نتیجه در دفترِ خرید (به ۲۴۷ هم می‌رود). همه‌ی مسیرها از این‌جا می‌گذرند: کال‌بک، بازسنجی،
# بازار، تمدیدِ بازار، کدِ ۱۰۰٪. رفرنسِ بازار خودِ توکنِ خرید است و در دفتر نمی‌رود.
events.record('payment_result', order=order, via=event, gateway=gateway,
old_status=old_status, new_status=new_status, ignored=is_duplicate,
ref_id=gateway_ref_id if gateway == 'zarinpal' else '')
newly_paid = new_status == 'paid' and not already_paid and not is_duplicate
if newly_paid:
if order.subscription_id: