pénzügyi modul továbbfejlesztése (csomagkezelés)
This commit is contained in:
@@ -256,8 +256,15 @@ async def get_user_vehicles(
|
||||
# Use a raw SQL expression for JSONB boolean ordering
|
||||
order_expr = text("(individual_equipment->>'is_primary')::boolean DESC NULLS LAST")
|
||||
|
||||
if current_user.scope_id is None:
|
||||
# Personal mode: show vehicles in organizations where user is a member
|
||||
# P0 BUGFIX (2026-07-28): Staff users (ADMIN, SUPERADMIN, MODERATOR, etc.)
|
||||
# should NOT enter corporate mode even if scope_id is set. They need to
|
||||
# see vehicles through the personal/org membership path.
|
||||
staff_roles = {'SUPERADMIN', 'ADMIN', 'MODERATOR', 'SALES_REP', 'SERVICE_MGR'}
|
||||
current_role = current_user.role.upper() if current_user.role else ''
|
||||
is_staff_user = current_role in staff_roles
|
||||
|
||||
if current_user.scope_id is None or is_staff_user:
|
||||
# Personal mode OR staff user: show vehicles in organizations where user is a member
|
||||
org_stmt = select(OrganizationMember.organization_id).where(
|
||||
OrganizationMember.user_id == current_user.id
|
||||
)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Request, Header, Query
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Request, Header, Query, Form
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, func, and_
|
||||
from typing import Optional, Dict, Any, List
|
||||
import logging
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
from app.api.deps import get_db, get_current_user
|
||||
from app.models.identity import User, Wallet, UserRole
|
||||
@@ -13,6 +15,8 @@ from app.services.config_service import config
|
||||
from app.services.payment_router import PaymentRouter
|
||||
from app.services.stripe_adapter import stripe_adapter
|
||||
from app.services.billing_engine import upgrade_subscription, get_user_balance
|
||||
from app.services.subscription_activator import SubscriptionActivator
|
||||
from app.core.config import settings
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -407,3 +411,302 @@ async def get_wallet_transactions(
|
||||
except Exception as e:
|
||||
logger.error(f"Tranzakció történet lekérdezési hiba: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Belső hiba: {str(e)}")
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Mock Payment Gateway — Checkout Page & Webhook Callback (Phase 2)
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
#
|
||||
# THOUGHT PROCESS:
|
||||
# These two endpoints simulate a real payment gateway lifecycle:
|
||||
#
|
||||
# 1. GET /mock-payment/checkout/{intent_id}
|
||||
# Displays a simple HTML page with "Pay Now" button.
|
||||
# The user sees an amount and clicks to confirm payment.
|
||||
# This is the URL returned as `checkout_url` by MockPaymentGateway
|
||||
# in `simulate_redirect` mode.
|
||||
#
|
||||
# 2. POST /mock-payment/callback
|
||||
# Simulates the webhook callback that a real payment gateway
|
||||
# (like Stripe) would send after successful payment.
|
||||
# Updates PaymentIntent PENDING → COMPLETED and activates
|
||||
# the subscription using the metadata stored by FinancialManager.
|
||||
#
|
||||
# Together, these allow frontend testing of the full payment flow:
|
||||
# purchase → redirect → pay → callback → activate subscription
|
||||
# without requiring real Stripe integration.
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.get("/mock-payment/checkout/{intent_id}")
|
||||
async def mock_checkout_page(
|
||||
intent_id: str,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Mock payment checkout page.
|
||||
|
||||
Displays a simple HTML page showing the payment amount and a "Pay Now"
|
||||
button. When the user clicks the button, it POSTs to the mock callback
|
||||
endpoint which finalizes the PaymentIntent and activates the subscription.
|
||||
|
||||
This simulates redirecting the user to a banking/payment portal.
|
||||
|
||||
Args:
|
||||
intent_id: The mock gateway intent ID (stored as stripe_session_id).
|
||||
db: Database session.
|
||||
|
||||
Returns:
|
||||
HTMLResponse with a styled mock checkout page, or 404 if not found.
|
||||
"""
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_CHECKOUT] Page requested for intent: %s",
|
||||
intent_id,
|
||||
)
|
||||
|
||||
# Look up the PaymentIntent by stripe_session_id (= gateway intent_id)
|
||||
stmt = select(PaymentIntent).where(
|
||||
PaymentIntent.stripe_session_id == intent_id,
|
||||
PaymentIntent.status == PaymentIntentStatus.PENDING,
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
payment_intent = result.scalar_one_or_none()
|
||||
|
||||
if not payment_intent:
|
||||
logger.warning(
|
||||
"[MOCK_PAYMENT_CHECKOUT] PaymentIntent not found or not PENDING: "
|
||||
"intent_id=%s", intent_id,
|
||||
)
|
||||
return HTMLResponse(
|
||||
content="<h1>Payment not found or already processed</h1>",
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
amount = float(payment_intent.gross_amount)
|
||||
currency = payment_intent.currency
|
||||
|
||||
# Determine the callback URL: POST back to the same origin
|
||||
callback_url = f"/api/v1/billing/mock-payment/callback"
|
||||
|
||||
# Simple but styled HTML checkout page
|
||||
html_content = f"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Mock Payment Gateway</title>
|
||||
<style>
|
||||
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
|
||||
body {{
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
display: flex; justify-content: center; align-items: center;
|
||||
min-height: 100vh; padding: 20px;
|
||||
}}
|
||||
.card {{
|
||||
background: white; border-radius: 16px; padding: 40px;
|
||||
max-width: 420px; width: 100%; box-shadow: 0 20px 60px rgba(0,0,0,0.3);
|
||||
text-align: center;
|
||||
}}
|
||||
.card h1 {{ font-size: 24px; color: #1a1a2e; margin-bottom: 8px; }}
|
||||
.card .subtitle {{ color: #666; font-size: 14px; margin-bottom: 24px; }}
|
||||
.amount {{
|
||||
font-size: 48px; font-weight: 700; color: #1a1a2e;
|
||||
margin: 20px 0; padding: 20px 0;
|
||||
border-top: 2px solid #f0f0f0; border-bottom: 2px solid #f0f0f0;
|
||||
}}
|
||||
.amount .currency {{ font-size: 24px; color: #666; }}
|
||||
.details {{ text-align: left; margin: 20px 0; padding: 16px; background: #f8f9fa; border-radius: 8px; }}
|
||||
.details dt {{ font-size: 12px; color: #999; text-transform: uppercase; letter-spacing: 0.5px; }}
|
||||
.details dd {{ font-size: 14px; color: #333; margin-bottom: 8px; }}
|
||||
.btn-pay {{
|
||||
display: inline-block; padding: 14px 48px; margin-top: 16px;
|
||||
background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
|
||||
color: white; border: none; border-radius: 8px;
|
||||
font-size: 18px; font-weight: 600; cursor: pointer;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
width: 100%;
|
||||
}}
|
||||
.btn-pay:hover {{ transform: translateY(-2px); box-shadow: 0 8px 24px rgba(34,197,94,0.4); }}
|
||||
.btn-pay:active {{ transform: translateY(0); }}
|
||||
.footer {{ margin-top: 20px; font-size: 12px; color: #999; }}
|
||||
.badge {{
|
||||
display: inline-block; padding: 4px 12px; border-radius: 20px;
|
||||
background: #fef3c7; color: #92400e; font-size: 12px; font-weight: 500;
|
||||
margin-bottom: 16px;
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<div class="badge">🧪 Mock Gateway — Development Mode</div>
|
||||
<h1>Complete Your Payment</h1>
|
||||
<p class="subtitle">This is a simulated payment page for testing</p>
|
||||
|
||||
<div class="amount">
|
||||
{amount:.2f} <span class="currency">{currency}</span>
|
||||
</div>
|
||||
|
||||
<dl class="details">
|
||||
<dt>Intent ID</dt>
|
||||
<dd>{intent_id[:20]}...</dd>
|
||||
<dt>Description</dt>
|
||||
<dd>Subscription Package Purchase</dd>
|
||||
</dl>
|
||||
|
||||
<form action="{callback_url}" method="POST">
|
||||
<input type="hidden" name="intent_id" value="{intent_id}">
|
||||
<button type="submit" class="btn-pay">
|
||||
✅ Pay {amount:.2f} {currency}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p class="footer">
|
||||
🔒 Connection simulated • No real payment will be charged
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_CHECKOUT] Serving checkout page: intent=%s amount=%.2f %s",
|
||||
intent_id, amount, currency,
|
||||
)
|
||||
|
||||
return HTMLResponse(content=html_content)
|
||||
|
||||
|
||||
@router.post("/mock-payment/callback")
|
||||
async def mock_payment_callback(
|
||||
intent_id: str = Form(...),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Mock payment gateway callback (webhook simulation).
|
||||
|
||||
Simulates the webhook that a real payment gateway would send after
|
||||
successful payment. This endpoint:
|
||||
|
||||
1. Looks up the PENDING PaymentIntent by gateway intent_id
|
||||
2. Updates it to COMPLETED
|
||||
3. Activates the subscription using stored metadata (tier_id, user_id, org_id)
|
||||
4. Returns a redirect to the frontend success page (or JSON response)
|
||||
|
||||
Args:
|
||||
intent_id: The mock gateway intent ID (Form field).
|
||||
db: Database session.
|
||||
|
||||
Returns:
|
||||
RedirectResponse to the frontend success URL, or JSONResponse if
|
||||
the frontend URL is not configured.
|
||||
"""
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_CALLBACK] Received callback for intent: %s",
|
||||
intent_id,
|
||||
)
|
||||
|
||||
# ── Step 1: Look up the PaymentIntent ─────────────────────────────────
|
||||
stmt = select(PaymentIntent).where(
|
||||
PaymentIntent.stripe_session_id == intent_id,
|
||||
PaymentIntent.status == PaymentIntentStatus.PENDING,
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
payment_intent = result.scalar_one_or_none()
|
||||
|
||||
if not payment_intent:
|
||||
logger.warning(
|
||||
"[MOCK_PAYMENT_CALLBACK] PaymentIntent not found or not PENDING: "
|
||||
"intent_id=%s", intent_id,
|
||||
)
|
||||
return JSONResponse(
|
||||
{"error": "PaymentIntent not found or not PENDING"},
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_CALLBACK] PaymentIntent found: id=%d amount=%.2f %s",
|
||||
payment_intent.id,
|
||||
float(payment_intent.gross_amount),
|
||||
payment_intent.currency,
|
||||
)
|
||||
|
||||
# ── Step 2: Update PaymentIntent to COMPLETED ─────────────────────────
|
||||
payment_intent.status = PaymentIntentStatus.COMPLETED
|
||||
payment_intent.completed_at = datetime.utcnow()
|
||||
|
||||
# ── Step 3: Activate the subscription ─────────────────────────────────
|
||||
# Read the purchase context from metadata (stored by FinancialManager)
|
||||
meta = payment_intent.meta_data or {}
|
||||
tier_id = meta.get("tier_id")
|
||||
user_id = meta.get("user_id")
|
||||
org_id = meta.get("org_id")
|
||||
duration_days = meta.get("duration_days")
|
||||
|
||||
subscription_id = None
|
||||
if tier_id and user_id:
|
||||
activator = SubscriptionActivator()
|
||||
try:
|
||||
if org_id:
|
||||
org_sub = await activator.activate_org_subscription(
|
||||
db=db, org_id=int(org_id), tier_id=int(tier_id),
|
||||
duration_days=int(duration_days) if duration_days else None,
|
||||
)
|
||||
subscription_id = org_sub.id
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_CALLBACK] Org subscription activated: "
|
||||
"org_id=%s sub_id=%d", org_id, org_sub.id,
|
||||
)
|
||||
else:
|
||||
user_sub = await activator.activate_user_subscription(
|
||||
db=db, user_id=int(user_id), tier_id=int(tier_id),
|
||||
duration_days=int(duration_days) if duration_days else None,
|
||||
)
|
||||
subscription_id = user_sub.id
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_CALLBACK] User subscription activated: "
|
||||
"user_id=%s sub_id=%d", user_id, user_sub.id,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[MOCK_PAYMENT_CALLBACK] Subscription activation failed: %s",
|
||||
str(e),
|
||||
)
|
||||
# Don't fail the callback — the PaymentIntent is already COMPLETED
|
||||
# The subscription can be activated manually or via retry logic
|
||||
else:
|
||||
logger.warning(
|
||||
"[MOCK_PAYMENT_CALLBACK] Missing tier_id or user_id in metadata. "
|
||||
"Subscription was NOT activated. metadata=%s", meta,
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_CALLBACK] Payment completed successfully: "
|
||||
"intent=%s, payment_intent_id=%d, amount=%.2f %s, "
|
||||
"subscription_id=%s",
|
||||
intent_id, payment_intent.id,
|
||||
float(payment_intent.gross_amount), payment_intent.currency,
|
||||
subscription_id,
|
||||
)
|
||||
|
||||
# ── Step 4: Redirect to frontend ──────────────────────────────────────
|
||||
# In production, redirect to the frontend success page.
|
||||
# If FRONTEND_URL is not configured, return JSON.
|
||||
frontend_url = getattr(settings, "FRONTEND_URL", None) or getattr(config, "FRONTEND_URL", None)
|
||||
if frontend_url:
|
||||
redirect_url = f"{frontend_url}/dashboard/subscription?payment=success"
|
||||
logger.info(
|
||||
"[MOCK_PAYMENT_CALLBACK] Redirecting to frontend: %s",
|
||||
redirect_url,
|
||||
)
|
||||
return RedirectResponse(url=redirect_url, status_code=302)
|
||||
|
||||
# Fallback: return JSON response
|
||||
return JSONResponse({
|
||||
"success": True,
|
||||
"payment_intent_id": payment_intent.id,
|
||||
"transaction_id": str(payment_intent.transaction_id) if payment_intent.transaction_id else None,
|
||||
"subscription_id": subscription_id,
|
||||
"message": "Payment completed successfully",
|
||||
})
|
||||
|
||||
@@ -42,7 +42,15 @@ def get_financial_manager() -> FinancialManager:
|
||||
"""
|
||||
Dependency that provides a configured FinancialManager instance.
|
||||
|
||||
Currently uses MockPaymentGateway as default. To switch to Stripe:
|
||||
Uses MockPaymentGateway in simulate_redirect mode as default.
|
||||
In this mode, paid tiers (> 0 EUR) generate a checkout URL;
|
||||
the frontend redirects the user to a mock payment page, and a
|
||||
webhook callback (POST /billing/mock-payment/callback) finalizes
|
||||
the payment and activates the subscription.
|
||||
|
||||
Free tiers ($0) bypass payment entirely and are activated immediately.
|
||||
|
||||
To switch to Stripe:
|
||||
from app.services.stripe_adapter import StripeAdapter
|
||||
return FinancialManager(payment_gateway=StripeAdapter())
|
||||
|
||||
@@ -50,7 +58,7 @@ def get_financial_manager() -> FinancialManager:
|
||||
A FinancialManager instance with the configured payment gateway.
|
||||
"""
|
||||
return FinancialManager(
|
||||
payment_gateway=MockPaymentGateway(mode="auto_approve"),
|
||||
payment_gateway=MockPaymentGateway(mode="simulate_redirect"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -139,28 +139,61 @@ async def get_public_subscriptions(
|
||||
**Szabály:**
|
||||
- Csak azokat a csomagokat adja vissza, ahol a `rules.lifecycle.is_public` = true
|
||||
(JSONB mező alapján szűrve). Ha a mező hiányzik, alapértelmezés szerint publikus.
|
||||
- Defense-in-Depth: A `rules.type` mező alapján szűrjük a csomagokat a felhasználó
|
||||
aktuális kontextusa szerint. Ha a user aktív szervezete `individual` típusú (vagy
|
||||
nincs aktív szervezet), csak `private`/`consumer` típusú csomagokat adunk vissza.
|
||||
Ha a szervezet business típusú, csak `corporate`/`business` típusú csomagokat.
|
||||
- Minden csomaghoz tartozik egy `resolved_pricing` mező, amely a felhasználó
|
||||
országkódja alapján feloldott árazást tartalmazza.
|
||||
- A frontend tovább szűrhet a `name` mező alapján (private_ vs corp_ előtag).
|
||||
"""
|
||||
# 1. Determine user's country code
|
||||
country_code = await get_user_country_code(current_user, db)
|
||||
|
||||
# 2. Fetch all public tiers
|
||||
# 2. Determine if user is in corporate context (defense-in-depth)
|
||||
active_org_id = getattr(current_user, "active_organization_id", None)
|
||||
is_corporate = False
|
||||
if active_org_id:
|
||||
org_type_stmt = select(Organization.org_type).where(
|
||||
Organization.id == active_org_id,
|
||||
Organization.is_deleted == False,
|
||||
)
|
||||
org_type_result = await db.execute(org_type_stmt)
|
||||
org_type = org_type_result.scalar_one_or_none()
|
||||
if org_type and org_type != "individual":
|
||||
is_corporate = True
|
||||
|
||||
# 3. Fetch all public tiers (filter out non-public at SQL level)
|
||||
stmt = (
|
||||
select(SubscriptionTier)
|
||||
.where(
|
||||
# Only show tiers where lifecycle.is_public is NOT explicitly 'false'
|
||||
# Using SQLAlchemy JSONB path query (same approach as admin_packages.py line 134)
|
||||
~SubscriptionTier.rules["lifecycle"]["is_public"].as_string().in_(["false"])
|
||||
)
|
||||
.order_by(SubscriptionTier.id)
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
tiers = result.scalars().all()
|
||||
|
||||
# 3. Build response with resolved pricing
|
||||
# 4. Build response with resolved pricing and type filtering
|
||||
response: List[PublicSubscriptionTierResponse] = []
|
||||
for t in tiers:
|
||||
rules = t.rules or {}
|
||||
if not rules.get("lifecycle", {}).get("is_public", True):
|
||||
continue
|
||||
|
||||
# Defense-in-Depth: Filter by target audience type
|
||||
rules_type = rules.get("type", None)
|
||||
if rules_type:
|
||||
if is_corporate:
|
||||
# In corporate context: only show corporate/business packages
|
||||
if rules_type not in ("corporate", "business"):
|
||||
continue
|
||||
else:
|
||||
# In private context: only show private/consumer packages
|
||||
if rules_type in ("corporate", "business"):
|
||||
continue
|
||||
|
||||
# Resolve pricing for this user's country
|
||||
resolved = resolve_pricing(rules, country_code)
|
||||
resolved_pricing = None
|
||||
@@ -253,12 +286,57 @@ async def get_my_subscription(
|
||||
user_tier = await SubscriptionService.get_user_tier(db, user_id)
|
||||
feature_flags = await SubscriptionService.get_user_feature_flags(db, user_id)
|
||||
|
||||
# ── P0 PENDING DOWNGRADE FIELDS (Issue #429) ──
|
||||
# Check if there's a pending downgrade on the current subscription
|
||||
has_pending_downgrade = False
|
||||
pending_tier_name = None
|
||||
pending_effective_date = None
|
||||
|
||||
if subscription_data:
|
||||
pending_sub = None
|
||||
if source == "organization" and active_org_id:
|
||||
pending_stmt = select(OrganizationSubscription).options(
|
||||
selectinload(OrganizationSubscription.pending_tier)
|
||||
).where(
|
||||
OrganizationSubscription.org_id == active_org_id,
|
||||
OrganizationSubscription.is_active == True,
|
||||
OrganizationSubscription.pending_tier_id.is_not(None),
|
||||
).order_by(OrganizationSubscription.id.desc()).limit(1)
|
||||
pending_result = await db.execute(pending_stmt)
|
||||
pending_sub = pending_result.scalar_one_or_none()
|
||||
elif source == "user":
|
||||
pending_stmt = select(UserSubscription).options(
|
||||
selectinload(UserSubscription.pending_tier)
|
||||
).where(
|
||||
UserSubscription.user_id == user_id,
|
||||
UserSubscription.is_active == True,
|
||||
UserSubscription.pending_tier_id.is_not(None),
|
||||
).order_by(UserSubscription.id.desc()).limit(1)
|
||||
pending_result = await db.execute(pending_stmt)
|
||||
pending_sub = pending_result.scalar_one_or_none()
|
||||
|
||||
if pending_sub and pending_sub.pending_tier:
|
||||
has_pending_downgrade = True
|
||||
pt = pending_sub.pending_tier
|
||||
pending_tier_name = (
|
||||
pt.rules.get("display_name", pt.name)
|
||||
if pt.rules else pt.name
|
||||
)
|
||||
pending_effective_date = (
|
||||
pending_sub.valid_until.isoformat()
|
||||
if pending_sub.valid_until else None
|
||||
)
|
||||
|
||||
return {
|
||||
"subscription": subscription_data,
|
||||
"tier": user_tier,
|
||||
"features": feature_flags.get("features", {}),
|
||||
"expires_at": feature_flags.get("expires_at"),
|
||||
"source": source,
|
||||
# ── P0 Pending downgrade fields ──
|
||||
"has_pending_downgrade": has_pending_downgrade,
|
||||
"pending_tier_name": pending_tier_name,
|
||||
"pending_effective_date": pending_effective_date,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -42,6 +42,155 @@ class NetworkResponse(BaseModel):
|
||||
level3: List[NetworkMemberL2L3]
|
||||
|
||||
|
||||
async def _resolve_subscription_data(
|
||||
db: AsyncSession,
|
||||
user: User,
|
||||
active_org_id: Optional[int] = None,
|
||||
) -> dict:
|
||||
"""
|
||||
P0 BUGFIX (2026-07-28): Unified subscription resolution shared by /auth/me and /users/me.
|
||||
|
||||
Resolves the user's real subscription limits (max_vehicles, max_garages),
|
||||
display_name, expiry, auto-renewal fields, and active add-ons from the
|
||||
assigned subscription_tier JSONB rules.
|
||||
|
||||
Resolution order:
|
||||
1. Org-level subscription (OrganizationSubscription) if active_org_id is set
|
||||
2. User-level subscription (UserSubscription) fallback
|
||||
3. Organization.base_asset_limit as ultimate fallback
|
||||
|
||||
Returns a dict with all subscription-related fields ready to merge into
|
||||
the user response.
|
||||
"""
|
||||
from app.models.core_logic import SubscriptionTier, OrganizationSubscription, UserSubscription
|
||||
from app.models.marketplace.organization import Organization
|
||||
|
||||
tier: Optional[SubscriptionTier] = None
|
||||
subscription_record = None
|
||||
|
||||
# Step 1: Try org-level subscription first
|
||||
if active_org_id is not None:
|
||||
org_sub_stmt = (
|
||||
select(OrganizationSubscription)
|
||||
.where(
|
||||
OrganizationSubscription.org_id == active_org_id,
|
||||
OrganizationSubscription.is_active == True,
|
||||
)
|
||||
.order_by(OrganizationSubscription.valid_from.desc())
|
||||
.limit(1)
|
||||
)
|
||||
subscription_record = (await db.execute(org_sub_stmt)).scalar_one_or_none()
|
||||
if subscription_record and subscription_record.tier_id:
|
||||
tier = await db.get(SubscriptionTier, subscription_record.tier_id)
|
||||
|
||||
# Step 2: Fall back to user-level subscription (runs even when active_org_id is set)
|
||||
if subscription_record is None:
|
||||
user_sub_stmt = (
|
||||
select(UserSubscription)
|
||||
.where(
|
||||
UserSubscription.user_id == user.id,
|
||||
UserSubscription.is_active == True,
|
||||
)
|
||||
.order_by(UserSubscription.valid_from.desc())
|
||||
.limit(1)
|
||||
)
|
||||
subscription_record = (await db.execute(user_sub_stmt)).scalar_one_or_none()
|
||||
if subscription_record and subscription_record.tier_id:
|
||||
tier = await db.get(SubscriptionTier, subscription_record.tier_id)
|
||||
|
||||
# Step 3: Extract limits from the resolved tier or fall back
|
||||
max_vehicles = 1
|
||||
max_garages = 1
|
||||
if tier and tier.rules:
|
||||
allowances = tier.rules.get("allowances", {})
|
||||
max_vehicles = int(allowances.get("max_vehicles", 1))
|
||||
max_garages = int(allowances.get("max_garages", 1))
|
||||
elif active_org_id is not None:
|
||||
org_stmt = select(Organization).where(Organization.id == active_org_id)
|
||||
org = (await db.execute(org_stmt)).scalar_one_or_none()
|
||||
if org:
|
||||
max_vehicles = org.base_asset_limit or 1
|
||||
max_garages = 1
|
||||
|
||||
# Step 4: Extract metadata from the resolved subscription record
|
||||
subscription_display_name: Optional[str] = None
|
||||
subscription_valid_until: Optional[datetime] = None
|
||||
subscription_tier_id: Optional[int] = None
|
||||
subscription_valid_from: Optional[datetime] = None
|
||||
subscription_auto_renew: bool = False
|
||||
subscription_next_renewal_date: Optional[datetime] = None
|
||||
subscription_wallet_auto_deduct: bool = False
|
||||
|
||||
if subscription_record is not None:
|
||||
subscription_valid_until = subscription_record.valid_until
|
||||
subscription_tier_id = subscription_record.tier_id
|
||||
subscription_valid_from = subscription_record.valid_from
|
||||
subscription_auto_renew = getattr(subscription_record, 'auto_renew', False)
|
||||
subscription_next_renewal_date = getattr(subscription_record, 'next_renewal_date', None)
|
||||
subscription_wallet_auto_deduct = getattr(subscription_record, 'wallet_auto_deduct', False)
|
||||
|
||||
# Resolve display_name from the resolved tier
|
||||
if tier and tier.rules:
|
||||
subscription_display_name = tier.rules.get("display_name", None)
|
||||
|
||||
# Step 5: Resolve active add-on subscriptions
|
||||
active_addons: List[Dict[str, Any]] = []
|
||||
if active_org_id is not None:
|
||||
addon_stmt = (
|
||||
select(OrganizationSubscription, SubscriptionTier)
|
||||
.join(SubscriptionTier, OrganizationSubscription.tier_id == SubscriptionTier.id)
|
||||
.where(
|
||||
OrganizationSubscription.org_id == active_org_id,
|
||||
OrganizationSubscription.is_active == True,
|
||||
SubscriptionTier.type == 'addon',
|
||||
)
|
||||
.order_by(OrganizationSubscription.valid_from.desc())
|
||||
)
|
||||
addon_result = await db.execute(addon_stmt)
|
||||
for sub, tier_row in addon_result:
|
||||
active_addons.append({
|
||||
"tier_id": tier_row.id,
|
||||
"display_name": tier_row.rules.get("display_name", tier_row.name) if tier_row.rules else tier_row.name,
|
||||
"valid_from": sub.valid_from.isoformat() if sub.valid_from else None,
|
||||
"valid_until": sub.valid_until.isoformat() if sub.valid_until else None,
|
||||
"is_active": sub.is_active,
|
||||
})
|
||||
else:
|
||||
addon_stmt = (
|
||||
select(UserSubscription, SubscriptionTier)
|
||||
.join(SubscriptionTier, UserSubscription.tier_id == SubscriptionTier.id)
|
||||
.where(
|
||||
UserSubscription.user_id == user.id,
|
||||
UserSubscription.is_active == True,
|
||||
SubscriptionTier.type == 'addon',
|
||||
)
|
||||
.order_by(UserSubscription.valid_from.desc())
|
||||
)
|
||||
addon_result = await db.execute(addon_stmt)
|
||||
for sub, tier_row in addon_result:
|
||||
active_addons.append({
|
||||
"tier_id": tier_row.id,
|
||||
"display_name": tier_row.rules.get("display_name", tier_row.name) if tier_row.rules else tier_row.name,
|
||||
"valid_from": sub.valid_from.isoformat() if sub.valid_from else None,
|
||||
"valid_until": sub.valid_until.isoformat() if sub.valid_until else None,
|
||||
"is_active": sub.is_active,
|
||||
})
|
||||
|
||||
return {
|
||||
"max_vehicles": max_vehicles,
|
||||
"max_garages": max_garages,
|
||||
"subscription_display_name": subscription_display_name,
|
||||
"subscription_expires_at": subscription_valid_until.isoformat() if subscription_valid_until else None,
|
||||
"subscription_tier_id": subscription_tier_id,
|
||||
"subscription_valid_from": subscription_valid_from.isoformat() if subscription_valid_from else None,
|
||||
"subscription_auto_renew": subscription_auto_renew,
|
||||
"subscription_next_renewal_date": subscription_next_renewal_date.isoformat() if subscription_next_renewal_date else None,
|
||||
"subscription_wallet_auto_deduct": subscription_wallet_auto_deduct,
|
||||
"active_addons": active_addons,
|
||||
"subscription_plan": user.subscription_plan,
|
||||
}
|
||||
|
||||
|
||||
async def _build_user_response(user: User, active_org_id: Optional[int] = None, db: Optional[AsyncSession] = None) -> dict:
|
||||
"""
|
||||
Segédfüggvény a UserResponse dict előállításához.
|
||||
@@ -113,10 +262,26 @@ async def _build_user_response(user: User, active_org_id: Optional[int] = None,
|
||||
if db is not None:
|
||||
pass
|
||||
|
||||
# ── P0: Resolve subscription limits ──
|
||||
# Default fallback values
|
||||
max_vehicles = 1
|
||||
max_garages = 1
|
||||
# ── P0: Resolve subscription limits via shared function ──
|
||||
# P0 BUGFIX (2026-07-28): Previously hardcoded max_vehicles=1 / max_garages=1.
|
||||
# Now uses _resolve_subscription_data() which queries the actual subscription_tier
|
||||
# JSONB rules. This fixes both /auth/me and /users/me endpoints in one place.
|
||||
if db is not None:
|
||||
sub_data = await _resolve_subscription_data(db, user, active_org_id)
|
||||
else:
|
||||
sub_data = {
|
||||
"max_vehicles": 1,
|
||||
"max_garages": 1,
|
||||
"subscription_display_name": None,
|
||||
"subscription_expires_at": None,
|
||||
"subscription_tier_id": None,
|
||||
"subscription_valid_from": None,
|
||||
"subscription_auto_renew": False,
|
||||
"subscription_next_renewal_date": None,
|
||||
"subscription_wallet_auto_deduct": False,
|
||||
"active_addons": [],
|
||||
"subscription_plan": user.subscription_plan,
|
||||
}
|
||||
|
||||
return {
|
||||
"id": user.id,
|
||||
@@ -127,9 +292,19 @@ async def _build_user_response(user: User, active_org_id: Optional[int] = None,
|
||||
"region_code": user.region_code,
|
||||
"person_id": user.person_id,
|
||||
"role": role_key,
|
||||
"subscription_plan": user.subscription_plan,
|
||||
"max_vehicles": max_vehicles,
|
||||
"max_garages": max_garages,
|
||||
"subscription_plan": sub_data["subscription_plan"],
|
||||
"max_vehicles": sub_data["max_vehicles"],
|
||||
"max_garages": sub_data["max_garages"],
|
||||
"subscription_display_name": sub_data["subscription_display_name"],
|
||||
"subscription_expires_at": sub_data["subscription_expires_at"],
|
||||
"subscription_tier_id": sub_data["subscription_tier_id"],
|
||||
"subscription_valid_from": sub_data["subscription_valid_from"],
|
||||
"subscription_auto_renew": sub_data["subscription_auto_renew"],
|
||||
"subscription_next_renewal_date": sub_data["subscription_next_renewal_date"],
|
||||
"subscription_wallet_auto_deduct": sub_data["subscription_wallet_auto_deduct"],
|
||||
"active_addons": sub_data["active_addons"],
|
||||
"user_registration_date": user.created_at.isoformat() if user.created_at else None,
|
||||
"created_at": user.created_at.isoformat() if user.created_at else None,
|
||||
"scope_level": user.scope_level or "individual",
|
||||
"scope_id": str(active_org_id) if active_org_id else None,
|
||||
"ui_mode": user.ui_mode or "personal",
|
||||
@@ -204,60 +379,21 @@ async def read_users_me(
|
||||
is_last_admin = await AuthService.check_is_last_admin(db, current_user.id)
|
||||
|
||||
# ── P0: Resolve real subscription limits from the assigned tier ──
|
||||
from app.models.core_logic import SubscriptionTier, OrganizationSubscription, UserSubscription
|
||||
max_vehicles = 1
|
||||
max_garages = 1
|
||||
|
||||
if active_org_id is not None:
|
||||
# Try org-level subscription first
|
||||
org_sub_stmt = (
|
||||
select(SubscriptionTier)
|
||||
.select_from(OrganizationSubscription)
|
||||
.join(SubscriptionTier, OrganizationSubscription.tier_id == SubscriptionTier.id)
|
||||
.where(
|
||||
OrganizationSubscription.org_id == active_org_id,
|
||||
OrganizationSubscription.is_active == True
|
||||
)
|
||||
.order_by(OrganizationSubscription.valid_from.desc())
|
||||
.limit(1)
|
||||
)
|
||||
tier = (await db.execute(org_sub_stmt)).scalar_one_or_none()
|
||||
if tier and tier.rules:
|
||||
allowances = tier.rules.get("allowances", {})
|
||||
max_vehicles = int(allowances.get("max_vehicles", 1))
|
||||
max_garages = int(allowances.get("max_garages", 1))
|
||||
else:
|
||||
# Fallback: read base_asset_limit from Organization record
|
||||
org_stmt = select(Organization).where(Organization.id == active_org_id)
|
||||
org = (await db.execute(org_stmt)).scalar_one_or_none()
|
||||
if org:
|
||||
max_vehicles = org.base_asset_limit or 1
|
||||
max_garages = 1 # No base_garage_limit column, default to 1
|
||||
else:
|
||||
# Personal mode: try user-level subscription
|
||||
user_sub_stmt = (
|
||||
select(SubscriptionTier)
|
||||
.select_from(UserSubscription)
|
||||
.join(SubscriptionTier, UserSubscription.tier_id == SubscriptionTier.id)
|
||||
.where(
|
||||
UserSubscription.user_id == current_user.id,
|
||||
UserSubscription.is_active == True
|
||||
)
|
||||
.order_by(UserSubscription.valid_from.desc())
|
||||
.limit(1)
|
||||
)
|
||||
tier = (await db.execute(user_sub_stmt)).scalar_one_or_none()
|
||||
if tier and tier.rules:
|
||||
allowances = tier.rules.get("allowances", {})
|
||||
max_vehicles = int(allowances.get("max_vehicles", 1))
|
||||
max_garages = int(allowances.get("max_garages", 1))
|
||||
# P0 BUGFIX (2026-07-28): Uses the shared _resolve_subscription_data() function
|
||||
# instead of duplicating the subscription resolution logic inline.
|
||||
# This fixes both /auth/me and /users/me in one place.
|
||||
#
|
||||
# _build_user_response() already calls _resolve_subscription_data() internally,
|
||||
# so _build_user_response now returns all subscription fields (max_vehicles,
|
||||
# subscription_display_name, etc.) in the base response. We just need to
|
||||
# override is_last_admin and org_capabilities post-build.
|
||||
sub_data = await _resolve_subscription_data(db, current_user, active_org_id)
|
||||
|
||||
# ── RBAC Phase 3: Build base response ──
|
||||
# P0 Phase 6: Pass db so system_capabilities gets populated from DB
|
||||
response_data = await _build_user_response(current_user, active_org_id, db)
|
||||
response_data["is_last_admin"] = is_last_admin
|
||||
response_data["max_vehicles"] = max_vehicles
|
||||
response_data["max_garages"] = max_garages
|
||||
# All subscription fields are already in response_data from _build_user_response
|
||||
|
||||
# ── RBAC Phase 3: Resolve org_capabilities ──
|
||||
# Get all organizations the user is a member of
|
||||
|
||||
Reference in New Issue
Block a user