556 lines
22 KiB
TypeScript
556 lines
22 KiB
TypeScript
'use client';
|
|
|
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import Link from 'next/link';
|
|
import { useEffect, useMemo, useState } from 'react';
|
|
import { Suspense } from 'react';
|
|
import { format } from 'date-fns';
|
|
import { Bot, Download, ExternalLink, NotebookPen, Search, TimerReset } from 'lucide-react';
|
|
import { useRouter, useSearchParams } from 'next/navigation';
|
|
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 { useAuthGuard } from '@/hooks/use-auth-guard';
|
|
import { useLinkPrefetch } from '@/hooks/use-link-prefetch';
|
|
import {
|
|
createResearchArtifact,
|
|
queueFilingAnalysis,
|
|
queueFilingSync
|
|
} from '@/lib/api';
|
|
import type { Filing } from '@/lib/types';
|
|
import { formatCurrencyByScale, type NumberScaleUnit } from '@/lib/format';
|
|
import { queryKeys } from '@/lib/query/keys';
|
|
import { filingsQueryOptions } from '@/lib/query/options';
|
|
|
|
const FINANCIAL_VALUE_SCALE_OPTIONS: Array<{ value: NumberScaleUnit; label: string }> = [
|
|
{ value: 'thousands', label: 'Thousands (K)' },
|
|
{ value: 'millions', label: 'Millions (M)' },
|
|
{ value: 'billions', label: 'Billions (B)' }
|
|
];
|
|
const FILINGS_QUERY_LIMIT = 120;
|
|
|
|
export default function FilingsPage() {
|
|
return (
|
|
<Suspense fallback={<div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Opening filings stream...</div>}>
|
|
<FilingsPageContent />
|
|
</Suspense>
|
|
);
|
|
}
|
|
|
|
function formatFilingDate(value: string) {
|
|
const date = new Date(value);
|
|
|
|
if (Number.isNaN(date.getTime())) {
|
|
return 'Unknown';
|
|
}
|
|
|
|
return format(date, 'MMM dd, yyyy');
|
|
}
|
|
|
|
function hasFinancialSnapshot(filing: Filing) {
|
|
return filing.filing_type === '10-K' || filing.filing_type === '10-Q';
|
|
}
|
|
|
|
function parseTagsInput(input: string) {
|
|
const unique = new Set<string>();
|
|
|
|
for (const segment of input.split(',')) {
|
|
const tag = segment.trim();
|
|
if (!tag) {
|
|
continue;
|
|
}
|
|
|
|
unique.add(tag);
|
|
}
|
|
|
|
return [...unique];
|
|
}
|
|
|
|
function normalizeTickerParam(value: string | null) {
|
|
if (typeof value !== 'string') {
|
|
return null;
|
|
}
|
|
|
|
const normalized = value.trim().toUpperCase();
|
|
return normalized.length > 0 ? normalized : null;
|
|
}
|
|
|
|
function asScaledFinancialSnapshot(
|
|
value: number | null | undefined,
|
|
scale: NumberScaleUnit
|
|
) {
|
|
if (value === null || value === undefined) {
|
|
return 'n/a';
|
|
}
|
|
|
|
return formatCurrencyByScale(value, scale);
|
|
}
|
|
|
|
function resolveOriginalFilingUrl(filing: Filing) {
|
|
if (filing.filing_url) {
|
|
return filing.filing_url;
|
|
}
|
|
|
|
if (!filing.primary_document) {
|
|
return null;
|
|
}
|
|
|
|
const cikDigits = filing.cik.replace(/\D/g, '');
|
|
const cikValue = Number.parseInt(cikDigits, 10);
|
|
|
|
if (!cikDigits || Number.isNaN(cikValue)) {
|
|
return null;
|
|
}
|
|
|
|
const compactAccession = filing.accession_number.replace(/-/g, '');
|
|
if (!compactAccession) {
|
|
return null;
|
|
}
|
|
|
|
return `https://www.sec.gov/Archives/edgar/data/${cikValue}/${compactAccession}/${filing.primary_document}`;
|
|
}
|
|
|
|
type FilingExternalLinkProps = {
|
|
href: string;
|
|
label: string;
|
|
};
|
|
|
|
function FilingExternalLink({ href, label }: FilingExternalLinkProps) {
|
|
return (
|
|
<a
|
|
href={href}
|
|
target="_blank"
|
|
rel="noreferrer"
|
|
className="inline-flex items-center gap-1 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)]"
|
|
>
|
|
{label}
|
|
<ExternalLink className="size-3" />
|
|
</a>
|
|
);
|
|
}
|
|
|
|
function FilingsPageContent() {
|
|
const { isPending, isAuthenticated } = useAuthGuard();
|
|
const searchParams = useSearchParams();
|
|
const router = useRouter();
|
|
const queryClient = useQueryClient();
|
|
const { prefetchReport } = useLinkPrefetch();
|
|
const activeTickerFilter = useMemo(() => normalizeTickerParam(searchParams.get('ticker')), [searchParams]);
|
|
const activeFilingsQueryKey = useMemo(
|
|
() => queryKeys.filings(activeTickerFilter, FILINGS_QUERY_LIMIT),
|
|
[activeTickerFilter]
|
|
);
|
|
const filingsQuery = useQuery({
|
|
...filingsQueryOptions({ ticker: activeTickerFilter ?? undefined, limit: FILINGS_QUERY_LIMIT }),
|
|
enabled: !isPending && isAuthenticated
|
|
});
|
|
|
|
const [syncTickerInput, setSyncTickerInput] = useState(() => activeTickerFilter ?? '');
|
|
const [syncCategoryInput, setSyncCategoryInput] = useState('');
|
|
const [syncTagsInput, setSyncTagsInput] = useState('');
|
|
const [filterTickerInput, setFilterTickerInput] = useState(() => activeTickerFilter ?? '');
|
|
const [financialValueScale, setFinancialValueScale] = useState<NumberScaleUnit>('millions');
|
|
const [actionNotice, setActionNotice] = useState<string | null>(null);
|
|
const [actionError, setActionError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
setSyncTickerInput(activeTickerFilter ?? '');
|
|
setFilterTickerInput(activeTickerFilter ?? '');
|
|
}, [activeTickerFilter]);
|
|
|
|
const filings = filingsQuery.data?.filings ?? [];
|
|
const loading = filingsQuery.isPending;
|
|
const filingsError = filingsQuery.error instanceof Error
|
|
? filingsQuery.error.message
|
|
: filingsQuery.error
|
|
? 'Unable to fetch filings'
|
|
: null;
|
|
|
|
const triggerSync = async () => {
|
|
if (!syncTickerInput.trim()) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setActionError(null);
|
|
await queueFilingSync({
|
|
ticker: syncTickerInput.trim().toUpperCase(),
|
|
limit: 20,
|
|
category: syncCategoryInput.trim() || undefined,
|
|
tags: parseTagsInput(syncTagsInput)
|
|
});
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
|
void queryClient.invalidateQueries({ queryKey: activeFilingsQueryKey });
|
|
} catch (err) {
|
|
setActionError(err instanceof Error ? err.message : 'Failed to queue filing sync');
|
|
}
|
|
};
|
|
|
|
const triggerAnalysis = async (accessionNumber: string) => {
|
|
try {
|
|
setActionError(null);
|
|
await queueFilingAnalysis(accessionNumber);
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
|
|
void queryClient.invalidateQueries({ queryKey: ['report'] });
|
|
} catch (err) {
|
|
setActionError(err instanceof Error ? err.message : 'Failed to queue filing analysis');
|
|
}
|
|
};
|
|
|
|
const saveToLibrary = async (filing: Filing) => {
|
|
try {
|
|
setActionError(null);
|
|
await createResearchArtifact({
|
|
ticker: filing.ticker,
|
|
kind: 'filing',
|
|
source: 'system',
|
|
subtype: 'filing_snapshot',
|
|
accessionNumber: filing.accession_number,
|
|
title: `${filing.filing_type} filing snapshot`,
|
|
summary: filing.analysis?.text ?? filing.analysis?.legacyInsights ?? `Captured filing ${filing.accession_number}.`,
|
|
bodyMarkdown: [
|
|
`Captured filing note for ${filing.company_name} (${filing.ticker}).`,
|
|
`Filed: ${formatFilingDate(filing.filing_date)}`,
|
|
`Accession: ${filing.accession_number}`,
|
|
'',
|
|
filing.analysis?.text ?? filing.analysis?.legacyInsights ?? 'Follow up on this filing from the stream.'
|
|
].join('\n'),
|
|
metadata: {
|
|
filingType: filing.filing_type,
|
|
filingDate: filing.filing_date,
|
|
filingUrl: filing.filing_url,
|
|
submissionUrl: filing.submission_url ?? null,
|
|
primaryDocument: filing.primary_document ?? null
|
|
}
|
|
});
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.researchWorkspace(filing.ticker) });
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.researchPacket(filing.ticker) });
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.researchJournal(filing.ticker) });
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.companyAnalysis(filing.ticker) });
|
|
void queryClient.invalidateQueries({ queryKey: queryKeys.watchlist() });
|
|
setActionNotice(`Saved ${filing.accession_number} to the ${filing.ticker} research library.`);
|
|
} catch (err) {
|
|
setActionError(err instanceof Error ? err.message : 'Failed to save filing to library');
|
|
}
|
|
};
|
|
|
|
const replaceTickerFilter = (ticker: string | null) => {
|
|
const nextParams = new URLSearchParams(searchParams.toString());
|
|
|
|
if (ticker) {
|
|
nextParams.set('ticker', ticker);
|
|
} else {
|
|
nextParams.delete('ticker');
|
|
}
|
|
|
|
const nextQuery = nextParams.toString();
|
|
router.replace(nextQuery ? `/filings?${nextQuery}` : '/filings', { scroll: false });
|
|
};
|
|
|
|
const groupedByTicker = useMemo(() => {
|
|
const counts = new Map<string, number>();
|
|
|
|
for (const filing of filings) {
|
|
counts.set(filing.ticker, (counts.get(filing.ticker) ?? 0) + 1);
|
|
}
|
|
|
|
return counts;
|
|
}, [filings]);
|
|
|
|
const selectedFinancialScaleLabel = useMemo(() => {
|
|
return FINANCIAL_VALUE_SCALE_OPTIONS.find((option) => option.value === financialValueScale)?.label ?? 'Millions (M)';
|
|
}, [financialValueScale]);
|
|
|
|
if (isPending || !isAuthenticated) {
|
|
return <div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Opening filings stream...</div>;
|
|
}
|
|
|
|
return (
|
|
<AppShell
|
|
title="Filings"
|
|
subtitle="Sync SEC submissions, keep 10-K/10-Q financial snapshots, and analyze qualitative signals from other forms."
|
|
activeTicker={activeTickerFilter}
|
|
actions={(
|
|
<>
|
|
<Link
|
|
href={`/search${activeTickerFilter ? `?ticker=${encodeURIComponent(activeTickerFilter)}` : ''}`}
|
|
className="inline-flex items-center justify-center gap-2 rounded-lg border border-[color:var(--line-weak)] px-3 py-2 text-sm text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
|
|
>
|
|
<Search className="size-4" />
|
|
Ask with RAG
|
|
</Link>
|
|
<Button
|
|
variant="secondary"
|
|
className="w-full sm:w-auto"
|
|
onClick={() => {
|
|
void queryClient.invalidateQueries({ queryKey: activeFilingsQueryKey });
|
|
}}
|
|
>
|
|
<TimerReset className="size-4" />
|
|
Refresh table
|
|
</Button>
|
|
</>
|
|
)}
|
|
>
|
|
<div className="grid grid-cols-1 gap-5 lg:grid-cols-[1.2fr_1fr]">
|
|
<Panel title="Sync Controller" subtitle="Queue ingestion jobs by ticker symbol.">
|
|
<form
|
|
className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center"
|
|
onSubmit={(event) => {
|
|
event.preventDefault();
|
|
void triggerSync();
|
|
}}
|
|
>
|
|
<Input
|
|
value={syncTickerInput}
|
|
onChange={(event) => setSyncTickerInput(event.target.value.toUpperCase())}
|
|
placeholder="Ticker (AAPL)"
|
|
className="w-full sm:max-w-xs"
|
|
/>
|
|
<Input
|
|
value={syncCategoryInput}
|
|
onChange={(event) => setSyncCategoryInput(event.target.value)}
|
|
placeholder="Category (optional)"
|
|
className="w-full sm:max-w-xs"
|
|
/>
|
|
<Input
|
|
value={syncTagsInput}
|
|
onChange={(event) => setSyncTagsInput(event.target.value)}
|
|
placeholder="Tags (comma-separated)"
|
|
className="w-full sm:max-w-xs"
|
|
/>
|
|
<Button type="submit" className="w-full sm:w-auto">
|
|
<Download className="size-4" />
|
|
Queue sync
|
|
</Button>
|
|
</form>
|
|
</Panel>
|
|
|
|
<Panel title="Search Index" subtitle="Filter by ticker in the local filing index.">
|
|
<form
|
|
className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center"
|
|
onSubmit={(event) => {
|
|
event.preventDefault();
|
|
const nextTicker = normalizeTickerParam(filterTickerInput);
|
|
setFilterTickerInput(nextTicker ?? '');
|
|
replaceTickerFilter(nextTicker);
|
|
}}
|
|
>
|
|
<Input
|
|
value={filterTickerInput}
|
|
onChange={(event) => setFilterTickerInput(event.target.value.toUpperCase())}
|
|
placeholder="Ticker filter"
|
|
className="w-full sm:max-w-xs"
|
|
/>
|
|
<Button type="submit" variant="secondary" className="w-full sm:w-auto">
|
|
<Search className="size-4" />
|
|
Apply
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
className="w-full sm:w-auto"
|
|
onClick={() => {
|
|
setFilterTickerInput('');
|
|
replaceTickerFilter(null);
|
|
}}
|
|
>
|
|
Clear
|
|
</Button>
|
|
</form>
|
|
</Panel>
|
|
</div>
|
|
|
|
<Panel
|
|
title="Filing Ledger"
|
|
subtitle={`${filings.length} records loaded${activeTickerFilter ? ` for ${activeTickerFilter}` : ''}. Values shown in ${selectedFinancialScaleLabel}.`}
|
|
variant="surface"
|
|
actions={(
|
|
<div className="flex w-full flex-wrap justify-start gap-2 sm:justify-end">
|
|
{FINANCIAL_VALUE_SCALE_OPTIONS.map((option) => (
|
|
<Button
|
|
key={option.value}
|
|
type="button"
|
|
variant={option.value === financialValueScale ? 'primary' : 'ghost'}
|
|
className="px-2 py-1 text-xs"
|
|
onClick={() => setFinancialValueScale(option.value)}
|
|
>
|
|
{option.label}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
)}
|
|
>
|
|
{actionError ? <p className="text-sm text-[#ffb5b5]">{actionError}</p> : null}
|
|
{filingsError ? <p className="text-sm text-[#ffb5b5]">{filingsError}</p> : null}
|
|
{actionNotice ? <p className="mt-2 text-sm text-[color:var(--accent)]">{actionNotice}</p> : null}
|
|
{loading ? (
|
|
<p className="text-sm text-[color:var(--terminal-muted)]">Fetching filings...</p>
|
|
) : filings.length === 0 ? (
|
|
<p className="text-sm text-[color:var(--terminal-muted)]">No filings available. Queue a sync job to ingest fresh SEC data.</p>
|
|
) : (
|
|
<div className="space-y-3">
|
|
<div className="space-y-3 lg:hidden">
|
|
{filings.map((filing) => {
|
|
const financialForm = hasFinancialSnapshot(filing);
|
|
const revenue = filing.metrics?.revenue;
|
|
const hasAnalysis = Boolean(filing.analysis?.text || filing.analysis?.legacyInsights);
|
|
const originalFilingUrl = resolveOriginalFilingUrl(filing);
|
|
|
|
return (
|
|
<article
|
|
key={filing.accession_number}
|
|
className="rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-4"
|
|
>
|
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
|
<div>
|
|
<p className="text-sm font-semibold text-[color:var(--terminal-bright)]">{filing.ticker} · {filing.filing_type}</p>
|
|
<p className="text-xs text-[color:var(--terminal-muted)]">{formatFilingDate(filing.filing_date)}</p>
|
|
</div>
|
|
<p className="text-xs text-[color:var(--terminal-muted)]">{hasAnalysis ? 'AI ready' : 'AI pending'}</p>
|
|
</div>
|
|
|
|
<p className="mt-2 text-sm text-[color:var(--terminal-bright)]">{filing.company_name}</p>
|
|
|
|
<dl className="mt-3 grid grid-cols-1 gap-2 text-xs sm:grid-cols-2">
|
|
<div className="rounded-md border border-[color:var(--line-weak)] px-2 py-1.5">
|
|
<dt className="text-[color:var(--terminal-muted)]">Financial Snapshot</dt>
|
|
<dd className="mt-1 text-[color:var(--terminal-bright)]">
|
|
{financialForm ? asScaledFinancialSnapshot(revenue, financialValueScale) : 'Qualitative filing'}
|
|
</dd>
|
|
</div>
|
|
<div className="rounded-md border border-[color:var(--line-weak)] px-2 py-1.5">
|
|
<dt className="text-[color:var(--terminal-muted)]">Accession</dt>
|
|
<dd className="mt-1 break-all text-[color:var(--terminal-bright)]">{filing.accession_number}</dd>
|
|
</div>
|
|
</dl>
|
|
|
|
<div className="mt-3 flex flex-wrap items-center gap-2">
|
|
{originalFilingUrl ? (
|
|
<FilingExternalLink href={originalFilingUrl} label="Original filing" />
|
|
) : (
|
|
<span className="text-xs text-[color:var(--terminal-muted)]">Original filing unavailable</span>
|
|
)}
|
|
{filing.submission_url ? (
|
|
<FilingExternalLink href={filing.submission_url} label="Submission" />
|
|
) : null}
|
|
<Button
|
|
variant="ghost"
|
|
onClick={() => void triggerAnalysis(filing.accession_number)}
|
|
className="px-2 py-1 text-xs"
|
|
>
|
|
<Bot className="size-3" />
|
|
Analyze
|
|
</Button>
|
|
<Button
|
|
variant="ghost"
|
|
onClick={() => void saveToLibrary(filing)}
|
|
className="px-2 py-1 text-xs"
|
|
>
|
|
<NotebookPen className="size-3" />
|
|
Save to library
|
|
</Button>
|
|
{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
|
|
</Link>
|
|
) : null}
|
|
</div>
|
|
</article>
|
|
);
|
|
})}
|
|
</div>
|
|
|
|
<div className="data-table-wrap hidden lg:block">
|
|
<table className="data-table w-full">
|
|
<thead>
|
|
<tr>
|
|
<th>Ticker</th>
|
|
<th>Type</th>
|
|
<th>Filed</th>
|
|
<th>Revenue Snapshot</th>
|
|
<th>Company</th>
|
|
<th>AI</th>
|
|
<th>Links</th>
|
|
<th>Action</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{filings.map((filing) => {
|
|
const financialForm = hasFinancialSnapshot(filing);
|
|
const revenue = filing.metrics?.revenue;
|
|
const hasAnalysis = Boolean(filing.analysis?.text || filing.analysis?.legacyInsights);
|
|
const originalFilingUrl = resolveOriginalFilingUrl(filing);
|
|
|
|
return (
|
|
<tr key={filing.accession_number}>
|
|
<td>
|
|
<div className="font-medium text-[color:var(--terminal-bright)]">{filing.ticker}</div>
|
|
<div className="text-xs text-[color:var(--terminal-muted)]">{groupedByTicker.get(filing.ticker)} filings</div>
|
|
</td>
|
|
<td>{filing.filing_type}</td>
|
|
<td>{formatFilingDate(filing.filing_date)}</td>
|
|
<td>{financialForm ? asScaledFinancialSnapshot(revenue, financialValueScale) : 'Qualitative filing'}</td>
|
|
<td className="max-w-[18rem]">{filing.company_name}</td>
|
|
<td>{hasAnalysis ? 'Ready' : 'Not generated'}</td>
|
|
<td>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
{originalFilingUrl ? (
|
|
<FilingExternalLink href={originalFilingUrl} label="Original" />
|
|
) : (
|
|
<span className="text-xs text-[color:var(--terminal-muted)]">Unavailable</span>
|
|
)}
|
|
{filing.submission_url ? (
|
|
<FilingExternalLink href={filing.submission_url} label="Submission" />
|
|
) : null}
|
|
</div>
|
|
</td>
|
|
<td>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<Button
|
|
variant="ghost"
|
|
onClick={() => void triggerAnalysis(filing.accession_number)}
|
|
className="px-2 py-1 text-xs"
|
|
>
|
|
<Bot className="size-3" />
|
|
Analyze
|
|
</Button>
|
|
<Button
|
|
variant="ghost"
|
|
onClick={() => void saveToLibrary(filing)}
|
|
className="px-2 py-1 text-xs"
|
|
>
|
|
<NotebookPen className="size-3" />
|
|
Journal
|
|
</Button>
|
|
{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
|
|
</Link>
|
|
) : null}
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</Panel>
|
|
</AppShell>
|
|
);
|
|
}
|