97 lines
2.9 KiB
Python
97 lines
2.9 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlmodel import Session, select
|
|
from typing import List, Optional
|
|
from uuid import UUID
|
|
|
|
from app.core.database import get_session
|
|
from app.api.deps import get_current_admin, get_current_user_optional
|
|
from app.models.report import Report
|
|
from app.models.user import User
|
|
from app.schemas.report import ReportCreate, ReportUpdate, ReportResponse
|
|
|
|
router = APIRouter(prefix="/api/reports", tags=["reports"])
|
|
|
|
@router.post("", response_model=ReportResponse, status_code=status.HTTP_201_CREATED)
|
|
async def create_report(
|
|
report_in: ReportCreate,
|
|
session: Session = Depends(get_session),
|
|
current_user: Optional[User] = Depends(get_current_user_optional)
|
|
):
|
|
"""Create a new user report."""
|
|
report = Report(
|
|
message=report_in.message,
|
|
user_id=current_user.id if current_user else None
|
|
)
|
|
session.add(report)
|
|
session.commit()
|
|
session.refresh(report)
|
|
|
|
return ReportResponse(
|
|
id=report.id,
|
|
user_id=report.user_id,
|
|
user_name=current_user.full_name if current_user else "Anónimo",
|
|
message=report.message,
|
|
status=report.status,
|
|
created_at=report.created_at
|
|
)
|
|
|
|
@router.get("", response_model=List[ReportResponse])
|
|
async def get_reports(
|
|
session: Session = Depends(get_session),
|
|
admin_auth: bool = Depends(get_current_admin)
|
|
):
|
|
"""Get all reports (Admin only)."""
|
|
statement = select(Report)
|
|
results = session.exec(statement).all()
|
|
|
|
reports = []
|
|
for report in results:
|
|
user_name = "Anónimo"
|
|
if report.user_id:
|
|
user = session.get(User, report.user_id)
|
|
if user:
|
|
user_name = user.full_name
|
|
|
|
reports.append(ReportResponse(
|
|
id=report.id,
|
|
user_id=report.user_id,
|
|
user_name=user_name,
|
|
message=report.message,
|
|
status=report.status,
|
|
created_at=report.created_at
|
|
))
|
|
|
|
return reports
|
|
|
|
@router.patch("/{report_id}", response_model=ReportResponse)
|
|
async def update_report_status(
|
|
report_id: UUID,
|
|
report_update: ReportUpdate,
|
|
session: Session = Depends(get_session),
|
|
admin_auth: bool = Depends(get_current_admin)
|
|
):
|
|
"""Update report status (Admin only)."""
|
|
report = session.get(Report, report_id)
|
|
if not report:
|
|
raise HTTPException(status_code=404, detail="Report not found")
|
|
|
|
report.status = report_update.status
|
|
session.add(report)
|
|
session.commit()
|
|
session.refresh(report)
|
|
|
|
user_name = "Anónimo"
|
|
if report.user_id:
|
|
user = session.get(User, report.user_id)
|
|
if user:
|
|
user_name = user.full_name
|
|
|
|
return ReportResponse(
|
|
id=report.id,
|
|
user_id=report.user_id,
|
|
user_name=user_name,
|
|
message=report.message,
|
|
status=report.status,
|
|
created_at=report.created_at
|
|
)
|