rebuild app as turbopack-first single-stack with internal api and openclaw tasks

This commit is contained in:
2026-02-23 23:38:06 -05:00
parent 5df09b714b
commit 6012dd3fcf
40 changed files with 1583 additions and 1578 deletions

View 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'));
}
}

View 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 });
}

View 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'));
}
}

View 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
});
}

View File

@@ -0,0 +1,10 @@
export async function GET() {
return Response.json({
user: {
id: 1,
email: 'operator@local.fiscal',
name: 'Local Operator',
image: null
}
});
}

View 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 });
}

View 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'));
}
}

View 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'));
}
}

View 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 });
}

View 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'));
}
}

View 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 });
}

View 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 });
}

View 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 });
}

View 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 });
}

View 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'));
}
}

View File

@@ -1,86 +1,32 @@
'use client';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { signIn, useSession } from '@/lib/better-auth';
import { AuthShell } from '@/components/auth/auth-shell';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
export default function SignInPage() {
const router = useRouter();
const { data: session, isPending: sessionPending } = useSession();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!sessionPending && session?.user) {
router.replace('/');
}
}, [sessionPending, session, router]);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setLoading(true);
setError(null);
try {
const result = await signIn.email({ email, password });
if (result.error) {
setError(result.error.message || 'Invalid credentials');
} else {
router.replace('/');
router.refresh();
}
} catch {
setError('Sign in failed');
} finally {
setLoading(false);
}
};
return (
<AuthShell
title="Sign in"
subtitle="Authenticate with Better Auth session-backed credentials."
title="Local Runtime Mode"
subtitle="Authentication is disabled in this rebuilt local-first environment."
footer={(
<>
No account yet?{' '}
<Link href="/auth/signup" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
Create one
Need multi-user auth later?{' '}
<Link href="/" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
Open command center
</Link>
</>
)}
>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Email</label>
<Input type="email" required value={email} onChange={(event) => setEmail(event.target.value)} placeholder="you@company.com" />
</div>
<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>
<div>
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Password</label>
<Input
type="password"
required
minLength={8}
value={password}
onChange={(event) => setPassword(event.target.value)}
placeholder="********"
/>
</div>
{error ? <p className="text-sm text-[#ff9f9f]">{error}</p> : null}
<Button type="submit" className="w-full" disabled={loading || sessionPending}>
{loading ? 'Signing in...' : 'Sign in'}
<Link href="/" className="mt-6 block">
<Button type="button" className="w-full">
Enter terminal
</Button>
</form>
</Link>
</AuthShell>
);
}

View File

@@ -1,96 +1,32 @@
'use client';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { signUp, useSession } from '@/lib/better-auth';
import { AuthShell } from '@/components/auth/auth-shell';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
export default function SignUpPage() {
const router = useRouter();
const { data: session, isPending: sessionPending } = useSession();
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!sessionPending && session?.user) {
router.replace('/');
}
}, [sessionPending, session, router]);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setLoading(true);
setError(null);
try {
const result = await signUp.email({
name,
email,
password
});
if (result.error) {
setError(result.error.message || 'Unable to create account');
} else {
router.replace('/');
router.refresh();
}
} catch {
setError('Sign up failed');
} finally {
setLoading(false);
}
};
return (
<AuthShell
title="Create account"
subtitle="Provision an analyst workspace with Better Auth sessions."
title="Workspace Provisioned"
subtitle="This clone now runs in local-operator mode and does not require account creation."
footer={(
<>
Already registered?{' '}
<Link href="/auth/signin" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
Sign in
Already set?{' '}
<Link href="/" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
Launch dashboard
</Link>
</>
)}
>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Name</label>
<Input required value={name} onChange={(event) => setName(event.target.value)} placeholder="Operator name" />
</div>
<p className="text-sm text-[color:var(--terminal-muted)]">
For production deployment you can reintroduce Better Auth, but the rebuilt stack is intentionally self-contained for fast iteration.
</p>
<div>
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Email</label>
<Input type="email" required value={email} onChange={(event) => setEmail(event.target.value)} placeholder="you@company.com" />
</div>
<div>
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Password</label>
<Input
type="password"
required
minLength={8}
value={password}
onChange={(event) => setPassword(event.target.value)}
placeholder="Minimum 8 characters"
/>
</div>
{error ? <p className="text-sm text-[#ff9f9f]">{error}</p> : null}
<Button type="submit" className="w-full" disabled={loading || sessionPending}>
{loading ? 'Creating account...' : 'Create account'}
<Link href="/" className="mt-6 block">
<Button type="button" className="w-full">
Open fiscal desk
</Button>
</form>
</Link>
</AuthShell>
);
}

View File

@@ -1,6 +1,7 @@
'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';
@@ -16,6 +17,14 @@ 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();

View File

@@ -3,6 +3,8 @@
@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;

View File

@@ -1,16 +1,5 @@
import './globals.css';
import type { Metadata } from 'next';
import { JetBrains_Mono, Space_Grotesk } from 'next/font/google';
const display = Space_Grotesk({
subsets: ['latin'],
variable: '--font-display'
});
const mono = JetBrains_Mono({
subsets: ['latin'],
variable: '--font-mono'
});
export const metadata: Metadata = {
title: 'Fiscal Clone',
@@ -19,7 +8,7 @@ export const metadata: Metadata = {
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={`${display.variable} ${mono.variable}`}>
<html lang="en">
<body>{children}</body>
</html>
);