feat(douyu): 查询工作台区分导入/查询数据、导入后自动查CK并修复登录刷新闪烁 (v0.4.29)

1) 闪烁修复:轮询(loadAccountsPage/loadManualBudget)改为静默模式,
   不再每 2.2s 点亮表格 loading 遮罩与预算 Tag spinner;活动结束后保留
   12s 宽限期继续静默刷新,避免登录刚完成就停刷导致行上残留「登录队列中」。

2) 导入后自动检测 CK:工作台 PUT 返回 imported_account_ids,前端分片
   并发检测并显示进度,失效/无 CK 账号直接标红;/accounts/ck-check 对
   无 CK、登录中的账号改为跳过(返回 checked/skipped)而不是整批报错。
   行内新增「重登/人工登录该账号」入口,走既有人工登录预算。

3) 数据来源区分:douyu_workbench_accounts 新增 data_state/imported_at/
   queried_at/relogin_at(迁移 20261130_0142)。导入标 imported,查询任务
   成功由 _mark_task 标 queried,人工重登入队标 stale;PUT 工作台改为
   upsert,不再整删整建以免重置状态。账号列表新增 workbench_scope/
   workbench_state 入参与 workbench_* 回填字段。

4) 重登后只查重登账号:新增 /query-workbench/pending-ids(导入未查 +
   重登待重查,仅含有可用 CK 者)与「只查待查询(N)」下拉;一键查询改为
   尊重当前筛选(跨页),修正原来无视筛选直接查整台的问题。

