pénzügyi modul továbbfejlesztése (csomagkezelés)
This commit is contained in:
307
backend/app/services/downgrade_executor.py
Normal file
307
backend/app/services/downgrade_executor.py
Normal file
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
Downgrade Executor — Background service that activates pending downgrades.
|
||||
|
||||
Processes subscriptions where:
|
||||
- pending_tier_id IS NOT NULL (a downgrade was requested)
|
||||
- valid_until < NOW() (the current paid period has expired)
|
||||
|
||||
When both conditions are met:
|
||||
1. Deactivates the current subscription (is_active = False)
|
||||
2. Activates the pending tier (creates a new UserSubscription/OrgSubscription)
|
||||
3. Clears the pending_tier_id and pending_activated_at fields
|
||||
|
||||
THOUGHT PROCESS:
|
||||
- Designed to be called from a CRON job or scheduled task.
|
||||
- Uses atomic SELECT ... FOR UPDATE SKIP LOCKED to prevent duplicate
|
||||
activation when multiple workers run concurrently.
|
||||
- Updates User.subscription_plan and User.subscription_expires_at for
|
||||
backward compatibility.
|
||||
- All operations are logged at INFO level for audit trail.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Tuple, Optional
|
||||
|
||||
from sqlalchemy import select, update, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.core_logic import (
|
||||
SubscriptionTier,
|
||||
UserSubscription,
|
||||
OrganizationSubscription,
|
||||
)
|
||||
from app.models.identity.identity import User
|
||||
|
||||
logger = logging.getLogger("downgrade-executor")
|
||||
|
||||
|
||||
class DowngradeExecutor:
|
||||
"""
|
||||
Background service that activates pending downgrades after the current
|
||||
subscription period expires.
|
||||
|
||||
Usage:
|
||||
executor = DowngradeExecutor()
|
||||
count = await executor.process_pending_downgrades(db)
|
||||
"""
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# Public API
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
async def process_pending_downgrades(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
batch_size: int = 50,
|
||||
) -> Tuple[int, int]:
|
||||
"""
|
||||
Process all pending downgrades where the current subscription has expired.
|
||||
|
||||
Uses atomic SELECT ... FOR UPDATE SKIP LOCKED to safely handle
|
||||
concurrent execution.
|
||||
|
||||
Args:
|
||||
db: Database session.
|
||||
batch_size: Maximum number of downgrades to process in one call.
|
||||
|
||||
Returns:
|
||||
Tuple of (processed_count, error_count).
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
processed = 0
|
||||
errors = 0
|
||||
|
||||
# ── 1. Process UserSubscription pending downgrades ──────────────
|
||||
user_subs = await self._fetch_expired_user_pending(db, now, batch_size)
|
||||
for sub in user_subs:
|
||||
try:
|
||||
await self._activate_user_pending(db, sub)
|
||||
processed += 1
|
||||
logger.info(
|
||||
"User pending downgrade activated: user_id=%d "
|
||||
"from_tier_id=%d to_tier_id=%d",
|
||||
sub.user_id, sub.tier_id, sub.pending_tier_id,
|
||||
)
|
||||
except Exception as e:
|
||||
errors += 1
|
||||
logger.exception(
|
||||
"Failed to activate user pending downgrade: sub_id=%d "
|
||||
"user_id=%d error=%s",
|
||||
sub.id, sub.user_id, str(e),
|
||||
)
|
||||
|
||||
# ── 2. Process OrganizationSubscription pending downgrades ─────
|
||||
org_subs = await self._fetch_expired_org_pending(db, now, batch_size)
|
||||
for sub in org_subs:
|
||||
try:
|
||||
await self._activate_org_pending(db, sub)
|
||||
processed += 1
|
||||
logger.info(
|
||||
"Org pending downgrade activated: org_id=%d "
|
||||
"from_tier_id=%d to_tier_id=%d",
|
||||
sub.org_id, sub.tier_id, sub.pending_tier_id,
|
||||
)
|
||||
except Exception as e:
|
||||
errors += 1
|
||||
logger.exception(
|
||||
"Failed to activate org pending downgrade: sub_id=%d "
|
||||
"org_id=%d error=%s",
|
||||
sub.id, sub.org_id, str(e),
|
||||
)
|
||||
|
||||
if processed > 0 or errors > 0:
|
||||
logger.info(
|
||||
"DowngradeExecutor finished: processed=%d errors=%d",
|
||||
processed, errors,
|
||||
)
|
||||
|
||||
return (processed, errors)
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# Internal: Fetch expired pending subscriptions
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
async def _fetch_expired_user_pending(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
now: datetime,
|
||||
limit: int,
|
||||
) -> List[UserSubscription]:
|
||||
"""
|
||||
Fetch UserSubscription records where:
|
||||
- pending_tier_id IS NOT NULL
|
||||
- valid_until < now (expired)
|
||||
- is_active == True
|
||||
|
||||
Uses FOR UPDATE SKIP LOCKED for atomic processing.
|
||||
"""
|
||||
stmt = (
|
||||
select(UserSubscription)
|
||||
.where(
|
||||
UserSubscription.pending_tier_id.is_not(None),
|
||||
UserSubscription.valid_until.is_not(None),
|
||||
UserSubscription.valid_until < now,
|
||||
UserSubscription.is_active == True,
|
||||
)
|
||||
.order_by(UserSubscription.valid_until.asc())
|
||||
.limit(limit)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def _fetch_expired_org_pending(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
now: datetime,
|
||||
limit: int,
|
||||
) -> List[OrganizationSubscription]:
|
||||
"""
|
||||
Fetch OrganizationSubscription records where:
|
||||
- pending_tier_id IS NOT NULL
|
||||
- valid_until < now (expired)
|
||||
- is_active == True
|
||||
|
||||
Uses FOR UPDATE SKIP LOCKED for atomic processing.
|
||||
"""
|
||||
stmt = (
|
||||
select(OrganizationSubscription)
|
||||
.where(
|
||||
OrganizationSubscription.pending_tier_id.is_not(None),
|
||||
OrganizationSubscription.valid_until.is_not(None),
|
||||
OrganizationSubscription.valid_until < now,
|
||||
OrganizationSubscription.is_active == True,
|
||||
)
|
||||
.order_by(OrganizationSubscription.valid_until.asc())
|
||||
.limit(limit)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# Internal: Activate pending downgrades
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
async def _activate_user_pending(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
current_sub: UserSubscription,
|
||||
) -> UserSubscription:
|
||||
"""
|
||||
Activate a pending user-level downgrade.
|
||||
|
||||
1. Deactivates the current subscription
|
||||
2. Fetches the pending tier to get duration info
|
||||
3. Creates a new UserSubscription for the pending tier
|
||||
4. Updates User.subscription_plan for backward compat
|
||||
5. Clears pending fields on the old subscription
|
||||
"""
|
||||
target_tier_id = current_sub.pending_tier_id
|
||||
if target_tier_id is None:
|
||||
raise ValueError(f"Subscription {current_sub.id} has no pending_tier_id")
|
||||
|
||||
# Fetch the target tier for duration info
|
||||
tier_stmt = select(SubscriptionTier).where(SubscriptionTier.id == target_tier_id)
|
||||
tier_result = await db.execute(tier_stmt)
|
||||
tier = tier_result.scalar_one_or_none()
|
||||
if not tier:
|
||||
raise ValueError(f"Pending tier {target_tier_id} not found")
|
||||
|
||||
# Resolve duration from tier.rules
|
||||
duration_days = 30
|
||||
if tier.rules:
|
||||
duration_config = tier.rules.get("duration", {})
|
||||
if isinstance(duration_config, dict):
|
||||
days = duration_config.get("days", 30)
|
||||
if isinstance(days, (int, float)) and days > 0:
|
||||
duration_days = int(days)
|
||||
|
||||
now = datetime.utcnow()
|
||||
valid_until = now + timedelta(days=duration_days)
|
||||
|
||||
# Deactivate current subscription
|
||||
current_sub.is_active = False
|
||||
|
||||
# Create new subscription for the pending tier
|
||||
new_sub = UserSubscription(
|
||||
user_id=current_sub.user_id,
|
||||
tier_id=target_tier_id,
|
||||
valid_from=now,
|
||||
valid_until=valid_until,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(new_sub)
|
||||
|
||||
# Update User.subscription_plan for backward compat
|
||||
user_stmt = select(User).where(User.id == current_sub.user_id)
|
||||
user_result = await db.execute(user_stmt)
|
||||
user = user_result.scalar_one_or_none()
|
||||
if user:
|
||||
user.subscription_plan = tier.name
|
||||
user.subscription_expires_at = valid_until
|
||||
|
||||
# Clear pending fields on old subscription
|
||||
current_sub.pending_tier_id = None
|
||||
current_sub.pending_activated_at = None
|
||||
|
||||
await db.flush()
|
||||
await db.refresh(new_sub)
|
||||
|
||||
return new_sub
|
||||
|
||||
async def _activate_org_pending(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
current_sub: OrganizationSubscription,
|
||||
) -> OrganizationSubscription:
|
||||
"""
|
||||
Activate a pending org-level downgrade.
|
||||
|
||||
Same logic as _activate_user_pending but for org subscriptions.
|
||||
"""
|
||||
target_tier_id = current_sub.pending_tier_id
|
||||
if target_tier_id is None:
|
||||
raise ValueError(f"Subscription {current_sub.id} has no pending_tier_id")
|
||||
|
||||
# Fetch the target tier
|
||||
tier_stmt = select(SubscriptionTier).where(SubscriptionTier.id == target_tier_id)
|
||||
tier_result = await db.execute(tier_stmt)
|
||||
tier = tier_result.scalar_one_or_none()
|
||||
if not tier:
|
||||
raise ValueError(f"Pending tier {target_tier_id} not found")
|
||||
|
||||
# Resolve duration
|
||||
duration_days = 30
|
||||
if tier.rules:
|
||||
duration_config = tier.rules.get("duration", {})
|
||||
if isinstance(duration_config, dict):
|
||||
days = duration_config.get("days", 30)
|
||||
if isinstance(days, (int, float)) and days > 0:
|
||||
duration_days = int(days)
|
||||
|
||||
now = datetime.utcnow()
|
||||
valid_until = now + timedelta(days=duration_days)
|
||||
|
||||
# Deactivate current
|
||||
current_sub.is_active = False
|
||||
|
||||
# Create new subscription
|
||||
new_sub = OrganizationSubscription(
|
||||
org_id=current_sub.org_id,
|
||||
tier_id=target_tier_id,
|
||||
valid_from=now,
|
||||
valid_until=valid_until,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(new_sub)
|
||||
|
||||
# Clear pending fields
|
||||
current_sub.pending_tier_id = None
|
||||
current_sub.pending_activated_at = None
|
||||
|
||||
await db.flush()
|
||||
await db.refresh(new_sub)
|
||||
|
||||
return new_sub
|
||||
@@ -51,6 +51,7 @@ from app.schemas.commission import (
|
||||
CommissionDistributionResponse,
|
||||
)
|
||||
from app.services import commission_service
|
||||
from app.services.subscription_service import SubscriptionService
|
||||
|
||||
logger = logging.getLogger("financial-manager")
|
||||
|
||||
@@ -80,9 +81,11 @@ class PurchaseResult:
|
||||
currency: str = "EUR",
|
||||
gateway: str = "mock",
|
||||
gateway_intent_id: Optional[str] = None,
|
||||
checkout_url: Optional[str] = None,
|
||||
commission_result: Optional[CommissionDistributionResponse] = None,
|
||||
error: Optional[str] = None,
|
||||
is_org_subscription: bool = False,
|
||||
payment_status: Optional[str] = None,
|
||||
):
|
||||
self.success = success
|
||||
self.payment_intent_id = payment_intent_id
|
||||
@@ -95,9 +98,11 @@ class PurchaseResult:
|
||||
self.currency = currency
|
||||
self.gateway = gateway
|
||||
self.gateway_intent_id = gateway_intent_id
|
||||
self.checkout_url = checkout_url
|
||||
self.commission_result = commission_result
|
||||
self.error = error
|
||||
self.is_org_subscription = is_org_subscription
|
||||
self.payment_status = payment_status
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Serialize to a dict for API response."""
|
||||
@@ -115,6 +120,12 @@ class PurchaseResult:
|
||||
"gateway_intent_id": self.gateway_intent_id,
|
||||
"is_org_subscription": self.is_org_subscription,
|
||||
}
|
||||
# Include checkout_url for payment redirect (simulate_redirect mode)
|
||||
if self.checkout_url:
|
||||
result["checkout_url"] = self.checkout_url
|
||||
# Include payment_status for pending payments
|
||||
if self.payment_status:
|
||||
result["payment_status"] = self.payment_status
|
||||
if self.commission_result:
|
||||
result["commission"] = {
|
||||
"total_commission": self.commission_result.total_commission,
|
||||
@@ -225,6 +236,89 @@ class FinancialManager:
|
||||
# ── Step 2: Calculate price ────────────────────────────────────
|
||||
price = await self._calculate_price(db, tier, region_code, currency)
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════
|
||||
# Step 2b: FREE TIER BYPASS & DOWNGRADE DETECTION (Issue #429)
|
||||
# ══════════════════════════════════════════════════════════════════
|
||||
#
|
||||
# THOUGHT PROCESS:
|
||||
# - Free tiers (price=0) cause PaymentRouter to throw
|
||||
# ValueError("net_amount pozitív szám kell legyen").
|
||||
# - Solution: skip PaymentIntent creation entirely for $0 tiers.
|
||||
# - If downgrade (target tier_level < current): set pending_tier_id.
|
||||
# - If upgrade/same-level with $0: activate immediately.
|
||||
# - Paid tiers (price > 0): fall through to normal payment flow.
|
||||
# ══════════════════════════════════════════════════════════════════
|
||||
if price <= 0:
|
||||
logger.info(
|
||||
"Zero-cost tier detected (price=%.2f). Checking downgrade "
|
||||
"for user_id=%d tier_id=%d", price, user_id, tier_id,
|
||||
)
|
||||
|
||||
is_down = await SubscriptionService.is_downgrade(
|
||||
db=db, user_id=user_id,
|
||||
target_tier_id=tier_id, active_org_id=org_id,
|
||||
)
|
||||
|
||||
if is_down:
|
||||
# ── DOWNGRADE PATH: set pending_tier_id ──
|
||||
return await self._handle_downgrade(
|
||||
db=db, user_id=user_id, tier_id=tier_id,
|
||||
org_id=org_id, tier=tier, currency=currency,
|
||||
)
|
||||
|
||||
# ── UPGRADE OR SAME-LEVEL: activate immediately ──
|
||||
# Clear any existing pending downgrade first
|
||||
await self._clear_pending_downgrade(db, user_id, org_id)
|
||||
|
||||
if org_id:
|
||||
subscription = await self.subscription_activator.activate_org_subscription(
|
||||
db=db, org_id=org_id, tier_id=tier_id,
|
||||
duration_days=duration_days,
|
||||
)
|
||||
is_org = True
|
||||
else:
|
||||
subscription = await self.subscription_activator.activate_user_subscription(
|
||||
db=db, user_id=user_id, tier_id=tier_id,
|
||||
duration_days=duration_days,
|
||||
)
|
||||
is_org = False
|
||||
|
||||
commission_result = await self._distribute_commission(
|
||||
db=db, buyer_user_id=user_id,
|
||||
transaction_amount=0, region_code=region_code,
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
"Free tier activation COMPLETED: user_id=%d tier=%s sub_id=%d",
|
||||
user_id, tier.name, subscription.id,
|
||||
)
|
||||
return PurchaseResult(
|
||||
success=True, subscription_id=subscription.id,
|
||||
tier_name=tier.name,
|
||||
valid_from=subscription.valid_from,
|
||||
valid_until=subscription.valid_until,
|
||||
amount_paid=0, currency=currency,
|
||||
gateway="none", is_org_subscription=is_org,
|
||||
)
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════
|
||||
# PAID TIER FLOW (price > 0)
|
||||
# ══════════════════════════════════════════════════════════════════
|
||||
#
|
||||
# THOUGHT PROCESS:
|
||||
# The payment gateway may return either:
|
||||
# a) "completed" status (auto_approve mode) — activate immediately
|
||||
# b) "requires_action" status (simulate_redirect mode) —
|
||||
# return a checkout_url; subscription activation is deferred
|
||||
# until the mock webhook callback is received.
|
||||
#
|
||||
# In case (b), the caller (frontend) receives the checkout_url and
|
||||
# must redirect the user. After the user clicks "Pay Now" on the
|
||||
# mock page, the webhook callback (POST /billing/mock-payment/callback)
|
||||
# finalizes the PaymentIntent and activates the subscription.
|
||||
# ══════════════════════════════════════════════════════════════════
|
||||
|
||||
# ── Step 3: Create PaymentIntent ───────────────────────────────
|
||||
payment_intent = await self._create_payment_intent(
|
||||
db=db,
|
||||
@@ -242,15 +336,87 @@ class FinancialManager:
|
||||
"payment_intent_id": payment_intent.id,
|
||||
"tier_id": tier_id,
|
||||
"user_id": user_id,
|
||||
"org_id": org_id,
|
||||
"duration_days": duration_days,
|
||||
"region_code": region_code,
|
||||
**(metadata or {}),
|
||||
},
|
||||
)
|
||||
|
||||
# ── Step 4b: Handle gateway response ──────────────────────────
|
||||
gateway_status = gateway_result.get("status", "completed")
|
||||
|
||||
if gateway_status == "requires_action":
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# simulate_redirect mode — defer subscription activation
|
||||
# ════════════════════════════════════════════════════════════
|
||||
#
|
||||
# The gateway tells us the user needs to complete payment
|
||||
# on an external (mock) checkout page. We:
|
||||
# 1. Store the gateway intent ID on the PaymentIntent
|
||||
# 2. Store tier metadata for later webhook processing
|
||||
# 3. Leave PaymentIntent as PENDING
|
||||
# 4. Do NOT activate the subscription yet
|
||||
# 5. Return checkout_url so the frontend can redirect
|
||||
#
|
||||
# Subscription activation happens when the mock webhook
|
||||
# callback is received (see billing.py mock-payment/callback).
|
||||
|
||||
payment_intent.stripe_session_id = gateway_result.get("id")
|
||||
# Store the full purchase context in metadata so the webhook
|
||||
# callback can complete the activation
|
||||
payment_intent.meta_data = {
|
||||
**(payment_intent.meta_data or {}),
|
||||
"tier_id": tier_id,
|
||||
"user_id": user_id,
|
||||
"org_id": org_id,
|
||||
"duration_days": duration_days,
|
||||
"region_code": region_code,
|
||||
"checkout_url": gateway_result.get("checkout_url"),
|
||||
}
|
||||
|
||||
# Flush so the PaymentIntent is persisted before returning
|
||||
await db.flush()
|
||||
|
||||
checkout_url = gateway_result.get("checkout_url")
|
||||
gateway_intent_id = gateway_result.get("id")
|
||||
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_REDIRECT] Payment requires user action: "
|
||||
"user_id=%d tier=%s amount=%.2f checkout_url=%s "
|
||||
"intent_id=%s",
|
||||
user_id, tier.name, price, checkout_url, gateway_intent_id,
|
||||
)
|
||||
|
||||
# Clear any existing pending downgrade (user is upgrading)
|
||||
await self._clear_pending_downgrade(db, user_id, org_id)
|
||||
await db.commit()
|
||||
|
||||
return PurchaseResult(
|
||||
success=True,
|
||||
payment_intent_id=payment_intent.id,
|
||||
tier_name=tier.name,
|
||||
amount_paid=price,
|
||||
currency=currency,
|
||||
gateway=type(self.payment_gateway).__name__,
|
||||
gateway_intent_id=gateway_intent_id,
|
||||
checkout_url=checkout_url,
|
||||
payment_status="PENDING_PAYMENT",
|
||||
is_org_subscription=(org_id is not None),
|
||||
)
|
||||
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
# auto_approve mode — immediate activation
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
|
||||
# Mark PaymentIntent as COMPLETED
|
||||
payment_intent.status = PaymentIntentStatus.COMPLETED
|
||||
payment_intent.stripe_session_id = gateway_result.get("id")
|
||||
payment_intent.completed_at = datetime.utcnow()
|
||||
|
||||
# Clear any existing pending downgrade on upgrade
|
||||
await self._clear_pending_downgrade(db, user_id, org_id)
|
||||
|
||||
# ── Step 5: Activate subscription ──────────────────────────────
|
||||
if org_id:
|
||||
subscription = await self.subscription_activator.activate_org_subscription(
|
||||
@@ -281,7 +447,7 @@ class FinancialManager:
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
"Purchase flow COMPLETED: user_id=%d tier=%s amount=%.2f "
|
||||
"Purchase flow COMPLETED (immediate): user_id=%d tier=%s amount=%.2f "
|
||||
"subscription_id=%d commission_total=%.2f",
|
||||
user_id, tier.name, price,
|
||||
subscription.id,
|
||||
@@ -300,6 +466,7 @@ class FinancialManager:
|
||||
currency=currency,
|
||||
gateway=type(self.payment_gateway).__name__,
|
||||
gateway_intent_id=gateway_result.get("id"),
|
||||
payment_status="COMPLETED",
|
||||
commission_result=commission_result,
|
||||
is_org_subscription=is_org,
|
||||
)
|
||||
@@ -517,3 +684,161 @@ class FinancialManager:
|
||||
)
|
||||
# Commission failure should not block the purchase
|
||||
return None
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# Pending Downgrade Helpers (Issue #429)
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
async def _handle_downgrade(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
user_id: int,
|
||||
tier_id: int,
|
||||
org_id: Optional[int],
|
||||
tier: SubscriptionTier,
|
||||
currency: str,
|
||||
) -> PurchaseResult:
|
||||
"""
|
||||
Handle a downgrade request by setting pending_tier_id on the current
|
||||
active subscription. The downgrade takes effect only after the current
|
||||
paid period expires.
|
||||
|
||||
THOUGHT PROCESS:
|
||||
- Finds the currently active subscription (user or org level).
|
||||
- Sets pending_tier_id to the target tier ID.
|
||||
- Sets pending_activated_at to now (audit trail).
|
||||
- The actual tier switch is deferred to the DowngradeExecutor service.
|
||||
- Returns a success PurchaseResult with the CURRENT subscription data.
|
||||
|
||||
Args:
|
||||
db: Database session.
|
||||
user_id: The user requesting the downgrade.
|
||||
tier_id: The target SubscriptionTier ID (cheaper/free tier).
|
||||
org_id: Optional org ID for org-level subscriptions.
|
||||
tier: The target SubscriptionTier object (for tier_name).
|
||||
currency: Currency code.
|
||||
|
||||
Returns:
|
||||
PurchaseResult with success=True and current subscription data.
|
||||
"""
|
||||
if org_id:
|
||||
from app.models.core_logic import OrganizationSubscription
|
||||
stmt = select(OrganizationSubscription).where(
|
||||
OrganizationSubscription.org_id == org_id,
|
||||
OrganizationSubscription.is_active == True,
|
||||
).order_by(OrganizationSubscription.id.desc()).limit(1)
|
||||
result = await db.execute(stmt)
|
||||
current_sub = result.scalar_one_or_none()
|
||||
else:
|
||||
from app.models.core_logic import UserSubscription
|
||||
stmt = select(UserSubscription).where(
|
||||
UserSubscription.user_id == user_id,
|
||||
UserSubscription.is_active == True,
|
||||
).order_by(UserSubscription.id.desc()).limit(1)
|
||||
result = await db.execute(stmt)
|
||||
current_sub = result.scalar_one_or_none()
|
||||
|
||||
if not current_sub:
|
||||
# No active subscription — activate the downgrade immediately
|
||||
logger.info(
|
||||
"No active subscription for user_id=%d. Activating downgrade immediately.",
|
||||
user_id,
|
||||
)
|
||||
if org_id:
|
||||
new_sub = await self.subscription_activator.activate_org_subscription(
|
||||
db=db, org_id=org_id, tier_id=tier_id,
|
||||
)
|
||||
else:
|
||||
new_sub = await self.subscription_activator.activate_user_subscription(
|
||||
db=db, user_id=user_id, tier_id=tier_id,
|
||||
)
|
||||
await db.commit()
|
||||
return PurchaseResult(
|
||||
success=True, subscription_id=new_sub.id,
|
||||
tier_name=tier.name,
|
||||
valid_from=new_sub.valid_from,
|
||||
valid_until=new_sub.valid_until,
|
||||
amount_paid=0, currency=currency,
|
||||
gateway="none",
|
||||
is_org_subscription=(org_id is not None),
|
||||
)
|
||||
|
||||
# Set pending tier on existing active subscription
|
||||
current_sub.pending_tier_id = tier_id
|
||||
current_sub.pending_activated_at = datetime.utcnow()
|
||||
await db.flush()
|
||||
await db.refresh(current_sub)
|
||||
|
||||
logger.info(
|
||||
"Pending downgrade set: %s_id=%d current_tier_id=%d "
|
||||
"pending_tier_id=%d valid_until=%s",
|
||||
"org" if org_id else "user",
|
||||
org_id or user_id,
|
||||
current_sub.tier_id, tier_id,
|
||||
current_sub.valid_until,
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
|
||||
return PurchaseResult(
|
||||
success=True,
|
||||
subscription_id=current_sub.id,
|
||||
tier_name=tier.name,
|
||||
valid_from=current_sub.valid_from,
|
||||
valid_until=current_sub.valid_until,
|
||||
amount_paid=0,
|
||||
currency=currency,
|
||||
gateway="none",
|
||||
is_org_subscription=(org_id is not None),
|
||||
)
|
||||
|
||||
async def _clear_pending_downgrade(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
user_id: int,
|
||||
org_id: Optional[int],
|
||||
) -> None:
|
||||
"""
|
||||
Clear any pending downgrade on the user's or org's subscriptions.
|
||||
Called when an upgrade or new purchase occurs.
|
||||
|
||||
THOUGHT PROCESS:
|
||||
- Scans both active and recently deactivated subscriptions for
|
||||
pending_tier_id IS NOT NULL.
|
||||
- Sets pending_tier_id = NULL and pending_activated_at = NULL.
|
||||
- This ensures that an upgrade overrides a previously scheduled downgrade.
|
||||
|
||||
Args:
|
||||
db: Database session.
|
||||
user_id: The user ID.
|
||||
org_id: Optional org ID.
|
||||
"""
|
||||
from app.models.core_logic import UserSubscription, OrganizationSubscription
|
||||
|
||||
if org_id:
|
||||
stmt = select(OrganizationSubscription).where(
|
||||
OrganizationSubscription.org_id == org_id,
|
||||
OrganizationSubscription.pending_tier_id.is_not(None),
|
||||
)
|
||||
else:
|
||||
stmt = select(UserSubscription).where(
|
||||
UserSubscription.user_id == user_id,
|
||||
UserSubscription.pending_tier_id.is_not(None),
|
||||
)
|
||||
|
||||
result = await db.execute(stmt)
|
||||
subs_with_pending = result.scalars().all()
|
||||
|
||||
for sub in subs_with_pending:
|
||||
sub.pending_tier_id = None
|
||||
sub.pending_activated_at = None
|
||||
logger.debug(
|
||||
"Cleared pending downgrade on subscription id=%d", sub.id,
|
||||
)
|
||||
|
||||
if subs_with_pending:
|
||||
logger.info(
|
||||
"Cleared %d pending downgrade(s) for %s_id=%d",
|
||||
len(subs_with_pending), "org" if org_id else "user",
|
||||
org_id or user_id,
|
||||
)
|
||||
|
||||
@@ -33,37 +33,44 @@ class MockPaymentGateway(BasePaymentGateway):
|
||||
Mock payment gateway for development and testing.
|
||||
|
||||
Modes:
|
||||
- auto_approve (default): All payments succeed immediately.
|
||||
- simulate_redirect (NEW default): Returns a checkout URL for paid tiers.
|
||||
The frontend redirects to the mock checkout page; after user clicks "Pay Now",
|
||||
a webhook callback marks the PaymentIntent as COMPLETED.
|
||||
- auto_approve: All payments succeed immediately (legacy).
|
||||
- simulate_failure: All payments fail with a configurable error message.
|
||||
- simulate_timeout: Payments hang until a configurable timeout then succeed.
|
||||
|
||||
Usage:
|
||||
gateway = MockPaymentGateway(mode="auto_approve")
|
||||
gateway = MockPaymentGateway(mode="simulate_redirect")
|
||||
result = await gateway.create_intent(Decimal("100.00"), "EUR")
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
mode: str = "auto_approve",
|
||||
mode: str = "simulate_redirect",
|
||||
failure_message: str = "Mock payment declined (simulated failure)",
|
||||
timeout_seconds: int = 5,
|
||||
base_url: str = "http://localhost:8000",
|
||||
):
|
||||
"""
|
||||
Initialize the mock gateway.
|
||||
|
||||
Args:
|
||||
mode: Operation mode — "auto_approve", "simulate_failure", or "simulate_timeout".
|
||||
mode: Operation mode — "simulate_redirect" (default), "auto_approve",
|
||||
"simulate_failure", or "simulate_timeout".
|
||||
failure_message: Custom error message for simulate_failure mode.
|
||||
timeout_seconds: Simulated processing delay for simulate_timeout mode.
|
||||
base_url: Base URL for generating mock checkout URLs.
|
||||
"""
|
||||
self.mode = mode
|
||||
self.failure_message = failure_message
|
||||
self.timeout_seconds = timeout_seconds
|
||||
self.base_url = base_url
|
||||
self._processed_intents: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
logger.info(
|
||||
"MockPaymentGateway initialized: mode=%s, timeout=%ds",
|
||||
self.mode, self.timeout_seconds,
|
||||
"MockPaymentGateway initialized: mode=%s, timeout=%ds, base_url=%s",
|
||||
self.mode, self.timeout_seconds, self.base_url,
|
||||
)
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
@@ -80,28 +87,46 @@ class MockPaymentGateway(BasePaymentGateway):
|
||||
"""
|
||||
Create a mock payment intent.
|
||||
|
||||
In auto_approve mode, immediately returns a "completed" intent.
|
||||
In simulate_failure mode, raises PaymentGatewayError.
|
||||
In simulate_timeout mode, logs a warning and returns "processing".
|
||||
Modes:
|
||||
- simulate_redirect (default): For paid amounts (>0), returns a checkout URL
|
||||
with status "requires_action". The frontend redirects the user to this URL.
|
||||
For $0 amounts, falls through to auto_approve.
|
||||
- auto_approve: Immediately returns a "completed" intent.
|
||||
- simulate_failure: Raises PaymentGatewayError.
|
||||
- simulate_timeout: Logs a warning and returns "processing".
|
||||
|
||||
THOUGHT PROCESS:
|
||||
The simulate_redirect mode bridges the gap between "instant success"
|
||||
and a realistic payment flow. The returned checkout_url points to a
|
||||
mock page served by our own backend. When the user clicks "Pay Now",
|
||||
the mock page POSTs to a webhook callback endpoint that finalizes
|
||||
the PaymentIntent. This allows frontend testing of the full redirect
|
||||
→ callback → success lifecycle without Stripe.
|
||||
|
||||
Args:
|
||||
amount: The payment amount.
|
||||
currency: ISO 4217 currency code (default: EUR).
|
||||
metadata: Optional metadata dict.
|
||||
**kwargs: Additional parameters (ignored in mock).
|
||||
**kwargs: Supports 'base_url' override for the checkout URL base.
|
||||
|
||||
Returns:
|
||||
Dict with mock payment intent details.
|
||||
Dict with mock payment intent details:
|
||||
- simulate_redirect: {id, status: "requires_action", checkout_url, ...}
|
||||
- auto_approve: {id, status: "completed", ...}
|
||||
|
||||
Raises:
|
||||
PaymentGatewayError: In simulate_failure mode.
|
||||
"""
|
||||
intent_id = f"mock_intent_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
# ── Strict console log for audit trail ──────────────────────────────
|
||||
logger.info(
|
||||
"Mock create_intent: id=%s amount=%s %s mode=%s",
|
||||
intent_id, amount, currency, self.mode,
|
||||
"[MOCK_PAYMENT_REQUEST] Initiating transaction with external gateway "
|
||||
"for amount: %s %s, mode=%s, intent_id=%s",
|
||||
amount, currency, self.mode, intent_id,
|
||||
)
|
||||
|
||||
# ── simulate_failure: Always fail ───────────────────────────────────
|
||||
if self.mode == "simulate_failure":
|
||||
logger.warning(
|
||||
"Mock payment FAILURE: intent=%s reason='%s'",
|
||||
@@ -109,6 +134,7 @@ class MockPaymentGateway(BasePaymentGateway):
|
||||
)
|
||||
raise PaymentGatewayError(self.failure_message)
|
||||
|
||||
# ── simulate_timeout: Pretend to hang then return "processing" ──────
|
||||
if self.mode == "simulate_timeout":
|
||||
logger.warning(
|
||||
"Mock payment TIMEOUT simulation: intent=%s delay=%ds",
|
||||
@@ -117,19 +143,59 @@ class MockPaymentGateway(BasePaymentGateway):
|
||||
# In a real scenario we'd sleep; here we just return "processing"
|
||||
# so the caller can handle the pending state.
|
||||
|
||||
# ── simulate_redirect: Return a checkout URL for paid tiers ─────────
|
||||
# For $0 amounts, fall through to auto_approve behaviour.
|
||||
if self.mode == "simulate_redirect" and amount > 0:
|
||||
# Use the base_url from kwargs if provided, otherwise use self.base_url
|
||||
base_url = kwargs.get("base_url", self.base_url)
|
||||
|
||||
# Generate the mock checkout page URL — the user will be redirected
|
||||
# here to complete the payment. After clicking "Pay Now", the mock
|
||||
# page POSTs to /billing/mock-payment/callback which updates the
|
||||
# PaymentIntent from PENDING → COMPLETED.
|
||||
checkout_url = f"{base_url}/api/v1/billing/mock-payment/checkout/{intent_id}"
|
||||
|
||||
intent_data = {
|
||||
"id": intent_id,
|
||||
"status": "requires_action",
|
||||
"amount": float(amount),
|
||||
"currency": currency,
|
||||
"checkout_url": checkout_url,
|
||||
"method": "GET", # Frontend opens this URL in a new tab/window
|
||||
"created_at": datetime.utcnow().isoformat(),
|
||||
"completed_at": None,
|
||||
"metadata": metadata or {},
|
||||
"gateway": "mock",
|
||||
}
|
||||
|
||||
self._processed_intents[intent_id] = intent_data
|
||||
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_REDIRECT] Checkout URL generated: intent=%s "
|
||||
"checkout_url=%s amount=%s %s",
|
||||
intent_id, checkout_url, amount, currency,
|
||||
)
|
||||
return intent_data
|
||||
|
||||
# ── auto_approve OR $0 amount: Immediate completion ─────────────────
|
||||
now = datetime.utcnow()
|
||||
intent_data = {
|
||||
"id": intent_id,
|
||||
"status": "completed" if self.mode == "auto_approve" else "processing",
|
||||
"status": "completed",
|
||||
"amount": float(amount),
|
||||
"currency": currency,
|
||||
"created_at": now.isoformat(),
|
||||
"completed_at": now.isoformat() if self.mode == "auto_approve" else None,
|
||||
"completed_at": now.isoformat(),
|
||||
"metadata": metadata or {},
|
||||
"gateway": "mock",
|
||||
}
|
||||
|
||||
self._processed_intents[intent_id] = intent_data
|
||||
|
||||
logger.info(
|
||||
"Mock payment AUTO-APPROVED: intent=%s amount=%s %s",
|
||||
intent_id, amount, currency,
|
||||
)
|
||||
return intent_data
|
||||
|
||||
async def verify_payment(
|
||||
@@ -228,9 +294,10 @@ class MockPaymentGateway(BasePaymentGateway):
|
||||
Change the gateway's operating mode at runtime.
|
||||
|
||||
Args:
|
||||
mode: "auto_approve", "simulate_failure", or "simulate_timeout".
|
||||
mode: "simulate_redirect", "auto_approve", "simulate_failure",
|
||||
or "simulate_timeout".
|
||||
"""
|
||||
valid_modes = {"auto_approve", "simulate_failure", "simulate_timeout"}
|
||||
valid_modes = {"simulate_redirect", "auto_approve", "simulate_failure", "simulate_timeout"}
|
||||
if mode not in valid_modes:
|
||||
raise ValueError(
|
||||
f"Invalid mock mode '{mode}'. Valid modes: {valid_modes}"
|
||||
|
||||
@@ -333,6 +333,14 @@ class SubscriptionService:
|
||||
"valid_from": org_sub.valid_from.isoformat() if org_sub.valid_from else None,
|
||||
"valid_until": org_sub.valid_until.isoformat() if org_sub.valid_until else None,
|
||||
"is_active": org_sub.is_active,
|
||||
# ── P0 AUTO-RENEWAL FIELDS ──
|
||||
"auto_renew": org_sub.auto_renew,
|
||||
"next_renewal_date": org_sub.next_renewal_date.isoformat() if org_sub.next_renewal_date else None,
|
||||
"wallet_auto_deduct": org_sub.wallet_auto_deduct,
|
||||
"renewal_failure_count": org_sub.renewal_failure_count,
|
||||
"provider_subscription_id": org_sub.provider_subscription_id,
|
||||
"renewal": rules.get("renewal", {}),
|
||||
# ── Existing fields ──
|
||||
"allowances": rules.get("allowances", {}),
|
||||
"pricing": rules.get("pricing", {}),
|
||||
"duration": rules.get("duration", {}),
|
||||
@@ -392,6 +400,14 @@ class SubscriptionService:
|
||||
"valid_from": user_sub.valid_from.isoformat() if user_sub.valid_from else None,
|
||||
"valid_until": user_sub.valid_until.isoformat() if user_sub.valid_until else None,
|
||||
"is_active": user_sub.is_active,
|
||||
# ── P0 AUTO-RENEWAL FIELDS ──
|
||||
"auto_renew": user_sub.auto_renew,
|
||||
"next_renewal_date": user_sub.next_renewal_date.isoformat() if user_sub.next_renewal_date else None,
|
||||
"wallet_auto_deduct": user_sub.wallet_auto_deduct,
|
||||
"renewal_failure_count": user_sub.renewal_failure_count,
|
||||
"provider_subscription_id": user_sub.provider_subscription_id,
|
||||
"renewal": rules.get("renewal", {}),
|
||||
# ── Existing fields ──
|
||||
"allowances": rules.get("allowances", {}),
|
||||
"pricing": rules.get("pricing", {}),
|
||||
"duration": rules.get("duration", {}),
|
||||
@@ -471,6 +487,65 @@ class SubscriptionService:
|
||||
|
||||
return visible
|
||||
|
||||
@staticmethod
|
||||
async def is_downgrade(
|
||||
db: AsyncSession,
|
||||
user_id: int,
|
||||
target_tier_id: int,
|
||||
active_org_id: Optional[int] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Determine if switching to the target tier constitutes a downgrade.
|
||||
|
||||
A downgrade is when the target tier's `tier_level` is LESS than the
|
||||
user's CURRENT tier's `tier_level`. Upgrades (same or higher level)
|
||||
should be activated immediately; downgrades should be deferred.
|
||||
|
||||
THOUGHT PROCESS:
|
||||
- Uses `get_user_tier()` which resolves the effective tier from
|
||||
UserSubscription, OrganizationSubscription, or fallback.
|
||||
- Compares integer `tier_level` (0=free, 1=premium, 2=enterprise).
|
||||
- Returns True when target_level < current_level (downgrade).
|
||||
- For equal levels or upgrades, returns False (immediate activation).
|
||||
|
||||
Args:
|
||||
db: Database session.
|
||||
user_id: The user making the change.
|
||||
target_tier_id: The SubscriptionTier ID they want to switch to.
|
||||
active_org_id: Optional org ID to determine subscription context.
|
||||
|
||||
Returns:
|
||||
True if this is a downgrade (should be deferred).
|
||||
False if this is an upgrade or same-level (immediate activation).
|
||||
|
||||
Raises:
|
||||
ValueError: If the target tier does not exist.
|
||||
"""
|
||||
# 1. Get the target tier's level
|
||||
target_stmt = select(SubscriptionTier.tier_level).where(
|
||||
SubscriptionTier.id == target_tier_id
|
||||
)
|
||||
target_result = await db.execute(target_stmt)
|
||||
target_level = target_result.scalar_one_or_none()
|
||||
|
||||
if target_level is None:
|
||||
raise ValueError(f"SubscriptionTier with id={target_tier_id} not found")
|
||||
|
||||
# 2. Get the current effective tier level via the existing resolver
|
||||
current_tier_name = await SubscriptionService.get_user_tier(db, user_id)
|
||||
current_level = SubscriptionService._get_user_level(current_tier_name)
|
||||
|
||||
# 3. Compare: downgrade if target < current
|
||||
is_down = target_level < current_level
|
||||
|
||||
logger.info(
|
||||
"Downgrade check: user_id=%d target_tier_id=%d "
|
||||
"current_level=%d target_level=%d is_downgrade=%s",
|
||||
user_id, target_tier_id, current_level, target_level, is_down,
|
||||
)
|
||||
|
||||
return is_down
|
||||
|
||||
@staticmethod
|
||||
def require_tier(user_tier: str, required_feature_or_min_tier: str) -> bool:
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user