galaxis-po/backend/app/api/portfolio.py

111 lines
3.0 KiB
Python

"""
Portfolio management API endpoints.
"""
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.api.deps import CurrentUser
from app.models.portfolio import Portfolio, PortfolioType
from app.schemas.portfolio import (
PortfolioCreate, PortfolioUpdate, PortfolioResponse, PortfolioDetail,
)
router = APIRouter(prefix="/api/portfolios", tags=["portfolios"])
@router.get("", response_model=List[PortfolioResponse])
async def list_portfolios(
current_user: CurrentUser,
db: Session = Depends(get_db),
):
"""Get all portfolios for current user."""
portfolios = (
db.query(Portfolio)
.filter(Portfolio.user_id == current_user.id)
.order_by(Portfolio.created_at.desc())
.all()
)
return portfolios
@router.post("", response_model=PortfolioResponse, status_code=status.HTTP_201_CREATED)
async def create_portfolio(
data: PortfolioCreate,
current_user: CurrentUser,
db: Session = Depends(get_db),
):
"""Create a new portfolio."""
portfolio_type = PortfolioType(data.portfolio_type)
portfolio = Portfolio(
user_id=current_user.id,
name=data.name,
portfolio_type=portfolio_type,
)
db.add(portfolio)
db.commit()
db.refresh(portfolio)
return portfolio
@router.get("/{portfolio_id}", response_model=PortfolioResponse)
async def get_portfolio(
portfolio_id: int,
current_user: CurrentUser,
db: Session = Depends(get_db),
):
"""Get a portfolio by ID."""
portfolio = db.query(Portfolio).filter(
Portfolio.id == portfolio_id,
Portfolio.user_id == current_user.id,
).first()
if not portfolio:
raise HTTPException(status_code=404, detail="Portfolio not found")
return portfolio
@router.put("/{portfolio_id}", response_model=PortfolioResponse)
async def update_portfolio(
portfolio_id: int,
data: PortfolioUpdate,
current_user: CurrentUser,
db: Session = Depends(get_db),
):
"""Update a portfolio."""
portfolio = db.query(Portfolio).filter(
Portfolio.id == portfolio_id,
Portfolio.user_id == current_user.id,
).first()
if not portfolio:
raise HTTPException(status_code=404, detail="Portfolio not found")
if data.name is not None:
portfolio.name = data.name
if data.portfolio_type is not None:
portfolio.portfolio_type = PortfolioType(data.portfolio_type)
db.commit()
db.refresh(portfolio)
return portfolio
@router.delete("/{portfolio_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_portfolio(
portfolio_id: int,
current_user: CurrentUser,
db: Session = Depends(get_db),
):
"""Delete a portfolio."""
portfolio = db.query(Portfolio).filter(
Portfolio.id == portfolio_id,
Portfolio.user_id == current_user.id,
).first()
if not portfolio:
raise HTTPException(status_code=404, detail="Portfolio not found")
db.delete(portfolio)
db.commit()
return None