from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from app.database import get_postgres_session from app.deps.org_manager import require_org_manager from app.models import Account from app.schemas import OrgSectionCreate, OrgSectionRead from app.services.org_sections import create_org_section, list_org_sections router = APIRouter(prefix="/sections", tags=["sections"]) @router.get("", response_model=list[OrgSectionRead]) async def get_sections( manager: Account = Depends(require_org_manager), session: AsyncSession = Depends(get_postgres_session), ) -> list[OrgSectionRead]: sections = await list_org_sections(session, manager.company_domain) await session.commit() return sections @router.post("", response_model=OrgSectionRead, status_code=status.HTTP_201_CREATED) async def add_section( payload: OrgSectionCreate, manager: Account = Depends(require_org_manager), session: AsyncSession = Depends(get_postgres_session), ) -> OrgSectionRead: try: section = await create_org_section( session, manager.company_domain, payload, ) await session.commit() return section except ValueError as error: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error), ) from error except IntegrityError as error: await session.rollback() raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail="That section could not be created.", ) from error