After_Chido_Api/services/report_service.py

86 lines
3.4 KiB
Python

from fastapi.security import OAuth2PasswordBearer
from sqlalchemy import insert, update, select, delete
from models.schemas import UserReport, UserReportUpdate
from config.database import get_db
from models.db import user_reports_table
from fastapi import Depends, HTTPException, status
from services.auth_service import AuthService
class ReportService:
@staticmethod
async def create_report(report: UserReport, db):
query = insert(user_reports_table).values(
reporter_id=report.reporter_id,
reported_user_id=report.reported_user_id,
reason=report.reason,
status="pending" # Par défaut, le statut est "pending"
)
try:
result = await db.execute(query)
await db.commit()
report_id = result.inserted_primary_key[0]
return {"id": report_id, **report.model_dump()}
except Exception as e:
await db.rollback()
raise HTTPException(status_code=500, detail=f"Could not create user report: {str(e)}")
@staticmethod
async def get_report_by_id(report_id: int, db, token: str):
await AuthService.admin_required(token, db)
query = select(user_reports_table).where(user_reports_table.c.id == report_id)
result = await db.execute(query)
report = result.mappings().fetchone()
if not report:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Report not found")
return dict(report)
@staticmethod
async def get_all_reports(db, token: str):
await AuthService.admin_required(token, db)
query = select(user_reports_table)
result = await db.execute(query)
reports = result.mappings().all()
return [dict(report) for report in reports]
@staticmethod
async def update_report(report_id: int, report_update: UserReportUpdate, db, token: str):
await AuthService.admin_required(token, db)
query = (
update(user_reports_table)
.where(user_reports_table.c.id == report_id)
.values(**report_update.model_dump(exclude_unset=True))
)
try:
await db.execute(query)
await db.commit()
# Récupérer le rapport mis à jour
select_query = select(user_reports_table).where(user_reports_table.c.id == report_id)
result = await db.execute(select_query)
updated_report = result.mappings().fetchone()
if not updated_report:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Report not found")
return dict(updated_report)
except Exception as e:
await db.rollback()
raise HTTPException(status_code=500, detail=f"Could not update report: {str(e)}")
@staticmethod
async def delete_report(report_id: int, db, token: str):
await AuthService.admin_required(token, db)
query = delete(user_reports_table).where(user_reports_table.c.id == report_id)
try:
result = await db.execute(query)
await db.commit()
if result.rowcount == 0:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Report not found")
return {"detail": "Report deleted successfully"}
except Exception as e:
await db.rollback()
raise HTTPException(status_code=500, detail=f"Could not delete report: {str(e)}")