Files
saas_backend/app/services/auth/tenant_module_service.py
T

87 lines
3.5 KiB
Python

from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from fastapi import HTTPException
from typing import List, Tuple
import uuid
from app.models.auth.tenant_model import Tenant
from app.models.auth.module_model import Module
from app.models.auth.tenant_module_model import TenantModule
from app.schemas.auth.tenant_module_schema import TenantModuleCreate, TenantModuleUpdate
class TenantModuleService:
@staticmethod
def list_tenant_modules(db: Session, tenant_id: str) -> List[Tuple[TenantModule, Module]]:
tenant = db.query(Tenant).filter(Tenant.id == uuid.UUID(tenant_id)).first()
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
return db.query(TenantModule, Module).join(
Module, TenantModule.module_id == Module.id
).filter(
TenantModule.tenant_id == tenant.id
).all()
@staticmethod
def assign_module(db: Session, tenant_id: str, assignment_data: TenantModuleCreate) -> TenantModule:
tenant = db.query(Tenant).filter(Tenant.id == uuid.UUID(tenant_id)).first()
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
module = db.query(Module).filter(Module.id == uuid.UUID(assignment_data.module_id)).first()
if not module:
raise HTTPException(status_code=404, detail="Module not found")
existing = db.query(TenantModule).filter(
TenantModule.tenant_id == tenant.id,
TenantModule.module_id == module.id
).first()
if existing:
raise HTTPException(status_code=409, detail="Module already assigned to this tenant")
try:
tenant_module = TenantModule(
tenant_id=tenant.id,
module_id=module.id,
assigned_environment_slug=assignment_data.assigned_environment_slug,
is_active=assignment_data.is_active,
module_config=assignment_data.module_config
)
db.add(tenant_module)
db.commit()
db.refresh(tenant_module)
return tenant_module
except IntegrityError:
db.rollback()
raise HTTPException(status_code=409, detail="Module assignment conflict")
@staticmethod
def update_assignment(db: Session, tenant_id: str, tenant_module_id: str, update_data: TenantModuleUpdate) -> TenantModule:
tenant_module = db.query(TenantModule).filter(
TenantModule.id == uuid.UUID(tenant_module_id),
TenantModule.tenant_id == uuid.UUID(tenant_id)
).first()
if not tenant_module:
raise HTTPException(status_code=404, detail="Tenant module assignment not found")
update_dict = update_data.model_dump(exclude_unset=True)
for key, value in update_dict.items():
setattr(tenant_module, key, value)
db.commit()
db.refresh(tenant_module)
return tenant_module
@staticmethod
def remove_assignment(db: Session, tenant_id: str, tenant_module_id: str):
tenant_module = db.query(TenantModule).filter(
TenantModule.id == uuid.UUID(tenant_module_id),
TenantModule.tenant_id == uuid.UUID(tenant_id)
).first()
if not tenant_module:
raise HTTPException(status_code=404, detail="Tenant module assignment not found")
db.delete(tenant_module)
db.commit()