Files
crm-system/app/routes/tenants.py
T

76 lines
2.2 KiB
Python
Raw Normal View History

"""Tenant management routes."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.deps import get_current_user, require_admin
from app.schemas.tenant import TenantCreate, TenantUserAssign
from app.services.tenant_service import tenant_service
router = APIRouter(prefix="/api/v1/tenants", tags=["tenants"])
@router.get("")
async def list_tenants(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""List tenants for the current user."""
user_id = uuid.UUID(current_user["user_id"])
tenants = await tenant_service.list_tenants_for_user(db, user_id)
return {"items": tenants}
@router.post("")
async def create_tenant(
body: TenantCreate,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_admin),
):
"""Create a new tenant (admin only)."""
tenant = await tenant_service.create_tenant(db, body.name, body.slug)
return {
"id": str(tenant.id),
"name": tenant.name,
"slug": tenant.slug,
}
@router.get("/{tenant_id}/users")
async def list_tenant_users(
tenant_id: str,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_admin),
):
"""List users in a tenant (admin only)."""
try:
tid = uuid.UUID(tenant_id)
except ValueError:
raise HTTPException(400, detail={"detail": "Invalid tenant_id", "code": "invalid_id"})
users = await tenant_service.list_tenant_users(db, tid)
return {"items": users}
@router.post("/{tenant_id}/users")
async def assign_user_to_tenant(
tenant_id: str,
body: TenantUserAssign,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_admin),
):
"""Assign a user to a tenant (admin only)."""
try:
tid = uuid.UUID(tenant_id)
uid = uuid.UUID(body.user_id)
except ValueError:
raise HTTPException(400, detail={"detail": "Invalid ID", "code": "invalid_id"})
ut = await tenant_service.assign_user_to_tenant(db, tid, uid)
return {"message": "User assigned to tenant"}