feat: add rebalancing calculation page

This commit is contained in:
zephyrdark 2026-02-03 08:30:43 +09:00
parent bc356d9edf
commit d2314cad4e

View File

@ -0,0 +1,249 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Sidebar from '@/components/layout/Sidebar';
import Header from '@/components/layout/Header';
import { api } from '@/lib/api';
interface RebalanceItem {
ticker: string;
name: string | null;
target_ratio: number;
current_ratio: number;
current_quantity: number;
current_value: number;
target_value: number;
diff_value: number;
diff_quantity: number;
action: string;
}
interface RebalanceResponse {
portfolio_id: number;
total_value: number;
items: RebalanceItem[];
}
interface SimulationResponse extends RebalanceResponse {
current_total: number;
additional_amount: number;
new_total: number;
}
export default function RebalancePage() {
const router = useRouter();
const params = useParams();
const portfolioId = params.id as string;
const [loading, setLoading] = useState(true);
const [rebalance, setRebalance] = useState<RebalanceResponse | SimulationResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [additionalAmount, setAdditionalAmount] = useState('');
const [simulating, setSimulating] = useState(false);
useEffect(() => {
const init = async () => {
try {
await api.getCurrentUser();
await fetchRebalance();
} catch {
router.push('/login');
} finally {
setLoading(false);
}
};
init();
}, [router, portfolioId]);
const fetchRebalance = async () => {
try {
setError(null);
const data = await api.get<RebalanceResponse>(`/api/portfolios/${portfolioId}/rebalance`);
setRebalance(data);
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to calculate rebalance';
setError(message);
}
};
const simulate = async () => {
if (!additionalAmount) return;
setSimulating(true);
try {
setError(null);
const data = await api.post<SimulationResponse>(
`/api/portfolios/${portfolioId}/rebalance/simulate`,
{ additional_amount: parseFloat(additionalAmount) }
);
setRebalance(data);
} catch (err) {
const message = err instanceof Error ? err.message : 'Simulation failed';
setError(message);
} finally {
setSimulating(false);
}
};
const formatCurrency = (value: number) => {
return new Intl.NumberFormat('ko-KR', {
style: 'currency',
currency: 'KRW',
maximumFractionDigits: 0,
}).format(value);
};
const getActionBadge = (action: string) => {
const styles: Record<string, string> = {
buy: 'bg-green-100 text-green-800',
sell: 'bg-red-100 text-red-800',
hold: 'bg-gray-100 text-gray-800',
};
const labels: Record<string, string> = {
buy: '매수',
sell: '매도',
hold: '유지',
};
return (
<span className={`px-2 py-1 rounded text-xs ${styles[action] || styles.hold}`}>
{labels[action] || action}
</span>
);
};
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-gray-500">Loading...</div>
</div>
);
}
return (
<div className="flex min-h-screen">
<Sidebar />
<div className="flex-1">
<Header />
<main className="p-6">
<h1 className="text-2xl font-bold text-gray-800 mb-6"> </h1>
{error && (
<div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
{error}
</div>
)}
{/* Simulation Input */}
<div className="bg-white rounded-lg shadow p-4 mb-6">
<div className="flex gap-4 items-end">
<div className="flex-1">
<label htmlFor="additional-amount" className="block text-sm font-medium text-gray-700 mb-2">
()
</label>
<input
id="additional-amount"
type="number"
value={additionalAmount}
onChange={(e) => setAdditionalAmount(e.target.value)}
className="w-full px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="예: 1000000"
/>
</div>
<button
onClick={simulate}
disabled={!additionalAmount || simulating}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:bg-blue-400 transition-colors"
>
{simulating ? '계산 중...' : '시뮬레이션'}
</button>
<button
onClick={fetchRebalance}
className="px-4 py-2 border rounded hover:bg-gray-50 transition-colors"
>
</button>
</div>
</div>
{rebalance && (
<>
{/* Summary */}
<div className="bg-white rounded-lg shadow p-4 mb-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<p className="text-sm text-gray-500"> </p>
<p className="text-xl font-bold">
{formatCurrency('current_total' in rebalance ? rebalance.current_total : rebalance.total_value)}
</p>
</div>
{'additional_amount' in rebalance && (
<>
<div>
<p className="text-sm text-gray-500"> </p>
<p className="text-xl font-bold text-blue-600">
+{formatCurrency(rebalance.additional_amount)}
</p>
</div>
<div>
<p className="text-sm text-gray-500"> </p>
<p className="text-xl font-bold">
{formatCurrency(rebalance.new_total)}
</p>
</div>
</>
)}
</div>
</div>
{/* Rebalance Table */}
<div className="bg-white rounded-lg shadow">
<div className="p-4 border-b">
<h2 className="text-lg font-semibold"> </h2>
</div>
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50">
<tr>
<th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-600"></th>
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600"> </th>
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600"> </th>
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600"> </th>
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600"> </th>
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600"> </th>
<th scope="col" className="px-4 py-3 text-center text-sm font-medium text-gray-600"></th>
</tr>
</thead>
<tbody className="divide-y">
{rebalance.items.map((item) => (
<tr key={item.ticker}>
<td className="px-4 py-3">
<div className="font-medium">{item.ticker}</div>
{item.name && <div className="text-xs text-gray-500">{item.name}</div>}
</td>
<td className="px-4 py-3 text-sm text-right">{item.target_ratio.toFixed(2)}%</td>
<td className="px-4 py-3 text-sm text-right">{item.current_ratio.toFixed(2)}%</td>
<td className="px-4 py-3 text-sm text-right">{item.current_quantity.toLocaleString()}</td>
<td className={`px-4 py-3 text-sm text-right ${
item.diff_value > 0 ? 'text-green-600' : item.diff_value < 0 ? 'text-red-600' : ''
}`}>
{item.diff_value > 0 ? '+' : ''}{formatCurrency(item.diff_value)}
</td>
<td className={`px-4 py-3 text-sm text-right font-medium ${
item.diff_quantity > 0 ? 'text-green-600' : item.diff_quantity < 0 ? 'text-red-600' : ''
}`}>
{item.diff_quantity > 0 ? '+' : ''}{item.diff_quantity}
</td>
<td className="px-4 py-3 text-center">{getActionBadge(item.action)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</>
)}
</main>
</div>
</div>
);
}