File size: 4,412 Bytes
49a2b31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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