Refactor subcription layer

This commit is contained in:
Urtzi Alfaro
2026-01-11 21:40:04 +01:00
parent 54163843ec
commit 55bb1c6451
7 changed files with 1369 additions and 300 deletions

View File

@@ -1095,139 +1095,6 @@ async def register_with_subscription(
detail="Failed to register with subscription"
)
@router.post(route_builder.build_base_route("subscriptions/{tenant_id}/cancel", include_tenant_prefix=False))
async def cancel_subscription(
tenant_id: UUID = Path(..., description="Tenant ID"),
current_user: Dict[str, Any] = Depends(get_current_user_dep),
payment_service: PaymentService = Depends(get_payment_service)
):
"""Cancel subscription for a tenant"""
try:
# Verify user is owner/admin of tenant
user_id = current_user.get('user_id')
user_role = current_user.get('role', '').lower()
# Check if user is tenant owner or admin
from app.services.tenant_service import EnhancedTenantService
from shared.database.base import create_database_manager
tenant_service = EnhancedTenantService(create_database_manager())
# Verify tenant access and role
async with tenant_service.database_manager.get_session() as session:
await tenant_service._init_repositories(session)
# Get tenant member record
member = await tenant_service.member_repo.get_member_by_user_and_tenant(
str(user_id), str(tenant_id)
)
if not member:
logger.warning("User not member of tenant",
user_id=user_id,
tenant_id=str(tenant_id))
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied: You are not a member of this tenant"
)
if member.role not in ['owner', 'admin']:
logger.warning("Insufficient permissions to cancel subscription",
user_id=user_id,
tenant_id=str(tenant_id),
role=member.role)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied: Only owners and admins can cancel subscriptions"
)
# Get subscription ID from database
subscription = await tenant_service.subscription_repo.get_active_subscription(str(tenant_id))
if not subscription or not subscription.stripe_subscription_id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No active subscription found for this tenant"
)
subscription_id = subscription.stripe_subscription_id
result = await payment_service.cancel_subscription(subscription_id)
return {
"success": True,
"message": "Subscription cancelled successfully",
"data": {
"subscription_id": result.id,
"status": result.status
}
}
except Exception as e:
logger.error("Failed to cancel subscription", error=str(e))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to cancel subscription"
)
@router.get(route_builder.build_base_route("subscriptions/{tenant_id}/invoices", include_tenant_prefix=False))
async def get_invoices(
tenant_id: UUID = Path(..., description="Tenant ID"),
current_user: Dict[str, Any] = Depends(get_current_user_dep),
payment_service: PaymentService = Depends(get_payment_service)
):
"""Get invoices for a tenant"""
try:
# Verify user has access to tenant
user_id = current_user.get('user_id')
from app.services.tenant_service import EnhancedTenantService
from shared.database.base import create_database_manager
tenant_service = EnhancedTenantService(create_database_manager())
async with tenant_service.database_manager.get_session() as session:
await tenant_service._init_repositories(session)
# Verify user is member of tenant
member = await tenant_service.member_repo.get_member_by_user_and_tenant(
str(user_id), str(tenant_id)
)
if not member:
logger.warning("User not member of tenant",
user_id=user_id,
tenant_id=str(tenant_id))
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied: You do not have access to this tenant"
)
# Get subscription with customer ID
subscription = await tenant_service.subscription_repo.get_active_subscription(str(tenant_id))
if not subscription:
# No subscription found, return empty invoices list
return []
# Check if subscription has stripe customer ID
stripe_customer_id = getattr(subscription, 'stripe_customer_id', None)
if not stripe_customer_id:
# No Stripe customer ID, return empty invoices (demo tenants, free tier, etc.)
logger.debug("No Stripe customer ID for tenant",
tenant_id=str(tenant_id),
plan=getattr(subscription, 'plan', 'unknown'))
return []
invoices = await payment_service.get_invoices(stripe_customer_id)
return invoices
except Exception as e:
logger.error("Failed to get invoices", error=str(e))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to get invoices"
)
async def _invalidate_tenant_tokens(tenant_id: str, redis_client):
"""