Compare commits

..
Author SHA1 Message Date
b11ac6965f fix(HEL-217): 限制温度走势图高度,按左栏对齐右侧并保留夜间提示
撤掉图表随右栏无限拉伸的布局,恢复一屏内的成熟比例;右侧两卡跟随左栏高度,夜间 tooltip 改用主题变量。

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-08-28 14:05:41 +00:00
18 changed files with 526 additions and 524 deletions
-16
View File
@@ -14,29 +14,13 @@
v
xiaobai-review 容器 :8765
|-- /app 只读应用代码
| `-- backend/features/heaven/assets/heaven_knowledge.json
| 镜像内 seed(不受 data 挂载遮盖)
`-- /app/data 宿主机 ./data 持久化挂载
|-- review.db
|-- iching_zh.json
`-- heaven_knowledge.json 优先读取;缺失时回退到上方 seed
```
账号、加密后的公共数据 Token、平台模型 API Key、生辰资料、行情快照和复盘数据均在
`data/review.db`。解密密钥来自 `.env` 中的 `APP_ENCRYPTION_KEY`。数据库与
密钥必须成对备份,任意一个丢失都无法恢复账号内的加密资料。
问天静态知识文件:
- `data/iching_zh.json``data/heaven_knowledge.json` 纳入 Git 与镜像构建;
`.dockerignore` 不排除这两个文件(只排除 `data/*.db``data/cache/` 等运行时产物)。
- Compose 把宿主机 `./data` 整目录挂到 `/app/data`,会遮盖镜像里同路径文件。
因此宿主机 `data/` 应保留上述两个 JSON;若只缺 `heaven_knowledge.json`
服务会回退读取镜像内
`backend/features/heaven/assets/heaven_knowledge.json`,解势仍可用。
- 持久化位置:正式环境以宿主机项目目录下的 `./data/heaven_knowledge.json` 为准;
补文件后无需改代码,重启容器即可加载。
管理员私有的问师 Skill 保存在宿主机 `data/private-mentor-skills/`。该目录随 `data`
挂载进入容器,但被 Git 与 Docker 构建上下文排除,不会进入 Gitea 或镜像。私有 Skill
只对管理员账号返回和开放调用,也会随本指南的 `data` 备份一起保存。
+1 -4
View File
@@ -23,10 +23,7 @@ COPY requirements.txt ./
RUN python -m pip install --no-cache-dir -r requirements.txt
COPY --chown=xiaobai:xiaobai . .
RUN mkdir -p /app/data && chown -R xiaobai:xiaobai /app/data \
&& test -f /app/data/heaven_knowledge.json \
&& test -f /app/data/iching_zh.json \
&& test -f /app/backend/features/heaven/assets/heaven_knowledge.json
RUN mkdir -p /app/data && chown -R xiaobai:xiaobai /app/data
USER xiaobai
@@ -1,117 +0,0 @@
{
"version": "2026.08.05-5",
"sources": {
"zhouyi": {
"title": "周易经文与十翼",
"scope": "卦辞、爻辞、彖传、象传",
"kind": "public_domain_primary",
"note": "观势与观心只引用本项目已校录的卦爻原文,不把现代网络释文当作原典。"
},
"jingfang": {
"title": "京氏易传",
"scope": "八宫与纳甲体系来源",
"kind": "public_domain_traditional",
"note": "确定性程序采用京房纳甲、八宫世应的通行排法。"
},
"huozhulin": {
"title": "火珠林",
"scope": "纳甲筮法、六亲与日月关系",
"kind": "public_domain_traditional",
"note": "用于观心规则脉络,不直接复制后世简化断语。"
},
"zengshan": {
"title": "增删卜易",
"scope": "用神、世应、动变、日月旺衰",
"kind": "public_domain_traditional",
"note": "只采用可明确编码且有一致输入条件的规则;争议规则单独标记。"
},
"neijing": {
"title": "黄帝内经·素问运气七篇",
"scope": "五运、司天在泉、主客气与运气关系",
"kind": "public_domain_primary",
"note": "观气将原典关系转成当日自我观察语言,不宣称对股价存在因果作用。"
}
},
"trend": {
"method": "本卦说明当下结构,实际动爻说明变化关节,之卦说明所趋结构;多动爻全部保留,不以固定口诀删去用户实际得到的爻。",
"rules": {
"stable": "无动爻时以本卦整体、上下卦关系和大象为主,说明结构的延续条件,不把静止等同于永远不变。",
"single": "一爻动时以该爻的时位、爻辞和象辞为变化核心,并用之卦检查变化后的结构。",
"multiple": "多爻动时逐一保留相关爻义,先找共同方向与冲突,再结合之卦给出有条件的倾向;不得用固定套话把不同动爻压成同一结论。"
}
},
"fortune": {
"principle": "先立中运与司天在泉的年纲,再察当前客气加临主气,最后以日辰说明当日触发;不使用产品权重推导传统结论。",
"movement": {
"太过": "太过表示该运之气偏于有余,解释时同时观察其本气表现与对所胜、所生关系的牵动,不直接等同于吉或凶。",
"不及": "不及表示该运之气偏于不足,解释时同时观察其所不胜来乘与所生受累的可能,不直接等同于弱势结论。"
},
"qi": {
"厥阴风木": "厥阴取风木之动,侧重疏泄、升发、变化与不定;偏盛时可表现为动摇、急变或升散不收。",
"少阴君火": "少阴取君火之明与热,侧重显化、温煦和内在驱动;偏盛时容易躁热,受制时则显而不畅。",
"太阴湿土": "太阴取湿土之濡与承载,侧重黏滞、蓄积和转化;偏盛时容易困重迟缓,得化时则能承接。",
"少阳相火": "少阳取相火之行与枢转,侧重外达、加速和往来;偏盛时容易浮越躁动,受阻时表现为枢机不利。",
"阳明燥金": "阳明取燥金之收与清肃,侧重收敛、裁决和边界;偏盛时容易干急严峻,得润时则清明有序。",
"太阳寒水": "太阳取寒水之藏与凝,侧重潜藏、收引和下行;偏盛时容易凝滞退缩,得温时则蓄势有根。"
},
"relations": {
"same": "客主同气表示同类气相并,重点看是否相得而彰,还是同气偏盛而亢;不能机械判为有利。",
"guest_generates_host": "客生主表示来气生助时令本气,气机较易衔接;仍需观察生助是否过度及年纲是否承接。",
"host_generates_guest": "主生客表示时令本气向来气流转,有相生也有外泄;不能只取相生而忽略主气受耗。",
"guest_controls_host": "客克主表示来气制约主气,传统称客胜为从;重点解释外来变化居上及原有节律受制。",
"host_controls_guest": "主克客表示主气制约来气,传统称主胜为逆;重点解释时令与来气相持而不把相克直接断凶。"
},
"day_trigger": "日辰只说明当日关系如何被触发,不与中运、司天在泉或主客气并列重复计权。",
"industry_boundary": "五行对应行业只作传统取象:可以说明本次已经出现的五行之气对相应行业形成的象征性关注、节奏或约束,但不得读取或猜测行业实时行情,不得预测涨跌,也不得把取象写成投资推荐。",
"personal_boundary": "personal.natal_day_master才是用户本命日主;today_relative_to_natal_day_master中的pillars是当日历法,stem_relations只是当日年、月、日三柱天干相对本命日主的确定性关系标签。只能使用本次检索到的关系释义,不得自行重算十神、扩展五行生克、使用藏干、库气或支的燥湿属性,也不得把当日日柱称为用户命局,或由这些字段推断命局中某一十神偏重、身强身弱或喜用神。",
"personal_relations": {
"比肩": "比肩作为当日天干关系标签,只提示用户可能更在意自主判断、同类比较或坚持原有立场;不能据此判断命局强弱或现实事件。",
"劫财": "劫财作为当日天干关系标签,只提示用户留意精力、注意力或可支配资源在同类事项间的分流与竞争感;不等同于破财或他人争夺。",
"食神": "食神作为当日天干关系标签,只提示用户留意表达、输出、舒缓与完成感;不等同于收益或确定的轻松结果。",
"伤官": "伤官作为当日天干关系标签,只提示用户留意质疑规则、急于表达或追求自主空间的倾向;不等同于冲突或违规。",
"偏财": "偏财作为当日天干关系标签,只提示用户留意机会分配、灵活取舍与非固定资源的吸引力;不等同于意外获利。",
"正财": "正财作为当日天干关系标签,只提示用户更关注可核对的结果、资源边界和务实落地;不等同于必得收益或现金变化。",
"七杀": "七杀作为当日天干关系标签,只提示用户留意紧迫感、外部压力和快速决断冲动;不等同于危险必然发生。",
"正官": "正官作为当日天干关系标签,只提示用户更在意规则、责任、秩序和可交付标准;不等同于结果必然受控。",
"偏印": "偏印作为当日天干关系标签,只提示用户留意内省、非惯常信息和反复推敲的倾向;不等同于退缩、失眠或方向错误。",
"正印": "正印作为当日天干关系标签,只提示用户更在意依据、支持、学习和安全边界;不等同于必然获得帮助。"
}
},
"heart": {
"presets": {
"trade": "关于我心中的这笔交易,此刻最需要看清的机会、阻碍与风险是什么?",
"mind": "此刻影响我交易判断的情绪、执念或盲点是什么?",
"unthemed": "不设具体问题,只观此刻一念。"
},
"focus": {
"trade": "以世爻、应爻、妻财爻及实际动变为主要检索对象,同时检查兄弟、官鬼和子孙的生克,不把任何单一六亲固定判吉凶。",
"mind": "以世爻和实际动爻为主,观察官鬼所示压力、子孙所示舒解及内外生克;不把心境问题强行翻译成价格方向。",
"unthemed": "不强选事项用神,以本卦、世爻、实际动爻和之卦作一般观照,不猜测用户没有提出的问题。",
"custom": "先依据用户明确写出的股票交易问题选择相关六亲;无法明确归类时退回世爻、动爻和卦变的一般解释,不擅自补全问题。"
},
"evidence_order": [
"用户问题与预设来源",
"本卦及卦宫",
"世应与所问相关六亲",
"月建日辰、旬空及冲合生克",
"实际动爻与变爻",
"之卦与整体卦义",
"六神辅助象义"
],
"limits": "六神只作辅助象义;空亡、月破、日冲、合冲刑害均需结合用神、世应和动变,不得单项宣布结果。",
"semantics": {
"self_response": "世爻表示求测者当前立场与承受状态,应爻表示所问事项的外部一端或对照面。应爻不是固定的合作方、庄家或资金方;只有用户问题明确给出该角色时,才可作对应解释。",
"calendar": "月建与日辰用于判断爻在起卦时刻的承受、生扶和制约。旬空表示该爻所象征的条件当下可能未落实、难发挥或有名无实,但不能单凭旬空判失败,也不能用填实日期预测何时涨跌或行动。月破、日冲、六合、六冲、六害和相刑同样必须与世应、相关六亲及动变合看。",
"movement": "动爻说明关系正在变化;变爻说明变化后的承接方向。回头生、回头克和原变爻生克只描述力量关系,不自动对应现实中的借贷、融资、合作或某个具体人物。进神退神只说明同类地支变化的进退趋势,不直接宣布价格方向。",
"six_spirits": "六神只补充表达色彩,不单独定成败。青龙不必然有利,白虎不必然紧急或凶险,朱雀不必然等同口舌,玄武不必然等同欺骗,勾陈与螣蛇也不得脱离爻位、六亲和动变独断。",
"timing_boundary": "观心不作应期预测。可以说明某项条件在起卦时刻尚未落实或受制,但不得给出未来若干日、某干支日、出空或填实后必然发生什么。",
"relatives": {
"兄弟": "兄弟是与卦宫五行同类的关系。在股票交易问题中可作为竞争、同类力量或资源分流的候选象义,但不直接等同合作方、亏损或他人拿走资金。",
"子孙": "子孙是卦宫所生的关系,可作为舒缓、产出、执行后的释放或对压力的制衡候选象义,但不直接等同收益、资金提供方或确定的利好。",
"妻财": "妻财是卦宫所克的关系,在股票交易问题中可作为价值、收益预期、持仓利益或可支配资源的候选象义,但不直接等同现金、融资、自有资金或必得之财。",
"官鬼": "官鬼是克制卦宫的关系,可作为压力、风险、规则约束或担忧的候选象义,但不直接等同借贷、坏消息、疾病或必然损失。",
"父母": "父母是生助卦宫的关系,可作为信息、依据、计划、规则、凭据或保护条件的候选象义,但不直接等同政策、合同或某一条消息。"
}
}
}
}
+4 -13
View File
@@ -3,24 +3,15 @@ from __future__ import annotations
import json
from http import HTTPStatus
from backend.features.heaven.knowledge import HeavenKnowledgeError
class HeavenHttpMixin:
def _send_heaven_client_error(self, exc: Exception) -> None:
payload: dict = {"error": str(exc)}
code = getattr(exc, "error_code", None)
if code:
payload["code"] = str(code)
self.send_json(payload, HTTPStatus.BAD_REQUEST)
def heaven_hexagram(self) -> None:
try:
body = self.read_json_body()
result = self.application_service.heaven_hexagram(body.get("lines"))
self.send_json({"ok": True, "hexagram": result})
except (ValueError, json.JSONDecodeError) as exc:
self._send_heaven_client_error(exc)
self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
def heaven_personal(self) -> None:
try:
@@ -28,12 +19,12 @@ class HeavenHttpMixin:
result = self.application_service.heaven_personal(body)
self.send_json({"ok": True, "personal": result})
except (ValueError, json.JSONDecodeError) as exc:
self._send_heaven_client_error(exc)
self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
def heaven_interpret(self) -> None:
try:
body = self.read_json_body()
result = self.application_service.heaven_interpret(body)
self.send_json({"ok": True, **result})
except (HeavenKnowledgeError, ValueError, json.JSONDecodeError) as exc:
self._send_heaven_client_error(exc)
except (ValueError, json.JSONDecodeError) as exc:
self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
+2 -53
View File
@@ -2,23 +2,12 @@ from __future__ import annotations
import json
from functools import lru_cache
from pathlib import Path
from typing import Any
from backend.bootstrap.config import APP_DIR
KNOWLEDGE_FILE = APP_DIR / "data" / "heaven_knowledge.json"
# Baked into the image outside the ./data bind mount so volume overlay cannot hide it.
KNOWLEDGE_SEED_FILE = Path(__file__).resolve().parent / "assets" / "heaven_knowledge.json"
class HeavenKnowledgeError(ValueError):
"""Structured knowledge-file failure surfaced to HTTP as Chinese API errors."""
def __init__(self, message: str, *, code: str) -> None:
super().__init__(message)
self.error_code = code
def prepare_heaven_context(mode: str, calculation: dict[str, Any]) -> dict[str, Any]:
@@ -390,49 +379,9 @@ def _line_record(line: dict[str, Any]) -> dict[str, Any]:
}
def resolve_heaven_knowledge_path() -> Path:
"""Prefer the persisted data-dir file; fall back to the image-baked seed."""
if KNOWLEDGE_FILE.is_file():
return KNOWLEDGE_FILE
if KNOWLEDGE_SEED_FILE.is_file():
return KNOWLEDGE_SEED_FILE
raise HeavenKnowledgeError(
"问天知识文件缺失:未找到 heaven_knowledge.json。"
"请确认宿主机 data 目录或镜像内 seed 文件完整。",
code="heaven_knowledge_missing",
)
@lru_cache(maxsize=1)
def _knowledge_catalog() -> dict[str, Any]:
path = resolve_heaven_knowledge_path()
try:
raw = path.read_text(encoding="utf-8")
except OSError as exc:
raise HeavenKnowledgeError(
f"问天知识文件无法读取({path.name}):{exc.strerror or exc}",
code="heaven_knowledge_missing",
) from exc
try:
payload = json.loads(raw)
except json.JSONDecodeError as exc:
raise HeavenKnowledgeError(
f"问天知识文件 JSON 损坏({path.name}),无法解析:"
f"{exc.lineno} 行附近。",
code="heaven_knowledge_invalid",
) from exc
if not isinstance(payload, dict):
raise HeavenKnowledgeError(
f"问天知识文件格式不正确({path.name}):根节点必须是对象。",
code="heaven_knowledge_invalid",
)
payload = json.loads(KNOWLEDGE_FILE.read_text(encoding="utf-8"))
if not payload.get("version") or not isinstance(payload.get("sources"), dict):
raise HeavenKnowledgeError(
f"问天知识库格式不完整({path.name}):缺少 version 或 sources。",
code="heaven_knowledge_invalid",
)
raise ValueError("问天知识库格式不完整。")
return payload
def clear_heaven_knowledge_cache() -> None:
_knowledge_catalog.cache_clear()
+13 -13
View File
@@ -372,9 +372,9 @@
"css_layers": [
"/shared/tokens.css?v=20260820-3",
"/shared/base.css?v=20260806-1",
"/shared/shell.css?v=20260827-hel183",
"/shared/shell.css?v=20260820-8",
"/shared/auth.css?v=20260820-5",
"/shared/components/controls.css?v=20260827-hel183",
"/shared/components/controls.css?v=20260820-2",
"/shared/components/navigation.css?v=20260820-1",
"/shared/components/cards.css?v=20260820-1",
"/shared/components/tables.css?v=20260820-1",
@@ -390,8 +390,8 @@
"/pages/popularity/foundation.css?v=20260820-1",
"/pages/dragon-tiger/foundation.css?v=20260820-1",
"/pages/screener/foundation.css?v=20260820-4",
"/pages/mentor/foundation.css?v=20260827-hel183",
"/pages/heaven/foundation.css?v=20260827-hel183",
"/pages/mentor/foundation.css?v=20260820-2",
"/pages/heaven/foundation.css?v=20260806-2",
"/pages/review/foundation.css?v=20260820-4"
],
"frontend_composition": {
@@ -436,8 +436,8 @@
"code_hotspots": [
{
"path": "frontend/pages/heaven/foundation.css",
"bytes": 182616,
"lines": 11494
"bytes": 185936,
"lines": 11734
},
{
"path": "frontend/pages/screener/foundation.css",
@@ -446,13 +446,13 @@
},
{
"path": "frontend/pages/heaven/page.js",
"bytes": 97268,
"lines": 2070
"bytes": 97189,
"lines": 2069
},
{
"path": "frontend/shared/shell.css",
"bytes": 63659,
"lines": 3763
"bytes": 63550,
"lines": 3757
},
{
"path": "backend/features/heaven/engine.py",
@@ -461,7 +461,7 @@
},
{
"path": "frontend/index.html",
"bytes": 47891,
"bytes": 47871,
"lines": 661
},
{
@@ -501,8 +501,8 @@
},
{
"path": "frontend/pages/heaven/page.html",
"bytes": 19885,
"lines": 269
"bytes": 19747,
"lines": 262
},
{
"path": "frontend/pages/screener/page.html",
+4 -4
View File
@@ -34,9 +34,9 @@
</script>
<link rel="stylesheet" href="/shared/tokens.css?v=20260820-3">
<link rel="stylesheet" href="/shared/base.css?v=20260806-1">
<link rel="stylesheet" href="/shared/shell.css?v=20260827-hel183">
<link rel="stylesheet" href="/shared/shell.css?v=20260820-8">
<link rel="stylesheet" href="/shared/auth.css?v=20260820-5">
<link rel="stylesheet" href="/shared/components/controls.css?v=20260827-hel183">
<link rel="stylesheet" href="/shared/components/controls.css?v=20260820-2">
<link rel="stylesheet" href="/shared/components/navigation.css?v=20260820-1">
<link rel="stylesheet" href="/shared/components/cards.css?v=20260820-1">
<link rel="stylesheet" href="/shared/components/tables.css?v=20260820-1">
@@ -52,8 +52,8 @@
<link rel="stylesheet" href="/pages/popularity/foundation.css?v=20260820-1">
<link rel="stylesheet" href="/pages/dragon-tiger/foundation.css?v=20260820-1">
<link rel="stylesheet" href="/pages/screener/foundation.css?v=20260820-4">
<link rel="stylesheet" href="/pages/mentor/foundation.css?v=20260827-hel183">
<link rel="stylesheet" href="/pages/heaven/foundation.css?v=20260827-hel183">
<link rel="stylesheet" href="/pages/mentor/foundation.css?v=20260820-2">
<link rel="stylesheet" href="/pages/heaven/foundation.css?v=20260806-2">
<link rel="stylesheet" href="/pages/review/foundation.css?v=20260820-4">
</head>
<body>
+243 -3
View File
@@ -93,6 +93,28 @@ body[data-active-view="heavenView"] .workspace-view {
display: none;
}
:where(#heavenView) .heaven-tabs {
display: flex;
border-bottom: 1px solid var(--line);
}
:where(#heavenView) .heaven-tab {
border-bottom: 3px solid transparent;
background: transparent;
cursor: pointer;
}
:where(#heavenView) .heaven-tab.active {
border-bottom-color: var(--coral);
}
:where(#heavenView) .heaven-tab:hover {
border-bottom-color: var(--coral);
}
:where(#heavenView) .heaven-panel {
display: none;
}
@@ -1853,6 +1875,60 @@ body[data-active-view="heavenView"] .workspace-view {
color: var(--heaven-ink-faint);
}
#heavenView .heaven-tab {
font-family: var(--heaven-serif);
height: 52px;
position: relative;
padding: 0px 2px;
border: 0px;
color: var(--heaven-ink-soft);
font-size: 14px;
font-weight: 600;
}
#heavenView .heaven-tab::after {
content: "";
position: absolute;
right: 0px;
bottom: 0px;
left: 0px;
height: 2px;
background: var(--heaven-cinnabar);
opacity: 0;
transform: scaleX(0.3);
transition: opacity 220ms ease, transform 260ms var(--ease-out);
}
#heavenView .heaven-tab.active {
color: var(--heaven-ink);
}
#heavenView .heaven-tab:hover {
color: var(--heaven-ink);
}
#heavenView .heaven-tab.active::after {
opacity: 1;
transform: scaleX(1);
}
:where(#heavenView) .heaven-proverb {
margin: 0px;
@@ -1884,7 +1960,7 @@ body[data-active-view="heavenView"] .workspace-view {
}
#heavenView .button:focus-visible,
#heavenView .segment:focus-visible,
#heavenView .heaven-tab:focus-visible,
#heavenView summary:focus-visible {
outline: 2px solid var(--heaven-cinnabar);
@@ -2547,6 +2623,12 @@ body[data-active-view="heavenView"] .workspace-view {
padding: 0px 14px;
}
#heavenView .heaven-tabs {
gap: 22px;
padding: 0px 14px;
}
.heaven-proverb {
padding: 8px 14px;
@@ -3011,7 +3093,7 @@ body[data-active-view="heavenView"] .workspace-view {
#heavenView.heaven-data-loading .heaven-panel,
#heavenView.heaven-data-loading .heaven-proverb,
#heavenView.heaven-data-loading .heaven-page-head {
#heavenView.heaven-data-loading .heaven-tabs {
opacity: 0.42;
pointer-events: none;
@@ -3613,7 +3695,7 @@ body[data-active-view="heavenView"] .workspace-view {
@media (max-width: 900px) {
#heavenView .heaven-panel > ,
#heavenView .heaven-proverb,
#heavenView .heaven-page-head,
#heavenView .heaven-tabs,
#heavenView .heaven-toolbar {
width: min(100% - 28px, 1280px);
}
@@ -3664,6 +3746,22 @@ body[data-active-view="heavenView"] .workspace-view {
display: none;
}
#heavenView .heaven-tabs {
display: grid;
grid-template-columns: repeat(3, minmax(0px, 1fr));
gap: 0px;
padding: 0px;
}
#heavenView .heaven-tab {
width: 100%;
min-width: 0px;
}
#heavenFortunePanel .fortune-heading {
display: flex;
@@ -3769,6 +3867,18 @@ body[data-active-view="heavenView"] .workspace-view {
}
@media (max-width: 520px) {
.heaven-tabs {
gap: 0px;
padding: 0px 8px;
}
.heaven-tab {
min-width: 0px;
flex: 1 1 0%;
}
.heaven-controls {
grid-template-columns: 1fr;
@@ -6122,6 +6232,26 @@ body[data-active-view="heavenView"] .workspace-view {
padding: 12px 20px;
}
#heavenView .heaven-tabs {
align-items: stretch;
gap: 30px;
border-color: var(--heaven-rule);
background: rgba(253, 252, 248, 0.96);
width: min(100% - 40px, 1280px);
margin-right: auto;
margin-left: auto;
min-height: 54px;
padding: 0px 20px;
}
#heavenView .heaven-proverb {
margin-right: auto;
@@ -6167,6 +6297,12 @@ body[data-active-view="heavenView"] .workspace-view {
padding: 10px 14px;
}
#heavenView .heaven-tabs {
min-height: 52px;
padding: 0px 14px;
}
#heavenView .heaven-proverb {
padding: 9px 14px;
}
@@ -6532,6 +6668,18 @@ body[data-active-view="heavenView"] .workspace-view {
color: var(--wt-faint);
}
:root[data-theme="light"] #heavenView .wt-tabs .wt-tab {
color: var(--wt-muted);
}
:root[data-theme="light"] #heavenView .wt-tabs .wt-tab small {
color: var(--wt-faint);
}
:root[data-theme="light"] #heavenView .wt-tabs .wt-tab.on {
color: var(--wt-gold-bright);
}
:root[data-theme="light"] #heavenView .wt-empty {
color: var(--wt-muted);
}
@@ -6980,6 +7128,88 @@ body[data-active-view="heavenView"] .workspace-view {
letter-spacing: 4px;
}
.wt-tabs {
display: flex;
justify-content: center;
gap: 34px;
margin-top: 20px;
}
.wt-tabs .wt-tab {
position: relative;
padding: 8px 4px;
border: 0px;
background: transparent;
color: rgba(216, 210, 189, 0.5);
font-size: 15px;
letter-spacing: 3px;
transition: color 0.2s;
}
.wt-tabs .wt-tab small {
display: block;
margin-top: 3px;
color: rgba(216, 210, 189, 0.3);
font-family: inherit;
font-size: 10px;
letter-spacing: 1px;
}
.wt-tabs .wt-tab::after {
content: "";
position: absolute;
bottom: -2px;
left: 50%;
width: 0px;
height: 1.5px;
background: var(--wt-gold);
transform: translateX(-50%);
transition: 0.25s;
}
.wt-tabs .wt-tab.on {
color: var(--wt-gold-bright);
}
.wt-tabs .wt-tab.on::after {
width: 100%;
}
.wt-tabs .wt-tab:disabled {
cursor: default;
}
.wt-tabs .wt-tab:focus {
outline: none;
}
.wt-tabs .wt-tab:focus-visible {
box-shadow: rgba(201, 165, 92, 0.45) 0px 2px 0px;
}
.heaven-proverb {
margin: 8px 0px 0px;
@@ -8842,6 +9072,16 @@ body[data-active-view="heavenView"] .workspace-view {
gap: 5px;
}
.wt-tabs {
gap: 16px;
}
.wt-tabs .wt-tab {
font-size: 13px;
letter-spacing: 2px;
}
.heaven-proverb {
text-align: center;
}
+6 -13
View File
@@ -1,23 +1,16 @@
<section id="heavenView" class="workspace-view member-feature-view heaven-shell wt">
<div class="member-gate" hidden><div class="member-gate-icon"><i data-lucide="lock-keyhole"></i></div><div><strong>问天仅对会员开放</strong><span>开通会员后可使用观势、观气、观心及平台解读。会员状态可从顶部账号标识进入。</span></div></div>
<div class="section-toolbar redesigned-page-head heaven-page-head">
<div class="section-title-group">
<h2>问天</h2>
<span class="section-subtitle"><b id="heavenDataDate">--</b></span>
</div>
<div class="toolbar-controls">
<div class="segmented" role="group" aria-label="问天模块">
<button class="segment active on" type="button" data-heaven-panel="trend" aria-current="page">观势</button>
<button class="segment" type="button" data-heaven-panel="fortune">观气</button>
<button class="segment" type="button" data-heaven-panel="heart">观心</button>
</div>
</div>
</div>
<header class="wt-head">
<div class="wt-title-line">
<h1 class="wt-serif">问 天</h1>
<span id="heavenDataDate">--</span>
</div>
<div class="verse wt-serif">观天之道 · 执天之行</div>
<nav class="wt-tabs" aria-label="问天模块">
<button class="wt-tab wt-serif on" type="button" data-heaven-panel="trend" aria-current="page">观势<small>三才六爻 · 量化成卦</small></button>
<button class="wt-tab wt-serif" type="button" data-heaven-panel="fortune">观气<small>五运六气 · 日辰生克</small></button>
<button class="wt-tab wt-serif" type="button" data-heaven-panel="heart">观心<small>静心占卜 · 第一念</small></button>
</nav>
</header>
<p class="heaven-proverb wt-serif">遇事不决可问春风,春风不语即随本心</p>
<div id="heavenNotice" class="inline-notice" role="status" hidden></div>
+1 -2
View File
@@ -1363,8 +1363,7 @@ async function interpretHeaven(mode) {
} catch (error) {
stopHeavenReadingAnimation();
state.heavenReadingLoading = false;
const detail = error?.payload?.message || error?.payload?.error || error.message;
state.heavenReadingError = detail || "问天解读失败";
state.heavenReadingError = error.message || "问天解读失败";
renderHeavenReadingDialog();
showHeavenNotice(state.heavenReadingError);
showToast(state.heavenReadingError);
+1 -1
View File
@@ -49,7 +49,7 @@ body[data-active-view="mentorView"] .app-page-context span {
height: 100%;
min-height: 0;
flex-direction: column;
padding: var(--page-pad-y) 0 0;
padding: 0;
color: var(--qp-text-1);
font-family: "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
}
+101
View File
@@ -1021,9 +1021,21 @@
}
.sentiment-chart-tooltip b {
color: inherit;
font-weight: 700;
}
:root[data-theme="dark"] #sentimentCycleView .sentiment-chart-tooltip {
border: 1px solid var(--border-strong);
background: var(--surface-muted);
color: var(--text-primary);
box-shadow: var(--elevation-float);
}
.sentiment-phase-block {
display: flex;
@@ -1673,6 +1685,95 @@
}
}
@media (min-width: 1024px) {
.redesigned-emotion-grid,
.emo-grid {
align-items: stretch;
}
.redesigned-sentiment-view .sentiment-analysis-main {
height: max-content;
}
.redesigned-sentiment-view .sentiment-analysis-rail {
height: 0;
min-height: 100%;
overflow: auto;
}
.redesigned-sentiment-view .sentiment-trend-panel {
display: flex;
flex-direction: column;
}
.redesigned-sentiment-view .sentiment-chart-shell {
flex: 0 0 auto;
height: min(350px, 40vh);
}
.redesigned-sentiment-view .sentiment-chart-shell canvas {
height: 100%;
}
.redesigned-sentiment-view .sentiment-cycle-summary {
flex: 0 0 auto;
}
.redesigned-sentiment-view .sentiment-components-panel {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
}
.redesigned-sentiment-view .sentiment-component-list {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
padding: 4px 16px 8px;
}
.redesigned-sentiment-view .sentiment-component-item {
padding: 4px 0px;
}
.redesigned-sentiment-view .sentiment-component-item small {
display: none;
}
.redesigned-sentiment-view .sentiment-phase-block {
gap: 12px;
padding: 10px 12px;
}
.redesigned-sentiment-view .sentiment-current-phase-badge {
padding: 8px 12px;
}
.redesigned-sentiment-view .sentiment-phase-advice {
margin-top: 4px;
padding: 4px 8px;
line-height: 1.4;
}
.redesigned-sentiment-view .sentiment-feedback-strip > span {
padding: 4px 10px;
}
}
@media (min-width: 1024px) {
.sentiment-cycle-summary {
grid-template-columns: minmax(270px, 1.25fr) repeat(3, minmax(160px, 1fr));
+2 -19
View File
@@ -46,29 +46,12 @@
}
}
function readableRequestError(error) {
const message = String(error?.message || "");
if (
error instanceof TypeError
|| /failed to fetch|networkerror|load failed|network request failed/i.test(message)
) {
return "网络请求失败,服务暂时不可用,请稍后重试。";
}
return message || "请求失败";
}
async function request(url, method = "GET", body = null, options = {}) {
let response;
try {
response = await fetch(url, requestOptions(method, body, options.signal));
} catch (error) {
throw new ApiError(readableRequestError(error), 0, null);
}
const response = await fetch(url, requestOptions(method, body, options.signal));
const payload = await parseJson(response);
handleUnauthorized(response, url);
if (!response.ok || payload.error) {
const message = payload.message || payload.error || "请求失败";
throw new ApiError(message, response.status, payload);
throw new ApiError(payload.error || "请求失败", response.status, payload);
}
return payload;
}
+2 -10
View File
@@ -660,9 +660,7 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
text-align: left;
height: var(--size-statusbar);
min-height: var(--size-statusbar);
min-height: 38px;
display: flex;
@@ -672,7 +670,7 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
margin: auto -8px -8px;
padding: 0 16px;
padding: 10px 16px;
border-right: 0px;
@@ -693,12 +691,6 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
font-size: 12px;
}
.sidebar-collapse-button .lucide {
width: 14px;
height: 14px;
}
body.sidebar-collapsed .sidebar-collapse-button span {
display: none;
}
+4 -10
View File
@@ -1294,9 +1294,7 @@ body.sidebar-collapsed {
}
.sidebar-brand {
height: var(--size-topbar);
min-height: var(--size-topbar);
min-height: 55px;
display: flex;
@@ -1306,7 +1304,7 @@ body.sidebar-collapsed {
margin: 0px -8px 7px;
padding: 0 16px;
padding: 0px 16px;
border-bottom: 1px solid var(--r2-line-soft);
@@ -2148,17 +2146,13 @@ body.sidebar-collapsed .status-bar {
}
.module-nav .sidebar-brand {
height: var(--size-topbar);
min-height: var(--size-topbar);
display: flex;
align-items: center;
gap: 8px;
padding: 0 16px;
padding: 14px 16px;
border-bottom: 1px solid var(--line-soft);
}
@@ -3500,7 +3494,7 @@ body.sidebar-collapsed .status-bar {
flex: 0 0 auto;
align-items: center;
gap: var(--header-action-gap);
margin-left: auto;
margin-left: 0;
overflow: visible;
}
+136 -96
View File
@@ -1,4 +1,6 @@
const { test, expect } = require("@playwright/test");
const fs = require("fs");
const path = require("path");
const dashboard = {
meta: {
@@ -725,6 +727,7 @@ test("collapsed overview and sentiment layout keep a single current reading", as
const trend = document.querySelector(".sentiment-trend-panel").getBoundingClientRect();
const summary = document.querySelector(".sentiment-cycle-summary").getBoundingClientRect();
const chart = document.querySelector(".sentiment-chart-shell").getBoundingClientRect();
const rail = document.querySelector(".sentiment-analysis-rail").getBoundingClientRect();
const detail = document.querySelector(".sentiment-detail-toolbar").getBoundingClientRect();
const label = document.querySelector(".sentiment-block .metric-label");
const status = document.querySelector(".sentiment-block .sentiment-text");
@@ -733,8 +736,10 @@ test("collapsed overview and sentiment layout keep a single current reading", as
return {
columnsAligned: Math.abs(trend.top - summary.top) < 1,
railAligned: Math.abs(summary.x - components.x) < 1 && Math.abs(summary.width - components.width) < 1 && components.top > summary.bottom,
bottomsAligned: Math.abs(trend.bottom - rail.bottom) < 2,
detailAfterAnalysis: detail.top > Math.max(trend.bottom, components.bottom),
chartHeight: chart.height,
viewportHeight: window.innerHeight,
sameType: labelStyle.fontSize === statusStyle.fontSize
&& labelStyle.fontWeight === statusStyle.fontWeight
&& labelStyle.lineHeight === statusStyle.lineHeight,
@@ -744,8 +749,11 @@ test("collapsed overview and sentiment layout keep a single current reading", as
});
expect(alignment.columnsAligned).toBe(true);
expect(alignment.railAligned).toBe(true);
expect(alignment.bottomsAligned).toBe(true);
expect(alignment.detailAfterAnalysis).toBe(true);
expect(alignment.chartHeight).toBeGreaterThanOrEqual(340);
expect(alignment.chartHeight).toBeLessThanOrEqual(360);
expect(alignment.chartHeight / alignment.viewportHeight).toBeLessThan(0.45);
expect(alignment.sameType).toBe(true);
expect(alignment.sameBaseline).toBe(true);
expect(alignment.noStatusOffset).toBe(true);
@@ -780,6 +788,134 @@ test("collapsed overview and sentiment layout keep a single current reading", as
}
});
function buildSentimentHistoryRows(count = 20) {
const phases = ["冰点", "修复", "发酵", "高潮", "分化", "退潮"];
return Array.from({ length: count }, (_, index) => {
const score = 28 + ((index * 7) % 55);
return {
trade_date: `2026-07-${String(index + 1).padStart(2, "0")}`,
score,
label: "情绪观察",
phase: phases[index % phases.length],
direction: index % 2 ? "升温" : "降温",
day_change: index % 2 ? 2.4 : -1.6,
seal_rate: 70 + (index % 10),
limit_up_count: 30 + index,
first_board_count: 20,
second_board_count: 6,
three_plus_count: 3,
max_height: 4,
broken_count: 17,
limit_down_count: 8,
previous_limit_count: 40,
previous_positive_count: 12,
previous_positive_rate: 30,
average_previous_change: -1.2,
normalization: "固定锚点",
history_days: count,
components: {
breadth: { label: "市场宽度", score: 55.8, weight: 20, summary: "红盘家数偏少" },
limit: { label: "涨停生态", score: 79.0, weight: 25, summary: "封板率仍需确认" },
profit: { label: "赚钱效应", score: 67.0, weight: 30, summary: "昨日反馈偏弱" },
ladder: { label: "连板结构", score: 81.5, weight: 15, summary: "高度仍在压缩" },
amount: { label: "成交活跃度", score: 46.1, weight: 10, summary: "量能低于均值" },
},
};
});
}
function contrastRatio(rgbA, rgbB) {
const channel = (value) => {
const scaled = value / 255;
return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
};
const luminance = (rgb) => {
const [red, green, blue] = rgb.match(/\d+/g).map(Number);
return 0.2126 * channel(red) + 0.7152 * channel(green) + 0.0722 * channel(blue);
};
const first = luminance(rgbA);
const second = luminance(rgbB);
const [high, low] = first > second ? [first, second] : [second, first];
return (high + 0.05) / (low + 0.05);
}
test("sentiment trend chart keeps one-screen proportion across 4K-equivalent zooms", async ({ page }) => {
const screenshotDir = path.join("runtime", "hel217-screenshots");
fs.mkdirSync(screenshotDir, { recursive: true });
await mockApplication(page, session("user", true));
await page.goto("/index.html");
const rows = buildSentimentHistoryRows(20);
await page.evaluate((historyRows) => {
state.sentimentHistory = { available_days: 20, rows: historyRows };
renderSentimentHistory();
}, rows);
await page.locator('[data-view="sentimentCycleView"]').first().click();
const viewports = [
{ name: "4k150-100", width: 2560, height: 1440 },
{ name: "4k150-110", width: 2328, height: 1309 },
{ name: "4k150-125", width: 2048, height: 1152 },
];
for (const viewport of viewports) {
await page.setViewportSize({ width: viewport.width, height: viewport.height });
await page.waitForTimeout(200);
for (const theme of ["light", "dark"]) {
const current = await page.locator("html").getAttribute("data-theme");
if (current !== theme) {
await page.locator("#themeToggle").click();
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
}
const metrics = await page.evaluate(() => {
const trend = document.querySelector(".sentiment-trend-panel").getBoundingClientRect();
const rail = document.querySelector(".sentiment-analysis-rail").getBoundingClientRect();
const chart = document.querySelector(".sentiment-chart-shell").getBoundingClientRect();
const detail = document.querySelector(".sentiment-detail-toolbar").getBoundingClientRect();
const history = document.querySelector(".sentiment-history-frame").getBoundingClientRect();
return {
chartHeight: chart.height,
viewportHeight: window.innerHeight,
bottomsAligned: Math.abs(trend.bottom - rail.bottom) < 2,
detailAfterAnalysis: detail.top > Math.max(trend.bottom, rail.bottom) - 1,
historyVisibleBelow: history.top > detail.bottom - 1,
overflowX: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1,
};
});
expect(metrics.chartHeight, viewport.name).toBeGreaterThanOrEqual(280);
expect(metrics.chartHeight, viewport.name).toBeLessThanOrEqual(360);
expect(metrics.chartHeight / metrics.viewportHeight, viewport.name).toBeLessThan(0.42);
expect(metrics.bottomsAligned, viewport.name).toBe(true);
expect(metrics.detailAfterAnalysis, viewport.name).toBe(true);
expect(metrics.historyVisibleBelow, viewport.name).toBe(true);
expect(metrics.overflowX, viewport.name).toBe(false);
if (theme === "dark") {
const tooltip = page.locator("#sentimentChartTooltip");
await page.locator("#sentimentTrendChart").hover({ position: { x: 360, y: 110 } });
await expect(tooltip).toBeVisible();
const tooltipColors = await tooltip.evaluate((element) => {
const style = getComputedStyle(element);
const bold = element.querySelector("b");
return {
color: style.color,
background: style.backgroundColor,
boldColor: bold ? getComputedStyle(bold).color : style.color,
text: element.textContent,
};
});
expect(tooltipColors.text).toMatch(/温度/);
expect(contrastRatio(tooltipColors.color, tooltipColors.background)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(tooltipColors.boldColor, tooltipColors.background)).toBeGreaterThanOrEqual(4.5);
}
await page.screenshot({
path: path.join(screenshotDir, `${viewport.name}-${theme}.png`),
fullPage: true,
});
}
}
});
test("limit-up pool separates stock identity and restores the reason column", async ({ page }) => {
await mockApplication(page, session("user", true));
await page.goto("/index.html");
@@ -3735,99 +3871,3 @@ test("desktop header keeps commands in view and tape text unclipped across works
await page.screenshot({ path: path.join(shotDir, "admin-390-night.png") });
fs.writeFileSync(path.join(shotDir, "measurements.json"), `${JSON.stringify(measurements, null, 2)}\n`);
});
test("HEL-183 heaven tools right-align and shell heights unify", async ({ page }) => {
const fs = require("node:fs");
const path = require("node:path");
const shotDir = path.join(__dirname, "../../runtime/hel183-shots");
fs.mkdirSync(shotDir, { recursive: true });
await page.setViewportSize({ width: 1440, height: 900 });
await mockApplication(page, session("admin", true));
await page.goto("/index.html");
const measure = () => page.evaluate(() => {
const box = (node) => {
if (!node) return null;
const r = node.getBoundingClientRect();
return { x: r.x, y: r.y, right: r.right, width: r.width, height: r.height };
};
const brand = document.querySelector(".module-nav .sidebar-brand") || document.querySelector(".sidebar-brand");
const header = document.querySelector(".app-header");
const actions = document.querySelector(".header-actions");
const collapse = document.querySelector(".sidebar-collapse-button");
const status = document.querySelector(".status-bar");
const overview = document.querySelector(".overview-strip");
const brandBox = box(brand);
const headerBox = box(header);
const actionsBox = box(actions);
const collapseBox = box(collapse);
const statusBox = box(status);
return {
brandHeight: brandBox ? Math.round(brandBox.height) : null,
headerHeight: headerBox ? Math.round(headerBox.height) : null,
brandBottom: brandBox ? Math.round(brandBox.y + brandBox.height) : null,
headerBottom: headerBox ? Math.round(headerBox.y + headerBox.height) : null,
collapseHeight: collapseBox ? Math.round(collapseBox.height) : null,
statusHeight: statusBox ? Math.round(statusBox.height) : null,
actionsNearRight: actionsBox && headerBox ? (headerBox.right - actionsBox.right) < 24 : false,
actionsMarginLeft: actions ? getComputedStyle(actions).marginLeft : null,
overviewDisplay: overview ? getComputedStyle(overview).display : null,
mentorPadTop: (() => {
const mentor = document.querySelector("#mentorView");
return mentor ? getComputedStyle(mentor).paddingTop : null;
})(),
};
});
await page.locator('[data-view="sentimentCycleView"]').first().click();
await expect(page.locator("#sentimentCycleView")).toHaveClass(/active-view/);
let geo = await measure();
expect(geo.brandHeight, "logo height").toBe(64);
expect(geo.headerHeight, "header height").toBe(64);
expect(geo.brandBottom, "logo/header bottom align").toBe(geo.headerBottom);
expect(geo.collapseHeight, "collapse height").toBe(28);
expect(geo.statusHeight, "status height").toBe(28);
expect(geo.actionsNearRight, "sentiment tools right").toBe(true);
await page.locator(".app-header").screenshot({ path: path.join(shotDir, "sentiment-header-day.png") });
await page.screenshot({ path: path.join(shotDir, "sentiment-page-day.png") });
await page.locator('[data-view="heavenView"]').first().click();
await expect(page.locator("#heavenView")).toHaveClass(/active-view/);
await expect(page.locator("#heavenView .heaven-page-head")).toBeVisible();
await expect(page.locator("#heavenView .heaven-page-head .segment")).toHaveCount(3);
geo = await measure();
expect(geo.overviewDisplay, "heaven hides overview").toBe("none");
expect(geo.actionsMarginLeft, "tools margin-left resolved").not.toBe("0px");
expect(Number.parseFloat(geo.actionsMarginLeft), "tools left auto gap").toBeGreaterThan(40);
expect(geo.actionsNearRight, "heaven tools right").toBe(true);
expect(geo.brandHeight).toBe(64);
expect(geo.collapseHeight).toBe(28);
await page.locator(".app-header").screenshot({ path: path.join(shotDir, "heaven-header-day.png") });
await page.screenshot({ path: path.join(shotDir, "heaven-page-day.png") });
await page.locator('[data-heaven-panel="fortune"]').click();
await expect(page.locator('[data-heaven-panel="fortune"]')).toHaveClass(/active/);
await expect(page.locator("#heavenFortunePanel")).toHaveClass(/active-heaven-panel/);
await page.locator('[data-view="mentorView"]').first().click();
await expect(page.locator("#mentorView")).toHaveClass(/active-view/);
geo = await measure();
expect(geo.mentorPadTop, "mentor top padding").toBe("14px");
await page.screenshot({ path: path.join(shotDir, "mentor-page-day.png") });
await page.locator("#themeToggle").click();
await page.locator('[data-view="heavenView"]').first().click();
await expect(page.locator("#heavenView")).toHaveClass(/active-view/);
geo = await measure();
expect(geo.actionsNearRight, "heaven night tools right").toBe(true);
expect(geo.brandHeight).toBe(64);
await page.locator(".app-header").screenshot({ path: path.join(shotDir, "heaven-header-night.png") });
await page.screenshot({ path: path.join(shotDir, "heaven-page-night.png") });
await page.locator('[data-view="sentimentCycleView"]').first().click();
await page.locator(".app-header").screenshot({ path: path.join(shotDir, "sentiment-header-night.png") });
await page.screenshot({ path: path.join(shotDir, "sentiment-page-night.png") });
await page.locator('[data-view="mentorView"]').first().click();
await page.screenshot({ path: path.join(shotDir, "mentor-page-night.png") });
});
+5
View File
@@ -343,6 +343,11 @@ class FrontendContractTests(unittest.TestCase):
self.assertIn("--sentiment-history-max-height: 510px;", self.tokens)
self.assertIn("max-height: var(--sentiment-history-max-height);", self.sentiment_styles)
self.assertIn("overflow: auto;", self.sentiment_styles)
self.assertIn("height: min(350px, 40vh);", self.sentiment_styles)
self.assertIn(':root[data-theme="dark"] #sentimentCycleView .sentiment-chart-tooltip {', self.sentiment_styles)
self.assertIn("background: var(--surface-muted);", self.sentiment_styles)
self.assertIn("color: var(--text-primary);", self.sentiment_styles)
self.assertNotIn("flex: 1 1 auto;\n\n height: auto;", self.sentiment_styles)
def test_mentor_final_visual_fix_contract(self):
shell_styles = (STATIC_DIR / "shared" / "shell.css").read_text(encoding="utf-8")
+1 -150
View File
@@ -1,162 +1,13 @@
from __future__ import annotations
import json
import tempfile
import unittest
from http import HTTPStatus
from pathlib import Path
from unittest.mock import patch
from backend.features.heaven.engine import build_five_phase_field, hexagram_from_lines
from backend.features.heaven.http import HeavenHttpMixin
from backend.features.heaven.knowledge import (
HeavenKnowledgeError,
clear_heaven_knowledge_cache,
prepare_heaven_context,
resolve_heaven_knowledge_path,
_knowledge_catalog,
)
from backend.features.heaven.knowledge import prepare_heaven_context
from backend.features.heaven.six_yao import build_six_yao_chart
class HeavenKnowledgeTests(unittest.TestCase):
def tearDown(self) -> None:
clear_heaven_knowledge_cache()
def test_catalog_loads_from_trusted_repo_file(self):
clear_heaven_knowledge_cache()
path = resolve_heaven_knowledge_path()
catalog = _knowledge_catalog()
self.assertTrue(path.is_file())
self.assertEqual(path.name, "heaven_knowledge.json")
self.assertTrue(str(catalog.get("version") or "").startswith("2026."))
self.assertIn("zhouyi", catalog["sources"])
self.assertIn("neijing", catalog["sources"])
self.assertEqual(len(catalog["fortune"]["qi"]), 6)
self.assertEqual(len(catalog["fortune"]["personal_relations"]), 10)
def test_missing_knowledge_file_raises_chinese_structured_error(self):
clear_heaven_knowledge_cache()
missing = Path(tempfile.mkdtemp()) / "missing-heaven_knowledge.json"
with patch(
"backend.features.heaven.knowledge.KNOWLEDGE_FILE", missing
), patch(
"backend.features.heaven.knowledge.KNOWLEDGE_SEED_FILE",
missing.with_name("missing-seed.json"),
):
with self.assertRaises(HeavenKnowledgeError) as raised:
_knowledge_catalog()
self.assertEqual(raised.exception.error_code, "heaven_knowledge_missing")
self.assertIn("缺失", str(raised.exception))
def test_corrupt_knowledge_json_raises_chinese_structured_error(self):
clear_heaven_knowledge_cache()
with tempfile.TemporaryDirectory() as temp_dir:
broken = Path(temp_dir) / "heaven_knowledge.json"
broken.write_text("{not-json", encoding="utf-8")
with patch(
"backend.features.heaven.knowledge.KNOWLEDGE_FILE", broken
), patch(
"backend.features.heaven.knowledge.KNOWLEDGE_SEED_FILE",
Path(temp_dir) / "unused-seed.json",
):
with self.assertRaises(HeavenKnowledgeError) as raised:
_knowledge_catalog()
self.assertEqual(raised.exception.error_code, "heaven_knowledge_invalid")
self.assertIn("损坏", str(raised.exception))
def test_interpret_http_returns_structured_chinese_error_for_missing_file(self):
class FakeHandler(HeavenHttpMixin):
def __init__(self) -> None:
self.payload = None
self.status = None
self.application_service = type(
"Svc",
(),
{
"heaven_interpret": staticmethod(
lambda _body: (_ for _ in ()).throw(
HeavenKnowledgeError(
"问天知识文件缺失:未找到 heaven_knowledge.json。",
code="heaven_knowledge_missing",
)
)
)
},
)()
def read_json_body(self):
return {"mode": "trend", "trade_date": "2026-08-04"}
def send_json(self, payload, status=HTTPStatus.OK, headers=None):
self.payload = payload
self.status = status
handler = FakeHandler()
handler.heaven_interpret()
self.assertEqual(handler.status, HTTPStatus.BAD_REQUEST)
self.assertIn("缺失", handler.payload["error"])
self.assertEqual(handler.payload["code"], "heaven_knowledge_missing")
def test_interpret_http_returns_structured_chinese_error_for_corrupt_json(self):
class FakeHandler(HeavenHttpMixin):
def __init__(self) -> None:
self.payload = None
self.status = None
self.application_service = type(
"Svc",
(),
{
"heaven_interpret": staticmethod(
lambda _body: (_ for _ in ()).throw(
HeavenKnowledgeError(
"问天知识文件 JSON 损坏(heaven_knowledge.json),无法解析:第 1 行附近。",
code="heaven_knowledge_invalid",
)
)
)
},
)()
def read_json_body(self):
return {"mode": "trend", "trade_date": "2026-08-04"}
def send_json(self, payload, status=HTTPStatus.OK, headers=None):
self.payload = payload
self.status = status
handler = FakeHandler()
handler.heaven_interpret()
self.assertEqual(handler.status, HTTPStatus.BAD_REQUEST)
self.assertIn("损坏", handler.payload["error"])
self.assertEqual(handler.payload["code"], "heaven_knowledge_invalid")
def test_seed_fallback_when_data_file_missing(self):
clear_heaven_knowledge_cache()
with tempfile.TemporaryDirectory() as temp_dir:
seed = Path(temp_dir) / "seed.json"
seed.write_text(
json.dumps(
{
"version": "test-seed",
"sources": {"zhouyi": {"title": "周易"}},
"trend": {"method": "m", "rules": {"stable": "s", "single": "a", "multiple": "b"}},
"fortune": {},
"heart": {},
},
ensure_ascii=False,
),
encoding="utf-8",
)
missing_data = Path(temp_dir) / "data-heaven_knowledge.json"
with patch(
"backend.features.heaven.knowledge.KNOWLEDGE_FILE", missing_data
), patch(
"backend.features.heaven.knowledge.KNOWLEDGE_SEED_FILE", seed
):
catalog = _knowledge_catalog()
self.assertEqual(catalog["version"], "test-seed")
def test_fortune_context_excludes_weighted_summary_and_adds_bounded_industry_symbols(self):
field = build_five_phase_field("2026-08-04")
prepared = prepare_heaven_context(