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

Update app/api/products.py

Browse files
Files changed (1) hide show
  1. app/api/products.py +133 -130
app/api/products.py CHANGED
@@ -1,131 +1,134 @@
1
- from fastapi import APIRouter, HTTPException, status, Depends, Query
2
- from sqlalchemy.ext.asyncio import AsyncSession
3
- from sqlalchemy import select
4
- from typing import List, Optional
5
- from ..core.dependencies import get_current_active_user
6
- from ..db.database import get_db
7
- from ..db.models import Product, User
8
- from ..db.schemas import ProductCreate, ProductInDB
9
-
10
- router = APIRouter()
11
-
12
- @router.post("/", response_model=ProductInDB)
13
- async def create_product(
14
- product: ProductCreate,
15
- current_user: User = Depends(get_current_active_user),
16
- db: AsyncSession = Depends(get_db)
17
- ) -> ProductInDB:
18
- # Ensure user belongs to the branch they're creating the product for
19
- if current_user.branch_id != product.branch_id and not current_user.is_superuser:
20
- raise HTTPException(
21
- status_code=403,
22
- detail="You can only create products for your own branch"
23
- )
24
-
25
- db_product = Product(**product.dict())
26
- db.add(db_product)
27
- await db.commit()
28
- await db.refresh(db_product)
29
- return db_product
30
-
31
- @router.get("/", response_model=List[ProductInDB])
32
- async def list_products(
33
- skip: int = 0,
34
- limit: int = 10,
35
- category: Optional[str] = None,
36
- branch_id: Optional[int] = Query(None, description="Filter products by branch"),
37
- current_user: User = Depends(get_current_active_user),
38
- db: AsyncSession = Depends(get_db)
39
- ) -> List[ProductInDB]:
40
- query = select(Product)
41
-
42
- # Filter by category if provided
43
- if category:
44
- query = query.where(Product.category == category)
45
-
46
- # Filter by branch if provided, otherwise use user's branch
47
- if branch_id:
48
- if not current_user.is_superuser and branch_id != current_user.branch_id:
49
- raise HTTPException(
50
- status_code=403,
51
- detail="You can only view products from your own branch"
52
- )
53
- query = query.where(Product.branch_id == branch_id)
54
- elif not current_user.is_superuser:
55
- # Non-superusers can only see products from their branch
56
- query = query.where(Product.branch_id == current_user.branch_id)
57
-
58
- query = query.offset(skip).limit(limit)
59
- result = await db.execute(query)
60
- return result.scalars().all()
61
-
62
- @router.get("/{product_id}", response_model=ProductInDB)
63
- async def get_product(
64
- product_id: int,
65
- current_user: User = Depends(get_current_active_user),
66
- db: AsyncSession = Depends(get_db)
67
- ) -> ProductInDB:
68
- stmt = select(Product).where(Product.id == product_id)
69
- result = await db.execute(stmt)
70
- product = result.scalar_one_or_none()
71
-
72
- if not product:
73
- raise HTTPException(status_code=404, detail="Product not found")
74
-
75
- # Check if user has access to this product's branch
76
- if not current_user.is_superuser and product.branch_id != current_user.branch_id:
77
- raise HTTPException(status_code=403, detail="You cannot access products from other branches")
78
-
79
- return product
80
-
81
- @router.put("/{product_id}", response_model=ProductInDB)
82
- async def update_product(
83
- product_id: int,
84
- product_update: ProductCreate,
85
- current_user: User = Depends(get_current_active_user),
86
- db: AsyncSession = Depends(get_db)
87
- ) -> ProductInDB:
88
- stmt = select(Product).where(Product.id == product_id)
89
- result = await db.execute(stmt)
90
- product = result.scalar_one_or_none()
91
-
92
- if not product:
93
- raise HTTPException(status_code=404, detail="Product not found")
94
-
95
- # Check if user has access to this product's branch
96
- if not current_user.is_superuser and product.branch_id != current_user.branch_id:
97
- raise HTTPException(status_code=403, detail="You cannot modify products from other branches")
98
-
99
- # Ensure the branch isn't being changed to a different branch
100
- if product_update.branch_id != product.branch_id:
101
- raise HTTPException(status_code=400, detail="Cannot change product's branch")
102
-
103
- # Update product fields
104
- update_data = product_update.dict(exclude_unset=True)
105
- for field, value in update_data.items():
106
- setattr(product, field, value)
107
-
108
- await db.commit()
109
- await db.refresh(product)
110
- return product
111
-
112
- @router.delete("/{product_id}")
113
- async def delete_product(
114
- product_id: int,
115
- current_user: User = Depends(get_current_active_user),
116
- db: AsyncSession = Depends(get_db)
117
- ):
118
- stmt = select(Product).where(Product.id == product_id)
119
- result = await db.execute(stmt)
120
- product = result.scalar_one_or_none()
121
-
122
- if not product:
123
- raise HTTPException(status_code=404, detail="Product not found")
124
-
125
- # Check if user has access to this product's branch
126
- if not current_user.is_superuser and product.branch_id != current_user.branch_id:
127
- raise HTTPException(status_code=403, detail="You cannot delete products from other branches")
128
-
129
- await db.delete(product)
130
- await db.commit()
 
 
 
131
  return {"status": "success", "message": "Product deleted"}
 
