feat(B2): add tenant model + migrations 035/036 + RLS policies
Migration 035: tenants table with 'Schaeffler' default seed. Migration 036: tenant_id FK on all tables, RLS policies, backfill. New domains/tenants/ with CRUD router (admin only). All domain models extended with tenant_id FK. core/database.py: get_db_for_tenant with RLS context setter. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from sqlalchemy import String, DateTime, Boolean
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class Tenant(Base):
|
||||
__tablename__ = "tenants"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
slug: Mapped[str] = mapped_column(String(100), nullable=False, unique=True)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
# Relationships (lazy=noload — loaded explicitly when needed)
|
||||
users: Mapped[list] = relationship("User", back_populates="tenant", lazy="noload")
|
||||
orders: Mapped[list] = relationship("Order", back_populates="tenant", lazy="noload")
|
||||
products: Mapped[list] = relationship("Product", back_populates="tenant", lazy="noload")
|
||||
@@ -0,0 +1,79 @@
|
||||
import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.utils.auth import require_admin
|
||||
from app.domains.tenants.schemas import TenantCreate, TenantUpdate, TenantOut
|
||||
from app.domains.tenants import service
|
||||
|
||||
router = APIRouter(prefix="/tenants", tags=["tenants"])
|
||||
|
||||
|
||||
@router.get("/", response_model=list[TenantOut])
|
||||
async def list_tenants(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: object = Depends(require_admin),
|
||||
):
|
||||
rows = await service.list_tenants(db)
|
||||
result = []
|
||||
for row in rows:
|
||||
tenant = row["tenant"]
|
||||
out = TenantOut.model_validate(tenant)
|
||||
out.user_count = row["user_count"]
|
||||
result.append(out)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/{tenant_id}", response_model=TenantOut)
|
||||
async def get_tenant(
|
||||
tenant_id: uuid.UUID,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: object = Depends(require_admin),
|
||||
):
|
||||
tenant = await service.get_tenant(db, tenant_id)
|
||||
if not tenant:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found")
|
||||
return TenantOut.model_validate(tenant)
|
||||
|
||||
|
||||
@router.post("/", response_model=TenantOut, status_code=status.HTTP_201_CREATED)
|
||||
async def create_tenant(
|
||||
body: TenantCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: object = Depends(require_admin),
|
||||
):
|
||||
tenant = await service.create_tenant(db, name=body.name, slug=body.slug, is_active=body.is_active)
|
||||
return TenantOut.model_validate(tenant)
|
||||
|
||||
|
||||
@router.put("/{tenant_id}", response_model=TenantOut)
|
||||
async def update_tenant(
|
||||
tenant_id: uuid.UUID,
|
||||
body: TenantUpdate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: object = Depends(require_admin),
|
||||
):
|
||||
tenant = await service.update_tenant(
|
||||
db, tenant_id,
|
||||
name=body.name,
|
||||
slug=body.slug,
|
||||
is_active=body.is_active,
|
||||
)
|
||||
if not tenant:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found")
|
||||
return TenantOut.model_validate(tenant)
|
||||
|
||||
|
||||
@router.delete("/{tenant_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_tenant(
|
||||
tenant_id: uuid.UUID,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: object = Depends(require_admin),
|
||||
):
|
||||
ok = await service.delete_tenant(db, tenant_id)
|
||||
if not ok:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Tenant not found or still has users assigned",
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class TenantCreate(BaseModel):
|
||||
name: str
|
||||
slug: str
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class TenantUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
slug: str | None = None
|
||||
is_active: bool | None = None
|
||||
|
||||
|
||||
class TenantOut(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
slug: str
|
||||
is_active: bool
|
||||
user_count: int | None = None
|
||||
created_at: datetime
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
@@ -0,0 +1,76 @@
|
||||
import uuid
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, func
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.domains.tenants.models import Tenant
|
||||
from app.domains.auth.models import User
|
||||
|
||||
|
||||
async def list_tenants(db: AsyncSession) -> list[dict]:
|
||||
"""Return all tenants with user counts."""
|
||||
result = await db.execute(
|
||||
select(
|
||||
Tenant,
|
||||
func.count(User.id).label("user_count"),
|
||||
)
|
||||
.outerjoin(User, User.tenant_id == Tenant.id)
|
||||
.group_by(Tenant.id)
|
||||
.order_by(Tenant.created_at)
|
||||
)
|
||||
rows = result.all()
|
||||
tenants = []
|
||||
for tenant, user_count in rows:
|
||||
tenants.append({"tenant": tenant, "user_count": user_count})
|
||||
return tenants
|
||||
|
||||
|
||||
async def get_tenant(db: AsyncSession, tenant_id: uuid.UUID) -> Tenant | None:
|
||||
result = await db.execute(select(Tenant).where(Tenant.id == tenant_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def create_tenant(db: AsyncSession, name: str, slug: str, is_active: bool = True) -> Tenant:
|
||||
tenant = Tenant(name=name, slug=slug, is_active=is_active)
|
||||
db.add(tenant)
|
||||
await db.commit()
|
||||
await db.refresh(tenant)
|
||||
return tenant
|
||||
|
||||
|
||||
async def update_tenant(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
name: str | None = None,
|
||||
slug: str | None = None,
|
||||
is_active: bool | None = None,
|
||||
) -> Tenant | None:
|
||||
tenant = await get_tenant(db, tenant_id)
|
||||
if not tenant:
|
||||
return None
|
||||
if name is not None:
|
||||
tenant.name = name
|
||||
if slug is not None:
|
||||
tenant.slug = slug
|
||||
if is_active is not None:
|
||||
tenant.is_active = is_active
|
||||
await db.commit()
|
||||
await db.refresh(tenant)
|
||||
return tenant
|
||||
|
||||
|
||||
async def delete_tenant(db: AsyncSession, tenant_id: uuid.UUID) -> bool:
|
||||
"""Delete a tenant. Returns False if tenant has users or does not exist."""
|
||||
tenant = await get_tenant(db, tenant_id)
|
||||
if not tenant:
|
||||
return False
|
||||
# Check for users
|
||||
result = await db.execute(
|
||||
select(func.count(User.id)).where(User.tenant_id == tenant_id)
|
||||
)
|
||||
user_count = result.scalar_one()
|
||||
if user_count > 0:
|
||||
return False
|
||||
await db.delete(tenant)
|
||||
await db.commit()
|
||||
return True
|
||||
Reference in New Issue
Block a user