Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(frontend): Portfolio page through t() in all seven locales, theme-aware charts, error-source rendering

Haozhe Wu8eb86f0fcd30
diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsx
index 02552d269..fb6834df4 100644
--- a/frontend/src/components/layout/Layout.tsx
+++ b/frontend/src/components/layout/Layout.tsx
@@ -24,7 +24,7 @@ export function Layout() {
{ to: "/runtime", icon: Activity, label: t('layout.runtime') },
{ to: "/scheduled", icon: CalendarClock, label: t('layout.scheduled') },
{ to: "/reports", icon: FileText, label: t('layout.reports') },
- { to: "/portfolio", icon: WalletCards, label: t('layout.portfolio', { defaultValue: 'Portfolio' }) },
+ { to: "/portfolio", icon: WalletCards, label: t('layout.portfolio') },
{ to: "/alpha-zoo", icon: Layers, label: t('layout.alphaZoo') },
{ to: "/options", icon: CandlestickChart, label: t('layout.optionsLab') },
{ to: "/settings", icon: Settings, label: t('layout.settings') },
diff --git a/frontend/src/components/portfolio/ConnectionCenter.tsx b/frontend/src/components/portfolio/ConnectionCenter.tsx
index f6eff705c..9f2427ad1 100644
--- a/frontend/src/components/portfolio/ConnectionCenter.tsx
+++ b/frontend/src/components/portfolio/ConnectionCenter.tsx
@@ -1,17 +1,23 @@
import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
import { CheckCircle2, FolderCode, Loader2, PlugZap, Plus, ShieldCheck, Trash2, X } from "lucide-react";
import { api, type ConnectionsResponse, type LocalConnection } from "@/lib/api";
interface Props {
open: boolean;
- zh: boolean;
onClose: () => void;
onChanged: () => Promise<void>;
}
const fieldClass = "w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:border-primary focus:ring-2 focus:ring-primary/20";
-export function ConnectionCenter({ open, zh, onClose, onChanged }: Props) {
+/**
+ * Drawer for the connections that exist only on this computer: create one from
+ * a read-only profile template, store its secrets in the OS credential vault,
+ * test it, or delete it. Nothing here can place an order.
+ */
+export function ConnectionCenter({ open, onClose, onChanged }: Props) {
+ const { t } = useTranslation();
const [data, setData] = useState<ConnectionsResponse | null>(null);
const [profileId, setProfileId] = useState("");
const [connectionId, setConnectionId] = useState("");
@@ -54,7 +60,7 @@ export function ConnectionCenter({ open, zh, onClose, onChanged }: Props) {
setProfileId("");
setConnectionId("");
setLabel("");
- setMessage(zh ? "本地连接已创建。" : "Local connection created.");
+ setMessage(t("portfolio.connections.created"));
} catch (error) {
setMessage(error instanceof Error ? error.message : String(error));
} finally {
@@ -68,7 +74,7 @@ export function ConnectionCenter({ open, zh, onClose, onChanged }: Props) {
try {
const result = await api.checkConnection(connection.id);
const ok = result.report.status === "ok" || result.report.configured === true;
- setMessage(ok ? (zh ? `${connection.label} 连接正常。` : `${connection.label} is ready.`) : JSON.stringify(result.report));
+ setMessage(ok ? t("portfolio.connections.testOk", { label: connection.label }) : JSON.stringify(result.report));
} catch (error) {
setMessage(error instanceof Error ? error.message : String(error));
} finally {
@@ -95,32 +101,32 @@ export function ConnectionCenter({ open, zh, onClose, onChanged }: Props) {
return <div className="fixed inset-0 z-[60] flex justify-end bg-black/40" role="presentation">
<section className="flex h-full w-full max-w-2xl flex-col border-l bg-background shadow-2xl" role="dialog" aria-modal="true" aria-labelledby="connection-center-title">
<header className="flex items-start justify-between border-b p-5">
- <div><h2 id="connection-center-title" className="text-lg font-semibold">{zh ? "本地连接中心" : "Local connection center"}</h2><p className="mt-1 text-xs text-muted-foreground">{zh ? "连接定义保存在本机;密钥只进入系统钥匙串。" : "Definitions stay local; secrets go only to the OS credential vault."}</p></div>
- <button type="button" onClick={onClose} className="rounded-md p-2 hover:bg-muted" aria-label={zh ? "关闭连接中心" : "Close connection center"}><X className="h-4 w-4" /></button>
+ <div><h2 id="connection-center-title" className="text-lg font-semibold">{t("portfolio.connections.title")}</h2><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.connections.subtitle")}</p></div>
+ <button type="button" onClick={onClose} className="rounded-md p-2 hover:bg-muted" aria-label={t("portfolio.connections.close")}><X className="h-4 w-4" /></button>
</header>
<div className="flex-1 space-y-6 overflow-y-auto p-5">
{message ? <div className="rounded-md border bg-muted/30 p-3 text-xs break-words">{message}</div> : null}
<section className="rounded-xl border bg-card p-4">
- <div className="flex items-center gap-2"><Plus className="h-4 w-4 text-primary" /><h3 className="font-medium">{zh ? "创建账户连接" : "Create account connection"}</h3></div>
- <p className="mt-1 text-xs text-muted-foreground">{zh ? "Profile 是公开模板;连接是只属于这台电脑的账户实例。" : "A profile is a public template; a connection is private to this computer."}</p>
+ <div className="flex items-center gap-2"><Plus className="h-4 w-4 text-primary" /><h3 className="font-medium">{t("portfolio.connections.createTitle")}</h3></div>
+ <p className="mt-1 text-xs text-muted-foreground">{t("portfolio.connections.createHint")}</p>
<div className="mt-4 grid gap-3 sm:grid-cols-2">
- <label className="text-xs text-muted-foreground sm:col-span-2">{zh ? "只读连接模板" : "Read-only profile"}<select value={profileId} onChange={(event) => chooseProfile(event.target.value)} className={`mt-1 ${fieldClass}`}><option value="">{zh ? "选择模板…" : "Choose a profile…"}</option>{profiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.label}</option>)}</select></label>
- <label className="text-xs text-muted-foreground">{zh ? "本地连接 ID" : "Local connection ID"}<input value={connectionId} onChange={(event) => setConnectionId(event.target.value.toLowerCase())} className={`mt-1 ${fieldClass}`} placeholder="my-broker-live" /></label>
- <label className="text-xs text-muted-foreground">{zh ? "显示名称" : "Display name"}<input value={label} onChange={(event) => setLabel(event.target.value)} className={`mt-1 ${fieldClass}`} placeholder={zh ? "我的主账户" : "My main account"} /></label>
+ <label className="text-xs text-muted-foreground sm:col-span-2">{t("portfolio.connections.profile")}<select value={profileId} onChange={(event) => chooseProfile(event.target.value)} className={`mt-1 ${fieldClass}`}><option value="">{t("portfolio.connections.chooseProfile")}</option>{profiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.label}</option>)}</select></label>
+ <label className="text-xs text-muted-foreground">{t("portfolio.connections.localId")}<input value={connectionId} onChange={(event) => setConnectionId(event.target.value.toLowerCase())} className={`mt-1 ${fieldClass}`} placeholder="my-broker-live" /></label>
+ <label className="text-xs text-muted-foreground">{t("portfolio.connections.displayName")}<input value={label} onChange={(event) => setLabel(event.target.value)} className={`mt-1 ${fieldClass}`} placeholder={t("portfolio.connections.displayNamePlaceholder")} /></label>
</div>
- <button type="button" onClick={() => void create()} disabled={!profileId || busy === "create"} className="mt-3 inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-40">{busy === "create" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}{zh ? "创建本地连接" : "Create connection"}</button>
+ <button type="button" onClick={() => void create()} disabled={!profileId || busy === "create"} className="mt-3 inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-40">{busy === "create" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}{t("portfolio.connections.create")}</button>
</section>
<section>
- <div className="flex items-end justify-between"><div><h3 className="font-medium">{zh ? "这台电脑上的连接" : "Connections on this computer"}</h3><p className="mt-1 text-xs text-muted-foreground">{data?.connections.length ?? 0} {zh ? "个连接" : "connections"}</p></div><ShieldCheck className="h-5 w-5 text-positive" /></div>
- <div className="mt-3 space-y-3">{data?.connections.map((connection) => <ConnectionCard key={connection.id} connection={connection} zh={zh} busy={busy} onTest={test} onDelete={remove} onSaved={async () => { await load(); await onChanged(); }} setBusy={setBusy} setMessage={setMessage} />)}{data && !data.connections.length ? <div className="rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground">{zh ? "还没有本地连接" : "No local connections yet"}</div> : null}</div>
+ <div className="flex items-end justify-between"><div><h3 className="font-medium">{t("portfolio.connections.listTitle")}</h3><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.connections.listCount", { count: data?.connections.length ?? 0 })}</p></div><ShieldCheck className="h-5 w-5 text-positive" /></div>
+ <div className="mt-3 space-y-3">{data?.connections.map((connection) => <ConnectionCard key={connection.id} connection={connection} busy={busy} onTest={test} onDelete={remove} onSaved={async () => { await load(); await onChanged(); }} setBusy={setBusy} setMessage={setMessage} />)}{data && !data.connections.length ? <div className="rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground">{t("portfolio.connections.empty")}</div> : null}</div>
</section>
<section className="rounded-xl border border-dashed p-4">
- <div className="flex items-center gap-2"><FolderCode className="h-4 w-4" /><h3 className="font-medium">{zh ? "让 Codex 接入新券商" : "Add a broker with Codex"}</h3></div>
- <p className="mt-2 text-xs leading-5 text-muted-foreground">{zh ? "让 Codex 运行 connector init,根据券商官方文档补全只读 adapter,通过 validate 后 install。插件安装在下面的本机目录,不进入项目仓库。" : "Ask Codex to run connector init, implement the read adapter from official docs, validate it, then install it. The plugin stays outside the repository."}</p>
+ <div className="flex items-center gap-2"><FolderCode className="h-4 w-4" /><h3 className="font-medium">{t("portfolio.connections.codexTitle")}</h3></div>
+ <p className="mt-2 text-xs leading-5 text-muted-foreground">{t("portfolio.connections.codexBody")}</p>
<code className="mt-3 block overflow-x-auto rounded-md bg-muted p-3 text-xs">{data?.plugin_directory ?? "~/.vibe-trading/connectors"}</code>
</section>
</div>
@@ -128,7 +134,8 @@ export function ConnectionCenter({ open, zh, onClose, onChanged }: Props) {
</div>;
}
-function ConnectionCard({ connection, zh, busy, onTest, onDelete, onSaved, setBusy, setMessage }: { connection: LocalConnection; zh: boolean; busy: string | null; onTest: (connection: LocalConnection) => Promise<void>; onDelete: (connection: LocalConnection) => Promise<void>; onSaved: () => Promise<void>; setBusy: (value: string | null) => void; setMessage: (value: string | null) => void }) {
+function ConnectionCard({ connection, busy, onTest, onDelete, onSaved, setBusy, setMessage }: { connection: LocalConnection; busy: string | null; onTest: (connection: LocalConnection) => Promise<void>; onDelete: (connection: LocalConnection) => Promise<void>; onSaved: () => Promise<void>; setBusy: (value: string | null) => void; setMessage: (value: string | null) => void }) {
+ const { t } = useTranslation();
const [values, setValues] = useState<Record<string, string>>({});
async function saveCredentials() {
setBusy(`credentials:${connection.id}`);
@@ -137,7 +144,7 @@ function ConnectionCard({ connection, zh, busy, onTest, onDelete, onSaved, setBu
await api.saveConnectionCredentials(connection.id, values);
setValues({});
await onSaved();
- setMessage(zh ? "凭证已保存到系统钥匙串。" : "Credentials saved to the OS vault.");
+ setMessage(t("portfolio.connections.savedVault"));
} catch (error) {
setMessage(error instanceof Error ? error.message : String(error));
} finally {
@@ -145,9 +152,9 @@ function ConnectionCard({ connection, zh, busy, onTest, onDelete, onSaved, setBu
}
}
return <article className="rounded-xl border bg-card p-4">
- <div className="flex items-start justify-between gap-3"><div><div className="font-medium">{connection.label}</div><div className="mt-1 flex flex-wrap gap-2 text-xs text-muted-foreground"><span>{connection.connector.toUpperCase()}</span><span>·</span><span>{connection.environment === "live" ? (zh ? "实盘" : "Live") : (zh ? "模拟" : "Paper")}</span><span>·</span><span>{connection.transport}</span></div></div><span className="inline-flex items-center gap-1 rounded-full bg-positive/10 px-2 py-1 text-xs text-positive"><ShieldCheck className="h-3 w-3" />{zh ? "结构只读" : "Read-only"}</span></div>
- {connection.credential_fields.length ? <div className="mt-4 grid gap-2 sm:grid-cols-2">{connection.credential_fields.map((field) => <label key={field.name} className="text-xs text-muted-foreground">{field.label}{connection.credential_status[field.name] ? <span className="ml-1 text-positive">{zh ? "已保存" : "saved"}</span> : null}<input type={field.secret ? "password" : "text"} value={values[field.name] ?? ""} onChange={(event) => setValues((current) => ({ ...current, [field.name]: event.target.value }))} className={`mt-1 ${fieldClass}`} placeholder={connection.credential_status[field.name] ? "••••••••" : ""} autoComplete="off" /></label>)}</div> : <p className="mt-3 text-xs text-muted-foreground">{connection.transport === "remote_mcp" ? (zh ? "使用 OAuth;需要时通过重新连接完成授权。" : "Uses OAuth; authorize through reconnect when required.") : (zh ? "凭证由现有连接器本地配置管理。" : "Credentials are managed by the existing local connector configuration.")}</p>}
- <div className="mt-4 flex flex-wrap gap-2">{connection.credential_fields.length ? <button type="button" onClick={() => void saveCredentials()} disabled={busy === `credentials:${connection.id}` || !Object.values(values).some(Boolean)} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-40"><ShieldCheck className="h-3.5 w-3.5" />{zh ? "保存到钥匙串" : "Save to vault"}</button> : null}<button type="button" onClick={() => void onTest(connection)} disabled={busy === `test:${connection.id}`} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs">{busy === `test:${connection.id}` ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <PlugZap className="h-3.5 w-3.5" />}{zh ? "测试连接" : "Test"}</button><button type="button" onClick={() => void onDelete(connection)} disabled={busy === `delete:${connection.id}`} className="ml-auto inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs text-danger hover:bg-danger/10"><Trash2 className="h-3.5 w-3.5" />{zh ? "删除" : "Delete"}</button></div>
- {connection.credentials_configured ? <div className="mt-3 flex items-center gap-1.5 text-xs text-positive"><CheckCircle2 className="h-3.5 w-3.5" />{zh ? "所需凭证已配置" : "Required credentials configured"}</div> : null}
+ <div className="flex items-start justify-between gap-3"><div><div className="font-medium">{connection.label}</div><div className="mt-1 flex flex-wrap gap-2 text-xs text-muted-foreground"><span>{connection.connector.toUpperCase()}</span><span>·</span><span>{connection.environment === "live" ? t("portfolio.env.live") : t("portfolio.env.paper")}</span><span>·</span><span>{connection.transport}</span></div></div><span className="inline-flex items-center gap-1 rounded-full bg-positive/10 px-2 py-1 text-xs text-positive"><ShieldCheck className="h-3 w-3" />{t("portfolio.connections.readOnly")}</span></div>
+ {connection.credential_fields.length ? <div className="mt-4 grid gap-2 sm:grid-cols-2">{connection.credential_fields.map((field) => <label key={field.name} className="text-xs text-muted-foreground">{field.label}{connection.credential_status[field.name] ? <span className="ml-1 text-positive">{t("portfolio.connections.credentialSaved")}</span> : null}<input type={field.secret ? "password" : "text"} value={values[field.name] ?? ""} onChange={(event) => setValues((current) => ({ ...current, [field.name]: event.target.value }))} className={`mt-1 ${fieldClass}`} placeholder={connection.credential_status[field.name] ? "••••••••" : ""} autoComplete="off" /></label>)}</div> : <p className="mt-3 text-xs text-muted-foreground">{connection.transport === "remote_mcp" ? t("portfolio.connections.oauthNote") : t("portfolio.connections.localNote")}</p>}
+ <div className="mt-4 flex flex-wrap gap-2">{connection.credential_fields.length ? <button type="button" onClick={() => void saveCredentials()} disabled={busy === `credentials:${connection.id}` || !Object.values(values).some(Boolean)} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-40"><ShieldCheck className="h-3.5 w-3.5" />{t("portfolio.connections.saveVault")}</button> : null}<button type="button" onClick={() => void onTest(connection)} disabled={busy === `test:${connection.id}`} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs">{busy === `test:${connection.id}` ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <PlugZap className="h-3.5 w-3.5" />}{t("portfolio.connections.test")}</button><button type="button" onClick={() => void onDelete(connection)} disabled={busy === `delete:${connection.id}`} className="ml-auto inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs text-danger hover:bg-danger/10"><Trash2 className="h-3.5 w-3.5" />{t("portfolio.connections.delete")}</button></div>
+ {connection.credentials_configured ? <div className="mt-3 flex items-center gap-1.5 text-xs text-positive"><CheckCircle2 className="h-3.5 w-3.5" />{t("portfolio.connections.configured")}</div> : null}
</article>;
}
diff --git a/frontend/src/components/portfolio/PortfolioSourceEditor.tsx b/frontend/src/components/portfolio/PortfolioSourceEditor.tsx
index e5aa66089..e12fad0ac 100644
--- a/frontend/src/components/portfolio/PortfolioSourceEditor.tsx
+++ b/frontend/src/components/portfolio/PortfolioSourceEditor.tsx
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
import { ArrowDown, ArrowUp, Plus, Save, Trash2, X } from "lucide-react";
import { ConnectionCenter } from "@/components/portfolio/ConnectionCenter";
import type {
@@ -12,7 +13,6 @@ interface Props {
settings: PortfolioSettings | null;
catalog: PortfolioSourceCatalogItem[];
saving: boolean;
- zh: boolean;
onClose: () => void;
onSave: (settings: PortfolioSettings) => Promise<void>;
onConnectionsChanged: () => Promise<void>;
@@ -20,7 +20,13 @@ interface Props {
const fieldClass = "w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:border-primary focus:ring-2 focus:ring-primary/20";
-export function PortfolioSourceEditor({ open, settings, catalog, saving, zh, onClose, onSave, onConnectionsChanged }: Props) {
+/**
+ * Drawer that edits which local read-only connections feed the portfolio and
+ * how they are displayed. It never collects or stores credentials — those live
+ * in the connection center and, ultimately, in the OS credential vault.
+ */
+export function PortfolioSourceEditor({ open, settings, catalog, saving, onClose, onSave, onConnectionsChanged }: Props) {
+ const { t } = useTranslation();
const [draft, setDraft] = useState<PortfolioSettings | null>(settings);
const [connectionToAdd, setConnectionToAdd] = useState("");
const [connectionCenterOpen, setConnectionCenterOpen] = useState(false);
@@ -87,36 +93,39 @@ export function PortfolioSourceEditor({ open, settings, catalog, saving, zh, onC
return <div className="fixed inset-0 z-50 flex justify-end bg-black/35" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>
<section className="flex h-full w-full max-w-xl flex-col border-l bg-background shadow-2xl" role="dialog" aria-modal="true" aria-labelledby="portfolio-source-editor-title">
<header className="flex items-start justify-between border-b p-5">
- <div><h2 id="portfolio-source-editor-title" className="text-lg font-semibold">{zh ? "管理持仓账户" : "Manage portfolio accounts"}</h2><p className="mt-1 text-xs text-muted-foreground">{zh ? "这里只保存账户选择和显示偏好,不保存密钥。" : "Only account selection and display preferences are stored here."}</p></div>
- <button type="button" onClick={onClose} className="rounded-md p-2 hover:bg-muted" aria-label={zh ? "关闭" : "Close"}><X className="h-4 w-4" /></button>
+ <div><h2 id="portfolio-source-editor-title" className="text-lg font-semibold">{t("portfolio.editor.title")}</h2><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.editor.subtitle")}</p></div>
+ <button type="button" onClick={onClose} className="rounded-md p-2 hover:bg-muted" aria-label={t("portfolio.editor.close")}><X className="h-4 w-4" /></button>
</header>
<div className="flex-1 space-y-6 overflow-y-auto p-5">
- <fieldset><legend className="text-sm font-medium">{zh ? "主要显示货币" : "Primary display currency"}</legend><div className="mt-2 grid grid-cols-2 gap-2">{(["USD", "CNY"] as const).map((currency) => <button key={currency} type="button" onClick={() => setDraft({ ...draft, display_currency: currency })} className={`rounded-md border px-3 py-2 text-sm ${draft.display_currency === currency ? "border-primary bg-primary/5 text-primary" : "bg-card"}`}>{currency}</button>)}</div></fieldset>
+ <fieldset><legend className="text-sm font-medium">{t("portfolio.editor.currency")}</legend><div className="mt-2 grid grid-cols-2 gap-2">{(["USD", "CNY"] as const).map((currency) => <button key={currency} type="button" onClick={() => setDraft({ ...draft, display_currency: currency })} className={`rounded-md border px-3 py-2 text-sm ${draft.display_currency === currency ? "border-primary bg-primary/5 text-primary" : "bg-card"}`}>{currency}</button>)}</div></fieldset>
<section>
- <div className="flex items-end justify-between gap-3"><div><h3 className="text-sm font-medium">{zh ? "已添加账户" : "Selected accounts"}</h3><p className="mt-1 text-xs text-muted-foreground">{zh ? "拖动顺序的替代操作:使用上下箭头。" : "Use the arrow buttons to change display order."}</p></div><span className="text-xs text-muted-foreground">{draft.sources.length}</span></div>
+ <div className="flex items-end justify-between gap-3"><div><h3 className="text-sm font-medium">{t("portfolio.editor.selected")}</h3><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.editor.selectedHint")}</p></div><span className="text-xs text-muted-foreground">{draft.sources.length}</span></div>
<div className="mt-3 space-y-3">
{draft.sources.map((source, index) => {
const connection = catalog.find((item) => item.connection_id === source.connection_id);
return <article key={source.connection_id} className="rounded-lg border bg-card p-4">
<div className="flex items-start gap-3">
- <input type="checkbox" checked={source.enabled} onChange={(event) => updateSource(index, { enabled: event.target.checked })} className="mt-2 h-4 w-4 accent-primary" aria-label={zh ? "启用账户" : "Enable account"} />
- <div className="min-w-0 flex-1"><input value={source.label} onChange={(event) => updateSource(index, { label: event.target.value })} className={fieldClass} aria-label={zh ? "账户名称" : "Account label"} /><div className="mt-2 flex flex-wrap gap-2 text-xs text-muted-foreground"><span>{connection?.connector.toUpperCase()}</span><span>·</span><span>{connection?.environment === "live" ? (zh ? "实盘" : "Live") : (zh ? "模拟" : "Paper")}</span><span>·</span><span>{connection?.transport}</span></div></div>
- <div className="flex gap-1"><button type="button" onClick={() => move(index, -1)} disabled={index === 0} className="rounded p-1.5 hover:bg-muted disabled:opacity-30" aria-label={zh ? "上移" : "Move up"}><ArrowUp className="h-4 w-4" /></button><button type="button" onClick={() => move(index, 1)} disabled={index === draft.sources.length - 1} className="rounded p-1.5 hover:bg-muted disabled:opacity-30" aria-label={zh ? "下移" : "Move down"}><ArrowDown className="h-4 w-4" /></button><button type="button" onClick={() => remove(index)} className="rounded p-1.5 text-danger hover:bg-danger/10" aria-label={zh ? "删除账户" : "Remove account"}><Trash2 className="h-4 w-4" /></button></div>
+ <input type="checkbox" checked={source.enabled} onChange={(event) => updateSource(index, { enabled: event.target.checked })} className="mt-2 h-4 w-4 accent-primary" aria-label={t("portfolio.editor.enableAccount")} />
+ <div className="min-w-0 flex-1"><input value={source.label} onChange={(event) => updateSource(index, { label: event.target.value })} className={fieldClass} aria-label={t("portfolio.editor.accountLabel")} /><div className="mt-2 flex flex-wrap gap-2 text-xs text-muted-foreground"><span>{connection?.connector.toUpperCase()}</span><span>·</span><span>{connection?.environment === "live" ? t("portfolio.env.live") : t("portfolio.env.paper")}</span><span>·</span><span>{connection?.transport}</span></div></div>
+ <div className="flex gap-1"><button type="button" onClick={() => move(index, -1)} disabled={index === 0} className="rounded p-1.5 hover:bg-muted disabled:opacity-30" aria-label={t("portfolio.editor.moveUp")}><ArrowUp className="h-4 w-4" /></button><button type="button" onClick={() => move(index, 1)} disabled={index === draft.sources.length - 1} className="rounded p-1.5 hover:bg-muted disabled:opacity-30" aria-label={t("portfolio.editor.moveDown")}><ArrowDown className="h-4 w-4" /></button><button type="button" onClick={() => remove(index)} className="rounded p-1.5 text-danger hover:bg-danger/10" aria-label={t("portfolio.editor.removeAccount")}><Trash2 className="h-4 w-4" /></button></div>
</div>
- <label className="mt-3 flex items-center gap-2 text-xs text-muted-foreground"><input type="checkbox" checked={source.include_cash} onChange={(event) => updateSource(index, { include_cash: event.target.checked })} className="h-4 w-4 accent-primary" />{zh ? "计入该账户现金" : "Include this account's cash"}</label>
+ <label className="mt-3 flex items-center gap-2 text-xs text-muted-foreground"><input type="checkbox" checked={source.include_cash} onChange={(event) => updateSource(index, { include_cash: event.target.checked })} className="h-4 w-4 accent-primary" />{t("portfolio.editor.includeCash")}</label>
</article>;
})}
- {!draft.sources.length ? <div className="rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground">{zh ? "还没有添加账户" : "No accounts selected"}</div> : null}
+ {!draft.sources.length ? <div className="rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground">{t("portfolio.editor.noAccounts")}</div> : null}
</div>
</section>
- <section><div className="flex items-end justify-between gap-3"><div><h3 className="text-sm font-medium">{zh ? "添加本地只读连接" : "Add a local read-only connection"}</h3><p className="mt-1 text-xs text-muted-foreground">{zh ? "这里只选择已经在这台电脑上创建的连接。" : "Choose from connections already created on this computer."}</p></div><button type="button" onClick={() => setConnectionCenterOpen(true)} className="shrink-0 text-xs text-primary">{zh ? "打开连接中心" : "Open connection center"}</button></div><div className="mt-3 flex gap-2"><select value={connectionToAdd} onChange={(event) => setConnectionToAdd(event.target.value)} className={fieldClass} disabled={!available.length}><option value="">{available.length ? (zh ? "选择连接…" : "Choose a connection…") : (zh ? "没有可添加的连接" : "No available connections")}</option>{available.map((connection) => <option key={connection.connection_id} value={connection.connection_id}>{connection.label}</option>)}</select><button type="button" onClick={add} disabled={!available.length} className="inline-flex shrink-0 items-center gap-2 rounded-md border px-3 py-2 text-sm disabled:opacity-40"><Plus className="h-4 w-4" />{zh ? "添加" : "Add"}</button></div></section>
+ <section>
+ <div className="flex items-end justify-between gap-3"><div><h3 className="text-sm font-medium">{t("portfolio.editor.addTitle")}</h3><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.editor.addHint")}</p></div><button type="button" onClick={() => setConnectionCenterOpen(true)} className="shrink-0 text-xs text-primary">{t("portfolio.editor.openConnections")}</button></div>
+ <div className="mt-3 flex gap-2"><select value={connectionToAdd} onChange={(event) => setConnectionToAdd(event.target.value)} className={fieldClass} aria-label={t("portfolio.editor.addTitle")} disabled={!available.length}><option value="">{available.length ? t("portfolio.editor.chooseConnection") : t("portfolio.editor.noConnections")}</option>{available.map((connection) => <option key={connection.connection_id} value={connection.connection_id}>{connection.label}</option>)}</select><button type="button" onClick={add} disabled={!available.length} className="inline-flex shrink-0 items-center gap-2 rounded-md border px-3 py-2 text-sm disabled:opacity-40"><Plus className="h-4 w-4" />{t("portfolio.editor.add")}</button></div>
+ </section>
</div>
- <footer className="flex items-center justify-between gap-3 border-t p-5"><p className="text-xs text-muted-foreground">{zh ? "保存后将刷新已启用账户。" : "Enabled accounts refresh after saving."}</p><div className="flex gap-2"><button type="button" onClick={onClose} className="rounded-md border px-4 py-2 text-sm">{zh ? "取消" : "Cancel"}</button><button type="button" disabled={saving} onClick={() => void onSave({ ...draft, sources: draft.sources.map((source, order) => ({ ...source, order })) })} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"><Save className="h-4 w-4" />{saving ? (zh ? "保存中" : "Saving") : (zh ? "保存并刷新" : "Save and refresh")}</button></div></footer>
+ <footer className="flex items-center justify-between gap-3 border-t p-5"><p className="text-xs text-muted-foreground">{t("portfolio.editor.footerHint")}</p><div className="flex gap-2"><button type="button" onClick={onClose} className="rounded-md border px-4 py-2 text-sm">{t("portfolio.editor.cancel")}</button><button type="button" disabled={saving} onClick={() => void onSave({ ...draft, sources: draft.sources.map((source, order) => ({ ...source, order })) })} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"><Save className="h-4 w-4" />{saving ? t("portfolio.editor.saving") : t("portfolio.editor.save")}</button></div></footer>
</section>
- <ConnectionCenter open={connectionCenterOpen} zh={zh} onClose={() => setConnectionCenterOpen(false)} onChanged={onConnectionsChanged} />
+ <ConnectionCenter open={connectionCenterOpen} onClose={() => setConnectionCenterOpen(false)} onChanged={onConnectionsChanged} />
</div>;
}
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index 77e1706e9..3a7669a7c 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -1408,5 +1408,151 @@
"loading": "جارٍ تحميل نتائج تحليل العوامل…",
"error": "تعذّر تحميل نتائج تحليل العوامل",
"noFactorData": "لا تتوفر نتائج تحليل عوامل لهذا التشغيل."
+ },
+ "portfolio": {
+ "page": {
+ "badge": "محلي للقراءة فقط · حسابات متعددة",
+ "title": "المحفظة",
+ "subtitle": "تقييم واحد يجمع كل الاتصالات المفعّلة للقراءة فقط. الحساب الذي يتعذّر قراءته يظهر كخطأ ولا يُحتسب ضمن الإجماليات.",
+ "fxFresh": "USD/CNY {{rate}} · سعر حي",
+ "fxCached": "USD/CNY {{rate}} · سعر مخزّن",
+ "manageAccounts": "إدارة الحسابات",
+ "exportCsv": "تصدير CSV",
+ "refreshAll": "تحديث الكل",
+ "refreshing": "جارٍ التحديث",
+ "warningsTitle": "ملاحظات على البيانات",
+ "emptyTitle": "لا توجد لقطة للمحفظة بعد",
+ "emptyBody": "أضف حسابًا واحدًا على الأقل للقراءة فقط لبدء التجميع.",
+ "emptyAction": "إضافة حساب",
+ "errorLoad": "تعذّر عرض المحفظة",
+ "errorRefresh": "فشل التحديث",
+ "errorReconnect": "فشلت إعادة ربط الحساب",
+ "errorSaveSettings": "تعذّر حفظ إعدادات المحفظة",
+ "errorExport": "فشل التصدير"
+ },
+ "metrics": {
+ "total": "إجمالي الأصول",
+ "change": "تغيّر الأصول اليوم",
+ "changeNote": "يشمل حركة السوق والإيداعات والسحوبات",
+ "coverage": "تغطية التقييم",
+ "coverageNote": "مُسعَّر {{priced}} · نقد {{cash}}",
+ "lastComplete": "آخر تحديث كامل",
+ "excluded": "تعذّرت قراءة {{count}} حسابات، وهي مستثناة من هذا الإجمالي"
+ },
+ "allocation": {
+ "byAccount": "التوزيع حسب الحساب",
+ "byHolding": "التوزيع حسب الأصل",
+ "center": "نسب الحيازات",
+ "other": "حيازات أخرى",
+ "cash": "نقد",
+ "unpriced": "غير مُسعَّر / أخرى",
+ "cashUnpriced": "نقد / غير مُسعَّر"
+ },
+ "accounts": {
+ "title": "حالة الحسابات",
+ "hint": "اضغط على حساب لتصفية الحيازات أدناه",
+ "clearFilter": "مسح التصفية",
+ "positions": "{{count}} مركزًا",
+ "fresh": "تمت القراءة بنجاح",
+ "failed": "تعذّرت قراءته — غير محتسب في الإجمالي",
+ "lastSuccess": "آخر قراءة ناجحة {{time}}",
+ "noSuccess": "لا توجد قراءة ناجحة بعد",
+ "reconnect": "إعادة الاتصال"
+ },
+ "holdings": {
+ "title": "تفاصيل الحيازات",
+ "count": "{{count}} مركزًا",
+ "search": "ابحث عن وسيط أو رمز أو سوق",
+ "colBroker": "الحساب",
+ "colSymbol": "الرمز",
+ "colType": "النوع",
+ "colQuantity": "الكمية",
+ "colCostPrice": "التكلفة / السعر",
+ "colValue": "القيمة",
+ "colWeight": "الوزن",
+ "colPnl": "أرباح/خسائر غير محققة",
+ "colData": "البيانات",
+ "priced": "مُسعَّر",
+ "unpriced": "غير مُسعَّر"
+ },
+ "history": {
+ "title": "تاريخ الأصول",
+ "hint": "تُعرض اللقطات الكاملة فقط، وقد يشمل التغيّر إيداعات وسحوبات.",
+ "count": "{{count}} لقطة كاملة",
+ "empty": "يبدأ السجل بعد أول تحديث كامل"
+ },
+ "credentials": {
+ "title": "الاتصالات وبيانات الاعتماد",
+ "readOnlyProfile": "ملف للقراءة فقط",
+ "writableProfile": "ملف يسمح بالكتابة",
+ "renewalAutomatic": "تجديد يديره الموصل",
+ "renewalSession": "يعتمد على جلسة محلية",
+ "renewalProvider": "المزوّد يدير مدة الصلاحية"
+ },
+ "status": {
+ "title": "جارٍ قراءة الحسابات المفعّلة تباعًا",
+ "reading": "قيد القراءة",
+ "done": "تم",
+ "failed": "فشل",
+ "waiting": "بالانتظار"
+ },
+ "env": {
+ "live": "حي",
+ "paper": "ورقي"
+ },
+ "editor": {
+ "title": "إدارة حسابات المحفظة",
+ "subtitle": "يُحفظ هنا اختيار الحسابات وتفضيلات العرض فقط، دون أي بيانات اعتماد.",
+ "close": "إغلاق",
+ "currency": "عملة العرض الأساسية",
+ "selected": "الحسابات المضافة",
+ "selectedHint": "استخدم سهمي الأعلى والأسفل لتغيير ترتيب العرض.",
+ "enableAccount": "تفعيل الحساب",
+ "accountLabel": "اسم الحساب",
+ "moveUp": "تحريك لأعلى",
+ "moveDown": "تحريك لأسفل",
+ "removeAccount": "إزالة الحساب",
+ "includeCash": "احتساب نقد هذا الحساب",
+ "noAccounts": "لم يتم اختيار أي حساب",
+ "addTitle": "إضافة اتصال محلي للقراءة فقط",
+ "addHint": "اختر من الاتصالات المنشأة مسبقًا على هذا الحاسوب.",
+ "openConnections": "فتح مركز الاتصالات",
+ "chooseConnection": "اختر اتصالًا…",
+ "noConnections": "لا توجد اتصالات متاحة",
+ "add": "إضافة",
+ "footerHint": "بعد الحفظ يتم تحديث الحسابات المفعّلة.",
+ "cancel": "إلغاء",
+ "save": "حفظ وتحديث",
+ "saving": "جارٍ الحفظ"
+ },
+ "connections": {
+ "title": "مركز الاتصالات المحلية",
+ "subtitle": "تبقى التعريفات على هذا الجهاز، والأسرار تذهب فقط إلى خزنة اعتمادات النظام.",
+ "close": "إغلاق مركز الاتصالات",
+ "createTitle": "إنشاء اتصال حساب",
+ "createHint": "الملف قالب عام، أما الاتصال فخاص بهذا الحاسوب وحده.",
+ "profile": "ملف للقراءة فقط",
+ "chooseProfile": "اختر ملفًا…",
+ "localId": "معرّف الاتصال المحلي",
+ "displayName": "الاسم المعروض",
+ "displayNamePlaceholder": "حسابي الرئيسي",
+ "create": "إنشاء اتصال",
+ "created": "تم إنشاء الاتصال المحلي.",
+ "listTitle": "الاتصالات على هذا الحاسوب",
+ "listCount": "{{count}} اتصالات",
+ "empty": "لا توجد اتصالات محلية بعد",
+ "codexTitle": "أضف وسيطًا بمساعدة Codex",
+ "codexBody": "اطلب من Codex تشغيل connector init، ثم كتابة موصل القراءة اعتمادًا على وثائق الوسيط الرسمية، واجتياز validate قبل install. تبقى الإضافة خارج مستودع المشروع.",
+ "readOnly": "للقراءة فقط",
+ "credentialSaved": "محفوظ",
+ "oauthNote": "يستخدم OAuth؛ امنح التفويض عبر إعادة الاتصال عند الحاجة.",
+ "localNote": "تدير بيانات الاعتماد إعدادات الموصل المحلي الحالية.",
+ "saveVault": "حفظ في الخزنة",
+ "savedVault": "حُفظت بيانات الاعتماد في خزنة النظام.",
+ "test": "اختبار",
+ "testOk": "{{label}} جاهز.",
+ "delete": "حذف",
+ "configured": "بيانات الاعتماد المطلوبة مضبوطة"
+ }
}
}
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index a98e8305a..83462a3fa 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -32,7 +32,8 @@
"skipToMain": "Zum Hauptinhalt springen",
"sidebar": "Vibe-Trading-Seitenleiste",
"mainNavigation": "Hauptnavigation",
- "about": "Über"
+ "about": "Über",
+ "portfolio": "Portfolio"
},
"runtime": {
"monitorBadge": "Runtime-Monitor",
@@ -1407,5 +1408,151 @@
"loading": "Faktor-Ergebnisse werden geladen…",
"error": "Faktor-Ergebnisse konnten nicht geladen werden",
"noFactorData": "Für diesen Lauf sind keine Faktor-Analyseergebnisse verfügbar."
+ },
+ "portfolio": {
+ "page": {
+ "badge": "Lokal & schreibgeschützt · Mehrere Konten",
+ "title": "Portfolio",
+ "subtitle": "Eine Bewertung über alle aktivierten schreibgeschützten Verbindungen. Ein Konto, das nicht gelesen werden kann, wird als Fehler gemeldet und bleibt aus den Summen heraus.",
+ "fxFresh": "USD/CNY {{rate}} · aktueller Kurs",
+ "fxCached": "USD/CNY {{rate}} · zwischengespeicherter Kurs",
+ "manageAccounts": "Konten verwalten",
+ "exportCsv": "CSV exportieren",
+ "refreshAll": "Alle aktualisieren",
+ "refreshing": "Wird aktualisiert",
+ "warningsTitle": "Hinweise zu den Daten",
+ "emptyTitle": "Noch kein Portfolio-Snapshot",
+ "emptyBody": "Fügen Sie mindestens ein schreibgeschütztes Konto hinzu, um zu beginnen.",
+ "emptyAction": "Konto hinzufügen",
+ "errorLoad": "Portfolio nicht verfügbar",
+ "errorRefresh": "Aktualisierung fehlgeschlagen",
+ "errorReconnect": "Erneutes Verbinden des Kontos fehlgeschlagen",
+ "errorSaveSettings": "Portfolio-Einstellungen konnten nicht gespeichert werden",
+ "errorExport": "Export fehlgeschlagen"
+ },
+ "metrics": {
+ "total": "Gesamtvermögen",
+ "change": "Heutige Vermögensänderung",
+ "changeNote": "Enthält Marktbewegungen sowie Ein- und Auszahlungen",
+ "coverage": "Bewertungsabdeckung",
+ "coverageNote": "Bewertet {{priced}} · Bargeld {{cash}}",
+ "lastComplete": "Letzte vollständige Aktualisierung",
+ "excluded": "{{count}} Konten konnten nicht gelesen werden und fehlen in dieser Summe"
+ },
+ "allocation": {
+ "byAccount": "Aufteilung nach Konto",
+ "byHolding": "Aufteilung nach Position",
+ "center": "Positionen",
+ "other": "Weitere Positionen",
+ "cash": "Bargeld",
+ "unpriced": "Ohne Kurs / Sonstiges",
+ "cashUnpriced": "Bargeld / ohne Kurs"
+ },
+ "accounts": {
+ "title": "Kontostatus",
+ "hint": "Auf ein Konto klicken, um die Positionen zu filtern",
+ "clearFilter": "Filter zurücksetzen",
+ "positions": "{{count}} Positionen",
+ "fresh": "Erfolgreich gelesen",
+ "failed": "Konnte nicht gelesen werden — nicht in der Summe enthalten",
+ "lastSuccess": "Letzter erfolgreicher Abruf {{time}}",
+ "noSuccess": "Noch kein erfolgreicher Abruf",
+ "reconnect": "Neu verbinden"
+ },
+ "holdings": {
+ "title": "Positionen",
+ "count": "{{count}} Positionen",
+ "search": "Broker, Symbol oder Markt suchen",
+ "colBroker": "Konto",
+ "colSymbol": "Symbol",
+ "colType": "Typ",
+ "colQuantity": "Stückzahl",
+ "colCostPrice": "Einstand / Kurs",
+ "colValue": "Wert",
+ "colWeight": "Gewicht",
+ "colPnl": "Nicht realisierte G/V",
+ "colData": "Daten",
+ "priced": "Bewertet",
+ "unpriced": "Ohne Kurs"
+ },
+ "history": {
+ "title": "Vermögensverlauf",
+ "hint": "Nur vollständige Snapshots; Änderungen können Ein- und Auszahlungen enthalten.",
+ "count": "{{count}} vollständige Snapshots",
+ "empty": "Der Verlauf beginnt nach der ersten vollständigen Aktualisierung"
+ },
+ "credentials": {
+ "title": "Verbindungen und Zugangsdaten",
+ "readOnlyProfile": "Schreibgeschütztes Profil",
+ "writableProfile": "Schreibfähiges Profil",
+ "renewalAutomatic": "Erneuerung durch den Connector",
+ "renewalSession": "Lokale Sitzung",
+ "renewalProvider": "Gültigkeit vom Anbieter verwaltet"
+ },
+ "status": {
+ "title": "Aktivierte Konten werden nacheinander gelesen",
+ "reading": "Wird gelesen",
+ "done": "Fertig",
+ "failed": "Fehlgeschlagen",
+ "waiting": "Wartet"
+ },
+ "env": {
+ "live": "Live",
+ "paper": "Paper"
+ },
+ "editor": {
+ "title": "Portfolio-Konten verwalten",
+ "subtitle": "Hier werden nur die Kontoauswahl und Anzeigeeinstellungen gespeichert.",
+ "close": "Schließen",
+ "currency": "Primäre Anzeigewährung",
+ "selected": "Ausgewählte Konten",
+ "selectedHint": "Mit den Pfeiltasten die Anzeigereihenfolge ändern.",
+ "enableAccount": "Konto aktivieren",
+ "accountLabel": "Kontobezeichnung",
+ "moveUp": "Nach oben",
+ "moveDown": "Nach unten",
+ "removeAccount": "Konto entfernen",
+ "includeCash": "Bargeld dieses Kontos einbeziehen",
+ "noAccounts": "Keine Konten ausgewählt",
+ "addTitle": "Lokale schreibgeschützte Verbindung hinzufügen",
+ "addHint": "Wählen Sie aus den bereits auf diesem Computer angelegten Verbindungen.",
+ "openConnections": "Verbindungszentrale öffnen",
+ "chooseConnection": "Verbindung wählen…",
+ "noConnections": "Keine Verbindungen verfügbar",
+ "add": "Hinzufügen",
+ "footerHint": "Nach dem Speichern werden die aktivierten Konten aktualisiert.",
+ "cancel": "Abbrechen",
+ "save": "Speichern und aktualisieren",
+ "saving": "Wird gespeichert"
+ },
+ "connections": {
+ "title": "Lokale Verbindungszentrale",
+ "subtitle": "Definitionen bleiben lokal; Geheimnisse landen ausschließlich im Anmeldeinformationsspeicher des Systems.",
+ "close": "Verbindungszentrale schließen",
+ "createTitle": "Kontoverbindung anlegen",
+ "createHint": "Ein Profil ist eine öffentliche Vorlage; eine Verbindung gehört nur zu diesem Computer.",
+ "profile": "Schreibgeschütztes Profil",
+ "chooseProfile": "Profil wählen…",
+ "localId": "Lokale Verbindungs-ID",
+ "displayName": "Anzeigename",
+ "displayNamePlaceholder": "Mein Hauptkonto",
+ "create": "Verbindung anlegen",
+ "created": "Lokale Verbindung angelegt.",
+ "listTitle": "Verbindungen auf diesem Computer",
+ "listCount": "{{count}} Verbindungen",
+ "empty": "Noch keine lokalen Verbindungen",
+ "codexTitle": "Broker mit Codex ergänzen",
+ "codexBody": "Lassen Sie Codex connector init ausführen, den Leseadapter anhand der offiziellen Dokumentation implementieren, ihn validieren und dann installieren. Das Plugin bleibt außerhalb des Repositorys.",
+ "readOnly": "Schreibgeschützt",
+ "credentialSaved": "gespeichert",
+ "oauthNote": "Nutzt OAuth; bei Bedarf über das erneute Verbinden autorisieren.",
+ "localNote": "Die Zugangsdaten verwaltet die vorhandene lokale Connector-Konfiguration.",
+ "saveVault": "Im Speicher ablegen",
+ "savedVault": "Zugangsdaten im Systemspeicher abgelegt.",
+ "test": "Testen",
+ "testOk": "{{label}} ist bereit.",
+ "delete": "Löschen",
+ "configured": "Erforderliche Zugangsdaten konfiguriert"
+ }
}
}
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index f0be96032..b8a3d9388 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -1408,5 +1408,151 @@
"loading": "Loading factor results…",
"error": "Failed to load factor results",
"noFactorData": "No factor analysis results are available for this run."
+ },
+ "portfolio": {
+ "page": {
+ "badge": "Local read-only · Multi-account",
+ "title": "Portfolio",
+ "subtitle": "One valuation across the enabled read-only connections. An account that cannot be read is reported as an error and left out of the totals.",
+ "fxFresh": "USD/CNY {{rate}} · live rate",
+ "fxCached": "USD/CNY {{rate}} · cached rate",
+ "manageAccounts": "Manage accounts",
+ "exportCsv": "Export CSV",
+ "refreshAll": "Refresh all",
+ "refreshing": "Refreshing",
+ "warningsTitle": "Data notes",
+ "emptyTitle": "No portfolio snapshot yet",
+ "emptyBody": "Add at least one read-only account to begin.",
+ "emptyAction": "Add account",
+ "errorLoad": "Portfolio unavailable",
+ "errorRefresh": "Refresh failed",
+ "errorReconnect": "Account reconnect failed",
+ "errorSaveSettings": "Unable to save portfolio settings",
+ "errorExport": "Export failed"
+ },
+ "metrics": {
+ "total": "Total assets",
+ "change": "Today's asset change",
+ "changeNote": "Includes market moves and cash flows",
+ "coverage": "Valuation coverage",
+ "coverageNote": "Priced {{priced}} · cash {{cash}}",
+ "lastComplete": "Last complete update",
+ "excluded": "{{count}} accounts could not be read and are excluded from this total"
+ },
+ "allocation": {
+ "byAccount": "Allocation by account",
+ "byHolding": "Allocation by holding",
+ "center": "Holdings",
+ "other": "Other holdings",
+ "cash": "Cash",
+ "unpriced": "Unpriced / other",
+ "cashUnpriced": "Cash / unpriced"
+ },
+ "accounts": {
+ "title": "Account status",
+ "hint": "Click an account to filter holdings",
+ "clearFilter": "Clear filter",
+ "positions": "{{count}} positions",
+ "fresh": "Read successfully",
+ "failed": "Could not be read — not counted in the total",
+ "lastSuccess": "Last successful read {{time}}",
+ "noSuccess": "No successful read yet",
+ "reconnect": "Reconnect"
+ },
+ "holdings": {
+ "title": "Holdings",
+ "count": "{{count}} positions",
+ "search": "Search broker, symbol or market",
+ "colBroker": "Broker",
+ "colSymbol": "Symbol",
+ "colType": "Type",
+ "colQuantity": "Quantity",
+ "colCostPrice": "Cost / Price",
+ "colValue": "Value",
+ "colWeight": "Weight",
+ "colPnl": "Unrealized P/L",
+ "colData": "Data",
+ "priced": "Priced",
+ "unpriced": "Unpriced"
+ },
+ "history": {
+ "title": "Asset history",
+ "hint": "Complete snapshots only; changes may include cash flows.",
+ "count": "{{count}} complete snapshots",
+ "empty": "History begins after a complete refresh"
+ },
+ "credentials": {
+ "title": "Connections and credentials",
+ "readOnlyProfile": "Read-only profile",
+ "writableProfile": "Write-capable profile",
+ "renewalAutomatic": "Connector-managed renewal",
+ "renewalSession": "Local session",
+ "renewalProvider": "Provider-managed validity"
+ },
+ "status": {
+ "title": "Refreshing enabled accounts sequentially",
+ "reading": "Reading",
+ "done": "Done",
+ "failed": "Failed",
+ "waiting": "Waiting"
+ },
+ "env": {
+ "live": "Live",
+ "paper": "Paper"
+ },
+ "editor": {
+ "title": "Manage portfolio accounts",
+ "subtitle": "Only account selection and display preferences are stored here.",
+ "close": "Close",
+ "currency": "Primary display currency",
+ "selected": "Selected accounts",
+ "selectedHint": "Use the arrow buttons to change display order.",
+ "enableAccount": "Enable account",
+ "accountLabel": "Account label",
+ "moveUp": "Move up",
+ "moveDown": "Move down",
+ "removeAccount": "Remove account",
+ "includeCash": "Include this account's cash",
+ "noAccounts": "No accounts selected",
+ "addTitle": "Add a local read-only connection",
+ "addHint": "Choose from connections already created on this computer.",
+ "openConnections": "Open connection center",
+ "chooseConnection": "Choose a connection…",
+ "noConnections": "No available connections",
+ "add": "Add",
+ "footerHint": "Enabled accounts refresh after saving.",
+ "cancel": "Cancel",
+ "save": "Save and refresh",
+ "saving": "Saving"
+ },
+ "connections": {
+ "title": "Local connection center",
+ "subtitle": "Definitions stay local; secrets go only to the OS credential vault.",
+ "close": "Close connection center",
+ "createTitle": "Create account connection",
+ "createHint": "A profile is a public template; a connection is private to this computer.",
+ "profile": "Read-only profile",
+ "chooseProfile": "Choose a profile…",
+ "localId": "Local connection ID",
+ "displayName": "Display name",
+ "displayNamePlaceholder": "My main account",
+ "create": "Create connection",
+ "created": "Local connection created.",
+ "listTitle": "Connections on this computer",
+ "listCount": "{{count}} connections",
+ "empty": "No local connections yet",
+ "codexTitle": "Add a broker with Codex",
+ "codexBody": "Ask Codex to run connector init, implement the read adapter from official docs, validate it, then install it. The plugin stays outside the repository.",
+ "readOnly": "Read-only",
+ "credentialSaved": "saved",
+ "oauthNote": "Uses OAuth; authorize through reconnect when required.",
+ "localNote": "Credentials are managed by the existing local connector configuration.",
+ "saveVault": "Save to vault",
+ "savedVault": "Credentials saved to the OS vault.",
+ "test": "Test",
+ "testOk": "{{label}} is ready.",
+ "delete": "Delete",
+ "configured": "Required credentials configured"
+ }
}
}
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 8aa72ceb8..284273a66 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -1408,5 +1408,151 @@
"loading": "Cargando resultados de factores…",
"error": "Error al cargar los resultados de factores",
"noFactorData": "No hay resultados de análisis de factores disponibles para esta ejecución."
+ },
+ "portfolio": {
+ "page": {
+ "badge": "Local y solo lectura · Varias cuentas",
+ "title": "Cartera",
+ "subtitle": "Una sola valoración de todas las conexiones de solo lectura activas. La cuenta que no se puede leer se marca como error y queda fuera de los totales.",
+ "fxFresh": "USD/CNY {{rate}} · tipo en vivo",
+ "fxCached": "USD/CNY {{rate}} · tipo en caché",
+ "manageAccounts": "Gestionar cuentas",
+ "exportCsv": "Exportar CSV",
+ "refreshAll": "Actualizar todo",
+ "refreshing": "Actualizando",
+ "warningsTitle": "Notas sobre los datos",
+ "emptyTitle": "Aún no hay ninguna instantánea de la cartera",
+ "emptyBody": "Añade al menos una cuenta de solo lectura para empezar.",
+ "emptyAction": "Añadir cuenta",
+ "errorLoad": "Cartera no disponible",
+ "errorRefresh": "Fallo al actualizar",
+ "errorReconnect": "No se pudo volver a conectar la cuenta",
+ "errorSaveSettings": "No se pudieron guardar los ajustes de la cartera",
+ "errorExport": "Fallo al exportar"
+ },
+ "metrics": {
+ "total": "Activos totales",
+ "change": "Variación de hoy",
+ "changeNote": "Incluye movimientos de mercado y entradas y salidas de efectivo",
+ "coverage": "Cobertura de valoración",
+ "coverageNote": "Valorado {{priced}} · efectivo {{cash}}",
+ "lastComplete": "Última actualización completa",
+ "excluded": "No se pudieron leer {{count}} cuentas y quedan fuera de este total"
+ },
+ "allocation": {
+ "byAccount": "Distribución por cuenta",
+ "byHolding": "Distribución por posición",
+ "center": "Posiciones",
+ "other": "Otras posiciones",
+ "cash": "Efectivo",
+ "unpriced": "Sin precio / otros",
+ "cashUnpriced": "Efectivo / sin precio"
+ },
+ "accounts": {
+ "title": "Estado de las cuentas",
+ "hint": "Pulsa una cuenta para filtrar las posiciones",
+ "clearFilter": "Quitar filtro",
+ "positions": "{{count}} posiciones",
+ "fresh": "Leída correctamente",
+ "failed": "No se pudo leer: no cuenta en el total",
+ "lastSuccess": "Última lectura correcta {{time}}",
+ "noSuccess": "Todavía sin ninguna lectura correcta",
+ "reconnect": "Volver a conectar"
+ },
+ "holdings": {
+ "title": "Posiciones",
+ "count": "{{count}} posiciones",
+ "search": "Buscar bróker, símbolo o mercado",
+ "colBroker": "Cuenta",
+ "colSymbol": "Símbolo",
+ "colType": "Tipo",
+ "colQuantity": "Cantidad",
+ "colCostPrice": "Coste / Precio",
+ "colValue": "Valor",
+ "colWeight": "Peso",
+ "colPnl": "P/G no realizada",
+ "colData": "Datos",
+ "priced": "Con precio",
+ "unpriced": "Sin precio"
+ },
+ "history": {
+ "title": "Histórico de activos",
+ "hint": "Solo instantáneas completas; los cambios pueden incluir entradas y salidas de efectivo.",
+ "count": "{{count}} instantáneas completas",
+ "empty": "El histórico empieza tras la primera actualización completa"
+ },
+ "credentials": {
+ "title": "Conexiones y credenciales",
+ "readOnlyProfile": "Perfil de solo lectura",
+ "writableProfile": "Perfil con permisos de escritura",
+ "renewalAutomatic": "Renovación gestionada por el conector",
+ "renewalSession": "Sesión local",
+ "renewalProvider": "Validez gestionada por el proveedor"
+ },
+ "status": {
+ "title": "Leyendo las cuentas activas una por una",
+ "reading": "Leyendo",
+ "done": "Hecho",
+ "failed": "Fallida",
+ "waiting": "En espera"
+ },
+ "env": {
+ "live": "En vivo",
+ "paper": "Demo"
+ },
+ "editor": {
+ "title": "Gestionar las cuentas de la cartera",
+ "subtitle": "Aquí solo se guardan la selección de cuentas y las preferencias de visualización.",
+ "close": "Cerrar",
+ "currency": "Moneda principal de visualización",
+ "selected": "Cuentas añadidas",
+ "selectedHint": "Usa las flechas para cambiar el orden de visualización.",
+ "enableAccount": "Activar cuenta",
+ "accountLabel": "Nombre de la cuenta",
+ "moveUp": "Subir",
+ "moveDown": "Bajar",
+ "removeAccount": "Quitar cuenta",
+ "includeCash": "Incluir el efectivo de esta cuenta",
+ "noAccounts": "No hay ninguna cuenta seleccionada",
+ "addTitle": "Añadir una conexión local de solo lectura",
+ "addHint": "Elige entre las conexiones ya creadas en este ordenador.",
+ "openConnections": "Abrir el centro de conexiones",
+ "chooseConnection": "Elige una conexión…",
+ "noConnections": "No hay conexiones disponibles",
+ "add": "Añadir",
+ "footerHint": "Al guardar se actualizan las cuentas activas.",
+ "cancel": "Cancelar",
+ "save": "Guardar y actualizar",
+ "saving": "Guardando"
+ },
+ "connections": {
+ "title": "Centro de conexiones locales",
+ "subtitle": "Las definiciones se quedan en este equipo; los secretos van solo al almacén de credenciales del sistema.",
+ "close": "Cerrar el centro de conexiones",
+ "createTitle": "Crear conexión de cuenta",
+ "createHint": "El perfil es una plantilla pública; la conexión es privada de este ordenador.",
+ "profile": "Perfil de solo lectura",
+ "chooseProfile": "Elige un perfil…",
+ "localId": "ID de conexión local",
+ "displayName": "Nombre visible",
+ "displayNamePlaceholder": "Mi cuenta principal",
+ "create": "Crear conexión",
+ "created": "Conexión local creada.",
+ "listTitle": "Conexiones en este ordenador",
+ "listCount": "{{count}} conexiones",
+ "empty": "Todavía no hay conexiones locales",
+ "codexTitle": "Añadir un bróker con Codex",
+ "codexBody": "Pide a Codex que ejecute connector init, implemente el adaptador de lectura a partir de la documentación oficial, lo valide y luego lo instale. El plugin queda fuera del repositorio.",
+ "readOnly": "Solo lectura",
+ "credentialSaved": "guardada",
+ "oauthNote": "Usa OAuth; autoriza mediante la reconexión cuando haga falta.",
+ "localNote": "Las credenciales las gestiona la configuración local del conector existente.",
+ "saveVault": "Guardar en el almacén",
+ "savedVault": "Credenciales guardadas en el almacén del sistema.",
+ "test": "Probar",
+ "testOk": "{{label}} está lista.",
+ "delete": "Eliminar",
+ "configured": "Credenciales necesarias configuradas"
+ }
}
}
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 3d7aaed85..1cfb51a2c 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -1408,5 +1408,151 @@
"loading": "ファクター分析結果を読み込み中…",
"error": "ファクター分析結果の読み込みに失敗しました",
"noFactorData": "この実行には利用可能なファクター分析結果がありません。"
+ },
+ "portfolio": {
+ "page": {
+ "badge": "ローカル読み取り専用 · 複数口座",
+ "title": "ポートフォリオ",
+ "subtitle": "有効な読み取り専用接続をまとめて 1 つの評価にします。読み取れなかった口座はエラーとして表示され、合計には含まれません。",
+ "fxFresh": "USD/CNY {{rate}} · 最新レート",
+ "fxCached": "USD/CNY {{rate}} · キャッシュされたレート",
+ "manageAccounts": "口座を管理",
+ "exportCsv": "CSV を書き出す",
+ "refreshAll": "すべて更新",
+ "refreshing": "更新中",
+ "warningsTitle": "データに関する注記",
+ "emptyTitle": "ポートフォリオのスナップショットがまだありません",
+ "emptyBody": "読み取り専用の口座を 1 つ以上追加すると集計が始まります。",
+ "emptyAction": "口座を追加",
+ "errorLoad": "ポートフォリオを取得できません",
+ "errorRefresh": "更新に失敗しました",
+ "errorReconnect": "口座の再接続に失敗しました",
+ "errorSaveSettings": "ポートフォリオ設定を保存できません",
+ "errorExport": "書き出しに失敗しました"
+ },
+ "metrics": {
+ "total": "総資産",
+ "change": "本日の資産変動",
+ "changeNote": "相場変動と入出金を含みます",
+ "coverage": "評価カバレッジ",
+ "coverageNote": "評価済み {{priced}} · 現金 {{cash}}",
+ "lastComplete": "最後の完全更新",
+ "excluded": "{{count}} 件の口座を読み取れなかったため、この合計から除外しています"
+ },
+ "allocation": {
+ "byAccount": "口座別の構成",
+ "byHolding": "銘柄別の構成",
+ "center": "保有比率",
+ "other": "その他の保有",
+ "cash": "現金",
+ "unpriced": "未評価 / その他",
+ "cashUnpriced": "現金 / 未評価"
+ },
+ "accounts": {
+ "title": "口座の状態",
+ "hint": "口座をクリックすると保有一覧を絞り込めます",
+ "clearFilter": "絞り込みを解除",
+ "positions": "{{count}} 件の保有",
+ "fresh": "読み取り成功",
+ "failed": "読み取れませんでした — 合計に含まれていません",
+ "lastSuccess": "最後に読み取れたのは {{time}}",
+ "noSuccess": "まだ一度も読み取れていません",
+ "reconnect": "再接続"
+ },
+ "holdings": {
+ "title": "保有明細",
+ "count": "{{count}} 件の保有",
+ "search": "証券会社・銘柄・市場で検索",
+ "colBroker": "口座",
+ "colSymbol": "銘柄",
+ "colType": "種別",
+ "colQuantity": "数量",
+ "colCostPrice": "取得単価 / 現在値",
+ "colValue": "評価額",
+ "colWeight": "構成比",
+ "colPnl": "評価損益",
+ "colData": "データ",
+ "priced": "評価済み",
+ "unpriced": "未評価"
+ },
+ "history": {
+ "title": "資産推移",
+ "hint": "完全なスナップショットのみを表示します。変動には入出金が含まれることがあります。",
+ "count": "{{count}} 件の完全なスナップショット",
+ "empty": "最初の完全更新のあとから記録が始まります"
+ },
+ "credentials": {
+ "title": "接続と認証情報",
+ "readOnlyProfile": "読み取り専用プロファイル",
+ "writableProfile": "書き込み可能プロファイル",
+ "renewalAutomatic": "コネクタが自動更新",
+ "renewalSession": "ローカルセッション依存",
+ "renewalProvider": "提供元が有効期限を管理"
+ },
+ "status": {
+ "title": "有効な口座を順番に読み取っています",
+ "reading": "読み取り中",
+ "done": "完了",
+ "failed": "失敗",
+ "waiting": "待機中"
+ },
+ "env": {
+ "live": "ライブ",
+ "paper": "ペーパー"
+ },
+ "editor": {
+ "title": "ポートフォリオの口座を管理",
+ "subtitle": "ここに保存されるのは口座の選択と表示設定だけで、認証情報は保存されません。",
+ "close": "閉じる",
+ "currency": "主表示通貨",
+ "selected": "追加済みの口座",
+ "selectedHint": "上下の矢印で表示順を変更できます。",
+ "enableAccount": "口座を有効にする",
+ "accountLabel": "口座名",
+ "moveUp": "上へ",
+ "moveDown": "下へ",
+ "removeAccount": "口座を削除",
+ "includeCash": "この口座の現金を含める",
+ "noAccounts": "口座がまだ選択されていません",
+ "addTitle": "ローカルの読み取り専用接続を追加",
+ "addHint": "このコンピューターで作成済みの接続から選びます。",
+ "openConnections": "接続センターを開く",
+ "chooseConnection": "接続を選択…",
+ "noConnections": "追加できる接続がありません",
+ "add": "追加",
+ "footerHint": "保存すると有効な口座が更新されます。",
+ "cancel": "キャンセル",
+ "save": "保存して更新",
+ "saving": "保存中"
+ },
+ "connections": {
+ "title": "ローカル接続センター",
+ "subtitle": "接続定義はこの端末に残り、秘密情報は OS の資格情報ストアにのみ保存されます。",
+ "close": "接続センターを閉じる",
+ "createTitle": "口座接続を作成",
+ "createHint": "プロファイルは公開テンプレート、接続はこのコンピューター専用の実体です。",
+ "profile": "読み取り専用プロファイル",
+ "chooseProfile": "プロファイルを選択…",
+ "localId": "ローカル接続 ID",
+ "displayName": "表示名",
+ "displayNamePlaceholder": "メイン口座",
+ "create": "接続を作成",
+ "created": "ローカル接続を作成しました。",
+ "listTitle": "このコンピューターの接続",
+ "listCount": "{{count}} 件の接続",
+ "empty": "ローカル接続がまだありません",
+ "codexTitle": "Codex で証券会社を追加",
+ "codexBody": "Codex に connector init を実行させ、公式ドキュメントから読み取り用アダプターを実装し、validate を通してから install します。プラグインはリポジトリの外に置かれます。",
+ "readOnly": "読み取り専用",
+ "credentialSaved": "保存済み",
+ "oauthNote": "OAuth を使用します。必要に応じて再接続で認可してください。",
+ "localNote": "認証情報は既存のローカルコネクタ設定が管理します。",
+ "saveVault": "資格情報ストアに保存",
+ "savedVault": "認証情報を OS の資格情報ストアに保存しました。",
+ "test": "接続テスト",
+ "testOk": "{{label}} は正常です。",
+ "delete": "削除",
+ "configured": "必要な認証情報は設定済みです"
+ }
}
}
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 626e6e99e..259fa7296 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -1408,5 +1408,151 @@
"loading": "팩터 분석 결과를 불러오는 중…",
"error": "팩터 분석 결과를 불러오지 못했습니다",
"noFactorData": "이 실행에는 사용 가능한 팩터 분석 결과가 없습니다."
+ },
+ "portfolio": {
+ "page": {
+ "badge": "로컬 읽기 전용 · 다중 계좌",
+ "title": "포트폴리오",
+ "subtitle": "활성화된 읽기 전용 연결을 하나의 평가로 합칩니다. 읽지 못한 계좌는 오류로 표시되며 합계에서 제외됩니다.",
+ "fxFresh": "USD/CNY {{rate}} · 실시간 환율",
+ "fxCached": "USD/CNY {{rate}} · 캐시된 환율",
+ "manageAccounts": "계좌 관리",
+ "exportCsv": "CSV 내보내기",
+ "refreshAll": "전체 새로고침",
+ "refreshing": "새로고침 중",
+ "warningsTitle": "데이터 참고",
+ "emptyTitle": "아직 포트폴리오 스냅샷이 없습니다",
+ "emptyBody": "읽기 전용 계좌를 하나 이상 추가하면 집계가 시작됩니다.",
+ "emptyAction": "계좌 추가",
+ "errorLoad": "포트폴리오를 불러올 수 없습니다",
+ "errorRefresh": "새로고침에 실패했습니다",
+ "errorReconnect": "계좌 재연결에 실패했습니다",
+ "errorSaveSettings": "포트폴리오 설정을 저장할 수 없습니다",
+ "errorExport": "내보내기에 실패했습니다"
+ },
+ "metrics": {
+ "total": "총자산",
+ "change": "오늘의 자산 변동",
+ "changeNote": "시세 변동과 입출금이 포함됩니다",
+ "coverage": "평가 커버리지",
+ "coverageNote": "평가 완료 {{priced}} · 현금 {{cash}}",
+ "lastComplete": "마지막 완전 업데이트",
+ "excluded": "{{count}}개 계좌를 읽지 못해 이 합계에서 제외했습니다"
+ },
+ "allocation": {
+ "byAccount": "계좌별 비중",
+ "byHolding": "종목별 비중",
+ "center": "보유 비중",
+ "other": "기타 보유",
+ "cash": "현금",
+ "unpriced": "미평가 / 기타",
+ "cashUnpriced": "현금 / 미평가"
+ },
+ "accounts": {
+ "title": "계좌 상태",
+ "hint": "계좌를 클릭하면 아래 보유 내역을 걸러 볼 수 있습니다",
+ "clearFilter": "필터 해제",
+ "positions": "보유 {{count}}건",
+ "fresh": "읽기 성공",
+ "failed": "읽지 못했습니다 — 합계에 포함되지 않음",
+ "lastSuccess": "마지막으로 성공한 읽기 {{time}}",
+ "noSuccess": "아직 성공한 읽기가 없습니다",
+ "reconnect": "다시 연결"
+ },
+ "holdings": {
+ "title": "보유 내역",
+ "count": "보유 {{count}}건",
+ "search": "증권사, 종목 또는 시장 검색",
+ "colBroker": "계좌",
+ "colSymbol": "종목",
+ "colType": "유형",
+ "colQuantity": "수량",
+ "colCostPrice": "평단가 / 현재가",
+ "colValue": "평가금액",
+ "colWeight": "비중",
+ "colPnl": "미실현 손익",
+ "colData": "데이터",
+ "priced": "평가 완료",
+ "unpriced": "미평가"
+ },
+ "history": {
+ "title": "자산 추이",
+ "hint": "완전한 스냅샷만 표시합니다. 변동에는 입출금이 포함될 수 있습니다.",
+ "count": "완전한 스냅샷 {{count}}건",
+ "empty": "첫 완전 새로고침 이후부터 기록이 쌓입니다"
+ },
+ "credentials": {
+ "title": "연결과 자격 증명",
+ "readOnlyProfile": "읽기 전용 프로필",
+ "writableProfile": "쓰기 가능 프로필",
+ "renewalAutomatic": "커넥터가 자동 갱신",
+ "renewalSession": "로컬 세션에 의존",
+ "renewalProvider": "제공자가 유효기간 관리"
+ },
+ "status": {
+ "title": "활성화된 계좌를 순서대로 읽는 중",
+ "reading": "읽는 중",
+ "done": "완료",
+ "failed": "실패",
+ "waiting": "대기 중"
+ },
+ "env": {
+ "live": "실거래",
+ "paper": "페이퍼"
+ },
+ "editor": {
+ "title": "포트폴리오 계좌 관리",
+ "subtitle": "여기에는 계좌 선택과 표시 설정만 저장되며 자격 증명은 저장되지 않습니다.",
+ "close": "닫기",
+ "currency": "기본 표시 통화",
+ "selected": "추가된 계좌",
+ "selectedHint": "위아래 화살표로 표시 순서를 바꿉니다.",
+ "enableAccount": "계좌 사용",
+ "accountLabel": "계좌 이름",
+ "moveUp": "위로",
+ "moveDown": "아래로",
+ "removeAccount": "계좌 제거",
+ "includeCash": "이 계좌의 현금 포함",
+ "noAccounts": "선택된 계좌가 없습니다",
+ "addTitle": "로컬 읽기 전용 연결 추가",
+ "addHint": "이 컴퓨터에 이미 만들어진 연결 중에서 고릅니다.",
+ "openConnections": "연결 센터 열기",
+ "chooseConnection": "연결 선택…",
+ "noConnections": "추가할 수 있는 연결이 없습니다",
+ "add": "추가",
+ "footerHint": "저장하면 활성화된 계좌를 새로고침합니다.",
+ "cancel": "취소",
+ "save": "저장 후 새로고침",
+ "saving": "저장 중"
+ },
+ "connections": {
+ "title": "로컬 연결 센터",
+ "subtitle": "연결 정의는 이 컴퓨터에 남고, 비밀 값은 OS 자격 증명 저장소에만 들어갑니다.",
+ "close": "연결 센터 닫기",
+ "createTitle": "계좌 연결 만들기",
+ "createHint": "프로필은 공개 템플릿이고, 연결은 이 컴퓨터에만 있는 실체입니다.",
+ "profile": "읽기 전용 프로필",
+ "chooseProfile": "프로필 선택…",
+ "localId": "로컬 연결 ID",
+ "displayName": "표시 이름",
+ "displayNamePlaceholder": "내 주 계좌",
+ "create": "연결 만들기",
+ "created": "로컬 연결을 만들었습니다.",
+ "listTitle": "이 컴퓨터의 연결",
+ "listCount": "연결 {{count}}개",
+ "empty": "아직 로컬 연결이 없습니다",
+ "codexTitle": "Codex로 증권사 추가하기",
+ "codexBody": "Codex에 connector init을 실행시키고, 공식 문서를 보고 읽기 전용 어댑터를 구현한 뒤 validate를 통과시키고 install 하세요. 플러그인은 저장소 밖에 설치됩니다.",
+ "readOnly": "읽기 전용",
+ "credentialSaved": "저장됨",
+ "oauthNote": "OAuth를 사용합니다. 필요하면 재연결로 승인하세요.",
+ "localNote": "자격 증명은 기존 로컬 커넥터 설정이 관리합니다.",
+ "saveVault": "자격 증명 저장소에 저장",
+ "savedVault": "자격 증명을 OS 저장소에 저장했습니다.",
+ "test": "연결 테스트",
+ "testOk": "{{label}} 연결이 정상입니다.",
+ "delete": "삭제",
+ "configured": "필요한 자격 증명이 설정되었습니다"
+ }
}
}
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index e59181104..3557aae27 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -1408,5 +1408,151 @@
"loading": "正在加载因子分析结果…",
"error": "加载因子分析结果失败",
"noFactorData": "本次运行没有可用的因子分析结果。"
+ },
+ "portfolio": {
+ "page": {
+ "badge": "本机只读 · 多账户",
+ "title": "持仓总览",
+ "subtitle": "把已启用的只读连接汇总成一份估值。读取失败的账户会标记为错误,并且不计入合计。",
+ "fxFresh": "USD/CNY {{rate}} · 实时汇率",
+ "fxCached": "USD/CNY {{rate}} · 缓存汇率",
+ "manageAccounts": "管理账户",
+ "exportCsv": "导出 CSV",
+ "refreshAll": "刷新全部账户",
+ "refreshing": "正在刷新",
+ "warningsTitle": "数据说明",
+ "emptyTitle": "还没有持仓快照",
+ "emptyBody": "至少添加一个只读账户后即可开始汇总。",
+ "emptyAction": "添加账户",
+ "errorLoad": "无法读取持仓",
+ "errorRefresh": "刷新失败",
+ "errorReconnect": "账户重新连接失败",
+ "errorSaveSettings": "无法保存持仓设置",
+ "errorExport": "导出失败"
+ },
+ "metrics": {
+ "total": "总资产",
+ "change": "今日资产变化",
+ "changeNote": "包含行情波动与入金、出金",
+ "coverage": "估值覆盖率",
+ "coverageNote": "已定价 {{priced}} · 现金 {{cash}}",
+ "lastComplete": "最后一次完整更新",
+ "excluded": "{{count}} 个账户读取失败,未计入该合计"
+ },
+ "allocation": {
+ "byAccount": "按账户分布",
+ "byHolding": "按持仓标的分布",
+ "center": "持仓占比",
+ "other": "其他持仓",
+ "cash": "现金",
+ "unpriced": "未定价 / 其他",
+ "cashUnpriced": "现金 / 未定价"
+ },
+ "accounts": {
+ "title": "账户状态",
+ "hint": "点击账户卡可筛选下方持仓",
+ "clearFilter": "清除筛选",
+ "positions": "{{count}} 项持仓",
+ "fresh": "读取成功",
+ "failed": "读取失败 — 未计入合计",
+ "lastSuccess": "上一次成功读取于 {{time}}",
+ "noSuccess": "尚未成功读取过",
+ "reconnect": "重新连接"
+ },
+ "holdings": {
+ "title": "持仓明细",
+ "count": "{{count}} 项持仓",
+ "search": "搜索账户、标的或市场",
+ "colBroker": "账户",
+ "colSymbol": "标的",
+ "colType": "类别",
+ "colQuantity": "数量",
+ "colCostPrice": "成本 / 现价",
+ "colValue": "市值",
+ "colWeight": "占比",
+ "colPnl": "未实现盈亏",
+ "colData": "数据状态",
+ "priced": "已定价",
+ "unpriced": "未定价"
+ },
+ "history": {
+ "title": "资产历史",
+ "hint": "只显示完整快照;资产变化可能包含入金和出金。",
+ "count": "{{count}} 个完整快照",
+ "empty": "完成首次完整刷新后开始积累"
+ },
+ "credentials": {
+ "title": "连接与凭证",
+ "readOnlyProfile": "只读连接模板",
+ "writableProfile": "可写连接模板",
+ "renewalAutomatic": "连接器自动续期",
+ "renewalSession": "依赖本地会话",
+ "renewalProvider": "由服务商管理有效期"
+ },
+ "status": {
+ "title": "正在依次读取已启用账户",
+ "reading": "读取中",
+ "done": "完成",
+ "failed": "失败",
+ "waiting": "等待"
+ },
+ "env": {
+ "live": "实盘",
+ "paper": "模拟"
+ },
+ "editor": {
+ "title": "管理持仓账户",
+ "subtitle": "这里只保存账户选择和显示偏好,不保存密钥。",
+ "close": "关闭",
+ "currency": "主要显示货币",
+ "selected": "已添加账户",
+ "selectedHint": "用上下箭头调整显示顺序。",
+ "enableAccount": "启用账户",
+ "accountLabel": "账户名称",
+ "moveUp": "上移",
+ "moveDown": "下移",
+ "removeAccount": "删除账户",
+ "includeCash": "计入该账户现金",
+ "noAccounts": "还没有添加账户",
+ "addTitle": "添加本地只读连接",
+ "addHint": "只能选择已经在这台电脑上创建的连接。",
+ "openConnections": "打开连接中心",
+ "chooseConnection": "选择连接…",
+ "noConnections": "没有可添加的连接",
+ "add": "添加",
+ "footerHint": "保存后将刷新已启用账户。",
+ "cancel": "取消",
+ "save": "保存并刷新",
+ "saving": "保存中"
+ },
+ "connections": {
+ "title": "本地连接中心",
+ "subtitle": "连接定义保存在本机;密钥只进入系统钥匙串。",
+ "close": "关闭连接中心",
+ "createTitle": "创建账户连接",
+ "createHint": "模板是公开的;连接只属于这台电脑。",
+ "profile": "只读连接模板",
+ "chooseProfile": "选择模板…",
+ "localId": "本地连接 ID",
+ "displayName": "显示名称",
+ "displayNamePlaceholder": "我的主账户",
+ "create": "创建本地连接",
+ "created": "本地连接已创建。",
+ "listTitle": "这台电脑上的连接",
+ "listCount": "{{count}} 个连接",
+ "empty": "还没有本地连接",
+ "codexTitle": "让 Codex 接入新券商",
+ "codexBody": "让 Codex 运行 connector init,按券商官方文档补全只读 adapter,通过 validate 后再 install。插件安装在本机目录,不进入项目仓库。",
+ "readOnly": "结构只读",
+ "credentialSaved": "已保存",
+ "oauthNote": "使用 OAuth;需要时通过重新连接完成授权。",
+ "localNote": "凭证由现有的本地连接器配置管理。",
+ "saveVault": "保存到钥匙串",
+ "savedVault": "凭证已保存到系统钥匙串。",
+ "test": "测试连接",
+ "testOk": "{{label}} 连接正常。",
+ "delete": "删除",
+ "configured": "所需凭证已配置"
+ }
}
}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index ae7dd7b8f..26cb1473d 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -80,22 +80,27 @@ export interface PortfolioPosition {
unrealized_pnl_usd?: number | null;
priced: boolean;
updated_at: string;
- stale?: boolean;
pricing_basis?: string;
price_error?: string;
}
+/**
+ * One portfolio source as of the last refresh.
+ *
+ * A source that could not be read has `status === "error"`, no totals, and
+ * contributes nothing to the snapshot totals; `last_success_at` (when present)
+ * is the timestamp of the last read that did succeed, and is only ever shown
+ * as history — never as a current valuation.
+ */
export interface PortfolioAccount {
source_id?: string;
profile_id?: string;
label?: string;
broker: string;
- status: "ok" | "stale" | "error";
- data_state?: "fresh" | "cached";
+ status: "ok" | "error";
last_success_at?: string;
- total_usd?: number;
- total_cny?: number;
- cash_or_unallocated_usd?: number;
+ total_usd?: number | null;
+ total_cny?: number | null;
priced_value_usd?: number;
cash_usd?: number;
unpriced_or_other_usd?: number;
@@ -115,6 +120,7 @@ export interface PortfolioAccount {
export interface PortfolioSnapshot {
snapshot_id: string;
created_at: string;
+ /** False whenever any enabled source did not reach `status === "ok"`. */
complete: boolean;
display_currency?: "USD" | "CNY";
totals: { usd: number; cny: number };
@@ -134,6 +140,7 @@ export interface PortfolioSnapshot {
brokers?: string[];
unrealized_pnl_usd?: number;
}>;
+ /** Backend-authored English notes; rendered verbatim, not translated. */
warnings: string[];
}
diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsx
index 8805da04d..517c55087 100644
--- a/frontend/src/pages/Portfolio.tsx
+++ b/frontend/src/pages/Portfolio.tsx
@@ -26,6 +26,9 @@ import {
type PortfolioSourceCatalogItem,
} from "@/lib/api";
import { echarts } from "@/lib/echarts";
+import { getChartTheme } from "@/lib/chart-theme";
+import { useThemeDark } from "@/lib/theme-store";
+import i18n from "@/i18n";
const BROKER_COLORS: Record<string, string> = {
IBKR: "#f05a47",
@@ -38,35 +41,65 @@ const HOLDING_COLORS = [
"#2d9cdb", "#d96c9d", "#7f8c8d", "#b5c83b", "#f05a47",
];
-function money(value: number | undefined, currency: "USD" | "CNY" = "USD") {
+/**
+ * Locale used by every Intl formatter on this page. The formatters live at
+ * module scope (chart option builders need them outside React), so they read
+ * the language off the i18n singleton rather than through a hook; components
+ * that render them subscribe to `useTranslation()` and therefore re-render
+ * whenever the language changes.
+ */
+function uiLocale(): string {
+ return i18n.language || "en";
+}
+
+function money(value: number | null | undefined, currency: "USD" | "CNY" = "USD") {
if (value == null || !Number.isFinite(value)) return "—";
- return new Intl.NumberFormat(undefined, {
+ return new Intl.NumberFormat(uiLocale(), {
style: "currency",
currency,
maximumFractionDigits: currency === "USD" ? 2 : 0,
}).format(value);
}
-function quantity(value: number | undefined) {
+function quantity(value: number | null | undefined) {
if (value == null || !Number.isFinite(value)) return "—";
- return new Intl.NumberFormat(undefined, { maximumFractionDigits: 8 }).format(value);
+ return new Intl.NumberFormat(uiLocale(), { maximumFractionDigits: 8 }).format(value);
}
function price(value: number | undefined | null) {
if (value == null || !Number.isFinite(value)) return "—";
- return new Intl.NumberFormat(undefined, {
+ return new Intl.NumberFormat(uiLocale(), {
minimumFractionDigits: value >= 1 ? 2 : 4,
maximumFractionDigits: value >= 100 ? 2 : value >= 1 ? 4 : 8,
}).format(value);
}
-function percentage(value: number | undefined) {
+function percentage(value: number | null | undefined) {
if (value == null || !Number.isFinite(value)) return "—";
- return `${(value * 100).toFixed(1)}%`;
+ return new Intl.NumberFormat(uiLocale(), {
+ style: "percent",
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1,
+ }).format(value);
+}
+
+/** ECharts reports slice shares as 0-100; `percentage` expects a 0-1 ratio. */
+function slicePercentage(percent: number) {
+ return percentage(percent / 100);
+}
+
+/** Compact USD tick label for the history axis, e.g. "$120K" / "1,2 Mio. $". */
+function compactUsd(value: number) {
+ return new Intl.NumberFormat(uiLocale(), {
+ style: "currency",
+ currency: "USD",
+ notation: "compact",
+ maximumFractionDigits: 1,
+ }).format(value);
}
function dateTime(value: string | undefined) {
- return value ? new Date(value).toLocaleString() : "—";
+ return value ? new Date(value).toLocaleString(uiLocale()) : "—";
}
function dayKey(value: string) {
@@ -74,9 +107,15 @@ function dayKey(value: string) {
return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
}
+/**
+ * Multi-account portfolio overview built from local read-only connections.
+ *
+ * An account the backend could not read arrives with `status === "error"` and
+ * no totals; it contributes nothing to the headline figures and is rendered as
+ * a failure card so the totals are never read as if those holdings counted.
+ */
export function Portfolio() {
- const { i18n } = useTranslation();
- const zh = i18n.language.startsWith("zh");
+ const { t } = useTranslation();
const [snapshot, setSnapshot] = useState<PortfolioSnapshot | null>(null);
const [history, setHistory] = useState<PortfolioHistoryPoint[]>([]);
const [loading, setLoading] = useState(true);
@@ -105,7 +144,7 @@ export function Portfolio() {
setPortfolioSettings(configuration.settings);
setSourceCatalog(configuration.catalog);
} catch (err) {
- setError(err instanceof Error ? err.message : "Portfolio unavailable");
+ setError(err instanceof Error ? err.message : t("portfolio.page.errorLoad"));
} finally {
setLoading(false);
}
@@ -138,7 +177,7 @@ export function Portfolio() {
const status = await api.getPortfolioRefreshStatus();
setRefreshState(normalizeRefreshState(status.refresh));
} catch (err) {
- setError(err instanceof Error ? err.message : "Refresh failed");
+ setError(err instanceof Error ? err.message : t("portfolio.page.errorRefresh"));
} finally {
window.clearInterval(timer);
setRefreshing(false);
@@ -152,7 +191,7 @@ export function Portfolio() {
await api.reconnectPortfolioSource(sourceId);
await refresh();
} catch (err) {
- setError(err instanceof Error ? err.message : "Account reconnect failed");
+ setError(err instanceof Error ? err.message : t("portfolio.page.errorReconnect"));
} finally {
setReconnecting(false);
}
@@ -173,7 +212,7 @@ export function Portfolio() {
setSnapshot(null);
}
} catch (err) {
- setError(err instanceof Error ? err.message : "Unable to save portfolio settings");
+ setError(err instanceof Error ? err.message : t("portfolio.page.errorSaveSettings"));
} finally {
setSavingSettings(false);
}
@@ -195,7 +234,7 @@ export function Portfolio() {
anchor.click();
URL.revokeObjectURL(url);
} catch (err) {
- setError(err instanceof Error ? err.message : "Export failed");
+ setError(err instanceof Error ? err.message : t("portfolio.page.errorExport"));
}
}
@@ -210,6 +249,11 @@ export function Portfolio() {
.sort((a, b) => (b.market_value_usd ?? 0) - (a.market_value_usd ?? 0));
}, [snapshot, query, sourceFilter]);
+ const failedAccounts = useMemo(
+ () => (snapshot?.accounts ?? []).filter((row) => row.status === "error"),
+ [snapshot],
+ );
+
const brokerAllocation = useMemo(() => (snapshot?.accounts ?? [])
.filter((row) => row.status !== "error" && (row.total_usd ?? 0) > 0)
.map((row) => ({
@@ -225,17 +269,17 @@ export function Portfolio() {
.sort((a, b) => b.market_value_usd - a.market_value_usd);
const shown = rows.slice(0, 7).map((row) => ({ name: row.symbol, value: row.market_value_usd }));
const other = rows.slice(7).reduce((sum, row) => sum + row.market_value_usd, 0);
- if (other > 0) shown.push({ name: zh ? "其他持仓" : "Other", value: other });
+ if (other > 0) shown.push({ name: t("portfolio.allocation.other"), value: other });
const valuation = snapshot?.valuation;
- if ((valuation?.cash_usd ?? 0) > 0.01) shown.push({ name: zh ? "现金" : "Cash", value: valuation?.cash_usd ?? 0 });
- if ((valuation?.unpriced_or_other_usd ?? 0) > 0.01) shown.push({ name: zh ? "未定价/其他" : "Unpriced / other", value: valuation?.unpriced_or_other_usd ?? 0 });
+ if ((valuation?.cash_usd ?? 0) > 0.01) shown.push({ name: t("portfolio.allocation.cash"), value: valuation?.cash_usd ?? 0 });
+ if ((valuation?.unpriced_or_other_usd ?? 0) > 0.01) shown.push({ name: t("portfolio.allocation.unpriced"), value: valuation?.unpriced_or_other_usd ?? 0 });
if (!valuation && snapshot) {
const priced = rows.reduce((sum, row) => sum + row.market_value_usd, 0);
const residual = Math.max(0, snapshot.totals.usd - priced);
- if (residual > 0.01) shown.push({ name: zh ? "现金/未定价" : "Cash / unpriced", value: residual });
+ if (residual > 0.01) shown.push({ name: t("portfolio.allocation.cashUnpriced"), value: residual });
}
return shown;
- }, [snapshot, zh]);
+ }, [snapshot, t]);
const dailyChange = useMemo(() => {
if (!snapshot || !history.length) return null;
@@ -259,111 +303,149 @@ export function Portfolio() {
<div>
<div className="mb-3 inline-flex items-center gap-2 rounded-full border bg-card px-3 py-1 text-xs text-muted-foreground">
<ShieldCheck className="h-3.5 w-3.5 text-positive" />
- {zh ? "本机只读 · 多账户汇总" : "Local read-only · Multi-account"}
+ {t("portfolio.page.badge")}
</div>
- <h1 className="text-3xl font-semibold tracking-tight">{zh ? "持仓总览" : "Portfolio"}</h1>
- <p className="mt-2 text-sm text-muted-foreground">
- {zh ? "统一汇总已启用的只读连接;连接失败时保留最后一次成功数据。" : "Unified valuation for enabled read-only connections with stale-safe fallback."}
- </p>
- {snapshot ? <p className="mt-2 text-xs text-muted-foreground">USD/CNY {snapshot.fx.usd_cny.toFixed(4)} · {snapshot.fx.stale ? (zh ? "缓存汇率" : "cached FX") : (zh ? "最新汇率" : "fresh FX")}</p> : null}
+ <h1 className="text-3xl font-semibold tracking-tight">{t("portfolio.page.title")}</h1>
+ <p className="mt-2 text-sm text-muted-foreground">{t("portfolio.page.subtitle")}</p>
+ {snapshot ? (
+ <p className="mt-2 text-xs text-muted-foreground">
+ {t(snapshot.fx.stale ? "portfolio.page.fxCached" : "portfolio.page.fxFresh", { rate: snapshot.fx.usd_cny.toFixed(4) })}
+ </p>
+ ) : null}
</div>
<div className="flex flex-wrap gap-2">
<button onClick={() => setEditorOpen(true)} className="inline-flex items-center gap-2 rounded-md border bg-card px-4 py-2 text-sm">
- <Settings2 className="h-4 w-4" />{zh ? "管理账户" : "Manage accounts"}
+ <Settings2 className="h-4 w-4" />{t("portfolio.page.manageAccounts")}
</button>
<button onClick={() => void download()} disabled={!snapshot} className="inline-flex items-center gap-2 rounded-md border bg-card px-4 py-2 text-sm disabled:opacity-50">
- <Download className="h-4 w-4" /> CSV
+ <Download className="h-4 w-4" />{t("portfolio.page.exportCsv")}
</button>
<button onClick={() => void refresh()} disabled={refreshing || reconnecting} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50">
{refreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
- {refreshing ? (zh ? "正在刷新" : "Refreshing") : (zh ? "刷新全部账户" : "Refresh all")}
+ {refreshing ? t("portfolio.page.refreshing") : t("portfolio.page.refreshAll")}
</button>
</div>
</header>
{error ? <div className="flex items-start gap-2 rounded-lg border border-danger/30 bg-danger/5 p-4 text-sm text-danger"><AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />{error}</div> : null}
- {refreshing && refreshState ? <RefreshProgress state={refreshState} settings={portfolioSettings} zh={zh} /> : null}
+ {refreshing && refreshState ? <RefreshProgress state={refreshState} settings={portfolioSettings} /> : null}
{loading ? <div className="flex h-56 items-center justify-center"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div> : null}
{!loading && !snapshot ? (
<section className="rounded-xl border border-dashed p-12 text-center">
<WalletCards className="mx-auto h-8 w-8 text-muted-foreground" />
- <h2 className="mt-4 font-medium">{zh ? "还没有持仓快照" : "No portfolio snapshot yet"}</h2>
- <p className="mt-2 text-sm text-muted-foreground">{zh ? "添加至少一个只读账户后即可开始汇总。" : "Add at least one read-only account to begin."}</p>
- <button onClick={() => setEditorOpen(true)} className="mt-5 inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"><Settings2 className="h-4 w-4" />{zh ? "添加账户" : "Add account"}</button>
+ <h2 className="mt-4 font-medium">{t("portfolio.page.emptyTitle")}</h2>
+ <p className="mt-2 text-sm text-muted-foreground">{t("portfolio.page.emptyBody")}</p>
+ <button onClick={() => setEditorOpen(true)} className="mt-5 inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"><Settings2 className="h-4 w-4" />{t("portfolio.page.emptyAction")}</button>
</section>
) : null}
{snapshot ? (
<>
<section className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
- <Metric label={zh ? "总资产" : "Total assets"} value={money(totalDisplay, displayCurrency)} note={displayCurrency === "USD" ? money(snapshot.totals.cny, "CNY") : money(snapshot.totals.usd)} icon={<WalletCards className="h-4 w-4" />} />
- <Metric label={zh ? "今日资产变化" : "Today's asset change"} value={dailyChange == null ? "—" : `${dailyChange >= 0 ? "+" : ""}${money(dailyChange)}`} note={zh ? "包含行情、入金和出金影响" : "Includes market moves and cash flows"} tone={dailyChange == null ? undefined : dailyChange >= 0 ? "positive" : "danger"} icon={<Clock3 className="h-4 w-4" />} />
- <Metric label={zh ? "估值覆盖率" : "Valuation coverage"} value={percentage(coverage)} note={zh ? `已定价 ${money(snapshot.valuation?.priced_usd)} · 现金 ${money(snapshot.valuation?.cash_usd)}` : "Priced holdings plus identified cash"} icon={<Database className="h-4 w-4" />} />
- <Metric label={zh ? "最后完整更新" : "Last complete update"} value={latestCompleteAt ? new Date(latestCompleteAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "—"} note={dateTime(latestCompleteAt)} tone={snapshot.complete ? "positive" : "warning"} icon={snapshot.complete ? <CheckCircle2 className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4" />} />
+ <Metric
+ label={t("portfolio.metrics.total")}
+ value={money(totalDisplay, displayCurrency)}
+ note={displayCurrency === "USD" ? money(snapshot.totals.cny, "CNY") : money(snapshot.totals.usd)}
+ warningNote={failedAccounts.length ? t("portfolio.metrics.excluded", { count: failedAccounts.length }) : undefined}
+ icon={<WalletCards className="h-4 w-4" />}
+ />
+ <Metric
+ label={t("portfolio.metrics.change")}
+ value={dailyChange == null ? "—" : `${dailyChange >= 0 ? "+" : ""}${money(dailyChange)}`}
+ note={t("portfolio.metrics.changeNote")}
+ tone={dailyChange == null ? undefined : dailyChange >= 0 ? "positive" : "danger"}
+ icon={<Clock3 className="h-4 w-4" />}
+ />
+ <Metric
+ label={t("portfolio.metrics.coverage")}
+ value={percentage(coverage)}
+ note={t("portfolio.metrics.coverageNote", { priced: money(snapshot.valuation?.priced_usd), cash: money(snapshot.valuation?.cash_usd) })}
+ icon={<Database className="h-4 w-4" />}
+ />
+ <Metric
+ label={t("portfolio.metrics.lastComplete")}
+ value={latestCompleteAt ? new Date(latestCompleteAt).toLocaleTimeString(uiLocale(), { hour: "2-digit", minute: "2-digit" }) : "—"}
+ note={dateTime(latestCompleteAt)}
+ tone={snapshot.complete ? "positive" : "warning"}
+ icon={snapshot.complete ? <CheckCircle2 className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4" />}
+ />
</section>
<section className="grid gap-4 xl:grid-cols-2">
- <AllocationPie title={zh ? "按账户分布" : "Allocation by account"} data={brokerAllocation} centerLabel={money(totalDisplay, displayCurrency)} onSelect={(id) => setSourceFilter(id)} />
- <AllocationPie title={zh ? "按持仓标的分布" : "Allocation by holding"} data={holdingAllocation} centerLabel={zh ? "持仓占比" : "Holdings"} />
+ <AllocationPie title={t("portfolio.allocation.byAccount")} data={brokerAllocation} centerLabel={money(totalDisplay, displayCurrency)} onSelect={(id) => setSourceFilter(id)} />
+ <AllocationPie title={t("portfolio.allocation.byHolding")} data={holdingAllocation} centerLabel={t("portfolio.allocation.center")} />
</section>
{snapshot.warnings.length ? (
<section className="rounded-lg border border-warning/30 bg-warning/5 p-4 text-sm">
- <div className="mb-2 font-medium text-warning">{zh ? "数据说明" : "Data notes"}</div>
+ <div className="mb-2 font-medium text-warning">{t("portfolio.page.warningsTitle")}</div>
<div className="space-y-1.5">{snapshot.warnings.map((warning) => <div key={warning} className="flex gap-2"><AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warning" /><span>{warning}</span></div>)}</div>
</section>
) : null}
<section>
<div className="mb-3 flex items-end justify-between gap-3">
- <div><h2 className="font-semibold">{zh ? "账户状态" : "Account status"}</h2><p className="mt-1 text-xs text-muted-foreground">{zh ? "点击账户卡可筛选下方持仓" : "Click an account to filter holdings"}</p></div>
- {sourceFilter !== "all" ? <button className="text-xs text-primary" onClick={() => setSourceFilter("all")}>{zh ? "清除筛选" : "Clear filter"}</button> : null}
+ <div><h2 className="font-semibold">{t("portfolio.accounts.title")}</h2><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.accounts.hint")}</p></div>
+ {sourceFilter !== "all" ? <button className="text-xs text-primary" onClick={() => setSourceFilter("all")}>{t("portfolio.accounts.clearFilter")}</button> : null}
</div>
<div className="grid gap-3 lg:grid-cols-3">
{snapshot.accounts.map((account) => (
- <AccountCard key={account.source_id ?? account.broker} account={account} active={sourceFilter === (account.source_id ?? account.broker)} zh={zh} displayCurrency={displayCurrency} onClick={() => { const id = account.source_id ?? account.broker; setSourceFilter((current) => current === id ? "all" : id); }} onReconnect={account.auth?.method === "OAuth" && account.source_id ? () => void reconnectSource(account.source_id!) : undefined} reconnecting={reconnecting} />
+ <AccountCard key={account.source_id ?? account.broker} account={account} active={sourceFilter === (account.source_id ?? account.broker)} displayCurrency={displayCurrency} onClick={() => { const id = account.source_id ?? account.broker; setSourceFilter((current) => current === id ? "all" : id); }} onReconnect={account.auth?.method === "OAuth" && account.source_id ? () => void reconnectSource(account.source_id!) : undefined} reconnecting={reconnecting} />
))}
</div>
</section>
<section className="overflow-hidden rounded-xl border bg-card">
<div className="flex flex-col gap-3 border-b p-4 lg:flex-row lg:items-center lg:justify-between">
- <div><h2 className="font-semibold">{zh ? "持仓明细" : "Holdings"}</h2><p className="mt-1 text-xs text-muted-foreground">{positions.length} {zh ? "项持仓" : "positions"}</p></div>
- <div className="relative w-full lg:w-72"><Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" /><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder={zh ? "搜索账户、标的或市场" : "Search broker, symbol or market"} className="w-full rounded-md border bg-background py-2 pl-9 pr-3 text-sm" /></div>
+ <div><h2 className="font-semibold">{t("portfolio.holdings.title")}</h2><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.holdings.count", { count: positions.length })}</p></div>
+ <div className="relative w-full lg:w-72"><Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" /><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t("portfolio.holdings.search")} aria-label={t("portfolio.holdings.search")} className="w-full rounded-md border bg-background py-2 pl-9 pr-3 text-sm" /></div>
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[1050px] text-sm">
- <thead className="bg-muted/40 text-left text-xs text-muted-foreground"><tr><Th>{zh ? "账户" : "Broker"}</Th><Th>{zh ? "标的" : "Symbol"}</Th><Th>{zh ? "类别" : "Type"}</Th><Th>{zh ? "数量" : "Quantity"}</Th><Th>{zh ? "成本 / 现价" : "Cost / Price"}</Th><Th>{zh ? "市值" : "Value"}</Th><Th>{zh ? "占比" : "Weight"}</Th><Th>{zh ? "未实现盈亏" : "Unrealized P/L"}</Th><Th>{zh ? "数据状态" : "Data"}</Th></tr></thead>
+ <thead className="bg-muted/40 text-left text-xs text-muted-foreground"><tr><Th>{t("portfolio.holdings.colBroker")}</Th><Th>{t("portfolio.holdings.colSymbol")}</Th><Th>{t("portfolio.holdings.colType")}</Th><Th>{t("portfolio.holdings.colQuantity")}</Th><Th>{t("portfolio.holdings.colCostPrice")}</Th><Th>{t("portfolio.holdings.colValue")}</Th><Th>{t("portfolio.holdings.colWeight")}</Th><Th>{t("portfolio.holdings.colPnl")}</Th><Th>{t("portfolio.holdings.colData")}</Th></tr></thead>
<tbody className="divide-y">
{positions.map((row) => {
const weight = snapshot.totals.usd > 0 ? row.market_value_usd / snapshot.totals.usd : 0;
- return <tr key={`${row.source_id ?? row.broker}-${row.symbol}`} className="hover:bg-muted/20"><Td><div className="font-medium">{row.source_label ?? row.broker.toUpperCase()}</div><div className="mt-1 text-xs"><BrokerBadge broker={row.broker} /></div></Td><Td><div className="font-medium">{row.symbol}</div><div className="max-w-52 truncate text-xs text-muted-foreground">{row.name}</div></Td><Td><span className="capitalize text-muted-foreground">{row.asset_type}</span></Td><Td>{quantity(row.quantity)}</Td><Td><div>{price(row.cost_price)}</div><div className="text-xs text-muted-foreground">{price(row.market_price)}</div></Td><Td><div className="font-medium">{row.priced ? money(row.market_value_usd) : "—"}</div><div className="text-xs text-muted-foreground">{row.priced ? money(row.market_value_cny, "CNY") : "未定价"}</div></Td><Td>{row.priced ? percentage(weight) : "—"}</Td><Td><span className={row.unrealized_pnl_usd == null ? "text-muted-foreground" : row.unrealized_pnl_usd >= 0 ? "text-positive" : "text-danger"}>{row.unrealized_pnl_usd == null ? "—" : money(row.unrealized_pnl_usd)}</span></Td><Td><DataBadge stale={row.stale} priced={row.priced} zh={zh} /></Td></tr>;
+ return <tr key={`${row.source_id ?? row.broker}-${row.symbol}`} className="hover:bg-muted/20"><Td><div className="font-medium">{row.source_label ?? row.broker.toUpperCase()}</div><div className="mt-1 text-xs"><BrokerBadge broker={row.broker} /></div></Td><Td><div className="font-medium">{row.symbol}</div><div className="max-w-52 truncate text-xs text-muted-foreground">{row.name}</div></Td><Td><span className="capitalize text-muted-foreground">{row.asset_type}</span></Td><Td>{quantity(row.quantity)}</Td><Td><div>{price(row.cost_price)}</div><div className="text-xs text-muted-foreground">{price(row.market_price)}</div></Td><Td><div className="font-medium">{row.priced ? money(row.market_value_usd) : "—"}</div><div className="text-xs text-muted-foreground">{row.priced ? money(row.market_value_cny, "CNY") : t("portfolio.holdings.unpriced")}</div></Td><Td>{row.priced ? percentage(weight) : "—"}</Td><Td><span className={row.unrealized_pnl_usd == null ? "text-muted-foreground" : row.unrealized_pnl_usd >= 0 ? "text-positive" : "text-danger"}>{row.unrealized_pnl_usd == null ? "—" : money(row.unrealized_pnl_usd)}</span></Td><Td><DataBadge priced={row.priced} /></Td></tr>;
})}
</tbody>
</table>
</div>
</section>
- <HistoryChart history={history} zh={zh} />
+ <HistoryChart history={history} />
<section className="rounded-xl border bg-card p-5">
- <div className="mb-4 flex items-center gap-2"><KeyRound className="h-4 w-4 text-muted-foreground" /><h2 className="font-semibold">{zh ? "连接与凭证" : "Connections and credentials"}</h2></div>
- <div className="grid gap-3 lg:grid-cols-3">{snapshot.accounts.map((account) => <CredentialCard key={account.source_id ?? account.broker} account={account} zh={zh} />)}</div>
+ <div className="mb-4 flex items-center gap-2"><KeyRound className="h-4 w-4 text-muted-foreground" /><h2 className="font-semibold">{t("portfolio.credentials.title")}</h2></div>
+ <div className="grid gap-3 lg:grid-cols-3">{snapshot.accounts.map((account) => <CredentialCard key={account.source_id ?? account.broker} account={account} />)}</div>
</section>
</>
) : null}
</div>
- <PortfolioSourceEditor open={editorOpen} settings={portfolioSettings} catalog={sourceCatalog} saving={savingSettings} zh={zh} onClose={() => setEditorOpen(false)} onSave={savePortfolioSettings} onConnectionsChanged={reloadConnections} />
+ <PortfolioSourceEditor open={editorOpen} settings={portfolioSettings} catalog={sourceCatalog} saving={savingSettings} onClose={() => setEditorOpen(false)} onSave={savePortfolioSettings} onConnectionsChanged={reloadConnections} />
</div>
);
}
-function Metric({ label, value, note, icon, tone }: { label: string; value: string; note?: string; icon: ReactNode; tone?: "positive" | "danger" | "warning" }) {
+/** Headline figure tile; `warningNote` is the amber caveat under the value. */
+function Metric({ label, value, note, warningNote, icon, tone }: { label: string; value: string; note?: string; warningNote?: string; icon: ReactNode; tone?: "positive" | "danger" | "warning" }) {
const toneClass = tone === "positive" ? "text-positive" : tone === "danger" ? "text-danger" : tone === "warning" ? "text-warning" : "";
- return <div className="rounded-xl border bg-card p-5"><div className="flex items-center justify-between text-xs text-muted-foreground"><span>{label}</span>{icon}</div><div className={`mt-3 text-2xl font-semibold tracking-tight ${toneClass}`}>{value}</div>{note ? <div className="mt-1 truncate text-xs text-muted-foreground" title={note}>{note}</div> : null}</div>;
+ return <div className="rounded-xl border bg-card p-5">
+ <div className="flex items-center justify-between text-xs text-muted-foreground"><span>{label}</span>{icon}</div>
+ <div className={`mt-3 text-2xl font-semibold tracking-tight ${toneClass}`}>{value}</div>
+ {note ? <div className="mt-1 truncate text-xs text-muted-foreground" title={note}>{note}</div> : null}
+ {warningNote ? <div className="mt-1 flex items-start gap-1.5 text-xs text-warning"><AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" /><span>{warningNote}</span></div> : null}
+ </div>;
}
+/**
+ * Coerce a refresh payload into the shape the progress panel renders.
+ *
+ * Older backends reported per-source progress under `brokers`, and a source
+ * entry can arrive as null; both are normalized here so a malformed payload
+ * cannot take the page down mid-refresh.
+ */
function normalizeRefreshState(state: PortfolioRefreshState | null | undefined): PortfolioRefreshState {
const candidate = state?.sources ?? state?.brokers;
const sources = candidate && typeof candidate === "object" && !Array.isArray(candidate)
@@ -380,20 +462,56 @@ function normalizeRefreshState(state: PortfolioRefreshState | null | undefined):
};
}
-function RefreshProgress({ state, settings, zh }: { state: PortfolioRefreshState; settings: PortfolioSettings | null; zh: boolean }) {
+function RefreshProgress({ state, settings }: { state: PortfolioRefreshState; settings: PortfolioSettings | null }) {
+ const { t } = useTranslation();
const labels = new Map(settings?.sources.map((source) => [source.connection_id, source.label]) ?? []);
const entries = Object.entries(normalizeRefreshState(state).sources ?? {});
- return <section className="rounded-lg border bg-card p-4"><div className="mb-3 flex items-center gap-2 text-sm font-medium"><Loader2 className="h-4 w-4 animate-spin text-primary" />{zh ? "正在依次读取已启用账户" : "Refreshing enabled accounts sequentially"}</div><div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">{entries.map(([sourceId, item]) => { const status = item.status ?? "pending"; return <div key={sourceId} className="flex items-center justify-between gap-3 rounded-md bg-muted/40 px-3 py-2 text-xs"><span className="truncate font-medium" title={labels.get(sourceId) ?? sourceId}>{labels.get(sourceId) ?? sourceId}</span><span className={status === "ok" ? "text-positive" : status === "error" ? "text-danger" : "text-muted-foreground"}>{status === "refreshing" ? (zh ? "读取中" : "Reading") : status === "ok" ? (zh ? "完成" : "Done") : status === "error" ? (zh ? "失败" : "Failed") : (zh ? "等待" : "Waiting")}</span></div>; })}</div></section>;
+ const statusLabel = (status: string) => status === "refreshing"
+ ? t("portfolio.status.reading")
+ : status === "ok"
+ ? t("portfolio.status.done")
+ : status === "error"
+ ? t("portfolio.status.failed")
+ : t("portfolio.status.waiting");
+ return <section className="rounded-lg border bg-card p-4">
+ <div className="mb-3 flex items-center gap-2 text-sm font-medium"><Loader2 className="h-4 w-4 animate-spin text-primary" />{t("portfolio.status.title")}</div>
+ <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">{entries.map(([sourceId, item]) => {
+ const status = item.status ?? "pending";
+ return <div key={sourceId} className="flex items-center justify-between gap-3 rounded-md bg-muted/40 px-3 py-2 text-xs">
+ <span className="truncate font-medium" title={labels.get(sourceId) ?? sourceId}>{labels.get(sourceId) ?? sourceId}</span>
+ <span className={status === "ok" ? "text-positive" : status === "error" ? "text-danger" : "text-muted-foreground"}>{statusLabel(status)}</span>
+ </div>;
+ })}</div>
+ </section>;
}
-function AccountCard({ account, active, zh, displayCurrency, onClick, onReconnect, reconnecting }: { account: PortfolioAccount; active: boolean; zh: boolean; displayCurrency: "USD" | "CNY"; onClick: () => void; onReconnect?: () => void; reconnecting: boolean }) {
- const stale = account.status === "stale";
+/**
+ * One account tile. A source with `status === "error"` has no totals at all —
+ * it renders the failure, the error text and the last successful read time
+ * instead of a value, so nothing on the card suggests it is part of the total.
+ */
+function AccountCard({ account, active, displayCurrency, onClick, onReconnect, reconnecting }: { account: PortfolioAccount; active: boolean; displayCurrency: "USD" | "CNY"; onClick: () => void; onReconnect?: () => void; reconnecting: boolean }) {
+ const { t } = useTranslation();
const failed = account.status === "error";
return <div role="button" tabIndex={0} onClick={onClick} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") onClick(); }} className={`cursor-pointer rounded-xl border bg-card p-5 transition ${active ? "border-primary ring-1 ring-primary/20" : "hover:border-primary/40"}`}>
- <div className="flex items-center justify-between"><div><div className="font-medium">{account.label ?? account.broker.toUpperCase()}</div><div className="mt-1 text-xs"><BrokerBadge broker={account.broker} /></div></div>{failed ? <WifiOff className="h-4 w-4 text-danger" /> : stale ? <AlertTriangle className="h-4 w-4 text-warning" /> : <CheckCircle2 className="h-4 w-4 text-positive" />}</div>
- {failed ? <p className="mt-4 text-sm text-danger">{zh ? "连接失败,且没有可用缓存" : "Connection failed with no cache"}</p> : <><div className="mt-4 text-2xl font-semibold">{displayCurrency === "CNY" ? money(account.total_cny, "CNY") : money(account.total_usd)}</div><div className="mt-1 text-xs text-muted-foreground">{displayCurrency === "CNY" ? money(account.total_usd) : money(account.total_cny, "CNY")} · {account.position_count ?? 0} {zh ? "项持仓" : "positions"}</div><div className="mt-4 flex items-center justify-between border-t pt-3 text-xs"><span className={stale ? "text-warning" : "text-positive"}>{stale ? (zh ? "使用缓存" : "Cached") : (zh ? "数据正常" : "Fresh")}</span><span className="text-muted-foreground">{dateTime(account.last_success_at)}</span></div></>}
- {(failed || stale) && account.error ? <p className="mt-3 line-clamp-2 text-xs text-muted-foreground" title={account.error}>{account.error}</p> : null}
- {(failed || stale) && onReconnect ? <button onClick={(event) => { event.stopPropagation(); onReconnect(); }} disabled={reconnecting} className="mt-3 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50">{reconnecting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}{zh ? "重新连接" : "Reconnect"}</button> : null}
+ <div className="flex items-center justify-between">
+ <div><div className="font-medium">{account.label ?? account.broker.toUpperCase()}</div><div className="mt-1 text-xs"><BrokerBadge broker={account.broker} /></div></div>
+ {failed ? <WifiOff className="h-4 w-4 text-danger" /> : <CheckCircle2 className="h-4 w-4 text-positive" />}
+ </div>
+ {failed ? (
+ <>
+ <p className="mt-4 text-sm text-danger">{t("portfolio.accounts.failed")}</p>
+ <p className="mt-2 text-xs text-muted-foreground">{account.last_success_at ? t("portfolio.accounts.lastSuccess", { time: dateTime(account.last_success_at) }) : t("portfolio.accounts.noSuccess")}</p>
+ </>
+ ) : (
+ <>
+ <div className="mt-4 text-2xl font-semibold">{displayCurrency === "CNY" ? money(account.total_cny, "CNY") : money(account.total_usd)}</div>
+ <div className="mt-1 text-xs text-muted-foreground">{displayCurrency === "CNY" ? money(account.total_usd) : money(account.total_cny, "CNY")} · {t("portfolio.accounts.positions", { count: account.position_count ?? 0 })}</div>
+ <div className="mt-4 flex items-center justify-between border-t pt-3 text-xs"><span className="text-positive">{t("portfolio.accounts.fresh")}</span><span className="text-muted-foreground">{dateTime(account.last_success_at)}</span></div>
+ </>
+ )}
+ {failed && account.error ? <p className="mt-3 line-clamp-2 text-xs text-muted-foreground" title={account.error}>{account.error}</p> : null}
+ {failed && onReconnect ? <button onClick={(event) => { event.stopPropagation(); onReconnect(); }} disabled={reconnecting} className="mt-3 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50">{reconnecting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}{t("portfolio.accounts.reconnect")}</button> : null}
</div>;
}
@@ -402,61 +520,99 @@ function BrokerBadge({ broker }: { broker: string }) {
return <span className="inline-flex items-center gap-2 font-medium uppercase"><span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: color }} />{broker}</span>;
}
-function DataBadge({ stale, priced, zh }: { stale?: boolean; priced: boolean; zh: boolean }) {
- if (stale) return <span className="rounded-full bg-warning/10 px-2 py-1 text-xs text-warning">{zh ? "缓存" : "Cached"}</span>;
- if (!priced) return <span className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">{zh ? "未定价" : "Unpriced"}</span>;
- return <span className="rounded-full bg-positive/10 px-2 py-1 text-xs text-positive">{zh ? "最新" : "Fresh"}</span>;
+function DataBadge({ priced }: { priced: boolean }) {
+ const { t } = useTranslation();
+ if (!priced) return <span className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">{t("portfolio.holdings.unpriced")}</span>;
+ return <span className="rounded-full bg-positive/10 px-2 py-1 text-xs text-positive">{t("portfolio.holdings.priced")}</span>;
}
-function CredentialCard({ account, zh }: { account: PortfolioAccount; zh: boolean }) {
+function CredentialCard({ account }: { account: PortfolioAccount }) {
+ const { t } = useTranslation();
const auth = account.auth;
- const renewal = auth?.renewal === "automatic" ? (zh ? "连接器自动续期" : "Connector-managed renewal") : auth?.renewal === "session" ? (zh ? "依赖本地会话" : "Local session") : (zh ? "由服务商管理有效期" : "Provider-managed validity");
- return <div className="rounded-lg border p-4"><div className="flex items-center justify-between gap-3"><div><span className="font-medium">{account.label ?? account.broker.toUpperCase()}</span><div className="mt-1 text-xs text-muted-foreground">{account.broker.toUpperCase()}</div></div><span className={`shrink-0 rounded-full px-2 py-1 text-xs ${auth?.readonly ? "bg-positive/10 text-positive" : "bg-warning/10 text-warning"}`}>{auth?.readonly ? (zh ? "只读连接模板" : "Read-only profile") : (zh ? "连接模板可写" : "Write-capable profile")}</span></div><div className="mt-3 text-sm">{auth?.method ?? "—"} · {renewal}</div><p className="mt-1 text-xs text-muted-foreground">{auth?.detail ?? "—"}</p></div>;
+ const renewal = auth?.renewal === "automatic"
+ ? t("portfolio.credentials.renewalAutomatic")
+ : auth?.renewal === "session"
+ ? t("portfolio.credentials.renewalSession")
+ : t("portfolio.credentials.renewalProvider");
+ return <div className="rounded-lg border p-4">
+ <div className="flex items-center justify-between gap-3">
+ <div><span className="font-medium">{account.label ?? account.broker.toUpperCase()}</span><div className="mt-1 text-xs text-muted-foreground">{account.broker.toUpperCase()}</div></div>
+ <span className={`shrink-0 rounded-full px-2 py-1 text-xs ${auth?.readonly ? "bg-positive/10 text-positive" : "bg-warning/10 text-warning"}`}>{auth?.readonly ? t("portfolio.credentials.readOnlyProfile") : t("portfolio.credentials.writableProfile")}</span>
+ </div>
+ <div className="mt-3 text-sm">{auth?.method ?? "—"} · {renewal}</div>
+ <p className="mt-1 text-xs text-muted-foreground">{auth?.detail ?? "—"}</p>
+ </div>;
}
type AllocationDatum = { id?: string; name: string; value: number; connector?: string };
function AllocationPie({ title, data, centerLabel, onSelect }: { title: string; data: AllocationDatum[]; centerLabel: string; onSelect?: (id: string) => void }) {
const ref = useRef<HTMLDivElement>(null);
+ const { i18n: instance } = useTranslation();
+ const dark = useThemeDark();
useEffect(() => {
if (!ref.current || ref.current.clientWidth === 0) return;
+ const theme = getChartTheme();
const chart = echarts.init(ref.current);
const brokerPalette = data.map((item) => BROKER_COLORS[(item.connector ?? item.name).toUpperCase()]).filter(Boolean);
const palette = brokerPalette.length === data.length ? brokerPalette : HOLDING_COLORS;
chart.setOption({
+ backgroundColor: "transparent",
color: palette,
- tooltip: { trigger: "item", formatter: (params: { name: string; value: number; percent: number }) => `${params.name}<br/>${money(params.value)} · ${params.percent.toFixed(1)}%` },
- legend: { type: "scroll", bottom: 0, left: "center", textStyle: { color: "#7c8493" } },
- series: [{ type: "pie", radius: ["46%", "70%"], center: ["50%", "43%"], avoidLabelOverlap: true, padAngle: 2, itemStyle: { borderRadius: 5 }, label: { show: true, formatter: (params: { name: string; percent: number }) => params.percent >= 2 ? `${params.name}\n${params.percent.toFixed(1)}%` : "", fontSize: 12 }, labelLine: { length: 10, length2: 7 }, labelLayout: { hideOverlap: true }, data }],
- graphic: [{ type: "text", left: "center", top: "39%", style: { text: centerLabel, textAlign: "center", fill: "#7c8493", fontSize: 12, fontWeight: 600 } }],
+ tooltip: {
+ trigger: "item",
+ backgroundColor: theme.tooltipBg,
+ borderColor: theme.tooltipBorder,
+ textStyle: { color: theme.tooltipText },
+ formatter: (params: { name: string; value: number; percent: number }) => `${params.name}<br/>${money(params.value)} · ${slicePercentage(params.percent)}`,
+ },
+ legend: { type: "scroll", bottom: 0, left: "center", textStyle: { color: theme.textColor }, pageTextStyle: { color: theme.textColor } },
+ series: [{ type: "pie", radius: ["46%", "70%"], center: ["50%", "43%"], avoidLabelOverlap: true, padAngle: 2, itemStyle: { borderRadius: 5 }, label: { show: true, color: theme.textColor, formatter: (params: { name: string; percent: number }) => params.percent >= 2 ? `${params.name}\n${slicePercentage(params.percent)}` : "", fontSize: 12 }, labelLine: { length: 10, length2: 7, lineStyle: { color: theme.gridColor } }, labelLayout: { hideOverlap: true }, data }],
+ graphic: [{ type: "text", left: "center", top: "39%", style: { text: centerLabel, textAlign: "center", fill: theme.textColor, fontSize: 12, fontWeight: 600 } }],
});
const resize = () => chart.resize();
const select = (params: { dataIndex?: number }) => { const item = params.dataIndex == null ? undefined : data[params.dataIndex]; if (item && onSelect) onSelect(item.id ?? item.name); };
chart.on("click", select);
window.addEventListener("resize", resize);
return () => { window.removeEventListener("resize", resize); chart.off("click", select); chart.dispose(); };
- }, [data, centerLabel, onSelect]);
+ }, [data, centerLabel, onSelect, dark, instance.language]);
return <div className="rounded-xl border bg-card p-5"><h2 className="font-semibold">{title}</h2><div ref={ref} className="h-80 w-full" /></div>;
}
-function HistoryChart({ history, zh }: { history: PortfolioHistoryPoint[]; zh: boolean }) {
+function HistoryChart({ history }: { history: PortfolioHistoryPoint[] }) {
const ref = useRef<HTMLDivElement>(null);
+ const { t, i18n: instance } = useTranslation();
+ const dark = useThemeDark();
useEffect(() => {
if (!ref.current || ref.current.clientWidth === 0) return;
+ const theme = getChartTheme();
const chart = echarts.init(ref.current);
const rows = history.slice(-180);
chart.setOption({
+ backgroundColor: "transparent",
grid: { left: 18, right: 18, top: 25, bottom: 28, containLabel: true },
- tooltip: { trigger: "axis", formatter: (items: Array<{ dataIndex: number; value: number }>) => { const item = items[0]; const row = rows[item.dataIndex]; return `${dateTime(row?.created_at)}<br/>${money(Number(item?.value))}`; } },
- xAxis: { type: "category", boundaryGap: false, data: rows.map((row) => new Date(row.created_at).toLocaleString([], { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" })), axisLabel: { color: "#7c8493", hideOverlap: true }, axisLine: { lineStyle: { color: "#d6d9df" } } },
- yAxis: { type: "value", scale: true, axisLabel: { color: "#7c8493", formatter: (value: number) => `$${Math.round(value / 1000)}k` }, splitLine: { lineStyle: { color: "#d6d9df", opacity: 0.45 } } },
+ tooltip: {
+ trigger: "axis",
+ backgroundColor: theme.tooltipBg,
+ borderColor: theme.tooltipBorder,
+ textStyle: { color: theme.tooltipText },
+ formatter: (items: Array<{ dataIndex: number; value: number }>) => { const item = items[0]; const row = rows[item.dataIndex]; return `${dateTime(row?.created_at)}<br/>${money(Number(item?.value))}`; },
+ },
+ xAxis: { type: "category", boundaryGap: false, data: rows.map((row) => new Date(row.created_at).toLocaleString(uiLocale(), { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" })), axisLabel: { color: theme.textColor, hideOverlap: true }, axisLine: { lineStyle: { color: theme.gridColor } } },
+ yAxis: { type: "value", scale: true, axisLabel: { color: theme.textColor, formatter: compactUsd }, splitLine: { lineStyle: { color: theme.gridColor, opacity: 0.45 } } },
series: [{ type: "line", data: rows.map((row) => Number(row.total_usd)), smooth: true, symbol: rows.length < 30 ? "circle" : "none", lineStyle: { width: 2, color: "#4f6edb" }, itemStyle: { color: "#4f6edb" }, areaStyle: { color: "rgba(79,110,219,0.10)" } }],
});
const resize = () => chart.resize();
window.addEventListener("resize", resize);
return () => { window.removeEventListener("resize", resize); chart.dispose(); };
- }, [history]);
- return <section className="rounded-xl border bg-card p-5"><div className="flex items-start justify-between gap-3"><div><h2 className="font-semibold">{zh ? "资产历史" : "Asset history"}</h2><p className="mt-1 text-xs text-muted-foreground">{zh ? "只显示完整快照;资产变化可能包含入金和出金。" : "Complete snapshots only; changes may include cash flows."}</p></div><span className="rounded-full bg-positive/10 px-2 py-1 text-xs text-positive">{history.length} {zh ? "个完整快照" : "complete snapshots"}</span></div>{history.length ? <div ref={ref} className="mt-4 h-64 w-full" /> : <div className="flex h-44 items-center justify-center text-sm text-muted-foreground">{zh ? "完成首次完整刷新后开始积累" : "History begins after a complete refresh"}</div>}</section>;
+ }, [history, dark, instance.language]);
+ return <section className="rounded-xl border bg-card p-5">
+ <div className="flex items-start justify-between gap-3">
+ <div><h2 className="font-semibold">{t("portfolio.history.title")}</h2><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.history.hint")}</p></div>
+ <span className="rounded-full bg-positive/10 px-2 py-1 text-xs text-positive">{t("portfolio.history.count", { count: history.length })}</span>
+ </div>
+ {history.length ? <div ref={ref} className="mt-4 h-64 w-full" /> : <div className="flex h-44 items-center justify-center text-sm text-muted-foreground">{t("portfolio.history.empty")}</div>}
+ </section>;
}
function Th({ children }: { children: ReactNode }) { return <th className="whitespace-nowrap px-4 py-3 font-medium">{children}</th>; }
diff --git a/frontend/src/pages/__tests__/Portfolio.test.tsx b/frontend/src/pages/__tests__/Portfolio.test.tsx
index 927f1e756..801737e3f 100644
--- a/frontend/src/pages/__tests__/Portfolio.test.tsx
+++ b/frontend/src/pages/__tests__/Portfolio.test.tsx
@@ -2,6 +2,7 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { Portfolio } from "@/pages/Portfolio";
import { api } from "@/lib/api";
+import i18n from "@/i18n";
vi.mock("@/lib/api", async () => {
const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");
@@ -63,6 +64,28 @@ const snapshot = {
warnings: [],
};
+// A source the backend could not read: status "error", no totals at all, and a
+// last_success_at that is history only. It contributes nothing to the totals,
+// which is why `complete` is false while the totals stay at the readable 1000.
+const FAILED_LAST_SUCCESS = "2026-08-08T09:30:00Z";
+const snapshotWithFailedSource = {
+ ...snapshot,
+ complete: false,
+ accounts: [
+ ...snapshot.accounts,
+ {
+ source_id: "binance-2",
+ broker: "binance",
+ label: "Binance backup",
+ status: "error" as const,
+ error_code: "ConnectionError",
+ error: "Read timed out after 30s",
+ last_success_at: FAILED_LAST_SUCCESS,
+ },
+ ],
+ warnings: ["Binance backup could not be read and is excluded from the totals."],
+};
+
const portfolioConfiguration = {
status: "ok",
settings: {
@@ -126,7 +149,7 @@ describe("Portfolio page", () => {
expect(await screen.findByText("AAPL")).toBeInTheDocument();
expect(screen.getByText("$1,000.00")).toBeInTheDocument();
- fireEvent.click(screen.getByRole("button", { name: /Refresh all|刷新全部账户/ }));
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.page.refreshAll") }));
await waitFor(() => expect(mocked.refreshPortfolio).toHaveBeenCalledTimes(1));
});
@@ -144,10 +167,10 @@ describe("Portfolio page", () => {
render(<Portfolio />);
await screen.findByText("AAPL");
- fireEvent.click(screen.getByRole("button", { name: /Refresh all|刷新全部账户/ }));
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.page.refreshAll") }));
await waitFor(() => expect(mocked.getPortfolioRefreshStatus).toHaveBeenCalled(), { timeout: 2_000 });
- expect(screen.getByRole("heading", { name: /Portfolio|持仓总览/ })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: i18n.t("portfolio.page.title") })).toBeInTheDocument();
finishRefresh({ status: "ok", snapshot });
await waitFor(() => expect(mocked.getPortfolioHistory).toHaveBeenCalledTimes(2));
@@ -157,11 +180,11 @@ describe("Portfolio page", () => {
render(<Portfolio />);
await screen.findByText("AAPL");
- fireEvent.click(screen.getByRole("button", { name: /Manage accounts|管理账户/ }));
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.page.manageAccounts") }));
expect(await screen.findByRole("dialog")).toBeInTheDocument();
- const labels = screen.getAllByRole("textbox", { name: /Account label|账户名称/ });
+ const labels = screen.getAllByRole("textbox", { name: i18n.t("portfolio.editor.accountLabel") });
fireEvent.change(labels[0], { target: { value: "Main IBKR" } });
- fireEvent.click(screen.getByRole("button", { name: /Save and refresh|保存并刷新/ }));
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.editor.save") }));
await waitFor(() => expect(mocked.updatePortfolioSettings).toHaveBeenCalledWith(
expect.objectContaining({
@@ -174,12 +197,12 @@ describe("Portfolio page", () => {
render(<Portfolio />);
await screen.findByText("AAPL");
- fireEvent.click(screen.getByRole("button", { name: /Manage accounts|管理账户/ }));
- fireEvent.click(await screen.findByRole("button", { name: /Open connection center|打开连接中心/ }));
- fireEvent.change(await screen.findByLabelText(/Read-only profile|只读连接模板/), {
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.page.manageAccounts") }));
+ fireEvent.click(await screen.findByRole("button", { name: i18n.t("portfolio.editor.openConnections") }));
+ fireEvent.change(await screen.findByLabelText(i18n.t("portfolio.connections.profile")), {
target: { value: "sample-live-readonly" },
});
- fireEvent.click(screen.getByRole("button", { name: /Create connection|创建本地连接/ }));
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.connections.create") }));
await waitFor(() => expect(mocked.createConnection).toHaveBeenCalledWith({
id: "sample-live",
@@ -187,4 +210,23 @@ describe("Portfolio page", () => {
label: "Sample Live · Local Read-Only",
}));
});
+
+ it("reports an unreadable account as an error and keeps it out of the total", async () => {
+ mocked.getPortfolio.mockResolvedValue({ status: "ok", snapshot: snapshotWithFailedSource });
+ render(<Portfolio />);
+ await screen.findByText("AAPL");
+
+ expect(screen.getByText(i18n.t("portfolio.accounts.failed"))).toBeInTheDocument();
+ expect(screen.getByText("Read timed out after 30s")).toBeInTheDocument();
+ expect(screen.getByText(
+ i18n.t("portfolio.accounts.lastSuccess", {
+ time: new Date(FAILED_LAST_SUCCESS).toLocaleString(i18n.language),
+ }),
+ )).toBeInTheDocument();
+
+ // The headline total stays at the readable value and says so out loud.
+ expect(screen.getByText("$1,000.00")).toBeInTheDocument();
+ expect(screen.getByText(i18n.t("portfolio.metrics.excluded", { count: 1 }))).toBeInTheDocument();
+ expect(screen.getByText(snapshotWithFailedSource.warnings[0])).toBeInTheDocument();
+ });
});