Files
saas_backend/app/services/auth/tenant_service.py
T
2026-01-17 14:18:00 +05:30

119 lines
4.2 KiB
Python

from sqlalchemy.orm import Session
from sqlalchemy import or_, cast, String
from fastapi import HTTPException, status
from app.models.auth.tenant_model import Tenant
from app.schemas.auth.tenant_schema import TenantCreate, TenantUpdate, TenantPaginatedResponse, TenantResponse
import uuid
from typing import Optional
class TenantService:
@staticmethod
def create_tenant(db: Session, tenant_data: TenantCreate) -> Tenant:
existing = db.query(Tenant).filter(Tenant.tenant_name == tenant_data.tenant_name).first()
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Tenant name already exists"
)
existing = db.query(Tenant).filter(Tenant.tenant_domain == tenant_data.tenant_domain).first()
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Tenant domain already exists"
)
tenant = Tenant(
tenant_name=tenant_data.tenant_name,
tenant_domain=tenant_data.tenant_domain,
tenant_logo_url=tenant_data.tenant_logo_url
)
db.add(tenant)
db.commit()
db.refresh(tenant)
return tenant
@staticmethod
def get_all_tenants(db: Session):
return db.query(Tenant).all()
@staticmethod
def get_tenant_by_id(db: Session, tenant_id: uuid.UUID) -> Tenant:
tenant = db.query(Tenant).filter(Tenant.id == tenant_id).first()
if not tenant:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Tenant not found"
)
return tenant
@staticmethod
def update_tenant(db: Session, tenant_id: uuid.UUID, tenant_data: TenantUpdate) -> Tenant:
tenant = TenantService.get_tenant_by_id(db, tenant_id)
update_dict = tenant_data.model_dump(exclude_unset=True)
if "tenant_name" in update_dict and update_dict["tenant_name"] != tenant.tenant_name:
existing = db.query(Tenant).filter(Tenant.tenant_name == update_dict["tenant_name"]).first()
if existing:
raise HTTPException(status_code=400, detail="Tenant name already exists")
if "tenant_domain" in update_dict and update_dict["tenant_domain"] != tenant.tenant_domain:
existing = db.query(Tenant).filter(Tenant.tenant_domain == update_dict["tenant_domain"]).first()
if existing:
raise HTTPException(status_code=400, detail="Tenant domain already exists")
for key, value in update_dict.items():
setattr(tenant, key, value)
db.commit()
db.refresh(tenant)
return tenant
@staticmethod
def delete_tenant(db: Session, tenant_id: uuid.UUID):
tenant = TenantService.get_tenant_by_id(db, tenant_id)
db.delete(tenant)
db.commit()
return {"message": "Tenant deleted successfully"}
@staticmethod
def get_tenants_paginated(
db: Session,
page: int = 1,
page_size: int = 10,
search: Optional[str] = None,
is_active: Optional[bool] = None,
) -> TenantPaginatedResponse:
query = db.query(Tenant)
if search and search.strip():
search_term = search.strip()
query = query.filter(
or_(
Tenant.tenant_name.ilike(f"%{search_term}%"),
Tenant.tenant_domain.ilike(f"%{search_term}%"),
cast(Tenant.id, String).ilike(f"%{search_term}%"),
)
)
if is_active is not None:
query = query.filter(Tenant.is_active == is_active)
total = query.count()
offset = (page - 1) * page_size
tenants = query.offset(offset).limit(page_size).all()
total_pages = (total + page_size - 1) // page_size if total > 0 else 0
return TenantPaginatedResponse(
items=[TenantResponse.from_orm(tenant) for tenant in tenants],
total=total,
page=page,
page_size=page_size,
total_pages=total_pages,
)