feat: add daily commission history for Web 2.0.8
This commit is contained in:
+16
-4
@@ -1,8 +1,8 @@
|
||||
# 牧羊人之心牧场助手 · Web 2.0.7
|
||||
# 牧羊人之心牧场助手 · Web 2.0.8
|
||||
|
||||
## 产品约束
|
||||
|
||||
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.7`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。
|
||||
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。Web `2.0.8`,源码发布入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md),功能与验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。
|
||||
|
||||
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
|
||||
|
||||
@@ -17,19 +17,29 @@
|
||||
## 核心操作
|
||||
|
||||
- 账号密码登录后选择区服进入;恢复已保存会话;退出与清除登录记录。游戏凭据仅交给同源服务端,不进入浏览器持久存储或 URL。
|
||||
- 手动选服、恢复会话和自动重登成功读取角色后,均默认开启策略,自动执行已配置且已勾选的功能,可在顶部停止;不改变各子功能的勾选。获取区服候选及失败候选不视为登录成功,界面以服务端在线与运行状态为准。导入配置只替换规则并停止执行,下次成功登录仍自动开启;服务重启后未成功登录时不直接执行。
|
||||
- 手动选服、恢复会话和自动重登成功读取角色后,默认执行已配置且已勾选的功能,不改变各子功能勾选。用户手动“停止”跨掉线、重登和服务重启保留,点击“开启”恢复;导入配置只替换规则,保留用户启停意图。获取区服候选及失败候选不视为登录成功,服务重启后未成功登录时不执行策略,界面以服务端状态为准。
|
||||
- 配置通过中文 schema 生成原生控件;逐蛋孵化/补货规则、物品赠礼保留量、逐魔物培养目标、关卡规则等直接在对应页面编辑。自动保存显示待保存、保存中、失败与已保存状态。
|
||||
- 培育室扩建、牧场锁定/解锁、批量派遣/喂养、上下文菜单和费用二次确认沿用核心行为。切换功能页只读取视图,不触发游戏写操作。
|
||||
- 主线默认当前主线,可切换筛选。地图按地区默认折叠,展示普通关卡、矿洞、难度、次数和工具库存。探险支持队员手选/自动与完成后自动领奖说明。
|
||||
- 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。
|
||||
- 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。
|
||||
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
|
||||
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
|
||||
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
|
||||
|
||||
## 2.0.8 自动委托与每日历史
|
||||
|
||||
- 自动委托包含“当前委托 / 每日记录”。当前页展示原始候选、任务状态、标注奖励及选择 / 回退原因;城市锁定候选显示不可接取。
|
||||
- 策略允许且满足城市、次数、资源与步骤支持条件的候选,跨城市按静态预计氪金20→15→10全局排序。高档不可用时日志说明原因,再选择可执行的低档,不保证全部接取20档。
|
||||
- 每日记录按账号、区服、角色隔离,以北京时间(UTC+8)自然日查询接取、推进、领奖和待核对事件,刷新和服务重启后可查。每角色保留最近90天、最多5000条事件。
|
||||
- 预计奖励与已确认实际奖励分别展示;实际氪金仅来自确认成功的 `taskComplete` 领奖回包 `response.reward.ke`,缺失金额显示“未确认”。接取、推进、预计奖励及旧完成标记不作为到账证据。
|
||||
- 旧历史仅从本地任务 journal 可证实的操作部分回填,不推造缺失记录。每日历史用于业务进度,运行详情继续使用原单一底部“自动委托”分类日志。
|
||||
|
||||
## 2.0.7 主培养与资质备用
|
||||
|
||||
同种只自动培养已养成的高等级主培养;新资质更好的魔物只作为备用保留,不分配经验、礼物或潜能材料。已启用种类按主培养1只、更优备用最多1只整理,新备用严格更优才替换,同分保留已有备用。主培养到上限或冷却时等待,不向同种备用转移资源。硬保护保留,未勾选种类不扩大自动整理范围。
|
||||
|
||||
2.0.8 沿用上述修复及现有界面,历史功能与验证记录见 [2.0.7 发布说明](../analysis/RELEASE_2_0_7.md)。
|
||||
|
||||
## 表单布局(2.0.6 起)
|
||||
|
||||
勾选框与右侧文字组成一组;数字、文本与下拉框采用标签在上、控件在下的布局。设置区限定合理宽度,并按可用空间排为多列,每日领取项目在单独分组中排列。界面尺寸变化不改变配置路径、自动保存或策略执行规则。
|
||||
@@ -69,6 +79,8 @@
|
||||
|
||||
## 安全与验证
|
||||
|
||||
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。证据与发布门禁见 [发布说明](../analysis/RELEASE_2_0_8.md#验证);历史版本结果不计入本版。
|
||||
|
||||
不发真实游戏 API 测试,不读取或更改私人 `local_state` 账号。浏览器测试仅使用临时目录、fake 后端或服务端离线演示。所有游戏文本用 `textContent` 呈现;日志使用服务端脱敏数据。管理登录、同源校验与 cookie 由 API 负责。
|
||||
|
||||
## 技术默认假设
|
||||
|
||||
+16
-9
@@ -1,19 +1,26 @@
|
||||
# Web 2.0.7 运行说明
|
||||
# Web 2.0.8 运行说明
|
||||
|
||||
本轮 Web 发布目标 **2.0.7**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。
|
||||
Web **2.0.8**,源码发布入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。自动委托提供当前委托与每日记录,功能和验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。
|
||||
|
||||
Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
|
||||
|
||||
## 迁移清单
|
||||
|
||||
- [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。
|
||||
- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,每次成功登录后自动执行已配置且已勾选的功能,可在顶部停止。
|
||||
- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,未手动停止时,成功登录后自动执行已配置且已勾选的功能;手动暂停跨重登保留,可在顶部开启。
|
||||
- [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。
|
||||
- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;历史 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测见下文。
|
||||
- [x] 本轮发布目标为 `2.0.7`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。
|
||||
- 2.0.7 修复同种重复培养:主培养与资质备用分离,自动喂养、赠礼和潜能突破仅作用于主培养,启用种类固定主培养1只与更优备用最多1只。详见 [本版发布说明](../analysis/RELEASE_2_0_7.md)。
|
||||
- [x] `2.0.8` 自动委托当前 / 每日记录、持久化历史及奖励证据区分;739项独立测试中736通过、3项 Windows 跳过,浏览器77项全部验证通过。战斗模拟仍为近似模型,特殊关卡并非全部支持。
|
||||
- 沿用 2.0.7 的同种重复培养修复:主培养与资质备用分离,自动喂养、赠礼和潜能突破仅作用于主培养,启用种类固定主培养1只与更优备用最多1只。详见 [2.0.7 发布说明](../analysis/RELEASE_2_0_7.md)。
|
||||
- 2.0.3 修复 2.0.2 日志布局:所有页签复用原有底部日志区,按当前账号与功能筛选,默认收起;操作约定见 [产品说明](PRODUCT.md#203-底部分类日志),验收结果见 [发布说明](../analysis/RELEASE_2_0_3.md#验证)。
|
||||
|
||||
## 自动委托(2.0.8)
|
||||
|
||||
- “当前委托”查看任务、原始候选和选择 / 回退原因;城市锁定候选显示不可接取。策略允许且满足城市、次数、资源和步骤条件的候选,跨城市按预计氪金20→15→10排序,日志说明高档不可用的原因。
|
||||
- “每日记录”按账号、区服、角色及北京时间(UTC+8)自然日查询接取、推进、领奖与待核对事件。历史持久保存,刷新或重启后可查;每角色保留最近90天、最多5000条事件。
|
||||
- 预计氪金来自静态任务配置,已确认氪金仅取确认成功的领奖回包 `response.reward.ke`;金额缺失显示“未确认”。接取、推进、旧完成标记和预计数额不作为实际奖励证据。
|
||||
- 旧历史仅从本地任务 journal 可证实的操作部分回填,不推造缺失的过去。业务历史之外的运行详情继续使用原单一底部“自动委托”分类日志。完整行为见 [发布说明](../analysis/RELEASE_2_0_8.md)。
|
||||
|
||||
## Windows 本地运行
|
||||
|
||||
使用 Python 3.12+,在项目根目录执行(本机已安装 3.13):
|
||||
@@ -32,7 +39,7 @@ py -3 -m venv .venv-web
|
||||
.\Start_Ranch_Web.cmd --demo --data-dir "$env:TEMP\ranch-web-demo-new" --no-browser
|
||||
```
|
||||
|
||||
健康检查 `GET /api/health` 不访问游戏 API。关闭终端时使用 Ctrl+C,让应用正常关闭账号队列。手动选服、恢复会话及自动重登成功读取角色后,均默认开启策略,只执行已勾选的功能,子功能不会全选。顶部“停止”暂停策略,仍保留状态监控;可用“开启”继续。登录后默认执行已勾选策略;只有手动“停止”才暂停,手动“开启”恢复。启停选择跨掉线、重新登录和服务重启保存,导入策略不会改变这个选择。
|
||||
健康检查 `GET /api/health` 不访问游戏 API。关闭终端时使用 Ctrl+C,让应用正常关闭账号队列。手动选服、恢复会话及自动重登成功读取角色后,默认执行已勾选功能,子功能不会全选;用户手动“停止”则继续保持暂停,点击“开启”恢复。启停选择跨掉线、重登和服务重启保存,导入策略保留该选择;停止策略后仍保留状态监控。
|
||||
|
||||
### 后台运行与断线处理
|
||||
|
||||
@@ -97,13 +104,13 @@ sh start-web.sh --no-browser
|
||||
|
||||
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
|
||||
|
||||
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.7**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
|
||||
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,稳定 Release 和正式镜像就绪、宿主机心跳有效后,可直接通过“帮助 → 检查版本更新…”升级 **2.0.8**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
|
||||
|
||||
## 离线验证
|
||||
|
||||
2.0.7 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_7.md#验证),以下历史记录不计入本版验收。
|
||||
2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。分组结果与证据见 [发布说明](../analysis/RELEASE_2_0_8.md#验证)。2.0.7 的结果保留在 [历史发布说明](../analysis/RELEASE_2_0_7.md#验证),以下历史记录也不计入本版验收。
|
||||
|
||||
### 历史验证记录(不计入 2.0.7)
|
||||
### 历史验证记录(不计入 2.0.8)
|
||||
|
||||
2.0.2 验证记录见 [历史发布说明](../analysis/RELEASE_2_0_2.md#验证)。
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Headless Web workspace for the ranch assistant."""
|
||||
|
||||
__version__ = "2.0.7"
|
||||
__version__ = "2.0.8"
|
||||
GAME_VERSION = "1.9.68"
|
||||
|
||||
__all__ = ["__version__", "GAME_VERSION"]
|
||||
|
||||
+41
-3
@@ -101,6 +101,7 @@ class _Job:
|
||||
workspace: str = ""
|
||||
category: str = "general"
|
||||
due_kind: str | None = None
|
||||
commission_failure: str = ""
|
||||
|
||||
def public(self):
|
||||
operation = {"__config": "set_config", "__view": "view"}.get(self.operation, self.operation)
|
||||
@@ -450,10 +451,41 @@ class AccountWorker:
|
||||
# Attribution must not prevent an otherwise valid action.
|
||||
category = "general"
|
||||
self._attribute_task(category)
|
||||
return _method(*args, **kwargs)
|
||||
try:
|
||||
return _method(*args, **kwargs)
|
||||
except CancelledBeforeDispatch:
|
||||
raise
|
||||
except Exception:
|
||||
if category == "commissions":
|
||||
# Enrich the existing error entry, preserving the original
|
||||
# exception and its one-time reporting on the worker.
|
||||
try:
|
||||
source = args[0] if args else kwargs.get("intent", kwargs.get("action"))
|
||||
if source is None and _name == "_run_progression_intent":
|
||||
source = intent
|
||||
self._commission_failure_context(engine, source)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
setattr(engine, name, routed)
|
||||
|
||||
def _commission_failure_context(self, engine, source):
|
||||
if self._execution is None or threading.current_thread() is not getattr(self, "thread", None):
|
||||
return
|
||||
field = lambda key, default=None: source.get(key, default) if isinstance(source, dict) else getattr(source, key, default)
|
||||
payload = field("payload") or {}
|
||||
type_id = field("source_task_type_id") or field("task_type_id") or payload.get("taskTypeId")
|
||||
info = engine._commission_info(type_id)
|
||||
name = info.get("name") or type_id or "名称未记录"
|
||||
reward = (info.get("reward") or {}).get("ke")
|
||||
expected = f"标注{reward}氪金" if type(reward) in (int, float) else "标注氪金未记录"
|
||||
path = field("path", "") or ""
|
||||
kind = field("kind", "")
|
||||
action = "接取" if path.endswith("taskLoopReceive") or kind in {"quest_accept", "progression_loop_accept"} else (
|
||||
"领奖" if path.endswith("taskComplete") or kind in {"quest_complete", "progression_complete"} else "推进")
|
||||
self._execution.commission_failure = f"委托「{name}」({expected}){action}异常,结果待核对"
|
||||
|
||||
def remember(self, value):
|
||||
with self._secret_lock:
|
||||
if isinstance(value, dict):
|
||||
@@ -544,7 +576,13 @@ class AccountWorker:
|
||||
notes = getattr(getattr(self.engine, name, None), "notes", ())
|
||||
sources.append((category, [self.safe_text(note) for note in notes[:512]]))
|
||||
for category, text in route_message(self.safe_text(message), context=self._task_category(), hints=note_hints(sources)):
|
||||
self.log(text, category=category)
|
||||
level = "info"
|
||||
if category == "commissions":
|
||||
if "战斗失败" in text:
|
||||
level = "error"
|
||||
elif any(marker in text for marker in ("结果未知", "未确认", "待确认", "等待核对", "奖励未记录")):
|
||||
level = "warning"
|
||||
self.log(text, category=category, level=level)
|
||||
|
||||
def _trace_event(self, event):
|
||||
fields = [event.get("operation", "网络"), event.get("kind", "")]
|
||||
@@ -844,7 +882,7 @@ class AccountWorker:
|
||||
if (job.consuming and job.operation != "start"
|
||||
and failure_sequence == self._game_failure_sequence):
|
||||
self._execution_failed(error)
|
||||
self.log(message, category=job.category, level="error")
|
||||
self.log((job.commission_failure + ";" if job.commission_failure else "") + message, category=job.category, level="error")
|
||||
finally:
|
||||
job.payload = {}
|
||||
try:
|
||||
|
||||
@@ -415,7 +415,7 @@ async function exportYields(account=current()) {
|
||||
async function command(name,account=current()) {
|
||||
try {
|
||||
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
|
||||
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.7'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
|
||||
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.8'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
|
||||
if(name==='updates')return await showUpdates();
|
||||
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
|
||||
if(!account)throw new Error('请先新增或选择账号。');
|
||||
@@ -640,7 +640,7 @@ async function bootstrap() {
|
||||
$('#app').hidden=false;
|
||||
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
||||
if(state.redirecting)return;
|
||||
$('#app-version').textContent=meta.version || '2.0.7';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
||||
$('#app-version').textContent=meta.version || '2.0.8';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
||||
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
|
||||
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
</div></details>
|
||||
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
|
||||
</nav>
|
||||
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.7</span></span>
|
||||
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.8</span></span>
|
||||
<span id="access-mode" class="muted"></span>
|
||||
</header>
|
||||
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
|
||||
|
||||
@@ -9,7 +9,7 @@ export const PAGES = [
|
||||
['commissions', '自动委托'], ['exploration', '自动探险'], ['maps', '自动扫荡'], ['statistics', '数据分析'], ['plans', '执行计划'], ['yields', '收益资料'],
|
||||
];
|
||||
|
||||
export const initialQuery = page => page === 'bag' ? {category: 'eggs'} : page === 'mainline' ? {category: 'mainline', state: 'current'} : page === 'ranch' ? {grouped: false} : page === 'maps' ? {category: 'all', only_unlocked: true} : {};
|
||||
export const initialQuery = page => page === 'bag' ? {category: 'eggs'} : page === 'mainline' ? {category: 'mainline', state: 'current'} : page === 'commissions' ? {tab: 'current'} : page === 'ranch' ? {grouped: false} : page === 'maps' ? {category: 'all', only_unlocked: true} : {};
|
||||
|
||||
class LoginPage {
|
||||
constructor(host, page) {
|
||||
@@ -161,7 +161,7 @@ export class PageView {
|
||||
filters.forEach(field => {
|
||||
if (this.key === 'bag' && field.key === 'category') return;
|
||||
included.add(field.key);
|
||||
if (!Object.hasOwn(this.query, field.key)) this.query[field.key] = field.value;
|
||||
if (!Object.hasOwn(this.query, field.key) || field.type === 'date' && !this.query[field.key]) this.query[field.key] = field.value;
|
||||
let item = this.filters.get(field.key);
|
||||
const signature = JSON.stringify({...field, value: undefined});
|
||||
if (!item || item.signature !== signature && !item.root.contains(document.activeElement)) {
|
||||
@@ -170,6 +170,7 @@ export class PageView {
|
||||
set: (_, value) => this.setQuery(field.key, value), onError: this.error,
|
||||
});
|
||||
if (field.key === 'search') { entry.root.type = 'search'; entry.root.placeholder = this.key === 'maps' ? '关卡、名称或掉落物品' : '按名称或编号筛选'; }
|
||||
if (field.type === 'date') entry.root.type = 'date';
|
||||
const root = el('label', {}, el('span', {text: field.label}), entry.root);
|
||||
item?.root.remove();
|
||||
item = {root, entry, signature};
|
||||
@@ -187,11 +188,17 @@ export class PageView {
|
||||
if (this.key === 'bag') tabs = [{key:'eggs',title:'魔物蛋'}, {key:'usable',title:'可使用'}, {key:'consumables',title:'消耗品'}, {key:'materials',title:'材料'}, {key:'other',title:'其他'}, {key:'equipment',title:'装备'}];
|
||||
if (!tabs.length && this.key === 'hatching') tabs = ['孵蛋策略','牧场策略','喂养策略'].map(title => ({key:title,title}));
|
||||
if (!tabs.length && this.key === 'mainline') tabs = [{key:'tasks',title:'任务状态'}, {key:'policy',title:'推进策略'}];
|
||||
if (this.key === 'commissions') this.activeSubtab = this.query.tab || 'current';
|
||||
const signature = JSON.stringify(tabs);
|
||||
if (this.tabSignature !== signature) {
|
||||
if (!this.activeSubtab || !tabs.some(tab => tab.key === this.activeSubtab)) this.activeSubtab = this.key === 'bag' ? this.query.category || tabs[0]?.key : tabs[0]?.key;
|
||||
this.subtabs.replaceChildren(...tabs.map(tab => el('button', {type: 'button', class: 'subtab', role: 'tab', 'data-key': tab.key, text: tab.title || tab.label,
|
||||
onClick: () => { this.activeSubtab = tab.key; if (this.key === 'bag') this.setQuery('category', tab.key); this.render(this.data || data); }})));
|
||||
onClick: () => {
|
||||
this.activeSubtab = tab.key;
|
||||
if (this.key === 'commissions') { this.setQuery('tab', tab.key); this.updateSubtabs(data); return; }
|
||||
if (this.key === 'bag') this.setQuery('category', tab.key);
|
||||
this.render(this.data || data);
|
||||
}})));
|
||||
this.tabSignature = signature;
|
||||
}
|
||||
$$('.subtab', this.subtabs).forEach(button => { const selected = button.dataset.key === this.activeSubtab; button.setAttribute('aria-selected', selected); button.tabIndex = selected ? 0 : -1; });
|
||||
@@ -220,7 +227,7 @@ export class PageView {
|
||||
const currencies = action.currencies ? optionsList(action.currencies) : [null];
|
||||
currencies.forEach(currency => {
|
||||
const button = el('button', {type: 'button', text: `${action.label}${currency ? `(${currency.label})` : ''}`, 'data-operation': action.operation,
|
||||
'data-selection': action.selection, onClick: () => this.options.action(this, action, currency?.value).catch(this.error)});
|
||||
'data-selection': action.selection, onClick: () => action.operation === 'reload_view' ? this.options.load(this, true).catch(this.error) : this.options.action(this, action, currency?.value).catch(this.error)});
|
||||
this.actionsHost.append(button);
|
||||
});
|
||||
});
|
||||
@@ -296,12 +303,12 @@ export class PageView {
|
||||
const data = this.data.details?.[row.id] || row.details;
|
||||
if (!data) return;
|
||||
const labels = {name:'名称',species:'种类',id:'魔物ID',level:'等级 / 当前上限',quality:'资质 攻/防/血/敏',reference_stats:'参考攻击 / 防御 / 生命 / 敏捷',growth:'成长数值',likes:'喜欢的物品',feel:'好感 / 上限',feed_exp:'喂养经验',scope:'管理范围'};
|
||||
const title=this.key==='ranch'?'魔物详情':this.key==='mainline'?'任务详情':this.key==='battles'?'战斗详情':'详情';
|
||||
const title=this.key==='ranch'?'魔物详情':this.key==='mainline'?'任务详情':this.key==='battles'?'战斗详情':this.key==='commissions'?'委托详情':'详情';
|
||||
dialog(title, el('div', {class:'detail-sections'}, detailsList(data, labels)), {info:true});
|
||||
}
|
||||
|
||||
openContext(event, selected, row) {
|
||||
const items = [{label:'刷新本页',run:()=>this.perform('refresh',{page:this.key})}];
|
||||
const items = [{label:'刷新本页',run:()=>this.key === 'commissions' && this.query.tab === 'history' ? this.options.load(this, true) : this.perform('refresh',{page:this.key})}];
|
||||
if (this.key === 'ranch') {
|
||||
items.push({label:'查看魔物详情',run:()=>this.showDetail(row)});
|
||||
(this.data.actions || []).filter(action => ['lock','unlock','sell','feed'].includes(action.operation)).forEach(action => items.push({label:action.label,disabled:!selected.length,run:()=>this.options.action(this,action)}));
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Commission subtabs, local reads and the original log region over loopback only."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.model import Catalog
|
||||
from ranch_web.tests.test_commission_history import history_fixture
|
||||
from ranch_web.views import build_view
|
||||
from . import test_workbench_browser as fixtures
|
||||
|
||||
if fixtures.AVAILABLE:
|
||||
from playwright.sync_api import expect
|
||||
|
||||
|
||||
@unittest.skipUnless(fixtures.AVAILABLE, "Python Playwright and a system Chromium browser are required")
|
||||
class CommissionHistoryBrowserTests(unittest.TestCase):
|
||||
setUpClass = classmethod(fixtures.WorkbenchBrowserTests.setUpClass.__func__)
|
||||
tearDownClass = classmethod(fixtures.WorkbenchBrowserTests.tearDownClass.__func__)
|
||||
await_job = fixtures.WorkbenchBrowserTests.await_job
|
||||
open = fixtures.WorkbenchBrowserTests.open
|
||||
go = fixtures.WorkbenchBrowserTests.go
|
||||
fulfill = staticmethod(fixtures.WorkbenchBrowserTests.fulfill)
|
||||
|
||||
def setUp(self):
|
||||
self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP forbidden")))
|
||||
fixtures.WorkbenchBrowserTests.setUp(self)
|
||||
self.context.set_default_timeout(6000)
|
||||
self.today = datetime.now(timezone(timedelta(hours=8))).date()
|
||||
self.external, self.writes, self.reads, self.pending = [], [], [], []
|
||||
self.hold = self.fail_reads = False
|
||||
self.engines = {}
|
||||
for identifier, label in ((self.first, "账号一"), (self.second, "账号二")):
|
||||
engine = Engine(Catalog(), budget_path=Path(self.temp.name) / identifier / "fixture-budget.json")
|
||||
engine.snapshot = demo_snapshot(engine.catalog)
|
||||
engine.catalog.data["task_info"] = {"test20": {"name": label + "高额候选", "reward": {"money": 123, "ke": 20}},
|
||||
"test15": {"name": label + "回退候选", "reward": {"money": 456, "ke": 15}}}
|
||||
engine.tasks.rows = Mock(return_value=[("test20", label + "高额候选", "城市 4 可接", "", {"city": 4}),
|
||||
("test15", label + "回退候选", "城市 1 可接", "", {"city": 1})])
|
||||
engine.tasks.current = Mock(return_value=[])
|
||||
engine.commission_offer_diagnostics = Mock(return_value=[])
|
||||
engine.progression_rows = Mock(return_value=[{"category": "commission", "task_type_id": "test20", "block_reason": "城市尚未解锁"},
|
||||
{"category": "commission", "task_type_id": "test15", "selection_reason": "20氪金候选未解锁,回退15氪金"}])
|
||||
engine.commission_history = lambda day=None, label=label: self.history(day, label)
|
||||
engine.client = Mock()
|
||||
self.engines[identifier] = engine
|
||||
|
||||
def local_only(route):
|
||||
if route.request.url.startswith(self.base + "/"):
|
||||
route.continue_()
|
||||
else:
|
||||
self.external.append(route.request.url)
|
||||
route.abort()
|
||||
|
||||
self.context.route("**/*", local_only)
|
||||
self.page.on("request", lambda request: self.writes.append(request) if request.method in ("POST", "PUT", "PATCH", "DELETE") else None)
|
||||
|
||||
def view(route):
|
||||
parsed = urlsplit(route.request.url)
|
||||
identifier = parsed.path.split("/")[-3]
|
||||
params = parse_qs(parsed.query)
|
||||
query = json.loads(params["query"][0]) if "query" in params else {key: value[0] for key, value in params.items()}
|
||||
self.reads.append((identifier, query))
|
||||
dto = build_view(self.engines[identifier], "commissions", self.manager.get_config(identifier)["config"], query)
|
||||
if self.hold:
|
||||
self.pending.append((route, dto))
|
||||
elif self.fail_reads:
|
||||
route.fulfill(status=503, content_type="application/json", body='{"detail":"本地记录读取失败"}')
|
||||
else:
|
||||
self.fulfill(route, {"loading": False, "data": dto})
|
||||
|
||||
self.page.route("**/api/accounts/*/views/commissions?*", view)
|
||||
|
||||
def history(self, day, label):
|
||||
fixture = history_fixture(day)
|
||||
fixture["rows"][0]["name"] = label + day + "提交魔物与道具"
|
||||
return fixture
|
||||
|
||||
def tearDown(self):
|
||||
try:
|
||||
self.assertEqual(self.external, [])
|
||||
self.assertEqual(self.errors, [])
|
||||
for engine in self.engines.values():
|
||||
engine.client.call.assert_not_called()
|
||||
finally:
|
||||
self.context.unroute_all(behavior="ignoreErrors")
|
||||
self.context.close()
|
||||
|
||||
def records(self):
|
||||
panel = self.go("commissions")
|
||||
panel.get_by_role("tab", name="每日记录", exact=True).click()
|
||||
expect(panel.locator('input[type="date"]')).to_have_value(self.today.isoformat())
|
||||
expect(panel.locator("tbody tr")).to_have_count(2)
|
||||
expect(panel).to_have_attribute("aria-busy", "false")
|
||||
return panel
|
||||
|
||||
def test_history_refresh_is_get_only_and_original_single_log_stays_collapsed(self):
|
||||
self.open()
|
||||
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
|
||||
panel = self.records()
|
||||
expect(panel.get_by_role("tab", name="每日记录")).to_have_attribute("aria-selected", "true")
|
||||
expect(panel.locator(".policy-form")).to_be_hidden()
|
||||
expect(panel.locator(".page-surface > p.page-summary")).to_contain_text("已记录接取 2 · 已记录完成 1")
|
||||
expect(panel.locator(".page-surface > p.page-summary")).to_contain_text("当日领奖确认氪金 15 · 当日接取标注氪金 35")
|
||||
expect(panel.locator('td[data-column="confirmed_ke"]')).to_have_text(["15", "未确认"])
|
||||
expect(self.page.locator("#log-panel")).to_have_count(1)
|
||||
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||
before = len(self.writes)
|
||||
with self.page.expect_request(lambda request: "/views/commissions?" in request.url) as seen:
|
||||
panel.get_by_role("button", name="刷新记录", exact=True).click()
|
||||
self.assertEqual(seen.value.method, "GET")
|
||||
expect(panel).to_have_attribute("aria-busy", "false")
|
||||
self.assertEqual(len(self.writes), before)
|
||||
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||
self.assertEqual(self.page.locator('[role="log"]').count(), 1)
|
||||
|
||||
panel.locator("tbody tr").first.click(button="right")
|
||||
with self.page.expect_request(lambda request: "/views/commissions?" in request.url) as seen:
|
||||
self.page.get_by_role("menuitem", name="刷新本页", exact=True).click()
|
||||
self.assertEqual(seen.value.method, "GET")
|
||||
expect(panel).to_have_attribute("aria-busy", "false")
|
||||
self.assertEqual(len(self.writes), before)
|
||||
artifact = Path(__file__).resolve().parents[3] / "test-artifacts" / "commission-history"
|
||||
artifact.mkdir(parents=True, exist_ok=True)
|
||||
self.page.screenshot(path=str(artifact / "desktop-daily-records.png"))
|
||||
|
||||
panel.locator("tbody tr").first.dblclick()
|
||||
detail = self.page.get_by_role("dialog")
|
||||
expect(detail).to_contain_text("委托详情")
|
||||
for value in ("铁矿石 ×2", "1级史莱姆 ×1", "城镇守卫", "战斗胜利", "回退15氪金"):
|
||||
expect(detail).to_contain_text(value)
|
||||
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||
|
||||
def test_current_policy_autosave_and_original_log_filters_commissions_in_both_subtabs(self):
|
||||
worker = self.manager._worker(self.first)
|
||||
worker.log("接取委托:仅委托可见(预计20氪金);已确认", category="commissions")
|
||||
worker.log("其他分类不可见", category="login")
|
||||
self.open()
|
||||
panel = self.go("commissions")
|
||||
with self.page.expect_request(lambda request: request.method == "PUT" and "/config" in request.url):
|
||||
panel.get_by_role("checkbox", name="允许提交道具(遵守保留数量)", exact=True).check()
|
||||
expect(self.page.locator("#save-status")).to_have_text("策略已自动保存")
|
||||
self.assertTrue(self.manager.get_config(self.first)["config"]["quest_policy"]["allow_items"])
|
||||
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||
self.page.locator("#log-toggle").click()
|
||||
expect(self.page.locator("#log-heading")).to_have_text("自动委托日志")
|
||||
expect(self.page.locator("#log-lines")).to_contain_text("仅委托可见")
|
||||
expect(self.page.locator("#log-lines")).not_to_contain_text("其他分类不可见")
|
||||
panel.get_by_role("tab", name="每日记录").click()
|
||||
expect(panel.get_by_label("记录日期(北京时间)")).to_be_visible()
|
||||
expect(self.page.locator("#log-panel")).to_be_visible()
|
||||
expect(self.page.locator("#log-panel")).to_have_count(1)
|
||||
expect(self.page.locator("#log-heading")).to_have_text("自动委托日志")
|
||||
expect(self.page.locator("#log-lines")).not_to_contain_text("其他分类不可见")
|
||||
|
||||
def test_date_account_isolation_and_keyboard_subtabs(self):
|
||||
self.open()
|
||||
panel = self.records()
|
||||
yesterday = (self.today - timedelta(days=1)).isoformat()
|
||||
panel.get_by_label("记录日期(北京时间)").fill(yesterday)
|
||||
expect(panel.locator("tbody tr").first).to_contain_text("账号一" + yesterday)
|
||||
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
|
||||
panel = self.records()
|
||||
expect(panel.get_by_label("记录日期(北京时间)")).to_have_value(self.today.isoformat())
|
||||
expect(panel.locator("tbody tr").first).to_contain_text("账号二" + self.today.isoformat())
|
||||
self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
|
||||
panel = self.page.locator('.page-panel[data-page="commissions"]:not([hidden])')
|
||||
expect(panel.get_by_label("记录日期(北京时间)")).to_have_value(yesterday)
|
||||
expect(panel.locator("tbody tr").first).to_contain_text("账号一" + yesterday)
|
||||
current = panel.get_by_role("tab", name="每日记录")
|
||||
current.focus()
|
||||
current.press("Home")
|
||||
expect(panel.get_by_role("tab", name="当前委托")).to_have_attribute("aria-selected", "true")
|
||||
expect(panel.locator('th[data-column="reward_ke"]')).to_have_text("标注氪金")
|
||||
expect(panel.locator("tbody tr").first).to_contain_text("城市尚未解锁")
|
||||
expect(panel.locator('td[data-column="status"]')).to_have_text(["暂不接取", "候选 / 条件待核对"])
|
||||
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||
|
||||
def test_loading_error_and_mobile_history_keep_original_layout(self):
|
||||
self.open()
|
||||
panel = self.records()
|
||||
self.hold = True
|
||||
panel.get_by_label("记录日期(北京时间)").fill((self.today - timedelta(days=2)).isoformat())
|
||||
expect(panel).to_have_attribute("aria-busy", "true")
|
||||
expect(panel.locator(".page-loading")).to_be_visible()
|
||||
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||
deadline = time.monotonic() + 5
|
||||
while not self.pending and time.monotonic() < deadline:
|
||||
self.page.wait_for_timeout(30)
|
||||
self.assertTrue(self.pending)
|
||||
self.hold = False
|
||||
route, dto = self.pending.pop(0)
|
||||
self.fulfill(route, {"loading": False, "data": dto})
|
||||
expect(panel).to_have_attribute("aria-busy", "false")
|
||||
expect(panel.locator(".page-loading")).to_be_hidden()
|
||||
self.fail_reads = True
|
||||
panel.get_by_role("button", name="刷新记录").click()
|
||||
expect(panel.locator(".page-error")).to_be_visible()
|
||||
expect(panel).to_have_attribute("aria-busy", "false")
|
||||
expect(self.page.locator("#log-panel")).to_be_hidden()
|
||||
self.fail_reads = False
|
||||
self.errors[:] = [error for error in self.errors if "503 (Service Unavailable)" not in error]
|
||||
panel.get_by_role("button", name="重新读取").click()
|
||||
expect(panel.locator(".page-error")).to_be_hidden()
|
||||
self.page.set_viewport_size({"width": 390, "height": 844})
|
||||
expect(panel.get_by_label("记录日期(北京时间)")).to_be_visible()
|
||||
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), 391)
|
||||
artifact = Path(__file__).resolve().parents[3] / "test-artifacts" / "commission-history"
|
||||
artifact.mkdir(parents=True, exist_ok=True)
|
||||
self.page.screenshot(path=str(artifact / "mobile-daily-records.png"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -51,8 +51,22 @@ class PageLoadingBrowserTests(unittest.TestCase):
|
||||
"details": {"help": "STATIC_HELP_SENTINEL", "note": "STATIC_NOTE_SENTINEL",
|
||||
"notes": ["金币不足,等待补货"]}}}
|
||||
self.hold, self.fail = False, False
|
||||
self.hold_after_real_retry_click = False
|
||||
self.page.add_init_script("""(() => {
|
||||
window.__loadingRetryClicked = false;
|
||||
document.addEventListener('click', event => {
|
||||
if (event.target instanceof Element && event.target.closest('.page-panel[data-page="bag"] .page-error button')) {
|
||||
window.__loadingRetryClicked = true;
|
||||
}
|
||||
}, true);
|
||||
})();""")
|
||||
|
||||
def view(route):
|
||||
if self.hold_after_real_retry_click:
|
||||
if not self.page.evaluate("window.__loadingRetryClicked"):
|
||||
route.fulfill(status=503, content_type="application/json", body='{"detail":"读取失败"}')
|
||||
return
|
||||
self.hold_after_real_retry_click = False
|
||||
if self.hold:
|
||||
self.pending.append(route)
|
||||
elif self.fail:
|
||||
@@ -156,8 +170,16 @@ class PageLoadingBrowserTests(unittest.TestCase):
|
||||
expect(panel.locator(".page-error")).to_be_visible()
|
||||
expect(panel).to_have_attribute("aria-busy", "false")
|
||||
expect(panel.locator(".page-loading")).to_be_hidden()
|
||||
# Passive polling must keep returning the error until the native click.
|
||||
# Holding a passive request here would hide the button before it can click.
|
||||
self.hold_after_real_retry_click = True
|
||||
self.hold, self.fail = True, False
|
||||
with self.page.expect_response(lambda response: "/views/bag?" in response.url and response.status == 503):
|
||||
pass # Exercise a real passive refresh during this transition.
|
||||
expect(panel.locator(".page-error")).to_be_visible()
|
||||
self.assertEqual(self.pending, [], "Passive errors must not park a request before the retry click")
|
||||
panel.get_by_role("button", name="重新读取").click()
|
||||
self.assertTrue(self.page.evaluate("window.__loadingRetryClicked"))
|
||||
route = self.wait_request()
|
||||
self.assert_centered(panel)
|
||||
self.summary.update(connection_state="offline", connected=False, connection_message="连接已中断")
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Commission DTO regressions with temporary engines and synthetic local history."""
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.model import Catalog
|
||||
from ranch_web.policies import default_config
|
||||
from ranch_web.views import build_view
|
||||
|
||||
|
||||
def history_fixture(day):
|
||||
return {"date": day, "dates": [day], "summary": {
|
||||
"accepted_count": 2, "completed_count": 1, "expected_ke": 35, "confirmed_ke": 15, "pending_count": 1, "unknown_reward_count": 0},
|
||||
"rows": [{"id": "local-15", "task_id": 71, "task_type_id": "test15", "name": "提交魔物与道具",
|
||||
"status": "completed", "accepted_at": day + "T01:02:03+00:00", "completed_at": day + "T02:03:04+00:00",
|
||||
"expected_ke": 15, "confirmed_ke": 15, "selection_reason": "20氪金候选城市尚未解锁,回退15氪金",
|
||||
"last_action": "服务器已确认领取15氪金", "events": [
|
||||
{"time": day + "T01:02:03+00:00", "kind": "accept", "status": "confirmed", "description": "接取委托,预计15氪金"},
|
||||
{"time": day + "T01:03:03+00:00", "kind": "handin_items", "status": "confirmed", "description": "已提交铁矿石 ×2"},
|
||||
{"time": day + "T01:04:03+00:00", "kind": "handin_monsters", "status": "confirmed", "description": "已提交1级史莱姆 ×1"},
|
||||
{"time": day + "T01:05:03+00:00", "kind": "dialogue", "status": "confirmed", "description": "已与城镇守卫对话"},
|
||||
{"time": day + "T01:06:03+00:00", "kind": "battle", "status": "confirmed", "description": "委托战斗胜利,推进第4步"},
|
||||
{"time": day + "T02:03:04+00:00", "kind": "claim", "status": "confirmed", "description": "服务器奖励回包确认氪金15"}]},
|
||||
{"id": "local-20", "task_id": 72, "task_type_id": "test20", "name": "奖励待核对的委托",
|
||||
"status": "unknown", "accepted_at": day + "T03:02:03+08:00", "completed_at": None,
|
||||
"expected_ke": 20, "confirmed_ke": None, "last_action": "领奖请求超时,等待核对",
|
||||
"events": [{"time": day + "T03:03:04+08:00", "kind": "claim", "status": "unknown", "description": "领奖回包未知"}]}]}
|
||||
|
||||
|
||||
class CommissionHistoryViewTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
root = self.enterContext(tempfile.TemporaryDirectory(prefix="commission-web-history-"))
|
||||
self.engine = Engine(Catalog(), budget_path=Path(root) / "budget.json")
|
||||
self.engine.snapshot = demo_snapshot(self.engine.catalog)
|
||||
self.engine.demo = False
|
||||
self.engine.client = Mock()
|
||||
self.engine.client.call.side_effect = AssertionError("Game calls forbidden in history views")
|
||||
self.config = default_config()
|
||||
self.history = history_fixture("2026-11-12")
|
||||
self.engine.commission_history = Mock(return_value=self.history)
|
||||
self.engine.commission_offer_diagnostics = Mock(return_value=[])
|
||||
|
||||
def view(self, **query):
|
||||
return build_view(self.engine, "commissions", self.config, {"tab": "history", **query})
|
||||
|
||||
def test_history_reads_only_local_helper_and_separates_confirmed_rewards(self):
|
||||
self.engine.tasks.rows = Mock(side_effect=AssertionError("Current tasks are not history"))
|
||||
self.engine.progression_rows = Mock(side_effect=AssertionError("Do not plan game actions in history"))
|
||||
self.engine.commission_offer_diagnostics.side_effect = AssertionError("History must not inspect current offers")
|
||||
self.engine.plans = Mock(side_effect=AssertionError("Do not plan in history"))
|
||||
dto = self.view(date="2026-11-12")
|
||||
self.engine.commission_history.assert_called_once_with(day="2026-11-12")
|
||||
self.engine.client.call.assert_not_called()
|
||||
self.assertEqual([tab["title"] for tab in dto["tabs"]], ["当前委托", "每日记录"])
|
||||
self.assertEqual(dto["form"], [])
|
||||
self.assertEqual(dto["actions"], [{"operation": "reload_view", "label": "刷新记录"}])
|
||||
self.assertIn("已记录接取 2", dto["summary"])
|
||||
self.assertIn("已记录完成 1", dto["summary"])
|
||||
self.assertIn("仅有本地已保存记录", dto["summary"])
|
||||
self.assertIn("当日领奖确认氪金 15", dto["summary"])
|
||||
self.assertIn("当日接取标注氪金 35", dto["summary"])
|
||||
self.assertIn("操作待核对 1", dto["summary"])
|
||||
self.assertIn("领奖金额未记录 0", dto["summary"])
|
||||
self.assertEqual(dto["rows"][1]["confirmed_ke"], "未确认")
|
||||
self.assertEqual(dto["rows"][1]["status_label"], "结果待核对")
|
||||
self.assertEqual(dto["rows"][0]["accepted_at"], "2026-11-12 09:02:03")
|
||||
self.assertEqual(dto["rows"][1]["completed_at"], "—")
|
||||
json.dumps(dto, ensure_ascii=False, allow_nan=False)
|
||||
|
||||
def test_details_show_actual_handins_dialogue_battle_and_claim_evidence(self):
|
||||
dto = self.view(date="2026-11-12")
|
||||
detail = dto["details"]["local-15"]
|
||||
for text in ("铁矿石 ×2", "1级史莱姆 ×1", "城镇守卫", "战斗胜利", "氪金15"):
|
||||
self.assertIn(text, detail["行动记录"])
|
||||
self.assertIn("回退15氪金", detail["选择 / 回退原因"])
|
||||
self.assertIn("结果待核对", dto["details"]["local-20"]["行动记录"])
|
||||
self.assertNotIn("已确认", dto["details"]["local-20"]["行动记录"])
|
||||
|
||||
def test_search_can_find_action_details_without_changing_daily_totals(self):
|
||||
dto = self.view(date="2026-11-12", search="铁矿石")
|
||||
self.assertEqual([row["id"] for row in dto["rows"]], ["local-15"])
|
||||
self.assertIn("已记录接取 2", dto["summary"])
|
||||
self.assertEqual(set(dto["details"]), {"local-15"})
|
||||
|
||||
def test_empty_history_does_not_invent_old_acceptance_from_current_tasks(self):
|
||||
self.engine.snapshot.raw["currentTasks"] = [{"id": 3, "typeId": "test20", "curStep": 1}]
|
||||
self.engine.commission_history.return_value = {"date": "2026-11-11", "summary": {}, "rows": []}
|
||||
dto = self.view(date="2026-11-11")
|
||||
self.assertEqual(dto["rows"], [])
|
||||
self.assertIn("已记录接取 0", dto["summary"])
|
||||
self.assertIn("历史接取与奖励未追溯", dto["summary"])
|
||||
|
||||
def test_history_available_without_snapshot(self):
|
||||
self.engine.snapshot = None
|
||||
dto = self.view(date="2026-11-12")
|
||||
self.assertEqual(len(dto["rows"]), 2)
|
||||
self.engine.client.call.assert_not_called()
|
||||
current = build_view(self.engine, "commissions", self.config)
|
||||
self.assertIn("请先登录", current["summary"])
|
||||
self.assertEqual(len(current["tabs"]), 2)
|
||||
|
||||
def test_default_date_is_beijing_today_at_utc_day_boundary(self):
|
||||
class FixedDatetime(datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return cls(2026, 11, 12, 17, tzinfo=timezone.utc).astimezone(tz)
|
||||
|
||||
with patch("ranch_web.views.datetime", FixedDatetime):
|
||||
dto = self.view()
|
||||
self.engine.commission_history.assert_called_once_with(day="2026-11-13")
|
||||
self.assertEqual(dto["filters"][0]["value"], "2026-11-13")
|
||||
self.assertEqual(dto["filters"][0]["type"], "date")
|
||||
|
||||
def test_invalid_date_never_calls_history_helper(self):
|
||||
for day in ("2026-11-31", "2026-1-1", "../2026-11-12", ["2026-11-12"]):
|
||||
with self.subTest(day=day), self.assertRaisesRegex(ValueError, "记录日期"):
|
||||
self.view(date=day)
|
||||
self.engine.commission_history.assert_not_called()
|
||||
|
||||
def test_raw_history_fields_never_reach_public_view(self):
|
||||
row = self.history["rows"][0]
|
||||
row["raw_response"] = {"token": "private-response"}
|
||||
row["events"][0].update(raw={"password": "private-event"}, payload={"removeIds": [1234567]})
|
||||
wire = json.dumps(self.view(date="2026-11-12"), ensure_ascii=False)
|
||||
for value in ("private-response", "private-event", "1234567", "raw_response", "removeIds"):
|
||||
self.assertNotIn(value, wire)
|
||||
|
||||
def test_current_offer_presence_never_implies_receivable(self):
|
||||
self.engine.catalog.data["task_info"] = {
|
||||
"test20": {"name": "高额候选", "reward": {"money": 123, "ke": 20}},
|
||||
"test15": {"name": "回退候选", "reward": {"money": 456, "ke": 15}}}
|
||||
self.engine.tasks.rows = Mock(return_value=[
|
||||
("test20", "高额候选", "城市 4 可接", "提交物品", {"city": 4}),
|
||||
("test15", "回退候选", "城市 1 可接", "提交金币", {"city": 1})])
|
||||
self.engine.tasks.current = Mock(return_value=[])
|
||||
self.engine.progression_rows = Mock(return_value=[
|
||||
{"category": "commission", "task_type_id": "test20", "block_reason": "城市尚未解锁"},
|
||||
{"category": "commission", "task_type_id": "test15", "selection_reason": "20氪金候选未解锁,回退15氪金"}])
|
||||
dto = build_view(self.engine, "commissions", self.config)
|
||||
high, fallback = dto["rows"]
|
||||
self.assertEqual(high["reward_ke"], 20)
|
||||
self.assertEqual(high["reward_money"], 123)
|
||||
self.assertEqual(high["status"], "暂不接取")
|
||||
self.assertEqual(high["reason"], "城市尚未解锁")
|
||||
self.assertNotIn("可接", fallback["status"])
|
||||
self.assertIn("回退15氪金", fallback["selection_reason"])
|
||||
self.assertIn("20 → 15 → 10", dto["details"][fallback["id"]]["接取优先级"])
|
||||
|
||||
def test_authoritative_offer_diagnostics_match_city_and_explain_fallback(self):
|
||||
self.engine.catalog.data["task_info"] = {
|
||||
"test20": {"name": "高额候选", "reward": {"money": 123, "ke": 20}},
|
||||
"test15": {"name": "回退候选", "reward": {"money": 456, "ke": 15}}}
|
||||
self.engine.tasks.rows = Mock(return_value=[
|
||||
("test20", "高额候选", "城市 4 可接", "", {"city": 4}),
|
||||
("test15", "回退候选", "城市 1 可接", "", {"city": 1}),
|
||||
("test15", "回退候选", "城市 9 可接", "", {"city": 9})])
|
||||
self.engine.tasks.current = Mock(return_value=[])
|
||||
self.engine.progression_rows = Mock(return_value=[
|
||||
{"category": "commission", "task_type_id": "test15", "block_reason": "错误城市的阻塞原因"}])
|
||||
self.engine.commission_offer_diagnostics.return_value = [
|
||||
{"task_type_id": "test20", "name": "高额候选", "city": 4, "expected_ke": 20, "eligible": False, "reason": "城市尚未解锁"},
|
||||
{"task_type_id": "test15", "name": "回退候选", "city": 1, "expected_ke": 15, "eligible": True, "reason": "可接取"},
|
||||
{"task_type_id": "test15", "name": "回退候选", "city": 9, "expected_ke": 15, "eligible": False, "reason": "提交魔物受保留保护"}]
|
||||
dto = build_view(self.engine, "commissions", self.config)
|
||||
self.assertEqual([row["status"] for row in dto["rows"]], ["暂不接取", "可接取", "暂不接取"])
|
||||
self.assertIn("选择 15 氪金", dto["rows"][1]["selection_reason"])
|
||||
self.assertIn("城市尚未解锁", dto["rows"][1]["selection_reason"])
|
||||
self.assertNotIn("错误城市", dto["rows"][1]["reason"])
|
||||
self.assertEqual(dto["rows"][2]["reason"], "提交魔物受保留保护")
|
||||
self.engine.client.call.assert_not_called()
|
||||
|
||||
def test_pending_zero_reward_and_cross_day_totals_remain_distinct(self):
|
||||
self.history["rows"][0].update(expected_ke=20, confirmed_ke=0, accepted_at="2026-11-11T01:02:03+08:00")
|
||||
self.history["rows"][1]["status"] = "pending"
|
||||
self.history["summary"].update(accepted_count=0, expected_ke=0, confirmed_ke=0)
|
||||
dto = self.view(date="2026-11-12")
|
||||
self.assertEqual(dto["rows"][0]["confirmed_ke"], 0)
|
||||
self.assertEqual(dto["rows"][0]["expected_ke"], 20)
|
||||
self.assertEqual(dto["rows"][1]["confirmed_ke"], "未确认")
|
||||
self.assertEqual(dto["rows"][1]["status_label"], "等待核对")
|
||||
self.assertIn("当日接取标注氪金 0", dto["summary"])
|
||||
self.assertNotIn("损失", dto["summary"])
|
||||
|
||||
def test_backend_read_error_visible_without_exposing_private_fields(self):
|
||||
self.history.update(error="委托历史无法读取,原文件已保留", notice="仅展示本地已保存记录")
|
||||
dto = self.view(date="2026-11-12")
|
||||
self.assertIn("委托历史无法读取,原文件已保留", dto["summary"])
|
||||
self.assertIn("仅有本地已保存记录", dto["summary"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Real worker/local ledger integration; game transports are always offline fakes."""
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from ranch_assistant.engine import Engine
|
||||
from ranch_web.tests import test_service as fixtures
|
||||
|
||||
|
||||
class CommissionHistoryServiceTests(unittest.TestCase):
|
||||
setUp = fixtures.ServiceTests.setUp
|
||||
account = fixtures.ServiceTests.account
|
||||
idle = fixtures.ServiceTests.idle
|
||||
job = fixtures.ServiceTests.job
|
||||
|
||||
def view(self, identifier, day):
|
||||
response = self.manager.view(identifier, "commissions", {"tab": "history", "date": day})
|
||||
if response["loading"]:
|
||||
self.job(identifier, {"id": response["job_id"]})
|
||||
response = self.manager.view(identifier, "commissions", {"tab": "history", "date": day})
|
||||
self.assertFalse(response["loading"])
|
||||
return response["data"]
|
||||
|
||||
def tick(self, identifier, *, failed=False):
|
||||
worker = self.manager._worker(identifier)
|
||||
with patch.object(worker.schedule, "due", return_value="poll"):
|
||||
self.job(identifier, worker.enqueue("__tick"), status="failed" if failed else "succeeded")
|
||||
|
||||
def test_real_local_ledger_history_is_account_role_day_isolated_without_game_calls(self):
|
||||
first, second = self.account(), self.account()
|
||||
worker = self.manager._worker(first)
|
||||
engine = worker.engine
|
||||
role = str(engine.snapshot.raw["master"]["id"])
|
||||
today = datetime.now(timezone(timedelta(hours=8))).date()
|
||||
stamp = datetime.combine(today, datetime.min.time(), timezone(timedelta(hours=8))).timestamp() + 3600
|
||||
info = {"type": 4, "name": "已保存的20氪金委托", "reward": {"ke": 20}}
|
||||
record = {"attempt_id": "synthetic-accept", "role_id": role, "task_type_id": "test20", "task_id": 71,
|
||||
"kind": "quest_accept", "path": "taskService/taskLoopReceive", "timestamp": stamp,
|
||||
"finished_at": stamp, "phase": "done", "outcome": "task", "response_confirmed": True,
|
||||
"response": {"resCode": 0, "task": {"id": 71, "typeId": "test20", "curStep": 1}},
|
||||
"commission": {"name": info["name"], "expected_ke": 20}}
|
||||
engine._commission_history.ingest(role, [record], lambda _: info, engine.snapshot)
|
||||
after = self.manager.logs(first)["next"]
|
||||
with patch.object(engine, "read_snapshot", side_effect=AssertionError("history must stay local")), \
|
||||
patch.object(engine, "poll", side_effect=AssertionError("history must not poll")):
|
||||
dto = self.view(first, today.isoformat())
|
||||
self.assertIn("已记录接取 1", dto["summary"])
|
||||
self.assertEqual(dto["rows"][0]["confirmed_ke"], "未确认")
|
||||
self.assertEqual(self.view(second, today.isoformat())["rows"], [])
|
||||
self.assertEqual(self.view(first, (today - timedelta(days=1)).isoformat())["rows"], [])
|
||||
original = engine.snapshot
|
||||
engine.snapshot = deepcopy(original)
|
||||
engine.snapshot.raw["master"]["id"] = "other-local-role"
|
||||
worker._invalidate_views()
|
||||
self.assertEqual(self.view(first, today.isoformat())["rows"], [])
|
||||
engine.snapshot = original
|
||||
worker._invalidate_views()
|
||||
self.assertEqual(len(self.view(first, today.isoformat())["rows"]), 1)
|
||||
self.assertEqual(fixtures.FakeClient.calls, [])
|
||||
self.assertEqual(self.manager.logs(first, after=after)["entries"], [], "Reading history must not create activity logs")
|
||||
|
||||
def test_accept_step_claim_and_unknown_messages_are_chinese_categorized_and_redacted(self):
|
||||
def action(engine, intent):
|
||||
return engine.snapshot, [], intent["message"]
|
||||
|
||||
with patch.object(Engine, "_run_progression_intent", action):
|
||||
identifier = self.account()
|
||||
worker = self.manager._worker(identifier)
|
||||
worker.engine.game_data = SimpleNamespace(task=lambda _: {"type": 4})
|
||||
messages = [
|
||||
("接取委托:本地测试(预计20氪金);已确认", "info"),
|
||||
("提交委托步骤:本地测试(预计20氪金);已提交铁矿石 ×2", "info"),
|
||||
("领取委托奖励:本地测试(预计20氪金);已确认,实际获得20氪金", "info"),
|
||||
("领取委托奖励:本地测试(预计20氪金);结果未知,等待核对,禁止重发", "warning"),
|
||||
("委托战斗:本地测试(预计20氪金);战斗失败,未推进委托", "error")]
|
||||
for message, level in messages:
|
||||
with self.subTest(message=message):
|
||||
before = self.manager.logs(identifier)["next"]
|
||||
intent = {"kind": "progression_complete", "task_type_id": "test20", "message": message + ";password=synthetic-password"}
|
||||
with patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent(intent)):
|
||||
self.tick(identifier)
|
||||
entries = self.manager.logs(identifier, after=before)["entries"]
|
||||
self.assertEqual(len(entries), 1)
|
||||
self.assertEqual((entries[0]["category"], entries[0]["level"]), ("commissions", level))
|
||||
self.assertIn("本地测试", entries[0]["message"])
|
||||
self.assertIn("20氪金", entries[0]["message"])
|
||||
self.assertNotIn("synthetic-password", entries[0]["message"])
|
||||
|
||||
def test_failed_commission_keeps_one_error_with_name_reward_and_no_success(self):
|
||||
def action(engine, intent):
|
||||
raise TimeoutError("token=synthetic-token 请求超时")
|
||||
|
||||
with patch.object(Engine, "_run_progression_intent", action):
|
||||
identifier = self.account()
|
||||
worker = self.manager._worker(identifier)
|
||||
worker.engine.game_data = SimpleNamespace(task=lambda _: {"type": 4, "name": "受保护的提交委托", "reward": {"ke": 20}})
|
||||
before = self.manager.logs(identifier)["next"]
|
||||
intent = {"kind": "progression_loop_accept", "task_type_id": "test20"}
|
||||
with patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent(intent)):
|
||||
self.tick(identifier, failed=True)
|
||||
entries = self.manager.logs(identifier, after=before)["entries"]
|
||||
self.assertEqual(len(entries), 1)
|
||||
self.assertEqual((entries[0]["category"], entries[0]["level"]), ("commissions", "error"))
|
||||
for value in ("受保护的提交委托", "标注20氪金", "接取异常", "结果待核对"):
|
||||
self.assertIn(value, entries[0]["message"])
|
||||
self.assertNotIn("synthetic-token", entries[0]["message"])
|
||||
self.assertNotIn("已确认", entries[0]["message"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+101
-9
@@ -13,6 +13,7 @@ from ranch_assistant.drop_statistics import analyze
|
||||
from ranch_assistant.presentation import monster_rows
|
||||
from ranch_assistant.battle_messages import battle_message
|
||||
from ranch_assistant.resource_stages import available_item_count, item_requirements, with_resource_data
|
||||
from ranch_assistant.quests import commission_priority, commission_selection
|
||||
from .policies import default_config, validate_config
|
||||
|
||||
|
||||
@@ -126,7 +127,10 @@ def build_view(engine, page, config, query=None):
|
||||
"form": [field | {"value": _value(config, field["path"])} for field in fields],
|
||||
"filters": [], "details": {}, "actions": [{"operation": "refresh", "label": "刷新本页", "payload": {"page": page}}]}
|
||||
builder = _BUILDERS.get(page)
|
||||
if engine.snapshot is None and page not in ("login", "yields", "statistics"):
|
||||
if page == "commissions":
|
||||
dto["tabs"] = [{"key": "current", "title": "当前委托"}, {"key": "history", "title": "每日记录"}]
|
||||
local_history = page == "commissions" and (query or {}).get("tab") == "history"
|
||||
if engine.snapshot is None and page not in ("login", "yields", "statistics") and not local_history:
|
||||
dto["summary"] = "请先登录或打开离线演示"
|
||||
return dto
|
||||
if builder is not None:
|
||||
@@ -562,33 +566,121 @@ def _battles(dto, engine, config, query):
|
||||
dto["actions"] = [{"operation": "refresh_tasks", "label": "刷新战斗记录", "payload": {}}]
|
||||
|
||||
|
||||
COMMISSION_STATES = {"accepted": "已接取", "active": "进行中", "in_progress": "进行中", "completed": "已完成", "pending": "等待核对",
|
||||
"claimed": "已领奖", "confirmed": "已确认", "unknown": "结果待核对", "failed": "失败", "cancelled": "已取消", "observed": "仅观察到任务", "blocked": "等待条件"}
|
||||
COMMISSION_EVENTS = {"accept": "接取", "step": "推进步骤", "claim": "领取奖励", "complete": "领取奖励", "dialogue": "对话", "battle": "战斗",
|
||||
"navigate": "前往任务地点", "farm": "收集委托材料", "local_step": "步骤收尾", "reset": "刷新每日委托",
|
||||
"handin": "交付", "handin_items": "提交道具", "handin_monsters": "提交魔物", "handin_money": "提交金币",
|
||||
"quest_accept": "接取", "quest_step": "推进步骤", "quest_complete": "领取奖励", "observe": "观察到任务"}
|
||||
|
||||
|
||||
def _commission_time(value):
|
||||
if value is None or value == "":
|
||||
return "—"
|
||||
try:
|
||||
if type(value) in (int, float):
|
||||
stamp = datetime.fromtimestamp(value / 1000 if value >= 1e12 else value, CHINA_TIME)
|
||||
elif isinstance(value, str):
|
||||
stamp = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
if stamp.tzinfo is None:
|
||||
stamp = stamp.replace(tzinfo=CHINA_TIME)
|
||||
else:
|
||||
return "—"
|
||||
return stamp.astimezone(CHINA_TIME).strftime("%Y-%m-%d %H:%M:%S")
|
||||
except (ValueError, OverflowError, OSError):
|
||||
return "时间未确认"
|
||||
|
||||
|
||||
def _commission_history(dto, engine, query):
|
||||
selected = query.get("date") or datetime.now(CHINA_TIME).date().isoformat()
|
||||
try:
|
||||
if not isinstance(selected, str) or datetime.strptime(selected, "%Y-%m-%d").date().isoformat() != selected:
|
||||
raise ValueError
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("记录日期须为 YYYY-MM-DD") from None
|
||||
history = engine.commission_history(day=selected)
|
||||
totals = history.get("summary") or {}
|
||||
dto["form"] = []
|
||||
dto["actions"] = [{"operation": "reload_view", "label": "刷新记录"}]
|
||||
dto["filters"] = [_filter("date", "记录日期(北京时间)", selected, kind="date")]
|
||||
search = _search(dto, query)
|
||||
dto["columns"] = [_column(key, label) for key, label in (("name", "委托"), ("status_label", "状态"),
|
||||
("expected_ke", "预计氪金"), ("confirmed_ke", "已确认氪金"), ("accepted_at", "接取时间(北京时间)"),
|
||||
("completed_at", "完成时间(北京时间)"), ("last_action", "最近行动"))]
|
||||
sources = history.get("rows") or []
|
||||
for index, source in enumerate(sources):
|
||||
status = _text(source.get("status"), "unknown")
|
||||
row = {"id": _text(source.get("id"), str(index)), "task_type_id": _text(source.get("task_type_id")),
|
||||
"name": _text(source.get("name")), "status_label": COMMISSION_STATES.get(status, "结果待核对"),
|
||||
"expected_ke": source.get("expected_ke") if type(source.get("expected_ke")) in (int, float) else "未记录",
|
||||
"confirmed_ke": source.get("confirmed_ke") if type(source.get("confirmed_ke")) in (int, float) else "未确认",
|
||||
"accepted_at": _commission_time(source.get("accepted_at")), "completed_at": _commission_time(source.get("completed_at")),
|
||||
"last_action": _text(source.get("last_action"), "暂无行动记录")}
|
||||
events = []
|
||||
for event in source.get("events") or []:
|
||||
kind, outcome = _text(event.get("kind"), "unknown"), _text(event.get("status"), "unknown")
|
||||
label = {"success": "已确认", "succeeded": "已确认", "confirmed": "已确认", "completed": "已确认",
|
||||
"failed": "失败", "unknown": "结果待核对", "pending": "等待核对", "cancelled": "已取消"}.get(outcome, "结果待核对")
|
||||
events.append(f"{_commission_time(event.get('time'))} · {COMMISSION_EVENTS.get(kind, '委托行动')} · {label} · {_text(event.get('description'))}")
|
||||
detail = {"委托": row["name"], "任务编号": row["task_type_id"], "状态": row["status_label"],
|
||||
"预计氪金": row["expected_ke"], "已确认氪金": row["confirmed_ke"], "接取时间(北京时间)": row["accepted_at"],
|
||||
"完成时间(北京时间)": row["completed_at"], "选择 / 回退原因": _text(source.get("selection_reason"), "未记录"),
|
||||
"行动记录": "\n".join(events) or "暂无行动记录"}
|
||||
if search and search not in " ".join(map(str, [*row.values(), *detail.values()])).casefold():
|
||||
continue
|
||||
dto["rows"].append(row)
|
||||
dto["details"][row["id"]] = detail
|
||||
dto["summary"] = (f"{selected} · 已记录接取 {totals.get('accepted_count', 0)} · 已记录完成 {totals.get('completed_count', 0)}"
|
||||
f" · 当日领奖确认氪金 {totals.get('confirmed_ke', 0)} · 当日接取标注氪金 {totals.get('expected_ke', 0)}"
|
||||
f" · 操作待核对 {totals.get('pending_count', 0)} · 领奖金额未记录 {totals.get('unknown_reward_count', 0)}")
|
||||
dto["summary"] += ";仅有本地已保存记录" if sources else ";当日暂无本地记录,历史接取与奖励未追溯"
|
||||
if history.get("error"):
|
||||
dto["summary"] += ";" + _text(history["error"])
|
||||
|
||||
|
||||
def _commissions(dto, engine, config, query):
|
||||
if query.get("tab") == "history":
|
||||
_commission_history(dto, engine, query)
|
||||
return
|
||||
snapshot, catalog = engine.snapshot, engine.catalog
|
||||
search = _search(dto, query)
|
||||
dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("name", "委托"), ("status", "状态"),
|
||||
("reward_money", "金币奖励"), ("reward_ke", "氪金奖励"), ("reason", "需求 / 下一步 / 阻塞原因"))]
|
||||
dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("name", "委托"), ("city", "城市"), ("status", "状态"),
|
||||
("reward_money", "标注金币"), ("reward_ke", "标注氪金"), ("selection_reason", "选择 / 回退原因"), ("reason", "需求 / 下一步 / 阻塞原因"))]
|
||||
diagnostics = {str(row.get("task_type_id")): row for row in engine.progression_rows() if _category(row.get("category")) == "commission"}
|
||||
source = engine.tasks.rows(snapshot, engine.quest_policy, engine.policy)
|
||||
offer_rows = engine.commission_offer_diagnostics()
|
||||
offers = {(str(row.get("task_type_id")), str(row.get("city"))): row for row in offer_rows}
|
||||
selected = next((row for row in offer_rows if row.get("eligible") is True), {})
|
||||
selection = commission_selection({"reward": {"ke": selected.get("expected_ke", 0)}}, offer_rows,
|
||||
[row for row in offer_rows if row.get("eligible") is False]) if selected else {}
|
||||
source = sorted(engine.tasks.rows(snapshot, engine.quest_policy, engine.policy), key=lambda row: (
|
||||
"city" in row[4], commission_priority(catalog.data.get("task_info", {}).get(str(row[0]), {}))))
|
||||
for index, (key, name, status, text, meta) in enumerate(source):
|
||||
diagnostic = diagnostics.get(str(key), {})
|
||||
reason = diagnostic.get("block_reason") or diagnostic.get("blocked_reason")
|
||||
offer = offers.get((str(key), str(meta.get("city"))), {}) if "city" in meta else {}
|
||||
if "city" in meta:
|
||||
status = "可接取" if offer.get("eligible") is True else "候选 / 条件待核对"
|
||||
reason = (offer.get("reason") if offer.get("eligible") is False else None) if offer else diagnostic.get("block_reason") or diagnostic.get("blocked_reason")
|
||||
if reason:
|
||||
status = "暂不接取" if "city" in meta else "等待条件"
|
||||
text = reason
|
||||
elif diagnostic.get("next_action"):
|
||||
elif not offer and diagnostic.get("next_action"):
|
||||
text = diagnostic["next_action"]
|
||||
info = catalog.data.get("task_info", {}).get(str(key), {})
|
||||
reward = info.get("reward") or {}
|
||||
row = {"id": f"{key}:{index}", "task_type_id": str(key), "name": name, "status": status,
|
||||
"reward_money": reward.get("money", 0), "reward_ke": reward.get("ke", 0), "reason": battle_message(text),
|
||||
"city": meta.get("city"), "active": "city" not in meta}
|
||||
"city": meta.get("city"), "active": "city" not in meta,
|
||||
"selection_reason": _text(offer.get("selection_reason") or (selection.get("selection_reason") if offer and offer == selected else None)
|
||||
or diagnostic.get("selection_reason") or meta.get("selection_reason") or (reason if "city" in meta else None),
|
||||
"较高氪金的可执行委托优先" if offer.get("eligible") is True else "接取条件待核对" if "city" in meta else "已接取,优先推进当前委托")}
|
||||
if search and search not in " ".join(map(str, row.values())).casefold():
|
||||
continue
|
||||
dto["rows"].append(row)
|
||||
dto["details"][row["id"]] = {"描述": info.get("des", ""), "需求 / 下一步": row["reason"],
|
||||
dto["details"][row["id"]] = {"描述": info.get("des", ""), "标注奖励": reward_summary(catalog, reward),
|
||||
"城市": _text(meta.get("city")), "选择 / 回退原因": row["selection_reason"], "需求 / 下一步": row["reason"],
|
||||
"交付限制": {"允许物品": engine.quest_policy.allow_items, "允许魔物": engine.quest_policy.allow_monsters,
|
||||
"单次金币上限": engine.quest_policy.max_money, "允许已支持战斗": engine.quest_policy.battle_tasks},
|
||||
"接取优先级": "氪金奖励较高的委托优先;仅接取原规划器确认可支持的委托"}
|
||||
"接取优先级": "跨城市按标注氪金 20 → 15 → 10 优先;20 氪金均不可用时回退到可执行的 15 / 10 氪金委托"}
|
||||
dto["summary"] = f"今日剩余可接次数:{snapshot.raw.get('history', {}).get('loopTaskNum', '未知')};当前委托:{len(engine.tasks.current(snapshot))}"
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user