Add subcription feature 6

This commit is contained in:
Urtzi Alfaro
2026-01-16 15:19:34 +01:00
parent 6b43116efd
commit 4bafceed0d
35 changed files with 3826 additions and 1789 deletions

View File

@@ -36,6 +36,9 @@ PUBLIC_ROUTES = [
"/api/v1/auth/verify",
"/api/v1/auth/start-registration", # Registration step 1 - SetupIntent creation
"/api/v1/auth/complete-registration", # Registration step 2 - Completion after 3DS
"/api/v1/registration/payment-setup", # New registration payment setup endpoint
"/api/v1/registration/complete", # New registration completion endpoint
"/api/v1/registration/state/", # Registration state check
"/api/v1/auth/verify-email", # Email verification
"/api/v1/auth/password/reset-request", # Password reset request - no auth required
"/api/v1/auth/password/reset", # Password reset with token - no auth required
@@ -621,7 +624,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
async with httpx.AsyncClient(timeout=3.0) as client:
headers = {"Authorization": request.headers.get("Authorization", "")}
response = await client.get(
f"{settings.TENANT_SERVICE_URL}/api/v1/subscriptions/{tenant_id}/tier",
f"{settings.TENANT_SERVICE_URL}/api/v1/tenants/{tenant_id}/subscription/tier",
headers=headers
)

View File

@@ -163,7 +163,7 @@ class APIRateLimitMiddleware(BaseHTTPMiddleware):
async with httpx.AsyncClient(timeout=2.0) as client:
response = await client.get(
f"{settings.TENANT_SERVICE_URL}/api/v1/subscriptions/{tenant_id}/tier",
f"{settings.TENANT_SERVICE_URL}/api/v1/tenants/{tenant_id}/subscription/tier",
headers={
"x-service": "gateway"
}

View File

@@ -24,7 +24,8 @@ logger = logging.getLogger(__name__)
READ_ONLY_WHITELIST_PATTERNS = [
r'^/api/v1/users/me/delete/request$',
r'^/api/v1/users/me/export.*$',
r'^/api/v1/subscriptions/.*',
r'^/api/v1/tenants/.*/subscription/.*', # All tenant subscription endpoints
r'^/api/v1/registration/.*', # Registration flow endpoints
r'^/api/v1/auth/.*', # Allow auth operations
r'^/api/v1/tenants/register$', # Allow new tenant registration (no existing tenant context)
r'^/api/v1/tenants/.*/orchestrator/run-daily-workflow$', # Allow workflow testing
@@ -56,7 +57,7 @@ class ReadOnlyModeMiddleware(BaseHTTPMiddleware):
try:
async with httpx.AsyncClient(timeout=5.0) as client:
response = await client.get(
f"{self.tenant_service_url}/api/v1/tenants/{tenant_id}/subscriptions/status",
f"{self.tenant_service_url}/api/v1/tenants/{tenant_id}/subscription/status",
headers={"Authorization": authorization}
)

View File

@@ -176,7 +176,8 @@ class SubscriptionMiddleware(BaseHTTPMiddleware):
r'/health.*',
r'/metrics.*',
r'/api/v1/auth/.*',
r'/api/v1/subscriptions/.*', # Subscription management itself
r'/api/v1/tenants/[^/]+/subscription/.*', # All tenant subscription endpoints
r'/api/v1/registration/.*', # Registration flow endpoints
r'/api/v1/tenants/[^/]+/members.*', # Basic tenant info
r'/api/v1/webhooks/.*', # Webhook endpoints - no tenant context
r'/docs.*',
@@ -295,9 +296,9 @@ class SubscriptionMiddleware(BaseHTTPMiddleware):
)
async with httpx.AsyncClient(timeout=timeout_config) as client:
# Use fast cached tier endpoint
# Use fast cached tier endpoint (new URL pattern)
tier_response = await client.get(
f"{settings.TENANT_SERVICE_URL}/api/v1/subscriptions/{tenant_id}/tier",
f"{settings.TENANT_SERVICE_URL}/api/v1/tenants/{tenant_id}/subscription/tier",
headers=headers
)

View File

@@ -1,5 +1,12 @@
"""
Subscription routes for API Gateway - Direct subscription endpoints
New URL Pattern Architecture:
- Registration: /registration/payment-setup, /registration/complete, /registration/state/{state_id}
- Tenant Subscription: /tenants/{tenant_id}/subscription/*
- Setup Intents: /setup-intents/{setup_intent_id}/verify
- Payment Customers: /payment-customers/create
- Plans: /plans (public)
"""
from fastapi import APIRouter, Request, Response, HTTPException, Path
@@ -15,74 +22,202 @@ logger = logging.getLogger(__name__)
router = APIRouter()
# ================================================================
# SUBSCRIPTION ENDPOINTS - Direct routing to tenant service
# PUBLIC ENDPOINTS (No Authentication)
# ================================================================
@router.api_route("/tenants/subscriptions/{tenant_id}/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_subscription_endpoints(request: Request, tenant_id: str = Path(...), path: str = ""):
"""Proxy subscription requests directly to tenant service"""
target_path = f"/api/v1/tenants/subscriptions/{tenant_id}/{path}".rstrip("/")
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/plans", methods=["GET", "OPTIONS"])
async def proxy_subscription_plans(request: Request):
"""Proxy subscription plans request to tenant service"""
target_path = "/plans"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/plans", methods=["GET", "OPTIONS"])
async def proxy_plans(request: Request):
"""Proxy plans request to tenant service"""
target_path = "/plans"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/{tenant_id}/invoices", methods=["GET", "OPTIONS"])
async def proxy_invoices(request: Request, tenant_id: str = Path(...)):
"""Proxy invoices request to tenant service"""
target_path = f"/api/v1/subscriptions/{tenant_id}/invoices"
@router.api_route("/plans/{tier}", methods=["GET", "OPTIONS"])
async def proxy_plan_details(request: Request, tier: str = Path(...)):
"""Proxy specific plan details request to tenant service"""
target_path = f"/plans/{tier}"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/{tenant_id}/status", methods=["GET", "OPTIONS"])
@router.api_route("/plans/{tier}/features", methods=["GET", "OPTIONS"])
async def proxy_plan_features(request: Request, tier: str = Path(...)):
"""Proxy plan features request to tenant service"""
target_path = f"/plans/{tier}/features"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/plans/{tier}/limits", methods=["GET", "OPTIONS"])
async def proxy_plan_limits(request: Request, tier: str = Path(...)):
"""Proxy plan limits request to tenant service"""
target_path = f"/plans/{tier}/limits"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/plans/compare", methods=["GET", "OPTIONS"])
async def proxy_plan_compare(request: Request):
"""Proxy plan comparison request to tenant service"""
target_path = "/plans/compare"
return await _proxy_to_tenant_service(request, target_path)
# ================================================================
# REGISTRATION FLOW ENDPOINTS (No Tenant Context)
# ================================================================
@router.api_route("/registration/payment-setup", methods=["POST", "OPTIONS"])
async def proxy_registration_payment_setup(request: Request):
"""Proxy registration payment setup request to tenant service"""
target_path = "/api/v1/registration/payment-setup"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/registration/complete", methods=["POST", "OPTIONS"])
async def proxy_registration_complete(request: Request):
"""Proxy registration completion request to tenant service"""
target_path = "/api/v1/registration/complete"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/registration/state/{state_id}", methods=["GET", "OPTIONS"])
async def proxy_registration_state(request: Request, state_id: str = Path(...)):
"""Proxy registration state request to tenant service"""
target_path = f"/api/v1/registration/state/{state_id}"
return await _proxy_to_tenant_service(request, target_path)
# ================================================================
# TENANT SUBSCRIPTION STATUS ENDPOINTS
# ================================================================
@router.api_route("/tenants/{tenant_id}/subscription/status", methods=["GET", "OPTIONS"])
async def proxy_subscription_status(request: Request, tenant_id: str = Path(...)):
"""Proxy subscription status request to tenant service"""
target_path = f"/api/v1/subscriptions/{tenant_id}/status"
target_path = f"/api/v1/tenants/{tenant_id}/subscription/status"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/{tenant_id}/payment-method", methods=["GET", "OPTIONS"])
@router.api_route("/tenants/{tenant_id}/subscription/details", methods=["GET", "OPTIONS"])
async def proxy_subscription_details(request: Request, tenant_id: str = Path(...)):
"""Proxy subscription details request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/details"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/tier", methods=["GET", "OPTIONS"])
async def proxy_subscription_tier(request: Request, tenant_id: str = Path(...)):
"""Proxy subscription tier request to tenant service (cached)"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/tier"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/limits", methods=["GET", "OPTIONS"])
async def proxy_subscription_limits(request: Request, tenant_id: str = Path(...)):
"""Proxy subscription limits request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/limits"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/usage", methods=["GET", "OPTIONS"])
async def proxy_subscription_usage(request: Request, tenant_id: str = Path(...)):
"""Proxy subscription usage request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/usage"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/features/{feature}", methods=["GET", "OPTIONS"])
async def proxy_subscription_feature(request: Request, tenant_id: str = Path(...), feature: str = Path(...)):
"""Proxy subscription feature check request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/features/{feature}"
return await _proxy_to_tenant_service(request, target_path)
# ================================================================
# SUBSCRIPTION MANAGEMENT ENDPOINTS
# ================================================================
@router.api_route("/tenants/{tenant_id}/subscription/cancel", methods=["POST", "OPTIONS"])
async def proxy_subscription_cancel(request: Request, tenant_id: str = Path(...)):
"""Proxy subscription cancellation request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/cancel"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/reactivate", methods=["POST", "OPTIONS"])
async def proxy_subscription_reactivate(request: Request, tenant_id: str = Path(...)):
"""Proxy subscription reactivation request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/reactivate"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/validate-upgrade/{new_plan}", methods=["GET", "OPTIONS"])
async def proxy_validate_upgrade(request: Request, tenant_id: str = Path(...), new_plan: str = Path(...)):
"""Proxy plan upgrade validation request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/validate-upgrade/{new_plan}"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/upgrade", methods=["POST", "OPTIONS"])
async def proxy_subscription_upgrade(request: Request, tenant_id: str = Path(...)):
"""Proxy subscription upgrade request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/upgrade"
return await _proxy_to_tenant_service(request, target_path)
# ================================================================
# QUOTA & LIMIT CHECK ENDPOINTS
# ================================================================
@router.api_route("/tenants/{tenant_id}/subscription/limits/locations", methods=["GET", "OPTIONS"])
async def proxy_location_limits(request: Request, tenant_id: str = Path(...)):
"""Proxy location limits check request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/limits/locations"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/limits/products", methods=["GET", "OPTIONS"])
async def proxy_product_limits(request: Request, tenant_id: str = Path(...)):
"""Proxy product limits check request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/limits/products"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/limits/users", methods=["GET", "OPTIONS"])
async def proxy_user_limits(request: Request, tenant_id: str = Path(...)):
"""Proxy user limits check request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/limits/users"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/limits/recipes", methods=["GET", "OPTIONS"])
async def proxy_recipe_limits(request: Request, tenant_id: str = Path(...)):
"""Proxy recipe limits check request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/limits/recipes"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/tenants/{tenant_id}/subscription/limits/suppliers", methods=["GET", "OPTIONS"])
async def proxy_supplier_limits(request: Request, tenant_id: str = Path(...)):
"""Proxy supplier limits check request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/limits/suppliers"
return await _proxy_to_tenant_service(request, target_path)
# ================================================================
# PAYMENT MANAGEMENT ENDPOINTS
# ================================================================
@router.api_route("/tenants/{tenant_id}/subscription/payment-method", methods=["GET", "POST", "OPTIONS"])
async def proxy_payment_method(request: Request, tenant_id: str = Path(...)):
"""Proxy payment method request to tenant service"""
target_path = f"/api/v1/subscriptions/{tenant_id}/payment-method"
target_path = f"/api/v1/tenants/{tenant_id}/subscription/payment-method"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/cancel", methods=["POST", "OPTIONS"])
async def proxy_subscription_cancel(request: Request):
"""Proxy subscription cancellation request to tenant service"""
target_path = "/api/v1/subscriptions/cancel"
@router.api_route("/tenants/{tenant_id}/subscription/invoices", methods=["GET", "OPTIONS"])
async def proxy_invoices(request: Request, tenant_id: str = Path(...)):
"""Proxy invoices request to tenant service"""
target_path = f"/api/v1/tenants/{tenant_id}/subscription/invoices"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/create-for-registration", methods=["POST", "OPTIONS"])
async def proxy_create_for_registration(request: Request):
"""Proxy create-for-registration request to tenant service"""
target_path = "/api/v1/subscriptions/create-for-registration"
# ================================================================
# SETUP INTENT VERIFICATION
# ================================================================
@router.api_route("/setup-intents/{setup_intent_id}/verify", methods=["GET", "OPTIONS"])
async def proxy_setup_intent_verify(request: Request, setup_intent_id: str = Path(...)):
"""Proxy SetupIntent verification request to tenant service"""
target_path = f"/api/v1/setup-intents/{setup_intent_id}/verify"
return await _proxy_to_tenant_service(request, target_path)
# ================================================================
# PAYMENT CUSTOMER MANAGEMENT
# ================================================================
@router.api_route("/payment-customers/create", methods=["POST", "OPTIONS"])
async def proxy_payment_customer_create(request: Request):
"""Proxy payment customer creation request to tenant service"""
target_path = "/api/v1/payment-customers/create"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/setup-intents/{setup_intent_id}/verify", methods=["GET", "OPTIONS"])
async def proxy_setup_intent_verify(request: Request, setup_intent_id: str):
"""Proxy SetupIntent verification request to tenant service"""
target_path = f"/api/v1/setup-intents/{setup_intent_id}/verify"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/reactivate", methods=["POST", "OPTIONS"])
async def proxy_subscription_reactivate(request: Request):
"""Proxy subscription reactivation request to tenant service"""
target_path = "/api/v1/subscriptions/reactivate"
return await _proxy_to_tenant_service(request, target_path)
# ================================================================
# USAGE FORECAST ENDPOINTS
# ================================================================
@router.api_route("/usage-forecast", methods=["GET", "OPTIONS"])
async def proxy_usage_forecast(request: Request):
@@ -125,7 +260,7 @@ async def _proxy_request(request: Request, target_path: str, service_url: str):
# Use unified HeaderManager for consistent header forwarding
headers = header_manager.get_all_headers_for_proxy(request)
# Debug logging
user_context = getattr(request.state, 'user', None)
service_context = getattr(request.state, 'service', None)
@@ -179,4 +314,4 @@ async def _proxy_request(request: Request, target_path: str, service_url: str):
raise HTTPException(
status_code=500,
detail="Internal gateway error"
)
)

