Files
investor-flow/app/src/components/PortfolioPanel.tsx
T
Investor Flow Build ac94acf9e3
CI / Test & Type-Check (push) Canceled after 0s
feat: dealer flow, mirror portfolio (M21), options convexity, FINRA short interest, alert producers, vendor gate
Snapshot of in-progress module work across multiple slices:

- Dealer Flow: dealerExposureEngine, dealerMapService, dealerMapExplain,
  dealerMapIntegrity, dealerMapReplay, dealerStudyEngine, hanStyleLevels
- Mirror Portfolio (M21): fundRepository, captureIngest, mirrorAlertProducers,
  fund holdings strip, live book, position capture ingest
- Options: BSM, NormalizedOptionSurface types, OptionsChainRouter,
  ConvexityGate, option legs panel
- Alert producers: vixLevel, rotation, thesis, unlock, portfolioRisk,
  mirror (fund_capture, fund_13f, mirror_diff)
- FINRA short interest adapter + queue integration
- SEC company tickers adapter + ingest (symbol search index seed)
- Vendor gate (rate-limit-first data plane, ADR-0009)
- CUSIP registry, reverse 13F refresh, stock float service
- LRU cache, portfolio backtest engine
- Frontend: dealer-flow, funds, journal, lab, monitor, plan, portfolio,
  reports, screener, strategies, theses, guided-start, exits, more pages
- Volume profile, workspace profile, visibility-aware poll
- ADRs 0010 (mirror math not advice), 0011 (symbol search index)
- VENDOR_INTEGRATIONS.md, END_USER_TEST.md
- .gitignore: exclude DBs, .DS_Store, local config, agent scratch
2026-08-10 13:36:26 -04:00

252 lines
8.6 KiB
TypeScript

