Spaces:
Paused

File size: 7,556 Bytes
dfe4f9f
 
 
 
 
 
 
 
 
 
 
ff28ba2
 
47cf527
ff28ba2
 
dfe4f9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579285c
dfe4f9f
 
 
 
 
579285c
dfe4f9f
 
 
 
 
 
 
 
 
 
 
 
 
579285c
dfe4f9f
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""
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"]