feat: rebuild fiscal clone architecture and harden coolify deployment

This commit is contained in:
2026-02-23 21:10:39 -05:00
parent cae7cbb98f
commit 04e5caf4e1
61 changed files with 3826 additions and 2923 deletions

View File

@@ -1,301 +1,332 @@
'use client';
import { useSession } from '@/lib/better-auth';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
import { format } from 'date-fns';
import Link from 'next/link';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, BarChart, CartesianGrid, XAxis, YAxis, Bar } from 'recharts';
import { BrainCircuit, Plus, RefreshCcw, Trash2 } from 'lucide-react';
import { AppShell } from '@/components/shell/app-shell';
import { Panel } from '@/components/ui/panel';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { StatusPill } from '@/components/ui/status-pill';
import { useAuthGuard } from '@/hooks/use-auth-guard';
import { useTaskPoller } from '@/hooks/use-task-poller';
import {
deleteHolding,
getLatestPortfolioInsight,
getTask,
getPortfolioSummary,
listHoldings,
queuePortfolioInsights,
queuePriceRefresh,
upsertHolding
} from '@/lib/api';
import type { Holding, PortfolioInsight, PortfolioSummary, Task } from '@/lib/types';
import { asNumber, formatCurrency, formatPercent } from '@/lib/format';
type FormState = {
ticker: string;
shares: string;
avgCost: string;
currentPrice: string;
};
const CHART_COLORS = ['#6effd8', '#5fd3ff', '#66ffa1', '#8dbbff', '#f4f88f', '#ff9c9c'];
const EMPTY_SUMMARY: PortfolioSummary = {
positions: 0,
total_value: '0',
total_gain_loss: '0',
total_cost_basis: '0',
avg_return_pct: '0'
};
export default function PortfolioPage() {
const { data: session, isPending } = useSession();
const router = useRouter();
const [portfolio, setPortfolio] = useState([]);
const [summary, setSummary] = useState({ total_value: 0, total_gain_loss: 0, cost_basis: 0 });
const { isPending, isAuthenticated } = useAuthGuard();
const [holdings, setHoldings] = useState<Holding[]>([]);
const [summary, setSummary] = useState<PortfolioSummary>(EMPTY_SUMMARY);
const [latestInsight, setLatestInsight] = useState<PortfolioInsight | null>(null);
const [loading, setLoading] = useState(true);
const [showAddModal, setShowAddModal] = useState(false);
const [newHolding, setNewHolding] = useState({ ticker: '', shares: '', avg_cost: '' });
const [error, setError] = useState<string | null>(null);
const [activeTask, setActiveTask] = useState<Task | null>(null);
const [form, setForm] = useState<FormState>({ ticker: '', shares: '', avgCost: '', currentPrice: '' });
useEffect(() => {
if (!isPending && !session) {
router.push('/auth/signin');
return;
}
const loadPortfolio = useCallback(async () => {
setLoading(true);
setError(null);
if (session?.user?.id) {
fetchPortfolio(session.user.id);
}
}, [session, isPending, router]);
const fetchPortfolio = async (userId: string) => {
try {
const [portfolioRes, summaryRes] = await Promise.all([
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/portfolio/${userId}`),
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/portfolio/${userId}/summary`)
const [holdingsRes, summaryRes, insightRes] = await Promise.all([
listHoldings(),
getPortfolioSummary(),
getLatestPortfolioInsight()
]);
const portfolioData = await portfolioRes.json();
const summaryData = await summaryRes.json();
setPortfolio(portfolioData);
setSummary(summaryData);
} catch (error) {
console.error('Error fetching portfolio:', error);
setHoldings(holdingsRes.holdings);
setSummary(summaryRes.summary);
setLatestInsight(insightRes.insight);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not fetch portfolio data');
} finally {
setLoading(false);
}
};
}, []);
const handleAddHolding = async (e: React.FormEvent) => {
e.preventDefault();
const userId = session?.user?.id;
if (!userId) return;
useEffect(() => {
if (!isPending && isAuthenticated) {
void loadPortfolio();
}
}, [isPending, isAuthenticated, loadPortfolio]);
const polledTask = useTaskPoller({
taskId: activeTask?.id ?? null,
onTerminalState: async () => {
setActiveTask(null);
await loadPortfolio();
}
});
const liveTask = polledTask ?? activeTask;
const allocationData = useMemo(
() => holdings.map((holding) => ({
name: holding.ticker,
value: asNumber(holding.market_value)
})),
[holdings]
);
const performanceData = useMemo(
() => holdings.map((holding) => ({
name: holding.ticker,
value: asNumber(holding.gain_loss_pct)
})),
[holdings]
);
const submitHolding = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/portfolio`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
user_id: userId,
ticker: newHolding.ticker.toUpperCase(),
shares: parseFloat(newHolding.shares),
avg_cost: parseFloat(newHolding.avg_cost)
})
await upsertHolding({
ticker: form.ticker.toUpperCase(),
shares: Number(form.shares),
avgCost: Number(form.avgCost),
currentPrice: form.currentPrice ? Number(form.currentPrice) : undefined
});
setShowAddModal(false);
setNewHolding({ ticker: '', shares: '', avg_cost: '' });
fetchPortfolio(userId);
} catch (error) {
console.error('Error adding holding:', error);
setForm({ ticker: '', shares: '', avgCost: '', currentPrice: '' });
await loadPortfolio();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to save holding');
}
};
const handleDeleteHolding = async (id: number) => {
if (!confirm('Are you sure you want to delete this holding?')) return;
const userId = session?.user?.id;
if (!userId) return;
const queueRefresh = async () => {
try {
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/portfolio/${id}`, {
method: 'DELETE'
});
fetchPortfolio(userId);
} catch (error) {
console.error('Error deleting holding:', error);
const { task } = await queuePriceRefresh();
const latest = await getTask(task.id);
setActiveTask(latest.task);
} catch (err) {
setError(err instanceof Error ? err.message : 'Unable to queue price refresh');
}
};
if (loading) {
return <div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 flex items-center justify-center">Loading...</div>;
const queueInsights = async () => {
try {
const { task } = await queuePortfolioInsights();
const latest = await getTask(task.id);
setActiveTask(latest.task);
} catch (err) {
setError(err instanceof Error ? err.message : 'Unable to queue portfolio insights');
}
};
if (isPending || !isAuthenticated) {
return <div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Loading portfolio matrix...</div>;
}
const pieData = portfolio.length > 0 ? portfolio.map((p: any) => ({
name: p.ticker,
value: p.current_value || (p.shares * p.avg_cost)
})) : [];
const COLORS = ['#3b82f6', '#8b5cf6', '#10b981', '#f59e0b', '#ef4444', '#ec4899'];
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 text-white">
<nav className="border-b border-slate-700 bg-slate-900/50 backdrop-blur">
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
<Link href="/" className="text-2xl font-bold bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">
Fiscal Clone
</Link>
<div className="flex gap-4">
<Link href="/filings" className="hover:text-blue-400 transition">
Filings
</Link>
<Link href="/portfolio" className="hover:text-blue-400 transition">
Portfolio
</Link>
<Link href="/watchlist" className="hover:text-blue-400 transition">
Watchlist
</Link>
<AppShell
title="Portfolio Matrix"
subtitle="Position management, market valuation, and AI generated portfolio commentary."
actions={(
<>
<Button variant="secondary" onClick={() => void queueRefresh()}>
<RefreshCcw className="size-4" />
Queue price refresh
</Button>
<Button onClick={() => void queueInsights()}>
<BrainCircuit className="size-4" />
Generate AI brief
</Button>
</>
)}
>
{liveTask ? (
<Panel title="Task Runner" subtitle={liveTask.id}>
<div className="flex items-center justify-between rounded-lg border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-3 py-2">
<p className="text-sm text-[color:var(--terminal-bright)]">{liveTask.task_type}</p>
<StatusPill status={liveTask.status} />
</div>
</div>
</nav>
{liveTask.error ? <p className="mt-2 text-sm text-[#ff9f9f]">{liveTask.error}</p> : null}
</Panel>
) : null}
<main className="container mx-auto px-4 py-8">
<div className="flex justify-between items-center mb-6">
<h1 className="text-3xl font-bold">Portfolio</h1>
<button
onClick={() => setShowAddModal(true)}
className="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition"
>
+ Add Holding
</button>
</div>
{error ? (
<Panel>
<p className="text-sm text-[#ffb5b5]">{error}</p>
</Panel>
) : null}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
<div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
<h3 className="text-slate-400 mb-2">Total Value</h3>
<p className="text-3xl font-bold text-green-400">
${summary.total_value?.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '$0.00'}
</p>
</div>
<div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
<h3 className="text-slate-400 mb-2">Total Gain/Loss</h3>
<p className={`text-3xl font-bold ${summary.total_gain_loss >= 0 ? 'text-green-400' : 'text-red-400'}`}>
{summary.total_gain_loss >= 0 ? '+' : ''}${summary.total_gain_loss?.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '$0.00'}
</p>
</div>
<div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
<h3 className="text-slate-400 mb-2">Positions</h3>
<p className="text-3xl font-bold text-blue-400">{portfolio.length}</p>
</div>
</div>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
<Panel title="Total Value" className="lg:col-span-1">
<p className="text-3xl font-semibold text-[color:var(--terminal-bright)]">{formatCurrency(summary.total_value)}</p>
<p className="mt-2 text-sm text-[color:var(--terminal-muted)]">Cost basis {formatCurrency(summary.total_cost_basis)}</p>
</Panel>
<Panel title="Unrealized P&L" className="lg:col-span-1">
<p className={`text-3xl font-semibold ${asNumber(summary.total_gain_loss) >= 0 ? 'text-[#96f5bf]' : 'text-[#ff9f9f]'}`}>
{formatCurrency(summary.total_gain_loss)}
</p>
<p className="mt-2 text-sm text-[color:var(--terminal-muted)]">Average return {formatPercent(summary.avg_return_pct)}</p>
</Panel>
<Panel title="Positions" className="lg:col-span-1">
<p className="text-3xl font-semibold text-[color:var(--terminal-bright)]">{summary.positions}</p>
<p className="mt-2 text-sm text-[color:var(--terminal-muted)]">Active symbols in portfolio.</p>
</Panel>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
<div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
<h3 className="text-xl font-semibold mb-4">Portfolio Allocation</h3>
{pieData.length > 0 ? (
<ResponsiveContainer width="100%" height={300}>
<div className="grid grid-cols-1 gap-6 xl:grid-cols-2">
<Panel title="Allocation">
{loading ? (
<p className="text-sm text-[color:var(--terminal-muted)]">Loading chart...</p>
) : allocationData.length > 0 ? (
<div className="h-[300px]">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={pieData}
dataKey="value"
nameKey="name"
cx="50%"
cy="50%"
outerRadius={100}
label={(entry) => `${entry.name} ($${(entry.value / 1000).toFixed(1)}k)`}
>
{pieData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
<Pie data={allocationData} dataKey="value" nameKey="name" innerRadius={56} outerRadius={104} paddingAngle={2}>
{allocationData.map((entry, index) => (
<Cell key={`${entry.name}-${index}`} fill={CHART_COLORS[index % CHART_COLORS.length]} />
))}
</Pie>
<Tooltip />
<Tooltip formatter={(value: number) => formatCurrency(value)} />
</PieChart>
</ResponsiveContainer>
) : (
<p className="text-slate-400 text-center py-8">No holdings yet</p>
)}
</div>
</div>
) : (
<p className="text-sm text-[color:var(--terminal-muted)]">No holdings yet.</p>
)}
</Panel>
<div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
<h3 className="text-xl font-semibold mb-4">Performance</h3>
{portfolio.length > 0 ? (
<ResponsiveContainer width="100%" height={300}>
<LineChart data={portfolio.map((p: any) => ({ name: p.ticker, value: p.gain_loss_pct || 0 }))}>
<XAxis dataKey="name" stroke="#64748b" />
<YAxis stroke="#64748b" />
<CartesianGrid strokeDasharray="3 3" stroke="#334155" />
<Tooltip contentStyle={{ backgroundColor: '#1e293b', border: '#334155', borderRadius: '8px' }} />
<Line type="monotone" dataKey="value" stroke="#8b5cf6" strokeWidth={2} dot={{ fill: '#8b5cf6' }} />
</LineChart>
<Panel title="Performance %">
{loading ? (
<p className="text-sm text-[color:var(--terminal-muted)]">Loading chart...</p>
) : performanceData.length > 0 ? (
<div className="h-[300px]">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={performanceData}>
<CartesianGrid strokeDasharray="2 2" stroke="rgba(126, 217, 255, 0.2)" />
<XAxis dataKey="name" stroke="#8cb6c5" fontSize={12} />
<YAxis stroke="#8cb6c5" fontSize={12} />
<Tooltip formatter={(value: number) => `${value.toFixed(2)}%`} />
<Bar dataKey="value" fill="#68ffd5" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<p className="text-slate-400 text-center py-8">No performance data yet</p>
)}
</div>
</div>
</div>
) : (
<p className="text-sm text-[color:var(--terminal-muted)]">No performance data yet.</p>
)}
</Panel>
</div>
<div className="bg-slate-800/50 rounded-lg border border-slate-700 overflow-hidden">
<table className="w-full">
<thead className="bg-slate-700/50">
<tr>
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Ticker</th>
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Shares</th>
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Avg Cost</th>
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Current Price</th>
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Value</th>
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Gain/Loss</th>
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">%</th>
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Actions</th>
</tr>
</thead>
<tbody>
{portfolio.map((holding: any) => (
<tr key={holding.id} className="border-t border-slate-700 hover:bg-slate-700/30 transition">
<td className="px-6 py-4 font-semibold">{holding.ticker}</td>
<td className="px-6 py-4">{holding.shares.toLocaleString()}</td>
<td className="px-6 py-4">${holding.avg_cost.toFixed(2)}</td>
<td className="px-6 py-4">${holding.current_price?.toFixed(2) || 'N/A'}</td>
<td className="px-6 py-4">${holding.current_value?.toFixed(2) || 'N/A'}</td>
<td className={`px-6 py-4 ${holding.gain_loss >= 0 ? 'text-green-400' : 'text-red-400'}`}>
{holding.gain_loss >= 0 ? '+' : ''}${holding.gain_loss?.toFixed(2) || '0.00'}
</td>
<td className={`px-6 py-4 ${holding.gain_loss_pct >= 0 ? 'text-green-400' : 'text-red-400'}`}>
{holding.gain_loss_pct >= 0 ? '+' : ''}{holding.gain_loss_pct?.toFixed(2) || '0.00'}%
</td>
<td className="px-6 py-4">
<button
onClick={() => handleDeleteHolding(holding.id)}
className="text-red-400 hover:text-red-300 transition"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</main>
<div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.5fr_1fr]">
<Panel title="Holdings Table" subtitle="Live mark-to-market values from latest refresh.">
{loading ? (
<p className="text-sm text-[color:var(--terminal-muted)]">Loading holdings...</p>
) : holdings.length === 0 ? (
<p className="text-sm text-[color:var(--terminal-muted)]">No holdings added yet.</p>
) : (
<div className="overflow-x-auto">
<table className="data-table min-w-[780px]">
<thead>
<tr>
<th>Ticker</th>
<th>Shares</th>
<th>Avg Cost</th>
<th>Price</th>
<th>Value</th>
<th>Gain/Loss</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{holdings.map((holding) => (
<tr key={holding.id}>
<td>{holding.ticker}</td>
<td>{asNumber(holding.shares).toLocaleString()}</td>
<td>{formatCurrency(holding.avg_cost)}</td>
<td>{holding.current_price ? formatCurrency(holding.current_price) : 'n/a'}</td>
<td>{formatCurrency(holding.market_value)}</td>
<td className={asNumber(holding.gain_loss) >= 0 ? 'text-[#96f5bf]' : 'text-[#ff9898]'}>
{formatCurrency(holding.gain_loss)} ({formatPercent(holding.gain_loss_pct)})
</td>
<td>
<Button
variant="danger"
className="px-2 py-1 text-xs"
onClick={async () => {
try {
await deleteHolding(holding.id);
await loadPortfolio();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete holding');
}
}}
>
<Trash2 className="size-3" />
Delete
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Panel>
{showAddModal && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4">
<div className="bg-slate-800 rounded-lg p-6 border border-slate-700 max-w-md w-full">
<h2 className="text-2xl font-bold mb-4">Add Holding</h2>
<form onSubmit={handleAddHolding} className="space-y-4">
<div>
<label className="block text-sm font-medium text-slate-300 mb-2">Ticker</label>
<input
type="text"
value={newHolding.ticker}
onChange={(e) => setNewHolding({...newHolding, ticker: e.target.value})}
className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
placeholder="AAPL"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-300 mb-2">Shares</label>
<input
type="number"
step="0.0001"
value={newHolding.shares}
onChange={(e) => setNewHolding({...newHolding, shares: e.target.value})}
className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
placeholder="100"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-300 mb-2">Average Cost</label>
<input
type="number"
step="0.01"
value={newHolding.avg_cost}
onChange={(e) => setNewHolding({...newHolding, avg_cost: e.target.value})}
className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
placeholder="150.00"
required
/>
</div>
<div className="flex gap-4">
<button
type="submit"
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg transition"
>
Add
</button>
<button
type="button"
onClick={() => setShowAddModal(false)}
className="flex-1 bg-slate-700 hover:bg-slate-600 text-white py-3 rounded-lg transition"
>
Cancel
</button>
</div>
</form>
<Panel title="Add / Update Holding">
<form onSubmit={submitHolding} className="space-y-3">
<div>
<label className="mb-1 block text-xs uppercase tracking-[0.16em] text-[color:var(--terminal-muted)]">Ticker</label>
<Input value={form.ticker} onChange={(event) => setForm((prev) => ({ ...prev, ticker: event.target.value.toUpperCase() }))} required />
</div>
<div>
<label className="mb-1 block text-xs uppercase tracking-[0.16em] text-[color:var(--terminal-muted)]">Shares</label>
<Input type="number" step="0.0001" min="0.0001" value={form.shares} onChange={(event) => setForm((prev) => ({ ...prev, shares: event.target.value }))} required />
</div>
<div>
<label className="mb-1 block text-xs uppercase tracking-[0.16em] text-[color:var(--terminal-muted)]">Average Cost</label>
<Input type="number" step="0.0001" min="0.0001" value={form.avgCost} onChange={(event) => setForm((prev) => ({ ...prev, avgCost: event.target.value }))} required />
</div>
<div>
<label className="mb-1 block text-xs uppercase tracking-[0.16em] text-[color:var(--terminal-muted)]">Current Price (optional)</label>
<Input type="number" step="0.0001" min="0" value={form.currentPrice} onChange={(event) => setForm((prev) => ({ ...prev, currentPrice: event.target.value }))} />
</div>
<Button type="submit" className="w-full">
<Plus className="size-4" />
Save holding
</Button>
</form>
<div className="mt-5 border-t border-[color:var(--line-weak)] pt-4">
<p className="text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Latest AI Insight</p>
<p className="mt-2 whitespace-pre-wrap text-sm leading-6 text-[color:var(--terminal-bright)]">
{latestInsight?.content ?? 'No insight available yet. Queue an AI brief from the header.'}
</p>
</div>
</div>
)}
</div>
</Panel>
</div>
</AppShell>
);
}