"use client";
import { useCallback, useEffect, useState } from "react";
import { api, type PortfolioHolding } from "@/lib/trpc";
import { UI_STRINGS } from "@/lib/strings";
import { Card, CardHeader, Button, Input } from "@/components/ui";
export interface PortfolioPanelProps {
onChange?: (holdings: PortfolioHolding[]) => void;
bare?: boolean;
}
export function PortfolioPanel({ onChange, bare = false }: PortfolioPanelProps) {
const [holdings, setHoldings] = useState<PortfolioHolding[]>([]);
const [draftSymbol, setDraftSymbol] = useState("");
const [draftShares, setDraftShares] = useState("");
const [draftCost, setDraftCost] = useState("");
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [editing, setEditing] = useState<string | null>(null);
const [editShares, setEditShares] = useState("");
const [editCost, setEditCost] = useState("");
const load = useCallback(async (): Promise<PortfolioHolding[] | null> => {
try {
const next = await api.portfolio.holdings();
setHoldings(next);
setError(null);
return next;
} catch (e) {
setError(e instanceof Error ? e.message : "Could not load holdings.");
return null;
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
const notifyChange = (next: PortfolioHolding[]) => {
onChange?.(next);
};
const add = async () => {
const symbol = draftSymbol.trim().toUpperCase();
const shares = parseFloat(draftShares);
const avgCost = parseFloat(draftCost);
if (!symbol || !Number.isFinite(shares) || shares <= 0 || !Number.isFinite(avgCost) || avgCost < 0) {
setError("Symbol, positive share count, and average cost are required.");
return;
}
setBusy(true);
setError(null);
try {
await api.portfolio.addHolding(symbol, shares, avgCost);
setDraftSymbol("");
setDraftShares("");
setDraftCost("");
const next = await load();
if (next) notifyChange(next);
} catch (e) {
setError(e instanceof Error ? e.message : "Could not record holding.");
} finally {
setBusy(false);
}
};
const remove = async (symbol: string) => {
setBusy(true);
setError(null);
try {
await api.portfolio.removeHolding(symbol);
const next = await load();
if (next) notifyChange(next);
} catch (e) {
setError(e instanceof Error ? e.message : "Could not remove holding.");
} finally {
setBusy(false);
}
};
const startEdit = (h: PortfolioHolding) => {
setEditing(h.symbol);
setEditShares(String(h.shares));
setEditCost(String(h.avg_cost));
setError(null);
};
const cancelEdit = () => {
setEditing(null);
setEditShares("");
setEditCost("");
};
const saveEdit = async (symbol: string) => {
const shares = parseFloat(editShares);
const avgCost = parseFloat(editCost);
if (!Number.isFinite(shares) || shares <= 0 || !Number.isFinite(avgCost) || avgCost < 0) {
setError("Shares must be positive and avg cost must be 0 or more.");
return;
}
setBusy(true);
setError(null);
try {
await api.portfolio.updateHolding(symbol, { shares, avgCost });
setEditing(null);
const next = await load();
if (next) notifyChange(next);
} catch (e) {
setError(e instanceof Error ? e.message : "Could not update holding.");
} finally {
setBusy(false);
}
};
const totalValue = holdings.reduce((sum, h) => sum + h.shares * h.avg_cost, 0);
const body = (
<>
{UI_STRINGS.portfolioCaption ? (
<p className="text-xs text-fg-muted mb-3">{UI_STRINGS.portfolioCaption}</p>
) : null}
<div className="grid grid-cols-1 sm:grid-cols-4 gap-2">
<label className="block text-xs text-fg-muted sm:col-span-1">
Symbol
<Input
value={draftSymbol}
onChange={(e) => { setDraftSymbol(e.target.value); setError(null); }}
placeholder="e.g. AAPL"
className="mt-1"
disabled={busy}
/>
</label>
<label className="block text-xs text-fg-muted">
Shares
<Input
value={draftShares}
onChange={(e) => { setDraftShares(e.target.value); setError(null); }}
placeholder="100"
type="number"
className="mt-1"
disabled={busy}
/>
</label>
<label className="block text-xs text-fg-muted">
Avg cost ($)
<Input
value={draftCost}
onChange={(e) => { setDraftCost(e.target.value); setError(null); }}
placeholder="150.00"
type="number"
step="0.01"
className="mt-1"
disabled={busy}
/>
</label>
<div className="flex items-end">
<Button onClick={add} disabled={busy} className="w-full">
{busy ? "Saving…" : "Record holding"}
</Button>
</div>
</div>
{error && <p className="mt-3 text-sm text-danger">{error}</p>}
{loading ? (
<p className="mt-4 text-sm text-fg-faint">Loading holdings…</p>
) : holdings.length === 0 ? (
<p className="mt-4 text-sm text-fg-faint">{UI_STRINGS.emptyPortfolio}</p>
) : (
<div className="mt-4 space-y-2 max-h-72 overflow-y-auto">
<div className="grid grid-cols-[minmax(0,1fr)_4.5rem_5rem_5rem_4rem] gap-2 text-xs text-fg-faint pb-1 border-b border-line">
<span>Symbol</span>
<span className="text-right">Shares</span>
<span className="text-right">Avg cost</span>
<span className="text-right">Cost basis</span>
<span className="text-right" />
</div>
{holdings.map((h) => (
editing === h.symbol ? (
<div key={h.symbol} className="grid grid-cols-[minmax(0,1fr)_4.5rem_5rem_5rem_4rem] gap-2 items-center py-1.5 text-sm rounded bg-surface-sunken">
<span className="font-mono text-fg truncate">{h.symbol}</span>
<Input
value={editShares}
onChange={(e) => setEditShares(e.target.value)}
type="number"
className="text-right"
disabled={busy}
/>
<Input
value={editCost}
onChange={(e) => setEditCost(e.target.value)}
type="number"
step="0.01"
className="text-right"
disabled={busy}
/>
<span className="text-right tnum text-fg">
${(parseFloat(editShares || "0") * parseFloat(editCost || "0")).toFixed(0)}
</span>
<div className="flex gap-1 justify-end">
<Button size="sm" variant="ghost" onClick={() => saveEdit(h.symbol)} disabled={busy}>
Save
</Button>
<Button size="sm" variant="ghost" onClick={cancelEdit} disabled={busy}>
Cancel
</Button>
</div>
</div>
) : (
<div
key={h.symbol}
className="grid grid-cols-[minmax(0,1fr)_4.5rem_5rem_5rem_4rem] gap-2 items-center py-1.5 text-sm rounded hover:bg-surface-sunken transition-colors cursor-pointer"
onClick={() => startEdit(h)}
>
<span className="font-mono text-fg truncate">{h.symbol}</span>
<span className="text-right tnum text-fg-muted">{h.shares}</span>
<span className="text-right tnum text-fg-muted">${h.avg_cost.toFixed(2)}</span>
<span className="text-right tnum text-fg">${(h.shares * h.avg_cost).toFixed(0)}</span>
<button
type="button"
onClick={(e) => { e.stopPropagation(); remove(h.symbol); }}
disabled={busy}
className="text-xs text-fg-faint hover:text-danger text-right disabled:opacity-50"
>
Remove
</button>
</div>
)
))}
<div className="flex justify-between pt-2 border-t border-line text-sm font-semibold text-fg">
<span>Cost-basis total</span>
<span className="tnum">${totalValue.toFixed(0)}</span>
</div>
</div>
)}
</>
);
if (bare) return <div className="space-y-1">{body}</div>;
return (
<Card>
<CardHeader title={UI_STRINGS.portfolioTitle} />
{body}
</Card>
);
}