Fred808 commited on
Commit
49a2b31
·
verified ·
1 Parent(s): 8a44fbc

Update app/api/branches.py

Browse files
Files changed (1) hide show
  1. app/api/branches.py +127 -89
app/api/branches.py CHANGED
@@ -1,89 +1,127 @@
1
- from fastapi import APIRouter, HTTPException, Depends
2
- from sqlalchemy.ext.asyncio import AsyncSession
3
- from sqlalchemy import select
4
- from typing import List
5
- from ..core.dependencies import get_current_superuser
6
- from ..db.database import get_db
7
- from ..db.models import Branch
8
- from ..db.schemas import BranchCreate, BranchInDB
9
-
10
- router = APIRouter()
11
-
12
- @router.post("/", response_model=BranchInDB)
13
- async def create_branch(
14
- branch: BranchCreate,
15
- current_user = Depends(get_current_superuser),
16
- db: AsyncSession = Depends(get_db)
17
- ) -> BranchInDB:
18
- """Create a new branch (superuser only)"""
19
- db_branch = Branch(**branch.dict())
20
- db.add(db_branch)
21
- await db.commit()
22
- await db.refresh(db_branch)
23
- return db_branch
24
-
25
- @router.get("/", response_model=List[BranchInDB])
26
- async def list_branches(
27
- skip: int = 0,
28
- limit: int = 100,
29
- db: AsyncSession = Depends(get_db)
30
- ) -> List[BranchInDB]:
31
- """List all branches"""
32
- query = select(Branch).offset(skip).limit(limit)
33
- result = await db.execute(query)
34
- return result.scalars().all()
35
-
36
- @router.get("/{branch_id}", response_model=BranchInDB)
37
- async def get_branch(
38
- branch_id: int,
39
- db: AsyncSession = Depends(get_db)
40
- ) -> BranchInDB:
41
- """Get a specific branch"""
42
- stmt = select(Branch).where(Branch.id == branch_id)
43
- result = await db.execute(stmt)
44
- branch = result.scalar_one_or_none()
45
-
46
- if not branch:
47
- raise HTTPException(status_code=404, detail="Branch not found")
48
- return branch
49
-
50
- @router.put("/{branch_id}", response_model=BranchInDB)
51
- async def update_branch(
52
- branch_id: int,
53
- branch_update: BranchCreate,
54
- current_user = Depends(get_current_superuser),
55
- db: AsyncSession = Depends(get_db)
56
- ) -> BranchInDB:
57
- """Update a branch (superuser only)"""
58
- stmt = select(Branch).where(Branch.id == branch_id)
59
- result = await db.execute(stmt)
60
- branch = result.scalar_one_or_none()
61
-
62
- if not branch:
63
- raise HTTPException(status_code=404, detail="Branch not found")
64
-
65
- # Update branch fields
66
- for field, value in branch_update.dict().items():
67
- setattr(branch, field, value)
68
-
69
- await db.commit()
70
- await db.refresh(branch)
71
- return branch
72
-
73
- @router.delete("/{branch_id}")
74
- async def delete_branch(
75
- branch_id: int,
76
- current_user = Depends(get_current_superuser),
77
- db: AsyncSession = Depends(get_db)
78
- ):
79
- """Delete a branch (superuser only)"""
80
- stmt = select(Branch).where(Branch.id == branch_id)
81
- result = await db.execute(stmt)
82
- branch = result.scalar_one_or_none()
83
-
84
- if not branch:
85
- raise HTTPException(status_code=404, detail="Branch not found")
86
-
87
- await db.delete(branch)
88
- await db.commit()
89
- return {"status": "success", "message": "Branch deleted"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException, Depends
2
+ from sqlalchemy.ext.asyncio import AsyncSession
3
+ from sqlalchemy import select
4
+ from typing import List
5
+ import logging
6
+ from ..core.dependencies import get_current_superuser
7
+ from ..db.database import get_db
8
+ from ..db.models import Branch
9
+ from ..db.schemas import BranchCreate, BranchInDB
10
+
11
+ router = APIRouter()
12
+ logger = logging.getLogger(__name__)
13
+
14
+ @router.post("/", response_model=BranchInDB)
15
+ async def create_branch(
16
+ branch: BranchCreate,
17
+ current_user = Depends(get_current_superuser),
18
+ db: AsyncSession = Depends(get_db)
19
+ ) -> BranchInDB:
20
+ """Create a new branch (superuser only)"""
21
+ logger.info(f"Creating branch with data: {branch.dict()}")
22
+ try:
23
+ db_branch = Branch(**branch.dict())
24
+ db.add(db_branch)
25
+ await db.commit()
26
+ await db.refresh(db_branch)
27
+ logger.info(f"Successfully created branch with id: {db_branch.id}")
28
+ return db_branch
29
+ except Exception as e:
30
+ logger.error(f"Error creating branch: {str(e)}")
31
+ await db.rollback()
32
+ raise
33
+
34
+ @router.get("/", response_model=List[BranchInDB])
35
+ async def list_branches(
36
+ skip: int = 0,
37
+ limit: int = 100,
38
+ db: AsyncSession = Depends(get_db)
39
+ ) -> List[BranchInDB]:
40
+ """List all branches"""
41
+ logger.info("Listing branches")
42
+ try:
43
+ query = select(Branch).offset(skip).limit(limit)
44
+ result = await db.execute(query)
45
+ branches = result.scalars().all()
46
+ logger.info(f"Found {len(list(branches))} branches")
47
+ return branches
48
+ except Exception as e:
49
+ logger.error(f"Error listing branches: {str(e)}")
50
+ raise
51
+
52
+ @router.get("/{branch_id}", response_model=BranchInDB)
53
+ async def get_branch(
54
+ branch_id: int,
55
+ db: AsyncSession = Depends(get_db)
56
+ ) -> BranchInDB:
57
+ """Get a specific branch"""
58
+ logger.info(f"Getting branch with id: {branch_id}")
59
+ try:
60
+ stmt = select(Branch).where(Branch.id == branch_id)
61
+ result = await db.execute(stmt)
62
+ branch = result.scalar_one_or_none()
63
+
64
+ if not branch:
65
+ logger.warning(f"Branch with id {branch_id} not found")
66
+ raise HTTPException(status_code=404, detail="Branch not found")
67
+ return branch
68
+ except Exception as e:
69
+ logger.error(f"Error getting branch: {str(e)}")
70
+ raise
71
+
72
+ @router.put("/{branch_id}", response_model=BranchInDB)
73
+ async def update_branch(
74
+ branch_id: int,
75
+ branch_update: BranchCreate,
76
+ current_user = Depends(get_current_superuser),
77
+ db: AsyncSession = Depends(get_db)
78
+ ) -> BranchInDB:
79
+ """Update a branch (superuser only)"""
80
+ logger.info(f"Updating branch with id: {branch_id} with data: {branch_update.dict()}")
81
+ try:
82
+ stmt = select(Branch).where(Branch.id == branch_id)
83
+ result = await db.execute(stmt)
84
+ branch = result.scalar_one_or_none()
85
+
86
+ if not branch:
87
+ logger.warning(f"Branch with id {branch_id} not found")
88
+ raise HTTPException(status_code=404, detail="Branch not found")
89
+
90
+ # Update branch fields
91
+ for field, value in branch_update.dict().items():
92
+ setattr(branch, field, value)
93
+
94
+ await db.commit()
95
+ await db.refresh(branch)
96
+ logger.info(f"Successfully updated branch with id: {branch.id}")
97
+ return branch
98
+ except Exception as e:
99
+ logger.error(f"Error updating branch: {str(e)}")
100
+ await db.rollback()
101
+ raise
102
+
103
+ @router.delete("/{branch_id}")
104
+ async def delete_branch(
105
+ branch_id: int,
106
+ current_user = Depends(get_current_superuser),
107
+ db: AsyncSession = Depends(get_db)
108
+ ):
109
+ """Delete a branch (superuser only)"""
110
+ logger.info(f"Deleting branch with id: {branch_id}")
111
+ try:
112
+ stmt = select(Branch).where(Branch.id == branch_id)
113
+ result = await db.execute(stmt)
114
+ branch = result.scalar_one_or_none()
115
+
116
+ if not branch:
117
+ logger.warning(f"Branch with id {branch_id} not found")
118
+ raise HTTPException(status_code=404, detail="Branch not found")
119
+
120
+ await db.delete(branch)
121
+ await db.commit()
122
+ logger.info(f"Successfully deleted branch with id: {branch_id}")
123
+ return {"status": "success", "message": "Branch deleted"}
124
+ except Exception as e:
125
+ logger.error(f"Error deleting branch: {str(e)}")
126
+ await db.rollback()
127
+ raise