78 lines
2.6 KiB
Python
78 lines
2.6 KiB
Python
import uuid
|
|
from datetime import datetime
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from ..database import get_db
|
|
from ..models.report import Report
|
|
from ..models.address import Address
|
|
from ..schemas.report import ReportCreate, ReportOut, ReportListItem
|
|
from .deps import get_current_user
|
|
|
|
router = APIRouter(prefix="/reports", tags=["reports"])
|
|
|
|
REPORT_TYPE_LABELS = {
|
|
"NO_PASO": "Camión no pasó",
|
|
"RETRASO": "Retraso en la ruta",
|
|
"ACUMULACION": "Acumulación de basura",
|
|
"OTRO": "Otro",
|
|
}
|
|
|
|
|
|
def _generate_folio() -> str:
|
|
date_str = datetime.utcnow().strftime("%Y%m%d")
|
|
short = str(uuid.uuid4())[:6].upper()
|
|
return f"MRL-{date_str}-{short}"
|
|
|
|
|
|
@router.post("/", response_model=ReportOut, status_code=201)
|
|
def create_report(data: ReportCreate, db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
address = db.query(Address).filter(Address.id == data.address_id, Address.user_id == user.id).first()
|
|
if not address:
|
|
raise HTTPException(status_code=404, detail="Domicilio no encontrado")
|
|
if data.report_type not in REPORT_TYPE_LABELS:
|
|
raise HTTPException(status_code=400, detail="Tipo de reporte inválido")
|
|
|
|
report = Report(
|
|
user_id=user.id,
|
|
address_id=data.address_id,
|
|
folio=_generate_folio(),
|
|
report_type=data.report_type,
|
|
description=data.description,
|
|
)
|
|
db.add(report)
|
|
db.commit()
|
|
db.refresh(report)
|
|
|
|
return ReportOut(
|
|
id=report.id,
|
|
folio=report.folio,
|
|
report_type=report.report_type,
|
|
description=report.description,
|
|
status=report.status,
|
|
created_at=report.created_at,
|
|
address_label=address.label,
|
|
)
|
|
|
|
|
|
@router.get("/", response_model=list[ReportListItem])
|
|
def list_reports(db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
reports = db.query(Report).filter(Report.user_id == user.id).order_by(Report.created_at.desc()).all()
|
|
return reports
|
|
|
|
|
|
@router.get("/{report_id}", response_model=ReportOut)
|
|
def get_report(report_id: int, db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
report = db.query(Report).filter(Report.id == report_id, Report.user_id == user.id).first()
|
|
if not report:
|
|
raise HTTPException(status_code=404, detail="Reporte no encontrado")
|
|
address = db.query(Address).filter(Address.id == report.address_id).first()
|
|
return ReportOut(
|
|
id=report.id,
|
|
folio=report.folio,
|
|
report_type=report.report_type,
|
|
description=report.description,
|
|
status=report.status,
|
|
created_at=report.created_at,
|
|
address_label=address.label if address else None,
|
|
)
|