|
| 1 | +from fastapi import HTTPException, status |
| 2 | +from sqlalchemy.orm import Session |
| 3 | + |
| 4 | +from app.repository.theme_repository import ThemeRepository |
| 5 | +from app.schemas.theme_schemas import ThemeUpdateSchema, ThemeResponseSchema |
| 6 | + |
| 7 | + |
| 8 | +def update_theme( |
| 9 | + theme_id: str, |
| 10 | + user_id: str, |
| 11 | + data: ThemeUpdateSchema, |
| 12 | + db: Session |
| 13 | +) -> ThemeResponseSchema: |
| 14 | + |
| 15 | + try: |
| 16 | + repository = ThemeRepository(db) |
| 17 | + theme = repository.get_theme_by_id(theme_id) |
| 18 | + |
| 19 | + if not theme: |
| 20 | + raise HTTPException( |
| 21 | + status_code=status.HTTP_404_NOT_FOUND, |
| 22 | + detail="Theme not found" |
| 23 | + ) |
| 24 | + |
| 25 | + if theme.user_id != user_id: |
| 26 | + raise HTTPException( |
| 27 | + status_code=status.HTTP_403_FORBIDDEN, |
| 28 | + detail="Access denied" |
| 29 | + ) |
| 30 | + |
| 31 | + update_data = data.model_dump(exclude_unset=True) |
| 32 | + |
| 33 | + if not update_data: |
| 34 | + raise HTTPException( |
| 35 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 36 | + detail="At least one field must be provided for update" |
| 37 | + ) |
| 38 | + |
| 39 | + if "title" in update_data and update_data["title"] is not None: |
| 40 | + if not update_data["title"].strip(): |
| 41 | + raise HTTPException( |
| 42 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 43 | + detail="Title cannot be empty" |
| 44 | + ) |
| 45 | + |
| 46 | + if "description" in update_data and update_data["description"] is not None: |
| 47 | + if not update_data["description"].strip(): |
| 48 | + raise HTTPException( |
| 49 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 50 | + detail="Description cannot be empty" |
| 51 | + ) |
| 52 | + |
| 53 | + updated_theme = repository.update_theme(theme_id, update_data) |
| 54 | + |
| 55 | + return ThemeResponseSchema.model_validate(updated_theme) |
| 56 | + |
| 57 | + except HTTPException: |
| 58 | + raise |
| 59 | + |
| 60 | + except Exception as e: |
| 61 | + raise HTTPException( |
| 62 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 63 | + detail=f"Error updating theme: {str(e)}" |
| 64 | + ) |
0 commit comments