fix(douyu): 恢复限兑商品查询展示口径

This commit is contained in:
yml
2026-11-22 22:43:22 +08:00
parent 3ad7310a6e
commit 053461b353
4 changed files with 110 additions and 48 deletions
+10
View File
@@ -423,6 +423,16 @@ class TestOverviewAggregation:
assert "兔兔白日梦" in self._run().marked["message"]
assert "已拥有 1 个" in self._run().marked["message"]
def test_limited_goods_view_uses_legacy_message(self):
self.task.result = {"payload": {"view": "limited_goods"}}
self.session.commit()
h = self._run()
assert h.marked["result"]["view"] == "limited_goods"
assert h.marked["message"].startswith("已达上限 1 个:")
assert "兔兔白日梦" in h.marked["message"]
def test_is_read_only_no_events_and_no_status_change(self):
"""纯查询不是「事实」—— 不能进时间线,也不能改生命周期状态。"""
before = self.session.query(AccountEvent).count()
+49 -27
View File
@@ -124,13 +124,38 @@ def _group_by_scope(
return grouped
def _overview_owned_text(snapshot: dict[str, Any]) -> str:
def _overview_success_message(
snapshot: dict[str, Any],
errors: dict[str, Any],
*,
view: str = "",
) -> str:
if view == "limited_goods":
goods = [
str(item.get("commodityName") or item.get("name") or "")
for item in (snapshot.get("limited_goods") or [])
if isinstance(item, dict)
]
names = [name for name in goods if name]
message = (
"无受限商品(均可兑换)"
if not names
else f"已达上限 {len(names)} 个: {', '.join(names[:5])}"
)
if errors.get("limited_goods"):
message += f"({errors['limited_goods']})"
return message
owned = [
str(item.get("name") or "")
for item in (snapshot.get("high_value_goods") or [])
if isinstance(item, dict) and not item.get("missing") and item.get("owned")
g["name"]
for g in (snapshot.get("high_value_goods") or [])
if isinstance(g, dict) and not g.get("missing") and g.get("owned")
]
return f": {', '.join(owned)}" if owned else ""
message = f"一键查询完成;高价值套装已拥有 {len(owned)} 个"
if owned:
message += f": {', '.join(owned)}"
if errors:
message += f"({len(errors)} 项未取到)"
return message
def _goods_config(config: dict) -> list[str]:
@@ -177,7 +202,15 @@ class OverviewMixin:
def _client(self, cookie: str) -> DouyuActivityClient: ...
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
def _push_log(self, level: str, message: str) -> None: ...
def _task_payload(self, task: DouyuTask) -> dict: ...
def _overview_view(self, task: DouyuTask) -> str:
result = task.result if isinstance(task.result, dict) else {}
payload_raw = result.get("payload")
payload = payload_raw if isinstance(payload_raw, dict) else {}
runtime_payload = getattr(self, "payload", None)
if isinstance(runtime_payload, dict):
payload = {**payload, **runtime_payload}
return str(payload.get("view") or "").strip()
def _refresh_account_gold_balance(
self, client: DouyuActivityClient, account: Account
) -> dict: ...
@@ -447,19 +480,16 @@ class OverviewMixin:
绝不因此让整次查询失败(账号没绑电竞手册就是最常见的例子)。
"""
started_at = datetime.now(UTC)
view = self._overview_view(task)
cached = self._cached_overview(account, task, now=started_at)
if cached is not None:
owned_count = sum(
1
for item in (cached.get("high_value_goods") or [])
if isinstance(item, dict)
and not item.get("missing")
and item.get("owned")
)
message = (
"一键查询命中本地新鲜快照;"
f"高价值套装已拥有 {owned_count} 个"
f"{_overview_owned_text(cached)}"
cached["view"] = view or str(cached.get("view") or "")
message = _overview_success_message(
cached,
cached.get("errors")
if isinstance(cached.get("errors"), dict)
else {},
view=view,
)
self._push_log(
"info",
@@ -475,6 +505,7 @@ class OverviewMixin:
queried_at = datetime.now(UTC)
overview: dict[str, Any] = {
"queried_at": queried_at.isoformat(),
"view": view,
"assets": {},
"elite": {},
"esports": {},
@@ -1043,16 +1074,7 @@ class OverviewMixin:
# 但**不改生命周期状态,也不制造业务事实事件**;任务活动由执行器统一记录。
account.updated_at = datetime.now(UTC)
owned = [
g["name"]
for g in overview["high_value_goods"]
if not g.get("missing") and g.get("owned")
]
message = f"一键查询完成;高价值套装已拥有 {len(owned)} 个"
if owned:
message += f": {', '.join(owned)}"
if errors:
message += f"({len(errors)} 项未取到)"
message = _overview_success_message(overview, errors, view=view)
# 落到账号上:任务会被保留策略清掉,而「这个账号现在什么情况」是账号的信息,
# 应该在账号管理里看,不该依赖一条日志的寿命。
@@ -1469,10 +1469,13 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
zIndex: 1050,
} : { display: 'none' };
const runContextAction = (taskType: string) => {
const runContextAction = (
taskType: string,
payload: Record<string, unknown> = {},
) => {
if (!contextMenu) return;
setContextMenu(null);
void startTask(taskType, contextMenu.accountIds);
void startTask(taskType, contextMenu.accountIds, payload);
};
// ---- 电竞手册绑定面板 ----
@@ -1891,6 +1894,14 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
render: (_, record) => {
const latest = latestTaskByAccount.get(record.id);
if (!latest) return <Text type="secondary">暂无操作</Text>;
const limitedGoodsView = latest.task_type === 'query_account_overview'
&& latest.result?.view === 'limited_goods';
const latestLabel = limitedGoodsView
? '查询限兑商品'
: (taskTypes[latest.task_type] || latest.task_type);
const latestMessage = limitedGoodsView
? limitedGoodsTaskText(latest)
: latest.message;
return (
<Space direction="vertical" size={1} style={{ width: '100%' }}>
<Space size={4} wrap>
@@ -1898,12 +1909,12 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
{TASK_STATUS_LABELS[latest.status] || latest.status}
</Tag>
<Text strong ellipsis style={{ maxWidth: 170 }}>
{taskTypes[latest.task_type] || latest.task_type}
{latestLabel}
</Text>
</Space>
{latest.message ? (
<Text type="secondary" style={{ fontSize: 12 }} ellipsis title={latest.message}>
{latest.message}
{latestMessage ? (
<Text type="secondary" style={{ fontSize: 12 }} ellipsis title={latestMessage}>
{latestMessage}
</Text>
) : null}
<Text type="secondary" style={{ fontSize: 12 }}>
@@ -2848,18 +2859,23 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
size="small"
title={contextMenu.accountIds.length > 1 ? '批量动作' : '账号动作'}
styles={{ body: { padding: 4 } }}
style={{ width: 200, boxShadow: '0 4px 12px rgba(0,0,0,0.12)' }}
style={{
width: 200,
maxHeight: 'calc(100vh - 24px)',
overflowY: 'auto',
boxShadow: '0 4px 12px rgba(0,0,0,0.12)',
}}
>
<Space direction="vertical" style={{ width: '100%' }}>
{quickActions.map((item) => (
<Button
key={item.key} block size="small" type="text"
icon={item.icon}
onClick={() => runContextAction(item.key)}
onClick={() => runContextAction(item.key, item.payload)}
disabled={contextMenu.accountIds.some((id) => runningAccountIds.has(id))}
style={{ justifyContent: 'flex-start' }}
>
{taskTypes[item.key] || item.key}
{item.label || taskTypes[item.key] || item.key}
</Button>
))}
</Space>
+26 -12
View File
@@ -37,7 +37,14 @@ export const TASK_STATUS_LABELS: Record<string, string> = {
stopped: '已停止',
};
export const ELITE_QUICK_ACTIONS = [
export type DouyuQuickAction = {
key: string;
label?: string;
payload?: Record<string, unknown>;
icon: ReactNode;
};
export const ELITE_QUICK_ACTIONS: DouyuQuickAction[] = [
{ key: 'get_bind_qr', icon: <QrcodeOutlined /> },
{ key: 'confirm_bind', icon: <CheckCircleOutlined /> },
{ key: 'query_elite_status', icon: <SearchOutlined /> },
@@ -45,6 +52,12 @@ export const ELITE_QUICK_ACTIONS = [
{ key: 'query_points', icon: <SearchOutlined /> },
{ key: 'query_game_name', icon: <SearchOutlined /> },
{ key: 'query_change_bind_time', icon: <FieldTimeOutlined /> },
{
key: 'query_account_overview',
label: '查询限兑商品',
payload: { view: 'limited_goods' },
icon: <SearchOutlined />,
},
{ key: 'query_gold_balance', icon: <SearchOutlined /> },
{ key: 'lock_goods', icon: <ShoppingOutlined /> },
{ key: 'exchange_goods', icon: <ShoppingOutlined /> },
@@ -52,7 +65,7 @@ export const ELITE_QUICK_ACTIONS = [
{ key: 'donate_elite_gift', icon: <GiftOutlined /> },
];
export const ESPORTS_QUICK_ACTIONS = [
export const ESPORTS_QUICK_ACTIONS: DouyuQuickAction[] = [
{ key: 'prepare_esports_bind', icon: <QrcodeOutlined /> },
{ key: 'query_esports_game_name', icon: <SearchOutlined /> },
{ key: 'create_esports_qr', icon: <CreditCardOutlined /> },
@@ -66,7 +79,7 @@ export const ESPORTS_QUICK_ACTIONS = [
{ key: 'donate_esports_firework_gift', icon: <GiftOutlined /> },
];
export const PEACE_QUICK_ACTIONS = [
export const PEACE_QUICK_ACTIONS: DouyuQuickAction[] = [
{ key: 'get_xpd_bind_qr', icon: <QrcodeOutlined /> },
{ key: 'query_xpd_bind_info', icon: <SearchOutlined /> },
{ key: 'confirm_xpd_bind', icon: <CheckCircleOutlined /> },
@@ -329,15 +342,16 @@ export function limitedGoodsName(item: unknown): string {
export function limitedGoodsTaskText(task: DouyuTaskItem | null | undefined): string {
if (!task) return '';
if (task.message?.trim()) return task.message.trim();
const count = resultNumber(task.result, 'limited_count');
if (count == null) return '';
if (count <= 0) return '无受限商品(均可兑换)';
const goods = task.result?.limited_goods;
const names = Array.isArray(goods)
? goods.map(limitedGoodsName).filter(Boolean).slice(0, 5)
: [];
return names.length ? `已达上限 ${count} 个: ${names.join(', ')}` : `已达上限 ${count} 个`;
if (count != null) {
if (count <= 0) return '无受限商品(均可兑换)';
const goods = task.result?.limited_goods;
const names = Array.isArray(goods)
? goods.map(limitedGoodsName).filter(Boolean).slice(0, 5)
: [];
return names.length ? `已达上限 ${count} 个: ${names.join(', ')}` : `已达上限 ${count} 个`;
}
return task.message?.trim() || '';
}
export function savedPositiveInteger(key: string, fallback = 1): number {
@@ -350,7 +364,7 @@ export const HANDBOOK_META: Record<HandbookKind, {
title: string;
description: string;
taskTypes: Set<string>;
quickActions: Array<{ key: string; icon: ReactNode }>;
quickActions: DouyuQuickAction[];
}> = {
elite: {
title: '精英宝典工作台',