64 lines
1.9 KiB
Python
64 lines
1.9 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.watchlist import Watchlist
|
|
from app.schemas.stock import WatchlistItem, WatchlistAddRequest
|
|
|
|
router = APIRouter(prefix="/watchlist", tags=["watchlist"])
|
|
|
|
|
|
@router.get("", response_model=list[WatchlistItem])
|
|
async def get_watchlist(
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
result = await db.execute(
|
|
select(Watchlist)
|
|
.where(Watchlist.user_id == current_user.id)
|
|
.order_by(Watchlist.sort_order, Watchlist.id)
|
|
)
|
|
return result.scalars().all()
|
|
|
|
|
|
@router.post("", response_model=WatchlistItem, status_code=status.HTTP_201_CREATED)
|
|
async def add_to_watchlist(
|
|
payload: WatchlistAddRequest,
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
existing = await db.execute(
|
|
select(Watchlist).where(
|
|
Watchlist.user_id == current_user.id,
|
|
Watchlist.symbol == payload.symbol,
|
|
)
|
|
)
|
|
if existing.scalar_one_or_none():
|
|
raise HTTPException(status_code=409, detail="已在自选股中")
|
|
|
|
item = Watchlist(
|
|
user_id=current_user.id,
|
|
symbol=payload.symbol,
|
|
name=payload.name,
|
|
)
|
|
db.add(item)
|
|
await db.flush()
|
|
await db.refresh(item)
|
|
return item
|
|
|
|
|
|
@router.delete("/{symbol}", status_code=status.HTTP_204_NO_CONTENT)
|
|
async def remove_from_watchlist(
|
|
symbol: str,
|
|
current_user: User = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
await db.execute(
|
|
delete(Watchlist).where(
|
|
Watchlist.user_id == current_user.id,
|
|
Watchlist.symbol == symbol,
|
|
)
|
|
)
|