53 lines
2.4 KiB
Python
53 lines
2.4 KiB
Python
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
from pydantic import BaseModel
|
|
from typing import Optional
|
|
from app.database import get_db
|
|
from app.models.user import User
|
|
from app.models.shopping_list import ShoppingItem
|
|
from app.utils.security import get_current_user
|
|
|
|
router = APIRouter(prefix="/api", tags=["shopping"])
|
|
|
|
class ShoppingAdd(BaseModel):
|
|
product_name: str
|
|
barcode: Optional[str] = None
|
|
|
|
@router.post("/shopping-list")
|
|
async def add_to_list(data: ShoppingAdd, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
|
item = ShoppingItem(user_id=user.id, product_name=data.product_name, barcode=data.barcode)
|
|
db.add(item)
|
|
await db.commit()
|
|
await db.refresh(item)
|
|
return {"id": item.id, "product_name": item.product_name, "barcode": item.barcode, "checked": item.checked, "added_at": item.added_at.isoformat()}
|
|
|
|
@router.get("/shopping-list")
|
|
async def get_list(user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
|
res = await db.execute(
|
|
select(ShoppingItem).where(ShoppingItem.user_id == user.id).order_by(ShoppingItem.added_at.desc())
|
|
)
|
|
items = res.scalars().all()
|
|
return [{"id": i.id, "product_name": i.product_name, "barcode": i.barcode, "checked": i.checked,
|
|
"added_at": i.added_at.isoformat()} for i in items]
|
|
|
|
@router.delete("/shopping-list/{item_id}")
|
|
async def delete_item(item_id: int, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
|
res = await db.execute(select(ShoppingItem).where(ShoppingItem.id == item_id, ShoppingItem.user_id == user.id))
|
|
item = res.scalar_one_or_none()
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item não encontrado")
|
|
await db.delete(item)
|
|
await db.commit()
|
|
return {"ok": True}
|
|
|
|
@router.put("/shopping-list/{item_id}/toggle")
|
|
async def toggle_item(item_id: int, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
|
res = await db.execute(select(ShoppingItem).where(ShoppingItem.id == item_id, ShoppingItem.user_id == user.id))
|
|
item = res.scalar_one_or_none()
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item não encontrado")
|
|
item.checked = not item.checked
|
|
await db.commit()
|
|
return {"id": item.id, "checked": item.checked}
|