flatten app to repo root and update docker deployment for single-stack runtime
This commit is contained in:
26
app/api/filings/[accessionNumber]/analyze/route.ts
Normal file
26
app/api/filings/[accessionNumber]/analyze/route.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { enqueueTask } from '@/lib/server/tasks';
|
||||
|
||||
type Context = {
|
||||
params: Promise<{ accessionNumber: string }>;
|
||||
};
|
||||
|
||||
export async function POST(_request: Request, context: Context) {
|
||||
try {
|
||||
const { accessionNumber } = await context.params;
|
||||
|
||||
if (!accessionNumber || accessionNumber.trim().length < 4) {
|
||||
return jsonError('Invalid accession number');
|
||||
}
|
||||
|
||||
const task = await enqueueTask({
|
||||
taskType: 'analyze_filing',
|
||||
payload: { accessionNumber: accessionNumber.trim() },
|
||||
priority: 65
|
||||
});
|
||||
|
||||
return Response.json({ task });
|
||||
} catch (error) {
|
||||
return jsonError(asErrorMessage(error, 'Failed to queue filing analysis task'));
|
||||
}
|
||||
}
|
||||
22
app/api/filings/route.ts
Normal file
22
app/api/filings/route.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { getStoreSnapshot } from '@/lib/server/store';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const url = new URL(request.url);
|
||||
const tickerFilter = url.searchParams.get('ticker')?.trim().toUpperCase();
|
||||
const limitValue = Number(url.searchParams.get('limit') ?? 50);
|
||||
const limit = Number.isFinite(limitValue)
|
||||
? Math.min(Math.max(Math.trunc(limitValue), 1), 250)
|
||||
: 50;
|
||||
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const filtered = tickerFilter
|
||||
? snapshot.filings.filter((filing) => filing.ticker === tickerFilter)
|
||||
: snapshot.filings;
|
||||
|
||||
const filings = filtered
|
||||
.slice()
|
||||
.sort((a, b) => Date.parse(b.filing_date) - Date.parse(a.filing_date))
|
||||
.slice(0, limit);
|
||||
|
||||
return Response.json({ filings });
|
||||
}
|
||||
28
app/api/filings/sync/route.ts
Normal file
28
app/api/filings/sync/route.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { enqueueTask } from '@/lib/server/tasks';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const payload = await request.json() as {
|
||||
ticker?: string;
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
if (!payload.ticker || payload.ticker.trim().length < 1) {
|
||||
return jsonError('ticker is required');
|
||||
}
|
||||
|
||||
const task = await enqueueTask({
|
||||
taskType: 'sync_filings',
|
||||
payload: {
|
||||
ticker: payload.ticker.trim().toUpperCase(),
|
||||
limit: payload.limit ?? 20
|
||||
},
|
||||
priority: 90
|
||||
});
|
||||
|
||||
return Response.json({ task });
|
||||
} catch (error) {
|
||||
return jsonError(asErrorMessage(error, 'Failed to queue filings sync task'));
|
||||
}
|
||||
}
|
||||
16
app/api/health/route.ts
Normal file
16
app/api/health/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { getStoreSnapshot } from '@/lib/server/store';
|
||||
|
||||
export async function GET() {
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const queue = snapshot.tasks.reduce<Record<string, number>>((acc, task) => {
|
||||
acc[task.status] = (acc[task.status] ?? 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
return Response.json({
|
||||
status: 'ok',
|
||||
version: '3.0.0',
|
||||
timestamp: new Date().toISOString(),
|
||||
queue
|
||||
});
|
||||
}
|
||||
10
app/api/me/route.ts
Normal file
10
app/api/me/route.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
export async function GET() {
|
||||
return Response.json({
|
||||
user: {
|
||||
id: 1,
|
||||
email: 'operator@local.fiscal',
|
||||
name: 'Local Operator',
|
||||
image: null
|
||||
}
|
||||
});
|
||||
}
|
||||
89
app/api/portfolio/holdings/[id]/route.ts
Normal file
89
app/api/portfolio/holdings/[id]/route.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { jsonError } from '@/lib/server/http';
|
||||
import { recalculateHolding } from '@/lib/server/portfolio';
|
||||
import { withStore } from '@/lib/server/store';
|
||||
|
||||
type Context = {
|
||||
params: Promise<{ id: string }>;
|
||||
};
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function asPositiveNumber(value: unknown) {
|
||||
const parsed = typeof value === 'number' ? value : Number(value);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request, context: Context) {
|
||||
const { id } = await context.params;
|
||||
const numericId = Number(id);
|
||||
|
||||
if (!Number.isInteger(numericId) || numericId <= 0) {
|
||||
return jsonError('Invalid holding id');
|
||||
}
|
||||
|
||||
const payload = await request.json() as {
|
||||
shares?: number;
|
||||
avgCost?: number;
|
||||
currentPrice?: number;
|
||||
};
|
||||
|
||||
let found = false;
|
||||
let updated: unknown = null;
|
||||
|
||||
await withStore((store) => {
|
||||
const index = store.holdings.findIndex((entry) => entry.id === numericId);
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
found = true;
|
||||
const existing = store.holdings[index];
|
||||
|
||||
const shares = asPositiveNumber(payload.shares) ?? Number(existing.shares);
|
||||
const avgCost = asPositiveNumber(payload.avgCost) ?? Number(existing.avg_cost);
|
||||
const currentPrice = asPositiveNumber(payload.currentPrice) ?? Number(existing.current_price ?? existing.avg_cost);
|
||||
|
||||
const next = recalculateHolding({
|
||||
...existing,
|
||||
shares: shares.toFixed(6),
|
||||
avg_cost: avgCost.toFixed(6),
|
||||
current_price: currentPrice.toFixed(6),
|
||||
updated_at: nowIso(),
|
||||
last_price_at: nowIso()
|
||||
});
|
||||
|
||||
store.holdings[index] = next;
|
||||
updated = next;
|
||||
});
|
||||
|
||||
if (!found) {
|
||||
return jsonError('Holding not found', 404);
|
||||
}
|
||||
|
||||
return Response.json({ holding: updated });
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, context: Context) {
|
||||
const { id } = await context.params;
|
||||
const numericId = Number(id);
|
||||
|
||||
if (!Number.isInteger(numericId) || numericId <= 0) {
|
||||
return jsonError('Invalid holding id');
|
||||
}
|
||||
|
||||
let removed = false;
|
||||
|
||||
await withStore((store) => {
|
||||
const next = store.holdings.filter((holding) => holding.id !== numericId);
|
||||
removed = next.length !== store.holdings.length;
|
||||
store.holdings = next;
|
||||
});
|
||||
|
||||
if (!removed) {
|
||||
return jsonError('Holding not found', 404);
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
97
app/api/portfolio/holdings/route.ts
Normal file
97
app/api/portfolio/holdings/route.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import type { Holding } from '@/lib/types';
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { recalculateHolding } from '@/lib/server/portfolio';
|
||||
import { getStoreSnapshot, withStore } from '@/lib/server/store';
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function asPositiveNumber(value: unknown) {
|
||||
const parsed = typeof value === 'number' ? value : Number(value);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const holdings = snapshot.holdings
|
||||
.slice()
|
||||
.sort((a, b) => Number(b.market_value) - Number(a.market_value));
|
||||
|
||||
return Response.json({ holdings });
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const payload = await request.json() as {
|
||||
ticker?: string;
|
||||
shares?: number;
|
||||
avgCost?: number;
|
||||
currentPrice?: number;
|
||||
};
|
||||
|
||||
if (!payload.ticker || payload.ticker.trim().length < 1) {
|
||||
return jsonError('ticker is required');
|
||||
}
|
||||
|
||||
const shares = asPositiveNumber(payload.shares);
|
||||
const avgCost = asPositiveNumber(payload.avgCost);
|
||||
|
||||
if (shares === null) {
|
||||
return jsonError('shares must be a positive number');
|
||||
}
|
||||
|
||||
if (avgCost === null) {
|
||||
return jsonError('avgCost must be a positive number');
|
||||
}
|
||||
|
||||
const ticker = payload.ticker.trim().toUpperCase();
|
||||
const now = nowIso();
|
||||
let holding: Holding | null = null;
|
||||
|
||||
await withStore((store) => {
|
||||
const existingIndex = store.holdings.findIndex((entry) => entry.ticker === ticker);
|
||||
const currentPrice = asPositiveNumber(payload.currentPrice) ?? avgCost;
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
const existing = store.holdings[existingIndex];
|
||||
const updated = recalculateHolding({
|
||||
...existing,
|
||||
ticker,
|
||||
shares: shares.toFixed(6),
|
||||
avg_cost: avgCost.toFixed(6),
|
||||
current_price: currentPrice.toFixed(6),
|
||||
updated_at: now,
|
||||
last_price_at: now
|
||||
});
|
||||
|
||||
store.holdings[existingIndex] = updated;
|
||||
holding = updated;
|
||||
return;
|
||||
}
|
||||
|
||||
store.counters.holdings += 1;
|
||||
const created = recalculateHolding({
|
||||
id: store.counters.holdings,
|
||||
user_id: 1,
|
||||
ticker,
|
||||
shares: shares.toFixed(6),
|
||||
avg_cost: avgCost.toFixed(6),
|
||||
current_price: currentPrice.toFixed(6),
|
||||
market_value: '0',
|
||||
gain_loss: '0',
|
||||
gain_loss_pct: '0',
|
||||
last_price_at: now,
|
||||
created_at: now,
|
||||
updated_at: now
|
||||
});
|
||||
|
||||
store.holdings.unshift(created);
|
||||
holding = created;
|
||||
});
|
||||
|
||||
return Response.json({ holding });
|
||||
} catch (error) {
|
||||
return jsonError(asErrorMessage(error, 'Failed to save holding'));
|
||||
}
|
||||
}
|
||||
16
app/api/portfolio/insights/generate/route.ts
Normal file
16
app/api/portfolio/insights/generate/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { enqueueTask } from '@/lib/server/tasks';
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
const task = await enqueueTask({
|
||||
taskType: 'portfolio_insights',
|
||||
payload: {},
|
||||
priority: 70
|
||||
});
|
||||
|
||||
return Response.json({ task });
|
||||
} catch (error) {
|
||||
return jsonError(asErrorMessage(error, 'Failed to queue insights task'));
|
||||
}
|
||||
}
|
||||
10
app/api/portfolio/insights/latest/route.ts
Normal file
10
app/api/portfolio/insights/latest/route.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { getStoreSnapshot } from '@/lib/server/store';
|
||||
|
||||
export async function GET() {
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const insight = snapshot.insights
|
||||
.slice()
|
||||
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at))[0] ?? null;
|
||||
|
||||
return Response.json({ insight });
|
||||
}
|
||||
16
app/api/portfolio/refresh-prices/route.ts
Normal file
16
app/api/portfolio/refresh-prices/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { enqueueTask } from '@/lib/server/tasks';
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
const task = await enqueueTask({
|
||||
taskType: 'refresh_prices',
|
||||
payload: {},
|
||||
priority: 80
|
||||
});
|
||||
|
||||
return Response.json({ task });
|
||||
} catch (error) {
|
||||
return jsonError(asErrorMessage(error, 'Failed to queue refresh task'));
|
||||
}
|
||||
}
|
||||
8
app/api/portfolio/summary/route.ts
Normal file
8
app/api/portfolio/summary/route.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { buildPortfolioSummary } from '@/lib/server/portfolio';
|
||||
import { getStoreSnapshot } from '@/lib/server/store';
|
||||
|
||||
export async function GET() {
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const summary = buildPortfolioSummary(snapshot.holdings);
|
||||
return Response.json({ summary });
|
||||
}
|
||||
17
app/api/tasks/[taskId]/route.ts
Normal file
17
app/api/tasks/[taskId]/route.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { jsonError } from '@/lib/server/http';
|
||||
import { getTaskById } from '@/lib/server/tasks';
|
||||
|
||||
type Context = {
|
||||
params: Promise<{ taskId: string }>;
|
||||
};
|
||||
|
||||
export async function GET(_request: Request, context: Context) {
|
||||
const { taskId } = await context.params;
|
||||
const task = await getTaskById(taskId);
|
||||
|
||||
if (!task) {
|
||||
return jsonError('Task not found', 404);
|
||||
}
|
||||
|
||||
return Response.json({ task });
|
||||
}
|
||||
20
app/api/tasks/route.ts
Normal file
20
app/api/tasks/route.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { TaskStatus } from '@/lib/types';
|
||||
import { listRecentTasks } from '@/lib/server/tasks';
|
||||
|
||||
const ALLOWED_STATUSES: TaskStatus[] = ['queued', 'running', 'completed', 'failed'];
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const url = new URL(request.url);
|
||||
const limitValue = Number(url.searchParams.get('limit') ?? 20);
|
||||
const limit = Number.isFinite(limitValue)
|
||||
? Math.min(Math.max(Math.trunc(limitValue), 1), 200)
|
||||
: 20;
|
||||
|
||||
const rawStatuses = url.searchParams.getAll('status');
|
||||
const statuses = rawStatuses.filter((status): status is TaskStatus => {
|
||||
return ALLOWED_STATUSES.includes(status as TaskStatus);
|
||||
});
|
||||
|
||||
const tasks = await listRecentTasks(limit, statuses.length > 0 ? statuses : undefined);
|
||||
return Response.json({ tasks });
|
||||
}
|
||||
29
app/api/watchlist/[id]/route.ts
Normal file
29
app/api/watchlist/[id]/route.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { jsonError } from '@/lib/server/http';
|
||||
import { withStore } from '@/lib/server/store';
|
||||
|
||||
type Context = {
|
||||
params: Promise<{ id: string }>;
|
||||
};
|
||||
|
||||
export async function DELETE(_request: Request, context: Context) {
|
||||
const { id } = await context.params;
|
||||
const numericId = Number(id);
|
||||
|
||||
if (!Number.isInteger(numericId) || numericId <= 0) {
|
||||
return jsonError('Invalid watchlist id', 400);
|
||||
}
|
||||
|
||||
let removed = false;
|
||||
|
||||
await withStore((store) => {
|
||||
const next = store.watchlist.filter((item) => item.id !== numericId);
|
||||
removed = next.length !== store.watchlist.length;
|
||||
store.watchlist = next;
|
||||
});
|
||||
|
||||
if (!removed) {
|
||||
return jsonError('Watchlist item not found', 404);
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
71
app/api/watchlist/route.ts
Normal file
71
app/api/watchlist/route.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { WatchlistItem } from '@/lib/types';
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { getStoreSnapshot, withStore } from '@/lib/server/store';
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const items = snapshot.watchlist
|
||||
.slice()
|
||||
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));
|
||||
|
||||
return Response.json({ items });
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const payload = await request.json() as {
|
||||
ticker?: string;
|
||||
companyName?: string;
|
||||
sector?: string;
|
||||
};
|
||||
|
||||
if (!payload.ticker || payload.ticker.trim().length < 1) {
|
||||
return jsonError('ticker is required');
|
||||
}
|
||||
|
||||
if (!payload.companyName || payload.companyName.trim().length < 1) {
|
||||
return jsonError('companyName is required');
|
||||
}
|
||||
|
||||
let item: WatchlistItem | null = null;
|
||||
|
||||
await withStore((store) => {
|
||||
const ticker = payload.ticker!.trim().toUpperCase();
|
||||
const existingIndex = store.watchlist.findIndex((entry) => entry.ticker === ticker);
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
const existing = store.watchlist[existingIndex];
|
||||
const updated: WatchlistItem = {
|
||||
...existing,
|
||||
company_name: payload.companyName!.trim(),
|
||||
sector: payload.sector?.trim() || null
|
||||
};
|
||||
|
||||
store.watchlist[existingIndex] = updated;
|
||||
item = updated;
|
||||
return;
|
||||
}
|
||||
|
||||
store.counters.watchlist += 1;
|
||||
const created: WatchlistItem = {
|
||||
id: store.counters.watchlist,
|
||||
user_id: 1,
|
||||
ticker,
|
||||
company_name: payload.companyName!.trim(),
|
||||
sector: payload.sector?.trim() || null,
|
||||
created_at: nowIso()
|
||||
};
|
||||
|
||||
store.watchlist.unshift(created);
|
||||
item = created;
|
||||
});
|
||||
|
||||
return Response.json({ item });
|
||||
} catch (error) {
|
||||
return jsonError(asErrorMessage(error, 'Failed to create watchlist item'));
|
||||
}
|
||||
}
|
||||
32
app/auth/signin/page.tsx
Normal file
32
app/auth/signin/page.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { AuthShell } from '@/components/auth/auth-shell';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export default function SignInPage() {
|
||||
return (
|
||||
<AuthShell
|
||||
title="Local Runtime Mode"
|
||||
subtitle="Authentication is disabled in this rebuilt local-first environment."
|
||||
footer={(
|
||||
<>
|
||||
Need multi-user auth later?{' '}
|
||||
<Link href="/" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
|
||||
Open command center
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">
|
||||
Continue directly into the fiscal terminal. API routes are same-origin and task execution is fully local with OpenClaw support.
|
||||
</p>
|
||||
|
||||
<Link href="/" className="mt-6 block">
|
||||
<Button type="button" className="w-full">
|
||||
Enter terminal
|
||||
</Button>
|
||||
</Link>
|
||||
</AuthShell>
|
||||
);
|
||||
}
|
||||
32
app/auth/signup/page.tsx
Normal file
32
app/auth/signup/page.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { AuthShell } from '@/components/auth/auth-shell';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export default function SignUpPage() {
|
||||
return (
|
||||
<AuthShell
|
||||
title="Workspace Provisioned"
|
||||
subtitle="This clone now runs in local-operator mode and does not require account creation."
|
||||
footer={(
|
||||
<>
|
||||
Already set?{' '}
|
||||
<Link href="/" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
|
||||
Launch dashboard
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">
|
||||
For production deployment you can reintroduce full multi-user authentication, but this rebuild is intentionally self-contained for fast iteration.
|
||||
</p>
|
||||
|
||||
<Link href="/" className="mt-6 block">
|
||||
<Button type="button" className="w-full">
|
||||
Open fiscal desk
|
||||
</Button>
|
||||
</Link>
|
||||
</AuthShell>
|
||||
);
|
||||
}
|
||||
260
app/filings/page.tsx
Normal file
260
app/filings/page.tsx
Normal file
@@ -0,0 +1,260 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Suspense } 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() {
|
||||
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 FilingsPageContent() {
|
||||
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(() => {
|
||||
const ticker = searchParams.get('ticker');
|
||||
if (ticker) {
|
||||
const normalized = ticker.toUpperCase();
|
||||
setSyncTickerInput(normalized);
|
||||
setFilterTickerInput(normalized);
|
||||
setSearchTicker(normalized);
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
const loadFilings = useCallback(async (ticker?: string) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
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);
|
||||
}
|
||||
}, []);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
try {
|
||||
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 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');
|
||||
}
|
||||
};
|
||||
|
||||
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 (
|
||||
<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 the task engine.`}>
|
||||
<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>
|
||||
{liveTask.error ? <p className="mt-2 text-sm text-[#ff9898]">{liveTask.error}</p> : null}
|
||||
</Panel>
|
||||
) : null}
|
||||
|
||||
<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();
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
value={syncTickerInput}
|
||||
onChange={(event) => setSyncTickerInput(event.target.value.toUpperCase())}
|
||||
placeholder="Ticker (AAPL)"
|
||||
className="max-w-xs"
|
||||
/>
|
||||
<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"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setFilterTickerInput('');
|
||||
setSearchTicker('');
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</form>
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
<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>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) => {
|
||||
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>
|
||||
)}
|
||||
</Panel>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
127
app/globals.css
Normal file
127
app/globals.css
Normal file
@@ -0,0 +1,127 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
--font-display: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
|
||||
--font-mono: "Menlo", "SFMono-Regular", "Consolas", "Liberation Mono", monospace;
|
||||
--bg-0: #05080d;
|
||||
--bg-1: #08121a;
|
||||
--bg-2: #0b1f28;
|
||||
--panel: rgba(6, 17, 24, 0.8);
|
||||
--panel-soft: rgba(7, 22, 31, 0.62);
|
||||
--panel-bright: rgba(10, 33, 45, 0.9);
|
||||
--line-weak: rgba(126, 217, 255, 0.22);
|
||||
--line-strong: rgba(123, 255, 217, 0.75);
|
||||
--accent: #68ffd5;
|
||||
--accent-strong: #8cffeb;
|
||||
--danger: #ff7070;
|
||||
--danger-soft: rgba(122, 33, 33, 0.44);
|
||||
--terminal-bright: #e8fff8;
|
||||
--terminal-muted: #94b9c5;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
font-family: var(--font-display), sans-serif;
|
||||
color: var(--terminal-bright);
|
||||
background:
|
||||
radial-gradient(circle at 18% -10%, rgba(126, 217, 255, 0.25), transparent 35%),
|
||||
radial-gradient(circle at 84% 0%, rgba(104, 255, 213, 0.2), transparent 30%),
|
||||
linear-gradient(140deg, var(--bg-0), var(--bg-1) 50%, var(--bg-2));
|
||||
}
|
||||
|
||||
.app-surface,
|
||||
.auth-page {
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ambient-grid {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background-image:
|
||||
linear-gradient(rgba(126, 217, 255, 0.08) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(126, 217, 255, 0.07) 1px, transparent 1px);
|
||||
background-size: 34px 34px;
|
||||
mask-image: radial-gradient(ellipse at center, black 20%, transparent 75%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.noise-layer {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
opacity: 0.3;
|
||||
background-image: radial-gradient(rgba(160, 255, 227, 0.15) 0.7px, transparent 0.7px);
|
||||
background-size: 4px 4px;
|
||||
}
|
||||
|
||||
.terminal-caption {
|
||||
font-family: var(--font-mono), monospace;
|
||||
}
|
||||
|
||||
.panel-heading {
|
||||
font-family: var(--font-mono), monospace;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
|
||||
.data-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.data-table th,
|
||||
.data-table td {
|
||||
border-bottom: 1px solid var(--line-weak);
|
||||
padding: 0.75rem 0.65rem;
|
||||
text-align: left;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.data-table th {
|
||||
font-family: var(--font-mono), monospace;
|
||||
font-size: 0.75rem;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--terminal-muted);
|
||||
}
|
||||
|
||||
.data-table tbody tr:hover {
|
||||
background-color: rgba(17, 47, 61, 0.45);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.ambient-grid {
|
||||
animation: subtle-grid-shift 18s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes subtle-grid-shift {
|
||||
0% {
|
||||
transform: translateY(0px);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
100% {
|
||||
transform: translateY(0px);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.ambient-grid {
|
||||
background-size: 26px 26px;
|
||||
}
|
||||
}
|
||||
15
app/layout.tsx
Normal file
15
app/layout.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import './globals.css';
|
||||
import type { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Fiscal Clone',
|
||||
description: 'Futuristic fiscal intelligence terminal with durable tasks and OpenClaw integration.'
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
229
app/page.tsx
Normal file
229
app/page.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Activity, Bot, RefreshCw, Sparkles } from 'lucide-react';
|
||||
import { AppShell } from '@/components/shell/app-shell';
|
||||
import { Panel } from '@/components/ui/panel';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { MetricCard } from '@/components/dashboard/metric-card';
|
||||
import { TaskFeed } from '@/components/dashboard/task-feed';
|
||||
import { StatusPill } from '@/components/ui/status-pill';
|
||||
import { useAuthGuard } from '@/hooks/use-auth-guard';
|
||||
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';
|
||||
|
||||
type DashboardState = {
|
||||
summary: PortfolioSummary;
|
||||
filingsCount: number;
|
||||
watchlistCount: number;
|
||||
tasks: Task[];
|
||||
latestInsight: PortfolioInsight | null;
|
||||
};
|
||||
|
||||
const EMPTY_STATE: DashboardState = {
|
||||
summary: {
|
||||
positions: 0,
|
||||
total_value: '0',
|
||||
total_gain_loss: '0',
|
||||
total_cost_basis: '0',
|
||||
avg_return_pct: '0'
|
||||
},
|
||||
filingsCount: 0,
|
||||
watchlistCount: 0,
|
||||
tasks: [],
|
||||
latestInsight: null
|
||||
};
|
||||
|
||||
export default function CommandCenterPage() {
|
||||
const { isPending, isAuthenticated, session } = useAuthGuard();
|
||||
const [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);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const [summaryRes, filingsRes, watchlistRes, tasksRes, insightRes] = await Promise.all([
|
||||
getPortfolioSummary(),
|
||||
listFilings({ limit: 200 }),
|
||||
listWatchlist(),
|
||||
listRecentTasks(20),
|
||||
getLatestPortfolioInsight()
|
||||
]);
|
||||
|
||||
setState({
|
||||
summary: summaryRes.summary,
|
||||
filingsCount: filingsRes.filings.length,
|
||||
watchlistCount: watchlistRes.items.length,
|
||||
tasks: tasksRes.tasks,
|
||||
latestInsight: insightRes.insight
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load dashboard');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
void loadData();
|
||||
}
|
||||
}, [isPending, isAuthenticated, loadData]);
|
||||
|
||||
const trackedTask = useTaskPoller({
|
||||
taskId: activeTaskId,
|
||||
onTerminalState: () => {
|
||||
setActiveTaskId(null);
|
||||
void loadData();
|
||||
}
|
||||
});
|
||||
|
||||
const headerActions = (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const { task } = await queuePriceRefresh();
|
||||
setActiveTaskId(task.id);
|
||||
const latest = await getTask(task.id);
|
||||
setState((prev) => ({ ...prev, tasks: [latest.task, ...prev.tasks] }));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to queue price refresh');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<RefreshCw className="size-4" />
|
||||
Refresh prices
|
||||
</Button>
|
||||
<Button
|
||||
onClick={async () => {
|
||||
try {
|
||||
const { task } = await queuePortfolioInsights();
|
||||
setActiveTaskId(task.id);
|
||||
const latest = await getTask(task.id);
|
||||
setState((prev) => ({ ...prev, tasks: [latest.task, ...prev.tasks] }));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to queue AI insight');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Sparkles className="size-4" />
|
||||
Queue AI insight
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
const signedGain = useMemo(() => {
|
||||
const gain = Number(state.summary.total_gain_loss ?? 0);
|
||||
return gain >= 0 ? `+${formatCurrency(gain)}` : formatCurrency(gain);
|
||||
}, [state.summary.total_gain_loss]);
|
||||
|
||||
if (isPending || !isAuthenticated) {
|
||||
return <div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Booting secure terminal...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
title="Command Center"
|
||||
subtitle={`Welcome back${session?.user?.name ? `, ${session.user.name}` : ''}. Review tasks, portfolio health, and AI outputs.`}
|
||||
actions={headerActions}
|
||||
>
|
||||
{activeTaskId && trackedTask ? (
|
||||
<Panel title="Live Task" subtitle={`Task ${activeTaskId.slice(0, 8)} is active.`}>
|
||||
<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)]">{trackedTask.task_type.replace('_', ' ')}</p>
|
||||
<StatusPill status={trackedTask.status} />
|
||||
</div>
|
||||
{trackedTask.error ? (
|
||||
<p className="mt-3 text-sm text-[#ff9898]">{trackedTask.error}</p>
|
||||
) : null}
|
||||
</Panel>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<Panel>
|
||||
<p className="text-sm text-[#ffb5b5]">{error}</p>
|
||||
</Panel>
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<MetricCard label="Portfolio Value" value={formatCurrency(state.summary.total_value)} delta={formatCompactCurrency(state.summary.total_cost_basis)} />
|
||||
<MetricCard
|
||||
label="Unrealized P&L"
|
||||
value={signedGain}
|
||||
delta={formatPercent(state.summary.avg_return_pct)}
|
||||
positive={Number(state.summary.total_gain_loss) >= 0}
|
||||
/>
|
||||
<MetricCard label="Tracked Filings" value={String(state.filingsCount)} delta="Last 200 records" />
|
||||
<MetricCard label="Watchlist Nodes" value={String(state.watchlistCount)} delta={`${state.summary.positions} positions active`} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 xl:grid-cols-3">
|
||||
<Panel title="Recent Tasks" subtitle="Durable jobs from queue processor" className="xl:col-span-1">
|
||||
{loading ? (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">Loading tasks...</p>
|
||||
) : (
|
||||
<TaskFeed tasks={state.tasks} />
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
<Panel title="AI Brief" subtitle="Latest portfolio insight from OpenClaw/ZeroClaw" className="xl:col-span-2">
|
||||
{loading ? (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">Loading intelligence output...</p>
|
||||
) : state.latestInsight ? (
|
||||
<>
|
||||
<div className="mb-3 inline-flex items-center gap-2 rounded-md border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-2 py-1 text-xs text-[color:var(--terminal-muted)]">
|
||||
<Bot className="size-3.5" />
|
||||
{state.latestInsight.provider} :: {state.latestInsight.model}
|
||||
</div>
|
||||
<p className="whitespace-pre-wrap text-sm leading-6 text-[color:var(--terminal-bright)]">{state.latestInsight.content}</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">No AI brief yet. Queue one from the action bar.</p>
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
<Panel title="Quick Links" subtitle="Feature modules">
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
<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">
|
||||
<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">
|
||||
<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">
|
||||
<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>
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel>
|
||||
<div className="flex items-center gap-2 text-xs uppercase tracking-[0.24em] text-[color:var(--terminal-muted)]">
|
||||
<Activity className="size-4" />
|
||||
Runtime state: {loading ? 'syncing' : 'stable'}
|
||||
</div>
|
||||
</Panel>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
332
app/portfolio/page.tsx
Normal file
332
app/portfolio/page.tsx
Normal file
@@ -0,0 +1,332 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { PieChart, Pie, Cell, Tooltip, 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';
|
||||
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 {
|
||||
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';
|
||||
|
||||
type FormState = {
|
||||
ticker: string;
|
||||
shares: string;
|
||||
avgCost: string;
|
||||
currentPrice: string;
|
||||
};
|
||||
|
||||
const CHART_COLORS = ['#6effd8', '#5fd3ff', '#66ffa1', '#8dbbff', '#f4f88f', '#ff9c9c'];
|
||||
|
||||
const EMPTY_SUMMARY: PortfolioSummary = {
|
||||
positions: 0,
|
||||
total_value: '0',
|
||||
total_gain_loss: '0',
|
||||
total_cost_basis: '0',
|
||||
avg_return_pct: '0'
|
||||
};
|
||||
|
||||
export default function PortfolioPage() {
|
||||
const { isPending, isAuthenticated } = useAuthGuard();
|
||||
|
||||
const [holdings, setHoldings] = useState<Holding[]>([]);
|
||||
const [summary, setSummary] = useState<PortfolioSummary>(EMPTY_SUMMARY);
|
||||
const [latestInsight, setLatestInsight] = useState<PortfolioInsight | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [activeTask, setActiveTask] = useState<Task | null>(null);
|
||||
const [form, setForm] = useState<FormState>({ ticker: '', shares: '', avgCost: '', currentPrice: '' });
|
||||
|
||||
const loadPortfolio = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const [holdingsRes, summaryRes, insightRes] = await Promise.all([
|
||||
listHoldings(),
|
||||
getPortfolioSummary(),
|
||||
getLatestPortfolioInsight()
|
||||
]);
|
||||
|
||||
setHoldings(holdingsRes.holdings);
|
||||
setSummary(summaryRes.summary);
|
||||
setLatestInsight(insightRes.insight);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Could not fetch portfolio data');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && isAuthenticated) {
|
||||
void loadPortfolio();
|
||||
}
|
||||
}, [isPending, isAuthenticated, loadPortfolio]);
|
||||
|
||||
const polledTask = useTaskPoller({
|
||||
taskId: activeTask?.id ?? null,
|
||||
onTerminalState: async () => {
|
||||
setActiveTask(null);
|
||||
await loadPortfolio();
|
||||
}
|
||||
});
|
||||
|
||||
const liveTask = polledTask ?? activeTask;
|
||||
|
||||
const allocationData = useMemo(
|
||||
() => holdings.map((holding) => ({
|
||||
name: holding.ticker,
|
||||
value: asNumber(holding.market_value)
|
||||
})),
|
||||
[holdings]
|
||||
);
|
||||
|
||||
const performanceData = useMemo(
|
||||
() => holdings.map((holding) => ({
|
||||
name: holding.ticker,
|
||||
value: asNumber(holding.gain_loss_pct)
|
||||
})),
|
||||
[holdings]
|
||||
);
|
||||
|
||||
const submitHolding = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
try {
|
||||
await upsertHolding({
|
||||
ticker: form.ticker.toUpperCase(),
|
||||
shares: Number(form.shares),
|
||||
avgCost: Number(form.avgCost),
|
||||
currentPrice: form.currentPrice ? Number(form.currentPrice) : undefined
|
||||
});
|
||||
|
||||
setForm({ ticker: '', shares: '', avgCost: '', currentPrice: '' });
|
||||
await loadPortfolio();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save holding');
|
||||
}
|
||||
};
|
||||
|
||||
const queueRefresh = async () => {
|
||||
try {
|
||||
const { task } = await queuePriceRefresh();
|
||||
const latest = await getTask(task.id);
|
||||
setActiveTask(latest.task);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unable to queue price refresh');
|
||||
}
|
||||
};
|
||||
|
||||
const queueInsights = async () => {
|
||||
try {
|
||||
const { task } = await queuePortfolioInsights();
|
||||
const latest = await getTask(task.id);
|
||||
setActiveTask(latest.task);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unable to queue portfolio insights');
|
||||
}
|
||||
};
|
||||
|
||||
if (isPending || !isAuthenticated) {
|
||||
return <div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Loading portfolio matrix...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
title="Portfolio Matrix"
|
||||
subtitle="Position management, market valuation, and AI generated portfolio commentary."
|
||||
actions={(
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => void queueRefresh()}>
|
||||
<RefreshCcw className="size-4" />
|
||||
Queue price refresh
|
||||
</Button>
|
||||
<Button onClick={() => void queueInsights()}>
|
||||
<BrainCircuit className="size-4" />
|
||||
Generate AI brief
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
{liveTask ? (
|
||||
<Panel title="Task Runner" subtitle={liveTask.id}>
|
||||
<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>
|
||||
{liveTask.error ? <p className="mt-2 text-sm text-[#ff9f9f]">{liveTask.error}</p> : null}
|
||||
</Panel>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<Panel>
|
||||
<p className="text-sm text-[#ffb5b5]">{error}</p>
|
||||
</Panel>
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
|
||||
<Panel title="Total Value" className="lg:col-span-1">
|
||||
<p className="text-3xl font-semibold text-[color:var(--terminal-bright)]">{formatCurrency(summary.total_value)}</p>
|
||||
<p className="mt-2 text-sm text-[color:var(--terminal-muted)]">Cost basis {formatCurrency(summary.total_cost_basis)}</p>
|
||||
</Panel>
|
||||
<Panel title="Unrealized P&L" className="lg:col-span-1">
|
||||
<p className={`text-3xl font-semibold ${asNumber(summary.total_gain_loss) >= 0 ? 'text-[#96f5bf]' : 'text-[#ff9f9f]'}`}>
|
||||
{formatCurrency(summary.total_gain_loss)}
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-[color:var(--terminal-muted)]">Average return {formatPercent(summary.avg_return_pct)}</p>
|
||||
</Panel>
|
||||
<Panel title="Positions" className="lg:col-span-1">
|
||||
<p className="text-3xl font-semibold text-[color:var(--terminal-bright)]">{summary.positions}</p>
|
||||
<p className="mt-2 text-sm text-[color:var(--terminal-muted)]">Active symbols in portfolio.</p>
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 xl:grid-cols-2">
|
||||
<Panel title="Allocation">
|
||||
{loading ? (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">Loading chart...</p>
|
||||
) : allocationData.length > 0 ? (
|
||||
<div className="h-[300px]">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie data={allocationData} dataKey="value" nameKey="name" innerRadius={56} outerRadius={104} paddingAngle={2}>
|
||||
{allocationData.map((entry, index) => (
|
||||
<Cell key={`${entry.name}-${index}`} fill={CHART_COLORS[index % CHART_COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip formatter={(value: number | string | undefined) => formatCurrency(value)} />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">No holdings yet.</p>
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
<Panel title="Performance %">
|
||||
{loading ? (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">Loading chart...</p>
|
||||
) : performanceData.length > 0 ? (
|
||||
<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)}%`} />
|
||||
<Bar dataKey="value" fill="#68ffd5" radius={[4, 4, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">No performance data yet.</p>
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.5fr_1fr]">
|
||||
<Panel title="Holdings Table" subtitle="Live mark-to-market values from latest refresh.">
|
||||
{loading ? (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">Loading holdings...</p>
|
||||
) : holdings.length === 0 ? (
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">No holdings added yet.</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="data-table min-w-[780px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Ticker</th>
|
||||
<th>Shares</th>
|
||||
<th>Avg Cost</th>
|
||||
<th>Price</th>
|
||||
<th>Value</th>
|
||||
<th>Gain/Loss</th>
|
||||
<th>Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{holdings.map((holding) => (
|
||||
<tr key={holding.id}>
|
||||
<td>{holding.ticker}</td>
|
||||
<td>{asNumber(holding.shares).toLocaleString()}</td>
|
||||
<td>{formatCurrency(holding.avg_cost)}</td>
|
||||
<td>{holding.current_price ? formatCurrency(holding.current_price) : 'n/a'}</td>
|
||||
<td>{formatCurrency(holding.market_value)}</td>
|
||||
<td className={asNumber(holding.gain_loss) >= 0 ? 'text-[#96f5bf]' : 'text-[#ff9898]'}>
|
||||
{formatCurrency(holding.gain_loss)} ({formatPercent(holding.gain_loss_pct)})
|
||||
</td>
|
||||
<td>
|
||||
<Button
|
||||
variant="danger"
|
||||
className="px-2 py-1 text-xs"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await deleteHolding(holding.id);
|
||||
await loadPortfolio();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete holding');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Trash2 className="size-3" />
|
||||
Delete
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
<Panel title="Add / Update Holding">
|
||||
<form onSubmit={submitHolding} className="space-y-3">
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.16em] 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.16em] text-[color:var(--terminal-muted)]">Shares</label>
|
||||
<Input type="number" step="0.0001" min="0.0001" value={form.shares} onChange={(event) => setForm((prev) => ({ ...prev, shares: event.target.value }))} required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.16em] text-[color:var(--terminal-muted)]">Average Cost</label>
|
||||
<Input type="number" step="0.0001" min="0.0001" value={form.avgCost} onChange={(event) => setForm((prev) => ({ ...prev, avgCost: event.target.value }))} required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.16em] text-[color:var(--terminal-muted)]">Current Price (optional)</label>
|
||||
<Input type="number" step="0.0001" min="0" value={form.currentPrice} onChange={(event) => setForm((prev) => ({ ...prev, currentPrice: event.target.value }))} />
|
||||
</div>
|
||||
<Button type="submit" className="w-full">
|
||||
<Plus className="size-4" />
|
||||
Save holding
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-5 border-t border-[color:var(--line-weak)] pt-4">
|
||||
<p className="text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Latest AI Insight</p>
|
||||
<p className="mt-2 whitespace-pre-wrap text-sm leading-6 text-[color:var(--terminal-bright)]">
|
||||
{latestInsight?.content ?? 'No insight available yet. Queue an AI brief from the header.'}
|
||||
</p>
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
181
app/watchlist/page.tsx
Normal file
181
app/watchlist/page.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
'use client';
|
||||
|
||||
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 { isPending, isAuthenticated } = useAuthGuard();
|
||||
|
||||
const [items, setItems] = useState<WatchlistItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [activeTask, setActiveTask] = useState<Task | null>(null);
|
||||
const [form, setForm] = useState<FormState>({ ticker: '', companyName: '', sector: '' });
|
||||
|
||||
const loadWatchlist = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await listWatchlist();
|
||||
setItems(response.items);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load watchlist');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
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 upsertWatchlistItem({
|
||||
ticker: form.ticker.toUpperCase(),
|
||||
companyName: form.companyName,
|
||||
sector: form.sector || undefined
|
||||
});
|
||||
|
||||
setForm({ ticker: '', companyName: '', sector: '' });
|
||||
await loadWatchlist();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save watchlist item');
|
||||
}
|
||||
};
|
||||
|
||||
const queueSync = async (ticker: string) => {
|
||||
try {
|
||||
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 (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 (
|
||||
<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>
|
||||
</Panel>
|
||||
) : null}
|
||||
|
||||
<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="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>
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
<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