Files
investor-flow/app/src/components/PortfolioPanel.tsx
T

188 lines
6.4 KiB
TypeScript
Raw Normal View History

"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 {
/** Called after holdings change so parents (e.g. Risk) can refresh posture. */
onChange?: (holdings: PortfolioHolding[]) => void;
/** When true, omit outer Card chrome (parent already provides a card). */
bare?: boolean;
}
/**
* Record open holdings (symbol / shares / avg cost). Feeds risk posture, not the watchlist.
* ADR-0007: user-owned records only - no trade instructions.
*/
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 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 totalValue = holdings.reduce((sum, h) => sum + h.shares * h.avg_cost, 0);
const body = (
<>
<p className="text-xs text-fg-muted mb-3">{UI_STRINGS.portfolioCaption}</p>
<p className="text-xs text-fg-faint mb-3">{UI_STRINGS.portfolioVsWatchlist}</p>
<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)}
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)}
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)}
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 />
</div>
{holdings.map((h) => (
<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"
>
<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={() => 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}
<p className="mt-4 text-[10px] text-fg-faint italic">{UI_STRINGS.primaryRuleFooter}</p>
</Card>
);
}