feat: add daily commission history for Web 2.0.8

This commit is contained in:
AttilaNet
2026-11-13 09:59:43 +08:00
parent ad25d5b403
commit 296653d8d3
25 changed files with 2179 additions and 96 deletions
+196
View File
@@ -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()