diff --git a/DEVLOG.md b/DEVLOG.md index f525464..455da6d 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -2909,3 +2909,7 @@ PMS最终代码56db0fd已推送,155 web/WS/beat为execution-2b1c447,worker 用户确认移除“观测”类别。页面统一普通、提示、警告、重要及全来源计数;无定义等级显示提示,分钟生命周期留详情,过期置灰保持。开发机80批和1440/390/320真实响应复现通过,422条计数一致。等待候选断网回归后仅155页面服务定向发布,详见[接续](docs/信号流四级统一发布_2026-11-06.md)。 12:42:09在155仅重建pms-web为pms:signal-levels-242193d,候选80批断网通过。其余18容器及私有配置保持,页面哈希与提交一致;实时1379条四级合计一致。确认与落库1665247一致,缺口、待入账和孤儿0,对账通过。文档与截图见上述接续,无自然分钟事件不冒充判收。 + +## 2026-11-09 账户累计盈亏与消息布局 + +总览增加双策略账户累计盈亏,标明实际初始化起点与未回报费用待补,估值缺失不伪装为零。消息分类统一再次点击收起,栏头和展开内容整体吸顶,侧栏高度随实际布局调整,修复滚动到底部及自动刷新时内容挤入顶部。开发机账务专项与页面三道护栏通过,1440、390、320隔离真实响应复现通过,所有写请求拒绝。仅安排155的pms-web定向发布,详见[修复接续](docs/账户盈亏与消息布局修复_2026-11-09.md)。 diff --git a/app/services/portfolio.py b/app/services/portfolio.py index 2858658..98582e0 100644 --- a/app/services/portfolio.py +++ b/app/services/portfolio.py @@ -12,6 +12,7 @@ from __future__ import annotations import json import logging +import math from app.core import cushion as cu from app.core import strategy_book as books @@ -258,6 +259,35 @@ def caps_ctx(view: dict, *, ts_code=None, is_new_name=False, sector=None) -> dic } +def account_performance() -> dict: + """只读账户累计盈亏,使用双策略现金账本的初始化基线。""" + from config.settings import settings + empty = {"ready": False, "profit": None, "started_at": None, + "reason": "账户收益基线尚未建立"} + if not settings.INFRA_STRATEGY_BOOK_SCHEMA: + return empty + try: + from app.services import rotation_accounting + view = rotation_accounting.view() + empty["started_at"] = view.get("started_at") + if not view.get("ready"): + empty["reason"] = view.get("reason") or "账户估值待补齐" + return empty + difference = view.get("cash_difference") + if difference is not None and abs(difference) > .02: + empty["reason"] = "账户现金与策略账本待核对" + return empty + profit = (view.get("metrics") or {}).get("account", {}).get("profit") + if profit is None or not math.isfinite(profit): + return empty + return {"ready": True, "profit": round(profit, 2), + "started_at": view.get("started_at"), "reason": None} + except Exception: + logger.exception("账户累计盈亏读取失败") + empty["reason"] = "账户累计盈亏暂不可用" + return empty + + def overview() -> dict: """页面顶部仪表 (总览)。任何一环取不到都不该让页面开不了 —— 逐项 try。""" try: @@ -275,6 +305,7 @@ def overview() -> dict: # 会让人以为钱多得是 (07-30: cash_est 199 万 vs 真实可用 97 万) "cash_avail": t["cash_avail"], "cash_source": t["cash_source"], "total_asset": t["total_asset"], "cash_why": t["cash_why"], + "account_performance": account_performance(), "account_market_value": t["account_market_value"], "frozen_cash": t["frozen_cash"], "float_pnl": t["float_pnl"], "float_pnl_pct": t["float_pnl_pct"], "solid_names": t["solid_names"], diff --git a/app/web/static/index.html b/app/web/static/index.html index 3d12de3..1595410 100644 --- a/app/web/static/index.html +++ b/app/web/static/index.html @@ -29,7 +29,7 @@ body{margin:0;background:var(--plane);color:var(--ink); .clr-up{color:var(--up);} .clr-down{color:var(--down);} /* 顶栏 */ /* 2026-09-18 改单行: 不折行; 状态是标签 (.hst, 与综合分析列的 .dim 同款), 动作收进右侧菜单 */ -.hd{position:sticky;top:0;z-index:30;display:flex;align-items:center;gap:10px;flex-wrap:nowrap;min-height:46px;box-sizing:border-box; +.hd{position:sticky;top:0;z-index:50;display:flex;align-items:center;gap:10px;flex-wrap:nowrap;min-height:46px;box-sizing:border-box; margin:0 -16px 6px;padding:8px 16px;background:rgba(244,245,242,.94);backdrop-filter:blur(8px);border-bottom:1px solid var(--hair);} .hd h1{font-size:15px;margin:0;font-weight:680;letter-spacing:.2px;white-space:nowrap;flex:none;} .hd .ver{color:var(--muted);font-size:12px;font-weight:400;margin-left:6px;} @@ -262,7 +262,8 @@ pre.json{background:var(--surface-2);border:1px solid var(--hair);border-radius: .ops-grid .set-fields{font-size:12.5px;} /* ── 融合消息栏: 上游告警 + 系统下单 + 待确认提议 + 策略与风控, 混成一条时间线 ── */ -.msgbar{position:sticky;top:46px;z-index:40;display:flex;align-items:center;gap:9px; +.messages{position:sticky;top:var(--pms-header-height,46px);z-index:40;padding:1px 0 4px;background:var(--plane);overflow-anchor:none;} +.msgbar{position:relative;display:flex;align-items:center;gap:9px; background:var(--surface);border:1px solid var(--hair);border-left:3px solid var(--accent); border-radius:12px;padding:7px 12px;margin:10px 0 4px;box-shadow:var(--shadow);font-size:13px;} .msgbar.lv-warn{border-left-color:var(--warn);} @@ -271,7 +272,7 @@ pre.json{background:var(--surface-2);border:1px solid var(--hair);border-radius: .mb-label{font-weight:660;color:var(--ink-2);white-space:nowrap;display:flex;align-items:center;gap:6px;} .mb-label .bell{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 3px var(--accent-weak);} .mb-tabs{display:flex;gap:5px;} -.mb-tab{font-size:11.5px;font-weight:560;padding:2px 9px;border-radius:999px;cursor:pointer; +.mb-tab{font-family:inherit;font-size:11.5px;font-weight:560;padding:2px 9px;border-radius:999px;cursor:pointer; border:1px solid transparent;background:var(--surface-2);color:var(--ink-2);user-select:none;white-space:nowrap;} .mb-tab .n{opacity:.62;margin-left:3px;} .mb-tab.on{background:var(--accent-weak);color:var(--accent);border-color:#cfe1f8;} @@ -281,10 +282,10 @@ pre.json{background:var(--surface-2);border:1px solid var(--hair);border-radius: background:none;border:0;padding:3px 2px;white-space:nowrap;} .mb-sep{width:1px;height:15px;background:var(--hair);flex:none;} @media(max-width:1080px){ .msgbar .mb-tabs{display:none;} } -.mb-panel{position:relative;background:var(--surface);border:1px solid var(--hair);border-radius:12px; +.mb-panel{position:relative;overscroll-behavior:contain;overflow-anchor:none;background:var(--surface);border:1px solid var(--hair);border-radius:12px; box-shadow:0 12px 38px rgba(17,17,16,.14),0 2px 8px rgba(17,17,16,.06); - padding:4px 0;margin:0 0 10px;max-height:392px;overflow:auto;z-index:39;} -.mb-panel .mb-tabs{padding:7px 14px 8px;border-bottom:1px solid var(--hair);} + padding:4px 0;margin:0 0 10px;max-height:var(--pms-message-max-height,392px);overflow:auto;} +.mb-panel .mb-tabs{flex-wrap:wrap;padding:7px 14px 8px;border-bottom:1px solid var(--hair);} .mb-row{display:flex;align-items:flex-start;gap:9px;padding:6px 14px;font-size:13px;} .mb-row:hover{background:var(--surface-2);} .mb-kind{width:52px;flex:none;font-size:11px;font-weight:600;padding:1px 0;border-radius:5px;text-align:center;} @@ -301,18 +302,18 @@ pre.json{background:var(--surface-2);border:1px solid var(--hair);border-radius: /* ── 三栏骨架 ── */ .shell{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:13px;align-items:start;} -.side{position:sticky;top:96px;align-self:start;transition:width .16s ease;} +.side{position:sticky;top:var(--pms-workbench-top,96px);align-self:start;transition:width .16s ease;} .side-l,.side-r{width:var(--strip-w);} body.dock-l:not(.l-fold) .side-l{width:var(--rail-w);} body.dock-r:not(.r-fold) .side-r{width:var(--rail-w-r);} .rail{background:var(--surface);border:1px solid var(--hair);border-radius:14px;box-shadow:var(--shadow); - display:none;flex-direction:column;max-height:calc(100vh - 116px);overflow:hidden;} + display:none;flex-direction:column;max-height:calc(100vh - var(--pms-workbench-top,96px) - 64px);overflow:hidden;} body.dock-l:not(.l-fold) #railL{display:flex;} body.dock-r:not(.r-fold) #railR{display:flex;} /* 浮层几何刻意只用老写法 (2026-09-01): min()/inset 这类新函数在旧 Safari 上整条声明 被丢, 浮层就成了没背景没遮罩的"透明面板" (iPad 实锅)。宽度用 width+max-width 等价 表达; 背景先给一条固定色兜底再让变量覆盖 */ -.rail.open{display:flex;position:fixed;top:96px;bottom:18px;width:560px;max-width:88vw;max-height:none; +.rail.open{display:flex;position:fixed;top:var(--pms-overlay-top,96px);bottom:18px;width:560px;max-width:88vw;max-height:none; background:#ffffff;background:var(--surface); z-index:2010;box-shadow:0 12px 38px rgba(17,17,16,.2),0 2px 8px rgba(17,17,16,.08);} #railL.open{left:16px;} #railR.open{right:16px;} @@ -618,7 +619,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;} -
+

