58 lines
2.0 KiB
Python
58 lines
2.0 KiB
Python
from uuid import UUID
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.database import get_db
|
|
from app.api.deps import get_current_active_user
|
|
from app.models import User, Session, SessionRating
|
|
from app.schemas.analytics import SessionRatingCreate, SessionRatingResponse
|
|
|
|
router = APIRouter(tags=["ratings"])
|
|
|
|
|
|
@router.post("/sessions/{session_id}/rate", response_model=SessionRatingResponse, status_code=status.HTTP_201_CREATED)
|
|
async def rate_session(
|
|
session_id: UUID,
|
|
data: SessionRatingCreate,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_active_user),
|
|
):
|
|
"""Submit a CSAT rating (1-5) for a completed session."""
|
|
# Verify session exists and belongs to user
|
|
result = await db.execute(select(Session).where(Session.id == session_id))
|
|
session = result.scalar_one_or_none()
|
|
if not session:
|
|
raise HTTPException(status_code=404, detail="Session not found")
|
|
if session.user_id != current_user.id:
|
|
raise HTTPException(status_code=403, detail="Not your session")
|
|
if not session.completed_at:
|
|
raise HTTPException(status_code=400, detail="Session not completed yet")
|
|
|
|
# Check for duplicate
|
|
existing = await db.execute(
|
|
select(SessionRating).where(SessionRating.session_id == session_id)
|
|
)
|
|
if existing.scalar_one_or_none():
|
|
raise HTTPException(status_code=409, detail="Session already rated")
|
|
|
|
rating = SessionRating(
|
|
session_id=session_id,
|
|
user_id=current_user.id,
|
|
tree_id=session.tree_id,
|
|
account_id=current_user.account_id,
|
|
rating=data.rating,
|
|
comment=data.comment,
|
|
)
|
|
db.add(rating)
|
|
await db.commit()
|
|
await db.refresh(rating)
|
|
|
|
return SessionRatingResponse(
|
|
id=str(rating.id),
|
|
session_id=str(rating.session_id),
|
|
rating=rating.rating,
|
|
comment=rating.comment,
|
|
created_at=rating.created_at,
|
|
)
|