78 lines
2.2 KiB
Python
78 lines
2.2 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select, delete
|
|
from app.core.database import get_db
|
|
from app.api.deps import get_current_user
|
|
from app.models.user import User
|
|
from app.models.alert import Alert
|
|
from app.schemas.stock import AlertCreate, AlertOut
|
|
|
|
router = APIRouter(prefix="/alerts", tags=["alerts"])
|
|
|
|
|
|
@router.get("", response_model=list[AlertOut])
|
|
async def get_alerts(
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
result = await db.execute(
|
|
select(Alert)
|
|
.where(Alert.user_id == current_user.id)
|
|
.order_by(Alert.id.desc())
|
|
)
|
|
return result.scalars().all()
|
|
|
|
|
|
@router.post("", response_model=AlertOut, status_code=status.HTTP_201_CREATED)
|
|
async def create_alert(
|
|
payload: AlertCreate,
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
alert = Alert(
|
|
user_id=current_user.id,
|
|
symbol=payload.symbol,
|
|
name=payload.name,
|
|
alert_type=payload.alert_type,
|
|
threshold=payload.threshold,
|
|
)
|
|
db.add(alert)
|
|
await db.flush()
|
|
await db.refresh(alert)
|
|
return alert
|
|
|
|
|
|
@router.delete("/{alert_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
async def delete_alert(
|
|
alert_id: int,
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
result = await db.execute(
|
|
select(Alert).where(Alert.id == alert_id, Alert.user_id == current_user.id)
|
|
)
|
|
alert = result.scalar_one_or_none()
|
|
if not alert:
|
|
raise HTTPException(status_code=404, detail="预警不存在")
|
|
|
|
await db.delete(alert)
|
|
|
|
|
|
@router.patch("/{alert_id}/toggle", response_model=AlertOut)
|
|
async def toggle_alert(
|
|
alert_id: int,
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
result = await db.execute(
|
|
select(Alert).where(Alert.id == alert_id, Alert.user_id == current_user.id)
|
|
)
|
|
alert = result.scalar_one_or_none()
|
|
if not alert:
|
|
raise HTTPException(status_code=404, detail="预警不存在")
|
|
|
|
alert.is_active = not alert.is_active
|
|
await db.flush()
|
|
await db.refresh(alert)
|
|
return alert
|