v0.2 - 19 features: comparator, allergies, gamification, shopping list, achievements, stats, profile, share, bottom nav
This commit is contained in:
48
backend/app/routers/compare.py
Normal file
48
backend/app/routers/compare.py
Normal file
@@ -0,0 +1,48 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
import json
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
from app.models.scan import Scan
|
||||
from app.models.product import Product
|
||||
from app.utils.security import get_current_user
|
||||
from app.services.achievements import check_achievements
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["compare"])
|
||||
|
||||
@router.post("/compare")
|
||||
async def compare_products(data: dict, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||
scan_ids = data.get("scan_ids", [])
|
||||
if len(scan_ids) < 2 or len(scan_ids) > 4:
|
||||
raise HTTPException(status_code=400, detail="Selecione entre 2 e 4 produtos")
|
||||
|
||||
results = []
|
||||
for sid in scan_ids:
|
||||
res = await db.execute(select(Scan).where(Scan.id == sid, Scan.user_id == user.id))
|
||||
scan = res.scalar_one_or_none()
|
||||
if not scan:
|
||||
raise HTTPException(status_code=404, detail=f"Scan {sid} não encontrado")
|
||||
|
||||
analysis = json.loads(scan.analysis_json or '{}')
|
||||
prod_res = await db.execute(select(Product).where(Product.barcode == scan.barcode))
|
||||
product = prod_res.scalar_one_or_none()
|
||||
|
||||
results.append({
|
||||
"scan_id": scan.id,
|
||||
"product_name": scan.product_name,
|
||||
"brand": scan.brand,
|
||||
"score": scan.score,
|
||||
"image_url": product.image_url if product else None,
|
||||
"nutri_score": product.nutri_score if product else None,
|
||||
"nova_group": product.nova_group if product else None,
|
||||
"positives": analysis.get("positives", []),
|
||||
"negatives": analysis.get("negatives", []),
|
||||
"nutrition": analysis.get("nutrition", {}),
|
||||
"nutrition_verdict": analysis.get("nutrition_verdict", ""),
|
||||
})
|
||||
|
||||
# Check comparison achievement
|
||||
await check_achievements(user.id, db, action="compare")
|
||||
|
||||
return {"products": results}
|
||||
Reference in New Issue
Block a user