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

View File

@@ -1,9 +1,8 @@
'use client';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { Activity, BookOpenText, ChartCandlestick, Eye, LogOut } from 'lucide-react';
import { signOut, useSession } from '@/lib/better-auth';
import { usePathname } from 'next/navigation';
import { Activity, BookOpenText, ChartCandlestick, Eye } from 'lucide-react';
import { cn } from '@/lib/utils';
type AppShellProps = {
@@ -22,14 +21,6 @@ const NAV_ITEMS = [
export function AppShell({ title, subtitle, actions, children }: AppShellProps) {
const pathname = usePathname();
const router = useRouter();
const { data: session } = useSession();
const handleSignOut = async () => {
await signOut();
router.replace('/auth/signin');
router.refresh();
};
return (
<div className="app-surface">
@@ -70,16 +61,11 @@ export function AppShell({ title, subtitle, actions, children }: AppShellProps)
</nav>
<div className="mt-auto rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-3">
<p className="text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Session</p>
<p className="mt-1 truncate text-sm text-[color:var(--terminal-bright)]">{session?.user?.email ?? 'anonymous'}</p>
<button
type="button"
onClick={handleSignOut}
className="mt-3 inline-flex w-full items-center justify-center gap-2 rounded-lg border border-[color:var(--line-weak)] bg-[color:var(--panel)] px-3 py-2 text-xs text-[color:var(--terminal-bright)] transition hover:border-[color:var(--line-strong)] hover:bg-[color:var(--panel-bright)]"
>
<LogOut className="size-3.5" />
Sign out
</button>
<p className="text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Runtime</p>
<p className="mt-1 truncate text-sm text-[color:var(--terminal-bright)]">local operator mode</p>
<p className="mt-2 text-xs text-[color:var(--terminal-muted)]">
OpenClaw and market data are driven by environment configuration and live API tasks.
</p>
</div>
</aside>

View File

@@ -1,22 +1,16 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from '@/lib/better-auth';
export function useAuthGuard() {
const { data: session, isPending } = useSession();
const router = useRouter();
useEffect(() => {
if (!isPending && !session) {
router.replace('/auth/signin');
}
}, [isPending, session, router]);
return {
session,
isPending,
isAuthenticated: Boolean(session?.user)
session: {
user: {
id: 1,
name: 'Local Operator',
email: 'operator@local.fiscal',
image: null
}
},
isPending: false,
isAuthenticated: true
};
}

View File

@@ -1,11 +0,0 @@
import { createAuthClient } from 'better-auth/react';
import { resolveApiBaseURL } from '@/lib/runtime-url';
export const authClient = createAuthClient({
baseURL: resolveApiBaseURL(process.env.NEXT_PUBLIC_API_URL),
fetchOptions: {
credentials: 'include'
}
});
export const { signIn, signUp, signOut, useSession } = authClient;

View File

@@ -2,44 +2,12 @@ function trimTrailingSlash(value: string) {
return value.endsWith('/') ? value.slice(0, -1) : value;
}
function isInternalHost(hostname: string) {
return hostname === 'backend'
|| hostname === 'localhost'
|| hostname === '127.0.0.1'
|| hostname.endsWith('.internal');
}
function parseUrl(url: string) {
try {
return new URL(url);
} catch {
return null;
}
}
export function resolveApiBaseURL(configuredBaseURL: string | undefined) {
const fallbackLocal = 'http://localhost:3001';
const candidate = configuredBaseURL?.trim() || fallbackLocal;
const candidate = configuredBaseURL?.trim();
if (typeof window === 'undefined') {
return trimTrailingSlash(candidate);
if (!candidate) {
return '';
}
const parsed = parseUrl(candidate);
if (!parsed) {
return `${window.location.origin}`;
}
const browserHost = window.location.hostname;
const browserIsLocal = browserHost === 'localhost' || browserHost === '127.0.0.1';
if (!browserIsLocal && isInternalHost(parsed.hostname)) {
console.warn(
`[fiscal] NEXT_PUBLIC_API_URL is internal (${parsed.hostname}); falling back to https://api.${browserHost}`
);
return trimTrailingSlash(`https://api.${browserHost}`);
}
return trimTrailingSlash(parsed.toString());
return trimTrailingSlash(candidate);
}

View File

@@ -0,0 +1,11 @@
export function jsonError(message: string, status = 400) {
return Response.json({ error: message }, { status });
}
export function asErrorMessage(error: unknown, fallback: string) {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return fallback;
}

View File

@@ -0,0 +1,92 @@
type ChatCompletionResponse = {
choices?: Array<{
message?: {
content?: string;
};
}>;
};
function envValue(name: string) {
const value = process.env[name];
if (!value) {
return undefined;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
const DEFAULT_MODEL = 'zeroclaw';
function fallbackResponse(prompt: string) {
const clipped = prompt.split('\n').slice(0, 6).join(' ').slice(0, 260);
return [
'OpenClaw fallback mode is active (missing OPENCLAW_BASE_URL or OPENCLAW_API_KEY).',
'Thesis: Portfolio remains analyzable with local heuristics until live model access is configured.',
'Risk scan: Concentration and filing sentiment should be monitored after each sync cycle.',
`Context digest: ${clipped}`
].join('\n\n');
}
export function getOpenClawConfig() {
return {
baseUrl: envValue('OPENCLAW_BASE_URL'),
apiKey: envValue('OPENCLAW_API_KEY'),
model: envValue('OPENCLAW_MODEL') ?? DEFAULT_MODEL
};
}
export function isOpenClawConfigured() {
const config = getOpenClawConfig();
return Boolean(config.baseUrl && config.apiKey);
}
export async function runOpenClawAnalysis(prompt: string, systemPrompt?: string) {
const config = getOpenClawConfig();
if (!config.baseUrl || !config.apiKey) {
return {
provider: 'local-fallback',
model: config.model,
text: fallbackResponse(prompt)
};
}
const response = await fetch(`${config.baseUrl}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.apiKey}`
},
body: JSON.stringify({
model: config.model,
temperature: 0.2,
messages: [
systemPrompt
? { role: 'system', content: systemPrompt }
: null,
{ role: 'user', content: prompt }
].filter(Boolean)
}),
cache: 'no-store'
});
if (!response.ok) {
const body = await response.text();
throw new Error(`OpenClaw request failed (${response.status}): ${body.slice(0, 220)}`);
}
const payload = await response.json() as ChatCompletionResponse;
const text = payload.choices?.[0]?.message?.content?.trim();
if (!text) {
throw new Error('OpenClaw returned an empty response');
}
return {
provider: 'openclaw',
model: config.model,
text
};
}

View File

@@ -0,0 +1,69 @@
import type { Holding, PortfolioSummary } from '@/lib/types';
function asFiniteNumber(value: string | number | null | undefined) {
if (value === null || value === undefined) {
return 0;
}
const parsed = typeof value === 'number' ? value : Number(value);
return Number.isFinite(parsed) ? parsed : 0;
}
function toDecimalString(value: number, digits = 4) {
return value.toFixed(digits);
}
export function recalculateHolding(base: Holding): Holding {
const shares = asFiniteNumber(base.shares);
const avgCost = asFiniteNumber(base.avg_cost);
const price = base.current_price === null
? avgCost
: asFiniteNumber(base.current_price);
const marketValue = shares * price;
const costBasis = shares * avgCost;
const gainLoss = marketValue - costBasis;
const gainLossPct = costBasis > 0 ? (gainLoss / costBasis) * 100 : 0;
return {
...base,
shares: toDecimalString(shares, 6),
avg_cost: toDecimalString(avgCost, 6),
current_price: toDecimalString(price, 6),
market_value: toDecimalString(marketValue, 2),
gain_loss: toDecimalString(gainLoss, 2),
gain_loss_pct: toDecimalString(gainLossPct, 2)
};
}
export function buildPortfolioSummary(holdings: Holding[]): PortfolioSummary {
const positions = holdings.length;
const totals = holdings.reduce(
(acc, holding) => {
const shares = asFiniteNumber(holding.shares);
const avgCost = asFiniteNumber(holding.avg_cost);
const marketValue = asFiniteNumber(holding.market_value);
const gainLoss = asFiniteNumber(holding.gain_loss);
acc.totalValue += marketValue;
acc.totalGainLoss += gainLoss;
acc.totalCostBasis += shares * avgCost;
return acc;
},
{ totalValue: 0, totalGainLoss: 0, totalCostBasis: 0 }
);
const avgReturnPct = totals.totalCostBasis > 0
? (totals.totalGainLoss / totals.totalCostBasis) * 100
: 0;
return {
positions,
total_value: toDecimalString(totals.totalValue, 2),
total_gain_loss: toDecimalString(totals.totalGainLoss, 2),
total_cost_basis: toDecimalString(totals.totalCostBasis, 2),
avg_return_pct: toDecimalString(avgReturnPct, 2)
};
}

View File

@@ -0,0 +1,44 @@
const YAHOO_BASE = 'https://query1.finance.yahoo.com/v8/finance/chart';
function fallbackQuote(ticker: string) {
const normalized = ticker.trim().toUpperCase();
let hash = 0;
for (const char of normalized) {
hash = (hash * 31 + char.charCodeAt(0)) % 100000;
}
return 40 + (hash % 360) + ((hash % 100) / 100);
}
export async function getQuote(ticker: string): Promise<number> {
const normalizedTicker = ticker.trim().toUpperCase();
try {
const response = await fetch(`${YAHOO_BASE}/${normalizedTicker}?interval=1d&range=1d`, {
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; FiscalClone/3.0)'
},
cache: 'no-store'
});
if (!response.ok) {
return fallbackQuote(normalizedTicker);
}
const payload = await response.json() as {
chart?: {
result?: Array<{ meta?: { regularMarketPrice?: number } }>;
};
};
const price = payload.chart?.result?.[0]?.meta?.regularMarketPrice;
if (typeof price !== 'number' || !Number.isFinite(price)) {
return fallbackQuote(normalizedTicker);
}
return price;
} catch {
return fallbackQuote(normalizedTicker);
}
}

248
frontend/lib/server/sec.ts Normal file
View File

@@ -0,0 +1,248 @@
import type { Filing } from '@/lib/types';
type FilingType = Filing['filing_type'];
type TickerDirectoryRecord = {
cik_str: number;
ticker: string;
title: string;
};
type RecentFilingsPayload = {
filings?: {
recent?: {
accessionNumber?: string[];
filingDate?: string[];
form?: string[];
primaryDocument?: string[];
};
};
cik?: string;
name?: string;
};
type CompanyFactsPayload = {
facts?: {
'us-gaap'?: Record<string, { units?: Record<string, Array<{ val?: number; end?: string; filed?: string }>> }>;
};
};
type SecFiling = {
ticker: string;
cik: string;
companyName: string;
filingType: FilingType;
filingDate: string;
accessionNumber: string;
filingUrl: string | null;
};
const SUPPORTED_FORMS: FilingType[] = ['10-K', '10-Q', '8-K'];
const TICKER_CACHE_TTL_MS = 1000 * 60 * 60 * 12;
let tickerCache = new Map<string, TickerDirectoryRecord>();
let tickerCacheLoadedAt = 0;
function envUserAgent() {
return process.env.SEC_USER_AGENT || 'Fiscal Clone <support@fiscal.local>';
}
function todayIso() {
return new Date().toISOString().slice(0, 10);
}
function pseudoMetric(seed: string, min: number, max: number) {
let hash = 0;
for (const char of seed) {
hash = (hash * 33 + char.charCodeAt(0)) % 100000;
}
const fraction = (hash % 10000) / 10000;
return min + (max - min) * fraction;
}
function fallbackFilings(ticker: string, limit: number): SecFiling[] {
const normalized = ticker.trim().toUpperCase();
const companyName = `${normalized} Holdings Inc.`;
const filings: SecFiling[] = [];
for (let i = 0; i < limit; i += 1) {
const filingType = SUPPORTED_FORMS[i % SUPPORTED_FORMS.length];
const date = new Date(Date.now() - i * 1000 * 60 * 60 * 24 * 35).toISOString().slice(0, 10);
const accessionNumber = `${Date.now()}-${i}`;
filings.push({
ticker: normalized,
cik: String(100000 + i),
companyName,
filingType,
filingDate: date,
accessionNumber,
filingUrl: null
});
}
return filings;
}
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url, {
headers: {
'User-Agent': envUserAgent(),
Accept: 'application/json'
},
cache: 'no-store'
});
if (!response.ok) {
throw new Error(`SEC request failed (${response.status})`);
}
return await response.json() as T;
}
async function ensureTickerCache() {
const isFresh = Date.now() - tickerCacheLoadedAt < TICKER_CACHE_TTL_MS;
if (isFresh && tickerCache.size > 0) {
return;
}
const payload = await fetchJson<Record<string, TickerDirectoryRecord>>('https://www.sec.gov/files/company_tickers.json');
const next = new Map<string, TickerDirectoryRecord>();
for (const record of Object.values(payload)) {
next.set(record.ticker.toUpperCase(), record);
}
tickerCache = next;
tickerCacheLoadedAt = Date.now();
}
async function resolveTicker(ticker: string) {
await ensureTickerCache();
const normalized = ticker.trim().toUpperCase();
const record = tickerCache.get(normalized);
if (!record) {
throw new Error(`Ticker ${normalized} not found in SEC directory`);
}
return {
ticker: normalized,
cik: String(record.cik_str),
companyName: record.title
};
}
function pickLatestFact(payload: CompanyFactsPayload, tag: string): number | null {
const unitCollections = payload.facts?.['us-gaap']?.[tag]?.units;
if (!unitCollections) {
return null;
}
const preferredUnits = ['USD', 'USD/shares'];
for (const unit of preferredUnits) {
const series = unitCollections[unit];
if (!series?.length) {
continue;
}
const best = [...series]
.filter((item) => typeof item.val === 'number')
.sort((a, b) => {
const aDate = Date.parse(a.filed ?? a.end ?? '1970-01-01');
const bDate = Date.parse(b.filed ?? b.end ?? '1970-01-01');
return bDate - aDate;
})[0];
if (best?.val !== undefined) {
return best.val;
}
}
return null;
}
export async function fetchRecentFilings(ticker: string, limit = 20): Promise<SecFiling[]> {
const safeLimit = Math.min(Math.max(Math.trunc(limit), 1), 50);
try {
const company = await resolveTicker(ticker);
const cikPadded = company.cik.padStart(10, '0');
const payload = await fetchJson<RecentFilingsPayload>(`https://data.sec.gov/submissions/CIK${cikPadded}.json`);
const recent = payload.filings?.recent;
if (!recent) {
return fallbackFilings(company.ticker, safeLimit);
}
const forms = recent.form ?? [];
const accessionNumbers = recent.accessionNumber ?? [];
const filingDates = recent.filingDate ?? [];
const primaryDocuments = recent.primaryDocument ?? [];
const filings: SecFiling[] = [];
for (let i = 0; i < forms.length; i += 1) {
const filingType = forms[i] as FilingType;
if (!SUPPORTED_FORMS.includes(filingType)) {
continue;
}
const accessionNumber = accessionNumbers[i];
if (!accessionNumber) {
continue;
}
const compactAccession = accessionNumber.replace(/-/g, '');
const documentName = primaryDocuments[i];
const filingUrl = documentName
? `https://www.sec.gov/Archives/edgar/data/${Number(company.cik)}/${compactAccession}/${documentName}`
: null;
filings.push({
ticker: company.ticker,
cik: company.cik,
companyName: payload.name ?? company.companyName,
filingType,
filingDate: filingDates[i] ?? todayIso(),
accessionNumber,
filingUrl
});
if (filings.length >= safeLimit) {
break;
}
}
return filings.length > 0 ? filings : fallbackFilings(company.ticker, safeLimit);
} catch {
return fallbackFilings(ticker, safeLimit);
}
}
export async function fetchFilingMetrics(cik: string, ticker: string) {
try {
const normalized = cik.padStart(10, '0');
const payload = await fetchJson<CompanyFactsPayload>(`https://data.sec.gov/api/xbrl/companyfacts/CIK${normalized}.json`);
return {
revenue: pickLatestFact(payload, 'Revenues'),
netIncome: pickLatestFact(payload, 'NetIncomeLoss'),
totalAssets: pickLatestFact(payload, 'Assets'),
cash: pickLatestFact(payload, 'CashAndCashEquivalentsAtCarryingValue'),
debt: pickLatestFact(payload, 'LongTermDebt')
};
} catch {
return {
revenue: Math.round(pseudoMetric(`${ticker}-revenue`, 2_000_000_000, 350_000_000_000)),
netIncome: Math.round(pseudoMetric(`${ticker}-net`, 150_000_000, 40_000_000_000)),
totalAssets: Math.round(pseudoMetric(`${ticker}-assets`, 4_000_000_000, 500_000_000_000)),
cash: Math.round(pseudoMetric(`${ticker}-cash`, 200_000_000, 180_000_000_000)),
debt: Math.round(pseudoMetric(`${ticker}-debt`, 300_000_000, 220_000_000_000))
};
}
}

View File

@@ -0,0 +1,100 @@
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import type { Filing, Holding, PortfolioInsight, Task, WatchlistItem } from '@/lib/types';
export type DataStore = {
counters: {
watchlist: number;
holdings: number;
filings: number;
insights: number;
};
watchlist: WatchlistItem[];
holdings: Holding[];
filings: Filing[];
tasks: Task[];
insights: PortfolioInsight[];
};
const DATA_DIR = path.join(process.cwd(), 'data');
const STORE_PATH = path.join(DATA_DIR, 'store.json');
let writeQueue = Promise.resolve();
function nowIso() {
return new Date().toISOString();
}
function createDefaultStore(): DataStore {
const now = nowIso();
return {
counters: {
watchlist: 0,
holdings: 0,
filings: 0,
insights: 0
},
watchlist: [],
holdings: [],
filings: [],
tasks: [],
insights: [
{
id: 1,
user_id: 1,
provider: 'local-bootstrap',
model: 'zeroclaw',
content: [
'System initialized in local-first mode.',
'Add holdings and sync filings to produce a live AI brief via OpenClaw.'
].join('\n'),
created_at: now
}
]
};
}
async function ensureStoreFile() {
await mkdir(DATA_DIR, { recursive: true });
try {
await readFile(STORE_PATH, 'utf8');
} catch {
const defaultStore = createDefaultStore();
defaultStore.counters.insights = defaultStore.insights.length;
await writeFile(STORE_PATH, JSON.stringify(defaultStore, null, 2), 'utf8');
}
}
async function readStore(): Promise<DataStore> {
await ensureStoreFile();
const raw = await readFile(STORE_PATH, 'utf8');
return JSON.parse(raw) as DataStore;
}
async function writeStore(store: DataStore) {
await writeFile(STORE_PATH, JSON.stringify(store, null, 2), 'utf8');
}
function cloneStore(store: DataStore): DataStore {
return JSON.parse(JSON.stringify(store)) as DataStore;
}
export async function getStoreSnapshot() {
const store = await readStore();
return cloneStore(store);
}
export async function withStore<T>(mutator: (store: DataStore) => T | Promise<T>): Promise<T> {
const run = async () => {
const store = await readStore();
const result = await mutator(store);
await writeStore(store);
return result;
};
const nextRun = writeQueue.then(run, run);
writeQueue = nextRun.then(() => undefined, () => undefined);
return await nextRun;
}

View File

@@ -0,0 +1,404 @@
import { randomUUID } from 'node:crypto';
import type { Filing, Holding, PortfolioInsight, Task, TaskStatus, TaskType } from '@/lib/types';
import { runOpenClawAnalysis } from '@/lib/server/openclaw';
import { buildPortfolioSummary, recalculateHolding } from '@/lib/server/portfolio';
import { getQuote } from '@/lib/server/prices';
import { fetchFilingMetrics, fetchRecentFilings } from '@/lib/server/sec';
import { getStoreSnapshot, withStore } from '@/lib/server/store';
type EnqueueTaskInput = {
taskType: TaskType;
payload?: Record<string, unknown>;
priority?: number;
maxAttempts?: number;
};
const activeTaskRuns = new Set<string>();
function nowIso() {
return new Date().toISOString();
}
function toTaskResult(value: unknown): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return { value };
}
return value as Record<string, unknown>;
}
function parseTicker(raw: unknown) {
if (typeof raw !== 'string' || raw.trim().length < 1) {
throw new Error('Ticker is required');
}
return raw.trim().toUpperCase();
}
function parseLimit(raw: unknown, fallback: number, min: number, max: number) {
const numberValue = typeof raw === 'number' ? raw : Number(raw);
if (!Number.isFinite(numberValue)) {
return fallback;
}
const intValue = Math.trunc(numberValue);
return Math.min(Math.max(intValue, min), max);
}
function queueTaskRun(taskId: string, delayMs = 40) {
setTimeout(() => {
void processTask(taskId);
}, delayMs);
}
async function markTask(taskId: string, mutator: (task: Task) => void) {
await withStore((store) => {
const index = store.tasks.findIndex((task) => task.id === taskId);
if (index < 0) {
return;
}
const task = store.tasks[index];
mutator(task);
task.updated_at = nowIso();
});
}
async function processSyncFilings(task: Task) {
const ticker = parseTicker(task.payload.ticker);
const limit = parseLimit(task.payload.limit, 20, 1, 50);
const filings = await fetchRecentFilings(ticker, limit);
const metricsByCik = new Map<string, Filing['metrics']>();
for (const filing of filings) {
if (!metricsByCik.has(filing.cik)) {
const metrics = await fetchFilingMetrics(filing.cik, filing.ticker);
metricsByCik.set(filing.cik, metrics);
}
}
let insertedCount = 0;
let updatedCount = 0;
await withStore((store) => {
for (const filing of filings) {
const existingIndex = store.filings.findIndex((entry) => entry.accession_number === filing.accessionNumber);
const timestamp = nowIso();
const metrics = metricsByCik.get(filing.cik) ?? null;
if (existingIndex >= 0) {
const existing = store.filings[existingIndex];
store.filings[existingIndex] = {
...existing,
ticker: filing.ticker,
cik: filing.cik,
filing_type: filing.filingType,
filing_date: filing.filingDate,
company_name: filing.companyName,
filing_url: filing.filingUrl,
metrics,
updated_at: timestamp
};
updatedCount += 1;
} else {
store.counters.filings += 1;
store.filings.unshift({
id: store.counters.filings,
ticker: filing.ticker,
filing_type: filing.filingType,
filing_date: filing.filingDate,
accession_number: filing.accessionNumber,
cik: filing.cik,
company_name: filing.companyName,
filing_url: filing.filingUrl,
metrics,
analysis: null,
created_at: timestamp,
updated_at: timestamp
});
insertedCount += 1;
}
}
store.filings.sort((a, b) => {
const byDate = Date.parse(b.filing_date) - Date.parse(a.filing_date);
return Number.isFinite(byDate) && byDate !== 0
? byDate
: Date.parse(b.updated_at) - Date.parse(a.updated_at);
});
});
return {
ticker,
fetched: filings.length,
inserted: insertedCount,
updated: updatedCount
};
}
async function processRefreshPrices() {
const snapshot = await getStoreSnapshot();
const tickers = [...new Set(snapshot.holdings.map((holding) => holding.ticker))];
const quotes = new Map<string, number>();
for (const ticker of tickers) {
const quote = await getQuote(ticker);
quotes.set(ticker, quote);
}
let updatedCount = 0;
const updateTime = nowIso();
await withStore((store) => {
store.holdings = store.holdings.map((holding) => {
const quote = quotes.get(holding.ticker);
if (quote === undefined) {
return holding;
}
updatedCount += 1;
return recalculateHolding({
...holding,
current_price: quote.toFixed(6),
last_price_at: updateTime,
updated_at: updateTime
});
});
});
return {
updatedCount,
totalTickers: tickers.length
};
}
async function processAnalyzeFiling(task: Task) {
const accessionNumber = typeof task.payload.accessionNumber === 'string'
? task.payload.accessionNumber
: '';
if (!accessionNumber) {
throw new Error('accessionNumber is required');
}
const snapshot = await getStoreSnapshot();
const filing = snapshot.filings.find((entry) => entry.accession_number === accessionNumber);
if (!filing) {
throw new Error(`Filing ${accessionNumber} not found`);
}
const prompt = [
'You are a fiscal research assistant focused on regulatory signals.',
`Analyze this SEC filing from ${filing.company_name} (${filing.ticker}).`,
`Form: ${filing.filing_type}`,
`Filed: ${filing.filing_date}`,
`Metrics: ${JSON.stringify(filing.metrics ?? {})}`,
'Return concise sections: Thesis, Red Flags, Follow-up Questions, Portfolio Impact.'
].join('\n');
const analysis = await runOpenClawAnalysis(prompt, 'Use concise institutional analyst language.');
await withStore((store) => {
const index = store.filings.findIndex((entry) => entry.accession_number === accessionNumber);
if (index < 0) {
return;
}
store.filings[index] = {
...store.filings[index],
analysis: {
provider: analysis.provider,
model: analysis.model,
text: analysis.text
},
updated_at: nowIso()
};
});
return {
accessionNumber,
provider: analysis.provider,
model: analysis.model
};
}
function holdingDigest(holdings: Holding[]) {
return holdings.map((holding) => ({
ticker: holding.ticker,
shares: holding.shares,
avgCost: holding.avg_cost,
currentPrice: holding.current_price,
marketValue: holding.market_value,
gainLoss: holding.gain_loss,
gainLossPct: holding.gain_loss_pct
}));
}
async function processPortfolioInsights() {
const snapshot = await getStoreSnapshot();
const summary = buildPortfolioSummary(snapshot.holdings);
const prompt = [
'Generate portfolio intelligence with actionable recommendations.',
`Portfolio summary: ${JSON.stringify(summary)}`,
`Holdings: ${JSON.stringify(holdingDigest(snapshot.holdings))}`,
'Respond with: 1) health score (0-100), 2) top 3 risks, 3) top 3 opportunities, 4) next actions in 7 days.'
].join('\n');
const analysis = await runOpenClawAnalysis(prompt, 'Act as a risk-aware buy-side analyst.');
const createdAt = nowIso();
await withStore((store) => {
store.counters.insights += 1;
const insight: PortfolioInsight = {
id: store.counters.insights,
user_id: 1,
provider: analysis.provider,
model: analysis.model,
content: analysis.text,
created_at: createdAt
};
store.insights.unshift(insight);
});
return {
provider: analysis.provider,
model: analysis.model,
summary
};
}
async function runTaskProcessor(task: Task) {
switch (task.task_type) {
case 'sync_filings':
return await processSyncFilings(task);
case 'refresh_prices':
return await processRefreshPrices();
case 'analyze_filing':
return await processAnalyzeFiling(task);
case 'portfolio_insights':
return await processPortfolioInsights();
default:
throw new Error(`Unsupported task type: ${task.task_type}`);
}
}
async function processTask(taskId: string) {
if (activeTaskRuns.has(taskId)) {
return;
}
activeTaskRuns.add(taskId);
try {
const task = await withStore((store) => {
const index = store.tasks.findIndex((entry) => entry.id === taskId);
if (index < 0) {
return null;
}
const target = store.tasks[index];
if (target.status !== 'queued') {
return null;
}
target.status = 'running';
target.attempts += 1;
target.updated_at = nowIso();
return { ...target };
});
if (!task) {
return;
}
try {
const result = toTaskResult(await runTaskProcessor(task));
await markTask(taskId, (target) => {
target.status = 'completed';
target.result = result;
target.error = null;
target.finished_at = nowIso();
});
} catch (error) {
const reason = error instanceof Error ? error.message : 'Task failed unexpectedly';
const shouldRetry = task.attempts < task.max_attempts;
if (shouldRetry) {
await markTask(taskId, (target) => {
target.status = 'queued';
target.error = reason;
});
queueTaskRun(taskId, 1200);
} else {
await markTask(taskId, (target) => {
target.status = 'failed';
target.error = reason;
target.finished_at = nowIso();
});
}
}
} finally {
activeTaskRuns.delete(taskId);
}
}
export async function enqueueTask(input: EnqueueTaskInput) {
const createdAt = nowIso();
const task: Task = {
id: randomUUID(),
task_type: input.taskType,
status: 'queued',
priority: input.priority ?? 50,
payload: input.payload ?? {},
result: null,
error: null,
attempts: 0,
max_attempts: input.maxAttempts ?? 3,
created_at: createdAt,
updated_at: createdAt,
finished_at: null
};
await withStore((store) => {
store.tasks.unshift(task);
store.tasks.sort((a, b) => {
if (a.priority !== b.priority) {
return b.priority - a.priority;
}
return Date.parse(b.created_at) - Date.parse(a.created_at);
});
});
queueTaskRun(task.id);
return task;
}
export async function getTaskById(taskId: string) {
const snapshot = await getStoreSnapshot();
return snapshot.tasks.find((task) => task.id === taskId) ?? null;
}
export async function listRecentTasks(limit = 20, statuses?: TaskStatus[]) {
const safeLimit = Math.min(Math.max(Math.trunc(limit), 1), 200);
const snapshot = await getStoreSnapshot();
const filtered = statuses && statuses.length > 0
? snapshot.tasks.filter((task) => statuses.includes(task.status))
: snapshot.tasks;
return filtered
.slice()
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at))
.slice(0, safeLimit);
}

View File

@@ -64,10 +64,11 @@ export type Filing = {
};
export type TaskStatus = 'queued' | 'running' | 'completed' | 'failed';
export type TaskType = 'sync_filings' | 'refresh_prices' | 'analyze_filing' | 'portfolio_insights';
export type Task = {
id: string;
task_type: 'sync_filings' | 'refresh_prices' | 'analyze_filing' | 'portfolio_insights';
task_type: TaskType;
status: TaskStatus;
priority: number;
payload: Record<string, unknown>;

View File

@@ -1,5 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

View File

@@ -2,8 +2,11 @@
const nextConfig = {
reactStrictMode: true,
output: 'standalone',
turbopack: {
root: __dirname
},
env: {
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || ''
},
async headers() {
return [

File diff suppressed because it is too large Load Diff

View File

@@ -3,13 +3,12 @@
"version": "2.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"dev": "next dev --turbopack",
"build": "next build --turbopack",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"better-auth": "^1.4.18",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"lucide-react": "^0.574.0",

View File

@@ -1,7 +1,11 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
@@ -11,7 +15,7 @@
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
@@ -19,9 +23,19 @@
}
],
"paths": {
"@/*": ["./*"]
"@/*": [
"./*"
]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}