Admin-Desk2 / app /api /branches.py
Fred808's picture
Update app/api/branches.py
49a2b31 verified
from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import List
import logging
from ..core.dependencies import get_current_superuser
from ..db.database import get_db
from ..db.models import Branch
from ..db.schemas import BranchCreate, BranchInDB
router = APIRouter()
logger = logging.getLogger(__name__)
@router.post("/", response_model=BranchInDB)
async def create_branch(
branch: BranchCreate,
current_user = Depends(get_current_superuser),
db: AsyncSession = Depends(get_db)
) -> BranchInDB:
"""Create a new branch (superuser only)"""
logger.info(f"Creating branch with data: {branch.dict()}")
try:
db_branch = Branch(**branch.dict())
db.add(db_branch)
await db.commit()
await db.refresh(db_branch)
logger.info(f"Successfully created branch with id: {db_branch.id}")
return db_branch
except Exception as e:
logger.error(f"Error creating branch: {str(e)}")
await db.rollback()
raise
@router.get("/", response_model=List[BranchInDB])
async def list_branches(
skip: int = 0,
limit: int = 100,
db: AsyncSession = Depends(get_db)
) -> List[BranchInDB]:
"""List all branches"""
logger.info("Listing branches")
try:
query = select(Branch).offset(skip).limit(limit)
result = await db.execute(query)
branches = result.scalars().all()
logger.info(f"Found {len(list(branches))} branches")
return branches
except Exception as e:
logger.error(f"Error listing branches: {str(e)}")
raise
@router.get("/{branch_id}", response_model=BranchInDB)
async def get_branch(
branch_id: int,
db: AsyncSession = Depends(get_db)
) -> BranchInDB:
"""Get a specific branch"""
logger.info(f"Getting branch with id: {branch_id}")
try:
stmt = select(Branch).where(Branch.id == branch_id)
result = await db.execute(stmt)
branch = result.scalar_one_or_none()
if not branch:
logger.warning(f"Branch with id {branch_id} not found")
raise HTTPException(status_code=404, detail="Branch not found")
return branch
except Exception as e:
logger.error(f"Error getting branch: {str(e)}")
raise
@router.put("/{branch_id}", response_model=BranchInDB)
async def update_branch(
branch_id: int,
branch_update: BranchCreate,
current_user = Depends(get_current_superuser),
db: AsyncSession = Depends(get_db)
) -> BranchInDB:
"""Update a branch (superuser only)"""
logger.info(f"Updating branch with id: {branch_id} with data: {branch_update.dict()}")
try:
stmt = select(Branch).where(Branch.id == branch_id)
result = await db.execute(stmt)
branch = result.scalar_one_or_none()
if not branch:
logger.warning(f"Branch with id {branch_id} not found")
raise HTTPException(status_code=404, detail="Branch not found")
# Update branch fields
for field, value in branch_update.dict().items():
setattr(branch, field, value)
await db.commit()
await db.refresh(branch)
logger.info(f"Successfully updated branch with id: {branch.id}")
return branch
except Exception as e:
logger.error(f"Error updating branch: {str(e)}")
await db.rollback()
raise
@router.delete("/{branch_id}")
async def delete_branch(
branch_id: int,
current_user = Depends(get_current_superuser),
db: AsyncSession = Depends(get_db)
):
"""Delete a branch (superuser only)"""
logger.info(f"Deleting branch with id: {branch_id}")
try:
stmt = select(Branch).where(Branch.id == branch_id)
result = await db.execute(stmt)
branch = result.scalar_one_or_none()
if not branch:
logger.warning(f"Branch with id {branch_id} not found")
raise HTTPException(status_code=404, detail="Branch not found")
await db.delete(branch)
await db.commit()
logger.info(f"Successfully deleted branch with id: {branch_id}")
return {"status": "success", "message": "Branch deleted"}
except Exception as e:
logger.error(f"Error deleting branch: {str(e)}")
await db.rollback()
raise