upgrade navigation and route prefetch responsiveness
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import Link from 'next/link';
|
||||
import { Suspense, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
@@ -19,7 +20,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Panel } from '@/components/ui/panel';
|
||||
import { useAuthGuard } from '@/hooks/use-auth-guard';
|
||||
import { getCompanyAnalysis } from '@/lib/api';
|
||||
import { useLinkPrefetch } from '@/hooks/use-link-prefetch';
|
||||
import {
|
||||
asNumber,
|
||||
formatCurrency,
|
||||
@@ -27,6 +28,8 @@ import {
|
||||
formatPercent,
|
||||
type NumberScaleUnit
|
||||
} from '@/lib/format';
|
||||
import { queryKeys } from '@/lib/query/keys';
|
||||
import { companyAnalysisQueryOptions } from '@/lib/query/options';
|
||||
import type { CompanyAnalysis } from '@/lib/types';
|
||||
|
||||
type FinancialPeriodFilter = 'quarterlyAndFiscalYearEnd' | 'quarterlyOnly' | 'fiscalYearEndOnly';
|
||||
@@ -53,6 +56,12 @@ const FINANCIAL_VALUE_SCALE_OPTIONS: Array<{ value: NumberScaleUnit; label: stri
|
||||
{ value: 'billions', label: 'Billions (B)' }
|
||||
];
|
||||
|
||||
const CHART_TEXT = '#e8fff8';
|
||||
const CHART_MUTED = '#b4ced9';
|
||||
const CHART_GRID = 'rgba(126, 217, 255, 0.24)';
|
||||
const CHART_TOOLTIP_BG = 'rgba(6, 17, 24, 0.95)';
|
||||
const CHART_TOOLTIP_BORDER = 'rgba(123, 255, 217, 0.45)';
|
||||
|
||||
function formatShortDate(value: string) {
|
||||
return format(new Date(value), 'MMM yyyy');
|
||||
}
|
||||
@@ -109,6 +118,8 @@ export default function AnalysisPage() {
|
||||
function AnalysisPageContent() {
|
||||
const { isPending, isAuthenticated } = useAuthGuard();
|
||||
const searchParams = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const { prefetchReport, prefetchResearchTicker } = useLinkPrefetch();
|
||||
|
||||
const [tickerInput, setTickerInput] = useState('MSFT');
|
||||
const [ticker, setTicker] = useState('MSFT');
|
||||
@@ -134,11 +145,16 @@ function AnalysisPageContent() {
|
||||
}, [searchParams]);
|
||||
|
||||
const loadAnalysis = useCallback(async (symbol: string) => {
|
||||
setLoading(true);
|
||||
const options = companyAnalysisQueryOptions(symbol);
|
||||
|
||||
if (!queryClient.getQueryData(options.queryKey)) {
|
||||
setLoading(true);
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await getCompanyAnalysis(symbol);
|
||||
const response = await queryClient.ensureQueryData(options);
|
||||
setAnalysis(response.analysis);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unable to load company analysis');
|
||||
@@ -146,7 +162,7 @@ function AnalysisPageContent() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
@@ -199,8 +215,15 @@ function AnalysisPageContent() {
|
||||
<AppShell
|
||||
title="Company Analysis"
|
||||
subtitle="Research a single ticker across pricing, 10-K/10-Q financials, qualitative filings, and generated AI reports."
|
||||
activeTicker={analysis?.company.ticker ?? ticker}
|
||||
actions={(
|
||||
<Button variant="secondary" onClick={() => void loadAnalysis(ticker)}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.companyAnalysis(ticker.trim().toUpperCase()) });
|
||||
void loadAnalysis(ticker);
|
||||
}}
|
||||
>
|
||||
<RefreshCcw className="size-4" />
|
||||
Refresh
|
||||
</Button>
|
||||
@@ -229,7 +252,12 @@ function AnalysisPageContent() {
|
||||
Analyze
|
||||
</Button>
|
||||
{analysis ? (
|
||||
<Link href={`/filings?ticker=${analysis.company.ticker}`} className="text-sm text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
|
||||
<Link
|
||||
href={`/filings?ticker=${analysis.company.ticker}`}
|
||||
onMouseEnter={() => prefetchResearchTicker(analysis.company.ticker)}
|
||||
onFocus={() => prefetchResearchTicker(analysis.company.ticker)}
|
||||
className="text-sm text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
Open filing stream
|
||||
</Link>
|
||||
) : null}
|
||||
@@ -277,10 +305,35 @@ function AnalysisPageContent() {
|
||||
<div className="h-[320px]">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<LineChart data={priceSeries}>
|
||||
<CartesianGrid strokeDasharray="2 2" stroke="rgba(126, 217, 255, 0.2)" />
|
||||
<XAxis dataKey="label" minTickGap={32} stroke="#8cb6c5" fontSize={12} />
|
||||
<YAxis stroke="#8cb6c5" fontSize={12} tickFormatter={(value: number) => `$${value.toFixed(0)}`} />
|
||||
<Tooltip formatter={(value: number | string | undefined) => formatCurrency(value)} />
|
||||
<CartesianGrid strokeDasharray="2 2" stroke={CHART_GRID} />
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
minTickGap={32}
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
/>
|
||||
<YAxis
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
tickFormatter={(value: number) => `$${value.toFixed(0)}`}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value: number | string | undefined) => formatCurrency(value)}
|
||||
contentStyle={{
|
||||
backgroundColor: CHART_TOOLTIP_BG,
|
||||
border: `1px solid ${CHART_TOOLTIP_BORDER}`,
|
||||
borderRadius: '0.75rem'
|
||||
}}
|
||||
labelStyle={{ color: CHART_TEXT }}
|
||||
itemStyle={{ color: CHART_TEXT }}
|
||||
cursor={{ stroke: 'rgba(104, 255, 213, 0.35)', strokeWidth: 1 }}
|
||||
/>
|
||||
<Line type="monotone" dataKey="close" stroke="#68ffd5" strokeWidth={2} dot={false} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
@@ -432,6 +485,8 @@ function AnalysisPageContent() {
|
||||
<p className="text-xs text-[color:var(--terminal-muted)]">{report.accessionNumber}</p>
|
||||
<Link
|
||||
href={`/analysis/reports/${analysis.company.ticker}/${encodeURIComponent(report.accessionNumber)}`}
|
||||
onMouseEnter={() => prefetchReport(analysis.company.ticker, report.accessionNumber)}
|
||||
onFocus={() => prefetchReport(analysis.company.ticker, report.accessionNumber)}
|
||||
className="text-xs uppercase tracking-[0.12em] text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
Open summary
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import Link from 'next/link';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
@@ -7,7 +8,9 @@ import { ArrowLeft, BrainCircuit, RefreshCcw } from 'lucide-react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { AppShell } from '@/components/shell/app-shell';
|
||||
import { useAuthGuard } from '@/hooks/use-auth-guard';
|
||||
import { getCompanyAiReport } from '@/lib/api';
|
||||
import { useLinkPrefetch } from '@/hooks/use-link-prefetch';
|
||||
import { queryKeys } from '@/lib/query/keys';
|
||||
import { aiReportQueryOptions } from '@/lib/query/options';
|
||||
import type { CompanyAiReportDetail } from '@/lib/types';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Panel } from '@/components/ui/panel';
|
||||
@@ -25,6 +28,8 @@ function formatFilingDate(value: string) {
|
||||
export default function AnalysisReportPage() {
|
||||
const { isPending, isAuthenticated } = useAuthGuard();
|
||||
const params = useParams<{ ticker: string; accessionNumber: string }>();
|
||||
const queryClient = useQueryClient();
|
||||
const { prefetchResearchTicker } = useLinkPrefetch();
|
||||
|
||||
const tickerFromRoute = useMemo(() => {
|
||||
const value = typeof params.ticker === 'string' ? params.ticker : '';
|
||||
@@ -48,11 +53,16 @@ export default function AnalysisReportPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
const options = aiReportQueryOptions(accessionNumber);
|
||||
|
||||
if (!queryClient.getQueryData(options.queryKey)) {
|
||||
setLoading(true);
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await getCompanyAiReport(accessionNumber);
|
||||
const response = await queryClient.ensureQueryData(options);
|
||||
setReport(response.report);
|
||||
} catch (err) {
|
||||
setReport(null);
|
||||
@@ -60,7 +70,7 @@ export default function AnalysisReportPage() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [accessionNumber]);
|
||||
}, [accessionNumber, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
@@ -73,13 +83,30 @@ export default function AnalysisReportPage() {
|
||||
}
|
||||
|
||||
const resolvedTicker = report?.ticker ?? tickerFromRoute;
|
||||
const analysisHref = resolvedTicker ? `/analysis?ticker=${encodeURIComponent(resolvedTicker)}` : '/analysis';
|
||||
const filingsHref = resolvedTicker ? `/filings?ticker=${encodeURIComponent(resolvedTicker)}` : '/filings';
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
title="AI Summary"
|
||||
subtitle={`Detailed filing analysis${resolvedTicker ? ` for ${resolvedTicker}` : ''}.`}
|
||||
activeTicker={resolvedTicker}
|
||||
breadcrumbs={[
|
||||
{ label: 'Analysis', href: analysisHref },
|
||||
{ label: 'Reports', href: analysisHref },
|
||||
{ label: resolvedTicker || 'Summary' }
|
||||
]}
|
||||
actions={(
|
||||
<Button variant="secondary" onClick={() => void loadReport()} disabled={loading}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
if (accessionNumber) {
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.report(accessionNumber) });
|
||||
}
|
||||
void loadReport();
|
||||
}}
|
||||
disabled={loading}
|
||||
>
|
||||
<RefreshCcw className="size-4" />
|
||||
Refresh
|
||||
</Button>
|
||||
@@ -88,14 +115,18 @@ export default function AnalysisReportPage() {
|
||||
<Panel>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Link
|
||||
href={`/analysis?ticker=${resolvedTicker}`}
|
||||
href={analysisHref}
|
||||
onMouseEnter={() => prefetchResearchTicker(resolvedTicker)}
|
||||
onFocus={() => prefetchResearchTicker(resolvedTicker)}
|
||||
className="inline-flex items-center gap-1 text-xs uppercase tracking-[0.12em] text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
<ArrowLeft className="size-3" />
|
||||
Back to analysis
|
||||
</Link>
|
||||
<Link
|
||||
href={`/filings?ticker=${resolvedTicker}`}
|
||||
href={filingsHref}
|
||||
onMouseEnter={() => prefetchResearchTicker(resolvedTicker)}
|
||||
onFocus={() => prefetchResearchTicker(resolvedTicker)}
|
||||
className="inline-flex items-center gap-1 text-xs uppercase tracking-[0.12em] text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
<ArrowLeft className="size-3" />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import Link from 'next/link';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Suspense } from 'react';
|
||||
@@ -12,10 +13,13 @@ 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 { useLinkPrefetch } from '@/hooks/use-link-prefetch';
|
||||
import { useTaskPoller } from '@/hooks/use-task-poller';
|
||||
import { getTask, listFilings, queueFilingAnalysis, queueFilingSync } from '@/lib/api';
|
||||
import { queueFilingAnalysis, queueFilingSync } from '@/lib/api';
|
||||
import type { Filing, Task } from '@/lib/types';
|
||||
import { formatCurrencyByScale, type NumberScaleUnit } from '@/lib/format';
|
||||
import { queryKeys } from '@/lib/query/keys';
|
||||
import { filingsQueryOptions, taskQueryOptions } from '@/lib/query/options';
|
||||
|
||||
const FINANCIAL_VALUE_SCALE_OPTIONS: Array<{ value: NumberScaleUnit; label: string }> = [
|
||||
{ value: 'thousands', label: 'Thousands (K)' },
|
||||
@@ -102,6 +106,8 @@ function FilingExternalLink({ href, label }: FilingExternalLinkProps) {
|
||||
function FilingsPageContent() {
|
||||
const { isPending, isAuthenticated } = useAuthGuard();
|
||||
const searchParams = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const { prefetchReport } = useLinkPrefetch();
|
||||
|
||||
const [filings, setFilings] = useState<Filing[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -123,18 +129,23 @@ function FilingsPageContent() {
|
||||
}, [searchParams]);
|
||||
|
||||
const loadFilings = useCallback(async (ticker?: string) => {
|
||||
setLoading(true);
|
||||
const options = filingsQueryOptions({ ticker, limit: 120 });
|
||||
|
||||
if (!queryClient.getQueryData(options.queryKey)) {
|
||||
setLoading(true);
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await listFilings({ ticker, limit: 120 });
|
||||
const response = await queryClient.ensureQueryData(options);
|
||||
setFilings(response.filings);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unable to fetch filings');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
@@ -146,6 +157,8 @@ function FilingsPageContent() {
|
||||
taskId: activeTask?.id ?? null,
|
||||
onTerminalState: async () => {
|
||||
setActiveTask(null);
|
||||
void queryClient.invalidateQueries({ queryKey: ['filings'] });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
await loadFilings(searchTicker || undefined);
|
||||
}
|
||||
});
|
||||
@@ -159,8 +172,10 @@ function FilingsPageContent() {
|
||||
|
||||
try {
|
||||
const { task } = await queueFilingSync({ ticker: syncTickerInput.trim().toUpperCase(), limit: 20 });
|
||||
const latest = await getTask(task.id);
|
||||
const latest = await queryClient.fetchQuery(taskQueryOptions(task.id));
|
||||
setActiveTask(latest.task);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
void queryClient.invalidateQueries({ queryKey: ['filings'] });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to queue filing sync');
|
||||
}
|
||||
@@ -169,8 +184,10 @@ function FilingsPageContent() {
|
||||
const triggerAnalysis = async (accessionNumber: string) => {
|
||||
try {
|
||||
const { task } = await queueFilingAnalysis(accessionNumber);
|
||||
const latest = await getTask(task.id);
|
||||
const latest = await queryClient.fetchQuery(taskQueryOptions(task.id));
|
||||
setActiveTask(latest.task);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
void queryClient.invalidateQueries({ queryKey: ['report'] });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to queue filing analysis');
|
||||
}
|
||||
@@ -196,10 +213,18 @@ function FilingsPageContent() {
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
title="Filings Stream"
|
||||
title="Filings"
|
||||
subtitle="Sync SEC submissions, keep 10-K/10-Q financial snapshots, and analyze qualitative signals from other forms."
|
||||
activeTicker={searchTicker || null}
|
||||
actions={(
|
||||
<Button variant="secondary" className="w-full sm:w-auto" onClick={() => void loadFilings(searchTicker || undefined)}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="w-full sm:w-auto"
|
||||
onClick={() => {
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.filings(searchTicker || null, 120) });
|
||||
void loadFilings(searchTicker || undefined);
|
||||
}}
|
||||
>
|
||||
<TimerReset className="size-4" />
|
||||
Refresh table
|
||||
</Button>
|
||||
@@ -351,6 +376,8 @@ function FilingsPageContent() {
|
||||
{hasAnalysis ? (
|
||||
<Link
|
||||
href={`/analysis/reports/${filing.ticker}/${encodeURIComponent(filing.accession_number)}`}
|
||||
onMouseEnter={() => prefetchReport(filing.ticker, filing.accession_number)}
|
||||
onFocus={() => prefetchReport(filing.ticker, filing.accession_number)}
|
||||
className="inline-flex items-center rounded-md border border-[color:var(--line-weak)] px-2 py-1 text-xs text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
Open summary
|
||||
@@ -419,6 +446,8 @@ function FilingsPageContent() {
|
||||
{hasAnalysis ? (
|
||||
<Link
|
||||
href={`/analysis/reports/${filing.ticker}/${encodeURIComponent(filing.accession_number)}`}
|
||||
onMouseEnter={() => prefetchReport(filing.ticker, filing.accession_number)}
|
||||
onFocus={() => prefetchReport(filing.ticker, filing.accession_number)}
|
||||
className="inline-flex items-center rounded-md border border-[color:var(--line-weak)] px-2 py-1 text-xs text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
Summary
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import Link from 'next/link';
|
||||
import { Suspense, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
@@ -25,12 +26,14 @@ import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Panel } from '@/components/ui/panel';
|
||||
import { useAuthGuard } from '@/hooks/use-auth-guard';
|
||||
import { getCompanyAnalysis } from '@/lib/api';
|
||||
import { useLinkPrefetch } from '@/hooks/use-link-prefetch';
|
||||
import {
|
||||
formatCurrencyByScale,
|
||||
formatPercent,
|
||||
type NumberScaleUnit
|
||||
} from '@/lib/format';
|
||||
import { queryKeys } from '@/lib/query/keys';
|
||||
import { companyAnalysisQueryOptions } from '@/lib/query/options';
|
||||
import type { CompanyAnalysis } from '@/lib/types';
|
||||
|
||||
type StatementPeriodPoint = {
|
||||
@@ -76,6 +79,16 @@ const FINANCIAL_VALUE_SCALE_OPTIONS: Array<{ value: NumberScaleUnit; label: stri
|
||||
{ value: 'billions', label: 'Billions (B)' }
|
||||
];
|
||||
|
||||
const CHART_TEXT = '#e8fff8';
|
||||
const CHART_MUTED = '#b4ced9';
|
||||
const CHART_GRID = 'rgba(126, 217, 255, 0.24)';
|
||||
const CHART_TOOLTIP_BG = 'rgba(6, 17, 24, 0.95)';
|
||||
const CHART_TOOLTIP_BORDER = 'rgba(123, 255, 217, 0.45)';
|
||||
|
||||
function renderLegendLabel(value: string) {
|
||||
return <span style={{ color: CHART_TEXT }}>{value}</span>;
|
||||
}
|
||||
|
||||
function formatShortDate(value: string) {
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
@@ -380,6 +393,8 @@ export default function FinancialsPage() {
|
||||
function FinancialsPageContent() {
|
||||
const { isPending, isAuthenticated } = useAuthGuard();
|
||||
const searchParams = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const { prefetchResearchTicker } = useLinkPrefetch();
|
||||
|
||||
const [tickerInput, setTickerInput] = useState('MSFT');
|
||||
const [ticker, setTicker] = useState('MSFT');
|
||||
@@ -405,11 +420,16 @@ function FinancialsPageContent() {
|
||||
}, [searchParams]);
|
||||
|
||||
const loadFinancials = useCallback(async (symbol: string) => {
|
||||
setLoading(true);
|
||||
const options = companyAnalysisQueryOptions(symbol);
|
||||
|
||||
if (!queryClient.getQueryData(options.queryKey)) {
|
||||
setLoading(true);
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await getCompanyAnalysis(symbol);
|
||||
const response = await queryClient.ensureQueryData(options);
|
||||
setAnalysis(response.analysis);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unable to load financial history');
|
||||
@@ -417,7 +437,7 @@ function FinancialsPageContent() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
@@ -535,8 +555,15 @@ function FinancialsPageContent() {
|
||||
<AppShell
|
||||
title="Financials"
|
||||
subtitle="Explore 10-K and 10-Q fundamentals, profitability, and balance sheet dynamics by ticker."
|
||||
activeTicker={analysis?.company.ticker ?? ticker}
|
||||
actions={(
|
||||
<Button variant="secondary" onClick={() => void loadFinancials(ticker)}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.companyAnalysis(ticker.trim().toUpperCase()) });
|
||||
void loadFinancials(ticker);
|
||||
}}
|
||||
>
|
||||
<RefreshCcw className="size-4" />
|
||||
Refresh
|
||||
</Button>
|
||||
@@ -566,10 +593,20 @@ function FinancialsPageContent() {
|
||||
</Button>
|
||||
{analysis ? (
|
||||
<>
|
||||
<Link href={`/analysis?ticker=${analysis.company.ticker}`} className="text-sm text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
|
||||
<Link
|
||||
href={`/analysis?ticker=${analysis.company.ticker}`}
|
||||
onMouseEnter={() => prefetchResearchTicker(analysis.company.ticker)}
|
||||
onFocus={() => prefetchResearchTicker(analysis.company.ticker)}
|
||||
className="text-sm text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
Open full analysis
|
||||
</Link>
|
||||
<Link href={`/filings?ticker=${analysis.company.ticker}`} className="text-sm text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
|
||||
<Link
|
||||
href={`/filings?ticker=${analysis.company.ticker}`}
|
||||
onMouseEnter={() => prefetchResearchTicker(analysis.company.ticker)}
|
||||
onFocus={() => prefetchResearchTicker(analysis.company.ticker)}
|
||||
className="text-sm text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
Open filings stream
|
||||
</Link>
|
||||
</>
|
||||
@@ -648,11 +685,36 @@ function FinancialsPageContent() {
|
||||
<div className="h-[330px]">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={chartSeries}>
|
||||
<CartesianGrid strokeDasharray="2 2" stroke="rgba(126, 217, 255, 0.2)" />
|
||||
<XAxis dataKey="label" minTickGap={20} stroke="#8cb6c5" fontSize={12} />
|
||||
<YAxis stroke="#8cb6c5" fontSize={12} tickFormatter={(value: number) => asAxisCurrencyTick(value, financialValueScale)} />
|
||||
<Tooltip formatter={(value) => asTooltipCurrency(value, financialValueScale)} />
|
||||
<Legend />
|
||||
<CartesianGrid strokeDasharray="2 2" stroke={CHART_GRID} />
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
minTickGap={20}
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
/>
|
||||
<YAxis
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
tickFormatter={(value: number) => asAxisCurrencyTick(value, financialValueScale)}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value) => asTooltipCurrency(value, financialValueScale)}
|
||||
contentStyle={{
|
||||
backgroundColor: CHART_TOOLTIP_BG,
|
||||
border: `1px solid ${CHART_TOOLTIP_BORDER}`,
|
||||
borderRadius: '0.75rem'
|
||||
}}
|
||||
labelStyle={{ color: CHART_TEXT }}
|
||||
itemStyle={{ color: CHART_TEXT }}
|
||||
cursor={{ fill: 'rgba(104, 255, 213, 0.08)' }}
|
||||
/>
|
||||
<Legend wrapperStyle={{ paddingTop: '0.75rem' }} formatter={renderLegendLabel} />
|
||||
<Bar dataKey="revenue" name="Revenue" fill="#68ffd5" radius={[4, 4, 0, 0]} />
|
||||
<Bar dataKey="netIncome" name="Net Income" fill="#5fd3ff" radius={[4, 4, 0, 0]} />
|
||||
</BarChart>
|
||||
@@ -676,11 +738,36 @@ function FinancialsPageContent() {
|
||||
<stop offset="95%" stopColor="#68ffd5" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="2 2" stroke="rgba(126, 217, 255, 0.2)" />
|
||||
<XAxis dataKey="label" minTickGap={20} stroke="#8cb6c5" fontSize={12} />
|
||||
<YAxis stroke="#8cb6c5" fontSize={12} tickFormatter={(value: number) => asAxisCurrencyTick(value, financialValueScale)} />
|
||||
<Tooltip formatter={(value) => asTooltipCurrency(value, financialValueScale)} />
|
||||
<Legend />
|
||||
<CartesianGrid strokeDasharray="2 2" stroke={CHART_GRID} />
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
minTickGap={20}
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
/>
|
||||
<YAxis
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
tickFormatter={(value: number) => asAxisCurrencyTick(value, financialValueScale)}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value) => asTooltipCurrency(value, financialValueScale)}
|
||||
contentStyle={{
|
||||
backgroundColor: CHART_TOOLTIP_BG,
|
||||
border: `1px solid ${CHART_TOOLTIP_BORDER}`,
|
||||
borderRadius: '0.75rem'
|
||||
}}
|
||||
labelStyle={{ color: CHART_TEXT }}
|
||||
itemStyle={{ color: CHART_TEXT }}
|
||||
cursor={{ fill: 'rgba(104, 255, 213, 0.08)' }}
|
||||
/>
|
||||
<Legend wrapperStyle={{ paddingTop: '0.75rem' }} formatter={renderLegendLabel} />
|
||||
<Area type="monotone" dataKey="totalAssets" name="Total Assets" stroke="#68ffd5" fill="url(#assetsGradient)" strokeWidth={2} />
|
||||
<Line type="monotone" dataKey="cash" name="Cash" stroke="#8bd3ff" strokeWidth={2} dot={false} />
|
||||
<Line type="monotone" dataKey="debt" name="Debt" stroke="#ffd08a" strokeWidth={2} dot={false} />
|
||||
@@ -701,9 +788,24 @@ function FinancialsPageContent() {
|
||||
<div className="h-[300px]">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<LineChart data={chartSeries}>
|
||||
<CartesianGrid strokeDasharray="2 2" stroke="rgba(126, 217, 255, 0.2)" />
|
||||
<XAxis dataKey="label" minTickGap={20} stroke="#8cb6c5" fontSize={12} />
|
||||
<YAxis stroke="#8cb6c5" fontSize={12} tickFormatter={(value: number) => `${value.toFixed(0)}%`} />
|
||||
<CartesianGrid strokeDasharray="2 2" stroke={CHART_GRID} />
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
minTickGap={20}
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
/>
|
||||
<YAxis
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
tickFormatter={(value: number) => `${value.toFixed(0)}%`}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value) => {
|
||||
const normalized = normalizeTooltipValue(value);
|
||||
@@ -714,8 +816,16 @@ function FinancialsPageContent() {
|
||||
const numeric = Number(normalized);
|
||||
return Number.isFinite(numeric) ? `${numeric.toFixed(2)}%` : 'n/a';
|
||||
}}
|
||||
contentStyle={{
|
||||
backgroundColor: CHART_TOOLTIP_BG,
|
||||
border: `1px solid ${CHART_TOOLTIP_BORDER}`,
|
||||
borderRadius: '0.75rem'
|
||||
}}
|
||||
labelStyle={{ color: CHART_TEXT }}
|
||||
itemStyle={{ color: CHART_TEXT }}
|
||||
cursor={{ stroke: 'rgba(104, 255, 213, 0.35)', strokeWidth: 1 }}
|
||||
/>
|
||||
<Legend />
|
||||
<Legend wrapperStyle={{ paddingTop: '0.75rem' }} formatter={renderLegendLabel} />
|
||||
<Line type="monotone" dataKey="netMargin" name="Net Margin" stroke="#68ffd5" strokeWidth={2} dot={false} connectNulls />
|
||||
<Line type="monotone" dataKey="debtToAssets" name="Debt / Assets" stroke="#ffb980" strokeWidth={2} dot={false} connectNulls />
|
||||
</LineChart>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import './globals.css';
|
||||
import type { Metadata } from 'next';
|
||||
import { QueryProvider } from '@/components/providers/query-provider';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Fiscal Clone',
|
||||
@@ -9,7 +10,9 @@ export const metadata: Metadata = {
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>{children}</body>
|
||||
<body>
|
||||
<QueryProvider>{children}</QueryProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
79
app/page.tsx
79
app/page.tsx
@@ -1,5 +1,6 @@
|
||||
'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';
|
||||
@@ -10,19 +11,23 @@ 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 { useLinkPrefetch } from '@/hooks/use-link-prefetch';
|
||||
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';
|
||||
import { queryKeys } from '@/lib/query/keys';
|
||||
import {
|
||||
filingsQueryOptions,
|
||||
latestPortfolioInsightQueryOptions,
|
||||
portfolioSummaryQueryOptions,
|
||||
recentTasksQueryOptions,
|
||||
taskQueryOptions,
|
||||
watchlistQueryOptions
|
||||
} from '@/lib/query/options';
|
||||
|
||||
type DashboardState = {
|
||||
summary: PortfolioSummary;
|
||||
@@ -48,22 +53,33 @@ const EMPTY_STATE: DashboardState = {
|
||||
|
||||
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 [activeTaskId, setActiveTaskId] = useState<string | null>(null);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
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([
|
||||
getPortfolioSummary(),
|
||||
listFilings({ limit: 200 }),
|
||||
listWatchlist(),
|
||||
listRecentTasks(20),
|
||||
getLatestPortfolioInsight()
|
||||
queryClient.ensureQueryData(summaryOptions),
|
||||
queryClient.ensureQueryData(filingsOptions),
|
||||
queryClient.ensureQueryData(watchlistOptions),
|
||||
queryClient.ensureQueryData(tasksOptions),
|
||||
queryClient.ensureQueryData(insightOptions)
|
||||
]);
|
||||
|
||||
setState({
|
||||
@@ -78,7 +94,7 @@ export default function CommandCenterPage() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
@@ -90,6 +106,10 @@ export default function CommandCenterPage() {
|
||||
taskId: activeTaskId,
|
||||
onTerminalState: () => {
|
||||
setActiveTaskId(null);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.portfolioSummary() });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.latestPortfolioInsight() });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
void queryClient.invalidateQueries({ queryKey: ['filings'] });
|
||||
void loadData();
|
||||
}
|
||||
});
|
||||
@@ -102,8 +122,10 @@ export default function CommandCenterPage() {
|
||||
try {
|
||||
const { task } = await queuePriceRefresh();
|
||||
setActiveTaskId(task.id);
|
||||
const latest = await getTask(task.id);
|
||||
const latest = await queryClient.fetchQuery(taskQueryOptions(task.id));
|
||||
setState((prev) => ({ ...prev, tasks: [latest.task, ...prev.tasks] }));
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.portfolioSummary() });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to queue price refresh');
|
||||
}
|
||||
@@ -117,8 +139,10 @@ export default function CommandCenterPage() {
|
||||
try {
|
||||
const { task } = await queuePortfolioInsights();
|
||||
setActiveTaskId(task.id);
|
||||
const latest = await getTask(task.id);
|
||||
const latest = await queryClient.fetchQuery(taskQueryOptions(task.id));
|
||||
setState((prev) => ({ ...prev, tasks: [latest.task, ...prev.tasks] }));
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.latestPortfolioInsight() });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to queue AI insight');
|
||||
}
|
||||
@@ -211,15 +235,34 @@ export default function CommandCenterPage() {
|
||||
<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="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">
|
||||
<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"
|
||||
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="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">
|
||||
<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"
|
||||
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 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">
|
||||
<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"
|
||||
onMouseEnter={() => prefetchPortfolioSurfaces()}
|
||||
onFocus={() => prefetchPortfolioSurfaces()}
|
||||
>
|
||||
<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>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, BarChart, CartesianGrid, XAxis, YAxis, Bar } from 'recharts';
|
||||
import { PieChart, Pie, Cell, Tooltip, Legend, 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';
|
||||
@@ -12,16 +13,19 @@ 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';
|
||||
import { queryKeys } from '@/lib/query/keys';
|
||||
import {
|
||||
holdingsQueryOptions,
|
||||
latestPortfolioInsightQueryOptions,
|
||||
portfolioSummaryQueryOptions,
|
||||
taskQueryOptions
|
||||
} from '@/lib/query/options';
|
||||
|
||||
type FormState = {
|
||||
ticker: string;
|
||||
@@ -31,6 +35,11 @@ type FormState = {
|
||||
};
|
||||
|
||||
const CHART_COLORS = ['#6effd8', '#5fd3ff', '#66ffa1', '#8dbbff', '#f4f88f', '#ff9c9c'];
|
||||
const CHART_TEXT = '#e8fff8';
|
||||
const CHART_MUTED = '#b4ced9';
|
||||
const CHART_GRID = 'rgba(126, 217, 255, 0.24)';
|
||||
const CHART_TOOLTIP_BG = 'rgba(6, 17, 24, 0.95)';
|
||||
const CHART_TOOLTIP_BORDER = 'rgba(123, 255, 217, 0.45)';
|
||||
|
||||
const EMPTY_SUMMARY: PortfolioSummary = {
|
||||
positions: 0,
|
||||
@@ -42,6 +51,7 @@ const EMPTY_SUMMARY: PortfolioSummary = {
|
||||
|
||||
export default function PortfolioPage() {
|
||||
const { isPending, isAuthenticated } = useAuthGuard();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [holdings, setHoldings] = useState<Holding[]>([]);
|
||||
const [summary, setSummary] = useState<PortfolioSummary>(EMPTY_SUMMARY);
|
||||
@@ -52,14 +62,21 @@ export default function PortfolioPage() {
|
||||
const [form, setForm] = useState<FormState>({ ticker: '', shares: '', avgCost: '', currentPrice: '' });
|
||||
|
||||
const loadPortfolio = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const holdingsOptions = holdingsQueryOptions();
|
||||
const summaryOptions = portfolioSummaryQueryOptions();
|
||||
const insightOptions = latestPortfolioInsightQueryOptions();
|
||||
|
||||
if (!queryClient.getQueryData(summaryOptions.queryKey)) {
|
||||
setLoading(true);
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const [holdingsRes, summaryRes, insightRes] = await Promise.all([
|
||||
listHoldings(),
|
||||
getPortfolioSummary(),
|
||||
getLatestPortfolioInsight()
|
||||
queryClient.ensureQueryData(holdingsOptions),
|
||||
queryClient.ensureQueryData(summaryOptions),
|
||||
queryClient.ensureQueryData(insightOptions)
|
||||
]);
|
||||
|
||||
setHoldings(holdingsRes.holdings);
|
||||
@@ -70,7 +87,7 @@ export default function PortfolioPage() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
@@ -82,6 +99,10 @@ export default function PortfolioPage() {
|
||||
taskId: activeTask?.id ?? null,
|
||||
onTerminalState: async () => {
|
||||
setActiveTask(null);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.holdings() });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.portfolioSummary() });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.latestPortfolioInsight() });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
await loadPortfolio();
|
||||
}
|
||||
});
|
||||
@@ -116,6 +137,8 @@ export default function PortfolioPage() {
|
||||
});
|
||||
|
||||
setForm({ ticker: '', shares: '', avgCost: '', currentPrice: '' });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.holdings() });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.portfolioSummary() });
|
||||
await loadPortfolio();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save holding');
|
||||
@@ -125,8 +148,10 @@ export default function PortfolioPage() {
|
||||
const queueRefresh = async () => {
|
||||
try {
|
||||
const { task } = await queuePriceRefresh();
|
||||
const latest = await getTask(task.id);
|
||||
const latest = await queryClient.fetchQuery(taskQueryOptions(task.id));
|
||||
setActiveTask(latest.task);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.portfolioSummary() });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unable to queue price refresh');
|
||||
}
|
||||
@@ -135,8 +160,10 @@ export default function PortfolioPage() {
|
||||
const queueInsights = async () => {
|
||||
try {
|
||||
const { task } = await queuePortfolioInsights();
|
||||
const latest = await getTask(task.id);
|
||||
const latest = await queryClient.fetchQuery(taskQueryOptions(task.id));
|
||||
setActiveTask(latest.task);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.latestPortfolioInsight() });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unable to queue portfolio insights');
|
||||
}
|
||||
@@ -148,7 +175,7 @@ export default function PortfolioPage() {
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
title="Portfolio Matrix"
|
||||
title="Portfolio"
|
||||
subtitle="Position management, market valuation, and AI generated portfolio commentary."
|
||||
actions={(
|
||||
<>
|
||||
@@ -209,7 +236,22 @@ export default function PortfolioPage() {
|
||||
<Cell key={`${entry.name}-${index}`} fill={CHART_COLORS[index % CHART_COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip formatter={(value: number | string | undefined) => formatCurrency(value)} />
|
||||
<Tooltip
|
||||
formatter={(value: number | string | undefined) => formatCurrency(value)}
|
||||
contentStyle={{
|
||||
backgroundColor: CHART_TOOLTIP_BG,
|
||||
border: `1px solid ${CHART_TOOLTIP_BORDER}`,
|
||||
borderRadius: '0.75rem'
|
||||
}}
|
||||
labelStyle={{ color: CHART_TEXT }}
|
||||
itemStyle={{ color: CHART_TEXT }}
|
||||
/>
|
||||
<Legend
|
||||
verticalAlign="bottom"
|
||||
iconType="circle"
|
||||
wrapperStyle={{ paddingTop: '0.75rem' }}
|
||||
formatter={(value) => <span style={{ color: CHART_TEXT }}>{value}</span>}
|
||||
/>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
@@ -225,10 +267,33 @@ export default function PortfolioPage() {
|
||||
<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 | string | undefined) => `${asNumber(value).toFixed(2)}%`} />
|
||||
<CartesianGrid strokeDasharray="2 2" stroke={CHART_GRID} />
|
||||
<XAxis
|
||||
dataKey="name"
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
/>
|
||||
<YAxis
|
||||
stroke={CHART_MUTED}
|
||||
fontSize={12}
|
||||
axisLine={{ stroke: CHART_MUTED }}
|
||||
tickLine={{ stroke: CHART_MUTED }}
|
||||
tick={{ fill: CHART_MUTED }}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value: number | string | undefined) => `${asNumber(value).toFixed(2)}%`}
|
||||
contentStyle={{
|
||||
backgroundColor: CHART_TOOLTIP_BG,
|
||||
border: `1px solid ${CHART_TOOLTIP_BORDER}`,
|
||||
borderRadius: '0.75rem'
|
||||
}}
|
||||
labelStyle={{ color: CHART_TEXT }}
|
||||
itemStyle={{ color: CHART_TEXT }}
|
||||
cursor={{ fill: 'rgba(104, 255, 213, 0.08)' }}
|
||||
/>
|
||||
<Bar dataKey="value" fill="#68ffd5" radius={[4, 4, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
@@ -277,6 +342,8 @@ export default function PortfolioPage() {
|
||||
onClick={async () => {
|
||||
try {
|
||||
await deleteHolding(holding.id);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.holdings() });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.portfolioSummary() });
|
||||
await loadPortfolio();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete holding');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { ArrowRight, Eye, Plus, Trash2 } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
@@ -8,10 +9,13 @@ 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 { useLinkPrefetch } from '@/hooks/use-link-prefetch';
|
||||
import { useAuthGuard } from '@/hooks/use-auth-guard';
|
||||
import { useTaskPoller } from '@/hooks/use-task-poller';
|
||||
import { deleteWatchlistItem, getTask, listWatchlist, queueFilingSync, upsertWatchlistItem } from '@/lib/api';
|
||||
import { deleteWatchlistItem, queueFilingSync, upsertWatchlistItem } from '@/lib/api';
|
||||
import type { Task, WatchlistItem } from '@/lib/types';
|
||||
import { queryKeys } from '@/lib/query/keys';
|
||||
import { taskQueryOptions, watchlistQueryOptions } from '@/lib/query/options';
|
||||
|
||||
type FormState = {
|
||||
ticker: string;
|
||||
@@ -21,6 +25,8 @@ type FormState = {
|
||||
|
||||
export default function WatchlistPage() {
|
||||
const { isPending, isAuthenticated } = useAuthGuard();
|
||||
const queryClient = useQueryClient();
|
||||
const { prefetchResearchTicker } = useLinkPrefetch();
|
||||
|
||||
const [items, setItems] = useState<WatchlistItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -29,18 +35,23 @@ export default function WatchlistPage() {
|
||||
const [form, setForm] = useState<FormState>({ ticker: '', companyName: '', sector: '' });
|
||||
|
||||
const loadWatchlist = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const options = watchlistQueryOptions();
|
||||
|
||||
if (!queryClient.getQueryData(options.queryKey)) {
|
||||
setLoading(true);
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await listWatchlist();
|
||||
const response = await queryClient.ensureQueryData(options);
|
||||
setItems(response.items);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load watchlist');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
@@ -52,6 +63,8 @@ export default function WatchlistPage() {
|
||||
taskId: activeTask?.id ?? null,
|
||||
onTerminalState: () => {
|
||||
setActiveTask(null);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
void queryClient.invalidateQueries({ queryKey: ['filings'] });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -68,6 +81,7 @@ export default function WatchlistPage() {
|
||||
});
|
||||
|
||||
setForm({ ticker: '', companyName: '', sector: '' });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.watchlist() });
|
||||
await loadWatchlist();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save watchlist item');
|
||||
@@ -77,8 +91,9 @@ export default function WatchlistPage() {
|
||||
const queueSync = async (ticker: string) => {
|
||||
try {
|
||||
const { task } = await queueFilingSync({ ticker, limit: 20 });
|
||||
const latest = await getTask(task.id);
|
||||
const latest = await queryClient.fetchQuery(taskQueryOptions(task.id));
|
||||
setActiveTask(latest.task);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : `Failed to queue sync for ${ticker}`);
|
||||
}
|
||||
@@ -128,6 +143,8 @@ export default function WatchlistPage() {
|
||||
</Button>
|
||||
<Link
|
||||
href={`/filings?ticker=${item.ticker}`}
|
||||
onMouseEnter={() => prefetchResearchTicker(item.ticker)}
|
||||
onFocus={() => prefetchResearchTicker(item.ticker)}
|
||||
className="inline-flex items-center gap-1 text-xs text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
Open stream
|
||||
@@ -135,6 +152,8 @@ export default function WatchlistPage() {
|
||||
</Link>
|
||||
<Link
|
||||
href={`/analysis?ticker=${item.ticker}`}
|
||||
onMouseEnter={() => prefetchResearchTicker(item.ticker)}
|
||||
onFocus={() => prefetchResearchTicker(item.ticker)}
|
||||
className="inline-flex items-center gap-1 text-xs text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
Analyze
|
||||
@@ -146,6 +165,7 @@ export default function WatchlistPage() {
|
||||
onClick={async () => {
|
||||
try {
|
||||
await deleteWatchlistItem(item.id);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.watchlist() });
|
||||
await loadWatchlist();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to remove symbol');
|
||||
|
||||
Reference in New Issue
Block a user