254 lines
11 KiB
TypeScript
254 lines
11 KiB
TypeScript
'use client';
|
|
|
|
import { useQueryClient } from '@tanstack/react-query';
|
|
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 { useAuthGuard } from '@/hooks/use-auth-guard';
|
|
import { useLinkPrefetch } from '@/hooks/use-link-prefetch';
|
|
import {
|
|
queuePortfolioInsights,
|
|
queuePriceRefresh
|
|
} from '@/lib/api';
|
|
import { buildGraphingHref } from '@/lib/graphing/catalog';
|
|
import type { PortfolioInsight, PortfolioSummary, Task } from '@/lib/types';
|
|
import { formatCompactCurrency, formatCurrency, formatPercent } from '@/lib/format';
|
|
import { queryKeys } from '@/lib/query/keys';
|
|
import {
|
|
filingsQueryOptions,
|
|
latestPortfolioInsightQueryOptions,
|
|
portfolioSummaryQueryOptions,
|
|
recentTasksQueryOptions,
|
|
watchlistQueryOptions
|
|
} from '@/lib/query/options';
|
|
|
|
type DashboardState = {
|
|
summary: PortfolioSummary;
|
|
filingsCount: number;
|
|
watchlistCount: number;
|
|
tasks: Task[];
|
|
latestInsight: PortfolioInsight | null;
|
|
};
|
|
|
|
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
|
|
};
|
|
|
|
export default function CommandCenterPage() {
|
|
const { isPending, isAuthenticated, session } = useAuthGuard();
|
|
const queryClient = useQueryClient();
|
|
const { prefetchPortfolioSurfaces } = useLinkPrefetch();
|
|
const [state, setState] = useState<DashboardState>(EMPTY_STATE);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const loadData = useCallback(async () => {
|
|
const summaryOptions = portfolioSummaryQueryOptions();
|
|
const filingsOptions = filingsQueryOptions({ limit: 200 });
|
|
const watchlistOptions = watchlistQueryOptions();
|
|
const tasksOptions = recentTasksQueryOptions(20);
|
|
const insightOptions = latestPortfolioInsightQueryOptions();
|
|
|
|
if (!queryClient.getQueryData(summaryOptions.queryKey)) {
|
|
setLoading(true);
|
|
}
|
|
|
|
setError(null);
|
|
|
|
try {
|
|
const [summaryRes, filingsRes, watchlistRes, tasksRes, insightRes] = await Promise.all([
|
|
queryClient.ensureQueryData(summaryOptions),
|
|
queryClient.ensureQueryData(filingsOptions),
|
|
queryClient.ensureQueryData(watchlistOptions),
|
|
queryClient.ensureQueryData(tasksOptions),
|
|
queryClient.ensureQueryData(insightOptions)
|
|
]);
|
|
|
|
setState({
|
|
summary: summaryRes.summary,
|
|
filingsCount: filingsRes.filings.length,
|
|
watchlistCount: watchlistRes.items.length,
|
|
tasks: tasksRes.tasks,
|
|
latestInsight: insightRes.insight
|
|
});
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : 'Failed to load dashboard');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [queryClient]);
|
|
|
|
useEffect(() => {
|
|
if (!isPending && isAuthenticated) {
|
|
void loadData();
|
|
}
|
|
}, [isPending, isAuthenticated, loadData]);
|
|
|
|
const headerActions = (
|
|
<>
|
|
<Button
|
|
variant="secondary"
|
|
onClick={async () => {
|
|
try {
|
|
await queuePriceRefresh();
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.portfolioSummary() });
|
|
await loadData();
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : 'Failed to queue price refresh');
|
|
}
|
|
}}
|
|
>
|
|
<RefreshCw className="size-4" />
|
|
Refresh prices
|
|
</Button>
|
|
<Button
|
|
onClick={async () => {
|
|
try {
|
|
await queuePortfolioInsights();
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.latestPortfolioInsight() });
|
|
await loadData();
|
|
} 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 (
|
|
<AppShell
|
|
title="Command Center"
|
|
subtitle={`Welcome back${session?.user?.name ? `, ${session.user.name}` : ''}. Review tasks, portfolio health, and AI outputs.`}
|
|
actions={headerActions}
|
|
>
|
|
{error ? (
|
|
<Panel variant="surface">
|
|
<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="Coverage Names" 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" variant="surface">
|
|
{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 AI SDK (Zhipu)" className="xl:col-span-2" variant="surface">
|
|
{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-4 md:grid-cols-2 xl:grid-cols-3">
|
|
<Link className="border-l-2 border-[color:var(--line-weak)] py-1 pl-4 pr-2 transition hover:border-[color:var(--line-strong)]" href="/analysis">
|
|
<p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Analysis</p>
|
|
<p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Inspect one company across prices, filings, financials, and AI reports.</p>
|
|
</Link>
|
|
<Link className="border-l-2 border-[color:var(--line-weak)] py-1 pl-4 pr-2 transition hover:border-[color:var(--line-strong)]" href="/financials">
|
|
<p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Financials</p>
|
|
<p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Focus on multi-period filing metrics, margins, leverage, and balance sheet composition.</p>
|
|
</Link>
|
|
<Link className="border-l-2 border-[color:var(--line-weak)] py-1 pl-4 pr-2 transition hover:border-[color:var(--line-strong)]" href={buildGraphingHref()}>
|
|
<p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Graphing</p>
|
|
<p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Compare one normalized metric across multiple companies with shareable chart state.</p>
|
|
</Link>
|
|
<Link
|
|
className="border-l-2 border-[color:var(--line-weak)] py-1 pl-4 pr-2 transition hover:border-[color:var(--line-strong)]"
|
|
href="/filings"
|
|
onMouseEnter={() => {
|
|
void queryClient.prefetchQuery(filingsQueryOptions({ limit: 120 }));
|
|
}}
|
|
onFocus={() => {
|
|
void queryClient.prefetchQuery(filingsQueryOptions({ limit: 120 }));
|
|
}}
|
|
>
|
|
<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="border-l-2 border-[color:var(--line-weak)] py-1 pl-4 pr-2 transition hover:border-[color:var(--line-strong)]"
|
|
href="/portfolio"
|
|
onMouseEnter={() => prefetchPortfolioSurfaces()}
|
|
onFocus={() => prefetchPortfolioSurfaces()}
|
|
>
|
|
<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 the active private portfolio and mark positions to market.</p>
|
|
</Link>
|
|
<Link
|
|
className="border-l-2 border-[color:var(--line-weak)] py-1 pl-4 pr-2 transition hover:border-[color:var(--line-strong)]"
|
|
href="/watchlist"
|
|
onMouseEnter={() => prefetchPortfolioSurfaces()}
|
|
onFocus={() => prefetchPortfolioSurfaces()}
|
|
>
|
|
<p className="panel-heading text-xs uppercase text-[color:var(--terminal-muted)]">Coverage</p>
|
|
<p className="mt-2 text-sm text-[color:var(--terminal-bright)]">Track research status, review cadence, and filing freshness per company.</p>
|
|
</Link>
|
|
</div>
|
|
</Panel>
|
|
|
|
<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>
|
|
</Panel>
|
|
</AppShell>
|
|
);
|
|
}
|