Add subcription feature 2
This commit is contained in:
@@ -13,6 +13,20 @@ from app.schemas.auth import (
|
||||
UserRegistration, UserLogin, TokenResponse, RefreshTokenRequest,
|
||||
PasswordChange, PasswordReset, UserResponse
|
||||
)
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
|
||||
# Schema for SetupIntent completion data
|
||||
class SetupIntentCompletionData(BaseModel):
|
||||
email: str
|
||||
password: str
|
||||
full_name: str
|
||||
setup_intent_id: str
|
||||
plan_id: str
|
||||
payment_method_id: str
|
||||
billing_interval: str = "monthly"
|
||||
coupon_code: Optional[str] = None
|
||||
from app.services.auth_service import EnhancedAuthService
|
||||
from app.models.users import User
|
||||
from app.core.database import get_db
|
||||
@@ -102,8 +116,7 @@ async def register(
|
||||
detail="Registration failed"
|
||||
)
|
||||
|
||||
@router.post("/api/v1/auth/register-with-subscription", response_model=TokenResponse)
|
||||
@track_execution_time("enhanced_registration_with_subscription_duration_seconds", "auth-service")
|
||||
@router.post("/api/v1/auth/register-with-subscription")
|
||||
async def register_with_subscription(
|
||||
user_data: UserRegistration,
|
||||
request: Request,
|
||||
@@ -112,18 +125,20 @@ async def register_with_subscription(
|
||||
"""
|
||||
Register new user and create subscription in one call
|
||||
|
||||
This endpoint implements the new registration flow where:
|
||||
1. User is created
|
||||
2. Payment customer is created via tenant service
|
||||
3. Tenant-independent subscription is created via tenant service
|
||||
4. Subscription data is stored in onboarding progress
|
||||
5. User is authenticated and returned with tokens
|
||||
NEW ARCHITECTURE: User is ONLY created AFTER payment verification
|
||||
|
||||
Flow:
|
||||
1. Validate user data
|
||||
2. Create payment customer via tenant service
|
||||
3. Create SetupIntent via tenant service
|
||||
4. If SetupIntent requires_action: Return SetupIntent data WITHOUT creating user
|
||||
5. If no SetupIntent required: Create user, create subscription, return tokens
|
||||
|
||||
The subscription will be linked to a tenant during the onboarding flow.
|
||||
"""
|
||||
metrics = get_metrics_collector(request)
|
||||
|
||||
logger.info("Registration with subscription attempt using new architecture",
|
||||
logger.info("Registration with subscription attempt using secure architecture",
|
||||
email=user_data.email)
|
||||
|
||||
try:
|
||||
@@ -146,54 +161,135 @@ async def register_with_subscription(
|
||||
detail="Full name is required"
|
||||
)
|
||||
|
||||
# Step 1: Register user using enhanced service
|
||||
logger.info("Step 1: Creating user", email=user_data.email)
|
||||
# NEW ARCHITECTURE: Create payment customer and SetupIntent BEFORE user creation
|
||||
if user_data.subscription_plan and user_data.payment_method_id:
|
||||
logger.info("Step 1: Creating payment customer and SetupIntent BEFORE user creation",
|
||||
email=user_data.email,
|
||||
plan=user_data.subscription_plan)
|
||||
|
||||
# Use tenant service orchestration endpoint for payment setup
|
||||
# This creates payment customer and SetupIntent in one coordinated workflow
|
||||
payment_setup_result = await auth_service.create_registration_payment_setup_via_tenant_service(
|
||||
user_data=user_data
|
||||
)
|
||||
|
||||
if not payment_setup_result or not payment_setup_result.get('success'):
|
||||
logger.error("Payment setup failed",
|
||||
email=user_data.email,
|
||||
error="Payment setup returned no success")
|
||||
|
||||
if metrics:
|
||||
metrics.increment_counter("enhanced_registration_with_subscription_total",
|
||||
labels={"status": "failed_payment_setup"})
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Payment setup failed"
|
||||
)
|
||||
|
||||
# CRITICAL: Check if SetupIntent requires 3DS authentication
|
||||
if payment_setup_result.get('requires_action'):
|
||||
# NEW ARCHITECTURE: Return SetupIntent data WITHOUT creating user
|
||||
logger.info("Payment setup requires SetupIntent authentication - deferring user creation",
|
||||
email=user_data.email,
|
||||
action_type=payment_setup_result.get('action_type'),
|
||||
setup_intent_id=payment_setup_result.get('setup_intent_id'))
|
||||
|
||||
if metrics:
|
||||
metrics.increment_counter("enhanced_registration_with_subscription_total",
|
||||
labels={"status": "requires_3ds"})
|
||||
|
||||
# Return SetupIntent data for frontend to handle 3DS
|
||||
# NO user created yet, NO tokens returned
|
||||
return {
|
||||
"requires_action": True,
|
||||
"action_type": payment_setup_result.get('action_type'),
|
||||
"client_secret": payment_setup_result.get('client_secret'),
|
||||
"setup_intent_id": payment_setup_result.get('setup_intent_id'),
|
||||
"customer_id": payment_setup_result.get('customer_id'),
|
||||
"payment_customer_id": payment_setup_result.get('payment_customer_id'),
|
||||
"plan_id": payment_setup_result.get('plan_id'),
|
||||
"payment_method_id": payment_setup_result.get('payment_method_id'),
|
||||
"trial_period_days": payment_setup_result.get('trial_period_days'),
|
||||
"email": payment_setup_result.get('email'),
|
||||
"full_name": payment_setup_result.get('full_name'),
|
||||
"billing_interval": payment_setup_result.get('billing_interval'),
|
||||
"coupon_code": payment_setup_result.get('coupon_code'),
|
||||
"message": payment_setup_result.get('message') or "Payment verification required before account creation"
|
||||
}
|
||||
else:
|
||||
# No 3DS required - proceed with user creation
|
||||
logger.info("No SetupIntent required - proceeding with user creation",
|
||||
email=user_data.email)
|
||||
else:
|
||||
# No subscription data provided - proceed with user creation
|
||||
logger.info("No subscription data provided - proceeding with user creation",
|
||||
email=user_data.email)
|
||||
|
||||
# Step 2: Create user (ONLY if no SetupIntent required)
|
||||
logger.info("Step 2: Creating user after payment verification",
|
||||
email=user_data.email)
|
||||
|
||||
result = await auth_service.register_user(user_data)
|
||||
user_id = result.user.id
|
||||
|
||||
logger.info("User created successfully", user_id=user_id)
|
||||
logger.info("User created successfully",
|
||||
user_id=user_id,
|
||||
email=user_data.email)
|
||||
|
||||
# Step 2: Create subscription via tenant service (if subscription data provided)
|
||||
subscription_id = None
|
||||
# Step 3: If subscription was created (no 3DS), store in onboarding progress
|
||||
if user_data.subscription_plan and user_data.payment_method_id:
|
||||
logger.info("Step 2: Creating tenant-independent subscription",
|
||||
user_id=user_id,
|
||||
plan=user_data.subscription_plan)
|
||||
|
||||
subscription_result = await auth_service.create_subscription_via_tenant_service(
|
||||
user_id=user_id,
|
||||
plan_id=user_data.subscription_plan,
|
||||
payment_method_id=user_data.payment_method_id,
|
||||
billing_cycle=user_data.billing_cycle or "monthly",
|
||||
coupon_code=user_data.coupon_code
|
||||
)
|
||||
|
||||
if subscription_result:
|
||||
subscription_id = subscription_result.get("subscription_id")
|
||||
subscription_id = payment_setup_result.get("subscription_id")
|
||||
|
||||
if subscription_id:
|
||||
logger.info("Tenant-independent subscription created successfully",
|
||||
user_id=user_id,
|
||||
subscription_id=subscription_id)
|
||||
|
||||
# Step 3: Store subscription data in onboarding progress
|
||||
logger.info("Step 3: Storing subscription data in onboarding progress",
|
||||
user_id=user_id)
|
||||
|
||||
# Update onboarding progress with subscription data
|
||||
|
||||
# Store subscription data in onboarding progress
|
||||
await auth_service.save_subscription_to_onboarding_progress(
|
||||
user_id=user_id,
|
||||
subscription_id=subscription_id,
|
||||
registration_data=user_data
|
||||
)
|
||||
|
||||
|
||||
logger.info("Subscription data stored in onboarding progress",
|
||||
user_id=user_id)
|
||||
|
||||
result.subscription_id = subscription_id
|
||||
else:
|
||||
logger.warning("Subscription creation failed, but user registration succeeded",
|
||||
logger.warning("No subscription ID returned, but user registration succeeded",
|
||||
user_id=user_id)
|
||||
else:
|
||||
logger.info("No subscription data provided, skipping subscription creation",
|
||||
user_id=user_id)
|
||||
|
||||
# Record successful registration
|
||||
if metrics:
|
||||
metrics.increment_counter("enhanced_registration_with_subscription_total",
|
||||
labels={"status": "success"})
|
||||
|
||||
logger.info("Registration with subscription completed successfully using secure architecture",
|
||||
user_id=user_id,
|
||||
email=user_data.email,
|
||||
subscription_id=result.subscription_id)
|
||||
|
||||
return result
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
if metrics:
|
||||
error_type = "validation_error" if "validation" in str(e).lower() else "conflict" if "conflict" in str(e).lower() else "failed"
|
||||
metrics.increment_counter("enhanced_registration_with_subscription_total",
|
||||
labels={"status": error_type})
|
||||
|
||||
logger.error("Registration with subscription system error using secure architecture",
|
||||
email=user_data.email,
|
||||
error=str(e),
|
||||
exc_info=True)
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Registration with subscription failed: " + str(e)
|
||||
)
|
||||
|
||||
# Record successful registration
|
||||
if metrics:
|
||||
@@ -206,6 +302,30 @@ async def register_with_subscription(
|
||||
|
||||
# Add subscription_id to the response
|
||||
result.subscription_id = subscription_id
|
||||
|
||||
# Check if subscription creation requires 3DS/SetupIntent authentication
|
||||
if subscription_result and subscription_result.get('requires_action'):
|
||||
result.requires_action = subscription_result.get('requires_action')
|
||||
result.action_type = subscription_result.get('action_type')
|
||||
result.client_secret = subscription_result.get('client_secret')
|
||||
result.setup_intent_id = subscription_result.get('setup_intent_id')
|
||||
result.payment_intent_id = subscription_result.get('payment_intent_id') # Legacy, deprecated
|
||||
|
||||
# Include data needed for post-3DS subscription completion
|
||||
result.customer_id = subscription_result.get('customer_id')
|
||||
result.plan_id = user_data.subscription_plan
|
||||
result.payment_method_id = user_data.payment_method_id
|
||||
result.trial_period_days = subscription_result.get('trial_period_days')
|
||||
result.user_id = user_id
|
||||
result.billing_interval = user_data.billing_cycle or "monthly"
|
||||
result.message = subscription_result.get('message')
|
||||
|
||||
logger.info("Registration requires SetupIntent authentication",
|
||||
user_id=user_id,
|
||||
requires_action=result.requires_action,
|
||||
action_type=result.action_type,
|
||||
setup_intent_id=result.setup_intent_id)
|
||||
|
||||
return result
|
||||
|
||||
except HTTPException as e:
|
||||
@@ -675,6 +795,142 @@ async def reset_password(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/complete-registration-after-setup-intent")
|
||||
@track_execution_time("registration_completion_duration_seconds", "auth-service")
|
||||
async def complete_registration_after_setup_intent(
|
||||
completion_data: SetupIntentCompletionData,
|
||||
request: Request,
|
||||
auth_service: EnhancedAuthService = Depends(get_auth_service)
|
||||
):
|
||||
"""
|
||||
Complete user registration after SetupIntent confirmation
|
||||
|
||||
This endpoint is called by the frontend after 3DS authentication is complete.
|
||||
It ensures users are only created after payment verification.
|
||||
|
||||
Args:
|
||||
completion_data: Data from frontend including SetupIntent ID and user info
|
||||
|
||||
Returns:
|
||||
TokenResponse with access_token, refresh_token, and user data
|
||||
|
||||
Raises:
|
||||
HTTPException: 400 if SetupIntent not succeeded
|
||||
HTTPException: 500 if registration fails
|
||||
"""
|
||||
metrics = get_metrics_collector(request)
|
||||
|
||||
logger.info("Completing registration after SetupIntent confirmation",
|
||||
email=completion_data.email,
|
||||
setup_intent_id=completion_data.setup_intent_id)
|
||||
|
||||
try:
|
||||
# Step 1: Verify SetupIntent using tenant service orchestration
|
||||
logger.info("Step 1: Verifying SetupIntent using orchestration service",
|
||||
setup_intent_id=completion_data.setup_intent_id)
|
||||
|
||||
verification_result = await auth_service.verify_setup_intent_via_tenant_service(
|
||||
completion_data.setup_intent_id
|
||||
)
|
||||
|
||||
if not verification_result or verification_result.get('status') != 'succeeded':
|
||||
status_code = status.HTTP_400_BAD_REQUEST
|
||||
detail = f"SetupIntent not succeeded: {verification_result.get('status') if verification_result else 'unknown'}"
|
||||
|
||||
logger.warning("SetupIntent verification failed via orchestration service",
|
||||
email=completion_data.email,
|
||||
setup_intent_id=completion_data.setup_intent_id,
|
||||
status=verification_result.get('status') if verification_result else 'unknown')
|
||||
|
||||
if metrics:
|
||||
metrics.increment_counter("registration_completion_total", labels={"status": "failed_verification"})
|
||||
|
||||
raise HTTPException(status_code=status_code, detail=detail)
|
||||
|
||||
logger.info("SetupIntent verification succeeded via orchestration service",
|
||||
setup_intent_id=completion_data.setup_intent_id)
|
||||
|
||||
# Step 2: Create user (ONLY after payment verification)
|
||||
logger.info("Step 2: Creating user after successful payment verification",
|
||||
email=completion_data.email)
|
||||
|
||||
user_data = UserRegistration(
|
||||
email=completion_data.email,
|
||||
password=completion_data.password,
|
||||
full_name=completion_data.full_name,
|
||||
subscription_plan=completion_data.plan_id,
|
||||
payment_method_id=completion_data.payment_method_id,
|
||||
billing_cycle=completion_data.billing_interval,
|
||||
coupon_code=completion_data.coupon_code
|
||||
)
|
||||
|
||||
registration_result = await auth_service.register_user(user_data)
|
||||
|
||||
logger.info("User created successfully after payment verification",
|
||||
user_id=registration_result.user.id,
|
||||
email=completion_data.email)
|
||||
|
||||
# Step 3: Create subscription (now that user exists)
|
||||
logger.info("Step 3: Creating subscription for verified user",
|
||||
user_id=registration_result.user.id,
|
||||
plan_id=completion_data.plan_id)
|
||||
|
||||
subscription_result = await auth_service.create_subscription_via_tenant_service(
|
||||
user_id=registration_result.user.id,
|
||||
plan_id=completion_data.plan_id,
|
||||
payment_method_id=completion_data.payment_method_id,
|
||||
billing_cycle=completion_data.billing_interval,
|
||||
coupon_code=completion_data.coupon_code
|
||||
)
|
||||
|
||||
if not subscription_result or not subscription_result.get('success'):
|
||||
logger.error("Subscription creation failed after successful user registration",
|
||||
user_id=registration_result.user.id,
|
||||
error="Subscription creation returned no success")
|
||||
|
||||
if metrics:
|
||||
metrics.increment_counter("registration_completion_total", labels={"status": "failed_subscription"})
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Subscription creation failed after user registration"
|
||||
)
|
||||
|
||||
logger.info("Subscription created successfully",
|
||||
user_id=registration_result.user.id,
|
||||
subscription_id=subscription_result.get('subscription_id'))
|
||||
|
||||
# Step 4: Return tokens and subscription data
|
||||
registration_result.subscription_id = subscription_result.get('subscription_id')
|
||||
|
||||
if metrics:
|
||||
metrics.increment_counter("registration_completion_total", labels={"status": "success"})
|
||||
|
||||
logger.info("Registration completed successfully after SetupIntent confirmation",
|
||||
user_id=registration_result.user.id,
|
||||
email=completion_data.email,
|
||||
subscription_id=subscription_result.get('subscription_id'))
|
||||
|
||||
return registration_result
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
if metrics:
|
||||
metrics.increment_counter("registration_completion_total", labels={"status": "error"})
|
||||
|
||||
logger.error("Registration completion system error",
|
||||
email=completion_data.email,
|
||||
setup_intent_id=completion_data.setup_intent_id,
|
||||
error=str(e),
|
||||
exc_info=True)
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Registration completion failed: " + str(e)
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/auth/health")
|
||||
async def health_check():
|
||||
"""Health check endpoint for enhanced auth service"""
|
||||
|
||||
@@ -516,7 +516,7 @@ async def update_user_tenant(
|
||||
tenant_id=tenant_id)
|
||||
|
||||
user_service = UserService(db)
|
||||
user = await user_service.get_user_by_id(uuid.UUID(user_id))
|
||||
user = await user_service.get_user_by_id(uuid.UUID(user_id), session=db)
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
|
||||
@@ -78,6 +78,20 @@ class TokenResponse(BaseModel):
|
||||
expires_in: int = 3600 # seconds
|
||||
user: Optional[UserData] = None
|
||||
subscription_id: Optional[str] = Field(None, description="Subscription ID if created during registration")
|
||||
# Payment action fields (3DS, SetupIntent, etc.)
|
||||
requires_action: Optional[bool] = Field(None, description="Whether payment action is required (3DS, SetupIntent confirmation)")
|
||||
action_type: Optional[str] = Field(None, description="Type of action required (setup_intent_confirmation, payment_intent_confirmation)")
|
||||
client_secret: Optional[str] = Field(None, description="Client secret for payment confirmation")
|
||||
payment_intent_id: Optional[str] = Field(None, description="Payment intent ID for 3DS authentication")
|
||||
setup_intent_id: Optional[str] = Field(None, description="SetupIntent ID for payment method verification")
|
||||
customer_id: Optional[str] = Field(None, description="Stripe customer ID")
|
||||
# Additional fields for post-confirmation subscription completion
|
||||
plan_id: Optional[str] = Field(None, description="Subscription plan ID")
|
||||
payment_method_id: Optional[str] = Field(None, description="Payment method ID")
|
||||
trial_period_days: Optional[int] = Field(None, description="Trial period in days")
|
||||
user_id: Optional[str] = Field(None, description="User ID for post-confirmation processing")
|
||||
billing_interval: Optional[str] = Field(None, description="Billing interval (monthly, yearly)")
|
||||
message: Optional[str] = Field(None, description="Additional message about payment action required")
|
||||
|
||||
class Config:
|
||||
schema_extra = {
|
||||
@@ -95,7 +109,13 @@ class TokenResponse(BaseModel):
|
||||
"created_at": "2025-07-22T10:00:00Z",
|
||||
"role": "user"
|
||||
},
|
||||
"subscription_id": "sub_1234567890"
|
||||
"subscription_id": "sub_1234567890",
|
||||
"requires_action": True,
|
||||
"action_type": "setup_intent_confirmation",
|
||||
"client_secret": "seti_1234_secret_5678",
|
||||
"payment_intent_id": None,
|
||||
"setup_intent_id": "seti_1234567890",
|
||||
"customer_id": "cus_1234567890"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -861,6 +861,94 @@ class EnhancedAuthService:
|
||||
error=str(e))
|
||||
return None
|
||||
|
||||
async def create_registration_payment_setup_via_tenant_service(
|
||||
self,
|
||||
user_data: UserRegistration
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Create registration payment setup via tenant service orchestration
|
||||
|
||||
This method uses the tenant service's orchestration service to create
|
||||
payment customer and SetupIntent in a coordinated workflow for the
|
||||
secure architecture where users are only created after payment verification.
|
||||
|
||||
Args:
|
||||
user_data: User registration data (email, full_name, etc.)
|
||||
|
||||
Returns:
|
||||
Dictionary with payment setup results including SetupIntent if required
|
||||
"""
|
||||
try:
|
||||
from shared.clients.tenant_client import TenantServiceClient
|
||||
from shared.config.base import BaseServiceSettings
|
||||
|
||||
tenant_client = TenantServiceClient(BaseServiceSettings())
|
||||
|
||||
# Prepare user data for tenant service orchestration
|
||||
user_data_for_tenant = {
|
||||
"email": user_data.email,
|
||||
"full_name": user_data.full_name,
|
||||
"payment_method_id": user_data.payment_method_id,
|
||||
"plan_id": user_data.subscription_plan or "professional",
|
||||
"billing_cycle": user_data.billing_cycle or "monthly",
|
||||
"coupon_code": user_data.coupon_code
|
||||
}
|
||||
|
||||
# Call tenant service orchestration endpoint
|
||||
result = await tenant_client.create_registration_payment_setup(user_data_for_tenant)
|
||||
|
||||
logger.info("Registration payment setup completed via tenant service orchestration",
|
||||
email=user_data.email,
|
||||
requires_action=result.get('requires_action'),
|
||||
setup_intent_id=result.get('setup_intent_id'))
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Registration payment setup via tenant service failed",
|
||||
email=user_data.email,
|
||||
error=str(e),
|
||||
exc_info=True)
|
||||
raise
|
||||
|
||||
async def verify_setup_intent_via_tenant_service(
|
||||
self,
|
||||
setup_intent_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Verify SetupIntent via tenant service orchestration
|
||||
|
||||
This method uses the tenant service's orchestration service to verify
|
||||
SetupIntent status before proceeding with user creation.
|
||||
|
||||
Args:
|
||||
setup_intent_id: SetupIntent ID to verify
|
||||
|
||||
Returns:
|
||||
Dictionary with SetupIntent verification result
|
||||
"""
|
||||
try:
|
||||
from shared.clients.tenant_client import TenantServiceClient
|
||||
from shared.config.base import BaseServiceSettings
|
||||
|
||||
tenant_client = TenantServiceClient(BaseServiceSettings())
|
||||
|
||||
# Call tenant service orchestration endpoint
|
||||
result = await tenant_client.verify_setup_intent_for_registration(setup_intent_id)
|
||||
|
||||
logger.info("SetupIntent verified via tenant service orchestration",
|
||||
setup_intent_id=setup_intent_id,
|
||||
status=result.get('status'))
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
logger.error("SetupIntent verification via tenant service failed",
|
||||
setup_intent_id=setup_intent_id,
|
||||
error=str(e),
|
||||
exc_info=True)
|
||||
raise
|
||||
|
||||
async def get_user_data_for_tenant_service(self, user_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get user data formatted for tenant service calls
|
||||
@@ -894,6 +982,101 @@ class EnhancedAuthService:
|
||||
error=str(e))
|
||||
raise
|
||||
|
||||
async def create_payment_customer_for_registration(
|
||||
self,
|
||||
user_data: UserRegistration
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Create payment customer for registration (BEFORE user creation)
|
||||
|
||||
This method creates a payment customer in the tenant service
|
||||
without requiring a user to exist first. This supports the
|
||||
secure architecture where users are only created after payment verification.
|
||||
|
||||
Args:
|
||||
user_data: User registration data
|
||||
|
||||
Returns:
|
||||
Dictionary with payment customer creation result
|
||||
|
||||
Raises:
|
||||
Exception: If payment customer creation fails
|
||||
"""
|
||||
try:
|
||||
from shared.clients.tenant_client import TenantServiceClient
|
||||
from app.core.config import settings
|
||||
|
||||
tenant_client = TenantServiceClient(settings)
|
||||
|
||||
# Prepare user data for tenant service (without user_id)
|
||||
user_data_for_tenant = {
|
||||
"email": user_data.email,
|
||||
"full_name": user_data.full_name,
|
||||
"name": user_data.full_name
|
||||
}
|
||||
|
||||
# Call tenant service to create payment customer
|
||||
payment_result = await tenant_client.create_payment_customer(
|
||||
user_data_for_tenant,
|
||||
user_data.payment_method_id
|
||||
)
|
||||
|
||||
logger.info("Payment customer created for registration (pre-user creation)",
|
||||
email=user_data.email,
|
||||
payment_customer_id=payment_result.get("payment_customer_id") if payment_result else "unknown")
|
||||
|
||||
return payment_result
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Payment customer creation failed for registration",
|
||||
email=user_data.email,
|
||||
error=str(e),
|
||||
exc_info=True)
|
||||
raise
|
||||
|
||||
async def verify_setup_intent(
|
||||
self,
|
||||
setup_intent_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Verify SetupIntent status with payment provider
|
||||
|
||||
This method checks if a SetupIntent has been successfully confirmed
|
||||
(either automatically or via 3DS authentication).
|
||||
|
||||
Args:
|
||||
setup_intent_id: SetupIntent ID to verify
|
||||
|
||||
Returns:
|
||||
Dictionary with SetupIntent verification result
|
||||
|
||||
Raises:
|
||||
Exception: If verification fails
|
||||
"""
|
||||
try:
|
||||
from shared.clients.tenant_client import TenantServiceClient
|
||||
from app.core.config import settings
|
||||
|
||||
tenant_client = TenantServiceClient(settings)
|
||||
|
||||
# Call tenant service to verify SetupIntent
|
||||
verification_result = await tenant_client.verify_setup_intent(
|
||||
setup_intent_id
|
||||
)
|
||||
|
||||
logger.info("SetupIntent verification result",
|
||||
setup_intent_id=setup_intent_id,
|
||||
status=verification_result.get("status") if verification_result else "unknown")
|
||||
|
||||
return verification_result
|
||||
|
||||
except Exception as e:
|
||||
logger.error("SetupIntent verification failed",
|
||||
setup_intent_id=setup_intent_id,
|
||||
error=str(e),
|
||||
exc_info=True)
|
||||
raise
|
||||
|
||||
async def save_subscription_to_onboarding_progress(
|
||||
self,
|
||||
user_id: str,
|
||||
|
||||
@@ -5,6 +5,7 @@ Updated to use repository pattern with dependency injection and improved error h
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, Any, List, Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from fastapi import HTTPException, status
|
||||
import structlog
|
||||
|
||||
@@ -27,22 +28,27 @@ class EnhancedUserService:
|
||||
"""Initialize service with database manager"""
|
||||
self.database_manager = database_manager
|
||||
|
||||
async def get_user_by_id(self, user_id: str) -> Optional[UserResponse]:
|
||||
async def get_user_by_id(self, user_id: str, session: Optional[AsyncSession] = None) -> Optional[UserResponse]:
|
||||
"""Get user by ID using repository pattern"""
|
||||
try:
|
||||
async with self.database_manager.get_session() as session:
|
||||
if session:
|
||||
# Use provided session (for direct session injection)
|
||||
user_repo = UserRepository(User, session)
|
||||
|
||||
user = await user_repo.get_by_id(user_id)
|
||||
if not user:
|
||||
return None
|
||||
|
||||
return UserResponse(
|
||||
id=str(user.id),
|
||||
email=user.email,
|
||||
full_name=user.full_name,
|
||||
is_active=user.is_active,
|
||||
is_verified=user.is_verified,
|
||||
else:
|
||||
# Use database manager to get session
|
||||
async with self.database_manager.get_session() as session:
|
||||
user_repo = UserRepository(User, session)
|
||||
|
||||
user = await user_repo.get_by_id(user_id)
|
||||
if not user:
|
||||
return None
|
||||
|
||||
return UserResponse(
|
||||
id=str(user.id),
|
||||
email=user.email,
|
||||
full_name=user.full_name,
|
||||
is_active=user.is_active,
|
||||
is_verified=user.is_verified,
|
||||
created_at=user.created_at,
|
||||
role=user.role,
|
||||
phone=getattr(user, 'phone', None),
|
||||
|
||||
Reference in New Issue
Block a user