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,110 +1,229 @@
'use client';
import { useSession } from '@/lib/better-auth';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Activity, Bot, RefreshCw, Sparkles } from 'lucide-react';
import { AppShell } from '@/components/shell/app-shell';
import { Panel } from '@/components/ui/panel';
import { Button } from '@/components/ui/button';
import { MetricCard } from '@/components/dashboard/metric-card';
import { TaskFeed } from '@/components/dashboard/task-feed';
import { StatusPill } from '@/components/ui/status-pill';
import { useAuthGuard } from '@/hooks/use-auth-guard';
import { useTaskPoller } from '@/hooks/use-task-poller';
import {
getLatestPortfolioInsight,
getPortfolioSummary,
getTask,
listFilings,
listRecentTasks,
listWatchlist,
queuePortfolioInsights,
queuePriceRefresh
} from '@/lib/api';
import type { PortfolioInsight, PortfolioSummary, Task } from '@/lib/types';
import { formatCompactCurrency, formatCurrency, formatPercent } from '@/lib/format';
export default function Home() {
const { data: session, isPending } = useSession();
const router = useRouter();
const [stats, setStats] = useState({ filings: 0, portfolioValue: 0, watchlist: 0 });
type DashboardState = {
summary: PortfolioSummary;
filingsCount: number;
watchlistCount: number;
tasks: Task[];
latestInsight: PortfolioInsight | null;
};
useEffect(() => {
if (!isPending && !session) {
router.push('/auth/signin');
return;
}
const EMPTY_STATE: DashboardState = {
summary: {
positions: 0,
total_value: '0',
total_gain_loss: '0',
total_cost_basis: '0',
avg_return_pct: '0'
},
filingsCount: 0,
watchlistCount: 0,
tasks: [],
latestInsight: null
};
if (session?.user) {
fetchStats(session.user.id);
}
}, [session, isPending, router]);
export default function CommandCenterPage() {
const { isPending, isAuthenticated, session } = useAuthGuard();
const [state, setState] = useState<DashboardState>(EMPTY_STATE);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [activeTaskId, setActiveTaskId] = useState<string | null>(null);
const loadData = useCallback(async () => {
setLoading(true);
setError(null);
const fetchStats = async (userId: string) => {
try {
const [portfolioRes, watchlistRes, filingsRes] = await Promise.all([
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/portfolio/${userId}/summary`),
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/watchlist/${userId}`),
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/filings`)
const [summaryRes, filingsRes, watchlistRes, tasksRes, insightRes] = await Promise.all([
getPortfolioSummary(),
listFilings({ limit: 200 }),
listWatchlist(),
listRecentTasks(20),
getLatestPortfolioInsight()
]);
const portfolioData = await portfolioRes.json();
const watchlistData = await watchlistRes.json();
const filingsData = await filingsRes.json();
setStats({
filings: filingsData.length || 0,
portfolioValue: portfolioData.total_value || 0,
watchlist: watchlistData.length || 0
setState({
summary: summaryRes.summary,
filingsCount: filingsRes.filings.length,
watchlistCount: watchlistRes.items.length,
tasks: tasksRes.tasks,
latestInsight: insightRes.insight
});
} catch (error) {
console.error('Error fetching stats:', error);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load dashboard');
} finally {
setLoading(false);
}
};
}, []);
useEffect(() => {
if (!isPending && isAuthenticated) {
void loadData();
}
}, [isPending, isAuthenticated, loadData]);
const trackedTask = useTaskPoller({
taskId: activeTaskId,
onTerminalState: () => {
setActiveTaskId(null);
void loadData();
}
});
const headerActions = (
<>
<Button
variant="secondary"
onClick={async () => {
try {
const { task } = await queuePriceRefresh();
setActiveTaskId(task.id);
const latest = await getTask(task.id);
setState((prev) => ({ ...prev, tasks: [latest.task, ...prev.tasks] }));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to queue price refresh');
}
}}
>
<RefreshCw className="size-4" />
Refresh prices
</Button>
<Button
onClick={async () => {
try {
const { task } = await queuePortfolioInsights();
setActiveTaskId(task.id);
const latest = await getTask(task.id);
setState((prev) => ({ ...prev, tasks: [latest.task, ...prev.tasks] }));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to queue AI insight');
}
}}
>
<Sparkles className="size-4" />
Queue AI insight
</Button>
</>
);
const signedGain = useMemo(() => {
const gain = Number(state.summary.total_gain_loss ?? 0);
return gain >= 0 ? `+${formatCurrency(gain)}` : formatCurrency(gain);
}, [state.summary.total_gain_loss]);
if (isPending || !isAuthenticated) {
return <div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Booting secure terminal...</div>;
}
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
<AppShell
title="Command Center"
subtitle={`Welcome back${session?.user?.name ? `, ${session.user.name}` : ''}. Review tasks, portfolio health, and AI outputs.`}
actions={headerActions}
>
{activeTaskId && trackedTask ? (
<Panel title="Live Task" subtitle={`Task ${activeTaskId.slice(0, 8)} is active.`}>
<div className="flex items-center justify-between gap-3 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)]">{trackedTask.task_type.replace('_', ' ')}</p>
<StatusPill status={trackedTask.status} />
</div>
{trackedTask.error ? (
<p className="mt-3 text-sm text-[#ff9898]">{trackedTask.error}</p>
) : null}
</Panel>
) : null}
{error ? (
<Panel>
<p className="text-sm text-[#ffb5b5]">{error}</p>
</Panel>
) : null}
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
<MetricCard label="Portfolio Value" value={formatCurrency(state.summary.total_value)} delta={formatCompactCurrency(state.summary.total_cost_basis)} />
<MetricCard
label="Unrealized P&L"
value={signedGain}
delta={formatPercent(state.summary.avg_return_pct)}
positive={Number(state.summary.total_gain_loss) >= 0}
/>
<MetricCard label="Tracked Filings" value={String(state.filingsCount)} delta="Last 200 records" />
<MetricCard label="Watchlist Nodes" value={String(state.watchlistCount)} delta={`${state.summary.positions} positions active`} />
</div>
<div className="grid grid-cols-1 gap-6 xl:grid-cols-3">
<Panel title="Recent Tasks" subtitle="Durable jobs from queue processor" className="xl:col-span-1">
{loading ? (
<p className="text-sm text-[color:var(--terminal-muted)]">Loading tasks...</p>
) : (
<TaskFeed tasks={state.tasks} />
)}
</Panel>
<Panel title="AI Brief" subtitle="Latest portfolio insight from OpenClaw/ZeroClaw" className="xl:col-span-2">
{loading ? (
<p className="text-sm text-[color:var(--terminal-muted)]">Loading intelligence output...</p>
) : state.latestInsight ? (
<>
<div className="mb-3 inline-flex items-center gap-2 rounded-md border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-2 py-1 text-xs text-[color:var(--terminal-muted)]">
<Bot className="size-3.5" />
{state.latestInsight.provider} :: {state.latestInsight.model}
</div>
<p className="whitespace-pre-wrap text-sm leading-6 text-[color:var(--terminal-bright)]">{state.latestInsight.content}</p>
</>
) : (
<p className="text-sm text-[color:var(--terminal-muted)]">No AI brief yet. Queue one from the action bar.</p>
)}
</Panel>
</div>
<Panel title="Quick Links" subtitle="Feature modules">
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<Link className="rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-4 transition hover:border-[color:var(--line-strong)] hover:bg-[color:var(--panel-bright)]" href="/filings">
<p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Filings</p>
<p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Sync SEC filings and trigger AI memo analysis.</p>
</Link>
<Link className="rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-4 transition hover:border-[color:var(--line-strong)] hover:bg-[color:var(--panel-bright)]" href="/portfolio">
<p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Portfolio</p>
<p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Manage holdings and mark to market in real time.</p>
</Link>
<Link className="rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-4 transition hover:border-[color:var(--line-strong)] hover:bg-[color:var(--panel-bright)]" href="/watchlist">
<p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Watchlist</p>
<p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Track priority tickers for monitoring and ingestion.</p>
</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>
</div>
</div>
</nav>
</Panel>
<main className="container mx-auto px-4 py-8">
<div className="mb-6">
<h1 className="text-3xl font-bold">Dashboard</h1>
<p className="text-slate-400">Welcome back, {session?.user?.name}</p>
<Panel>
<div className="flex items-center gap-2 text-xs uppercase tracking-[0.24em] text-[color:var(--terminal-muted)]">
<Activity className="size-4" />
Runtime state: {loading ? 'syncing' : 'stable'}
</div>
<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 Filings</h3>
<p className="text-4xl font-bold text-blue-400">{stats.filings}</p>
</div>
<div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
<h3 className="text-slate-400 mb-2">Portfolio Value</h3>
<p className="text-4xl font-bold text-green-400">
${stats.portfolioValue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
</p>
</div>
<div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
<h3 className="text-slate-400 mb-2">Watchlist</h3>
<p className="text-4xl font-bold text-purple-400">{stats.watchlist}</p>
</div>
</div>
<div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
<h2 className="text-xl font-semibold mb-4">Quick Actions</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Link href="/watchlist/add" className="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg text-center transition">
Add to Watchlist
</Link>
<Link href="/portfolio" className="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg text-center transition">
Add to Portfolio
</Link>
<Link href="/filings" className="bg-slate-700 hover:bg-slate-600 text-white px-6 py-3 rounded-lg text-center transition">
Search SEC Filings
</Link>
<Link href="/portfolio" className="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg text-center transition">
View Portfolio
</Link>
</div>
</div>
</main>
</div>
</Panel>
</AppShell>
);
}