Spaces:
Paused

yaz / src /apps /admin /api /tenant_api.py
anaselamr's picture
[PLATFORM] fix(endpoints+templates): Sprint 52 — zero-error operational pass
579285c
Raw History Blame Contribute Delete
7.56 kB
"""
Admin Tenant Management API
REST API endpoints for tenant administration
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query, Body, Request
from fastapi.responses import HTMLResponse
from typing import List, Optional, Dict, Any
from uuid import UUID
from pydantic import BaseModel, Field
from core.api.dependencies import get_current_user
from core.auth.models import TokenClaims
from core.templates import get_templates
from shared.models.schemas import StandardResponse, PaginatedResponse
from shared.db import get_db_session
from sqlalchemy.orm import Session
from ..domain.models import TenantConfig, TenantStatus
from ..services import TenantAdminService
# Create router
tenant_api_router = APIRouter(tags=["Admin - Tenants"])
# Service instance
_service = TenantAdminService()
# Request/Response Models
class CreateTenantRequest(BaseModel):
"""Request to create a tenant"""
tenant_name: str = Field(..., min_length=1, max_length=255)
tenant_code: str = Field(..., min_length=2, max_length=50)
billing_email: Optional[str] = None
billing_plan: str = Field(default="free")
max_users: Optional[int] = Field(default=None, ge=1)
features: Optional[Dict[str, bool]] = None
class UpdateTenantRequest(BaseModel):
"""Request to update a tenant"""
tenant_name: Optional[str] = None
billing_email: Optional[str] = None
billing_plan: Optional[str] = None
max_users: Optional[int] = None
features: Optional[Dict[str, bool]] = None
@tenant_api_router.post(
"/",
response_model=StandardResponse[TenantConfig],
status_code=status.HTTP_201_CREATED,
summary="Create tenant",
description="Create a new tenant with configuration"
)
async def create_tenant(
request: CreateTenantRequest,
db: Session = Depends(get_db_session),
current_user: TokenClaims = Depends(get_current_user)
):
"""Create a new tenant"""
tenant = await _service.create_tenant(
tenant_name=request.tenant_name,
tenant_code=request.tenant_code,
billing_email=request.billing_email,
billing_plan=request.billing_plan,
max_users=request.max_users,
features=request.features,
session=db
)
return StandardResponse(
success=True,
message="Tenant created successfully",
data=tenant
)
@tenant_api_router.get(
"/{tenant_id}",
response_model=StandardResponse[TenantConfig],
summary="Get tenant",
description="Retrieve tenant by ID"
)
async def get_tenant(
tenant_id: UUID,
db: Session = Depends(get_db_session),
current_user: TokenClaims = Depends(get_current_user)
):
"""Get tenant by ID"""
tenant = await _service.get_tenant(tenant_id, session=db)
return StandardResponse(
success=True,
message="Tenant retrieved successfully",
data=tenant
)
@tenant_api_router.get(
"/",
response_model=PaginatedResponse[TenantConfig],
summary="List tenants",
description="List tenants with optional filters"
)
async def list_tenants(
status: Optional[TenantStatus] = Query(None),
billing_plan: Optional[str] = Query(None),
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=1000),
db: Session = Depends(get_db_session),
current_user: TokenClaims = Depends(get_current_user)
):
"""List tenants with pagination"""
tenants = await _service.list_tenants(
status=status,
billing_plan=billing_plan,
skip=skip,
limit=limit,
session=db
)
return PaginatedResponse(
success=True,
message=f"Retrieved {len(tenants)} tenants",
data=tenants,
total=len(tenants),
page=skip // limit + 1,
page_size=limit
)
@tenant_api_router.put(
"/{tenant_id}",
response_model=StandardResponse[TenantConfig],
summary="Update tenant",
description="Update tenant configuration"
)
async def update_tenant(
tenant_id: UUID,
request: UpdateTenantRequest,
db: Session = Depends(get_db_session),
current_user: TokenClaims = Depends(get_current_user)
):
"""Update tenant configuration"""
updates = request.dict(exclude_unset=True)
tenant = await _service.update_tenant(tenant_id, updates, session=db)
return StandardResponse(
success=True,
message="Tenant updated successfully",
data=tenant
)
@tenant_api_router.post(
"/{tenant_id}/activate",
response_model=StandardResponse[TenantConfig],
summary="Activate tenant",
description="Activate a tenant"
)
async def activate_tenant(
tenant_id: UUID,
db: Session = Depends(get_db_session),
current_user: TokenClaims = Depends(get_current_user)
):
"""Activate a tenant"""
tenant = await _service.activate_tenant(tenant_id, session=db)
return StandardResponse(
success=True,
message="Tenant activated successfully",
data=tenant
)
@tenant_api_router.post(
"/{tenant_id}/suspend",
response_model=StandardResponse[TenantConfig],
summary="Suspend tenant",
description="Suspend a tenant"
)
async def suspend_tenant(
tenant_id: UUID,
reason: Optional[str] = Body(None),
db: Session = Depends(get_db_session),
current_user: TokenClaims = Depends(get_current_user)
):
"""Suspend a tenant"""
tenant = await _service.suspend_tenant(tenant_id, reason=reason, session=db)
return StandardResponse(
success=True,
message="Tenant suspended successfully",
data=tenant
)
@tenant_api_router.get(
"/statistics/overview",
response_model=StandardResponse[Dict[str, Any]],
summary="Get tenant statistics",
description="Get global tenant statistics"
)
async def get_tenant_statistics(
db: Session = Depends(get_db_session),
current_user: TokenClaims = Depends(get_current_user)
):
"""Get tenant statistics"""
stats = await _service.get_tenant_stats(session=db)
return StandardResponse(
success=True,
message="Tenant statistics retrieved successfully",
data=stats
)
# ============================================================================
# HTMX Template Endpoints
# ============================================================================
@tenant_api_router.get("/list/html", response_class=HTMLResponse)
async def get_tenants_html(
request: Request,
db: Session = Depends(get_db_session)
):
"""Render tenant list as HTML"""
tenants = await _service.list_tenants(session=db)
return templates.TemplateResponse(request, "tenants_list.html") # type: ignore[name-defined, index, return-value, var-annotated]
@tenant_api_router.get("/form", response_class=HTMLResponse)
async def get_tenant_form(request: Request):
"""Render tenant creation form"""
return templates.TemplateResponse(request, "tenant_form.html") # type: ignore[name-defined, index, return-value, var-annotated]
@tenant_api_router.get("/{tenant_id}/edit", response_class=HTMLResponse)
async def get_tenant_edit_form(
request: Request,
tenant_id: UUID,
db: Session = Depends(get_db_session)
):
"""Render tenant edit form"""
tenant = await _service.get_tenant(tenant_id, session=db)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
return templates.TemplateResponse(request, "tenant_form.html") # type: ignore[name-defined, index, return-value, var-annotated]
__all__ = ["tenant_api_router"]