After_Chido_Api/services/person_report_service.py

57 lines
2.2 KiB
Python

from sqlalchemy import select, update
from fastapi import HTTPException
from models.schemas import PersonReportCreate, PersonReportUpdate, PersonReportResponse
from config.database import get_db
from models.db import person_reports_table
from typing import Optional
from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")
class PersonReportService:
@staticmethod
async def create_report(report: PersonReportCreate, db):
query = person_reports_table.insert().values(**report.dict())
try:
result = await db.execute(query)
await db.commit()
report_id = result.inserted_primary_key[0]
return await PersonReportService.get_report(report_id, db)
except Exception as e:
await db.rollback()
raise HTTPException(status_code=500, detail=f"Could not create report: {str(e)}")
@staticmethod
async def update_report(report_id: int, report: PersonReportUpdate, db):
query = (
person_reports_table.update()
.where(person_reports_table.c.id == report_id)
.values(**report.dict(exclude_unset=True))
)
try:
await db.execute(query)
await db.commit()
return await PersonReportService.get_report(report_id, db)
except Exception as e:
await db.rollback()
raise HTTPException(status_code=500, detail=f"Could not update report: {str(e)}")
@staticmethod
async def get_report(report_id: int, db):
query = select(person_reports_table).where(person_reports_table.c.id == report_id)
result = await db.execute(query)
report = result.fetchone()
if not report:
raise HTTPException(status_code=404, detail="Report not found")
return PersonReportResponse(**report)
@staticmethod
async def list_reports(status: Optional[str] = None, db=Depends(get_db)):
query = select(person_reports_table)
if status:
query = query.where(person_reports_table.c.status == status)
result = await db.execute(query)
reports = result.fetchall()
return [PersonReportResponse(**report) for report in reports]