After_Chido_Api/services/report_service.py

1 line
2.9 KiB
Python

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 HTTPException, status
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.dict()}
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):
query = select(user_reports_table).where(user_reports_table.c.id == report_id)
result = await db.execute(query)
report = result.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):
query = select(user_reports_table)
result = await db.execute(query)
reports = result.fetchall()
return [dict(report) for report in reports]
@staticmethod
async def update_report(report_id: int, report_update: UserReportUpdate, db):
query = (
update(user_reports_table)
.where(user_reports_table.c.id == report_id)
.values(**report_update.dict(exclude_unset=True))
.returning(user_reports_table.c.id)
)
try:
result = await db.execute(query)
await db.commit()
updated_id = result.fetchone()
if not updated_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Report not found")
return {"id": updated_id[0], **report_update.dict()}
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):
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)}")