View File

@@ -119,6 +119,11 @@ async def get_user_all_tenants(request: Request, user_id: str = Path(...)):
"""Get all tenants accessible by a user (both owned and member tenants)"""
return await _proxy_to_tenant_service(request, f"/api/v1/tenants/user/{user_id}/tenants")
@router.get("/users/{user_id}/primary-tenant")
async def get_user_primary_tenant(request: Request, user_id: str = Path(...)):
"""Get the primary tenant for a user (used by auth service for subscription validation)"""
return await _proxy_to_tenant_service(request, f"/api/v1/tenants/users/{user_id}/primary-tenant")
@router.delete("/user/{user_id}/memberships")
async def delete_user_tenants(request: Request, user_id: str = Path(...)):
"""Get all tenant memberships for a user (admin only)"""
@@ -157,11 +162,9 @@ async def reset_category_settings(request: Request, tenant_id: str = Path(...),
# TENANT SUBSCRIPTION ENDPOINTS
# ================================================================
@router.api_route("/{tenant_id}/subscriptions/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_subscriptions(request: Request, tenant_id: str = Path(...), path: str = ""):
"""Proxy tenant subscription requests to tenant service"""
target_path = f"/api/v1/subscriptions/{tenant_id}/{path}".rstrip("/")
return await _proxy_to_tenant_service(request, target_path)
# NOTE: All subscription endpoints have been moved to gateway/app/routes/subscription.py
# as part of the architecture redesign for better separation of concerns.
# This wildcard route has been removed to avoid conflicts with the new specific routes.
@router.api_route("/subscriptions/plans", methods=["GET", "OPTIONS"])
async def proxy_available_plans(request: Request):

View File

@@ -183,15 +183,7 @@ user_proxy = UserProxy()
# USER MANAGEMENT ENDPOINTS - Proxied to auth service
# ================================================================
@router.get("/me")
async def get_current_user(request: Request):
"""Proxy get current user to auth service"""
return await user_proxy.forward_request("GET", "me", request)
@router.put("/me")
async def update_current_user(request: Request):
"""Proxy update current user to auth service"""
return await user_proxy.forward_request("PUT", "me", request)
@router.get("/delete/{user_id}/deletion-preview")
async def preview_user_deletion(user_id: str, request: Request):