PMS 持仓管理{{ health.now || '' }}

{{ marketState }} @@ -750,11 +751,12 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;} +
消息
- {{ k.label }}{{ msgCounts[k.key] }} +
@@ -776,13 +778,13 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;} 读取失败:{{ usrc('alerts').error }} 今天还没有消息
- +
-
+
- {{ k.label }}{{ msgCounts[k.key] }} +
这一类今天还没有消息。
@@ -802,6 +804,8 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
+
+
@@ -1083,6 +1087,8 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
账户总资产?
{{ money(ov.total_asset) }}
+
账户累计盈亏?
+
{{ accountPnlText }}
可用资金 (估算)?
{{ money(ov.cash_source==='ws' ? ov.cash_avail : ov.cash_est) }}
账户持仓市值?
{{ money(ov.account_market_value) }}
@@ -1094,8 +1100,6 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
{{ ov.names_count }}
待确认提议
{{ proposals.length }} 条
-
自主档位?
-
{{ tx('autonomy', ov.autonomy) }}
@@ -5352,6 +5356,40 @@ createApp({ const kindLabel = k => KIND_LABEL[k] || k; const hm = v => { const m = String(v || '').match(/\d{2}:\d{2}/); return m ? m[0] : (v || ''); }; const msgOpen = ref(false), msgKind = ref('all'); + const headerRef = ref(null), messagesRef = ref(null); + let layoutObserver; + function measureWorkbench() { + const headerHeight = Math.ceil(headerRef.value?.getBoundingClientRect().height || 46); + const messageHeight = Math.ceil(messagesRef.value?.getBoundingClientRect().height || 38); + const style = document.documentElement.style; + style.setProperty('--pms-header-height', headerHeight + 'px'); + style.setProperty('--pms-workbench-top', (headerHeight + messageHeight + 12) + 'px'); + style.setProperty('--pms-overlay-top', Math.max(96, headerHeight + 12) + 'px'); + style.setProperty('--pms-message-max-height', Math.max(100, Math.min(392, window.innerHeight - headerHeight - 160)) + 'px'); + } + onMounted(() => { + measureWorkbench(); + if (window.ResizeObserver) { + layoutObserver = new ResizeObserver(measureWorkbench); + for (const el of [headerRef.value, messagesRef.value]) if (el) layoutObserver.observe(el); + } + window.addEventListener('resize', measureWorkbench); + }); + onUnmounted(() => { + layoutObserver?.disconnect(); + window.removeEventListener('resize', measureWorkbench); + for (const key of ['header-height','workbench-top','overlay-top','message-max-height']) + document.documentElement.style.removeProperty('--pms-' + key); + }); + const accountPnl = computed(() => ov.value.account_performance || {profit:null}); + const accountPnlText = computed(() => accountPnl.value.profit == null ? '—' : + (accountPnl.value.profit > 0 ? '+' : '') + Number(accountPnl.value.profit).toLocaleString('zh-CN', {minimumFractionDigits:2, maximumFractionDigits:2})); + const accountPnlTip = computed(() => { + const value = accountPnl.value; + if (!value.ready) return value.reason || '账户累计盈亏暂不可用'; + const since = value.started_at ? '自' + String(value.started_at).slice(0,10) + '建立账户收益基线起,' : ''; + return since + '汇总主观量化与微盘轮动的已实现和持仓盈亏,内部划拨不计收益。已扣除入账费用,未回报费用待补。'; + }); // 时间字段各表叫法不一, 取到哪个算哪个; 排序用 HHMMSS, 同一天内够用。 const _at = (r, keys) => { for (const k of keys) { const v = r && r[k]; if (v) return String(v); } return ''; }; const _hm = s => { const m = String(s || '').match(/\d{2}:\d{2}/); return m ? m[0] : ''; }; @@ -5450,6 +5488,7 @@ createApp({ }); const msgShown = computed(() => msgKind.value === 'all' ? msgFeed.value : msgFeed.value.filter(m => m.kind === msgKind.value)); + watch([msgOpen, msgKind, msgShown], () => nextTick(measureWorkbench)); const msgLatest = computed(() => msgShown.value[0] || null); // 消息栏左边那道竖线的颜色: 有风控类的用橙, 有重要或警告的用琥珀, 否则中性。 const msgLevelClass = computed(() => { @@ -5458,8 +5497,13 @@ createApp({ if (it.some(m => ['DANGER', 'IMPORTANT', 'WARNING'].includes(String(m.level || '')))) return 'warn'; return it.length ? '' : 'none'; }); - function setMsgKind(k) { msgKind.value = k; msgOpen.value = true; } - function msgGo(m) { + function setMsgKind(k) { + msgOpen.value = msgKind.value === k ? !msgOpen.value : true; + msgKind.value = k; + } + async function msgGo(m) { + msgOpen.value = false; + await nextTick(); if (m.go === 'sig') { sigTab.value = 'brief'; openRailSide('l'); } else if (m.go === 'ins') { instructionTab.value='ins-'+m.book_id; insTab.value=m.ins_status==='CONFIRMED'?'done':_LIVE_INS.includes(m.ins_status)?'live':'end'; @@ -5573,7 +5617,7 @@ createApp({ openRailSide(side); } function scrimTE(e) { e.preventDefault(); closeRail(); } - function _onEsc(e) { if (e.key === 'Escape') {if(broadOpen.value)broadOpen.value=false;else if(etfOpen.value)etfOpen.value=false;else closeRail();} } + function _onEsc(e) { if (e.key === 'Escape') {if(broadOpen.value)broadOpen.value=false;else if(etfOpen.value)etfOpen.value=false;else if(railOpen.value)closeRail();else msgOpen.value=false;} } onMounted(() => { _railClasses(); applyDock(); window.addEventListener('resize', applyDock); @@ -5584,7 +5628,7 @@ createApp({ document.removeEventListener('keydown', _onEsc); }); - return { broad, broadOpen, broadTab, broadDays, broadPeriod, broadSearch, broadSectorId, + return { headerRef, messagesRef, accountPnl, accountPnlText, accountPnlTip, broad, broadOpen, broadTab, broadDays, broadPeriod, broadSearch, broadSectorId, broadMarket, broadDate, broadShortDate, broadAmount, broadColor, broadTail, broadRef, broadMetric, broadIndexes, broadSectorRows, broadSelected, broadRanks, broadRankMax, broadSectorCounts, broadChart, openBroad, flowShown, flowTotals, flowCoverageIncomplete, tab, loading, err, health, ov, params, catalog, commands, plans, plansOf, diff --git a/docs/evidence/overview-layout-ui-20261109/browser-checks.json b/docs/evidence/overview-layout-ui-20261109/browser-checks.json new file mode 100644 index 0000000..933f647 --- /dev/null +++ b/docs/evidence/overview-layout-ui-20261109/browser-checks.json @@ -0,0 +1,39 @@ +{ + "desktopCategories": [ + { + "label": "交易指令", + "opened": true, + "closed": true + }, + { + "label": "待确认提议", + "opened": true, + "closed": true + }, + { + "label": "策略与风控", + "opened": true, + "closed": true + }, + { + "label": "行情告警", + "opened": true, + "closed": true + }, + { + "label": "全部", + "opened": true, + "closed": true + } + ], + "mobileWidths": [ + 390, + 320 + ], + "mobileHorizontalOverflow": false, + "mobileSameCategoryCloses": true, + "scrollBottomNoOverlap": true, + "autoRefreshPreservesExpandedState": true, + "consoleErrors": [], + "acceptance": "本地隔离回放11月9日真实只读响应,所有写请求拒绝" +} \ No newline at end of file diff --git a/docs/evidence/overview-layout-ui-20261109/mobile.png b/docs/evidence/overview-layout-ui-20261109/mobile.png new file mode 100644 index 0000000..6441f50 Binary files /dev/null and b/docs/evidence/overview-layout-ui-20261109/mobile.png differ diff --git a/docs/evidence/overview-layout-ui-20261109/overview.png b/docs/evidence/overview-layout-ui-20261109/overview.png new file mode 100644 index 0000000..b896a04 Binary files /dev/null and b/docs/evidence/overview-layout-ui-20261109/overview.png differ diff --git a/docs/evidence/overview-layout-ui-20261109/scrolled.png b/docs/evidence/overview-layout-ui-20261109/scrolled.png new file mode 100644 index 0000000..329aa98 Binary files /dev/null and b/docs/evidence/overview-layout-ui-20261109/scrolled.png differ diff --git a/docs/开发入口.md b/docs/开发入口.md index 4485907..40e506f 100644 --- a/docs/开发入口.md +++ b/docs/开发入口.md @@ -6,6 +6,7 @@ | 任务 | 入口 | | --- | --- | +| 账户累计盈亏、消息分类收起及刷新布局 | [11月9日修复接续](账户盈亏与消息布局修复_2026-11-09.md),含账户收益基线、费用口径、桌面与窄屏验证及仅页面发布 | | 信号流统一四级、移除观测类别 | [11月6日四级发布](信号流四级统一发布_2026-11-06.md),含全来源计数、筛选与页面定向发布 | | 宽基每日资金展示、日报入口移除与当天信号完整覆盖 | [11月6日发布接续](宽基每日资金与信号覆盖发布_2026-11-06.md),最终原型、独立日度接入、四路信号覆盖及定向发布 | | 当前微盘接入、参数和运行待办 | [阶段接续与实验意见](微盘轮动阶段接续_2026-10-28.md);需要部署证据再读[50股发布记录](微盘轮动50股参数发布_2026-10-28.md) | diff --git a/docs/账户盈亏与消息布局修复_2026-11-09.md b/docs/账户盈亏与消息布局修复_2026-11-09.md new file mode 100644 index 0000000..4fafb36 --- /dev/null +++ b/docs/账户盈亏与消息布局修复_2026-11-09.md @@ -0,0 +1,27 @@ +# 账户累计盈亏与消息布局修复 + +核验时间:2026年11月9日10:27,北京时间。当前完成开发机验证,尚未发布;实际发布结果在本文后续补齐。 + +## 改动及边界 + +总览新增账户累计盈亏,使用双策略现金账本的账户权益减净投入,包含主观量化与微盘轮动已实现和持仓盈亏。策略内部划拨不计收益,用户设定的操作规模不作为收益本金。保留账户总资产、账户持仓市值及原策略持仓盈亏;去掉与顶部重复的自主档位卡片,维持八张卡片和既有视觉样式。 + +155当前收益基线建立于2026年11月2日10:08:20。提示说明统计起点及费用口径:已入账费用已扣除,未回报费用待补;不把未知费用当成已确认零费用。基线缺失、行情不完整、现金对账超容差或读取失败时显示破折号与原因,不展示零收益。此次只读已有账本,没有补写费用、修改初始化基线或推算开户以来净值。 + +消息栏的全部、行情告警、交易指令、待确认提议、策略与风控统一支持同类再次点击收起,切换类别保持展开,Escape关闭。点击消息跳转时先关闭面板。栏头和内容成为同一个吸顶区域,根据真实顶栏和消息高度计算侧栏位置及可用高度;自动刷新只更新内容,不重置当前分类和展开状态。窄屏分类按钮换行,面板内部滚动,不横向溢出或挤入顶栏。原信号行、操作入口和交易逻辑保持。 + +## 开发机验证 + +新增七项账务展示用例,覆盖两策略、已实现与未实现盈亏、已知费用、内部划拨、操作规模、负收益、缺估值、现金不符及读取失败;所在批次共16项通过。开发机最终80批隔离全量回归通过,包含页面三道护栏。 + +浏览器采用155在11月9日10:07读取的真实只读接口响应,保留原接口包装,本地补入同一实际账本计算出的新展示字段,所有写请求拒绝。这是隔离复现,不是真实登录验收。1440桌面及390、320窄屏检查通过:五类反复开合、切换类别、页面滚到底部、自然定时刷新及手动刷新、顶栏换行、消息高度限制与窄屏换行。账户盈亏显示带符号的两位金额,控制台错误为0。候选镜像仍须断网全量回归。 + +## 发布范围及回退 + +仅发布155模拟PMS的pms-web,原Compose项目、环境、私有覆盖和挂载保持。11月9日发布前页面为pms:signal-levels-242193d;唯一WS、worker、beat、采集、独立观测和其他容器不重建。188不操作,不注入委托、回报、模型请求或业务信号。 + +回退只恢复pms-web原镜像,保留账本、队列和全部业务回执。发布前保存实际配置与全部容器标识基线,候选通过后定向force-recreate,发布后核对镜像、页面哈希、真实接口、确认连续性、资金和数量对账。 + +发布前10:26:19只读核验:实例为pms-sim-155、表前缀为空、dispatch为ws,全局买入和执行暂停均为false。QMT确认与落库同为1732185,最近200条连续,缺口、待入账和孤儿均0,资金21.9秒,数量对账通过、现金差0。 + +[总览复现](evidence/overview-layout-ui-20261109/overview.png)、[滚动展开复现](evidence/overview-layout-ui-20261109/scrolled.png)、[窄屏复现](evidence/overview-layout-ui-20261109/mobile.png)。 diff --git a/scripts/run_tests.py b/scripts/run_tests.py index 40a48aa..44adb16 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -26,7 +26,7 @@ test_batch50_units.py QMT限价等待、价格来源故障、用户暂停、配额防重、试算隔离及收盘边界 (17例) test_batch49_units.py 持仓与指令分组、同名股票及批次归属、撤单账本、未迁移及缺数展示 (14例) test_batch48_units.py 策略账本隔离、轮换优先级、交易单位、模拟直接启用、读数及微盘50规则换版 (55例) - test_batch47_units.py 账户资金去重、买入额度与账户展示和策略估值分离 (9 例) + test_batch47_units.py 账户资金去重、买入额度、账户展示与双策略累计盈亏 (16 例) test_batch46_units.py 质地排序切换、档位准入、命令分配与白名单优先 (11 例) test_batch45_units.py 父指令总量:回放延迟、部分成交、跨日预留、故障守成与影子模式 (16 例) test_batch43_units.py 逐票来源核验、实际API至SQL事务、故障回滚与幂等 (14 例) diff --git a/scripts/test_batch47_units.py b/scripts/test_batch47_units.py index edd67ab..9ba8cf9 100644 --- a/scripts/test_batch47_units.py +++ b/scripts/test_batch47_units.py @@ -3,8 +3,12 @@ import unit_test_guard # noqa: F401 import os import sys import unittest +from unittest.mock import patch sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from config.settings import settings +from app.core import rotation_account +from app.services import rotation_accounting from app.core import rule_gate from app.services import portfolio from test_wiring import install_fakes @@ -101,5 +105,61 @@ class AccountFundsTest(unittest.TestCase): self.assertEqual(result['cash_avail'], 1806071.62) +class AccountPerformanceTest(unittest.TestCase): + def setUp(self): + self.fake = install_fakes(params={'PMS_TOTAL_SCALE': '2000000'}) + enabled = patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True) + enabled.start(); self.addCleanup(enabled.stop) + self.capital = rotation_account.seed(10000, {'original': 5000, 'micro30': 0}) + self.values = {'original': 5000, 'micro30': 0} + + def read(self, **changes): + view = {'ready': True, 'cash_difference': 0, 'started_at': '2026-10-27T15:30:00', + 'metrics': rotation_account.metrics(self.capital, self.values)} + view.update(changes) + with patch.object(rotation_accounting, 'view', return_value=view): + return portfolio.overview()['account_performance'] + + def test_both_books_realized_unrealized_and_booked_fees_are_included(self): + rotation_account.transfer(self.capital, 'original', 'micro30', 3000, self.values, 'move') + rotation_account.fill(self.capital, 'original', 'sell', 2000, 3, 'sell') + rotation_account.fill(self.capital, 'micro30', 'buy', 2500, 2, 'buy') + self.values = {'original': 3500, 'micro30': 2600} + result = self.read() + self.assertTrue(result['ready']) + self.assertEqual(result['profit'], 595) + self.assertEqual(result['started_at'], '2026-10-27T15:30:00') + + def test_internal_transfer_and_user_scale_do_not_create_profit(self): + rotation_account.transfer(self.capital, 'original', 'micro30', 3000, self.values, 'move') + self.assertEqual(self.read()['profit'], 0) + + def test_loss_keeps_sign(self): + self.values['original'] = 4321.12 + self.assertEqual(self.read()['profit'], -678.88) + + def test_missing_quotes_or_baseline_never_become_zero_profit(self): + for changes in ({'ready': False, 'reason': '估值待补'}, + {'ready': False, 'reason': '分策略现金尚未初始化'}, + {'metrics': {}}): + with self.subTest(changes=changes): + self.assertIsNone(self.read(**changes)['profit']) + + def test_cash_disagreement_hides_unverified_account_profit(self): + result = self.read(cash_difference=100) + self.assertFalse(result['ready']) + self.assertIsNone(result['profit']) + + def test_failure_does_not_hide_other_overview_fields(self): + with patch.object(rotation_accounting, 'view', side_effect=ValueError('test only')): + result = portfolio.overview() + self.assertTrue(result['ok']) + self.assertIsNone(result['account_performance']['profit']) + + def test_nonfinite_profit_is_not_sent_to_page(self): + result = self.read(metrics={'account': {'profit': float('inf')}}) + self.assertIsNone(result['profit']) + + if __name__ == '__main__': unittest.main()