Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2a165ada8 | ||
|
|
e29d5115fa | ||
|
|
aef8a059f2 | ||
|
|
f905b44675 | ||
|
|
541fb48c1c | ||
|
|
2a2d205a38 | ||
|
|
34cb32d78f | ||
|
|
89b8d33de7 | ||
|
|
d9ee725744 | ||
|
|
1cb2745867 | ||
|
|
f27471238a | ||
|
|
6d7a839202 | ||
|
|
fc1e5b89e4 | ||
|
|
cf206c7de9 | ||
|
|
09a935aac4 | ||
|
|
8e94c7b429 | ||
|
|
013ed29ffb | ||
|
|
7ad445bc9f | ||
|
|
ef86b31f6b | ||
|
|
94e6f618c8 | ||
|
|
f68f950106 |
@@ -9,6 +9,7 @@ __pycache__/
|
||||
*.log
|
||||
runtime/
|
||||
data/cache/
|
||||
data/backups/
|
||||
data/private-mentor-skills/
|
||||
data/*.db
|
||||
data/*.db-shm
|
||||
|
||||
@@ -14,13 +14,29 @@
|
||||
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` 备份一起保存。
|
||||
@@ -166,6 +182,7 @@ tools/build_image.sh <提交号> <镜像tag>
|
||||
该脚本的行为约束:
|
||||
|
||||
- 先 `git fetch`,再把提交号解析为完整 SHA,解析失败立即中止,绝不使用本地脏状态或服务器旧目录;
|
||||
- 构建前读取当前线上容器镜像的 `org.opencontainers.image.revision`,用 Git 祖先关系确认候选提交包含线上全部历史;落后 `main`、旁支或错误提交会直接退出,并打印线上提交、候选提交、文件差异和将丢失的提交;
|
||||
- 镜像 tag 必须以 `-<提交短号7位>` 结尾(如 `hel234-cefc869`),禁止 `latest`、`rollback-*`;
|
||||
- 通过 `git archive <提交> | ssh 部署机 docker build -` 流式构建,服务器上不存在构建用工作树;
|
||||
- 构建后回读镜像 label 里的 `org.opencontainers.image.revision`,与预期提交不一致则删除镜像并中止;
|
||||
|
||||
+4
-1
@@ -23,7 +23,10 @@ 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
|
||||
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
|
||||
|
||||
USER xiaobai
|
||||
|
||||
|
||||
@@ -41,13 +41,16 @@ class DashboardMixin:
|
||||
raise TushareError(f"No daily data returned for {trade_date}")
|
||||
|
||||
notices: list[str] = []
|
||||
limit_data_source = "official"
|
||||
try:
|
||||
limit_rows = self._load_limit_lists(trade_date)
|
||||
previous_limit_rows = self._load_limit_type(previous_trade_date, "U")
|
||||
if not limit_rows:
|
||||
limit_data_source = "derived"
|
||||
notices.append("涨跌停高级接口当日数据尚未更新,已使用日线数据推算。")
|
||||
limit_rows = self._derive_limits(trade_date, daily)
|
||||
except TushareError as exc:
|
||||
limit_data_source = "derived"
|
||||
notices.append(f"涨跌停高级接口不可用,已使用日线数据推算:{exc}")
|
||||
limit_rows = self._derive_limits(trade_date, daily)
|
||||
previous_daily = self._load_daily(previous_trade_date)
|
||||
@@ -79,6 +82,7 @@ class DashboardMixin:
|
||||
"trade_date": _display_date(trade_date),
|
||||
"previous_trade_date": _display_date(previous_trade_date),
|
||||
"source": "tushare",
|
||||
"limit_data_source": limit_data_source,
|
||||
"updated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
"notice": ";".join(notices),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"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": {
|
||||
"兄弟": "兄弟是与卦宫五行同类的关系。在股票交易问题中可作为竞争、同类力量或资源分流的候选象义,但不直接等同合作方、亏损或他人拿走资金。",
|
||||
"子孙": "子孙是卦宫所生的关系,可作为舒缓、产出、执行后的释放或对压力的制衡候选象义,但不直接等同收益、资金提供方或确定的利好。",
|
||||
"妻财": "妻财是卦宫所克的关系,在股票交易问题中可作为价值、收益预期、持仓利益或可支配资源的候选象义,但不直接等同现金、融资、自有资金或必得之财。",
|
||||
"官鬼": "官鬼是克制卦宫的关系,可作为压力、风险、规则约束或担忧的候选象义,但不直接等同借贷、坏消息、疾病或必然损失。",
|
||||
"父母": "父母是生助卦宫的关系,可作为信息、依据、计划、规则、凭据或保护条件的候选象义,但不直接等同政策、合同或某一条消息。"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,24 @@ 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_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
|
||||
self._send_heaven_client_error(exc)
|
||||
|
||||
def heaven_personal(self) -> None:
|
||||
try:
|
||||
@@ -19,12 +28,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_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
|
||||
self._send_heaven_client_error(exc)
|
||||
|
||||
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 (ValueError, json.JSONDecodeError) as exc:
|
||||
self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
|
||||
except (HeavenKnowledgeError, ValueError, json.JSONDecodeError) as exc:
|
||||
self._send_heaven_client_error(exc)
|
||||
|
||||
@@ -2,12 +2,23 @@ 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]:
|
||||
@@ -379,9 +390,49 @@ 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]:
|
||||
payload = json.loads(KNOWLEDGE_FILE.read_text(encoding="utf-8"))
|
||||
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",
|
||||
)
|
||||
if not payload.get("version") or not isinstance(payload.get("sources"), dict):
|
||||
raise ValueError("问天知识库格式不完整。")
|
||||
raise HeavenKnowledgeError(
|
||||
f"问天知识库格式不完整({path.name}):缺少 version 或 sources。",
|
||||
code="heaven_knowledge_invalid",
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def clear_heaven_knowledge_cache() -> None:
|
||||
_knowledge_catalog.cache_clear()
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Auditable recent-trading-day snapshot backfill helpers.
|
||||
|
||||
Planning and backup stay free of provider imports so feature boundary tests remain green.
|
||||
The service layer supplies open trading dates from the live calendar and executes sync.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
|
||||
MAX_RANGE_TRADING_DAYS = 15
|
||||
MAX_RECENT_TRADING_DAYS = 60
|
||||
DEFAULT_RECENT_TRADING_DAYS = 60
|
||||
|
||||
# Tables touched by a successful historical dashboard sync. User / token / model
|
||||
# tables must never appear here.
|
||||
SNAPSHOT_BACKFILL_WRITE_TABLES = frozenset(
|
||||
{
|
||||
"dashboard_snapshots",
|
||||
"data_snapshots",
|
||||
"sync_runs",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def clamp_recent_lookback(lookback: int) -> int:
|
||||
value = int(lookback)
|
||||
if value < 1:
|
||||
raise ValueError("回补交易日数量至少为 1。")
|
||||
if value > MAX_RECENT_TRADING_DAYS:
|
||||
raise ValueError(f"单次最多回补最近 {MAX_RECENT_TRADING_DAYS} 个交易日。")
|
||||
return value
|
||||
|
||||
|
||||
def calendar_window_start(end_date: str, lookback: int) -> str:
|
||||
"""Natural-day lower bound large enough to cover lookback open sessions."""
|
||||
end = datetime.strptime(end_date, "%Y%m%d").date()
|
||||
span = max(40, int(lookback * 2) + 20)
|
||||
return (end - timedelta(days=span)).strftime("%Y%m%d")
|
||||
|
||||
|
||||
def select_open_trade_dates(
|
||||
calendar_rows: Iterable[dict[str, Any]],
|
||||
end_date: str,
|
||||
lookback: int,
|
||||
) -> list[str]:
|
||||
"""Pick the last ``lookback`` open SSE sessions on or before ``end_date``."""
|
||||
lookback = clamp_recent_lookback(lookback)
|
||||
end = normalize_compact_date(end_date)
|
||||
open_dates = sorted(
|
||||
{
|
||||
normalize_compact_date(str(row.get("cal_date") or ""))
|
||||
for row in calendar_rows
|
||||
if int(row.get("is_open") or 0) == 1 and row.get("cal_date")
|
||||
}
|
||||
)
|
||||
open_dates = [item for item in open_dates if item <= end]
|
||||
if not open_dates:
|
||||
raise ValueError("交易日历未返回可用交易日,请检查行情 Token。")
|
||||
return open_dates[-lookback:]
|
||||
|
||||
|
||||
def select_open_trade_dates_in_range(
|
||||
calendar_rows: Iterable[dict[str, Any]],
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
*,
|
||||
maximum: int = MAX_RANGE_TRADING_DAYS,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Return (open_dates, skipped_non_trading_days) inside an inclusive range."""
|
||||
start = normalize_compact_date(start_date)
|
||||
end = normalize_compact_date(end_date)
|
||||
if start > end:
|
||||
raise ValueError("开始日期不能晚于结束日期。")
|
||||
open_set = {
|
||||
normalize_compact_date(str(row.get("cal_date") or ""))
|
||||
for row in calendar_rows
|
||||
if int(row.get("is_open") or 0) == 1 and row.get("cal_date")
|
||||
}
|
||||
open_dates: list[str] = []
|
||||
skipped: list[str] = []
|
||||
cursor = datetime.strptime(start, "%Y%m%d").date()
|
||||
last = datetime.strptime(end, "%Y%m%d").date()
|
||||
while cursor <= last:
|
||||
compact = cursor.strftime("%Y%m%d")
|
||||
if compact in open_set:
|
||||
open_dates.append(compact)
|
||||
else:
|
||||
skipped.append(compact)
|
||||
cursor += timedelta(days=1)
|
||||
if len(open_dates) > maximum:
|
||||
raise ValueError(f"单次最多回补 {maximum} 个交易日。")
|
||||
return open_dates, skipped
|
||||
|
||||
|
||||
def classify_snapshot_coverage(
|
||||
trade_dates: list[str],
|
||||
existing_dates: Iterable[str],
|
||||
) -> dict[str, Any]:
|
||||
present_set = {
|
||||
normalize_compact_date(item)
|
||||
for item in existing_dates
|
||||
if item
|
||||
}
|
||||
present = [item for item in trade_dates if item in present_set]
|
||||
missing = [item for item in trade_dates if item not in present_set]
|
||||
return {
|
||||
"trade_dates": list(trade_dates),
|
||||
"present": present,
|
||||
"missing": missing,
|
||||
"present_count": len(present),
|
||||
"missing_count": len(missing),
|
||||
}
|
||||
|
||||
|
||||
def create_sqlite_backup(
|
||||
source_path: Path,
|
||||
backup_dir: Path,
|
||||
*,
|
||||
label: str = "pre-backfill",
|
||||
stamped_at: datetime | None = None,
|
||||
) -> Path:
|
||||
"""Create a timestamped SQLite backup via the native backup API."""
|
||||
source = Path(source_path)
|
||||
if not source.exists():
|
||||
raise FileNotFoundError(f"数据库不存在:{source}")
|
||||
stamp = (stamped_at or datetime.now().astimezone()).strftime("%Y%m%d-%H%M%S")
|
||||
safe_label = "".join(ch if ch.isalnum() or ch in "-_" else "-" for ch in label).strip("-") or "backup"
|
||||
backup_dir = Path(backup_dir)
|
||||
backup_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = backup_dir / f"review-{safe_label}-{stamp}.db"
|
||||
source_conn = sqlite3.connect(f"file:{source}?mode=ro", uri=True)
|
||||
try:
|
||||
target_conn = sqlite3.connect(target)
|
||||
try:
|
||||
source_conn.backup(target_conn)
|
||||
target_conn.commit()
|
||||
finally:
|
||||
target_conn.close()
|
||||
finally:
|
||||
source_conn.close()
|
||||
return target
|
||||
|
||||
|
||||
def display_date(compact: str) -> str:
|
||||
value = normalize_compact_date(compact)
|
||||
return f"{value[:4]}-{value[4:6]}-{value[6:8]}"
|
||||
|
||||
|
||||
def normalize_compact_date(value: str) -> str:
|
||||
compact = str(value or "").replace("-", "").strip()
|
||||
if len(compact) != 8 or not compact.isdigit():
|
||||
raise ValueError("日期格式应为 YYYY-MM-DD。")
|
||||
datetime.strptime(compact, "%Y%m%d")
|
||||
return compact
|
||||
|
||||
|
||||
def build_backfill_audit(
|
||||
*,
|
||||
mode: str,
|
||||
end_date: str,
|
||||
lookback: int | None,
|
||||
coverage: dict[str, Any],
|
||||
skipped_non_trading_days: list[str] | None = None,
|
||||
backup_path: str | None = None,
|
||||
dry_run: bool = False,
|
||||
results: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
results = list(results or [])
|
||||
succeeded = [row for row in results if row.get("status") == "success"]
|
||||
skipped = [row for row in results if row.get("status") == "skipped"]
|
||||
failed = [row for row in results if row.get("status") == "failed"]
|
||||
return {
|
||||
"ok": not failed,
|
||||
"mode": mode,
|
||||
"dry_run": dry_run,
|
||||
"end_date": display_date(end_date),
|
||||
"lookback": lookback,
|
||||
"backup_path": backup_path,
|
||||
"write_tables": sorted(SNAPSHOT_BACKFILL_WRITE_TABLES),
|
||||
"trade_dates": [display_date(item) for item in coverage.get("trade_dates") or []],
|
||||
"present": [display_date(item) for item in coverage.get("present") or []],
|
||||
"missing": [display_date(item) for item in coverage.get("missing") or []],
|
||||
"skipped_non_trading_days": [
|
||||
display_date(item) for item in (skipped_non_trading_days or [])
|
||||
],
|
||||
"present_count": int(coverage.get("present_count") or 0),
|
||||
"missing_count": int(coverage.get("missing_count") or 0),
|
||||
"results": results,
|
||||
"succeeded_count": len(succeeded),
|
||||
"skipped_count": len(skipped),
|
||||
"failed_count": len(failed),
|
||||
"created_dates": [
|
||||
str(row.get("trade_date") or "")
|
||||
for row in succeeded
|
||||
if row.get("action") == "created"
|
||||
],
|
||||
}
|
||||
@@ -227,6 +227,31 @@ class MarketRepositoryMixin:
|
||||
result.append(payload)
|
||||
return result
|
||||
|
||||
def list_snapshot_trade_dates(
|
||||
self,
|
||||
start_date: str = "",
|
||||
end_date: str = "",
|
||||
) -> list[str]:
|
||||
clauses: list[str] = []
|
||||
parameters: list[Any] = []
|
||||
if start_date:
|
||||
clauses.append("trade_date >= ?")
|
||||
parameters.append(start_date)
|
||||
if end_date:
|
||||
clauses.append("trade_date <= ?")
|
||||
parameters.append(end_date)
|
||||
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
f"""
|
||||
SELECT trade_date FROM dashboard_snapshots
|
||||
{where}
|
||||
ORDER BY trade_date
|
||||
""",
|
||||
parameters,
|
||||
).fetchall()
|
||||
return [str(row["trade_date"]) for row in rows]
|
||||
|
||||
def start_sync(self, trade_date: str, source: str) -> int:
|
||||
started_at = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self.connect() as connection:
|
||||
|
||||
@@ -3,9 +3,11 @@ from __future__ import annotations
|
||||
import copy
|
||||
import re
|
||||
from datetime import date, datetime, time as dt_time, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from backend.bootstrap.config import (
|
||||
DATA_DIR,
|
||||
normalize_date,
|
||||
tushare_code,
|
||||
validate_stock_code,
|
||||
@@ -13,6 +15,17 @@ from backend.bootstrap.config import (
|
||||
)
|
||||
from backend.data.providers.ifind_client import IfindError
|
||||
from backend.data.providers.tushare_client import TushareClient, TushareError
|
||||
from backend.features.market.backfill_history import (
|
||||
DEFAULT_RECENT_TRADING_DAYS,
|
||||
MAX_RANGE_TRADING_DAYS,
|
||||
build_backfill_audit,
|
||||
calendar_window_start,
|
||||
classify_snapshot_coverage,
|
||||
create_sqlite_backup,
|
||||
display_date,
|
||||
select_open_trade_dates,
|
||||
select_open_trade_dates_in_range,
|
||||
)
|
||||
from backend.features.market.charts import ChartDataError
|
||||
from backend.features.market.insights import MarketInsightsService
|
||||
from backend.features.sentiment.engine import SENTIMENT_ENGINE_VERSION
|
||||
@@ -185,6 +198,11 @@ class MarketServiceMixin:
|
||||
raise TushareError("公共行情尚未配置")
|
||||
dashboard = self._tushare_client().dashboard(normalized_date)
|
||||
|
||||
if (dashboard.get("meta") or {}).get("limit_data_source") == "derived":
|
||||
raise TushareError(
|
||||
str((dashboard.get("meta") or {}).get("notice") or "官方涨跌停数据尚未返回")
|
||||
)
|
||||
|
||||
dashboard["meta"]["source"] = source
|
||||
dashboard["meta"]["requested_date"] = self._display_compact_date(normalized_date)
|
||||
dashboard = self._enrich_dashboard_sentiment(dashboard, normalized_date)
|
||||
@@ -890,31 +908,226 @@ class MarketServiceMixin:
|
||||
"intraday": intraday_points,
|
||||
}
|
||||
|
||||
def backfill(self, start_date: str, end_date: str) -> list[dict[str, Any]]:
|
||||
start = datetime.strptime(normalize_date(start_date), "%Y%m%d").date()
|
||||
end = datetime.strptime(normalize_date(end_date), "%Y%m%d").date()
|
||||
if start > end:
|
||||
raise ValueError("开始日期不能晚于结束日期。")
|
||||
weekdays = []
|
||||
current = start
|
||||
while current <= end:
|
||||
if current.weekday() < 5:
|
||||
weekdays.append(current)
|
||||
current += timedelta(days=1)
|
||||
if len(weekdays) > 15:
|
||||
raise ValueError("单次最多回补 15 个工作日。")
|
||||
results = []
|
||||
for day in weekdays:
|
||||
dashboard = self.sync_dashboard(day.strftime("%Y%m%d"))
|
||||
def backfill(
|
||||
self,
|
||||
start_date: str = "",
|
||||
end_date: str = "",
|
||||
*,
|
||||
lookback: int | None = None,
|
||||
dry_run: bool = False,
|
||||
force: bool = False,
|
||||
create_backup: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Backfill dashboard snapshots for real trading days only.
|
||||
|
||||
- Date-range mode keeps the admin UI contract (max 15 open sessions).
|
||||
- Recent mode fills the last N open sessions (default/max 60).
|
||||
Weekends and holidays are reported as skipped non-trading days, not errors.
|
||||
"""
|
||||
if not self.configured:
|
||||
raise ValueError("公共行情尚未配置,无法回补历史快照。")
|
||||
normalized_end = normalize_date(end_date or date.today().isoformat())
|
||||
if lookback is not None or not (start_date and end_date):
|
||||
target_lookback = (
|
||||
DEFAULT_RECENT_TRADING_DAYS if lookback is None else int(lookback)
|
||||
)
|
||||
return self.backfill_recent_trading_days(
|
||||
end_date=normalized_end,
|
||||
lookback=target_lookback,
|
||||
dry_run=dry_run,
|
||||
force=force,
|
||||
create_backup=create_backup,
|
||||
)
|
||||
return self._backfill_date_range(
|
||||
start_date=normalize_date(start_date),
|
||||
end_date=normalized_end,
|
||||
dry_run=dry_run,
|
||||
force=force,
|
||||
create_backup=create_backup,
|
||||
)
|
||||
|
||||
def backfill_recent_trading_days(
|
||||
self,
|
||||
end_date: str = "",
|
||||
lookback: int = DEFAULT_RECENT_TRADING_DAYS,
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
force: bool = False,
|
||||
create_backup: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
normalized_end = normalize_date(end_date or date.today().isoformat())
|
||||
trade_dates = self._load_recent_open_trade_dates(normalized_end, lookback)
|
||||
existing = self.database.list_snapshot_trade_dates(
|
||||
trade_dates[0], trade_dates[-1]
|
||||
)
|
||||
coverage = classify_snapshot_coverage(trade_dates, existing)
|
||||
return self._execute_snapshot_backfill(
|
||||
mode="recent",
|
||||
end_date=normalized_end,
|
||||
lookback=lookback,
|
||||
coverage=coverage,
|
||||
skipped_non_trading_days=[],
|
||||
dry_run=dry_run,
|
||||
force=force,
|
||||
create_backup=create_backup,
|
||||
)
|
||||
|
||||
def _backfill_date_range(
|
||||
self,
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
force: bool = False,
|
||||
create_backup: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
window_start = calendar_window_start(end_date, MAX_RANGE_TRADING_DAYS)
|
||||
calendar_rows = self._tushare_client().query(
|
||||
"trade_cal",
|
||||
{
|
||||
"exchange": "SSE",
|
||||
"start_date": min(window_start, start_date),
|
||||
"end_date": end_date,
|
||||
},
|
||||
"cal_date,is_open,pretrade_date",
|
||||
)
|
||||
trade_dates, skipped = select_open_trade_dates_in_range(
|
||||
calendar_rows,
|
||||
start_date,
|
||||
end_date,
|
||||
maximum=MAX_RANGE_TRADING_DAYS,
|
||||
)
|
||||
if not trade_dates:
|
||||
raise ValueError("选定区间内没有交易日,周末或节假日无需回补。")
|
||||
existing = self.database.list_snapshot_trade_dates(trade_dates[0], trade_dates[-1])
|
||||
coverage = classify_snapshot_coverage(trade_dates, existing)
|
||||
return self._execute_snapshot_backfill(
|
||||
mode="range",
|
||||
end_date=end_date,
|
||||
lookback=None,
|
||||
coverage=coverage,
|
||||
skipped_non_trading_days=skipped,
|
||||
dry_run=dry_run,
|
||||
force=force,
|
||||
create_backup=create_backup,
|
||||
)
|
||||
|
||||
def _load_recent_open_trade_dates(self, end_date: str, lookback: int) -> list[str]:
|
||||
start_date = calendar_window_start(end_date, lookback)
|
||||
calendar_rows = self._tushare_client().query(
|
||||
"trade_cal",
|
||||
{
|
||||
"exchange": "SSE",
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
},
|
||||
"cal_date,is_open,pretrade_date",
|
||||
)
|
||||
return select_open_trade_dates(calendar_rows, end_date, lookback)
|
||||
|
||||
def _execute_snapshot_backfill(
|
||||
self,
|
||||
*,
|
||||
mode: str,
|
||||
end_date: str,
|
||||
lookback: int | None,
|
||||
coverage: dict[str, Any],
|
||||
skipped_non_trading_days: list[str],
|
||||
dry_run: bool,
|
||||
force: bool,
|
||||
create_backup: bool,
|
||||
) -> dict[str, Any]:
|
||||
targets = list(coverage["trade_dates"] if force else coverage["missing"])
|
||||
backup_path: str | None = None
|
||||
if create_backup and not dry_run and targets:
|
||||
backup = create_sqlite_backup(
|
||||
Path(self.database.path),
|
||||
DATA_DIR / "backups",
|
||||
label=f"pre-{mode}-backfill",
|
||||
)
|
||||
backup_path = str(backup)
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
if dry_run:
|
||||
for trade_date in coverage["trade_dates"]:
|
||||
exists = trade_date in coverage["present"]
|
||||
if exists and not force:
|
||||
status = "skipped"
|
||||
action = "exists"
|
||||
else:
|
||||
status = "planned"
|
||||
action = "refresh" if exists else "create"
|
||||
results.append(
|
||||
{
|
||||
"requested_date": display_date(trade_date),
|
||||
"trade_date": display_date(trade_date),
|
||||
"status": status,
|
||||
"action": action,
|
||||
}
|
||||
)
|
||||
return build_backfill_audit(
|
||||
mode=mode,
|
||||
end_date=end_date,
|
||||
lookback=lookback,
|
||||
coverage=coverage,
|
||||
skipped_non_trading_days=skipped_non_trading_days,
|
||||
backup_path=backup_path,
|
||||
dry_run=True,
|
||||
results=results,
|
||||
)
|
||||
|
||||
present_before = set(coverage["present"])
|
||||
for trade_date in targets:
|
||||
existed = trade_date in present_before
|
||||
try:
|
||||
dashboard = self.sync_dashboard(trade_date)
|
||||
actual = normalize_date(
|
||||
str(dashboard.get("meta", {}).get("trade_date") or trade_date)
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"requested_date": display_date(trade_date),
|
||||
"trade_date": display_date(actual),
|
||||
"status": "success",
|
||||
"action": "refreshed" if existed else "created",
|
||||
"source": dashboard.get("meta", {}).get("source"),
|
||||
"records": self._record_count(dashboard),
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
results.append(
|
||||
{
|
||||
"requested_date": display_date(trade_date),
|
||||
"trade_date": display_date(trade_date),
|
||||
"status": "failed",
|
||||
"action": "refresh" if existed else "create",
|
||||
"error": str(exc),
|
||||
}
|
||||
)
|
||||
|
||||
for trade_date in coverage["present"]:
|
||||
if force:
|
||||
continue
|
||||
results.append(
|
||||
{
|
||||
"requested_date": day.isoformat(),
|
||||
"trade_date": dashboard["meta"]["trade_date"],
|
||||
"source": dashboard["meta"]["source"],
|
||||
"records": self._record_count(dashboard),
|
||||
"requested_date": display_date(trade_date),
|
||||
"trade_date": display_date(trade_date),
|
||||
"status": "skipped",
|
||||
"action": "exists",
|
||||
}
|
||||
)
|
||||
return results
|
||||
|
||||
results.sort(key=lambda row: str(row.get("requested_date") or ""))
|
||||
return build_backfill_audit(
|
||||
mode=mode,
|
||||
end_date=end_date,
|
||||
lookback=lookback,
|
||||
coverage=coverage,
|
||||
skipped_non_trading_days=skipped_non_trading_days,
|
||||
backup_path=backup_path,
|
||||
dry_run=False,
|
||||
results=results,
|
||||
)
|
||||
|
||||
def _stock_identity(self, code: str, trade_date: str) -> tuple[str, str]:
|
||||
snapshot = self.database.get_snapshot(trade_date) or {}
|
||||
@@ -955,4 +1168,3 @@ class MarketServiceMixin:
|
||||
len(dashboard.get(key) or [])
|
||||
for key in ("limits", "broken", "down_limits", "yesterday_limits")
|
||||
)
|
||||
|
||||
|
||||
@@ -26,13 +26,15 @@ class SystemHttpMixin:
|
||||
def start_background_refresh(self) -> None:
|
||||
try:
|
||||
body = self.read_json_body(allow_empty=True)
|
||||
started = self.application_service.request_background_sync(
|
||||
refresh = self.application_service.request_background_sync(
|
||||
str(body.get("trade_date") or date.today().isoformat())
|
||||
)
|
||||
started = bool(refresh.get("started"))
|
||||
self.send_json(
|
||||
{
|
||||
"ok": True,
|
||||
"started": started,
|
||||
"job_key": str(refresh.get("job_key") or ""),
|
||||
"message": "后台刷新已开始" if started else "已有后台刷新任务正在运行",
|
||||
},
|
||||
HTTPStatus.ACCEPTED,
|
||||
|
||||
@@ -29,11 +29,17 @@ class SystemRoutesMixin:
|
||||
def backfill_data(self) -> None:
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
results = self.application_service.backfill(
|
||||
lookback_raw = body.get("lookback")
|
||||
lookback = int(lookback_raw) if lookback_raw not in (None, "") else None
|
||||
audit = self.application_service.backfill(
|
||||
str(body.get("start_date") or ""),
|
||||
str(body.get("end_date") or ""),
|
||||
lookback=lookback,
|
||||
dry_run=bool(body.get("dry_run")),
|
||||
force=bool(body.get("force")),
|
||||
create_backup=body.get("create_backup", True) is not False,
|
||||
)
|
||||
self.send_json({"ok": True, "results": results})
|
||||
self.send_json({"ok": True, **audit, "results": audit.get("results") or []})
|
||||
except ValueError as exc:
|
||||
self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
|
||||
except Exception as exc:
|
||||
|
||||
+14
-3
@@ -7,6 +7,16 @@ from datetime import date
|
||||
from backend.bootstrap.config import normalize_date
|
||||
|
||||
|
||||
def _verified_dashboard_result(dashboard: dict[str, object]) -> dict[str, object]:
|
||||
meta = dashboard.get("meta") or {}
|
||||
if isinstance(meta, dict) and meta.get("carried_forward"):
|
||||
return {
|
||||
"status": "failed",
|
||||
"error": str(meta.get("notice") or "未获取到所选日期的最新行情"),
|
||||
}
|
||||
return dashboard
|
||||
|
||||
|
||||
class JobServiceMixin:
|
||||
def start_background_jobs(self) -> threading.Thread:
|
||||
return self.jobs.start_scheduler(
|
||||
@@ -20,15 +30,16 @@ class JobServiceMixin:
|
||||
workers_stopped = self.jobs.wait_for_idle(timeout_seconds)
|
||||
return scheduler_stopped and workers_stopped
|
||||
|
||||
def request_background_sync(self, trade_date: str) -> bool:
|
||||
def request_background_sync(self, trade_date: str) -> dict[str, object]:
|
||||
normalized = normalize_date(trade_date)
|
||||
key = f"manual:{normalized}:{time.time_ns()}"
|
||||
return self.jobs.submit(
|
||||
started = self.jobs.submit(
|
||||
"market.refresh",
|
||||
key,
|
||||
lambda: self.sync_dashboard(normalized),
|
||||
lambda: _verified_dashboard_result(self.sync_dashboard(normalized)),
|
||||
{"trade_date": normalized, "trigger": "administrator"},
|
||||
)
|
||||
return {"started": started, "job_key": key if started else ""}
|
||||
|
||||
def _background_refresh_tick(self) -> None:
|
||||
if not (
|
||||
|
||||
@@ -374,11 +374,11 @@
|
||||
}
|
||||
],
|
||||
"css_layers": [
|
||||
"/shared/tokens.css?v=20260829-1",
|
||||
"/shared/tokens.css?v=20260829-hel240",
|
||||
"/shared/base.css?v=20260806-1",
|
||||
"/shared/shell.css?v=20260820-8",
|
||||
"/shared/auth.css?v=20260829-1",
|
||||
"/shared/components/controls.css?v=20260820-2",
|
||||
"/shared/shell.css?v=20260829-hel237",
|
||||
"/shared/auth.css?v=20260829-hel240b",
|
||||
"/shared/components/controls.css?v=20260829-hel237",
|
||||
"/shared/components/navigation.css?v=20260820-1",
|
||||
"/shared/components/cards.css?v=20260820-1",
|
||||
"/shared/components/tables.css?v=20260820-1",
|
||||
@@ -394,8 +394,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=20260820-2",
|
||||
"/pages/heaven/foundation.css?v=20260806-2",
|
||||
"/pages/mentor/foundation.css?v=20260827-hel183",
|
||||
"/pages/heaven/foundation.css?v=20260827-hel183",
|
||||
"/pages/review/foundation.css?v=20260820-4"
|
||||
],
|
||||
"frontend_composition": {
|
||||
@@ -440,8 +440,8 @@
|
||||
"code_hotspots": [
|
||||
{
|
||||
"path": "frontend/pages/heaven/foundation.css",
|
||||
"bytes": 185936,
|
||||
"lines": 11734
|
||||
"bytes": 182616,
|
||||
"lines": 11494
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/screener/foundation.css",
|
||||
@@ -450,13 +450,13 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/heaven/page.js",
|
||||
"bytes": 97189,
|
||||
"lines": 2069
|
||||
"bytes": 97268,
|
||||
"lines": 2070
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/shell.css",
|
||||
"bytes": 63550,
|
||||
"lines": 3757
|
||||
"bytes": 63659,
|
||||
"lines": 3763
|
||||
},
|
||||
{
|
||||
"path": "backend/features/heaven/engine.py",
|
||||
@@ -465,8 +465,8 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/index.html",
|
||||
"bytes": 48037,
|
||||
"lines": 663
|
||||
"bytes": 48254,
|
||||
"lines": 664
|
||||
},
|
||||
{
|
||||
"path": "backend/features/screener/catalog.py",
|
||||
@@ -490,8 +490,8 @@
|
||||
},
|
||||
{
|
||||
"path": "backend/data/providers/tushare_dashboard.py",
|
||||
"bytes": 28051,
|
||||
"lines": 644
|
||||
"bytes": 28234,
|
||||
"lines": 648
|
||||
},
|
||||
{
|
||||
"path": "backend/data/providers/tushare_industries.py",
|
||||
@@ -505,8 +505,8 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/heaven/page.html",
|
||||
"bytes": 19747,
|
||||
"lines": 262
|
||||
"bytes": 19885,
|
||||
"lines": 269
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/screener/page.html",
|
||||
@@ -545,8 +545,8 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/admin.js",
|
||||
"bytes": 14145,
|
||||
"lines": 261
|
||||
"bytes": 14410,
|
||||
"lines": 268
|
||||
},
|
||||
{
|
||||
"path": "backend/features/heaven/market_context.py",
|
||||
@@ -555,8 +555,13 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/session.js",
|
||||
"bytes": 12848,
|
||||
"lines": 283
|
||||
"bytes": 13219,
|
||||
"lines": 289
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/dashboard.js",
|
||||
"bytes": 12894,
|
||||
"lines": 274
|
||||
},
|
||||
{
|
||||
"path": "backend/features/market/insights_auction_data.py",
|
||||
@@ -578,11 +583,6 @@
|
||||
"bytes": 10539,
|
||||
"lines": 244
|
||||
},
|
||||
{
|
||||
"path": "frontend/shared/dashboard.js",
|
||||
"bytes": 9993,
|
||||
"lines": 220
|
||||
},
|
||||
{
|
||||
"path": "backend/data/providers/tushare_sectors.py",
|
||||
"bytes": 9876,
|
||||
@@ -673,16 +673,16 @@
|
||||
"bytes": 5451,
|
||||
"lines": 118
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages.config.js",
|
||||
"bytes": 5385,
|
||||
"lines": 130
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/market/search.js",
|
||||
"bytes": 5384,
|
||||
"lines": 131
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages.config.js",
|
||||
"bytes": 5380,
|
||||
"lines": 130
|
||||
},
|
||||
{
|
||||
"path": "frontend/pages/auction/page.html",
|
||||
"bytes": 5350,
|
||||
@@ -773,6 +773,11 @@
|
||||
"bytes": 2299,
|
||||
"lines": 57
|
||||
},
|
||||
{
|
||||
"path": "backend/jobs/service.py",
|
||||
"bytes": 2219,
|
||||
"lines": 60
|
||||
},
|
||||
{
|
||||
"path": "backend/features/screener/regime.py",
|
||||
"bytes": 2202,
|
||||
@@ -804,9 +809,9 @@
|
||||
"lines": 45
|
||||
},
|
||||
{
|
||||
"path": "backend/jobs/service.py",
|
||||
"bytes": 1746,
|
||||
"lines": 49
|
||||
"path": "backend/features/system/routes.py",
|
||||
"bytes": 1791,
|
||||
"lines": 46
|
||||
},
|
||||
{
|
||||
"path": "backend/features/alerts/routes.py",
|
||||
@@ -833,11 +838,6 @@
|
||||
"bytes": 1455,
|
||||
"lines": 48
|
||||
},
|
||||
{
|
||||
"path": "backend/features/system/routes.py",
|
||||
"bytes": 1423,
|
||||
"lines": 40
|
||||
},
|
||||
{
|
||||
"path": "backend/features/themes/routes.py",
|
||||
"bytes": 1337,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# 行情历史补档(最近 60 个交易日)
|
||||
|
||||
用于修复 `dashboard_snapshots` 断档导致情绪周期 / 主题轮动 / 智能选股只剩当天的问题。
|
||||
保留 `latest_contiguous_history` 连续性规则;通过真实交易日历回补缺失交易日快照。
|
||||
|
||||
## 适用场景
|
||||
|
||||
- 库中已有稀疏历史快照,但最近一个真实交易日缺失,接口 `available_days=1`。
|
||||
- 需要可重复执行、可审计、可回退的补档,而不是迁库或放宽算法。
|
||||
|
||||
## 前置
|
||||
|
||||
1. 使用与线上一致的代码分支。
|
||||
2. 管理员账号已配置可用的公共 Tushare Token。
|
||||
3. 只操作目标环境自己的 `data/review.db`;禁止 `.36` 与 `.11` 互拷。
|
||||
|
||||
## 上线步骤(总工执行)
|
||||
|
||||
在目标环境容器内执行(应用根目录;宿主机也可直接跑,脚本已自带仓库根 `sys.path` 引导):
|
||||
|
||||
```bash
|
||||
# 1) 只读规划:区分已有、真正缺档;不会写入
|
||||
docker compose exec xiaobai-review python tools/backfill_recent_snapshots.py --account <管理员账号> --lookback 60 --dry-run --json
|
||||
|
||||
# 2) 正式补档:先走 SQLite backup API 写 data/backups/review-pre-recent-backfill-*.db
|
||||
# 再对缺失交易日调用现有 sync_dashboard
|
||||
docker compose exec xiaobai-review python tools/backfill_recent_snapshots.py --account <管理员账号> --lookback 60 --json
|
||||
|
||||
# 3) 验证
|
||||
# GET /api/sentiment/history?trade_date=YYYY-MM-DD&limit=60
|
||||
# 期望 available_days >= 20,且不再只有 1 天
|
||||
```
|
||||
|
||||
管理端日期区间回补(`/api/backfill`)已改为只处理交易日历中的开市日,周末/节假日会进入
|
||||
`skipped_non_trading_days`,不再当成错误;单次仍限制 15 个交易日。最近 60 日请用本工具。
|
||||
|
||||
## 写入边界
|
||||
|
||||
只会通过现有同步路径写入:
|
||||
|
||||
- `dashboard_snapshots`
|
||||
- 同步审计表 `sync_runs`
|
||||
- 必要时的 `data_snapshots`(仅当请求日被解析到其他交易日)
|
||||
|
||||
不得改动用户、Token、模型绑定或系统配置表。
|
||||
|
||||
## 回滚
|
||||
|
||||
1. 优先按审计结果的 `created_dates` 精确删除新增行:
|
||||
|
||||
```sql
|
||||
DELETE FROM dashboard_snapshots WHERE trade_date IN ('YYYYMMDD', ...);
|
||||
```
|
||||
|
||||
2. 若需整库回退,停止写入后用补档前备份覆盖:
|
||||
|
||||
```bash
|
||||
# 示例:把 data/backups/review-pre-recent-backfill-YYYYMMDD-HHMMSS.db
|
||||
# 复制回 data/review.db 后重启容器
|
||||
```
|
||||
|
||||
3. 代码回退:对该提交执行 Git revert 后重新部署镜像。
|
||||
|
||||
## 验收要点
|
||||
|
||||
- dry-run 与正式执行可重复跑;已有交易日默认跳过。
|
||||
- 周末、节假日出现在 `skipped_non_trading_days`,不计入失败。
|
||||
- 部分交易日同步失败时,其他日期仍会继续,并在审计结果中标 `failed`。
|
||||
- 情绪周期、主题轮动 9 列、智能选股置信度随连续交易日恢复。
|
||||
+7
-6
@@ -34,11 +34,11 @@
|
||||
document.documentElement.style.colorScheme = theme;
|
||||
})();
|
||||
</script>
|
||||
<link rel="stylesheet" href="/shared/tokens.css?v=20260829-1">
|
||||
<link rel="stylesheet" href="/shared/tokens.css?v=20260829-hel240">
|
||||
<link rel="stylesheet" href="/shared/base.css?v=20260806-1">
|
||||
<link rel="stylesheet" href="/shared/shell.css?v=20260820-8">
|
||||
<link rel="stylesheet" href="/shared/auth.css?v=20260829-1">
|
||||
<link rel="stylesheet" href="/shared/components/controls.css?v=20260820-2">
|
||||
<link rel="stylesheet" href="/shared/shell.css?v=20260829-hel237">
|
||||
<link rel="stylesheet" href="/shared/auth.css?v=20260829-hel240b">
|
||||
<link rel="stylesheet" href="/shared/components/controls.css?v=20260829-hel237">
|
||||
<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">
|
||||
@@ -54,8 +54,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=20260820-2">
|
||||
<link rel="stylesheet" href="/pages/heaven/foundation.css?v=20260806-2">
|
||||
<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/review/foundation.css?v=20260820-4">
|
||||
</head>
|
||||
<body>
|
||||
@@ -611,6 +611,7 @@
|
||||
<label class="form-field"><span>iFinD Refresh Token</span><input id="systemIfindTokenInput" type="password" autocomplete="off" maxlength="2048" placeholder="留空保留现有 Token"></label>
|
||||
<label class="switch-control"><input id="systemBackgroundRefresh" type="checkbox"><span>启用交易时段后台刷新</span></label>
|
||||
<p class="form-hint">所有用户读取同一份后台快照,页面不会随后台任务自动重绘。</p>
|
||||
<div id="adminRefreshStatus" class="admin-refresh-status" data-tone="idle" role="status" aria-live="polite"><i data-lucide="circle-dot"></i><span>尚未手动刷新</span></div>
|
||||
<div class="dialog-actions admin-inline-actions"><button id="adminRefreshButton" class="button" type="button"><i data-lucide="refresh-cw"></i>立即后台刷新</button><button class="button primary" type="submit">保存行情配置</button></div>
|
||||
</form>
|
||||
<section class="settings-section">
|
||||
|
||||
+61
-25
@@ -19,41 +19,77 @@
|
||||
document.documentElement.style.colorScheme = theme;
|
||||
})();
|
||||
</script>
|
||||
<link rel="stylesheet" href="/shared/tokens.css?v=20260829-1">
|
||||
<link rel="stylesheet" href="/shared/tokens.css?v=20260829-hel240">
|
||||
<link rel="stylesheet" href="/shared/base.css?v=20260806-1">
|
||||
<link rel="stylesheet" href="/shared/auth.css?v=20260829-1">
|
||||
<link rel="stylesheet" href="/shared/auth.css?v=20260829-hel243">
|
||||
<link rel="stylesheet" href="/shared/components/controls.css?v=20260820-2">
|
||||
</head>
|
||||
<body class="login-portal">
|
||||
<button id="loginThemeToggle" class="login-theme-toggle" type="button">🌙 夜间</button>
|
||||
<aside class="login-brand" aria-hidden="true">
|
||||
<div class="login-brand-mark"><span class="login-brand-glyph">复</span></div>
|
||||
<p class="login-brand-kicker">收盘之后 · 复盘开始</p>
|
||||
<h1 class="login-brand-title">小白复盘</h1>
|
||||
<p class="login-brand-lead">看懂情绪周期,把复盘变成下一次的先手。</p>
|
||||
<dl class="login-brand-stats">
|
||||
<div class="login-stat">
|
||||
<dt>市场情绪</dt>
|
||||
<dd>72 <span class="login-stat-tag">高热</span></dd>
|
||||
<div class="login-brand-header">
|
||||
<div class="login-brand-mark"><span class="login-brand-glyph">复</span></div>
|
||||
<div class="login-brand-identity">
|
||||
<p class="login-brand-name">小白复盘</p>
|
||||
<p class="login-brand-subtitle">A股个人复盘工作台</p>
|
||||
</div>
|
||||
<div class="login-stat">
|
||||
<dt>涨停</dt>
|
||||
<dd>63</dd>
|
||||
</div>
|
||||
<div class="login-stat">
|
||||
<dt>跌停</dt>
|
||||
<dd>4</dd>
|
||||
</div>
|
||||
<div class="login-stat">
|
||||
<dt>两市成交</dt>
|
||||
<dd>1.02万亿</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="login-brand-copy">
|
||||
<p class="login-brand-kicker">收盘之后 · 复盘开始</p>
|
||||
<h1 class="login-brand-title">看懂情绪周期,把复盘变成下一次的先手。</h1>
|
||||
<p class="login-brand-lead">情绪周期、涨停梯队、主题轮动、竞价、龙虎榜、人气榜、交易复盘,集中在一个安静的复盘空间。</p>
|
||||
</div>
|
||||
<div class="login-brand-market">
|
||||
<svg class="login-brand-chart" viewBox="0 0 480 168" focusable="false">
|
||||
<defs>
|
||||
<linearGradient id="loginChartFade" x1="0" x2="0" y1="0" y2="1">
|
||||
<stop offset="0%" stop-color="#d7e4ff" stop-opacity="0.18"></stop>
|
||||
<stop offset="100%" stop-color="#d7e4ff" stop-opacity="0"></stop>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path class="login-chart-area" d="M8 118 C 52 108, 78 96, 112 102 S 168 128, 204 112 S 268 78, 312 86 S 372 118, 428 92 L 472 84 L 472 168 L 8 168 Z"></path>
|
||||
<g class="login-candles">
|
||||
<g class="is-up" transform="translate(36 0)"><line x1="8" y1="58" x2="8" y2="128"></line><rect x="2" y="72" width="12" height="40"></rect></g>
|
||||
<g class="is-down" transform="translate(68 0)"><line x1="8" y1="64" x2="8" y2="132"></line><rect x="2" y="86" width="12" height="28"></rect></g>
|
||||
<g class="is-up" transform="translate(100 0)"><line x1="8" y1="48" x2="8" y2="118"></line><rect x="2" y="60" width="12" height="44"></rect></g>
|
||||
<g class="is-down" transform="translate(132 0)"><line x1="8" y1="70" x2="8" y2="136"></line><rect x="2" y="92" width="12" height="26"></rect></g>
|
||||
<g class="is-up" transform="translate(164 0)"><line x1="8" y1="42" x2="8" y2="110"></line><rect x="2" y="54" width="12" height="38"></rect></g>
|
||||
<g class="is-up" transform="translate(196 0)"><line x1="8" y1="36" x2="8" y2="98"></line><rect x="2" y="48" width="12" height="32"></rect></g>
|
||||
<g class="is-down" transform="translate(228 0)"><line x1="8" y1="58" x2="8" y2="128"></line><rect x="2" y="78" width="12" height="36"></rect></g>
|
||||
<g class="is-up" transform="translate(260 0)"><line x1="8" y1="40" x2="8" y2="104"></line><rect x="2" y="52" width="12" height="36"></rect></g>
|
||||
<g class="is-down" transform="translate(292 0)"><line x1="8" y1="66" x2="8" y2="134"></line><rect x="2" y="88" width="12" height="30"></rect></g>
|
||||
<g class="is-up" transform="translate(324 0)"><line x1="8" y1="44" x2="8" y2="112"></line><rect x="2" y="58" width="12" height="40"></rect></g>
|
||||
<g class="is-down" transform="translate(356 0)"><line x1="8" y1="72" x2="8" y2="138"></line><rect x="2" y="96" width="12" height="24"></rect></g>
|
||||
<g class="is-up" transform="translate(388 0)"><line x1="8" y1="38" x2="8" y2="108"></line><rect x="2" y="50" width="12" height="42"></rect></g>
|
||||
<g class="is-up" transform="translate(420 0)"><line x1="8" y1="32" x2="8" y2="96"></line><rect x="2" y="44" width="12" height="34"></rect></g>
|
||||
</g>
|
||||
<path class="login-chart-line" d="M8 118 C 52 108, 78 96, 112 102 S 168 128, 204 112 S 268 78, 312 86 S 372 118, 428 92 L 472 84"></path>
|
||||
</svg>
|
||||
<dl class="login-brand-stats">
|
||||
<div class="login-stat">
|
||||
<dt>市场情绪</dt>
|
||||
<dd>72 <span class="login-stat-tag">高热</span></dd>
|
||||
</div>
|
||||
<div class="login-stat">
|
||||
<dt>涨停</dt>
|
||||
<dd>63</dd>
|
||||
</div>
|
||||
<div class="login-stat">
|
||||
<dt>跌停</dt>
|
||||
<dd>4</dd>
|
||||
</div>
|
||||
<div class="login-stat login-stat-wide">
|
||||
<dt>两市成交</dt>
|
||||
<dd>1.02万亿</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
<p class="login-brand-disclaimer">股市有风险,投资需谨慎 · 本工具仅供个人复盘学习使用</p>
|
||||
</aside>
|
||||
<main class="login-stage">
|
||||
<button id="loginThemeToggle" class="login-theme-toggle" type="button">🌙 夜间</button>
|
||||
<section class="login-card" id="loginCard" aria-live="polite"></section>
|
||||
</main>
|
||||
<script src="/shared/api.js?v=20260803-2"></script>
|
||||
<script src="/login/page.js?v=20260829-1"></script>
|
||||
<script src="/login/page.js?v=20260829-hel243"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+115
-23
@@ -13,6 +13,8 @@
|
||||
loading: false,
|
||||
confirmingId: null,
|
||||
error: "",
|
||||
username: "",
|
||||
password: "",
|
||||
};
|
||||
|
||||
function escapeHtml(value) {
|
||||
@@ -52,48 +54,88 @@
|
||||
state.error = message || "";
|
||||
}
|
||||
|
||||
function membershipLabel(account) {
|
||||
if (account.role === "admin") return account.membership?.subscribed ? "管理员 · 会员" : "管理员";
|
||||
return account.membership?.subscribed ? "会员" : "普通用户";
|
||||
function formatLastUsed(value) {
|
||||
if (!value) return "";
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) return "";
|
||||
const now = new Date();
|
||||
const hh = String(parsed.getHours()).padStart(2, "0");
|
||||
const mm = String(parsed.getMinutes()).padStart(2, "0");
|
||||
if (parsed.toDateString() === now.toDateString()) return `今天 ${hh}:${mm}`;
|
||||
const yesterday = new Date(now);
|
||||
yesterday.setDate(now.getDate() - 1);
|
||||
if (parsed.toDateString() === yesterday.toDateString()) return `昨天 ${hh}:${mm}`;
|
||||
return `${parsed.getMonth() + 1}月${parsed.getDate()}日`;
|
||||
}
|
||||
|
||||
function chipsFor(account, current) {
|
||||
const chips = [];
|
||||
if (current) chips.push('<span class="login-chip login-chip-current">当前</span>');
|
||||
if (account.role === "admin") chips.push('<span class="login-chip">管理员</span>');
|
||||
if (account.membership?.subscribed) chips.push('<span class="login-chip login-chip-member">会员</span>');
|
||||
else if (account.role !== "admin") chips.push('<span class="login-chip">普通用户</span>');
|
||||
return chips.join("");
|
||||
}
|
||||
|
||||
function returnPath() {
|
||||
const raw = new URLSearchParams(global.location.search).get("next") || "";
|
||||
if (!raw) return "/";
|
||||
try {
|
||||
const url = new URL(raw, global.location.origin);
|
||||
if (url.origin !== global.location.origin) return "/";
|
||||
const path = url.pathname || "/";
|
||||
if (path === "/login" || path.startsWith("/login/")) return "/";
|
||||
return `${path}${url.search}${url.hash}` || "/";
|
||||
} catch (_error) {
|
||||
return "/";
|
||||
}
|
||||
}
|
||||
|
||||
function enterApp() {
|
||||
const next = new URLSearchParams(global.location.search).get("next");
|
||||
global.location.replace(next && next.startsWith("/") ? next : "/");
|
||||
global.location.replace(returnPath());
|
||||
}
|
||||
|
||||
function formMarkup(options) {
|
||||
const registering = state.mode === "register";
|
||||
const submitLabel = options.submitLabel
|
||||
|| (state.loading ? "正在登录..." : registering ? "注册并进入" : options.add ? "添加并进入" : "登录");
|
||||
const lead = options.lead;
|
||||
const hint = options.hint;
|
||||
const invalid = state.error ? " is-invalid" : "";
|
||||
return [
|
||||
options.back
|
||||
? '<button class="login-back" type="button" data-login-action="picker">返回账号列表</button>'
|
||||
: "",
|
||||
`<h2 class="login-card-title">${escapeHtml(options.title)}</h2>`,
|
||||
`<p class="login-card-lead">${escapeHtml(options.lead)}</p>`,
|
||||
`<p class="login-card-lead">${escapeHtml(lead)}</p>`,
|
||||
'<div class="login-tabs" role="tablist">',
|
||||
`<button class="login-tab${state.mode === "login" ? " is-active" : ""}" type="button" data-auth-mode="login">登录</button>`,
|
||||
`<button class="login-tab${state.mode === "register" ? " is-active" : ""}" type="button" data-auth-mode="register">注册</button>`,
|
||||
"</div>",
|
||||
'<form class="login-form" id="loginForm">',
|
||||
'<label class="form-field"><span>账号名</span><input id="loginUsername" type="text" minlength="3" maxlength="30" autocomplete="username" required></label>',
|
||||
`<label class="form-field"><span>密码</span><input id="loginPassword" type="password" minlength="8" maxlength="128" autocomplete="${registering ? "new-password" : "current-password"}" required></label>`,
|
||||
`<label class="form-field"><span>账号名</span><input id="loginUsername" type="text" minlength="3" maxlength="30" autocomplete="username" placeholder="请输入账号名" value="${escapeHtml(state.username)}" required></label>`,
|
||||
`<label class="form-field"><span>密码</span><input id="loginPassword" class="${invalid.trim()}" type="password" minlength="8" maxlength="128" autocomplete="${registering ? "new-password" : "current-password"}" placeholder="请输入密码" value="${escapeHtml(state.password)}" required></label>`,
|
||||
`<label class="form-field" id="loginConfirmField"${registering ? "" : " hidden"}><span>确认密码</span><input id="loginPasswordConfirm" type="password" minlength="8" maxlength="128" autocomplete="new-password"${registering ? " required" : ""}></label>`,
|
||||
state.error ? `<p class="login-error">${escapeHtml(state.error)}</p>` : '<p class="login-error" hidden></p>',
|
||||
`<button class="button primary login-submit" type="submit"${state.loading ? " disabled" : ""}>`,
|
||||
state.loading ? '<span class="login-spinner" aria-hidden="true"></span>' : "",
|
||||
`<span>${escapeHtml(submitLabel)}</span></button>`,
|
||||
"</form>",
|
||||
'<p class="login-hint">密码连续输错 5 次将锁定 10 分钟。还没有账号?切换到「注册」创建。</p>',
|
||||
`<p class="login-hint">${escapeHtml(hint)}</p>`,
|
||||
].join("");
|
||||
}
|
||||
|
||||
function accountRow(account) {
|
||||
const current = Number(account.user_id) === Number(state.currentUserId);
|
||||
const confirming = Number(state.confirmingId) === Number(account.user_id);
|
||||
const classes = `login-account-row${current ? " is-current" : ""}${confirming ? " is-confirming" : ""}`;
|
||||
if (state.view === "manage" && confirming) {
|
||||
const managing = state.view === "manage";
|
||||
const classes = [
|
||||
"login-account-row",
|
||||
current ? "is-current" : "",
|
||||
confirming ? "is-confirming" : "",
|
||||
!managing ? "is-switchable" : "",
|
||||
].filter(Boolean).join(" ");
|
||||
if (managing && confirming) {
|
||||
return [
|
||||
`<div class="${classes}" data-user-id="${account.user_id}">`,
|
||||
`<p class="login-confirm-copy">移除「${escapeHtml(account.username)}」的本机记录?</p>`,
|
||||
@@ -103,16 +145,25 @@
|
||||
"</div></div>",
|
||||
].join("");
|
||||
}
|
||||
const action = state.view === "manage"
|
||||
? `<button class="login-account-remove" type="button" data-confirm-id="${account.user_id}">移除</button>`
|
||||
const glyph = escapeHtml(String(account.username || "账").slice(0, 1));
|
||||
const tone = Number(account.user_id || 0) % 4;
|
||||
const used = formatLastUsed(account.last_used_at);
|
||||
const action = managing
|
||||
? `<button class="login-account-remove" type="button" data-confirm-id="${account.user_id}" aria-label="移除 ${escapeHtml(account.username)}"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M6 2h4l.5 1H14v1H2V3h3.5L6 2zm1 4v6H6V6h1zm3 0v6H9V6h1zM3.5 5H13l-.7 8.2A1.5 1.5 0 0 1 10.81 14H5.19a1.5 1.5 0 0 1-1.49-1.8L3.5 5z"></path></svg></button>`
|
||||
: current
|
||||
? '<span class="login-account-check" aria-hidden="true">✓</span>'
|
||||
: `<button class="login-account-enter" type="button" data-switch-id="${account.user_id}">进入</button>`;
|
||||
? '<span class="login-account-action"><span class="login-account-check" aria-hidden="true">✓</span>继续使用</span>'
|
||||
: "";
|
||||
const switchAttr = !managing && !current ? ` data-switch-id="${account.user_id}"` : "";
|
||||
const resumeAttr = !managing && current ? ` data-resume-id="${account.user_id}"` : "";
|
||||
return [
|
||||
`<div class="${classes}" data-user-id="${account.user_id}">`,
|
||||
`<div class="${classes}" data-user-id="${account.user_id}"${switchAttr}${resumeAttr}>`,
|
||||
`<span class="login-avatar tone-${tone}" aria-hidden="true">${glyph}</span>`,
|
||||
'<div class="login-account-meta">',
|
||||
'<div class="login-account-name">',
|
||||
`<strong>${escapeHtml(account.username)}</strong>`,
|
||||
`<span>${escapeHtml(membershipLabel(account))}${current ? " · 当前" : ""}</span>`,
|
||||
chipsFor(account, current),
|
||||
"</div>",
|
||||
used ? `<span class="login-account-used">上次登录 ${escapeHtml(used)}</span>` : "",
|
||||
"</div>",
|
||||
action,
|
||||
"</div>",
|
||||
@@ -123,10 +174,15 @@
|
||||
const count = state.accounts.length;
|
||||
const managing = state.view === "manage";
|
||||
return [
|
||||
`<h2 class="login-card-title">${managing ? "管理账号记录" : "选择账号"}</h2>`,
|
||||
`<p class="login-card-lead">这台电脑已记录 ${count} 个账号,可直接进入,无需再次输入密码。</p>`,
|
||||
managing
|
||||
? '<button class="login-manage" type="button" data-login-action="picker">完成</button>'
|
||||
? ""
|
||||
: '<button class="login-back" type="button" data-login-action="resume">返回复盘</button>',
|
||||
`<h2 class="login-card-title">${managing ? "管理账号记录" : "选择账号"}</h2>`,
|
||||
`<p class="login-card-lead">${managing
|
||||
? "移除只删除这台电脑上的登录记录,不会注销账号"
|
||||
: `这台电脑已记录 ${count} 个账号,点选即可进入,无需再次输入密码。`}</p>`,
|
||||
managing
|
||||
? '<div class="login-manage-toolbar"><p class="login-manage-hint">点击右侧图标移除对应记录</p><button class="login-manage-done" type="button" data-login-action="picker">完成</button></div>'
|
||||
: "",
|
||||
`<div class="login-account-list">${state.accounts.map(accountRow).join("")}</div>`,
|
||||
managing
|
||||
@@ -136,7 +192,9 @@
|
||||
? ""
|
||||
: '<button class="login-manage" type="button" data-login-action="manage">管理已记录的账号</button>',
|
||||
state.error ? `<p class="login-error">${escapeHtml(state.error)}</p>` : "",
|
||||
'<p class="login-privacy"><span class="login-lock" aria-hidden="true">🔒</span>账号记录仅保存在这台电脑的浏览器中</p>',
|
||||
managing
|
||||
? '<p class="login-privacy"><span class="login-lock" aria-hidden="true">🔒</span>移除后再次登录该账号需重新输入密码</p>'
|
||||
: '<p class="login-privacy"><span class="login-lock" aria-hidden="true">🔒</span>账号记录仅保存在这台电脑的浏览器中</p>',
|
||||
].join("");
|
||||
}
|
||||
|
||||
@@ -145,7 +203,10 @@
|
||||
if (state.view === "first" || state.view === "add") {
|
||||
card.innerHTML = formMarkup({
|
||||
title: state.view === "add" ? "添加账号" : "欢迎回来",
|
||||
lead: "登录后进入你的复盘空间",
|
||||
lead: state.view === "add" ? "登录另一个账号,添加后可随时一键切换" : "登录后进入你的复盘空间",
|
||||
hint: state.view === "add"
|
||||
? "添加后账号会保存在这台电脑,方便随时切换。"
|
||||
: "密码连续输错 5 次将锁定 10 分钟。还没有账号?切换到「注册」创建。",
|
||||
add: state.view === "add",
|
||||
back: state.view === "add",
|
||||
});
|
||||
@@ -166,6 +227,10 @@
|
||||
card.querySelectorAll("[data-login-action]").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
const action = button.dataset.loginAction;
|
||||
if (action === "resume") {
|
||||
resumeCurrentAccount();
|
||||
return;
|
||||
}
|
||||
if (action === "picker") {
|
||||
state.view = state.accounts.length ? "picker" : "first";
|
||||
state.confirmingId = null;
|
||||
@@ -184,8 +249,12 @@
|
||||
card.querySelectorAll("[data-switch-id]").forEach((button) => {
|
||||
button.addEventListener("click", () => switchAccount(Number(button.dataset.switchId)));
|
||||
});
|
||||
card.querySelectorAll("[data-resume-id]").forEach((button) => {
|
||||
button.addEventListener("click", () => resumeCurrentAccount());
|
||||
});
|
||||
card.querySelectorAll("[data-confirm-id]").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
button.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
state.confirmingId = Number(button.dataset.confirmId);
|
||||
render();
|
||||
});
|
||||
@@ -212,6 +281,8 @@
|
||||
event.preventDefault();
|
||||
const username = document.querySelector("#loginUsername").value.trim();
|
||||
const password = document.querySelector("#loginPassword").value;
|
||||
state.username = username;
|
||||
state.password = password;
|
||||
if (state.mode === "register" && password !== document.querySelector("#loginPasswordConfirm").value) {
|
||||
setError("两次输入的密码不一致。");
|
||||
render();
|
||||
@@ -244,6 +315,27 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function resumeCurrentAccount() {
|
||||
state.loading = true;
|
||||
setError("");
|
||||
render();
|
||||
try {
|
||||
const session = await api.request("/api/auth/me");
|
||||
const sessionUserId = session.user?.id;
|
||||
const matches = Boolean(session.authenticated) && (
|
||||
!state.currentUserId || Number(sessionUserId) === Number(state.currentUserId)
|
||||
);
|
||||
if (!matches) {
|
||||
throw new Error("当前会话已失效,请重新登录");
|
||||
}
|
||||
enterApp();
|
||||
} catch (error) {
|
||||
state.loading = false;
|
||||
setError(error.message || "当前会话已失效,请重新登录");
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
async function forgetAccount(userId) {
|
||||
try {
|
||||
await api.request("/api/auth/forget", "POST", { user_id: userId });
|
||||
|
||||
+415
-8
@@ -3192,8 +3192,7 @@
|
||||
.m-sys-grid div {
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
box-shadow: var(--elevation-card);
|
||||
background: var(--surface-muted);
|
||||
}
|
||||
|
||||
.m-sys-grid span {
|
||||
@@ -3209,16 +3208,424 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.m-sys-account-actions {
|
||||
display: grid;
|
||||
.m-sys-home {
|
||||
padding: 0 0 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.m-page[data-page^="system/"] .m-btn-primary {
|
||||
margin-bottom: 8px;
|
||||
.m-sys-body {
|
||||
padding: 12px 12px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.m-sys-home .m-card,
|
||||
.m-sys-body .m-card {
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
.m-sys-profile-card {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.m-sys-avatar {
|
||||
flex: 0 0 auto;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--action-soft);
|
||||
color: var(--action);
|
||||
font-size: var(--font-size-page-title);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.m-sys-profile-card strong {
|
||||
display: block;
|
||||
font-size: var(--font-size-card-title);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.m-sys-profile-meta {
|
||||
margin: 4px 0 8px;
|
||||
font-size: var(--font-size-caption);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.m-sys-badges {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.m-sys-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 22px;
|
||||
padding: 0 8px;
|
||||
border-radius: 999px;
|
||||
font-size: var(--font-size-aux);
|
||||
font-weight: 600;
|
||||
background: var(--surface-muted);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.m-sys-badge--admin {
|
||||
background: var(--action-soft);
|
||||
color: var(--action);
|
||||
}
|
||||
|
||||
.m-sys-badge--ok {
|
||||
background: var(--market-down-soft);
|
||||
color: var(--market-down);
|
||||
}
|
||||
|
||||
.m-sys-group-title {
|
||||
margin: 4px 0 0;
|
||||
font-size: var(--font-size-caption);
|
||||
font-weight: 600;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.m-sys-list {
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.m-sys-row {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 12px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
.m-sys-row + .m-sys-row {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.m-sys-row:active {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.m-sys-row-icon {
|
||||
flex: 0 0 auto;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--action-soft);
|
||||
color: var(--action);
|
||||
}
|
||||
|
||||
.m-sys-row--danger .m-sys-row-icon {
|
||||
background: var(--market-up-soft);
|
||||
color: var(--market-up);
|
||||
}
|
||||
|
||||
.m-sys-row-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.m-sys-row-body strong {
|
||||
display: block;
|
||||
font-size: var(--font-size-body);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.m-sys-row-body small {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
font-size: var(--font-size-caption);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.m-sys-row-chevron {
|
||||
flex: 0 0 auto;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.m-sys-foot {
|
||||
margin: 8px 0 0;
|
||||
text-align: center;
|
||||
font-size: var(--font-size-caption);
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.m-sys-notice {
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
background: var(--surface-muted);
|
||||
}
|
||||
|
||||
.m-sys-notice p {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-label);
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.m-sys-notice .m-sys-badges {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.m-sys-section {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.m-sys-section > strong,
|
||||
.m-sys-section-title {
|
||||
display: block;
|
||||
margin-bottom: 10px;
|
||||
font-size: var(--font-size-card-title);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.m-sys-hint {
|
||||
margin: 8px 0 0;
|
||||
font-size: var(--font-size-caption);
|
||||
color: var(--text-tertiary);
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.m-sys-status-list {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.m-sys-status-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: var(--font-size-body);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.m-sys-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.m-sys-dot--ok {
|
||||
background: var(--market-down);
|
||||
}
|
||||
|
||||
.m-sys-switch-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.m-sys-switch-row strong {
|
||||
display: block;
|
||||
font-size: var(--font-size-body);
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.m-btn-outline,
|
||||
.m-btn-outline-danger {
|
||||
width: 100%;
|
||||
height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
font-size: var(--font-size-body);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
.m-btn-outline {
|
||||
border: 1px solid var(--action);
|
||||
color: var(--action);
|
||||
}
|
||||
|
||||
.m-btn-outline:active {
|
||||
background: var(--action-soft);
|
||||
}
|
||||
|
||||
.m-btn-outline-danger {
|
||||
border: 1px solid var(--market-up);
|
||||
color: var(--market-up);
|
||||
}
|
||||
|
||||
.m-btn-outline-danger:active {
|
||||
background: var(--market-up-soft);
|
||||
}
|
||||
|
||||
.m-btn-outline:disabled,
|
||||
.m-btn-outline-danger:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.m-sys-model-card .m-sys-badges,
|
||||
.m-sys-user-row .m-sys-badges {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.m-sys-model-card {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.m-sys-model-card + .m-sys-model-card {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.m-sys-model-card:active {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.m-sys-user-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.m-sys-user-row + .m-sys-user-row {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.m-sys-user-row .m-btn-outline {
|
||||
width: auto;
|
||||
height: 32px;
|
||||
padding: 0 12px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.m-sys-pair {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.m-sheet-root.is-dialog .m-sheet {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.m-dialog {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 42%;
|
||||
width: calc(100% - 48px);
|
||||
max-width: 320px;
|
||||
transform: translate(-50%, -46%) scale(0.96);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
box-shadow: var(--elevation-float);
|
||||
padding: 18px 16px 14px;
|
||||
z-index: 3;
|
||||
opacity: 0;
|
||||
transition: opacity var(--motion-enter) var(--ease-enter),
|
||||
transform var(--motion-enter) var(--ease-enter);
|
||||
}
|
||||
|
||||
.m-sheet-root.is-open .m-dialog {
|
||||
opacity: 1;
|
||||
transform: translate(-50%, -50%) scale(1);
|
||||
}
|
||||
|
||||
.m-dialog h2 {
|
||||
margin: 0 0 8px;
|
||||
font-size: var(--font-size-card-title);
|
||||
color: var(--text-primary);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.m-dialog p {
|
||||
margin: 0 0 16px;
|
||||
font-size: var(--font-size-label);
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.m-dialog-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.m-dialog-actions .m-btn-outline,
|
||||
.m-dialog-actions .m-btn-outline-danger,
|
||||
.m-dialog-actions .m-btn-primary {
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.m-sys-sheet-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.m-sys-test-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 8px 0 12px;
|
||||
}
|
||||
|
||||
.m-sys-test-row .m-btn-outline {
|
||||
width: auto;
|
||||
flex: 0 0 auto;
|
||||
height: 36px;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
.m-sys-test-row [data-model-test-status] {
|
||||
flex: 1;
|
||||
font-size: var(--font-size-caption);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.m-sys-hero {
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.m-sys-hero strong {
|
||||
display: block;
|
||||
font-size: var(--font-size-page-title);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.m-page[data-page^="system/"] .m-card {
|
||||
margin-bottom: 12px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
+504
-159
@@ -91,6 +91,14 @@
|
||||
"sticky-note": '<path d="M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z"/><path d="M15 3v4a2 2 0 0 0 2 2h4"/>',
|
||||
bell: '<path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/>',
|
||||
lock: '<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>',
|
||||
user: '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',
|
||||
gem: '<path d="M6 3h12l4 6-10 13L2 9Z"/><path d="M11 3 8 9l4 13 4-13-3-6"/><path d="M2 9h20"/>',
|
||||
users: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
|
||||
"sliders-horizontal": '<line x1="21" x2="14" y1="4" y2="4"/><line x1="10" x2="3" y1="4" y2="4"/><line x1="21" x2="12" y1="12" y2="12"/><line x1="8" x2="3" y1="12" y2="12"/><line x1="21" x2="16" y1="20" y2="20"/><line x1="12" x2="3" y1="20" y2="20"/><line x1="14" x2="14" y1="2" y2="6"/><line x1="8" x2="8" y1="10" y2="14"/><line x1="16" x2="16" y1="18" y2="22"/>',
|
||||
sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>',
|
||||
moon: '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>',
|
||||
"arrow-left-right": '<path d="M8 3 4 7l4 4"/><path d="M4 7h16"/><path d="m16 21 4-4-4-4"/><path d="M20 17H4"/>',
|
||||
"log-out": '<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" x2="9" y1="12" y2="12"/>',
|
||||
};
|
||||
|
||||
function icon(name, size) {
|
||||
@@ -191,6 +199,10 @@
|
||||
account: null,
|
||||
admin: null,
|
||||
adminTab: "market",
|
||||
models: [],
|
||||
accounts: [],
|
||||
editingModelId: "",
|
||||
editingUserId: "",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1594,11 +1606,43 @@
|
||||
|
||||
/* ---------------------------------------------------------------- helpers shared by new pages */
|
||||
|
||||
function bindConfirmAction(onConfirm) {
|
||||
const ok = document.querySelector("[data-confirm-ok]");
|
||||
if (ok && typeof onConfirm === "function") {
|
||||
ok.addEventListener("click", function () {
|
||||
closeSheet();
|
||||
onConfirm();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function openCenteredDialog(content) {
|
||||
const root = ensureSheetRoot();
|
||||
sheetToken += 1;
|
||||
root.classList.add("is-dialog");
|
||||
root.innerHTML =
|
||||
'<div class="m-sheet-backdrop" data-sheet-backdrop></div>' +
|
||||
'<div class="m-dialog" role="dialog" aria-modal="true">' + content + "</div>";
|
||||
global.requestAnimationFrame(function () { root.classList.add("is-open"); });
|
||||
}
|
||||
|
||||
function openConfirmSheet(title, body, options) {
|
||||
const opts = options || {};
|
||||
const confirmLabel = opts.confirmLabel || "确定";
|
||||
const cancelLabel = opts.cancelLabel || "取消";
|
||||
const danger = Boolean(opts.danger);
|
||||
if (opts.centered) {
|
||||
openCenteredDialog(
|
||||
"<h2>" + escapeHtml(title) + "</h2>" +
|
||||
(body ? "<p>" + escapeHtml(body) + "</p>" : "") +
|
||||
'<div class="m-dialog-actions">' +
|
||||
'<button class="m-btn-outline" type="button" data-sheet-close>' + escapeHtml(cancelLabel) + "</button>" +
|
||||
'<button class="' + (danger ? "m-btn-outline-danger" : "m-btn-primary") + '" type="button" data-confirm-ok>' + escapeHtml(confirmLabel) + "</button>" +
|
||||
"</div>"
|
||||
);
|
||||
bindConfirmAction(opts.onConfirm);
|
||||
return;
|
||||
}
|
||||
openSheet(
|
||||
'<div class="m-sheet-head"><h2>' + escapeHtml(title) + '</h2>' +
|
||||
'<button class="m-sheet-close" type="button" data-sheet-close aria-label="关闭">' + icon("close", 20) + '</button></div>' +
|
||||
@@ -1610,13 +1654,7 @@
|
||||
'</div></div>',
|
||||
{ detail: false }
|
||||
);
|
||||
const ok = document.querySelector('[data-confirm-ok]');
|
||||
if (ok && typeof opts.onConfirm === 'function') {
|
||||
ok.addEventListener('click', function () {
|
||||
closeSheet();
|
||||
opts.onConfirm();
|
||||
});
|
||||
}
|
||||
bindConfirmAction(opts.onConfirm);
|
||||
}
|
||||
|
||||
function nextSeq() {
|
||||
@@ -3123,6 +3161,7 @@
|
||||
function openSheet(content, opts) {
|
||||
const root = ensureSheetRoot();
|
||||
sheetToken += 1;
|
||||
root.classList.remove("is-dialog");
|
||||
root.innerHTML =
|
||||
'<div class="m-sheet-backdrop" data-sheet-backdrop></div>' +
|
||||
'<div class="m-sheet' + (opts && opts.detail ? " m-sheet--detail" : "") + '" role="dialog" aria-modal="true">' +
|
||||
@@ -3138,12 +3177,16 @@
|
||||
if (!root) return;
|
||||
const token = sheetToken;
|
||||
root.classList.remove("is-open");
|
||||
root.classList.remove("is-dialog");
|
||||
global.setTimeout(function () {
|
||||
if (sheetToken === token && !root.classList.contains("is-open")) root.innerHTML = "";
|
||||
if (sheetToken === token && !root.classList.contains("is-open")) {
|
||||
root.innerHTML = "";
|
||||
}
|
||||
}, 340);
|
||||
}
|
||||
|
||||
function bindSheetDrag(root) {
|
||||
if (root.classList.contains("is-dialog")) return;
|
||||
const sheet = root.querySelector(".m-sheet");
|
||||
const backdrop = root.querySelector(".m-sheet-backdrop");
|
||||
const handle = root.querySelector(".m-sheet-handle");
|
||||
@@ -4863,7 +4906,7 @@
|
||||
return '<table class="m-table"><thead><tr>' + head + "</tr></thead><tbody>" + body + "</tbody></table>";
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 系统管理(恢复桌面端已有能力,禁止再走占位页) */
|
||||
/* ---------------------------------------------------------------- 系统管理(HEL-238 按确认样图重排) */
|
||||
|
||||
function isSystemPage(key) {
|
||||
return String(key || state.key || "").indexOf("system/") === 0;
|
||||
@@ -4889,13 +4932,27 @@
|
||||
return new Intl.DateTimeFormat("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" }).format(parsed);
|
||||
}
|
||||
|
||||
function currentUser() {
|
||||
return global.MobileSession && global.MobileSession.state ? global.MobileSession.state.user : null;
|
||||
}
|
||||
|
||||
function currentUsername() {
|
||||
const user = currentUser();
|
||||
return user && user.username ? user.username : "当前账号";
|
||||
}
|
||||
|
||||
function currentMembership() {
|
||||
const user = currentUser();
|
||||
return (user && user.membership) || {};
|
||||
}
|
||||
|
||||
function setupSystemPage(key) {
|
||||
state.key = key;
|
||||
state.requestedDate = todayString();
|
||||
state.sort = { key: "", dir: null };
|
||||
state.sortTable = { cols: null, reapply: null };
|
||||
state.detail = null;
|
||||
if (key === "system/admin") state.system.adminTab = "market";
|
||||
if (key === "system/admin") state.system.adminTab = state.system.adminTab || "market";
|
||||
document.getElementById("m-view").classList.add("m-view-feature");
|
||||
global.MobileRouter.updateHeader({ title: findLabel(key) || key, back: true, actions: "" });
|
||||
document.getElementById("m-view").innerHTML = complexFrame(key, complexScroll(skeletonHtml(6)));
|
||||
@@ -4917,6 +4974,9 @@
|
||||
if (seq !== state.seq || state.key !== key) return;
|
||||
if (key === "system/admin" || key === "system/members") {
|
||||
state.system.admin = payload || {};
|
||||
state.system.models = ((payload.llm && payload.llm.models) || []).map(function (item) {
|
||||
return Object.assign({}, item);
|
||||
});
|
||||
renderSystemAdmin(key);
|
||||
} else {
|
||||
state.system.account = payload || {};
|
||||
@@ -4929,9 +4989,115 @@
|
||||
});
|
||||
}
|
||||
|
||||
function currentUsername() {
|
||||
const user = global.MobileSession && global.MobileSession.state ? global.MobileSession.state.user : null;
|
||||
return user && user.username ? user.username : "当前账号";
|
||||
function formatLastUsed(value) {
|
||||
if (!value) return "";
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) return "";
|
||||
const now = new Date();
|
||||
const hh = String(parsed.getHours()).padStart(2, "0");
|
||||
const mm = String(parsed.getMinutes()).padStart(2, "0");
|
||||
const sameDay = parsed.toDateString() === now.toDateString();
|
||||
const yesterday = new Date(now);
|
||||
yesterday.setDate(now.getDate() - 1);
|
||||
if (sameDay) return "今天 " + hh + ":" + mm;
|
||||
if (parsed.toDateString() === yesterday.toDateString()) return "昨天 " + hh + ":" + mm;
|
||||
return membershipDateLabel(value) + " " + hh + ":" + mm;
|
||||
}
|
||||
|
||||
function systemRowHtml(item) {
|
||||
return '<button class="m-sys-row" type="button" data-route="#/feature/' + item.key + '">' +
|
||||
'<span class="m-sys-row-icon">' + icon(item.icon, 18) + "</span>" +
|
||||
'<span class="m-sys-row-body"><strong>' + escapeHtml(item.label) + "</strong><small>" + escapeHtml(item.hint) + "</small></span>" +
|
||||
'<span class="m-sys-row-chevron">' + icon("chevron-right", 16) + "</span>" +
|
||||
"</button>";
|
||||
}
|
||||
|
||||
function systemThemeRowHtml() {
|
||||
const dark = document.getElementById("m-app") && document.getElementById("m-app").dataset.theme === "dark";
|
||||
return '<div class="m-sys-row" data-theme-row>' +
|
||||
'<span class="m-sys-row-icon" data-theme-row-icon>' + icon(dark ? "moon" : "sun", 18) + "</span>" +
|
||||
'<span class="m-sys-row-body"><strong>外观主题</strong><small data-theme-row-label>' + (dark ? "当前:夜间模式" : "当前:日间模式") + "</small></span>" +
|
||||
'<button class="m-theme-switch" type="button" data-theme-toggle role="switch" aria-checked="' + (dark ? "true" : "false") + '" aria-label="切换日间/夜间模式"><span class="m-theme-switch-thumb"></span></button>' +
|
||||
"</div>";
|
||||
}
|
||||
|
||||
function renderSystemHome() {
|
||||
state.key = "system";
|
||||
document.getElementById("m-view").classList.remove("m-view-feature");
|
||||
global.MobileRouter.updateHeader({ title: "系统管理", back: false, actions: "" });
|
||||
const view = document.getElementById("m-view");
|
||||
view.innerHTML = '<div class="m-sys-home" data-system-page="home">' + skeletonHtml(4) + "</div>";
|
||||
const seq = nextSeq();
|
||||
Promise.all([
|
||||
global.MobileAPI.request("/api/account/status").catch(function () { return {}; }),
|
||||
global.MobileSession.listAccounts().catch(function () { return { accounts: [] }; })
|
||||
]).then(function (results) {
|
||||
if (seq !== state.seq || state.key !== "system") return;
|
||||
state.system.account = results[0] || {};
|
||||
state.system.accounts = (results[1] && results[1].accounts) || [];
|
||||
paintSystemHome();
|
||||
});
|
||||
}
|
||||
|
||||
function paintSystemHome() {
|
||||
const user = currentUser() || {};
|
||||
const membership = currentMembership();
|
||||
const account = state.system.account || {};
|
||||
const access = account.llm_access || {};
|
||||
const status = access.membership || membership;
|
||||
const username = user.username || currentUsername();
|
||||
const avatar = String(username).slice(0, 1);
|
||||
const remembered = (state.system.accounts || []).some(function (item) {
|
||||
return String(item.user_id) === String(user.id);
|
||||
});
|
||||
const currentGrant = (state.system.accounts || []).find(function (item) {
|
||||
return String(item.user_id) === String(user.id);
|
||||
});
|
||||
const lastUsed = formatLastUsed(currentGrant && currentGrant.last_used_at);
|
||||
const metaParts = [];
|
||||
if (lastUsed) metaParts.push("上次登录:" + lastUsed);
|
||||
if (remembered) metaParts.push("本机已记住");
|
||||
const badges = [];
|
||||
if (global.MobileSession.isAdmin()) badges.push('<span class="m-sys-badge m-sys-badge--admin">管理员</span>');
|
||||
if (status.subscribed) badges.push('<span class="m-sys-badge m-sys-badge--ok">会员有效</span>');
|
||||
else if (!global.MobileSession.isAdmin()) badges.push('<span class="m-sys-badge">普通用户</span>');
|
||||
const accountRows = [
|
||||
{ key: "system/profile", icon: "user", label: "账号资料", hint: "出生信息 · 加密保存" },
|
||||
{ key: "system/password", icon: "lock", label: "修改密码", hint: "建议定期更换" },
|
||||
{ key: "system/membership", icon: "gem", label: "会员状态", hint: "有效期与智能分析额度" }
|
||||
];
|
||||
const adminRows = [
|
||||
{ key: "system/admin", icon: "sliders-horizontal", label: "系统设置", hint: "行情数据 · 模型池" },
|
||||
{ key: "system/members", icon: "users", label: "会员管理", hint: "开通 · 续期 · 额度" }
|
||||
];
|
||||
const html =
|
||||
'<div class="m-sys-home" data-system-page="home">' +
|
||||
'<div class="m-card m-sys-profile-card"><span class="m-sys-avatar">' + escapeHtml(avatar) + "</span><div>" +
|
||||
"<strong>" + escapeHtml(username) + "</strong>" +
|
||||
(metaParts.length ? '<p class="m-sys-profile-meta">' + escapeHtml(metaParts.join(" · ")) + "</p>" : "") +
|
||||
(badges.length ? '<div class="m-sys-badges">' + badges.join("") + "</div>" : "") +
|
||||
"</div></div>" +
|
||||
'<h3 class="m-sys-group-title">账号</h3>' +
|
||||
'<div class="m-card m-sys-list">' + accountRows.map(systemRowHtml).join("") + "</div>" +
|
||||
'<h3 class="m-sys-group-title">偏好</h3>' +
|
||||
'<div class="m-card m-sys-list">' + systemThemeRowHtml() + "</div>" +
|
||||
(global.MobileSession.isAdmin()
|
||||
? '<h3 class="m-sys-group-title">管理员专区</h3><div class="m-card m-sys-list">' + adminRows.map(systemRowHtml).join("") + "</div>"
|
||||
: "") +
|
||||
'<h3 class="m-sys-group-title">其他</h3>' +
|
||||
'<div class="m-card m-sys-list">' +
|
||||
'<button class="m-sys-row" type="button" data-system-switch>' +
|
||||
'<span class="m-sys-row-icon">' + icon("arrow-left-right", 18) + "</span>" +
|
||||
'<span class="m-sys-row-body"><strong>切换账号</strong><small>本机免密进入其他账号</small></span>' +
|
||||
'<span class="m-sys-row-chevron">' + icon("chevron-right", 16) + "</span></button>" +
|
||||
'<button class="m-sys-row m-sys-row--danger" type="button" data-system-logout>' +
|
||||
'<span class="m-sys-row-icon">' + icon("log-out", 18) + "</span>" +
|
||||
'<span class="m-sys-row-body"><strong>退出登录</strong><small>退出后需要重新登录</small></span>' +
|
||||
'<span class="m-sys-row-chevron">' + icon("chevron-right", 16) + "</span></button>" +
|
||||
"</div>" +
|
||||
'<p class="m-sys-foot">' + (global.MobileSession.isAdmin() ? "小白复盘 · 内网个人版" : "系统设置与会员管理仅管理员可见") + "</p>" +
|
||||
"</div>";
|
||||
document.getElementById("m-view").innerHTML = html;
|
||||
}
|
||||
|
||||
function renderSystemProfile() {
|
||||
@@ -4947,9 +5113,10 @@
|
||||
const gender = birth.gender || "unspecified";
|
||||
const configured = Boolean(payload.birth_profile_configured);
|
||||
const html =
|
||||
'<div class="m-form-body" data-system-page="profile">' +
|
||||
'<div class="m-card"><strong>' + escapeHtml(currentUsername()) + "</strong><p class=\"m-sys-lead\">出生信息仅对当前账号可见并加密保存。</p></div>" +
|
||||
'<p class="m-sys-lead">原始信息加密保存且不在观气页回显;智能解读只使用排盘后的派生结果。</p>' +
|
||||
'<div class="m-sys-body" data-system-page="profile">' +
|
||||
'<div class="m-sys-notice"><p>出生信息仅对当前账号可见并加密保存。原始信息不会在观气页回显,智能解读只使用排盘后的派生结果。</p>' +
|
||||
'<div class="m-sys-badges"><span class="m-sys-badge ' + (configured ? "m-sys-badge--ok" : "") + '">' + (configured ? "已加密保存" : "尚未设置") + "</span></div></div>" +
|
||||
'<div class="m-card m-sys-section"><strong>命理资料</strong>' +
|
||||
formFieldHtml("出生日期", dateInputHtml("m-sys-birth-date", birthDate), true) +
|
||||
formFieldHtml("出生时间", '<input id="m-sys-birth-time" type="time" value="' + escapeHtml(birthTime) + '">', true) +
|
||||
formFieldHtml("性别", '<select id="m-sys-birth-gender">' +
|
||||
@@ -4957,12 +5124,10 @@
|
||||
'<option value="male"' + (gender === "male" ? " selected" : "") + ">男</option>" +
|
||||
'<option value="female"' + (gender === "female" ? " selected" : "") + ">女</option>" +
|
||||
"</select>", false) +
|
||||
'<p class="m-sys-lead">资料状态:' + (configured ? "已加密保存" : "尚未设置") + "</p>" +
|
||||
'<button class="m-btn-primary m-btn-danger" type="button" data-system-delete-birth' + (configured ? "" : " disabled") + ">删除资料</button>" +
|
||||
'<div class="m-card m-sys-account-actions">' +
|
||||
'<button class="m-btn-primary" type="button" data-system-switch>切换账号</button>' +
|
||||
'<button class="m-btn-primary m-btn-danger" type="button" data-system-logout>退出当前账号</button>' +
|
||||
"</div></div>";
|
||||
"</div>" +
|
||||
'<button class="m-btn-outline-danger" type="button" data-system-delete-birth' + (configured ? "" : " disabled") + ">删除命理资料</button>" +
|
||||
'<p class="m-sys-hint">删除后智能解读将无法使用出生信息,执行前会再次确认。</p>' +
|
||||
"</div>";
|
||||
const page = document.querySelector(".m-page");
|
||||
if (page) {
|
||||
page.innerHTML = '<div class="m-scroll" id="m-scroll">' + html + "</div>" +
|
||||
@@ -4972,17 +5137,16 @@
|
||||
|
||||
function renderSystemPassword() {
|
||||
const html =
|
||||
'<div class="m-form-body" data-system-page="password">' +
|
||||
'<p class="m-sys-lead">仅修改当前账号密码,不会保存在这台设备上。</p>' +
|
||||
formFieldHtml("当前密码", '<input id="m-sys-password-current" type="password" autocomplete="current-password">', true) +
|
||||
formFieldHtml("新密码", '<input id="m-sys-password-new" type="password" minlength="8" maxlength="128" autocomplete="new-password">', true) +
|
||||
formFieldHtml("确认新密码", '<input id="m-sys-password-confirm" type="password" minlength="8" maxlength="128" autocomplete="new-password">', true) +
|
||||
"</div>";
|
||||
'<div class="m-sys-body" data-system-page="password">' +
|
||||
'<div class="m-sys-notice"><p>仅修改当前账号的登录密码,密码不会保存在这台设备上。修改成功后下次登录需使用新密码。</p></div>' +
|
||||
'<div class="m-card m-sys-section"><strong>设置新密码</strong>' +
|
||||
formFieldHtml("当前密码", '<input id="m-sys-password-current" type="password" autocomplete="current-password" placeholder="输入现在的密码">', true, '<p class="m-field-error" hidden data-field-error="current"></p>') +
|
||||
formFieldHtml("新密码", '<input id="m-sys-password-new" type="password" minlength="8" maxlength="128" autocomplete="new-password" placeholder="8-128 位">', true, '<p class="m-sys-hint">建议字母与数字混合,不要与其他网站重复。</p><p class="m-field-error" hidden data-field-error="new"></p>') +
|
||||
formFieldHtml("确认新密码", '<input id="m-sys-password-confirm" type="password" minlength="8" maxlength="128" autocomplete="new-password" placeholder="再输入一次新密码">', true, '<p class="m-field-error" hidden data-field-error="confirm"></p>') +
|
||||
'<button class="m-btn-primary" type="button" data-system-save-password>更新密码</button>' +
|
||||
"</div></div>";
|
||||
const page = document.querySelector(".m-page");
|
||||
if (page) {
|
||||
page.innerHTML = '<div class="m-scroll" id="m-scroll">' + html + "</div>" +
|
||||
'<div class="m-form-bar"><button class="m-btn-primary" type="button" data-system-save-password>更新密码</button></div>';
|
||||
}
|
||||
if (page) page.innerHTML = '<div class="m-scroll" id="m-scroll">' + html + "</div>";
|
||||
}
|
||||
|
||||
function renderSystemMembership() {
|
||||
@@ -4995,25 +5159,28 @@
|
||||
? number(membership.remaining_days) + " 天"
|
||||
: (membership.is_admin || membership.subscribed ? "长期有效" : "--");
|
||||
const detail = membership.subscribed
|
||||
? ((membership.plan || "会员") + (membership.expires_at ? " · 有效至 " + membershipDateLabel(membership.expires_at) : " · 长期有效"))
|
||||
? ((membership.plan || "会员") + (membership.expires_at ? " · 有效至 " + membershipDateLabel(membership.expires_at) : " · 长期有效") + (membership.remaining_days != null ? ",剩余 " + number(membership.remaining_days) + " 天。" : "。"))
|
||||
: membership.is_admin
|
||||
? "管理员拥有智能功能管理权限,但不会因此显示为已开通会员。"
|
||||
: "开通会员后可使用智能选股、问师、问天、复盘助手等智能功能。";
|
||||
const quota = "会员默认每日智能分析额度 " + number(access.daily_limit) + " 次,由管理员统一设置。";
|
||||
const usage = membership.active ? ("今日已用 " + number(access.used_today) + " 次") : "今日智能分析:--";
|
||||
const usageSummary = membership.active ? (number(access.used_today) + " / " + number(access.daily_limit)) : "--";
|
||||
const usedToday = membership.active ? (number(access.used_today) + " 次") : "--";
|
||||
const remainingCalls = membership.is_admin ? "不限" : membership.active ? (number(access.remaining_calls) + " 次") : "--";
|
||||
const html =
|
||||
'<div class="m-form-body" data-system-page="membership">' +
|
||||
'<div class="m-card"><strong>' + escapeHtml(badge) + "</strong><p class=\"m-sys-lead\">" + escapeHtml(detail) + "</p><p class=\"m-sys-lead\">" + escapeHtml(quota) + "</p></div>" +
|
||||
'<div class="m-sys-body" data-system-page="membership">' +
|
||||
'<div class="m-card m-sys-hero"><strong>' + escapeHtml(badge) + '</strong>' +
|
||||
(membership.subscribed ? '<div class="m-sys-badges"><span class="m-sys-badge m-sys-badge--ok">已开通</span></div>' : "") +
|
||||
'<p class="m-sys-lead">' + escapeHtml(detail) + "</p></div>" +
|
||||
'<div class="m-card m-sys-section"><strong>今日智能分析</strong>' +
|
||||
'<div class="m-sys-grid">' +
|
||||
"<div><span>开通状态</span><strong>" + escapeHtml(stateLabel) + "</strong></div>" +
|
||||
"<div><span>剩余时长</span><strong>" + escapeHtml(remaining) + "</strong></div>" +
|
||||
"<div><span>今日智能分析</span><strong>" + escapeHtml(usageSummary) + "</strong></div>" +
|
||||
"<div><span>剩余智能分析</span><strong>" + escapeHtml(remainingCalls) + "</strong></div>" +
|
||||
"<div><span>今日已用</span><strong>" + escapeHtml(usedToday) + "</strong></div>" +
|
||||
"<div><span>今日剩余</span><strong>" + escapeHtml(remainingCalls) + "</strong></div>" +
|
||||
"</div>" +
|
||||
'<div class="m-card"><p class="m-sys-lead">' + escapeHtml(usage) + "</p>" +
|
||||
'<p class="m-sys-lead">行情、搜索、自选与复盘:普通用户可用。智能选股、问师、问天、复盘助手:仅会员可用。</p></div>' +
|
||||
'<p class="m-sys-hint">会员每日智能分析额度 ' + number(access.daily_limit) + " 次,每日 0 点自动重置,由管理员统一设置。</p></div>" +
|
||||
'<div class="m-card m-sys-section"><strong>权益说明</strong>' +
|
||||
'<p class="m-sys-lead">全部用户可用:行情、搜索、自选股、交易日志与复盘。</p>' +
|
||||
'<p class="m-sys-lead">会员专属:智能选股、问师、问天、复盘助手等智能功能。</p></div>' +
|
||||
"</div>";
|
||||
systemFill(html);
|
||||
}
|
||||
@@ -5026,6 +5193,10 @@
|
||||
"</div>";
|
||||
}
|
||||
|
||||
function statusDot(ok) {
|
||||
return '<span class="m-sys-dot' + (ok ? " m-sys-dot--ok" : "") + '"></span>';
|
||||
}
|
||||
|
||||
function renderSystemAdmin(key) {
|
||||
if (key === "system/members") {
|
||||
renderSystemMembers();
|
||||
@@ -5035,74 +5206,86 @@
|
||||
const data = payload.data || {};
|
||||
const ifind = data.ifind || {};
|
||||
const llm = payload.llm || {};
|
||||
const status = "Tushare " + (data.configured ? "已配置" : "未配置") +
|
||||
" · iFinD " + (ifind.configured ? "已配置" : "未配置") +
|
||||
" · " + number(data.snapshot_dates) + " 个交易日";
|
||||
const refreshLabel = data.background_refresh_enabled ? "后台刷新已启用" : "后台刷新已暂停";
|
||||
const tab = state.system.adminTab === "models" ? "models" : "market";
|
||||
const marketHtml =
|
||||
'<div class="m-form-body" data-system-admin-panel="market">' +
|
||||
'<div class="m-card"><strong>公共行情</strong><p class="m-sys-lead">' + escapeHtml(status) + "</p><p class=\"m-sys-lead\">" + escapeHtml(refreshLabel) + "</p></div>" +
|
||||
formFieldHtml("Tushare Token", '<input id="m-sys-token" type="password" autocomplete="off" minlength="20" placeholder="留空保留现有 Token">', false) +
|
||||
formFieldHtml("iFinD Refresh Token", '<input id="m-sys-ifind" type="password" autocomplete="off" maxlength="2048" placeholder="留空保留现有 Token">', false) +
|
||||
formFieldHtml("交易时段后台刷新", '<input id="m-sys-bg-refresh" type="checkbox"' + (data.background_refresh_enabled ? " checked" : "") + ">", false) +
|
||||
'<p class="m-sys-lead">所有用户读取同一份后台快照,页面不会随后台任务自动重绘。</p>' +
|
||||
'<button class="m-btn-primary" type="button" data-system-refresh>立即后台刷新</button>' +
|
||||
'<div class="m-card"><strong>历史数据回补</strong></div>' +
|
||||
'<div class="m-sys-body" data-system-admin-panel="market">' +
|
||||
'<div class="m-card m-sys-section"><strong>数据源状态</strong>' +
|
||||
'<div class="m-sys-status-list">' +
|
||||
'<div class="m-sys-status-item"><span>Tushare</span><span>' + statusDot(data.configured) + (data.configured ? " 已配置" : " 未配置") + "</span></div>" +
|
||||
'<div class="m-sys-status-item"><span>iFinD</span><span>' + statusDot(ifind.configured) + (ifind.configured ? " 已配置" : " 未配置") + "</span></div>" +
|
||||
'<div class="m-sys-status-item"><span>行情快照</span><strong>' + number(data.snapshot_dates) + " 个交易日</strong></div>" +
|
||||
'<div class="m-sys-status-item"><span>后台刷新</span><span>' + statusDot(data.background_refresh_enabled) + (data.background_refresh_enabled ? " 已启用" : " 已暂停") + "</span></div>" +
|
||||
"</div></div>" +
|
||||
'<div class="m-card m-sys-section"><strong>数据源密钥</strong>' +
|
||||
formFieldHtml("Tushare Token", '<input id="m-sys-token" type="password" autocomplete="off" minlength="20" placeholder="留空则保留现有 Token">', false) +
|
||||
formFieldHtml("iFinD Refresh Token", '<input id="m-sys-ifind" type="password" autocomplete="off" maxlength="2048" placeholder="留空则保留现有 Token">', false) +
|
||||
'<button class="m-btn-primary" type="button" data-system-save-market>保存密钥</button></div>' +
|
||||
'<div class="m-card m-sys-section"><strong>后台刷新</strong>' +
|
||||
'<div class="m-sys-switch-row"><div><strong>交易时段自动刷新</strong><p class="m-sys-hint">开启后后台定时更新快照</p></div>' +
|
||||
'<button class="m-theme-switch" type="button" data-system-toggle-refresh role="switch" aria-checked="' + (data.background_refresh_enabled ? "true" : "false") + '" aria-label="交易时段自动刷新"><span class="m-theme-switch-thumb"></span></button></div>' +
|
||||
'<input id="m-sys-bg-refresh" type="checkbox"' + (data.background_refresh_enabled ? " checked" : "") + ' hidden>' +
|
||||
'<button class="m-btn-outline" type="button" data-system-refresh>立即刷新一次</button>' +
|
||||
'<p class="m-sys-hint">所有用户读取同一份快照,刷新不影响当前页面内容。</p></div>' +
|
||||
'<div class="m-card m-sys-section"><strong>历史数据回补</strong>' +
|
||||
formFieldHtml("开始日期", dateInputHtml("m-sys-backfill-start", ""), false) +
|
||||
formFieldHtml("结束日期", dateInputHtml("m-sys-backfill-end", ""), false) +
|
||||
'<button class="m-btn-primary" type="button" data-system-backfill>开始回补</button>' +
|
||||
'<button class="m-btn-outline" type="button" data-system-backfill>开始回补</button>' +
|
||||
'<p class="m-sys-hint">回补用于补齐缺失的历史行情,开始前会再次确认;回补期间页面可正常使用。</p></div>' +
|
||||
"</div>";
|
||||
const models = state.system.models || [];
|
||||
const modelsHtml =
|
||||
'<div class="m-form-body" data-system-admin-panel="models">' +
|
||||
'<div class="m-sys-body" data-system-admin-panel="models">' +
|
||||
'<div class="m-card m-sys-section"><strong>模型分工</strong>' +
|
||||
formFieldHtml("主模型", '<select id="m-sys-primary-model"></select>', false) +
|
||||
formFieldHtml("辅助模型", '<select id="m-sys-fallback-model"></select>', false) +
|
||||
'<div id="m-sys-model-list">' + renderModelPoolHtml(llm.models || []) + "</div>" +
|
||||
'<button class="m-btn-primary" type="button" data-system-add-model>添加模型</button>' +
|
||||
'<p class="m-sys-hint">主模型不可用时自动改用辅助模型</p>' +
|
||||
'<button class="m-btn-primary" type="button" data-system-save-models>保存分工</button></div>' +
|
||||
'<div class="m-card m-sys-section"><strong>模型池 · ' + models.length + " 个</strong>" +
|
||||
'<div id="m-sys-model-list">' + renderModelPoolHtml(models) + "</div>" +
|
||||
'<p class="m-sys-hint">点任意模型卡片进入编辑:改名称、地址、密钥、测试连接或删除</p>' +
|
||||
'<button class="m-btn-primary" type="button" data-system-add-model>+ 添加模型</button></div>' +
|
||||
"</div>";
|
||||
const page = document.querySelector(".m-page");
|
||||
if (!page) return;
|
||||
const bar = tab === "models"
|
||||
? '<div class="m-form-bar"><button class="m-btn-primary" type="button" data-system-save-models>保存模型池</button></div>'
|
||||
: '<div class="m-form-bar"><button class="m-btn-primary" type="button" data-system-save-market>保存行情配置</button></div>';
|
||||
page.innerHTML = adminTabHtml() + '<div class="m-scroll" id="m-scroll">' + (tab === "models" ? modelsHtml : marketHtml) + "</div>" + bar;
|
||||
page.innerHTML = adminTabHtml() + '<div class="m-scroll" id="m-scroll">' + (tab === "models" ? modelsHtml : marketHtml) + "</div>";
|
||||
if (tab === "models") updateSystemModelRoleOptions(llm.primary_model_id || "", llm.fallback_model_id || "");
|
||||
}
|
||||
|
||||
function hostOfUrl(url) {
|
||||
try {
|
||||
return new URL(url).host;
|
||||
} catch (error) {
|
||||
return String(url || "").replace(/^https?:\/\//, "").split("/")[0] || "--";
|
||||
}
|
||||
}
|
||||
|
||||
function renderModelPoolHtml(models) {
|
||||
if (!models.length) {
|
||||
return '<div class="m-state"><p>模型池为空,请先添加模型</p></div>';
|
||||
}
|
||||
return models.map(function (item, index) {
|
||||
return '<article class="m-card" data-model-id="' + escapeHtml(item.id) + '">' +
|
||||
"<strong>" + escapeHtml(item.name || ("模型 " + (index + 1))) + "</strong>" +
|
||||
'<p class="m-sys-lead">' + (item.configured ? "已保存密钥" : "待配置") + "</p>" +
|
||||
formFieldHtml("显示名称", '<input data-model-field="name" maxlength="50" value="' + escapeHtml(item.name || "") + '">', true) +
|
||||
formFieldHtml("API Base URL", '<input data-model-field="base_url" type="url" value="' + escapeHtml(item.base_url || "https://api.openai.com/v1") + '">', true) +
|
||||
formFieldHtml("模型标识", '<input data-model-field="model" maxlength="100" value="' + escapeHtml(item.model || "") + '">', true) +
|
||||
formFieldHtml("API Key", '<input data-model-field="api_key" type="password" autocomplete="off" maxlength="300" placeholder="' + (item.configured ? "留空保留已保存的 Key" : "输入 API Key") + '">', !item.configured) +
|
||||
'<button class="m-btn-primary" type="button" data-system-test-model>测试连接</button>' +
|
||||
'<p class="m-sys-lead" data-model-test-status>未测试</p>' +
|
||||
'<button class="m-btn-primary m-btn-danger" type="button" data-system-delete-model>删除模型</button>' +
|
||||
"</article>";
|
||||
const llm = (state.system.admin && state.system.admin.llm) || {};
|
||||
return models.map(function (item) {
|
||||
const badges = [];
|
||||
if (item.id === llm.primary_model_id) badges.push('<span class="m-sys-badge m-sys-badge--admin">主模型</span>');
|
||||
if (item.id === llm.fallback_model_id) badges.push('<span class="m-sys-badge">辅助</span>');
|
||||
badges.push('<span class="m-sys-badge' + (item.configured ? " m-sys-badge--ok" : "") + '">' + (item.configured ? "已配置" : "待配置") + "</span>");
|
||||
return '<button class="m-sys-model-card" type="button" data-model-id="' + escapeHtml(item.id) + '" data-system-edit-model>' +
|
||||
"<div><strong>" + escapeHtml(item.name || "未命名模型") + "</strong>" +
|
||||
'<div class="m-sys-badges">' + badges.join("") + "</div>" +
|
||||
'<p class="m-sys-hint">' + escapeHtml(hostOfUrl(item.base_url) + " · " + (item.model || "未填写标识")) + "</p></div>" +
|
||||
'<span class="m-sys-row-chevron">' + icon("chevron-right", 16) + "</span></button>";
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function collectSystemModelPool() {
|
||||
const models = (state.system.admin && state.system.admin.llm && state.system.admin.llm.models) || [];
|
||||
const saved = new Map(models.map(function (item) { return [item.id, item]; }));
|
||||
return Array.prototype.map.call(document.querySelectorAll("#m-sys-model-list [data-model-id]"), function (row) {
|
||||
function fieldValue(name) {
|
||||
const input = row.querySelector("[data-model-field='" + name + "']");
|
||||
return String(input && input.value != null ? input.value : "").trim();
|
||||
}
|
||||
return (state.system.models || []).map(function (item) {
|
||||
return {
|
||||
id: row.dataset.modelId,
|
||||
name: fieldValue("name"),
|
||||
base_url: fieldValue("base_url"),
|
||||
model: fieldValue("model"),
|
||||
api_key: fieldValue("api_key"),
|
||||
configured: Boolean(saved.get(row.dataset.modelId) && saved.get(row.dataset.modelId).configured),
|
||||
id: item.id,
|
||||
name: item.name || "",
|
||||
base_url: item.base_url || "",
|
||||
model: item.model || "",
|
||||
api_key: item.api_key || "",
|
||||
configured: Boolean(item.configured)
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -5122,6 +5305,40 @@
|
||||
fallback.value = models.some(function (item) { return item.id === fallbackId; }) && fallbackId !== keepPrimary ? fallbackId : "";
|
||||
}
|
||||
|
||||
function openModelEditSheet(modelId) {
|
||||
const models = state.system.models || [];
|
||||
const item = models.find(function (row) { return row.id === modelId; }) || {};
|
||||
state.system.editingModelId = modelId;
|
||||
openSheet(
|
||||
'<div class="m-sheet-head"><h2>编辑模型</h2>' +
|
||||
'<button class="m-sheet-close" type="button" data-sheet-close aria-label="关闭">' + icon("close", 20) + "</button></div>" +
|
||||
'<div class="m-sheet-body" data-model-id="' + escapeHtml(modelId) + '">' +
|
||||
formFieldHtml("显示名称", '<input data-model-field="name" maxlength="50" value="' + escapeHtml(item.name || "") + '">', true) +
|
||||
formFieldHtml("API Base URL", '<input data-model-field="base_url" type="url" value="' + escapeHtml(item.base_url || "https://api.openai.com/v1") + '">', true) +
|
||||
formFieldHtml("模型标识", '<input data-model-field="model" maxlength="100" value="' + escapeHtml(item.model || "") + '">', true) +
|
||||
formFieldHtml("API Key", '<input data-model-field="api_key" type="password" autocomplete="off" maxlength="300" placeholder="' + (item.configured ? "留空则保留已保存的 Key" : "输入 API Key") + '">', !item.configured) +
|
||||
'<div class="m-sys-test-row"><button class="m-btn-outline" type="button" data-system-test-model>测试连接</button>' +
|
||||
'<span data-model-test-status>未测试</span></div>' +
|
||||
'<div class="m-sys-sheet-actions">' +
|
||||
'<button class="m-btn-outline-danger" type="button" data-system-delete-model>删除模型</button>' +
|
||||
'<button class="m-btn-primary" type="button" data-system-save-model>保存</button>' +
|
||||
"</div></div>"
|
||||
);
|
||||
}
|
||||
|
||||
function readModelSheetFields(root) {
|
||||
function fieldValue(name) {
|
||||
const input = root.querySelector("[data-model-field='" + name + "']");
|
||||
return String(input && input.value != null ? input.value : "").trim();
|
||||
}
|
||||
return {
|
||||
name: fieldValue("name"),
|
||||
base_url: fieldValue("base_url"),
|
||||
model: fieldValue("model"),
|
||||
api_key: fieldValue("api_key")
|
||||
};
|
||||
}
|
||||
|
||||
function renderSystemMembers() {
|
||||
const payload = state.system.admin || {};
|
||||
const membership = payload.membership || {};
|
||||
@@ -5129,39 +5346,77 @@
|
||||
const userHtml = users.map(function (user) {
|
||||
const admin = user.role === "admin";
|
||||
const member = Boolean(user.membership_subscribed);
|
||||
const identity = [admin ? "管理员" : "", member ? "会员有效" : "普通用户"].filter(Boolean).join(" · ");
|
||||
const badges = [];
|
||||
if (admin) badges.push('<span class="m-sys-badge m-sys-badge--admin">管理员</span>');
|
||||
if (member) badges.push('<span class="m-sys-badge m-sys-badge--ok">会员</span>');
|
||||
else badges.push('<span class="m-sys-badge">普通用户</span>');
|
||||
const expiry = member
|
||||
? (user.membership_expires_at ? "有效至 " + membershipDateLabel(user.membership_expires_at) : "永久有效")
|
||||
: user.membership_status === "suspended"
|
||||
? "会员已停用"
|
||||
: "尚未开通";
|
||||
return '<article class="m-card" data-admin-user="' + number(user.id) + '">' +
|
||||
"<strong>" + escapeHtml(user.username) + "</strong>" +
|
||||
'<p class="m-sys-lead">' + escapeHtml(identity) + " · 今日调用 " + number(user.used_today) + "</p>" +
|
||||
'<p class="m-sys-lead">' + escapeHtml(expiry) + "</p>" +
|
||||
formFieldHtml("状态", '<select data-member-status>' +
|
||||
'<option value="inactive"' + (user.membership_status === "inactive" ? " selected" : "") + ">未开通</option>" +
|
||||
'<option value="active"' + (user.membership_status === "active" ? " selected" : "") + ">有效</option>" +
|
||||
'<option value="suspended"' + (user.membership_status === "suspended" ? " selected" : "") + ">停用</option>" +
|
||||
"</select>", false) +
|
||||
formFieldHtml("开通 / 续期时长", '<select data-member-duration><option value="">选择时长</option>' +
|
||||
'<option value="1_month">1个月</option><option value="3_months">3个月</option>' +
|
||||
'<option value="12_months">12个月</option><option value="3_years">3年</option>' +
|
||||
'<option value="permanent">永久</option></select>', false) +
|
||||
'<button class="m-btn-primary" type="button" data-system-save-member>应用</button>' +
|
||||
"</article>";
|
||||
return '<div class="m-sys-user-row" data-admin-user="' + number(user.id) + '">' +
|
||||
'<div class="m-sys-row-body"><strong>' + escapeHtml(user.username) + "</strong>" +
|
||||
'<div class="m-sys-badges">' + badges.join("") + "</div>" +
|
||||
'<p class="m-sys-hint">' + escapeHtml(expiry) + " · 今日已用 " + number(user.used_today) + " 次</p></div>" +
|
||||
'<button class="m-btn-outline" type="button" data-system-open-member>管理</button></div>';
|
||||
}).join("") || '<div class="m-state"><p>暂无注册用户</p></div>';
|
||||
const html =
|
||||
'<div class="m-form-body" data-system-page="members">' +
|
||||
'<div class="m-card"><strong>会员调用额度</strong><p class="m-sys-lead">每日自动重置</p></div>' +
|
||||
'<div class="m-sys-body" data-system-page="members">' +
|
||||
'<div class="m-card m-sys-section"><strong>全局额度</strong>' +
|
||||
formFieldHtml("会员每日智能分析上限", '<input id="m-sys-member-limit" type="number" min="1" max="1000" value="' + (number(membership.member_daily_limit) || 50) + '">', false) +
|
||||
'<button class="m-btn-primary" type="button" data-system-save-limit>保存调用额度</button>' +
|
||||
'<div class="m-card"><strong>会员账号</strong><p class="m-sys-lead">手动开通与续期</p></div>' +
|
||||
'<p class="m-sys-hint">对所有会员生效,每日 0 点自动重置。</p>' +
|
||||
'<button class="m-btn-primary" type="button" data-system-save-limit>保存额度</button></div>' +
|
||||
'<div class="m-card m-sys-section"><strong>会员账号 · ' + users.length + " 个</strong>" +
|
||||
userHtml +
|
||||
'<p class="m-sys-hint">点「管理」为对应账号开通、续期或停用会员。</p></div>' +
|
||||
"</div>";
|
||||
systemFill(html);
|
||||
}
|
||||
|
||||
function openMemberManageSheet(userId) {
|
||||
const users = (state.system.admin && state.system.admin.users) || [];
|
||||
const user = users.find(function (item) { return String(item.id) === String(userId); });
|
||||
if (!user) return;
|
||||
state.system.editingUserId = String(userId);
|
||||
const member = Boolean(user.membership_subscribed);
|
||||
const expiry = member
|
||||
? (user.membership_expires_at ? "有效至 " + membershipDateLabel(user.membership_expires_at) : "永久有效")
|
||||
: user.membership_status === "suspended" ? "会员已停用" : "尚未开通";
|
||||
openSheet(
|
||||
'<div class="m-sheet-head"><h2>管理会员 · ' + escapeHtml(user.username) + "</h2>" +
|
||||
'<button class="m-sheet-close" type="button" data-sheet-close aria-label="关闭">' + icon("close", 20) + "</button></div>" +
|
||||
'<div class="m-sheet-body" data-admin-user="' + number(user.id) + '">' +
|
||||
'<p class="m-sys-lead">当前状态:' + escapeHtml(expiry) + " · 今日已用 " + number(user.used_today) + " 次</p>" +
|
||||
formFieldHtml("会员状态", '<select data-member-status>' +
|
||||
'<option value="inactive"' + (user.membership_status === "inactive" ? " selected" : "") + ">未开通</option>" +
|
||||
'<option value="active"' + (user.membership_status === "active" ? " selected" : "") + ">有效</option>" +
|
||||
'<option value="suspended"' + (user.membership_status === "suspended" ? " selected" : "") + ">停用</option>" +
|
||||
"</select>", false) +
|
||||
formFieldHtml("开通 / 续期时长", '<select data-member-duration><option value="">选择时长</option>' +
|
||||
'<option value="1_month">1个月</option><option value="3_months">3个月</option>' +
|
||||
'<option value="12_months">12个月</option><option value="3_years">3年</option>' +
|
||||
'<option value="permanent">永久</option></select>', false) +
|
||||
'<p class="m-sys-hint">从当前时间开始顺延;已有会员则叠加续期。</p>' +
|
||||
'<div class="m-sys-sheet-actions">' +
|
||||
'<button class="m-btn-outline" type="button" data-sheet-close>取消</button>' +
|
||||
'<button class="m-btn-primary" type="button" data-system-save-member>应用</button>' +
|
||||
"</div></div>"
|
||||
);
|
||||
}
|
||||
|
||||
function setFieldError(inputId, message) {
|
||||
const input = document.getElementById(inputId);
|
||||
const field = input && input.closest(".m-form-field");
|
||||
if (!field) return;
|
||||
field.classList.toggle("is-invalid", Boolean(message));
|
||||
const error = field.querySelector("[data-field-error]");
|
||||
if (error) {
|
||||
error.hidden = !message;
|
||||
error.textContent = message || "";
|
||||
}
|
||||
}
|
||||
|
||||
function saveSystemBirth() {
|
||||
const birthDate = (document.getElementById("m-sys-birth-date") || {}).value;
|
||||
const birthTime = (document.getElementById("m-sys-birth-time") || {}).value;
|
||||
@@ -5176,7 +5431,7 @@
|
||||
gender: (document.getElementById("m-sys-birth-gender") || {}).value || "unspecified",
|
||||
trade_date: todayString(),
|
||||
}).then(function () {
|
||||
showToast("个人命理资料已保存到当前账号");
|
||||
showToast("个人命理资料已保存");
|
||||
loadSystem();
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "个人命理资料保存失败");
|
||||
@@ -5186,12 +5441,12 @@
|
||||
}
|
||||
|
||||
function deleteSystemBirth() {
|
||||
openConfirmSheet("删除资料", "确定删除当前账号保存的个人命理资料吗?", {
|
||||
openConfirmSheet("删除命理资料?", "删除后智能解读将无法使用你的出生信息,此操作不可恢复。", {
|
||||
danger: true,
|
||||
centered: true,
|
||||
confirmLabel: "删除",
|
||||
onConfirm: function () {
|
||||
global.MobileAPI.request("/api/account/birth-profile", "DELETE").then(function () {
|
||||
closeSheet();
|
||||
showToast("个人命理资料已删除");
|
||||
loadSystem();
|
||||
}).catch(function (error) {
|
||||
@@ -5205,6 +5460,23 @@
|
||||
const current = (document.getElementById("m-sys-password-current") || {}).value || "";
|
||||
const next = (document.getElementById("m-sys-password-new") || {}).value || "";
|
||||
const confirm = (document.getElementById("m-sys-password-confirm") || {}).value || "";
|
||||
setFieldError("m-sys-password-current", "");
|
||||
setFieldError("m-sys-password-new", "");
|
||||
setFieldError("m-sys-password-confirm", "");
|
||||
let invalid = false;
|
||||
if (!current) {
|
||||
setFieldError("m-sys-password-current", "请输入当前密码");
|
||||
invalid = true;
|
||||
}
|
||||
if (next.length < 8 || next.length > 128) {
|
||||
setFieldError("m-sys-password-new", "新密码长度应为 8 至 128 位");
|
||||
invalid = true;
|
||||
}
|
||||
if (next !== confirm) {
|
||||
setFieldError("m-sys-password-confirm", "两次输入的密码不一致,请重新输入。");
|
||||
invalid = true;
|
||||
}
|
||||
if (invalid) return;
|
||||
const button = document.querySelector("[data-system-save-password]");
|
||||
if (button) button.disabled = true;
|
||||
global.MobileAPI.request("/api/account/password", "POST", {
|
||||
@@ -5212,14 +5484,13 @@
|
||||
new_password: next,
|
||||
confirm_password: confirm,
|
||||
}).then(function () {
|
||||
const formIds = ["m-sys-password-current", "m-sys-password-new", "m-sys-password-confirm"];
|
||||
formIds.forEach(function (id) {
|
||||
["m-sys-password-current", "m-sys-password-new", "m-sys-password-confirm"].forEach(function (id) {
|
||||
const input = document.getElementById(id);
|
||||
if (input) input.value = "";
|
||||
});
|
||||
showToast("密码已更新");
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "密码更新失败");
|
||||
showToast("更新失败:" + (error && error.message ? error.message : "密码更新失败"));
|
||||
}).then(function () {
|
||||
if (button) button.disabled = false;
|
||||
});
|
||||
@@ -5232,10 +5503,10 @@
|
||||
function logoutSystemAccount() {
|
||||
openConfirmSheet("退出当前账号", "退出后需要重新登录。本机已记录的其他账号仍可直接切换。", {
|
||||
danger: true,
|
||||
centered: true,
|
||||
confirmLabel: "退出",
|
||||
onConfirm: function () {
|
||||
global.MobileSession.logout().then(function () {
|
||||
closeSheet();
|
||||
global.MobileRouter.replace("#/auth");
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "退出失败");
|
||||
@@ -5250,9 +5521,8 @@
|
||||
global.MobileAPI.request("/api/admin/settings", "POST", {
|
||||
tushare_token: ((document.getElementById("m-sys-token") || {}).value || "").trim(),
|
||||
ifind_refresh_token: ((document.getElementById("m-sys-ifind") || {}).value || "").trim(),
|
||||
background_refresh_enabled: Boolean((document.getElementById("m-sys-bg-refresh") || {}).checked),
|
||||
}).then(function () {
|
||||
showToast("行情配置已保存");
|
||||
showToast("行情密钥已保存");
|
||||
loadSystem();
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "系统配置保存失败");
|
||||
@@ -5261,30 +5531,65 @@
|
||||
});
|
||||
}
|
||||
|
||||
function toggleSystemRefresh() {
|
||||
const enabled = !Boolean((state.system.admin && state.system.admin.data && state.system.admin.data.background_refresh_enabled));
|
||||
global.MobileAPI.request("/api/admin/settings", "POST", {
|
||||
background_refresh_enabled: enabled,
|
||||
}).then(function () {
|
||||
showToast(enabled ? "后台刷新已启用" : "后台刷新已暂停");
|
||||
loadSystem();
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "后台刷新设置失败");
|
||||
});
|
||||
}
|
||||
|
||||
function saveSystemModels() {
|
||||
const button = document.querySelector("[data-system-save-models]");
|
||||
if (button) button.disabled = true;
|
||||
global.MobileAPI.request("/api/admin/settings", "POST", {
|
||||
models: collectSystemModelPool(),
|
||||
primary_model_id: (document.getElementById("m-sys-primary-model") || {}).value || "",
|
||||
fallback_model_id: (document.getElementById("m-sys-fallback-model") || {}).value || "",
|
||||
}).then(function () {
|
||||
showToast("模型池已保存");
|
||||
showToast("模型分工已保存");
|
||||
loadSystem();
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "模型池保存失败");
|
||||
showToast(error && error.message ? error.message : "模型分工保存失败");
|
||||
}).then(function () {
|
||||
if (button) button.disabled = false;
|
||||
});
|
||||
}
|
||||
|
||||
function persistSystemModels(models, message) {
|
||||
return global.MobileAPI.request("/api/admin/settings", "POST", { models: models }).then(function () {
|
||||
showToast(message || "模型池已保存");
|
||||
closeSheet();
|
||||
loadSystem();
|
||||
});
|
||||
}
|
||||
|
||||
function saveEditedSystemModel() {
|
||||
const sheet = document.querySelector(".m-sheet-body[data-model-id]");
|
||||
if (!sheet) return;
|
||||
const id = sheet.dataset.modelId;
|
||||
const fields = readModelSheetFields(sheet);
|
||||
const models = collectSystemModelPool().map(function (item) {
|
||||
if (item.id !== id) return item;
|
||||
return Object.assign({}, item, fields);
|
||||
});
|
||||
persistSystemModels(models, "模型已保存").catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "模型保存失败");
|
||||
});
|
||||
}
|
||||
|
||||
function addSystemModel() {
|
||||
const models = collectSystemModelPool();
|
||||
const id = "model-" + Date.now() + "-" + Math.floor(Math.random() * 10000);
|
||||
models.push({ id: id, name: "模型 " + (models.length + 1), base_url: "https://api.openai.com/v1", model: "", api_key: "", configured: false });
|
||||
const created = { id: id, name: "模型 " + (models.length + 1), base_url: "https://api.openai.com/v1", model: "", api_key: "", configured: false };
|
||||
state.system.models = models.concat([created]);
|
||||
const list = document.getElementById("m-sys-model-list");
|
||||
if (list) list.innerHTML = renderModelPoolHtml(models);
|
||||
if (list) list.innerHTML = renderModelPoolHtml(state.system.models);
|
||||
updateSystemModelRoleOptions(id, (document.getElementById("m-sys-fallback-model") || {}).value || "");
|
||||
openModelEditSheet(id);
|
||||
}
|
||||
|
||||
function deleteSystemModel(row) {
|
||||
@@ -5292,25 +5597,36 @@
|
||||
const id = row.dataset.modelId;
|
||||
const primary = (document.getElementById("m-sys-primary-model") || {}).value;
|
||||
const fallback = (document.getElementById("m-sys-fallback-model") || {}).value;
|
||||
if (id === primary || id === fallback) {
|
||||
const llm = (state.system.admin && state.system.admin.llm) || {};
|
||||
if (id === primary || id === fallback || id === llm.primary_model_id || id === llm.fallback_model_id) {
|
||||
showToast("请先为主模型或辅助模型选择其他模型,再删除当前模型");
|
||||
return;
|
||||
}
|
||||
const models = collectSystemModelPool().filter(function (item) { return item.id !== id; });
|
||||
const list = document.getElementById("m-sys-model-list");
|
||||
if (list) list.innerHTML = renderModelPoolHtml(models);
|
||||
updateSystemModelRoleOptions(primary, fallback);
|
||||
openConfirmSheet("删除模型?", "删除后该模型将从模型池移除,此操作不可恢复。", {
|
||||
danger: true,
|
||||
centered: true,
|
||||
confirmLabel: "删除",
|
||||
onConfirm: function () {
|
||||
const models = collectSystemModelPool().filter(function (item) { return item.id !== id; });
|
||||
persistSystemModels(models, "模型已删除").catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "删除失败");
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function testSystemModel(row) {
|
||||
if (!row) return;
|
||||
const status = row.querySelector("[data-model-test-status]");
|
||||
const button = row.querySelector("[data-system-test-model]");
|
||||
const profile = collectSystemModelPool().find(function (item) { return item.id === row.dataset.modelId; }) || {};
|
||||
const status = document.querySelector("[data-model-test-status]");
|
||||
const button = document.querySelector("[data-system-test-model]");
|
||||
const sheet = document.querySelector(".m-sheet-body[data-model-id]");
|
||||
const id = (sheet && sheet.dataset.modelId) || row.dataset.modelId;
|
||||
const fields = sheet ? readModelSheetFields(sheet) : {};
|
||||
const profile = Object.assign({}, collectSystemModelPool().find(function (item) { return item.id === id; }) || {}, fields, { id: id });
|
||||
if (button) button.disabled = true;
|
||||
if (status) status.textContent = "连接中";
|
||||
global.MobileAPI.request("/api/admin/settings/test", "POST", { model_id: row.dataset.modelId, profile: profile }).then(function (payload) {
|
||||
if (status) status.textContent = "已连通 · " + number(payload.result && payload.result.latency_ms) + " ms";
|
||||
global.MobileAPI.request("/api/admin/settings/test", "POST", { model_id: id, profile: profile }).then(function (payload) {
|
||||
if (status) status.textContent = "上次测试:成功 · " + number(payload.result && payload.result.latency_ms) + "ms";
|
||||
}).catch(function (error) {
|
||||
if (status) status.textContent = error && error.message ? error.message : "测试失败";
|
||||
}).then(function () {
|
||||
@@ -5331,19 +5647,27 @@
|
||||
}
|
||||
|
||||
function startSystemBackfill() {
|
||||
const button = document.querySelector("[data-system-backfill]");
|
||||
if (button) button.disabled = true;
|
||||
global.MobileAPI.request("/api/backfill", "POST", {
|
||||
start_date: (document.getElementById("m-sys-backfill-start") || {}).value,
|
||||
end_date: (document.getElementById("m-sys-backfill-end") || {}).value,
|
||||
}).then(function (payload) {
|
||||
const count = payload && payload.results ? payload.results.length : 0;
|
||||
showToast("历史回补完成,共处理 " + count + " 个工作日");
|
||||
loadSystem();
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "回补失败");
|
||||
}).then(function () {
|
||||
if (button) button.disabled = false;
|
||||
const startDate = (document.getElementById("m-sys-backfill-start") || {}).value;
|
||||
const endDate = (document.getElementById("m-sys-backfill-end") || {}).value;
|
||||
openConfirmSheet("开始历史回补?", "将按选定日期补齐缺失行情,回补期间页面仍可使用。", {
|
||||
confirmLabel: "开始回补",
|
||||
centered: true,
|
||||
onConfirm: function () {
|
||||
const button = document.querySelector("[data-system-backfill]");
|
||||
if (button) button.disabled = true;
|
||||
global.MobileAPI.request("/api/backfill", "POST", {
|
||||
start_date: startDate,
|
||||
end_date: endDate,
|
||||
}).then(function (payload) {
|
||||
const count = payload && payload.results ? payload.results.length : 0;
|
||||
showToast("历史回补完成,共处理 " + count + " 个工作日");
|
||||
loadSystem();
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "回补失败");
|
||||
}).then(function () {
|
||||
if (button) button.disabled = false;
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5364,21 +5688,35 @@
|
||||
|
||||
function saveSystemMember(card) {
|
||||
if (!card) return;
|
||||
const button = card.querySelector("[data-system-save-member]");
|
||||
if (button) button.disabled = true;
|
||||
global.MobileAPI.request("/api/admin/membership", "POST", {
|
||||
user_id: card.dataset.adminUser,
|
||||
status: (card.querySelector("[data-member-status]") || {}).value,
|
||||
duration: (card.querySelector("[data-member-duration]") || {}).value,
|
||||
}).then(function (payload) {
|
||||
if (state.system.admin) state.system.admin.users = payload.users || [];
|
||||
showToast("会员状态已更新");
|
||||
renderSystemMembers();
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "会员状态保存失败");
|
||||
}).then(function () {
|
||||
if (button) button.disabled = false;
|
||||
});
|
||||
const status = (card.querySelector("[data-member-status]") || {}).value;
|
||||
const apply = function () {
|
||||
const button = card.querySelector("[data-system-save-member]");
|
||||
if (button) button.disabled = true;
|
||||
global.MobileAPI.request("/api/admin/membership", "POST", {
|
||||
user_id: card.dataset.adminUser,
|
||||
status: status,
|
||||
duration: (card.querySelector("[data-member-duration]") || {}).value,
|
||||
}).then(function (payload) {
|
||||
if (state.system.admin) state.system.admin.users = payload.users || [];
|
||||
closeSheet();
|
||||
showToast("会员状态已更新");
|
||||
renderSystemMembers();
|
||||
}).catch(function (error) {
|
||||
showToast(error && error.message ? error.message : "会员状态保存失败");
|
||||
}).then(function () {
|
||||
if (button) button.disabled = false;
|
||||
});
|
||||
};
|
||||
if (status === "suspended") {
|
||||
openConfirmSheet("停用该会员?", "停用后该账号将无法使用会员智能功能,可稍后重新开通。", {
|
||||
danger: true,
|
||||
centered: true,
|
||||
confirmLabel: "停用",
|
||||
onConfirm: apply
|
||||
});
|
||||
return;
|
||||
}
|
||||
apply();
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- events */
|
||||
@@ -5522,8 +5860,12 @@
|
||||
if (event.target.closest("[data-system-switch]")) { switchSystemAccount(); return; }
|
||||
if (event.target.closest("[data-system-logout]")) { logoutSystemAccount(); return; }
|
||||
if (event.target.closest("[data-system-save-market]")) { saveSystemMarket(); return; }
|
||||
if (event.target.closest("[data-system-toggle-refresh]")) { toggleSystemRefresh(); return; }
|
||||
if (event.target.closest("[data-system-save-models]")) { saveSystemModels(); return; }
|
||||
if (event.target.closest("[data-system-save-model]")) { saveEditedSystemModel(); return; }
|
||||
if (event.target.closest("[data-system-add-model]")) { addSystemModel(); return; }
|
||||
const editModel = event.target.closest("[data-system-edit-model]");
|
||||
if (editModel) { openModelEditSheet(editModel.dataset.modelId); return; }
|
||||
const deleteModel = event.target.closest("[data-system-delete-model]");
|
||||
if (deleteModel) { deleteSystemModel(deleteModel.closest("[data-model-id]")); return; }
|
||||
const testModel = event.target.closest("[data-system-test-model]");
|
||||
@@ -5531,6 +5873,8 @@
|
||||
if (event.target.closest("[data-system-refresh]")) { startSystemRefresh(); return; }
|
||||
if (event.target.closest("[data-system-backfill]")) { startSystemBackfill(); return; }
|
||||
if (event.target.closest("[data-system-save-limit]")) { saveSystemMemberLimit(); return; }
|
||||
const openMember = event.target.closest("[data-system-open-member]");
|
||||
if (openMember) { openMemberManageSheet(openMember.closest("[data-admin-user]").dataset.adminUser); return; }
|
||||
const saveMember = event.target.closest("[data-system-save-member]");
|
||||
if (saveMember) { saveSystemMember(saveMember.closest("[data-admin-user]")); return; }
|
||||
|
||||
@@ -5691,5 +6035,6 @@
|
||||
global.MobilePages = {
|
||||
render: renderPage,
|
||||
has: function (key) { return Boolean(pageConfig(key) || isComplexPage(key)); },
|
||||
renderSystemHome: renderSystemHome,
|
||||
};
|
||||
})(window);
|
||||
|
||||
@@ -187,9 +187,9 @@
|
||||
const dark = document.getElementById("m-app").dataset.theme === "dark";
|
||||
const toggle = document.querySelector("[data-theme-toggle]");
|
||||
if (toggle) toggle.setAttribute("aria-checked", dark ? "true" : "false");
|
||||
const rowIcon = document.querySelector(".m-theme-row-icon");
|
||||
const rowIcon = document.querySelector(".m-theme-row-icon, [data-theme-row-icon]");
|
||||
if (rowIcon) rowIcon.innerHTML = icon(dark ? "moon" : "sun");
|
||||
const rowBodySmall = document.querySelector(".m-theme-row-body small");
|
||||
const rowBodySmall = document.querySelector(".m-theme-row-body small, [data-theme-row-label]");
|
||||
if (rowBodySmall) rowBodySmall.textContent = dark ? "当前:夜间模式" : "当前:日间模式";
|
||||
}
|
||||
|
||||
@@ -206,6 +206,10 @@
|
||||
replace(DEFAULT_HASH);
|
||||
return;
|
||||
}
|
||||
if (key === "system" && global.MobilePages && typeof global.MobilePages.renderSystemHome === "function") {
|
||||
global.MobilePages.renderSystemHome();
|
||||
return;
|
||||
}
|
||||
const items = visibleHubItems(hub);
|
||||
updateHeader({ title: hub.title, back: false });
|
||||
const section = key === "system" ? themeToggleSection() : "";
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
"/shared/table.js?v=20260803-1",
|
||||
"/shared/theme.js?v=20260803-1",
|
||||
"/shared/dashboard.js?v=20260820-1",
|
||||
"/shared/session.js?v=20260803-1",
|
||||
"/shared/session.js?v=20260829-hel243",
|
||||
"/shared/admin.js?v=20260803-1",
|
||||
"/app.js?v=20260803-2",
|
||||
];
|
||||
|
||||
Vendored
+3
-243
@@ -93,28 +93,6 @@ 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;
|
||||
}
|
||||
@@ -1875,60 +1853,6 @@ 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;
|
||||
|
||||
@@ -1960,7 +1884,7 @@ body[data-active-view="heavenView"] .workspace-view {
|
||||
}
|
||||
|
||||
#heavenView .button:focus-visible,
|
||||
#heavenView .heaven-tab:focus-visible,
|
||||
#heavenView .segment:focus-visible,
|
||||
#heavenView summary:focus-visible {
|
||||
outline: 2px solid var(--heaven-cinnabar);
|
||||
|
||||
@@ -2623,12 +2547,6 @@ body[data-active-view="heavenView"] .workspace-view {
|
||||
padding: 0px 14px;
|
||||
}
|
||||
|
||||
#heavenView .heaven-tabs {
|
||||
gap: 22px;
|
||||
|
||||
padding: 0px 14px;
|
||||
}
|
||||
|
||||
.heaven-proverb {
|
||||
padding: 8px 14px;
|
||||
|
||||
@@ -3093,7 +3011,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-tabs {
|
||||
#heavenView.heaven-data-loading .heaven-page-head {
|
||||
opacity: 0.42;
|
||||
|
||||
pointer-events: none;
|
||||
@@ -3695,7 +3613,7 @@ body[data-active-view="heavenView"] .workspace-view {
|
||||
@media (max-width: 900px) {
|
||||
#heavenView .heaven-panel > ,
|
||||
#heavenView .heaven-proverb,
|
||||
#heavenView .heaven-tabs,
|
||||
#heavenView .heaven-page-head,
|
||||
#heavenView .heaven-toolbar {
|
||||
width: min(100% - 28px, 1280px);
|
||||
}
|
||||
@@ -3746,22 +3664,6 @@ 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;
|
||||
|
||||
@@ -3867,18 +3769,6 @@ 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;
|
||||
|
||||
@@ -6232,26 +6122,6 @@ 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;
|
||||
|
||||
@@ -6297,12 +6167,6 @@ 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;
|
||||
}
|
||||
@@ -6668,18 +6532,6 @@ 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);
|
||||
}
|
||||
@@ -7128,88 +6980,6 @@ 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;
|
||||
|
||||
@@ -9072,16 +8842,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
<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>
|
||||
|
||||
@@ -1363,7 +1363,8 @@ async function interpretHeaven(mode) {
|
||||
} catch (error) {
|
||||
stopHeavenReadingAnimation();
|
||||
state.heavenReadingLoading = false;
|
||||
state.heavenReadingError = error.message || "问天解读失败";
|
||||
const detail = error?.payload?.message || error?.payload?.error || error.message;
|
||||
state.heavenReadingError = detail || "问天解读失败";
|
||||
renderHeavenReadingDialog();
|
||||
showHeavenNotice(state.heavenReadingError);
|
||||
showToast(state.heavenReadingError);
|
||||
|
||||
Vendored
+1
-1
@@ -49,7 +49,7 @@ body[data-active-view="mentorView"] .app-page-context span {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
flex-direction: column;
|
||||
padding: 0;
|
||||
padding: var(--page-pad-y) 0 0;
|
||||
color: var(--qp-text-1);
|
||||
font-family: "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,14 @@ async function backfillData() {
|
||||
start_date: document.querySelector("#backfillStart").value,
|
||||
end_date: document.querySelector("#backfillEnd").value,
|
||||
});
|
||||
showToast(`历史回补完成,共处理 ${payload.results.length} 个工作日`);
|
||||
const failed = (payload.failed_count || 0);
|
||||
const skipped = (payload.skipped_non_trading_days || []).length;
|
||||
const suffix = failed
|
||||
? `,失败 ${failed} 个`
|
||||
: skipped
|
||||
? `,跳过 ${skipped} 个非交易日`
|
||||
: "";
|
||||
showToast(`历史回补完成,共处理 ${payload.results.length} 个交易日${suffix}`);
|
||||
state.sentimentHistory = null;
|
||||
state.sentimentHistoryKey = "";
|
||||
if (state.activeView === "sentimentCycleView") {
|
||||
|
||||
+19
-2
@@ -46,12 +46,29 @@
|
||||
}
|
||||
}
|
||||
|
||||
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 = {}) {
|
||||
const response = await fetch(url, requestOptions(method, body, options.signal));
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url, requestOptions(method, body, options.signal));
|
||||
} catch (error) {
|
||||
throw new ApiError(readableRequestError(error), 0, null);
|
||||
}
|
||||
const payload = await parseJson(response);
|
||||
handleUnauthorized(response, url);
|
||||
if (!response.ok || payload.error) {
|
||||
throw new ApiError(payload.error || "请求失败", response.status, payload);
|
||||
const message = payload.message || payload.error || "请求失败";
|
||||
throw new ApiError(message, response.status, payload);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
+432
-67
@@ -471,6 +471,32 @@
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.admin-refresh-status {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: var(--surface-muted);
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.admin-refresh-status svg {
|
||||
flex: 0 0 auto;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.admin-refresh-status[data-tone="running"] { color: var(--primary); }
|
||||
.admin-refresh-status[data-tone="success"] { color: var(--down); }
|
||||
.admin-refresh-status[data-tone="warning"] { color: var(--warning); }
|
||||
.admin-refresh-status[data-tone="failure"] { color: var(--up); }
|
||||
|
||||
.account-button > span {
|
||||
flex: 0 0 auto;
|
||||
|
||||
@@ -1668,6 +1694,11 @@ button.account-role-badge:focus-visible {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
body.login-portal {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.login-portal {
|
||||
min-height: 100vh;
|
||||
|
||||
@@ -1678,8 +1709,20 @@ button.account-role-badge:focus-visible {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.login-stage {
|
||||
position: relative;
|
||||
|
||||
flex: 1 1 auto;
|
||||
|
||||
display: grid;
|
||||
|
||||
place-items: center;
|
||||
|
||||
padding: 48px 24px;
|
||||
}
|
||||
|
||||
.login-theme-toggle {
|
||||
position: fixed;
|
||||
position: absolute;
|
||||
|
||||
z-index: 2;
|
||||
|
||||
@@ -1705,81 +1748,221 @@ button.account-role-badge:focus-visible {
|
||||
}
|
||||
|
||||
.login-brand {
|
||||
width: clamp(420px, 34vw, 560px);
|
||||
position: relative;
|
||||
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
|
||||
padding: 44px 48px 36px;
|
||||
flex-direction: column;
|
||||
|
||||
width: var(--login-brand-share);
|
||||
|
||||
min-width: var(--login-brand-min);
|
||||
|
||||
max-width: var(--login-brand-cap);
|
||||
|
||||
flex: 0 0 var(--login-brand-share);
|
||||
|
||||
overflow: hidden;
|
||||
|
||||
padding: var(--login-brand-pad);
|
||||
|
||||
background: var(--login-brand-gradient);
|
||||
|
||||
color: #f4f7ff;
|
||||
}
|
||||
|
||||
.login-brand-header {
|
||||
display: flex;
|
||||
|
||||
align-items: center;
|
||||
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.login-brand-mark {
|
||||
display: flex;
|
||||
|
||||
flex: 0 0 var(--login-brand-mark-size);
|
||||
|
||||
align-items: center;
|
||||
|
||||
justify-content: center;
|
||||
|
||||
width: 56px;
|
||||
width: var(--login-brand-mark-size);
|
||||
|
||||
height: 56px;
|
||||
height: var(--login-brand-mark-size);
|
||||
|
||||
border-radius: 16px;
|
||||
border-radius: 12px;
|
||||
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.login-brand-glyph {
|
||||
font-size: 24px;
|
||||
font-size: 20px;
|
||||
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.login-brand-identity {
|
||||
display: grid;
|
||||
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.login-brand-name {
|
||||
margin: 0;
|
||||
|
||||
font-size: var(--login-brand-name-size);
|
||||
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.login-brand-subtitle {
|
||||
margin: 0;
|
||||
|
||||
font-size: var(--font-size-caption);
|
||||
|
||||
letter-spacing: 0.02em;
|
||||
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.login-brand-copy {
|
||||
display: flex;
|
||||
|
||||
flex: 1 1 auto;
|
||||
|
||||
flex-direction: column;
|
||||
|
||||
justify-content: flex-end;
|
||||
|
||||
padding: 24px 0 20px;
|
||||
}
|
||||
|
||||
.login-brand-kicker {
|
||||
margin: 28px 0 8px;
|
||||
display: inline-flex;
|
||||
|
||||
align-self: flex-start;
|
||||
|
||||
margin: 0 0 14px;
|
||||
|
||||
padding: 4px 10px;
|
||||
|
||||
border: 1px solid rgba(255, 255, 255, 0.18);
|
||||
|
||||
border-radius: 999px;
|
||||
|
||||
font-size: var(--font-size-caption);
|
||||
|
||||
letter-spacing: 0.08em;
|
||||
|
||||
opacity: 0.78;
|
||||
opacity: 0.86;
|
||||
}
|
||||
|
||||
.login-brand-title {
|
||||
margin: 0;
|
||||
|
||||
font-size: 36px;
|
||||
max-width: 12.4em;
|
||||
|
||||
font-size: var(--login-hero-size);
|
||||
|
||||
font-weight: var(--font-weight-semibold);
|
||||
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.login-brand-lead {
|
||||
margin: 12px 0 0;
|
||||
|
||||
max-width: 18em;
|
||||
max-width: 28em;
|
||||
|
||||
font-size: var(--font-size-body);
|
||||
font-size: var(--font-size-label);
|
||||
|
||||
line-height: 1.7;
|
||||
|
||||
opacity: 0.86;
|
||||
opacity: 0.78;
|
||||
}
|
||||
|
||||
.login-brand-market {
|
||||
position: relative;
|
||||
|
||||
min-height: 168px;
|
||||
}
|
||||
|
||||
.login-brand-chart {
|
||||
display: block;
|
||||
|
||||
width: 100%;
|
||||
|
||||
height: 168px;
|
||||
}
|
||||
|
||||
.login-chart-area {
|
||||
fill: url(#loginChartFade);
|
||||
}
|
||||
|
||||
.login-chart-line {
|
||||
fill: none;
|
||||
|
||||
stroke: var(--login-trend-line);
|
||||
|
||||
stroke-width: 2;
|
||||
|
||||
stroke-linecap: round;
|
||||
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
.login-candles line {
|
||||
stroke-width: 1.5;
|
||||
}
|
||||
|
||||
.login-candles .is-up line,
|
||||
.login-candles .is-up rect {
|
||||
fill: var(--login-candle-up);
|
||||
|
||||
stroke: var(--login-candle-up);
|
||||
}
|
||||
|
||||
.login-candles .is-down line,
|
||||
.login-candles .is-down rect {
|
||||
fill: var(--login-candle-down);
|
||||
|
||||
stroke: var(--login-candle-down);
|
||||
}
|
||||
|
||||
.login-brand-stats {
|
||||
display: grid;
|
||||
position: absolute;
|
||||
|
||||
grid-template-columns: 1fr 1fr;
|
||||
right: 0;
|
||||
|
||||
gap: 16px 20px;
|
||||
bottom: 18px;
|
||||
|
||||
margin: 40px 0 0;
|
||||
left: 0;
|
||||
|
||||
display: flex;
|
||||
|
||||
flex-wrap: wrap;
|
||||
|
||||
gap: 8px;
|
||||
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.login-stat {
|
||||
display: flex;
|
||||
|
||||
align-items: baseline;
|
||||
|
||||
gap: 6px;
|
||||
|
||||
margin: 0;
|
||||
|
||||
padding: 6px 10px;
|
||||
|
||||
border-radius: 999px;
|
||||
|
||||
background: var(--login-stat-chip-bg);
|
||||
}
|
||||
|
||||
.login-stat dt {
|
||||
@@ -1789,37 +1972,49 @@ button.account-role-badge:focus-visible {
|
||||
}
|
||||
|
||||
.login-stat dd {
|
||||
margin: 4px 0 0;
|
||||
margin: 0;
|
||||
|
||||
font-size: 20px;
|
||||
font-size: var(--font-size-body);
|
||||
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.login-stat:nth-child(1) dd {
|
||||
color: #f0b45a;
|
||||
}
|
||||
|
||||
.login-stat:nth-child(2) dd {
|
||||
color: var(--login-candle-up);
|
||||
}
|
||||
|
||||
.login-stat:nth-child(3) dd {
|
||||
color: var(--login-candle-down);
|
||||
}
|
||||
|
||||
.login-stat-tag {
|
||||
margin-left: 6px;
|
||||
margin-left: 4px;
|
||||
|
||||
font-size: var(--font-size-caption);
|
||||
|
||||
font-weight: var(--font-weight-regular);
|
||||
}
|
||||
|
||||
.login-stage {
|
||||
flex: 1 1 auto;
|
||||
.login-brand-disclaimer {
|
||||
margin: 12px 0 0;
|
||||
|
||||
display: grid;
|
||||
font-size: var(--font-size-aux);
|
||||
|
||||
place-items: center;
|
||||
letter-spacing: 0.02em;
|
||||
|
||||
padding: 48px 24px;
|
||||
opacity: 0.48;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: 400px;
|
||||
width: var(--login-card-width);
|
||||
|
||||
max-width: calc(100vw - 48px);
|
||||
|
||||
padding: 32px;
|
||||
padding: var(--login-card-pad);
|
||||
|
||||
border: 1px solid var(--border-strong);
|
||||
|
||||
@@ -1839,7 +2034,7 @@ button.account-role-badge:focus-visible {
|
||||
.login-card-title {
|
||||
margin: 0;
|
||||
|
||||
font-size: 22px;
|
||||
font-size: var(--login-card-title-size);
|
||||
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
@@ -1894,16 +2089,14 @@ button.account-role-badge:focus-visible {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.login-portal .form-field input {
|
||||
height: 38px;
|
||||
.login-portal .form-field input.is-invalid {
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
.login-submit {
|
||||
width: 100%;
|
||||
|
||||
height: 40px;
|
||||
|
||||
min-height: 40px;
|
||||
min-height: var(--login-submit-height);
|
||||
}
|
||||
|
||||
.login-spinner {
|
||||
@@ -1962,10 +2155,7 @@ button.account-role-badge:focus-visible {
|
||||
}
|
||||
|
||||
.login-back,
|
||||
.login-add,
|
||||
.login-manage,
|
||||
.login-account-enter,
|
||||
.login-account-remove {
|
||||
.login-manage {
|
||||
border: 0;
|
||||
|
||||
background: transparent;
|
||||
@@ -1984,15 +2174,27 @@ button.account-role-badge:focus-visible {
|
||||
}
|
||||
|
||||
.login-portal .login-add {
|
||||
display: block;
|
||||
display: flex;
|
||||
|
||||
align-items: center;
|
||||
|
||||
justify-content: center;
|
||||
|
||||
width: 100%;
|
||||
|
||||
min-height: 40px;
|
||||
min-height: 44px;
|
||||
|
||||
margin-top: 8px;
|
||||
margin-top: 12px;
|
||||
|
||||
text-align: left;
|
||||
border: 1px dashed var(--border-strong);
|
||||
|
||||
border-radius: var(--size-radius-md);
|
||||
|
||||
background: transparent;
|
||||
|
||||
color: var(--action);
|
||||
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.login-portal .login-manage {
|
||||
@@ -2000,33 +2202,67 @@ button.account-role-badge:focus-visible {
|
||||
|
||||
width: 100%;
|
||||
|
||||
min-height: 40px;
|
||||
min-height: 36px;
|
||||
|
||||
margin-top: 8px;
|
||||
|
||||
text-align: left;
|
||||
padding: 0;
|
||||
|
||||
text-align: center;
|
||||
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.login-account-list {
|
||||
display: grid;
|
||||
|
||||
gap: 8px;
|
||||
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.login-account-row {
|
||||
.login-manage-toolbar {
|
||||
display: flex;
|
||||
|
||||
align-items: center;
|
||||
|
||||
justify-content: space-between;
|
||||
|
||||
min-height: 58px;
|
||||
gap: 12px;
|
||||
|
||||
padding: 0 14px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.login-manage-hint {
|
||||
margin: 0;
|
||||
|
||||
color: var(--text-tertiary);
|
||||
|
||||
font-size: var(--font-size-caption);
|
||||
}
|
||||
|
||||
.login-manage-done {
|
||||
border: 0;
|
||||
|
||||
background: transparent;
|
||||
|
||||
color: var(--action);
|
||||
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.login-account-list {
|
||||
display: grid;
|
||||
|
||||
gap: 10px;
|
||||
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.login-account-row {
|
||||
display: grid;
|
||||
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
|
||||
align-items: center;
|
||||
|
||||
gap: 12px;
|
||||
|
||||
min-height: var(--login-account-row-min);
|
||||
|
||||
padding: 10px 14px;
|
||||
|
||||
border: 1px solid var(--border);
|
||||
|
||||
@@ -2035,6 +2271,10 @@ button.account-role-badge:focus-visible {
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.login-account-row.is-switchable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.login-account-row.is-current {
|
||||
border-color: var(--action);
|
||||
}
|
||||
@@ -2042,33 +2282,147 @@ button.account-role-badge:focus-visible {
|
||||
.login-account-row.is-confirming {
|
||||
display: grid;
|
||||
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
|
||||
gap: 10px;
|
||||
|
||||
padding: 12px 14px;
|
||||
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
.login-avatar {
|
||||
display: grid;
|
||||
|
||||
place-items: center;
|
||||
|
||||
width: var(--login-account-avatar);
|
||||
|
||||
height: var(--login-account-avatar);
|
||||
|
||||
border-radius: 50%;
|
||||
|
||||
color: #fff;
|
||||
|
||||
font-size: var(--font-size-body);
|
||||
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.login-avatar.tone-0 {
|
||||
background: var(--action);
|
||||
}
|
||||
|
||||
.login-avatar.tone-1 {
|
||||
background: var(--market-up);
|
||||
}
|
||||
|
||||
.login-avatar.tone-2 {
|
||||
background: var(--market-down);
|
||||
}
|
||||
|
||||
.login-avatar.tone-3 {
|
||||
background: var(--warning);
|
||||
}
|
||||
|
||||
.login-account-meta {
|
||||
display: grid;
|
||||
|
||||
gap: 2px;
|
||||
gap: 4px;
|
||||
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.login-account-name {
|
||||
display: flex;
|
||||
|
||||
flex-wrap: wrap;
|
||||
|
||||
align-items: center;
|
||||
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.login-account-meta strong {
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.login-account-meta span {
|
||||
.login-account-used {
|
||||
color: var(--text-tertiary);
|
||||
|
||||
font-size: var(--font-size-caption);
|
||||
}
|
||||
|
||||
.login-chip {
|
||||
display: inline-flex;
|
||||
|
||||
align-items: center;
|
||||
|
||||
min-height: 18px;
|
||||
|
||||
padding: 0 6px;
|
||||
|
||||
border-radius: 999px;
|
||||
|
||||
background: var(--surface-muted);
|
||||
|
||||
color: var(--text-secondary);
|
||||
|
||||
font-size: var(--font-size-aux);
|
||||
}
|
||||
|
||||
.login-chip-current {
|
||||
background: var(--action-soft);
|
||||
|
||||
color: var(--action);
|
||||
}
|
||||
|
||||
.login-chip-member {
|
||||
background: var(--warning-soft);
|
||||
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.login-account-check {
|
||||
color: var(--action);
|
||||
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.login-account-action {
|
||||
display: grid;
|
||||
|
||||
justify-items: end;
|
||||
|
||||
gap: 2px;
|
||||
|
||||
color: var(--action);
|
||||
|
||||
font-size: var(--font-size-caption);
|
||||
}
|
||||
|
||||
.login-account-remove {
|
||||
display: grid;
|
||||
|
||||
place-items: center;
|
||||
|
||||
width: 28px;
|
||||
|
||||
height: 28px;
|
||||
|
||||
border: 0;
|
||||
|
||||
background: transparent;
|
||||
|
||||
color: var(--text-tertiary);
|
||||
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.login-account-remove:hover {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.login-confirm-copy {
|
||||
margin: 0;
|
||||
|
||||
@@ -2081,6 +2435,18 @@ button.account-role-badge:focus-visible {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
@media (min-width: 1921px) {
|
||||
.login-brand {
|
||||
width: var(--login-brand-wide-share);
|
||||
|
||||
min-width: var(--login-brand-cap);
|
||||
|
||||
max-width: none;
|
||||
|
||||
flex-basis: var(--login-brand-wide-share);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.login-portal {
|
||||
flex-direction: column;
|
||||
@@ -2089,22 +2455,21 @@ button.account-role-badge:focus-visible {
|
||||
.login-brand {
|
||||
width: 100%;
|
||||
|
||||
min-width: 0;
|
||||
|
||||
max-width: none;
|
||||
|
||||
flex-basis: auto;
|
||||
|
||||
padding: 20px 20px 16px;
|
||||
}
|
||||
|
||||
.login-brand-lead,
|
||||
.login-brand-stats {
|
||||
.login-brand-copy,
|
||||
.login-brand-market,
|
||||
.login-brand-disclaimer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.login-brand-title {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.login-brand-kicker {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.login-stage {
|
||||
padding: 28px 16px 40px;
|
||||
}
|
||||
|
||||
@@ -660,7 +660,9 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
|
||||
|
||||
text-align: left;
|
||||
|
||||
min-height: 38px;
|
||||
height: var(--size-statusbar);
|
||||
|
||||
min-height: var(--size-statusbar);
|
||||
|
||||
display: flex;
|
||||
|
||||
@@ -670,7 +672,7 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
|
||||
|
||||
margin: auto -8px -8px;
|
||||
|
||||
padding: 10px 16px;
|
||||
padding: 0 16px;
|
||||
|
||||
border-right: 0px;
|
||||
|
||||
@@ -691,6 +693,12 @@ 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;
|
||||
}
|
||||
|
||||
@@ -40,17 +40,71 @@ async function loadDashboard(force = false, background = false, showOverlay = tr
|
||||
async function startAdminRefresh() {
|
||||
const buttons = [document.querySelector("#syncButton"), document.querySelector("#adminRefreshButton")].filter(Boolean);
|
||||
buttons.forEach((button) => { button.disabled = true; });
|
||||
const requestedDate = elements.tradeDate.value;
|
||||
setAdminRefreshStatus("running", `正在刷新 ${requestedDate} 的行情,请稍候…`, "loader-circle");
|
||||
try {
|
||||
const payload = await apiRequest("/api/admin/refresh", "POST", { trade_date: elements.tradeDate.value });
|
||||
showToast(payload.message || "后台刷新已提交");
|
||||
setStatus("后台刷新运行中,当前页面保持不变");
|
||||
const payload = await apiRequest("/api/admin/refresh", "POST", { trade_date: requestedDate });
|
||||
if (!payload.started || !payload.job_key) {
|
||||
setAdminRefreshStatus("warning", "已有刷新任务正在运行,请稍后再试。", "clock-3");
|
||||
showToast(payload.message || "已有后台刷新任务正在运行");
|
||||
return;
|
||||
}
|
||||
setStatus(`正在刷新 ${requestedDate} 的行情`);
|
||||
const job = await waitForAdminRefresh(payload.job_key);
|
||||
if (job.status === "failed") {
|
||||
const reason = job.message || job.error_code || "数据源未返回结果";
|
||||
setAdminRefreshStatus("failure", `刷新失败:${reason}`, "circle-x");
|
||||
setStatus("后台刷新失败");
|
||||
showToast("后台刷新失败");
|
||||
return;
|
||||
}
|
||||
const query = new URLSearchParams({ trade_date: requestedDate });
|
||||
const dashboard = await apiRequest(`/api/dashboard?${query}`);
|
||||
applyDashboard(dashboard);
|
||||
const meta = dashboard.meta || {};
|
||||
const actualDate = String(meta.trade_date || "").slice(0, 10);
|
||||
const requestedCompact = requestedDate.replaceAll("-", "");
|
||||
const actualCompact = actualDate.replaceAll("-", "");
|
||||
const updated = formatTimestamp(meta.updated_at);
|
||||
if (actualCompact !== requestedCompact || meta.carried_forward) {
|
||||
const reason = meta.notice ? `;${meta.notice}` : "";
|
||||
setAdminRefreshStatus("warning", `刷新已完成,但没有获取到 ${requestedDate} 的最新行情;当前仍是 ${actualDate || "未知日期"}${reason}`, "triangle-alert");
|
||||
showToast("刷新完成,但未获取到所选日期的最新行情");
|
||||
} else if (meta.notice) {
|
||||
setAdminRefreshStatus("warning", `已刷新到 ${actualDate}(${updated}),但数据源提示:${meta.notice}`, "triangle-alert");
|
||||
showToast(`已刷新到 ${actualDate},请留意数据源提示`);
|
||||
} else {
|
||||
setAdminRefreshStatus("success", `刷新成功:已获取 ${actualDate} 的最新行情,更新时间 ${updated}`, "circle-check");
|
||||
showToast(`刷新成功:已获取 ${actualDate} 的最新行情`);
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(error.message || "后台刷新启动失败");
|
||||
const message = error.message || "后台刷新失败";
|
||||
setAdminRefreshStatus("failure", `刷新失败:${message}`, "circle-x");
|
||||
setStatus("后台刷新失败");
|
||||
showToast(message);
|
||||
} finally {
|
||||
buttons.forEach((button) => { button.disabled = false; });
|
||||
}
|
||||
}
|
||||
|
||||
function setAdminRefreshStatus(tone, message, icon = "circle-dot") {
|
||||
const status = document.querySelector("#adminRefreshStatus");
|
||||
if (!status) return;
|
||||
status.dataset.tone = tone;
|
||||
status.innerHTML = `<i data-lucide="${icon}"></i><span>${escapeHtml(message)}</span>`;
|
||||
refreshIcons();
|
||||
}
|
||||
|
||||
async function waitForAdminRefresh(jobKey) {
|
||||
for (let attempt = 0; attempt < 120; attempt += 1) {
|
||||
const payload = await apiRequest("/api/admin/settings");
|
||||
const job = (payload.data?.jobs || []).find((item) => item.idempotency_key === jobKey);
|
||||
if (job && ["success", "failed"].includes(job.status)) return job;
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
throw new Error("刷新等待超时,请稍后重试");
|
||||
}
|
||||
|
||||
function applyDashboard(payload, background = false) {
|
||||
state.dashboard = payload;
|
||||
const selectedDate = payload.meta.requested_date || payload.meta.trade_date;
|
||||
|
||||
@@ -196,7 +196,13 @@ async function changeAccountPassword(event) {
|
||||
|
||||
async function switchAccount() {
|
||||
toggleAccountDropdown(false);
|
||||
window.location.assign("/login/");
|
||||
const params = new URLSearchParams();
|
||||
const next = `${window.location.pathname}${window.location.search}${window.location.hash}`;
|
||||
if (next.startsWith("/") && !next.startsWith("//") && next !== "/login" && !next.startsWith("/login/") && !next.startsWith("/login?")) {
|
||||
params.set("next", next);
|
||||
}
|
||||
const query = params.toString();
|
||||
window.location.assign("/login/" + (query ? `?${query}` : ""));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1294,7 +1294,9 @@ body.sidebar-collapsed {
|
||||
}
|
||||
|
||||
.sidebar-brand {
|
||||
min-height: 55px;
|
||||
height: var(--size-topbar);
|
||||
|
||||
min-height: var(--size-topbar);
|
||||
|
||||
display: flex;
|
||||
|
||||
@@ -1304,7 +1306,7 @@ body.sidebar-collapsed {
|
||||
|
||||
margin: 0px -8px 7px;
|
||||
|
||||
padding: 0px 16px;
|
||||
padding: 0 16px;
|
||||
|
||||
border-bottom: 1px solid var(--r2-line-soft);
|
||||
|
||||
@@ -2146,13 +2148,17 @@ 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: 14px 16px;
|
||||
padding: 0 16px;
|
||||
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
}
|
||||
@@ -3494,7 +3500,7 @@ body.sidebar-collapsed .status-bar {
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
gap: var(--header-action-gap);
|
||||
margin-left: 0;
|
||||
margin-left: auto;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
|
||||
@@ -147,6 +147,24 @@
|
||||
--duration-fast: 150ms;
|
||||
--duration-normal: 220ms;
|
||||
--login-brand-gradient: linear-gradient(165deg, #0c1e4a, #16307c, #2153cc);
|
||||
--login-brand-share: 34%;
|
||||
--login-brand-min: 420px;
|
||||
--login-brand-cap: 560px;
|
||||
--login-brand-wide-share: 29.2%;
|
||||
--login-brand-pad: 36px 40px 24px;
|
||||
--login-brand-mark-size: 44px;
|
||||
--login-brand-name-size: 16px;
|
||||
--login-hero-size: 28px;
|
||||
--login-card-width: 408px;
|
||||
--login-card-pad: 32px;
|
||||
--login-card-title-size: 22px;
|
||||
--login-account-row-min: 72px;
|
||||
--login-account-avatar: 40px;
|
||||
--login-submit-height: 40px;
|
||||
--login-stat-chip-bg: rgba(8, 12, 24, 0.48);
|
||||
--login-candle-up: #e07078;
|
||||
--login-candle-down: #3db88a;
|
||||
--login-trend-line: rgba(244, 247, 255, 0.88);
|
||||
|
||||
--font-size-aux: 11.5px;
|
||||
--font-size-caption: 12.5px;
|
||||
@@ -516,6 +534,10 @@
|
||||
--warning-line-strong: #66502d;
|
||||
--control-shadow: 0 1px 3px rgba(0, 0, 0, .3);
|
||||
--login-brand-gradient: linear-gradient(165deg, #080c18, #0e1730, #14224a);
|
||||
--login-stat-chip-bg: rgba(6, 8, 16, 0.58);
|
||||
--login-candle-up: #f06d73;
|
||||
--login-candle-down: #43bc8a;
|
||||
--login-trend-line: rgba(232, 236, 244, 0.9);
|
||||
--dialog-backdrop: var(--backdrop);
|
||||
--ladder-level-1: #2d2426;
|
||||
--ladder-level-2: #2b2822;
|
||||
|
||||
@@ -3868,3 +3868,99 @@ 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") });
|
||||
});
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
const { test, expect } = require("@playwright/test");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const SHOT_DIR = path.resolve(__dirname, "../../../verify-shots");
|
||||
fs.mkdirSync(SHOT_DIR, { recursive: true });
|
||||
|
||||
function loginPayload(user) {
|
||||
return {
|
||||
@@ -54,6 +59,15 @@ async function mockLoginPortal(page, options = {}) {
|
||||
return;
|
||||
}
|
||||
if ((url.pathname === "/api/auth/login" || url.pathname === "/api/auth/register") && method === "POST") {
|
||||
if (options.loginDelay) await new Promise((resolve) => setTimeout(resolve, options.loginDelay));
|
||||
if (options.loginFails) {
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ error: "账号名或密码不正确,请重新输入。" }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
@@ -67,14 +81,58 @@ async function mockLoginPortal(page, options = {}) {
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/api/auth/me") {
|
||||
const current = accounts.find((item) => Number(item.user_id) === Number(currentUserId)) || null;
|
||||
const authenticated = Boolean(current) && !options.sessionExpired;
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
ok: true,
|
||||
authenticated: Boolean(currentUserId),
|
||||
authenticated,
|
||||
csrf_token: "portal-csrf",
|
||||
user: accounts.find((item) => Number(item.user_id) === Number(currentUserId)) || null,
|
||||
user: authenticated ? {
|
||||
id: current.user_id,
|
||||
username: current.username,
|
||||
role: current.role,
|
||||
membership: current.membership,
|
||||
} : null,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/api/dashboard") {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
ok: true,
|
||||
meta: {
|
||||
trade_date: "2026-07-22",
|
||||
requested_date: "2026-07-22",
|
||||
source: "tushare",
|
||||
realtime: false,
|
||||
cached: true,
|
||||
market_status: "closed",
|
||||
updated_at: "2026-07-22T15:00:00+08:00",
|
||||
},
|
||||
overview: {
|
||||
up_count: 2100,
|
||||
down_count: 2800,
|
||||
limit_up_count: 42,
|
||||
limit_down_count: 8,
|
||||
broken_count: 17,
|
||||
seal_rate: 71.2,
|
||||
amount_billion: 12600,
|
||||
sentiment_score: 48,
|
||||
},
|
||||
limits: [],
|
||||
broken: [],
|
||||
down_limits: [],
|
||||
yesterday_limits: [],
|
||||
limit_performance: [],
|
||||
ladders: [],
|
||||
sectors: [],
|
||||
sector_rotation: [],
|
||||
}),
|
||||
});
|
||||
return;
|
||||
@@ -149,3 +207,240 @@ test("managing accounts removes a local record after inline confirmation", async
|
||||
await expect(page.locator(".login-account-row")).toHaveCount(1);
|
||||
await expect(page.locator(".login-account-row")).toContainText("alpha_user");
|
||||
});
|
||||
|
||||
async function assertConfirmedSkeleton(page, { width, height }) {
|
||||
await expect(page.locator(".login-brand-title")).toHaveText("看懂情绪周期,把复盘变成下一次的先手。");
|
||||
await expect(page.locator(".login-brand-header")).toBeVisible();
|
||||
await expect(page.locator(".login-brand-chart")).toBeVisible();
|
||||
await expect(page.locator(".login-brand-stats")).toBeVisible();
|
||||
await expect(page.locator(".login-brand-kicker")).toHaveText("收盘之后 · 复盘开始");
|
||||
const brand = await page.locator(".login-brand").boundingBox();
|
||||
const header = await page.locator(".login-brand-header").boundingBox();
|
||||
const mark = await page.locator(".login-brand-mark").boundingBox();
|
||||
const name = await page.locator(".login-brand-name").boundingBox();
|
||||
const title = await page.locator(".login-brand-title").boundingBox();
|
||||
const stats = await page.locator(".login-brand-stats").boundingBox();
|
||||
const chart = await page.locator(".login-brand-chart").boundingBox();
|
||||
const card = await page.locator(".login-card").boundingBox();
|
||||
expect(brand).toBeTruthy();
|
||||
expect(header.y - brand.y).toBeLessThan(48);
|
||||
expect(Math.abs(mark.y - name.y)).toBeLessThan(16);
|
||||
expect(title.y).toBeGreaterThan(height * 0.28);
|
||||
expect(title.y).toBeLessThan(height * 0.72);
|
||||
expect(stats.y).toBeGreaterThan(height * 0.55);
|
||||
expect(chart.height).toBeGreaterThan(80);
|
||||
expect(card.width).toBeGreaterThan(380);
|
||||
expect(card.width).toBeLessThan(450);
|
||||
if (width === 1440) {
|
||||
expect(brand.width).toBeGreaterThan(470);
|
||||
expect(brand.width).toBeLessThan(520);
|
||||
expect(brand.height).toBe(height);
|
||||
} else if (width === 1920) {
|
||||
expect(brand.width).toBeGreaterThan(540);
|
||||
expect(brand.width).toBeLessThan(580);
|
||||
} else {
|
||||
expect(brand.width).toBeGreaterThan(560);
|
||||
}
|
||||
}
|
||||
|
||||
async function openPortal(page, { theme, width, height, accounts, currentUserId, loginFails, loginDelay }) {
|
||||
await page.addInitScript((nextTheme) => {
|
||||
localStorage.setItem("xiaobaiTheme", nextTheme);
|
||||
}, theme);
|
||||
await page.setViewportSize({ width, height });
|
||||
await mockLoginPortal(page, { accounts, currentUserId, loginFails, loginDelay });
|
||||
await page.goto("/login/");
|
||||
}
|
||||
|
||||
for (const theme of ["light", "dark"]) {
|
||||
for (const [width, height] of [[1440, 900], [1920, 1080]]) {
|
||||
test(`confirmed skeleton ${theme} ${width}x${height}`, async ({ page }) => {
|
||||
await openPortal(page, { theme, width, height, accounts: [] });
|
||||
await assertConfirmedSkeleton(page, { width, height });
|
||||
await expect(page.locator("#loginThemeToggle")).toHaveText(theme === "dark" ? "☀ 日间" : "🌙 夜间");
|
||||
await page.screenshot({ path: path.join(SHOT_DIR, `first-${theme}-${width}.png`), fullPage: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test("ultrawide keeps the left brand from collapsing into a strip", async ({ page }) => {
|
||||
await openPortal(page, { theme: "dark", width: 2560, height: 1080, accounts: [] });
|
||||
await assertConfirmedSkeleton(page, { width: 2560, height: 1080 });
|
||||
});
|
||||
|
||||
test("picker add remove error and loading share the same desktop skeleton", async ({ page }) => {
|
||||
const accounts = SAVED_ACCOUNTS.map((item) => ({ ...item }));
|
||||
await openPortal(page, {
|
||||
theme: "dark",
|
||||
width: 1440,
|
||||
height: 900,
|
||||
accounts,
|
||||
currentUserId: 1,
|
||||
});
|
||||
await assertConfirmedSkeleton(page, { width: 1440, height: 900 });
|
||||
await expect(page.locator(".login-card-title")).toHaveText("选择账号");
|
||||
await expect(page.locator(".login-avatar")).toHaveCount(2);
|
||||
await expect(page.locator(".login-add")).toBeVisible();
|
||||
await page.screenshot({ path: path.join(SHOT_DIR, "picker-dark-1440.png"), fullPage: true });
|
||||
|
||||
await page.locator('[data-login-action="add"]').click();
|
||||
await expect(page.locator(".login-card-title")).toHaveText("添加账号");
|
||||
await assertConfirmedSkeleton(page, { width: 1440, height: 900 });
|
||||
await page.screenshot({ path: path.join(SHOT_DIR, "add-dark-1440.png"), fullPage: true });
|
||||
|
||||
await page.locator('[data-login-action="picker"]').click();
|
||||
await page.locator('[data-login-action="manage"]').click();
|
||||
await expect(page.locator(".login-card-title")).toHaveText("管理账号记录");
|
||||
await page.locator('[data-confirm-id="2"]').click();
|
||||
await expect(page.locator(".login-confirm-copy")).toContainText("beta_user");
|
||||
await page.screenshot({ path: path.join(SHOT_DIR, "remove-dark-1440.png"), fullPage: true });
|
||||
});
|
||||
|
||||
test("login failure and loading keep the confirmed first-login skeleton", async ({ page }) => {
|
||||
await openPortal(page, {
|
||||
theme: "light",
|
||||
width: 1440,
|
||||
height: 900,
|
||||
accounts: [],
|
||||
loginFails: true,
|
||||
});
|
||||
await page.locator("#loginUsername").fill("baiqizhi");
|
||||
await page.locator("#loginPassword").fill("wrong-password");
|
||||
await page.locator(".login-submit").click();
|
||||
await expect(page.locator(".login-error")).toContainText("账号名或密码不正确");
|
||||
await expect(page.locator("#loginPassword")).toHaveClass(/is-invalid/);
|
||||
await assertConfirmedSkeleton(page, { width: 1440, height: 900 });
|
||||
await page.screenshot({ path: path.join(SHOT_DIR, "error-light-1440.png"), fullPage: true });
|
||||
});
|
||||
|
||||
test("loading button appears on the confirmed first-login skeleton", async ({ page }) => {
|
||||
await openPortal(page, {
|
||||
theme: "dark",
|
||||
width: 1440,
|
||||
height: 900,
|
||||
accounts: [],
|
||||
loginDelay: 2500,
|
||||
});
|
||||
await page.evaluate(() => {
|
||||
window.location.replace = () => {};
|
||||
});
|
||||
await page.locator("#loginUsername").fill("baiqizhi");
|
||||
await page.locator("#loginPassword").fill("password12");
|
||||
const submit = page.locator(".login-submit").click();
|
||||
await expect(page.locator(".login-submit")).toContainText("正在登录...");
|
||||
await expect(page.locator(".login-spinner")).toBeVisible();
|
||||
await assertConfirmedSkeleton(page, { width: 1440, height: 900 });
|
||||
await page.screenshot({ path: path.join(SHOT_DIR, "loading-dark-1440.png"), fullPage: true });
|
||||
await submit;
|
||||
});
|
||||
|
||||
async function openPicker(page, options = {}) {
|
||||
const accounts = options.accounts || SAVED_ACCOUNTS.map((item) => ({ ...item }));
|
||||
const currentUserId = options.currentUserId ?? 1;
|
||||
const next = options.next || "/index.html?view=sentimentCycleView";
|
||||
await page.unroute("**/api/**").catch(() => {});
|
||||
await mockLoginPortal(page, {
|
||||
accounts,
|
||||
currentUserId,
|
||||
sessionExpired: options.sessionExpired,
|
||||
switchFails: options.switchFails,
|
||||
});
|
||||
await page.goto(`/login/?next=${encodeURIComponent(next)}`);
|
||||
await expect(page.locator(".login-card-title")).toHaveText("选择账号");
|
||||
}
|
||||
|
||||
test("clicking the current account from two workspace pages returns without switching", async ({ page }) => {
|
||||
const views = ["sentimentCycleView", "ladderView"];
|
||||
for (const viewId of views) {
|
||||
const next = `/index.html?view=${viewId}`;
|
||||
const switchCalls = [];
|
||||
const onRequest = (request) => {
|
||||
if (request.url().includes("/api/auth/switch") && request.method() === "POST") {
|
||||
switchCalls.push(request);
|
||||
}
|
||||
};
|
||||
page.on("request", onRequest);
|
||||
await openPicker(page, { next });
|
||||
await expect(page.locator('[data-resume-id="1"]')).toContainText("继续使用");
|
||||
await expect(page.locator('[data-resume-id="1"]')).toContainText("当前");
|
||||
await page.locator('[data-resume-id="1"]').click();
|
||||
await expect(page).toHaveURL(new RegExp(`[?&]view=${viewId}\\b`));
|
||||
expect(switchCalls).toEqual([]);
|
||||
page.off("request", onRequest);
|
||||
}
|
||||
});
|
||||
|
||||
test("a lone current account can return from the picker instead of dead-ending", async ({ page }) => {
|
||||
await openPicker(page, {
|
||||
accounts: [SAVED_ACCOUNTS[0]],
|
||||
currentUserId: 1,
|
||||
next: "/index.html?view=reviewWorkspaceView",
|
||||
});
|
||||
await expect(page.locator(".login-account-row")).toHaveCount(1);
|
||||
await expect(page.locator('[data-switch-id]')).toHaveCount(0);
|
||||
await page.locator('[data-resume-id="1"]').click();
|
||||
await expect(page).toHaveURL(/view=reviewWorkspaceView/);
|
||||
});
|
||||
|
||||
test("the return control also restores the originating workspace page", async ({ page }) => {
|
||||
await openPicker(page, { next: "/index.html?view=ladderView" });
|
||||
await page.locator('[data-login-action="resume"]').click();
|
||||
await expect(page).toHaveURL(/view=ladderView/);
|
||||
});
|
||||
|
||||
test("refreshing the picker still returns to the originating page", async ({ page }) => {
|
||||
await openPicker(page, { next: "/index.html?view=sentimentCycleView" });
|
||||
await page.reload();
|
||||
await expect(page.locator(".login-card-title")).toHaveText("选择账号");
|
||||
await page.locator('[data-resume-id="1"]').click();
|
||||
await expect(page).toHaveURL(/view=sentimentCycleView/);
|
||||
});
|
||||
|
||||
test("an expired current session asks for login instead of pretending to return", async ({ page }) => {
|
||||
await openPicker(page, {
|
||||
next: "/index.html?view=sentimentCycleView",
|
||||
sessionExpired: true,
|
||||
});
|
||||
await page.locator('[data-resume-id="1"]').click();
|
||||
await expect(page.locator(".login-error")).toHaveText("当前会话已失效,请重新登录");
|
||||
await expect(page).toHaveURL(/\/login\/?/);
|
||||
});
|
||||
|
||||
test("other saved accounts still switch while the current row only resumes", async ({ page }) => {
|
||||
await openPicker(page, { next: "/index.html?view=auctionView" });
|
||||
const switched = page.waitForRequest((request) => (
|
||||
request.url().includes("/api/auth/switch") && request.method() === "POST"
|
||||
));
|
||||
await page.locator('[data-switch-id="2"]').click();
|
||||
const request = await switched;
|
||||
expect(JSON.parse(request.postData() || "{}")).toEqual({ user_id: 2 });
|
||||
});
|
||||
|
||||
test("workspace switch-account menu carries the current page back to the picker", async ({ page }) => {
|
||||
await mockLoginPortal(page, {
|
||||
accounts: SAVED_ACCOUNTS.map((item) => ({ ...item })),
|
||||
currentUserId: 1,
|
||||
});
|
||||
await page.goto("/index.html?view=sentimentCycleView");
|
||||
await expect(page.locator("#accountButton")).toBeVisible();
|
||||
await page.locator("#accountButton").click();
|
||||
await page.locator("#switchAccountMenuButton").click();
|
||||
await expect(page).toHaveURL(/\/login\/\?next=/);
|
||||
await expect(page.locator(".login-card-title")).toHaveText("选择账号");
|
||||
await page.locator('[data-resume-id="1"]').click();
|
||||
await expect(page).toHaveURL(/view=sentimentCycleView/);
|
||||
});
|
||||
|
||||
test("workspace switch-account from a second page also returns to that page", async ({ page }) => {
|
||||
await mockLoginPortal(page, {
|
||||
accounts: SAVED_ACCOUNTS.map((item) => ({ ...item })),
|
||||
currentUserId: 1,
|
||||
});
|
||||
await page.goto("/index.html?view=ladderView");
|
||||
await expect(page.locator("#accountButton")).toBeVisible();
|
||||
await page.locator("#accountButton").click();
|
||||
await page.locator("#switchAccountMenuButton").click();
|
||||
await expect(page.locator(".login-card-title")).toHaveText("选择账号");
|
||||
await page.locator('[data-resume-id="1"]').click();
|
||||
await expect(page).toHaveURL(/view=ladderView/);
|
||||
});
|
||||
|
||||
@@ -138,6 +138,11 @@ async function mockMobileApi(page, options = {}) {
|
||||
payload = { items: [] };
|
||||
} else if (path === "/api/search") {
|
||||
payload = { groups: { stocks: [{ id: "002141", code: "002141", name: "贤丰控股", type: "stock", industry: "电子元件" }], sectors: [], themes: [], indices: [] } };
|
||||
} else if (path === "/api/auth/accounts") {
|
||||
payload = {
|
||||
accounts: [{ user_id: auth.user.id, username: auth.user.username, role: auth.user.role, last_used_at: "2026-07-22T09:12:00+08:00" }],
|
||||
current_user_id: auth.user.id,
|
||||
};
|
||||
} else if (path === "/api/account/status") {
|
||||
payload = {
|
||||
birth_profile_configured: true,
|
||||
@@ -284,12 +289,16 @@ test("mobile login renders before authentication", async ({ page }) => {
|
||||
test("four hub pages render their icon grids", async ({ page }) => {
|
||||
await mockMobileApi(page);
|
||||
await openMobile(page);
|
||||
for (const hub of ["market", "tools", "review", "system"]) {
|
||||
for (const hub of ["market", "tools", "review"]) {
|
||||
await page.evaluate((h) => { window.MobileRouter.navigate("#/hub/" + h); }, hub);
|
||||
await expect(page.locator(".m-hub-grid")).toBeVisible();
|
||||
await expect(page.locator(".m-hub-grid .m-grid-item").first()).toBeVisible();
|
||||
expect(await measureOverflow(page)).toBeLessThanOrEqual(1);
|
||||
}
|
||||
await page.evaluate(() => { window.MobileRouter.navigate("#/hub/system"); });
|
||||
await expect(page.locator("[data-system-page='home']")).toBeVisible();
|
||||
await expect(page.locator(".m-sys-row").first()).toBeVisible();
|
||||
expect(await measureOverflow(page)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
for (const theme of ["day", "night"]) {
|
||||
@@ -344,7 +353,7 @@ test("system management pages render real content instead of placeholders", asyn
|
||||
}
|
||||
await navigateToFeature(page, "system/profile");
|
||||
await expect(page.locator("#m-sys-birth-date")).toBeVisible();
|
||||
await expect(page.locator("[data-system-switch]")).toBeVisible();
|
||||
await expect(page.locator("[data-system-save-birth]")).toBeVisible();
|
||||
await navigateToFeature(page, "system/password");
|
||||
await expect(page.locator("#m-sys-password-current")).toBeVisible();
|
||||
await navigateToFeature(page, "system/membership");
|
||||
@@ -355,7 +364,64 @@ test("system management pages render real content instead of placeholders", asyn
|
||||
await expect(page.locator("#m-sys-member-limit")).toBeVisible();
|
||||
});
|
||||
|
||||
test("empty profile save click shows a toast instead of a dead button", async ({ page }) => {
|
||||
test("system home groups entries and keeps admin-only items gated", async ({ page }) => {
|
||||
await mockMobileApi(page);
|
||||
await openMobile(page);
|
||||
await page.evaluate(() => { window.MobileRouter.navigate("#/hub/system"); });
|
||||
await expect(page.locator("[data-system-page='home']")).toBeVisible();
|
||||
await expect(page.locator("#m-view")).toContainText("账号");
|
||||
await expect(page.locator("#m-view")).toContainText("偏好");
|
||||
await expect(page.locator("#m-view")).toContainText("管理员专区");
|
||||
await expect(page.locator("[data-theme-toggle]")).toBeVisible();
|
||||
await expect(page.locator("[data-system-switch]")).toBeVisible();
|
||||
expect(await measureOverflow(page)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("system settings tabs, model editor, delete confirm and theme toggle work", async ({ page }) => {
|
||||
await mockMobileApi(page);
|
||||
await openMobile(page);
|
||||
await navigateToFeature(page, "system/admin");
|
||||
await expect(page.locator("[data-system-admin-panel='market']")).toBeVisible();
|
||||
await page.locator("[data-system-admin-tab='models']").click();
|
||||
await expect(page.locator("[data-system-admin-panel='models']")).toBeVisible();
|
||||
await page.locator("[data-system-edit-model]").first().click();
|
||||
await expect(page.locator(".m-sheet-root.is-open")).toBeVisible();
|
||||
await expect(page.locator(".m-sheet-head h2")).toHaveText("编辑模型");
|
||||
await page.locator("[data-sheet-close]").click();
|
||||
await page.locator("[data-system-admin-tab='market']").click();
|
||||
await expect(page.locator("#m-sys-token")).toBeVisible();
|
||||
|
||||
await navigateToFeature(page, "system/profile");
|
||||
await page.locator("[data-system-delete-birth]").click();
|
||||
await expect(page.locator(".m-dialog")).toBeVisible();
|
||||
await expect(page.locator(".m-dialog")).toContainText("删除命理资料");
|
||||
await page.locator("[data-sheet-close]").click();
|
||||
|
||||
await page.evaluate(() => { window.MobileRouter.navigate("#/hub/system"); });
|
||||
await expect(page.locator("[data-theme-toggle]")).toBeVisible();
|
||||
const before = await page.locator("#m-app").getAttribute("data-theme");
|
||||
await page.locator("[data-theme-toggle]").click();
|
||||
await expect.poll(async () => page.locator("#m-app").getAttribute("data-theme")).not.toBe(before);
|
||||
|
||||
await navigateToFeature(page, "system/members");
|
||||
await page.locator("[data-system-open-member]").click();
|
||||
await expect(page.locator(".m-sheet-root.is-open")).toBeVisible();
|
||||
await expect(page.locator(".m-sheet-head h2")).toContainText("管理会员");
|
||||
});
|
||||
|
||||
test("password mismatch shows inline error instead of a silent submit", async ({ page }) => {
|
||||
await mockMobileApi(page);
|
||||
await openMobile(page);
|
||||
await navigateToFeature(page, "system/password");
|
||||
await page.locator("#m-sys-password-current").fill("OldPass12");
|
||||
await page.locator("#m-sys-password-new").fill("NewPass123");
|
||||
await page.locator("#m-sys-password-confirm").fill("OtherPass123");
|
||||
await page.locator("[data-system-save-password]").click();
|
||||
await expect(page.locator("[data-field-error='confirm']")).toBeVisible();
|
||||
await expect(page.locator("[data-field-error='confirm']")).toContainText("两次输入的密码不一致");
|
||||
});
|
||||
|
||||
test("empty birth profile save shows a validation toast", async ({ page }) => {
|
||||
await mockMobileApi(page);
|
||||
await openMobile(page);
|
||||
await navigateToFeature(page, "system/profile");
|
||||
@@ -371,9 +437,10 @@ test("non-admin cannot open system admin pages as placeholders", async ({ page }
|
||||
await mockMobileApi(page, { auth: authSession("user", true) });
|
||||
await openMobile(page);
|
||||
await page.evaluate(() => { window.MobileRouter.navigate("#/hub/system"); });
|
||||
await expect(page.locator(".m-hub-grid")).toBeVisible();
|
||||
await expect(page.locator('.m-grid-item[data-route="#/feature/system/admin"]')).toHaveCount(0);
|
||||
await expect(page.locator('.m-grid-item[data-route="#/feature/system/members"]')).toHaveCount(0);
|
||||
await expect(page.locator("[data-system-page='home']")).toBeVisible();
|
||||
await expect(page.locator('[data-route="#/feature/system/admin"]')).toHaveCount(0);
|
||||
await expect(page.locator('[data-route="#/feature/system/members"]')).toHaveCount(0);
|
||||
await expect(page.locator("[data-system-switch]")).toBeVisible();
|
||||
await navigateToFeature(page, "system/admin");
|
||||
await expect(page.locator("#m-view")).not.toContainText(PLACEHOLDER_COPY);
|
||||
await expect(page.locator("[data-system-page='forbidden']")).toBeVisible();
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from backend.jobs.service import _verified_dashboard_result
|
||||
|
||||
|
||||
class AdminRefreshStatusTests(unittest.TestCase):
|
||||
def test_carried_snapshot_is_reported_as_failed_job(self):
|
||||
result = _verified_dashboard_result(
|
||||
{"meta": {"carried_forward": True, "notice": "官方涨跌停数据尚未返回"}}
|
||||
)
|
||||
|
||||
self.assertEqual(result["status"], "failed")
|
||||
self.assertEqual(result["error"], "官方涨跌停数据尚未返回")
|
||||
|
||||
def test_current_snapshot_is_reported_as_successful_job(self):
|
||||
dashboard = {"meta": {"trade_date": "2026-08-28", "carried_forward": False}}
|
||||
|
||||
self.assertIs(_verified_dashboard_result(dashboard), dashboard)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,124 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CHECK = ROOT / "tools" / "check_deploy_baseline.sh"
|
||||
BUILD = ROOT / "tools" / "build_image.sh"
|
||||
|
||||
|
||||
def run_check(repo: Path, candidate: str, live: str) -> subprocess.CompletedProcess[str]:
|
||||
env = os.environ.copy()
|
||||
env["GIT_DIR"] = str(repo / ".git")
|
||||
env["GIT_WORK_TREE"] = str(repo)
|
||||
return subprocess.run(
|
||||
["bash", str(CHECK), candidate, "--live-revision", live],
|
||||
cwd=repo,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env=env,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def git(repo: Path, *args: str) -> str:
|
||||
result = subprocess.run(
|
||||
["git", *args],
|
||||
cwd=repo,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
class DeployBaselineGateTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.tmpdir = tempfile.TemporaryDirectory()
|
||||
cls.repo = Path(cls.tmpdir.name) / "repo"
|
||||
cls.repo.mkdir()
|
||||
git(cls.repo, "init")
|
||||
git(cls.repo, "config", "user.email", "gate@example.com")
|
||||
git(cls.repo, "config", "user.name", "Gate")
|
||||
(cls.repo / "README").write_text("base\n", encoding="utf-8")
|
||||
git(cls.repo, "add", "README")
|
||||
git(cls.repo, "commit", "-m", "base")
|
||||
cls.base = git(cls.repo, "rev-parse", "HEAD")
|
||||
|
||||
(cls.repo / "online.txt").write_text("live\n", encoding="utf-8")
|
||||
git(cls.repo, "add", "online.txt")
|
||||
git(cls.repo, "commit", "-m", "online")
|
||||
cls.live = git(cls.repo, "rev-parse", "HEAD")
|
||||
|
||||
git(cls.repo, "checkout", "-b", "successor")
|
||||
(cls.repo / "next.txt").write_text("next\n", encoding="utf-8")
|
||||
git(cls.repo, "add", "next.txt")
|
||||
git(cls.repo, "commit", "-m", "successor of live")
|
||||
cls.successor = git(cls.repo, "rev-parse", "HEAD")
|
||||
|
||||
git(cls.repo, "checkout", "-B", "lagging-main", cls.base)
|
||||
(cls.repo / "stale.txt").write_text("stale main\n", encoding="utf-8")
|
||||
git(cls.repo, "add", "stale.txt")
|
||||
git(cls.repo, "commit", "-m", "lagging main")
|
||||
cls.lagging = git(cls.repo, "rev-parse", "HEAD")
|
||||
|
||||
git(cls.repo, "checkout", "-B", "side", cls.base)
|
||||
(cls.repo / "side.txt").write_text("side branch\n", encoding="utf-8")
|
||||
git(cls.repo, "add", "side.txt")
|
||||
git(cls.repo, "commit", "-m", "unrelated side branch")
|
||||
cls.side = git(cls.repo, "rev-parse", "HEAD")
|
||||
|
||||
git(cls.repo, "checkout", "-B", "successor", cls.successor)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.tmpdir.cleanup()
|
||||
|
||||
def test_check_script_is_executable(self) -> None:
|
||||
self.assertTrue(CHECK.exists())
|
||||
self.assertTrue(stat.S_IXUSR & CHECK.stat().st_mode)
|
||||
|
||||
def test_successor_of_live_passes(self) -> None:
|
||||
result = run_check(self.repo, self.successor, self.live)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn(self.live, result.stdout)
|
||||
self.assertIn(self.successor, result.stdout)
|
||||
self.assertIn("next.txt", result.stdout)
|
||||
self.assertIn("祖先关系通过", result.stdout)
|
||||
|
||||
def test_lagging_main_is_blocked(self) -> None:
|
||||
result = run_check(self.repo, self.lagging, self.live)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("拒绝", result.stderr)
|
||||
|
||||
def test_side_branch_is_blocked(self) -> None:
|
||||
result = run_check(self.repo, self.side, self.live)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("拒绝", result.stderr)
|
||||
|
||||
def test_unknown_commit_is_blocked(self) -> None:
|
||||
result = run_check(self.repo, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", self.live)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("无法解析", result.stderr)
|
||||
|
||||
def test_build_image_calls_the_gate_and_rejects_latest(self) -> None:
|
||||
source = BUILD.read_text(encoding="utf-8")
|
||||
self.assertIn("check_deploy_baseline.sh", source)
|
||||
self.assertIn("禁止构建 latest", source)
|
||||
self.assertIn("org.opencontainers.image.revision", source)
|
||||
gate = CHECK.read_text(encoding="utf-8")
|
||||
self.assertIn("org.opencontainers.image.revision", gate)
|
||||
self.assertIn("merge-base --is-ancestor", gate)
|
||||
self.assertIn("候选将丢失的提交", gate)
|
||||
self.assertIn("禁止人工填写", gate)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,13 +1,162 @@
|
||||
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.knowledge import prepare_heaven_context
|
||||
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.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(
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOGIN = (ROOT / "frontend" / "login" / "index.html").read_text(encoding="utf-8")
|
||||
LOGIN_JS = (ROOT / "frontend" / "login" / "page.js").read_text(encoding="utf-8")
|
||||
AUTH = (ROOT / "frontend" / "shared" / "auth.css").read_text(encoding="utf-8")
|
||||
TOKENS = (ROOT / "frontend" / "shared" / "tokens.css").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
class LoginPortalContractTests(unittest.TestCase):
|
||||
def test_confirmed_brand_skeleton_is_in_markup(self) -> None:
|
||||
for needle in (
|
||||
'class="login-brand-header"',
|
||||
'class="login-brand-name"',
|
||||
"A股个人复盘工作台",
|
||||
'class="login-brand-kicker"',
|
||||
"看懂情绪周期,把复盘变成下一次的先手。",
|
||||
'class="login-brand-chart"',
|
||||
'class="login-brand-stats"',
|
||||
"股市有风险,投资需谨慎",
|
||||
'id="loginThemeToggle"',
|
||||
'id="loginCard"',
|
||||
):
|
||||
self.assertIn(needle, LOGIN)
|
||||
|
||||
def test_login_tokens_own_the_confirmed_layout_metrics(self) -> None:
|
||||
for needle in (
|
||||
"--login-brand-share: 34%;",
|
||||
"--login-brand-cap: 560px;",
|
||||
"--login-brand-wide-share: 29.2%;",
|
||||
"--login-card-width: 408px;",
|
||||
"--login-hero-size: 28px;",
|
||||
"--login-account-row-min: 72px;",
|
||||
):
|
||||
self.assertIn(needle, TOKENS)
|
||||
self.assertIn("width: var(--login-brand-share);", AUTH)
|
||||
self.assertIn("width: var(--login-card-width);", AUTH)
|
||||
self.assertIn("justify-content: flex-end;", AUTH)
|
||||
self.assertIn("body.login-portal {", AUTH)
|
||||
self.assertIn("padding-bottom: 0;", AUTH)
|
||||
self.assertNotIn("padding: 0 0 var(--statusbar-height);", AUTH)
|
||||
|
||||
def test_portal_keeps_account_switch_and_theme_hooks(self) -> None:
|
||||
self.assertIn("data-switch-id", LOGIN_JS)
|
||||
self.assertIn("data-resume-id", LOGIN_JS)
|
||||
self.assertIn('data-login-action="manage"', LOGIN_JS)
|
||||
self.assertIn('data-login-action="add"', LOGIN_JS)
|
||||
self.assertIn('data-login-action="resume"', LOGIN_JS)
|
||||
self.assertIn("继续使用", LOGIN_JS)
|
||||
self.assertIn("返回复盘", LOGIN_JS)
|
||||
self.assertIn("/api/auth/me", LOGIN_JS)
|
||||
self.assertIn("xiaobaiTheme", LOGIN_JS)
|
||||
self.assertNotIn("内网个人版", LOGIN)
|
||||
self.assertNotIn("192.168.200.11", LOGIN)
|
||||
self.assertNotIn("/api/heaven", LOGIN_JS)
|
||||
|
||||
def test_current_account_row_stays_clickable_without_reswitching(self) -> None:
|
||||
self.assertIn("resumeCurrentAccount", LOGIN_JS)
|
||||
self.assertIn("当前会话已失效,请重新登录", LOGIN_JS)
|
||||
self.assertNotIn("!managing && !current ? \"is-switchable\"", LOGIN_JS)
|
||||
session = (ROOT / "frontend" / "shared" / "session.js").read_text(encoding="utf-8")
|
||||
self.assertIn('params.set("next", next)', session)
|
||||
self.assertIn(".login-account-action", AUTH)
|
||||
@@ -43,6 +43,7 @@ class MobileSystemPagesRegressionTests(unittest.TestCase):
|
||||
def test_system_pages_render_real_controls_not_stubs(self) -> None:
|
||||
pages = PAGES.read_text(encoding="utf-8")
|
||||
for marker in (
|
||||
'data-system-page="home"',
|
||||
'data-system-page="profile"',
|
||||
'data-system-page="password"',
|
||||
'data-system-page="membership"',
|
||||
@@ -54,6 +55,11 @@ class MobileSystemPagesRegressionTests(unittest.TestCase):
|
||||
"m-sys-token",
|
||||
"m-sys-member-limit",
|
||||
"data-system-switch",
|
||||
"data-system-edit-model",
|
||||
"data-system-open-member",
|
||||
"管理员专区",
|
||||
"保存密钥",
|
||||
"保存分工",
|
||||
'location.assign("/login/")',
|
||||
):
|
||||
self.assertIn(marker, pages)
|
||||
@@ -73,6 +79,8 @@ class MobileSystemPagesRegressionTests(unittest.TestCase):
|
||||
"data-system-save-models",
|
||||
"data-system-save-market",
|
||||
"data-system-refresh",
|
||||
"data-system-toggle-refresh",
|
||||
"data-system-save-model",
|
||||
):
|
||||
self.assertIn(name, pages)
|
||||
self.assertNotIn(name + '">', pages)
|
||||
|
||||
@@ -111,6 +111,25 @@ class RealtimeDashboardTests(unittest.TestCase):
|
||||
self.assertEqual(quote["amount_billion"], 3.0)
|
||||
self.assertAlmostEqual(quote["turnover_rate"], 0.01)
|
||||
|
||||
def test_close_dashboard_marks_official_limit_data(self):
|
||||
dashboard = self.client.dashboard("20260720")
|
||||
|
||||
self.assertEqual(dashboard["meta"]["limit_data_source"], "official")
|
||||
|
||||
def test_close_dashboard_marks_derived_limit_data_as_incomplete(self):
|
||||
original_query = self.client.query
|
||||
|
||||
def query(api_name, params=None, fields=""):
|
||||
if api_name == "limit_list_d":
|
||||
return []
|
||||
return original_query(api_name, params, fields)
|
||||
|
||||
self.client.query = query
|
||||
dashboard = self.client.dashboard("20260720")
|
||||
|
||||
self.assertEqual(dashboard["meta"]["limit_data_source"], "derived")
|
||||
self.assertIn("日线数据推算", dashboard["meta"]["notice"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.features.market.backfill_history import (
|
||||
build_backfill_audit,
|
||||
classify_snapshot_coverage,
|
||||
create_sqlite_backup,
|
||||
select_open_trade_dates,
|
||||
select_open_trade_dates_in_range,
|
||||
)
|
||||
from backend.features.market.service import MarketServiceMixin
|
||||
from backend.features.sentiment.engine import (
|
||||
build_sentiment_history,
|
||||
latest_contiguous_history,
|
||||
)
|
||||
from backend.features.sentiment.service import SentimentServiceMixin
|
||||
from database import ReviewDatabase
|
||||
|
||||
|
||||
def _snapshot(trade_date: str, previous_trade_date: str) -> dict[str, Any]:
|
||||
display = f"{trade_date[:4]}-{trade_date[4:6]}-{trade_date[6:8]}"
|
||||
previous_display = (
|
||||
f"{previous_trade_date[:4]}-{previous_trade_date[4:6]}-{previous_trade_date[6:8]}"
|
||||
if previous_trade_date
|
||||
else ""
|
||||
)
|
||||
return {
|
||||
"meta": {
|
||||
"trade_date": display,
|
||||
"previous_trade_date": previous_display,
|
||||
"source": "tushare",
|
||||
},
|
||||
"overview": {
|
||||
"up_count": 2500,
|
||||
"down_count": 2000,
|
||||
"flat_count": 100,
|
||||
"amount_billion": 12000,
|
||||
"limit_up_count": 40,
|
||||
"limit_down_count": 5,
|
||||
"broken_count": 10,
|
||||
"seal_rate": 70,
|
||||
"max_height": 3,
|
||||
"second_board_count": 8,
|
||||
"three_plus_count": 4,
|
||||
"previous_limit_count": 35,
|
||||
"previous_positive_rate": 55,
|
||||
"average_previous_change": 1.2,
|
||||
"median_previous_change": 0.8,
|
||||
"advance_rate": 20,
|
||||
"severe_loss_rate": 5,
|
||||
"previous_down_count": 3,
|
||||
"ladder_completeness": 60,
|
||||
"limit_amount_billion": 300,
|
||||
},
|
||||
"limits": [{"code": "000001"}],
|
||||
"broken": [],
|
||||
"down_limits": [],
|
||||
"yesterday_limits": [],
|
||||
}
|
||||
|
||||
|
||||
class _BackfillHarness(MarketServiceMixin, SentimentServiceMixin):
|
||||
def __init__(self, database: ReviewDatabase) -> None:
|
||||
self.database = database
|
||||
self.sync_lock = threading.Lock()
|
||||
self.configured = True
|
||||
self.token = "test-token"
|
||||
self.current_user_id = 1
|
||||
self._calendar_rows: list[dict[str, Any]] = []
|
||||
self._fail_dates: set[str] = set()
|
||||
self.sync_calls: list[str] = []
|
||||
|
||||
def _tushare_client(self): # type: ignore[override]
|
||||
harness = self
|
||||
|
||||
class _Client:
|
||||
def query(self, api_name, params, fields=""):
|
||||
assert api_name == "trade_cal"
|
||||
start = str(params["start_date"])
|
||||
end = str(params["end_date"])
|
||||
return [
|
||||
row
|
||||
for row in harness._calendar_rows
|
||||
if start <= str(row["cal_date"]) <= end
|
||||
]
|
||||
|
||||
return _Client()
|
||||
|
||||
def sync_dashboard(self, trade_date: str) -> dict[str, Any]: # type: ignore[override]
|
||||
compact = trade_date.replace("-", "")
|
||||
self.sync_calls.append(compact)
|
||||
if compact in self._fail_dates:
|
||||
raise ValueError(f"simulated failure for {compact}")
|
||||
previous = ""
|
||||
for row in self._calendar_rows:
|
||||
if str(row["cal_date"]) == compact:
|
||||
previous = str(row.get("pretrade_date") or "")
|
||||
break
|
||||
payload = _snapshot(compact, previous)
|
||||
self.database.save_snapshot(compact, "tushare", payload)
|
||||
return payload
|
||||
|
||||
def _apply_reason_overrides(self, dashboard: dict[str, Any]) -> dict[str, Any]:
|
||||
return dashboard
|
||||
|
||||
def _with_storage(self, dashboard: dict[str, Any], cached: bool) -> dict[str, Any]:
|
||||
return dashboard
|
||||
|
||||
|
||||
class BackfillHistoryHelperTests(unittest.TestCase):
|
||||
def test_select_open_trade_dates_skips_weekends_and_holidays(self) -> None:
|
||||
rows = [
|
||||
{"cal_date": "20260821", "is_open": 1, "pretrade_date": "20260820"},
|
||||
{"cal_date": "20260822", "is_open": 0, "pretrade_date": "20260821"}, # Sat
|
||||
{"cal_date": "20260823", "is_open": 0, "pretrade_date": "20260821"}, # Sun
|
||||
{"cal_date": "20260824", "is_open": 1, "pretrade_date": "20260821"},
|
||||
{"cal_date": "20260825", "is_open": 1, "pretrade_date": "20260824"},
|
||||
{"cal_date": "20260826", "is_open": 1, "pretrade_date": "20260825"},
|
||||
{"cal_date": "20260827", "is_open": 1, "pretrade_date": "20260826"},
|
||||
]
|
||||
selected = select_open_trade_dates(rows, "20260827", 4)
|
||||
self.assertEqual(selected, ["20260824", "20260825", "20260826", "20260827"])
|
||||
|
||||
def test_range_mode_reports_non_trading_days_separately(self) -> None:
|
||||
rows = [
|
||||
{"cal_date": "20260821", "is_open": 1},
|
||||
{"cal_date": "20260824", "is_open": 1},
|
||||
]
|
||||
open_dates, skipped = select_open_trade_dates_in_range(
|
||||
rows, "20260821", "20260824"
|
||||
)
|
||||
self.assertEqual(open_dates, ["20260821", "20260824"])
|
||||
self.assertEqual(skipped, ["20260822", "20260823"])
|
||||
|
||||
def test_classify_snapshot_coverage_finds_real_gaps(self) -> None:
|
||||
coverage = classify_snapshot_coverage(
|
||||
["20260824", "20260825", "20260826", "20260827"],
|
||||
["20260824", "20260827"],
|
||||
)
|
||||
self.assertEqual(coverage["missing"], ["20260825", "20260826"])
|
||||
self.assertEqual(coverage["present"], ["20260824", "20260827"])
|
||||
|
||||
|
||||
class ContiguousHistoryGapTests(unittest.TestCase):
|
||||
def test_missing_previous_trade_day_collapses_to_today(self) -> None:
|
||||
payloads = [
|
||||
_snapshot("20260824", "20260821"),
|
||||
_snapshot("20260827", "20260826"), # gap: 20260826 missing
|
||||
]
|
||||
series = latest_contiguous_history(build_sentiment_history(payloads))
|
||||
self.assertEqual([row["trade_date"] for row in series], ["20260827"])
|
||||
|
||||
def test_continuous_history_keeps_full_tail(self) -> None:
|
||||
payloads = [
|
||||
_snapshot("20260825", "20260824"),
|
||||
_snapshot("20260826", "20260825"),
|
||||
_snapshot("20260827", "20260826"),
|
||||
]
|
||||
series = latest_contiguous_history(build_sentiment_history(payloads))
|
||||
self.assertEqual(
|
||||
[row["trade_date"] for row in series],
|
||||
["20260825", "20260826", "20260827"],
|
||||
)
|
||||
|
||||
|
||||
class SnapshotBackfillServiceTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.db_path = Path(self.temporary.name) / "review.db"
|
||||
self.database = ReviewDatabase(self.db_path)
|
||||
self.service = _BackfillHarness(self.database)
|
||||
self.service._calendar_rows = [
|
||||
{"cal_date": "20260820", "is_open": 1, "pretrade_date": "20260819"},
|
||||
{"cal_date": "20260821", "is_open": 1, "pretrade_date": "20260820"},
|
||||
{"cal_date": "20260822", "is_open": 0, "pretrade_date": "20260821"},
|
||||
{"cal_date": "20260823", "is_open": 0, "pretrade_date": "20260821"},
|
||||
{"cal_date": "20260824", "is_open": 1, "pretrade_date": "20260821"},
|
||||
{"cal_date": "20260825", "is_open": 1, "pretrade_date": "20260824"},
|
||||
{"cal_date": "20260826", "is_open": 1, "pretrade_date": "20260825"},
|
||||
{"cal_date": "20260827", "is_open": 1, "pretrade_date": "20260826"},
|
||||
]
|
||||
# Sparse history mimicking .11: keep 0824 and today, miss 0825/0826.
|
||||
self.database.save_snapshot("20260824", "tushare", _snapshot("20260824", "20260821"))
|
||||
self.database.save_snapshot("20260827", "tushare", _snapshot("20260827", "20260826"))
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.temporary.cleanup()
|
||||
|
||||
def test_recent_backfill_fills_gap_and_restores_history(self) -> None:
|
||||
before = self.service.sentiment_history("20260827", 20)
|
||||
self.assertEqual(before["available_days"], 1)
|
||||
|
||||
with patch(
|
||||
"backend.features.market.service.create_sqlite_backup",
|
||||
return_value=Path(self.temporary.name) / "fake-backup.db",
|
||||
) as backup:
|
||||
audit = self.service.backfill_recent_trading_days(
|
||||
end_date="20260827",
|
||||
lookback=4,
|
||||
dry_run=False,
|
||||
create_backup=True,
|
||||
)
|
||||
|
||||
backup.assert_called_once()
|
||||
self.assertEqual(sorted(self.service.sync_calls), ["20260825", "20260826"])
|
||||
self.assertEqual(audit["missing"], ["2026-08-25", "2026-08-26"])
|
||||
self.assertEqual(sorted(audit["created_dates"]), ["2026-08-25", "2026-08-26"])
|
||||
after = self.service.sentiment_history("20260827", 20)
|
||||
self.assertGreaterEqual(after["available_days"], 4)
|
||||
self.assertEqual(
|
||||
[row["trade_date"] for row in after["rows"]],
|
||||
["20260824", "20260825", "20260826", "20260827"],
|
||||
)
|
||||
|
||||
def test_dry_run_does_not_write_snapshots(self) -> None:
|
||||
audit = self.service.backfill_recent_trading_days(
|
||||
end_date="20260827",
|
||||
lookback=4,
|
||||
dry_run=True,
|
||||
create_backup=True,
|
||||
)
|
||||
self.assertTrue(audit["dry_run"])
|
||||
self.assertEqual(self.service.sync_calls, [])
|
||||
self.assertIsNone(audit["backup_path"])
|
||||
self.assertEqual(
|
||||
self.database.list_snapshot_trade_dates("20260824", "20260827"),
|
||||
["20260824", "20260827"],
|
||||
)
|
||||
|
||||
def test_repeat_execution_skips_existing_days(self) -> None:
|
||||
with patch(
|
||||
"backend.features.market.service.create_sqlite_backup",
|
||||
return_value=Path(self.temporary.name) / "fake-backup.db",
|
||||
):
|
||||
first = self.service.backfill_recent_trading_days(
|
||||
end_date="20260827", lookback=4
|
||||
)
|
||||
self.service.sync_calls.clear()
|
||||
second = self.service.backfill_recent_trading_days(
|
||||
end_date="20260827", lookback=4
|
||||
)
|
||||
self.assertEqual(first["succeeded_count"], 2)
|
||||
self.assertEqual(self.service.sync_calls, [])
|
||||
self.assertEqual(second["missing_count"], 0)
|
||||
self.assertEqual(second["skipped_count"], 4)
|
||||
self.assertIsNone(second["backup_path"])
|
||||
|
||||
def test_partial_failure_continues_remaining_days(self) -> None:
|
||||
self.service._fail_dates.add("20260825")
|
||||
with patch(
|
||||
"backend.features.market.service.create_sqlite_backup",
|
||||
return_value=Path(self.temporary.name) / "fake-backup.db",
|
||||
):
|
||||
audit = self.service.backfill_recent_trading_days(
|
||||
end_date="20260827", lookback=4
|
||||
)
|
||||
self.assertFalse(audit["ok"])
|
||||
self.assertEqual(audit["failed_count"], 1)
|
||||
self.assertEqual(audit["succeeded_count"], 1)
|
||||
self.assertIn("20260826", self.database.list_snapshot_trade_dates())
|
||||
self.assertNotIn("20260825", self.database.list_snapshot_trade_dates())
|
||||
|
||||
def test_range_backfill_skips_weekend_without_treating_as_error(self) -> None:
|
||||
with patch(
|
||||
"backend.features.market.service.create_sqlite_backup",
|
||||
return_value=Path(self.temporary.name) / "fake-backup.db",
|
||||
):
|
||||
audit = self.service.backfill(
|
||||
start_date="2026-08-21",
|
||||
end_date="2026-08-24",
|
||||
)
|
||||
self.assertEqual(audit["mode"], "range")
|
||||
self.assertEqual(audit["skipped_non_trading_days"], ["2026-08-22", "2026-08-23"])
|
||||
self.assertEqual(sorted(self.service.sync_calls), ["20260821"])
|
||||
self.assertTrue(audit["ok"])
|
||||
|
||||
def test_sqlite_backup_api_creates_restorable_copy(self) -> None:
|
||||
backup_dir = Path(self.temporary.name) / "backups"
|
||||
backup = create_sqlite_backup(
|
||||
self.db_path,
|
||||
backup_dir,
|
||||
label="pre-recent-backfill",
|
||||
stamped_at=datetime(2026, 8, 27, 15, 30, 0),
|
||||
)
|
||||
self.assertTrue(backup.exists())
|
||||
self.assertIn("pre-recent-backfill-20260827-153000", backup.name)
|
||||
restored = ReviewDatabase(backup)
|
||||
self.assertEqual(
|
||||
restored.list_snapshot_trade_dates(),
|
||||
["20260824", "20260827"],
|
||||
)
|
||||
|
||||
def test_audit_lists_only_snapshot_related_write_tables(self) -> None:
|
||||
audit = build_backfill_audit(
|
||||
mode="recent",
|
||||
end_date="20260827",
|
||||
lookback=60,
|
||||
coverage={"trade_dates": [], "present": [], "missing": [], "present_count": 0, "missing_count": 0},
|
||||
)
|
||||
self.assertEqual(
|
||||
audit["write_tables"],
|
||||
["dashboard_snapshots", "data_snapshots", "sync_runs"],
|
||||
)
|
||||
self.assertNotIn("users", audit["write_tables"])
|
||||
self.assertNotIn("system_settings", audit["write_tables"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+11
-1
@@ -17,12 +17,22 @@ registry, and verification tools.
|
||||
`backend/features/*/routes.py` owners.
|
||||
- `python tools/build_architecture_inventory.py [--check]`: generate or verify
|
||||
`config/architecture-inventory.json` from the current source tree.
|
||||
- `python tools/backfill_recent_snapshots.py --account <admin> [--lookback 60] [--dry-run]`:
|
||||
auditable recent trading-day dashboard snapshot backfill. See
|
||||
`docs/maintenance/行情历史补档.md`.
|
||||
- `bash tools/build_image.sh <commit> <tag>`: the only sanctioned way to build the
|
||||
production Docker image. Streams `git archive <commit>` to the deploy host over SSH
|
||||
(default `moxiaobai@192.168.200.11`), refuses tags that do not end with the commit
|
||||
short SHA, verifies the revision label after the build, and appends a record to
|
||||
`~/xiaobai-build/BUILD_LOG.tsv` on the host. Building from any server-side working
|
||||
tree is forbidden; see `DOCKER_DEPLOY.md`.
|
||||
tree is forbidden; see `DOCKER_DEPLOY.md`. Before building, it runs
|
||||
`tools/check_deploy_baseline.sh` so the candidate commit must contain the currently
|
||||
running container's Git revision as an ancestor.
|
||||
- `bash tools/check_deploy_baseline.sh <commit> [--live-revision <sha>]`: deployment
|
||||
ancestor gate. Reads the live `org.opencontainers.image.revision` from the running
|
||||
`xiaobai-review` container (or `--live-revision` in tests), prints the live SHA,
|
||||
candidate SHA, file diff, and commits the candidate would drop, then exits if the
|
||||
live revision is not an ancestor of the candidate.
|
||||
|
||||
`verify_baseline.py` does not inspect a parent checkout or skip tests according to files outside
|
||||
this application. Historical comparison scripts were retired after final standalone acceptance;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Auditable recent trading-day dashboard snapshot backfill.
|
||||
|
||||
Examples:
|
||||
|
||||
python tools/backfill_recent_snapshots.py --account admin --dry-run
|
||||
python tools/backfill_recent_snapshots.py --account admin --lookback 60
|
||||
python tools/backfill_recent_snapshots.py --account admin --end-date 2026-08-27 --force
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from backend.application import SERVICE
|
||||
from backend.bootstrap.config import normalize_date
|
||||
from backend.features.market.backfill_history import DEFAULT_RECENT_TRADING_DAYS
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Backfill the latest N real trading-day dashboard snapshots"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--account",
|
||||
required=True,
|
||||
help="Account that can resolve the shared Tushare token",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--end-date",
|
||||
default=date.today().isoformat(),
|
||||
help="Inclusive end date YYYY-MM-DD (default: today)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--lookback",
|
||||
type=int,
|
||||
default=DEFAULT_RECENT_TRADING_DAYS,
|
||||
help=f"Number of open trading days to cover (default {DEFAULT_RECENT_TRADING_DAYS}, max 60)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Plan only: classify missing gaps without writing",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="Re-sync days that already have snapshots",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-backup",
|
||||
action="store_true",
|
||||
help="Skip the SQLite backup API step (not recommended)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
help="Print the full audit payload as JSON",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
user = SERVICE.database.user_by_username(args.account.strip())
|
||||
if not user:
|
||||
raise SystemExit("account not found")
|
||||
SERVICE.bind_user(int(user["id"]))
|
||||
|
||||
end_date = normalize_date(args.end_date)
|
||||
audit = SERVICE.backfill_recent_trading_days(
|
||||
end_date=end_date,
|
||||
lookback=args.lookback,
|
||||
dry_run=args.dry_run,
|
||||
force=args.force,
|
||||
create_backup=not args.no_backup,
|
||||
)
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(audit, ensure_ascii=False, indent=2))
|
||||
raise SystemExit(0 if audit.get("ok") else 1)
|
||||
|
||||
print(
|
||||
f"mode={audit['mode']} end={audit['end_date']} lookback={audit['lookback']} "
|
||||
f"dry_run={audit['dry_run']}"
|
||||
)
|
||||
print(
|
||||
f"present={audit['present_count']} missing={audit['missing_count']} "
|
||||
f"succeeded={audit['succeeded_count']} skipped={audit['skipped_count']} "
|
||||
f"failed={audit['failed_count']}"
|
||||
)
|
||||
if audit.get("backup_path"):
|
||||
print(f"backup={audit['backup_path']}")
|
||||
if audit.get("missing"):
|
||||
print("missing_dates=" + ",".join(audit["missing"]))
|
||||
if audit.get("created_dates"):
|
||||
print("created_dates=" + ",".join(audit["created_dates"]))
|
||||
failed = [row for row in audit.get("results") or [] if row.get("status") == "failed"]
|
||||
for row in failed:
|
||||
print(f"failed {row.get('requested_date')}: {row.get('error')}")
|
||||
if not audit.get("ok"):
|
||||
raise SystemExit(1)
|
||||
print("backfill complete")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -59,6 +59,9 @@ if [[ "$TAG" != *-"$SHORT" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> 部署基线门禁(线上提交必须是候选祖先)"
|
||||
bash "$(git rev-parse --show-toplevel)/tools/check_deploy_baseline.sh" "$FULL_SHA"
|
||||
|
||||
echo "==> 构建计划"
|
||||
echo " 提交: ${FULL_SHA} ${SUBJECT}"
|
||||
echo " 镜像: ${REPO_NAME}:${TAG} @ ${HOST}"
|
||||
|
||||
Executable
+126
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env bash
|
||||
# 部署基线门禁(HEL-238):候选提交必须包含当前线上提交的全部历史。
|
||||
# 线上提交号从运行中的容器镜像 label 读取,禁止人工填写“看起来正确”的基线。
|
||||
set -euo pipefail
|
||||
|
||||
HOST_DEFAULT="moxiaobai@192.168.200.11"
|
||||
CONTAINER_DEFAULT="xiaobai-review"
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
用法: tools/check_deploy_baseline.sh <candidate_commit> [--live-revision <sha>]
|
||||
<candidate_commit> 准备构建/部署的提交(完整或前缀)
|
||||
--live-revision <sha> 仅测试用:直接指定线上提交,跳过 SSH 读取
|
||||
环境变量:
|
||||
XB_BUILD_HOST 部署机 SSH(默认 moxiaobai@192.168.200.11)
|
||||
XB_LIVE_CONTAINER 运行中容器名(默认 xiaobai-review)
|
||||
XB_LIVE_REVISION 若已设置则视为线上提交,不再 SSH
|
||||
EOF
|
||||
exit 2
|
||||
}
|
||||
|
||||
[ $# -ge 1 ] || usage
|
||||
CANDIDATE="$1"
|
||||
shift
|
||||
LIVE_OVERRIDE=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--live-revision)
|
||||
[ $# -ge 2 ] || usage
|
||||
LIVE_OVERRIDE="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
;;
|
||||
*)
|
||||
echo "拒绝:未知参数 $1" >&2
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
HOST="${XB_BUILD_HOST:-$HOST_DEFAULT}"
|
||||
CONTAINER="${XB_LIVE_CONTAINER:-$CONTAINER_DEFAULT}"
|
||||
|
||||
case "$HOST" in
|
||||
*192.168.200.36*)
|
||||
echo "拒绝:192.168.200.36 已永久废弃,严禁在其上构建或部署。" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
read_live_revision() {
|
||||
if [ -n "${LIVE_OVERRIDE}" ]; then
|
||||
printf '%s\n' "${LIVE_OVERRIDE}"
|
||||
return
|
||||
fi
|
||||
if [ -n "${XB_LIVE_REVISION:-}" ]; then
|
||||
printf '%s\n' "${XB_LIVE_REVISION}"
|
||||
return
|
||||
fi
|
||||
ssh -o BatchMode=yes "$HOST" bash -s -- "$CONTAINER" <<'REMOTE'
|
||||
set -euo pipefail
|
||||
container="$1"
|
||||
revision="$(docker inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$container" 2>/dev/null || true)"
|
||||
if [ -z "$revision" ] || [ "$revision" = "<no value>" ]; then
|
||||
image="$(docker inspect --format '{{.Image}}' "$container" 2>/dev/null || true)"
|
||||
if [ -n "$image" ]; then
|
||||
revision="$(docker inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$image" 2>/dev/null || true)"
|
||||
fi
|
||||
fi
|
||||
if [ -z "$revision" ] || [ "$revision" = "<no value>" ]; then
|
||||
echo "拒绝:无法从线上容器 ${container} 读取 org.opencontainers.image.revision。" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$revision"
|
||||
REMOTE
|
||||
}
|
||||
|
||||
LIVE_RAW="$(read_live_revision)"
|
||||
LIVE_RAW="$(printf '%s' "$LIVE_RAW" | tr -d '[:space:]')"
|
||||
if [ -z "$LIVE_RAW" ]; then
|
||||
echo "拒绝:线上提交号为空,禁止继续构建或部署。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CANDIDATE_SHA="$(git rev-parse --verify --quiet "${CANDIDATE}^{commit}" || true)"
|
||||
if [ -z "$CANDIDATE_SHA" ]; then
|
||||
echo "拒绝:候选提交 ${CANDIDATE} 无法解析。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LIVE_SHA="$(git rev-parse --verify --quiet "${LIVE_RAW}^{commit}" || true)"
|
||||
if [ -z "$LIVE_SHA" ]; then
|
||||
echo "拒绝:线上提交 ${LIVE_RAW} 在本地仓库无法解析;请先 git fetch,禁止手工填写替代基线。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> 部署基线对照"
|
||||
echo " 线上提交: ${LIVE_SHA}"
|
||||
echo " 候选提交: ${CANDIDATE_SHA}"
|
||||
|
||||
echo "==> 候选相对线上的文件差异"
|
||||
DIFF_FILES="$(git diff --name-only "$LIVE_SHA" "$CANDIDATE_SHA" || true)"
|
||||
if [ -z "$DIFF_FILES" ]; then
|
||||
echo " (无文件差异)"
|
||||
else
|
||||
printf '%s\n' "$DIFF_FILES" | sed 's/^/ /'
|
||||
fi
|
||||
|
||||
echo "==> 候选将丢失的提交(线上有、候选没有)"
|
||||
LOST="$(git log --oneline "$CANDIDATE_SHA".."$LIVE_SHA" || true)"
|
||||
if [ -z "$LOST" ]; then
|
||||
echo " (无)"
|
||||
else
|
||||
printf '%s\n' "$LOST" | sed 's/^/ /'
|
||||
fi
|
||||
|
||||
if ! git merge-base --is-ancestor "$LIVE_SHA" "$CANDIDATE_SHA"; then
|
||||
echo "拒绝:候选提交不是当前线上提交的后继,部署会丢失线上已有提交。禁止构建或部署。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> 祖先关系通过:线上 ${LIVE_SHA:0:7} 是候选 ${CANDIDATE_SHA:0:7} 的祖先"
|
||||
Reference in New Issue
Block a user