5) CSV 末尾追加「数据来源 / 数据更新说明」两列,保持原有列序不变。
This commit is contained in:
yml
2026-11-30 20:04:26 +08:00
parent ecb987fff0
commit 6ad8025a86
16 changed files with 1336 additions and 98 deletions
+216 -23
View File
@@ -88,6 +88,7 @@ from ..services.account_protection_service import (
evaluate_protection_targets,
update_protection_group,
)
from ..services.account_query_filters import cookie_operable_filter
from ..services.account_supply_service import (
SupplyInventory,
evaluate_supply_target,
@@ -112,6 +113,13 @@ from ..services.douyu_exchange_result_image import (
save_exchange_result_image,
)
from ..services.douyu_goods_service import serialize_goods
from ..services.douyu_query_workbench import (
DATA_STATE_IMPORTED,
DATA_STATES,
mark_workbench_stale,
pending_query_ids,
workbench_state_map,
)
from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
from ..services.douyu_service import (
DOUYU_ACTIVE_TASK_STATUSES,
@@ -810,7 +818,8 @@ def _account_out(
game_channel=account.game_channel or "",
gold_balance=account.gold_balance,
exchange_balance=account.exchange_balance,
**bind_payload(account),
# pydantic 模型字段含 datetime/bool,字典展开只能按 Any 传入。
**cast(dict[str, Any], bind_payload(account)),
# 未确认绑定时接口倒计时是占位值;API 出口也做一次归一,兼容历史行。
change_role_wait_time=account.change_role_wait_time if elite_cooldown else 0,
elite_opened=account.elite_opened,
@@ -1015,13 +1024,19 @@ def list_task_accounts(
ids: str = Query(""),
account_names: str = Query(""),
ck_status: str = "",
workbench_scope: str = "",
workbench_state: str = "",
include_all: bool = False,
page: int | None = Query(None, ge=1),
page_size: int = Query(50, ge=1, le=200),
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""查看斗鱼账号。默认只返回持有 Cookie 的可执行账号;include_all=true 时返回全部可见账号(供查询工作台使用)。"""
"""查看斗鱼账号。默认只返回持有 Cookie 的可执行账号;include_all=true 时返回全部可见账号(供查询工作台使用)。
`workbench_scope` 传入时会回填该工作台的数据来源(导入未查询 / 已查询 / 重登待重查),
`workbench_state` 可按数据来源筛选(跨页生效)。
"""
query, selected_names, selected_ids = _apply_task_account_filters(
_visible_task_accounts_query(db, current, include_all=include_all),
search=search,
@@ -1030,6 +1045,18 @@ def list_task_accounts(
ids=ids,
ck_status=ck_status,
)
scope = (workbench_scope or "").strip()
if scope:
member_query = select(DouyuWorkbenchAccount.account_id).where(
DouyuWorkbenchAccount.user_id == current.id,
DouyuWorkbenchAccount.handbook_scope == scope,
)
state = (workbench_state or "").strip()
if state:
if state not in DATA_STATES:
raise HTTPException(status_code=400, detail="无效的数据状态筛选")
member_query = member_query.where(DouyuWorkbenchAccount.data_state == state)
query = query.filter(Account.id.in_(member_query))
total = None
if page is not None:
total = query.order_by(None).count()
@@ -1044,9 +1071,26 @@ def list_task_accounts(
if include_all
else None
)
result = [
_account_out(account, in_flight_login_ids=in_flight_ids) for account in rows
]
state_rows = (
workbench_state_map(
db,
user_id=int(current.id),
account_ids=[int(account.id) for account in rows],
handbook_scope=scope,
)
if scope
else {}
)
result = []
for account in rows:
item = _account_out(account, in_flight_login_ids=in_flight_ids)
state_row = state_rows.get(int(account.id))
if state_row is not None:
item.workbench_data_state = state_row.data_state or DATA_STATE_IMPORTED
item.workbench_imported_at = state_row.imported_at
item.workbench_queried_at = state_row.queried_at
item.workbench_relogin_at = state_row.relogin_at
result.append(item)
if page is not None:
return {
"items": result,
@@ -1063,11 +1107,16 @@ def list_task_account_ids(
tag: str = Query(""),
account_names: str = Query(""),
ck_status: str = "",
workbench_scope: str = "",
workbench_state: str = "",
include_all: bool = False,
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""返回当前用户可导入工作台的全部账号 ID,不受列表分页限制。"""
"""返回当前用户可导入工作台的全部账号 ID,不受列表分页限制。
`workbench_scope` / `workbench_state` 与 `/accounts` 一致:用于「一键查询当前筛选结果」。
"""
query, selected_names, selected_ids = _apply_task_account_filters(
_visible_task_accounts_query(db, current, include_all=include_all),
search=search,
@@ -1075,6 +1124,18 @@ def list_task_account_ids(
account_names=account_names,
ck_status=ck_status,
)
scope = (workbench_scope or "").strip()
if scope:
member_query = select(DouyuWorkbenchAccount.account_id).where(
DouyuWorkbenchAccount.user_id == current.id,
DouyuWorkbenchAccount.handbook_scope == scope,
)
state = (workbench_state or "").strip()
if state:
if state not in DATA_STATES:
raise HTTPException(status_code=400, detail="无效的数据状态筛选")
member_query = member_query.where(DouyuWorkbenchAccount.data_state == state)
query = query.filter(Account.id.in_(member_query))
account_ids = [
account_id
for (account_id,) in _order_task_accounts(
@@ -1096,10 +1157,46 @@ def check_task_accounts_ck(
复用 CK 操作页的检测逻辑:检测结果会写回 ``accounts.ck_check_status``,
因此导入账号后刷新列表仍能看到「有效 / 失效」。
导入场景会整批传入(包含无 CK / 正在登录的账号),这些账号会被跳过而不是
整体报错 —— 调用方只需要拿到真正能检测的那批结论。
"""
from .cookies import _check_cookies
return _check_cookies(ids, db, current, detailed=False)
requested_ids = [
int(value) for value in dict.fromkeys(
item.strip() for item in (ids or "").split(",") if item.strip().isdigit()
)
]
if not requested_ids:
raise HTTPException(status_code=400, detail="请指定账号ID")
checkable_ids = [
int(account_id)
for (account_id,) in _visible_task_accounts_query(db, current, include_all=True)
.filter(Account.id.in_(requested_ids), cookie_operable_filter())
.enable_eagerloads(False)
.with_entities(Account.id)
.all()
]
skipped = len(requested_ids) - len(checkable_ids)
if not checkable_ids:
return {
"results": [],
"success": True,
"checked": 0,
"skipped": skipped,
"message": "所选账号均无可用 CK(待登录或正在登录中)",
}
result = _check_cookies(
",".join(str(account_id) for account_id in checkable_ids),
db,
current,
detailed=False,
)
if isinstance(result, dict):
result["skipped"] = skipped
result["checked"] = len(result.get("results") or [])
return result
@router.post("/accounts/relogin-invalid")
@@ -1176,7 +1273,11 @@ def update_workbench_accounts(
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:task")),
):
"""用当前完整账号集合覆盖一个工作台,作为跨浏览器的同步状态。"""
"""用当前完整账号集合覆盖一个工作台,作为跨浏览器的同步状态。
保留已有账号行的数据状态(导入/已查询/待重查),只把本次新加入的账号标记为
「导入未查询」,避免每次增删账号都把工作台的查询状态重置。
"""
account_ids = list(dict.fromkeys(req.account_ids))
if any(account_id < 1 for account_id in account_ids):
raise HTTPException(status_code=400, detail="无效的账号ID")
@@ -1194,23 +1295,53 @@ def update_workbench_accounts(
db.add(DouyuWorkbench(user_id=current.id, handbook_scope=req.handbook_scope))
else:
workbench.updated_at = datetime.now(UTC)
db.query(DouyuWorkbenchAccount).filter(
DouyuWorkbenchAccount.user_id == current.id,
DouyuWorkbenchAccount.handbook_scope == req.handbook_scope,
).delete(synchronize_session=False)
db.add_all(
[
DouyuWorkbenchAccount(
user_id=current.id,
handbook_scope=req.handbook_scope,
account_id=account_id,
sort_order=index,
existing_rows = {
int(row.account_id): row
for row in db.query(DouyuWorkbenchAccount)
.filter(
DouyuWorkbenchAccount.user_id == current.id,
DouyuWorkbenchAccount.handbook_scope == req.handbook_scope,
)
.all()
}
keep = set(account_ids)
removed = [account_id for account_id in existing_rows if account_id not in keep]
if removed:
db.query(DouyuWorkbenchAccount).filter(
DouyuWorkbenchAccount.user_id == current.id,
DouyuWorkbenchAccount.handbook_scope == req.handbook_scope,
DouyuWorkbenchAccount.account_id.in_(removed),
).delete(synchronize_session=False)
now = datetime.now(UTC)
imported_account_ids: list[int] = []
for index, account_id in enumerate(account_ids):
row = existing_rows.get(account_id)
if row is None:
db.add(
DouyuWorkbenchAccount(
user_id=current.id,
handbook_scope=req.handbook_scope,
account_id=account_id,
sort_order=index,
data_state=DATA_STATE_IMPORTED,
imported_at=now,
)
)
for index, account_id in enumerate(account_ids)
]
)
imported_account_ids.append(account_id)
continue
row.sort_order = index
if not row.imported_at:
row.imported_at = row.created_at or now
if not row.data_state:
row.data_state = DATA_STATE_IMPORTED
db.commit()
return {"account_ids": account_ids, "success": True}
return {
"account_ids": account_ids,
"imported_account_ids": imported_account_ids,
"success": True,
}
_SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
@@ -1409,6 +1540,30 @@ def list_query_workbench_invalid_ids(
}
@router.get("/query-workbench/pending-ids")
def list_query_workbench_pending_ids(
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:task")),
):
"""返回工作台内「待查询」账号:导入未查 + 重登成功后待重查(均有可用 CK)。
重登成功后的账号只选这一批回查,不会把整个工作台再跑一遍。
"""
member_ids = _query_workbench_member_ids(db, current)
if not member_ids:
return {
"account_ids": [],
"imported_ids": [],
"stale_ids": [],
"total": 0,
}
return pending_query_ids(
db,
user_id=int(current.id),
visible_account_ids=member_ids,
)
@router.get("/query-workbench/manual-budget")
def get_query_workbench_manual_budget(
db: Session = Depends(get_db),
@@ -1526,6 +1681,9 @@ def relogin_query_workbench_invalid_accounts(
batch_ids.append(batch_id)
total_queued = len(relogin_ids) + len(login_ids)
# 重登(或首次登录)成功后的账号数据已过期:标记为「待重查」,
# 这样重登完成后可以只回查这批账号,而不是把整个工作台重跑一遍。
mark_workbench_stale(db, relogin_ids + login_ids, commit=False)
record_audit(
db,
current,
@@ -1558,6 +1716,32 @@ def relogin_query_workbench_invalid_accounts(
}
_WORKBENCH_STATE_LABELS = {
"imported": "导入未查询",
"queried": "已查询",
"stale": "重登待重查",
}
def _workbench_state_label(row: DouyuWorkbenchAccount | None) -> str:
if row is None:
return "未在工作台"
return _WORKBENCH_STATE_LABELS.get(row.data_state or "", "导入未查询")
def _workbench_state_note(row: DouyuWorkbenchAccount | None) -> str:
"""导出附带「什么时候导入 / 什么时候查的」,避免把旧数据当新结果。"""
if row is None:
return ""
if row.data_state == "queried" and row.queried_at is not None:
return f"查询于 {_format_shanghai_dt(row.queried_at)}"
if row.data_state == "stale" and row.relogin_at is not None:
return f"重登于 {_format_shanghai_dt(row.relogin_at)},待重新查询"
if row.imported_at is not None:
return f"导入于 {_format_shanghai_dt(row.imported_at)},未查询资产"
return "未查询资产"
@router.post("/query-workbench/export")
def export_query_workbench_csv(
req: DouyuQueryWorkbenchExportRequest,
@@ -1607,8 +1791,15 @@ def export_query_workbench_csv(
"官方换绑时间",
"换绑冷却说明",
"最近更新时间",
"数据来源",
"数据更新说明",
]
)
state_rows = workbench_state_map(
db,
user_id=int(current.id),
account_ids=[int(acc.id) for acc in ordered_accounts],
)
for acc in ordered_accounts:
if not acc.cookie:
ck_label = "无CK"
@@ -1678,6 +1869,8 @@ def export_query_workbench_csv(
_format_shanghai_dt(acc.role_change_official_at),
cooldown_note,
_format_shanghai_dt(acc.updated_at or acc.overview_queried_at),
_workbench_state_label(state_rows.get(int(acc.id))),
_workbench_state_note(state_rows.get(int(acc.id))),
]
]
)