1
+ from fastapi import APIRouter, HTTPException, status, Depends, Query
2
+ from sqlalchemy.ext.asyncio import AsyncSession
3
+ from sqlalchemy import select
4
+ from typing import List, Optional
5
+ from ..core.dependencies import get_current_active_user
6
+ from ..db.database import get_db
7
+ from ..db.models import Product, User
8
+ from ..db.schemas import ProductCreate, ProductInDB
9
+
10
+ router = APIRouter()
11
+
12
+ @router.post("/", response_model=ProductInDB)
13
+ async def create_product(
14
+ product: ProductCreate,
15
+ current_user: User = Depends(get_current_active_user),
16
+ db: AsyncSession = Depends(get_db)
17
+ ) -> ProductInDB:
18
+ # Ensure user belongs to the branch they're creating the product for
19
+ if current_user.branch_id != product.branch_id and not current_user.is_superuser:
20
+ raise HTTPException(
21
+ status_code=403,
22
+ detail="You can only create products for your own branch"
23
+ )
24
+
25
+ # Create product with current user as seller
26
+ product_data = product.dict()
27
+ product_data["seller_id"] = current_user.id
28
+ db_product = Product(**product_data)
29
+ db.add(db_product)
30
+ await db.commit()
31
+ await db.refresh(db_product)
32
+ return db_product
33
+
34
+ @router.get("/", response_model=List[ProductInDB])
35
+ async def list_products(
36
+ skip: int = 0,
37
+ limit: int = 10,
38
+ category: Optional[str] = None,
39
+ branch_id: Optional[int] = Query(None, description="Filter products by branch"),
40
+ current_user: User = Depends(get_current_active_user),
41
+ db: AsyncSession = Depends(get_db)
42
+ ) -> List[ProductInDB]:
43
+ query = select(Product)
44
+
45
+ # Filter by category if provided
46
+ if category:
47
+ query = query.where(Product.category == category)
48
+
49
+ # Filter by branch if provided, otherwise use user's branch
50
+ if branch_id:
51
+ if not current_user.is_superuser and branch_id != current_user.branch_id:
52
+ raise HTTPException(
53
+ status_code=403,
54
+ detail="You can only view products from your own branch"
55
+ )
56
+ query = query.where(Product.branch_id == branch_id)
57
+ elif not current_user.is_superuser:
58
+ # Non-superusers can only see products from their branch
59
+ query = query.where(Product.branch_id == current_user.branch_id)
60
+
61
+ query = query.offset(skip).limit(limit)
62
+ result = await db.execute(query)
63
+ return result.scalars().all()
64
+
65
+ @router.get("/{product_id}", response_model=ProductInDB)
66
+ async def get_product(
67
+ product_id: int,
68
+ current_user: User = Depends(get_current_active_user),
69
+ db: AsyncSession = Depends(get_db)
70
+ ) -> ProductInDB:
71
+ stmt = select(Product).where(Product.id == product_id)
72
+ result = await db.execute(stmt)
73
+ product = result.scalar_one_or_none()
74
+
75
+ if not product:
76
+ raise HTTPException(status_code=404, detail="Product not found")
77
+
78
+ # Check if user has access to this product's branch
79
+ if not current_user.is_superuser and product.branch_id != current_user.branch_id:
80
+ raise HTTPException(status_code=403, detail="You cannot access products from other branches")
81
+
82
+ return product
83
+
84
+ @router.put("/{product_id}", response_model=ProductInDB)
85
+ async def update_product(
86
+ product_id: int,
87
+ product_update: ProductCreate,
88
+ current_user: User = Depends(get_current_active_user),
89
+ db: AsyncSession = Depends(get_db)
90
+ ) -> ProductInDB:
91
+ stmt = select(Product).where(Product.id == product_id)
92
+ result = await db.execute(stmt)
93
+ product = result.scalar_one_or_none()
94
+
95
+ if not product:
96
+ raise HTTPException(status_code=404, detail="Product not found")
97
+
98
+ # Check if user has access to this product's branch
99
+ if not current_user.is_superuser and product.branch_id != current_user.branch_id:
100
+ raise HTTPException(status_code=403, detail="You cannot modify products from other branches")
101
+
102
+ # Ensure the branch isn't being changed to a different branch
103
+ if product_update.branch_id != product.branch_id:
104
+ raise HTTPException(status_code=400, detail="Cannot change product's branch")
105
+
106
+ # Update product fields
107
+ update_data = product_update.dict(exclude_unset=True)
108
+ for field, value in update_data.items():
109
+ setattr(product, field, value)
110
+
111
+ await db.commit()
112
+ await db.refresh(product)
113
+ return product
114
+
115
+ @router.delete("/{product_id}")
116
+ async def delete_product(
117
+ product_id: int,
118
+ current_user: User = Depends(get_current_active_user),
119
+ db: AsyncSession = Depends(get_db)
120
+ ):
121
+ stmt = select(Product).where(Product.id == product_id)
122
+ result = await db.execute(stmt)
123
+ product = result.scalar_one_or_none()
124
+
125
+ if not product:
126
+ raise HTTPException(status_code=404, detail="Product not found")
127
+
128
+ # Check if user has access to this product's branch
129
+ if not current_user.is_superuser and product.branch_id != current_user.branch_id:
130
+ raise HTTPException(status_code=403, detail="You cannot delete products from other branches")
131
+
132
+ await db.delete(product)
133
+ await db.commit()
134
  return {"status": "success", "message": "Product deleted"}