feat: rebuild fiscal clone architecture and harden coolify deployment
This commit is contained in:
@@ -1,185 +1,251 @@
|
||||
'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 { format } from 'date-fns';
|
||||
import { Bot, Download, Search, TimerReset } from 'lucide-react';
|
||||
import { 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 { StatusPill } from '@/components/ui/status-pill';
|
||||
import { useAuthGuard } from '@/hooks/use-auth-guard';
|
||||
import { useTaskPoller } from '@/hooks/use-task-poller';
|
||||
import { getTask, listFilings, queueFilingAnalysis, queueFilingSync } from '@/lib/api';
|
||||
import type { Filing, Task } from '@/lib/types';
|
||||
import { formatCompactCurrency } from '@/lib/format';
|
||||
|
||||
export default function FilingsPage() {
|
||||
const { data: session, isPending } = useSession();
|
||||
const router = useRouter();
|
||||
const [filings, setFilings] = useState([]);
|
||||
const { isPending, isAuthenticated } = useAuthGuard();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const [filings, setFilings] = useState<Filing[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [syncTickerInput, setSyncTickerInput] = useState('');
|
||||
const [filterTickerInput, setFilterTickerInput] = useState('');
|
||||
const [searchTicker, setSearchTicker] = useState('');
|
||||
const [activeTask, setActiveTask] = useState<Task | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && !session) {
|
||||
router.push('/auth/signin');
|
||||
return;
|
||||
const ticker = searchParams.get('ticker');
|
||||
if (ticker) {
|
||||
const normalized = ticker.toUpperCase();
|
||||
setSyncTickerInput(normalized);
|
||||
setFilterTickerInput(normalized);
|
||||
setSearchTicker(normalized);
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
if (session?.user) {
|
||||
fetchFilings();
|
||||
}
|
||||
}, [session, isPending, router]);
|
||||
|
||||
const fetchFilings = async (ticker?: string) => {
|
||||
const loadFilings = useCallback(async (ticker?: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const url = ticker
|
||||
? `${process.env.NEXT_PUBLIC_API_URL}/api/filings/${ticker}`
|
||||
: `${process.env.NEXT_PUBLIC_API_URL}/api/filings`;
|
||||
setError(null);
|
||||
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
setFilings(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching filings:', error);
|
||||
try {
|
||||
const response = await listFilings({ ticker, limit: 120 });
|
||||
setFilings(response.filings);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unable to fetch filings');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleSearch = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
fetchFilings(searchTicker || undefined);
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
void loadFilings(searchTicker || undefined);
|
||||
}
|
||||
}, [isPending, isAuthenticated, searchTicker, loadFilings]);
|
||||
|
||||
const polledTask = useTaskPoller({
|
||||
taskId: activeTask?.id ?? null,
|
||||
onTerminalState: async () => {
|
||||
setActiveTask(null);
|
||||
await loadFilings(searchTicker || undefined);
|
||||
}
|
||||
});
|
||||
|
||||
const liveTask = polledTask ?? activeTask;
|
||||
|
||||
const triggerSync = async () => {
|
||||
if (!syncTickerInput.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleRefresh = async (ticker: string) => {
|
||||
try {
|
||||
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/filings/refresh/${ticker}`, {
|
||||
method: 'POST'
|
||||
});
|
||||
fetchFilings(ticker);
|
||||
} catch (error) {
|
||||
console.error('Error refreshing filings:', error);
|
||||
const { task } = await queueFilingSync({ ticker: syncTickerInput.trim().toUpperCase(), limit: 20 });
|
||||
const latest = await getTask(task.id);
|
||||
setActiveTask(latest.task);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to queue filing sync');
|
||||
}
|
||||
};
|
||||
|
||||
const getFilingTypeColor = (type: string) => {
|
||||
switch (type) {
|
||||
case '10-K': return 'bg-blue-500/20 text-blue-400 border-blue-500/30';
|
||||
case '10-Q': return 'bg-green-500/20 text-green-400 border-green-500/30';
|
||||
case '8-K': return 'bg-purple-500/20 text-purple-400 border-purple-500/30';
|
||||
default: return 'bg-slate-500/20 text-slate-400 border-slate-500/30';
|
||||
const triggerAnalysis = async (accessionNumber: string) => {
|
||||
try {
|
||||
const { task } = await queueFilingAnalysis(accessionNumber);
|
||||
const latest = await getTask(task.id);
|
||||
setActiveTask(latest.task);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to queue filing analysis');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 flex items-center justify-center">Loading...</div>;
|
||||
const 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]);
|
||||
|
||||
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 (
|
||||
<div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 text-white">
|
||||
<nav className="border-b border-slate-700 bg-slate-900/50 backdrop-blur">
|
||||
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
|
||||
<Link href="/" className="text-2xl font-bold bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">
|
||||
Fiscal Clone
|
||||
</Link>
|
||||
<div className="flex gap-4">
|
||||
<Link href="/filings" className="hover:text-blue-400 transition">
|
||||
Filings
|
||||
</Link>
|
||||
<Link href="/portfolio" className="hover:text-blue-400 transition">
|
||||
Portfolio
|
||||
</Link>
|
||||
<Link href="/watchlist" className="hover:text-blue-400 transition">
|
||||
Watchlist
|
||||
</Link>
|
||||
<AppShell
|
||||
title="Filings Stream"
|
||||
subtitle="Sync SEC submissions and generate AI red-flag analysis asynchronously."
|
||||
actions={(
|
||||
<Button variant="secondary" onClick={() => void loadFilings(searchTicker || undefined)}>
|
||||
<TimerReset className="size-4" />
|
||||
Refresh table
|
||||
</Button>
|
||||
)}
|
||||
>
|
||||
{liveTask ? (
|
||||
<Panel title="Active Task" subtitle={`${liveTask.task_type} is processing in worker.`}>
|
||||
<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)]">{liveTask.id}</p>
|
||||
<StatusPill status={liveTask.status} />
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
{liveTask.error ? <p className="mt-2 text-sm text-[#ff9898]">{liveTask.error}</p> : null}
|
||||
</Panel>
|
||||
) : null}
|
||||
|
||||
<main className="container mx-auto px-4 py-8">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h1 className="text-3xl font-bold">SEC Filings</h1>
|
||||
<Link
|
||||
href="/watchlist/add"
|
||||
className="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition"
|
||||
<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-wrap items-center gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void triggerSync();
|
||||
}}
|
||||
>
|
||||
+ Add to Watchlist
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700 mb-8">
|
||||
<form onSubmit={handleSearch} className="flex gap-4">
|
||||
<input
|
||||
type="text"
|
||||
value={searchTicker}
|
||||
onChange={(e) => setSearchTicker(e.target.value)}
|
||||
className="flex-1 bg-slate-700/50 border border-slate-600 rounded-lg px-4 py-3 text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="Search by ticker (e.g., AAPL)"
|
||||
<Input
|
||||
value={syncTickerInput}
|
||||
onChange={(event) => setSyncTickerInput(event.target.value.toUpperCase())}
|
||||
placeholder="Ticker (AAPL)"
|
||||
className="max-w-xs"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="bg-blue-600 hover:bg-blue-700 px-6 py-3 rounded-lg transition"
|
||||
>
|
||||
Search
|
||||
</button>
|
||||
<button
|
||||
<Button type="submit">
|
||||
<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-wrap items-center gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
setSearchTicker(filterTickerInput.trim().toUpperCase());
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
value={filterTickerInput}
|
||||
onChange={(event) => setFilterTickerInput(event.target.value.toUpperCase())}
|
||||
placeholder="Ticker filter"
|
||||
className="max-w-xs"
|
||||
/>
|
||||
<Button type="submit" variant="secondary">
|
||||
<Search className="size-4" />
|
||||
Apply
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => { setSearchTicker(''); fetchFilings(); }}
|
||||
className="bg-slate-700 hover:bg-slate-600 px-6 py-3 rounded-lg transition"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setFilterTickerInput('');
|
||||
setSearchTicker('');
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
<div className="bg-slate-800/50 rounded-lg border border-slate-700 overflow-hidden">
|
||||
{filings.length > 0 ? (
|
||||
<table className="w-full">
|
||||
<thead className="bg-slate-700/50">
|
||||
<Panel title="Filing Ledger" subtitle={`${filings.length} records loaded${searchTicker ? ` for ${searchTicker}` : ''}.`}>
|
||||
{error ? <p className="text-sm text-[#ffb5b5]">{error}</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="overflow-x-auto">
|
||||
<table className="data-table min-w-[980px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Ticker</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Company</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Type</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Filing Date</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Actions</th>
|
||||
<th>Ticker</th>
|
||||
<th>Type</th>
|
||||
<th>Filed</th>
|
||||
<th>Revenue Snapshot</th>
|
||||
<th>Company</th>
|
||||
<th>AI</th>
|
||||
<th>Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filings.map((filing: any) => (
|
||||
<tr key={filing.id} className="border-t border-slate-700 hover:bg-slate-700/30 transition">
|
||||
<td className="px-6 py-4 font-semibold">{filing.ticker}</td>
|
||||
<td className="px-6 py-4">{filing.company_name}</td>
|
||||
<td className="px-6 py-4">
|
||||
<span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getFilingTypeColor(filing.filing_type)}`}>
|
||||
{filing.filing_type}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
{format(new Date(filing.filing_date), 'MMM dd, yyyy')}
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<button
|
||||
onClick={() => window.open(`https://www.sec.gov/Archives/${filing.accession_number.replace(/-/g, '')}/${filing.accession_number}-index.htm`, '_blank')}
|
||||
className="text-blue-400 hover:text-blue-300 transition mr-4"
|
||||
>
|
||||
View on SEC
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleRefresh(filing.ticker)}
|
||||
className="text-green-400 hover:text-green-300 transition"
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{filings.map((filing) => {
|
||||
const revenue = filing.metrics?.revenue;
|
||||
const hasAnalysis = Boolean(filing.analysis?.text || filing.analysis?.legacyInsights);
|
||||
|
||||
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>{format(new Date(filing.filing_date), 'MMM dd, yyyy')}</td>
|
||||
<td>{revenue ? formatCompactCurrency(revenue) : 'n/a'}</td>
|
||||
<td>{filing.company_name}</td>
|
||||
<td>{hasAnalysis ? 'Ready' : 'Not generated'}</td>
|
||||
<td>
|
||||
<div className="flex items-center gap-2">
|
||||
{filing.filing_url ? (
|
||||
<a
|
||||
href={filing.filing_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-xs text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
SEC
|
||||
</a>
|
||||
) : null}
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => void triggerAnalysis(filing.accession_number)}
|
||||
className="px-2 py-1 text-xs"
|
||||
>
|
||||
<Bot className="size-3" />
|
||||
Analyze
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-slate-400 text-lg mb-4">No filings found</p>
|
||||
<p className="text-slate-500 text-sm">
|
||||
Add stocks to your watchlist to track their SEC filings
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user