Files
New-planet-api/new-planet-backend/app/api/v1/schedules.py

150 lines
5.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from datetime import date
from app.db.session import get_db
from app.api.deps import get_current_active_user
from app.models.user import User
from app.schemas.schedule import Schedule, ScheduleCreate, ScheduleUpdate
from app.crud import schedule as crud_schedule
from app.services.schedule_generator import schedule_generator
from app.schemas.ai import ScheduleGenerateRequest, ScheduleGenerateResponse
router = APIRouter()
@router.get("", response_model=List[Schedule])
async def get_schedules(
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=100),
schedule_date: date = Query(None),
current_user: User = Depends(get_current_active_user),
db: AsyncSession = Depends(get_db)
):
"""Получить список расписаний пользователя"""
if schedule_date:
schedule = await crud_schedule.get_by_date(db, current_user.id, schedule_date)
return [schedule] if schedule else []
else:
schedules = await crud_schedule.get_by_user(db, current_user.id, skip, limit)
return schedules
@router.get("/{schedule_id}", response_model=Schedule)
async def get_schedule(
schedule_id: str,
current_user: User = Depends(get_current_active_user),
db: AsyncSession = Depends(get_db)
):
"""Получить расписание по ID"""
schedule = await crud_schedule.get_with_tasks(db, schedule_id)
if not schedule:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Schedule not found"
)
if schedule.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions"
)
return schedule
@router.post("", response_model=Schedule, status_code=status.HTTP_201_CREATED)
async def create_schedule(
schedule_in: ScheduleCreate,
current_user: User = Depends(get_current_active_user),
db: AsyncSession = Depends(get_db)
):
"""Создать новое расписание"""
schedule_data = schedule_in.model_dump()
schedule_data["user_id"] = current_user.id
schedule = await crud_schedule.create(db, schedule_data)
# Перезагрузить расписание с tasks для корректной сериализации
schedule = await crud_schedule.get_with_tasks(db, schedule.id)
return schedule
@router.put("/{schedule_id}", response_model=Schedule)
async def update_schedule(
schedule_id: str,
schedule_in: ScheduleUpdate,
current_user: User = Depends(get_current_active_user),
db: AsyncSession = Depends(get_db)
):
"""Обновить расписание"""
schedule = await crud_schedule.get(db, schedule_id)
if not schedule:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Schedule not found"
)
if schedule.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions"
)
update_data = schedule_in.model_dump(exclude_unset=True)
schedule = await crud_schedule.update(db, schedule, update_data)
# Перезагрузить расписание с tasks для корректной сериализации
schedule = await crud_schedule.get_with_tasks(db, schedule.id)
return schedule
@router.delete("/{schedule_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_schedule(
schedule_id: str,
current_user: User = Depends(get_current_active_user),
db: AsyncSession = Depends(get_db)
):
"""Удалить расписание"""
schedule = await crud_schedule.get(db, schedule_id)
if not schedule:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Schedule not found"
)
if schedule.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions"
)
await crud_schedule.delete(db, schedule_id)
return None
@router.post("/generate", response_model=ScheduleGenerateResponse)
async def generate_schedule(
request: ScheduleGenerateRequest,
current_user: User = Depends(get_current_active_user),
db: AsyncSession = Depends(get_db)
):
"""Сгенерировать расписание через ИИ"""
try:
result = await schedule_generator.generate(
db=db,
user_id=current_user.id,
child_age=request.child_age,
preferences=request.preferences,
schedule_date=request.date,
description=request.description
)
return ScheduleGenerateResponse(
schedule_id=result["schedule_id"],
title=result["title"],
tasks=result["tasks"]
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to generate schedule: {str(e)}"
)