Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 27 additions & 11 deletions frontend/src/hooks/usePortfolio.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react'
import { apiRequest, API_CONFIG } from '../config/api'

interface PortfolioData {
id: string
Expand All @@ -13,6 +14,11 @@ interface PortfolioData {
lastRebalance: string
}

interface PortfolioResponse {
success?: boolean
portfolio: PortfolioData
}

export const usePortfolio = (portfolioId?: string) => {
const [portfolio, setPortfolio] = useState<PortfolioData | null>(null)
const [loading, setLoading] = useState(true)
Expand All @@ -24,10 +30,12 @@ export const usePortfolio = (portfolioId?: string) => {
const fetchPortfolio = async () => {
try {
setLoading(true)
const response = await fetch(`/api/portfolio/${portfolioId}`)
if (!response.ok) throw new Error('Failed to fetch portfolio')

const data = await response.json()
const data = await apiRequest<PortfolioResponse>(
`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.PORTFOLIO_DETAIL(portfolioId)}`
)
if (!data?.portfolio) {
throw new Error('Failed to fetch portfolio')
}
setPortfolio(data.portfolio)
setError(null)
} catch (err) {
Expand All @@ -48,19 +56,27 @@ export const usePortfolio = (portfolioId?: string) => {
if (!portfolioId) return

try {
const response = await fetch(`/api/portfolio/${portfolioId}/rebalance`, {
method: 'POST'
})
if (!response.ok) throw new Error('Rebalance failed')
await apiRequest(
`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.PORTFOLIO_REBALANCE(portfolioId)}`,
{
method: 'POST',
body: JSON.stringify({}),
}
)

// Refresh portfolio data
const portfolioResponse = await fetch(`/api/portfolio/${portfolioId}`)
const data = await portfolioResponse.json()
const data = await apiRequest<PortfolioResponse>(
`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.PORTFOLIO_DETAIL(portfolioId)}`
)
if (!data?.portfolio) {
throw new Error('Failed to fetch portfolio')
}
setPortfolio(data.portfolio)
setError(null)
} catch (err) {
setError(err instanceof Error ? err.message : 'Rebalance failed')
}
}

return { portfolio, loading, error, executeRebalance }
}
}