feat: rebuild fiscal clone architecture and harden coolify deployment
This commit is contained in:
@@ -1,224 +1,181 @@
|
||||
'use client';
|
||||
|
||||
import { useSession } from '@/lib/better-auth';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { ArrowRight, Eye, Plus, Trash2 } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
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 { deleteWatchlistItem, getTask, listWatchlist, queueFilingSync, upsertWatchlistItem } from '@/lib/api';
|
||||
import type { Task, WatchlistItem } from '@/lib/types';
|
||||
|
||||
type FormState = {
|
||||
ticker: string;
|
||||
companyName: string;
|
||||
sector: string;
|
||||
};
|
||||
|
||||
export default function WatchlistPage() {
|
||||
const { data: session, isPending } = useSession();
|
||||
const router = useRouter();
|
||||
const [watchlist, setWatchlist] = useState([]);
|
||||
const { isPending, isAuthenticated } = useAuthGuard();
|
||||
|
||||
const [items, setItems] = useState<WatchlistItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showAddModal, setShowAddModal] = useState(false);
|
||||
const [newStock, setNewStock] = useState({ ticker: '', company_name: '', sector: '' });
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [activeTask, setActiveTask] = useState<Task | null>(null);
|
||||
const [form, setForm] = useState<FormState>({ ticker: '', companyName: '', sector: '' });
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && !session) {
|
||||
router.push('/auth/signin');
|
||||
return;
|
||||
}
|
||||
const loadWatchlist = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
if (session?.user?.id) {
|
||||
fetchWatchlist(session.user.id);
|
||||
}
|
||||
}, [session, isPending, router]);
|
||||
|
||||
const fetchWatchlist = async (userId: string) => {
|
||||
try {
|
||||
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/watchlist/${userId}`);
|
||||
const data = await response.json();
|
||||
setWatchlist(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching watchlist:', error);
|
||||
const response = await listWatchlist();
|
||||
setItems(response.items);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load watchlist');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleAddStock = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const userId = session?.user?.id;
|
||||
if (!userId) return;
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
void loadWatchlist();
|
||||
}
|
||||
}, [isPending, isAuthenticated, loadWatchlist]);
|
||||
|
||||
const polledTask = useTaskPoller({
|
||||
taskId: activeTask?.id ?? null,
|
||||
onTerminalState: () => {
|
||||
setActiveTask(null);
|
||||
}
|
||||
});
|
||||
|
||||
const liveTask = polledTask ?? activeTask;
|
||||
|
||||
const submit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
try {
|
||||
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/watchlist`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
user_id: userId,
|
||||
ticker: newStock.ticker.toUpperCase(),
|
||||
company_name: newStock.company_name,
|
||||
sector: newStock.sector
|
||||
})
|
||||
await upsertWatchlistItem({
|
||||
ticker: form.ticker.toUpperCase(),
|
||||
companyName: form.companyName,
|
||||
sector: form.sector || undefined
|
||||
});
|
||||
|
||||
setShowAddModal(false);
|
||||
setNewStock({ ticker: '', company_name: '', sector: '' });
|
||||
fetchWatchlist(userId);
|
||||
} catch (error) {
|
||||
console.error('Error adding stock:', error);
|
||||
setForm({ ticker: '', companyName: '', sector: '' });
|
||||
await loadWatchlist();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save watchlist item');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteStock = async (id: number) => {
|
||||
if (!confirm('Are you sure you want to remove this stock from watchlist?')) return;
|
||||
const userId = session?.user?.id;
|
||||
if (!userId) return;
|
||||
|
||||
const queueSync = async (ticker: string) => {
|
||||
try {
|
||||
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/watchlist/${id}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
fetchWatchlist(userId);
|
||||
} catch (error) {
|
||||
console.error('Error deleting stock:', error);
|
||||
const { task } = await queueFilingSync({ ticker, limit: 20 });
|
||||
const latest = await getTask(task.id);
|
||||
setActiveTask(latest.task);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : `Failed to queue sync for ${ticker}`);
|
||||
}
|
||||
};
|
||||
|
||||
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>;
|
||||
if (isPending || !isAuthenticated) {
|
||||
return <div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Loading watchlist terminal...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 text-white">
|
||||
<nav className="border-b border-slate-700 bg-slate-900/50 backdrop-blur">
|
||||
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
|
||||
<Link href="/" className="text-2xl font-bold bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">
|
||||
Fiscal Clone
|
||||
</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="Watchlist"
|
||||
subtitle="Track symbols, company context, and trigger filing ingestion jobs from one surface."
|
||||
>
|
||||
{liveTask ? (
|
||||
<Panel title="Queue Status">
|
||||
<div className="flex items-center justify-between 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.task_type}</p>
|
||||
<StatusPill status={liveTask.status} />
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</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">Watchlist</h1>
|
||||
<button
|
||||
onClick={() => setShowAddModal(true)}
|
||||
className="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition"
|
||||
>
|
||||
+ Add Stock
|
||||
</button>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.6fr_1fr]">
|
||||
<Panel title="Symbols" subtitle="Your monitored universe.">
|
||||
{error ? <p className="text-sm text-[#ffb5b5]">{error}</p> : null}
|
||||
{loading ? (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">Loading watchlist...</p>
|
||||
) : items.length === 0 ? (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">No symbols yet. Add one from the right panel.</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
{items.map((item) => (
|
||||
<article key={item.id} className="rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">{item.sector ?? 'Unclassified'}</p>
|
||||
<h3 className="mt-1 text-xl font-semibold text-[color:var(--terminal-bright)]">{item.ticker}</h3>
|
||||
<p className="mt-1 text-sm text-[color:var(--terminal-muted)]">{item.company_name}</p>
|
||||
</div>
|
||||
<Eye className="size-4 text-[color:var(--accent)]" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{watchlist.map((stock: any) => (
|
||||
<div key={stock.id} className="bg-slate-800/50 rounded-lg p-6 border border-slate-700 hover:border-slate-600 transition">
|
||||
<div className="flex justify-between items-start mb-4">
|
||||
<div>
|
||||
<h3 className="text-2xl font-bold">{stock.ticker}</h3>
|
||||
<p className="text-slate-400">{stock.company_name}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleDeleteStock(stock.id)}
|
||||
className="text-red-400 hover:text-red-300 transition"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
{stock.sector && (
|
||||
<div className="inline-block bg-purple-500/20 text-purple-400 px-3 py-1 rounded-full text-sm">
|
||||
{stock.sector}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 flex gap-2">
|
||||
<Link
|
||||
href={`/filings?ticker=${stock.ticker}`}
|
||||
className="flex-1 bg-slate-700 hover:bg-slate-600 text-white py-2 rounded-lg text-center transition"
|
||||
>
|
||||
Filings
|
||||
</Link>
|
||||
<Link
|
||||
href={`/portfolio/add?ticker=${stock.ticker}`}
|
||||
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg text-center transition"
|
||||
>
|
||||
Add to Portfolio
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{watchlist.length === 0 && (
|
||||
<div className="col-span-full text-center py-12 bg-slate-800/50 rounded-lg border border-slate-700">
|
||||
<p className="text-slate-400 text-lg mb-4">Your watchlist is empty</p>
|
||||
<p className="text-slate-500 text-sm">
|
||||
Add stocks to track their SEC filings and monitor performance
|
||||
</p>
|
||||
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||
<Button variant="secondary" className="px-2 py-1 text-xs" onClick={() => void queueSync(item.ticker)}>
|
||||
Sync filings
|
||||
</Button>
|
||||
<Link
|
||||
href={`/filings?ticker=${item.ticker}`}
|
||||
className="inline-flex items-center gap-1 text-xs text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
|
||||
>
|
||||
Open stream
|
||||
<ArrowRight className="size-3" />
|
||||
</Link>
|
||||
<Button
|
||||
variant="danger"
|
||||
className="ml-auto px-2 py-1 text-xs"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await deleteWatchlistItem(item.id);
|
||||
await loadWatchlist();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to remove symbol');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Trash2 className="size-3" />
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</Panel>
|
||||
|
||||
{showAddModal && (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4">
|
||||
<div className="bg-slate-800 rounded-lg p-6 border border-slate-700 max-w-md w-full">
|
||||
<h2 className="text-2xl font-bold mb-4">Add to Watchlist</h2>
|
||||
<form onSubmit={handleAddStock} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-2">Ticker</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newStock.ticker}
|
||||
onChange={(e) => setNewStock({...newStock, ticker: e.target.value})}
|
||||
className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
|
||||
placeholder="AAPL"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-2">Company Name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newStock.company_name}
|
||||
onChange={(e) => setNewStock({...newStock, company_name: e.target.value})}
|
||||
className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
|
||||
placeholder="Apple Inc."
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-2">Sector (Optional)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newStock.sector}
|
||||
onChange={(e) => setNewStock({...newStock, sector: e.target.value})}
|
||||
className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
|
||||
placeholder="Technology"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<button
|
||||
type="submit"
|
||||
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg transition"
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAddModal(false)}
|
||||
className="flex-1 bg-slate-700 hover:bg-slate-600 text-white py-3 rounded-lg transition"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Panel title="Add Symbol" subtitle="Create or update a watchlist item.">
|
||||
<form onSubmit={submit} className="space-y-3">
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Ticker</label>
|
||||
<Input value={form.ticker} onChange={(event) => setForm((prev) => ({ ...prev, ticker: event.target.value.toUpperCase() }))} required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Company Name</label>
|
||||
<Input value={form.companyName} onChange={(event) => setForm((prev) => ({ ...prev, companyName: event.target.value }))} required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Sector</label>
|
||||
<Input value={form.sector} onChange={(event) => setForm((prev) => ({ ...prev, sector: event.target.value }))} />
|
||||
</div>
|
||||
<Button type="submit" className="w-full">
|
||||
<Plus className="size-4" />
|
||||
Save symbol
|
||||
</Button>
|
||||
</form>
|
||||
</Panel>
|
||||
</div>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user