diff --git a/README.md b/README.md index 01c623b..d7b6493 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 直播账号运营后台 -斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.28)。 +斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.29)。 ## 能做什么 diff --git a/docs/斗鱼/Go版本同步优化清单.md b/docs/斗鱼/Go版本同步优化清单.md index 343ae47..be9d737 100644 --- a/docs/斗鱼/Go版本同步优化清单.md +++ b/docs/斗鱼/Go版本同步优化清单.md @@ -87,3 +87,10 @@ - 后端任务与工作台:`query_assets_and_bind`(鱼翅 + 积分 + 换绑冷却合并查询)、`/api/douyu/accounts`(`include_all` / `ck_status`)、`/api/douyu/query-workbench/{lookup,invalid-ids,manual-budget,relogin-invalid,export}`; - 登录预算透传:`execution_worker` 对 `JOB_LOGIN_BATCH` / `JOB_RELOGIN_BATCH` 透传 `payload.category`(强制人工重登走 `CATEGORY_MANUAL`); - 前端页面:`DouyuQueryWorkbenchPage.tsx`、路由 `/douyu/query-workbench`。 + 5. `v0.4.29` **查询工作台数据来源区分 + 导入后 CK 自检**: + - 新表列:`douyu_workbench_accounts.{data_state, imported_at, queried_at, relogin_at}`(`imported` / `queried` / `stale`); + - `PUT /api/douyu/workbench-accounts` 改为 upsert(不再整删整建),只把新加入的账号标记 `imported` 并回传 `imported_account_ids`; + - `GET /api/douyu/accounts` 新增 `workbench_scope` / `workbench_state`,并回填 `workbench_data_state` 等字段; + - 新增 `GET /api/douyu/query-workbench/pending-ids`(导入未查 + 重登待重查);`POST /api/douyu/accounts/ck-check` 对无 CK/登录中账号改为跳过而非整体报错; + - 查询任务成功(`_mark_task`)回写 `data_state=queried`,人工重登回写 `data_state=stale`,因此重登成功后只查 `stale` 这一批; + - 前端:导入后自动分片检测 CK、静默轮询(去闪烁)、“数据:全部/导入未查询/已查询/重登待重查”筛选、「只查待查询(N)」按钮。 diff --git a/pyproject.toml b/pyproject.toml index f5aaf5b..522ab61 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "live-hub-py" -version = "0.4.28" +version = "0.4.29" description = "直播账号运营 Web 后台" readme = "README.md" requires-python = ">=3.12,<3.13" diff --git a/tests/test_douyu_query_workbench.py b/tests/test_douyu_query_workbench.py index 00a14c2..b097477 100644 --- a/tests/test_douyu_query_workbench.py +++ b/tests/test_douyu_query_workbench.py @@ -515,6 +515,22 @@ class TestQueryWorkbenchRouterAndExport: assert rows[3][12] == "已过期" assert rows[2][17] == "可换绑" assert rows[3][17] == "冷却中" + # 导出末尾两列区分「导入后的数据」与「一键查询后的数据」 + assert rows[0][-2] == "数据来源" + assert rows[2][-2] == "导入未查询" + assert "导入于" in rows[2][-1] + + from web.backend.services.douyu_query_workbench import mark_workbench_queried + + mark_workbench_queried(self.session, [self.acc_valid.id]) + resp = export_query_workbench_csv( + DouyuQueryWorkbenchExportRequest(ids=[self.acc_valid.id]), + db=self.session, + current=self.admin, + ) + rows = list(csv.reader(io.StringIO(resp.body.decode("utf-8-sig")))) + assert rows[1][-2] == "已查询" + assert "查询于" in rows[1][-1] def test_relogin_requires_login_batch_permission(self): with pytest.raises(HTTPException) as exc: @@ -653,3 +669,288 @@ def test_execution_worker_forwards_manual_category_for_relogin_batch(db, monkeyp assert captured.get("mode") == "relogin" assert captured.get("trigger_source") == "manual" assert captured.get("category") == CATEGORY_MANUAL + + +class _MarkTaskHarness(DouyuBatchRunnerCore): + """只用于驱动 `_mark_task` 的真实实现,绕过构造器里的代理/客户端依赖。""" + + def __init__(self, db): + import threading + + self.db = db + self.batch_id = "qw-mark-batch" + self.log_queue = None + self.loop = None + self.log_sink = None + self._hook_local = threading.local() + + def _push_log(self, *args, **kwargs): + pass + + +class TestQueryWorkbenchDataState: + """工作台必须能区分「导入后的数据」和「一键查询后的数据」。""" + + def setup_method(self): + self.engine = get_test_engine() + self.session = make_test_session(self.engine) + self.admin = User(username="state-admin", password_hash="h", role="super_admin") + self.session.add(self.admin) + self.session.flush() + + self.acc_a = Account( + username="state_a", + uid="9001", + password="pw", + email="a@e.com", + email_password="ep", + cookie="acf_uid=9001", + ck_check_status="valid", + assigned_to=self.admin.id, + ) + self.acc_b = Account( + username="state_b", + uid="9002", + password="pw", + email="b@e.com", + email_password="ep", + cookie="acf_uid=9002", + ck_check_status="valid", + assigned_to=self.admin.id, + ) + self.acc_nock = Account( + username="state_nock", + uid="", + password="pw", + email="c@e.com", + email_password="ep", + cookie="", + status="imported", + assigned_to=self.admin.id, + ) + self.session.add_all([self.acc_a, self.acc_b, self.acc_nock]) + self.session.commit() + + def teardown_method(self): + self.session.close() + + def _rows(self): + return { + int(row.account_id): row + for row in self.session.query(DouyuWorkbenchAccount).all() + } + + def test_import_marks_imported_and_resave_preserves_state(self): + res = update_workbench_accounts( + DouyuWorkbenchAccountsUpdate( + handbook_scope="query", account_ids=[self.acc_a.id, self.acc_b.id] + ), + db=self.session, + current=self.admin, + ) + assert res["imported_account_ids"] == [self.acc_a.id, self.acc_b.id] + rows = self._rows() + assert rows[self.acc_a.id].data_state == "imported" + assert rows[self.acc_a.id].imported_at is not None + + # 一键查询成功后应变成 queried + from web.backend.services.douyu_query_workbench import mark_workbench_queried + + assert mark_workbench_queried(self.session, [self.acc_a.id]) == 1 + rows = self._rows() + assert rows[self.acc_a.id].data_state == "queried" + assert rows[self.acc_a.id].queried_at is not None + + # 再次导入新账号(增删集合)不能把已有行的查询状态重置掉 + res = update_workbench_accounts( + DouyuWorkbenchAccountsUpdate( + handbook_scope="query", + account_ids=[self.acc_a.id, self.acc_b.id, self.acc_nock.id], + ), + db=self.session, + current=self.admin, + ) + assert res["imported_account_ids"] == [self.acc_nock.id] + rows = self._rows() + assert rows[self.acc_a.id].data_state == "queried" + assert rows[self.acc_b.id].data_state == "imported" + + # 移出账号只删那一行 + update_workbench_accounts( + DouyuWorkbenchAccountsUpdate( + handbook_scope="query", account_ids=[self.acc_a.id] + ), + db=self.session, + current=self.admin, + ) + assert set(self._rows().keys()) == {self.acc_a.id} + + def test_pending_ids_excludes_no_cookie_and_filters_by_state(self): + update_workbench_accounts( + DouyuWorkbenchAccountsUpdate( + handbook_scope="query", + account_ids=[self.acc_a.id, self.acc_b.id, self.acc_nock.id], + ), + db=self.session, + current=self.admin, + ) + from web.backend.services.douyu_query_workbench import mark_workbench_stale + + mark_workbench_stale(self.session, [self.acc_b.id]) + + from web.backend.routers.douyu import list_query_workbench_pending_ids + + pending = list_query_workbench_pending_ids(db=self.session, current=self.admin) + assert pending["imported_ids"] == [self.acc_a.id] + assert pending["stale_ids"] == [self.acc_b.id] + assert pending["total"] == 2 + + stale_items = list_task_accounts( + search="", + tag="", + ids=",".join( + str(acc_id) + for acc_id in (self.acc_a.id, self.acc_b.id, self.acc_nock.id) + ), + account_names="", + include_all=True, + workbench_scope="query", + workbench_state="stale", + page=None, + db=self.session, + current=self.admin, + ) + assert [item.username for item in stale_items] == ["state_b"] + assert stale_items[0].workbench_data_state == "stale" + assert stale_items[0].workbench_relogin_at is not None + + def test_ids_endpoint_supports_workbench_state_filter(self): + """「一键查询筛选结果」依靠 /accounts/ids 的跨页筛选。""" + from web.backend.routers.douyu import list_task_account_ids + + update_workbench_accounts( + DouyuWorkbenchAccountsUpdate( + handbook_scope="query", + account_ids=[self.acc_a.id, self.acc_b.id], + ), + db=self.session, + current=self.admin, + ) + from web.backend.services.douyu_query_workbench import mark_workbench_queried + + mark_workbench_queried(self.session, [self.acc_b.id]) + + imported_only = list_task_account_ids( + search="", + tag="", + account_names="", + ck_status="", + include_all=True, + workbench_scope="query", + workbench_state="imported", + db=self.session, + current=self.admin, + ) + assert imported_only["account_ids"] == [self.acc_a.id] + + queried_only = list_task_account_ids( + search="", + tag="", + account_names="", + ck_status="", + include_all=True, + workbench_scope="query", + workbench_state="queried", + db=self.session, + current=self.admin, + ) + assert queried_only["account_ids"] == [self.acc_b.id] + + with pytest.raises(HTTPException) as exc: + list_task_account_ids( + search="", + tag="", + account_names="", + ck_status="", + include_all=True, + workbench_scope="query", + workbench_state="bogus", + db=self.session, + current=self.admin, + ) + assert exc.value.status_code == 400 + + def test_relogin_marks_account_as_stale(self): + update_workbench_accounts( + DouyuWorkbenchAccountsUpdate( + handbook_scope="query", account_ids=[self.acc_a.id] + ), + db=self.session, + current=self.admin, + ) + self.acc_a.ck_check_status = "invalid" + self.session.commit() + + res = relogin_query_workbench_invalid_accounts( + DouyuQueryWorkbenchReloginRequest(ids=[self.acc_a.id]), + db=self.session, + current=self.admin, + ) + assert res["relogin_count"] == 1 + row = self._rows()[self.acc_a.id] + assert row.data_state == "stale" + assert row.relogin_at is not None + + def test_import_ck_check_skips_non_operable_ids_without_error(self): + """导入整批传进来时,无 CK / 登录中的账号应被跳过而不是整批报错。""" + from web.backend.routers.douyu import check_task_accounts_ck + + # 只传无 CK 账号:可检测集合为空,直接短路返回,不会发真实探测请求 + res = check_task_accounts_ck( + ids=str(self.acc_nock.id), + db=self.session, + current=self.admin, + ) + assert res["success"] is True + assert res["checked"] == 0 + assert res["skipped"] == 1 + assert res["results"] == [] + + def test_query_task_success_marks_queried_and_failure_keeps_state(self): + update_workbench_accounts( + DouyuWorkbenchAccountsUpdate( + handbook_scope="query", account_ids=[self.acc_a.id] + ), + db=self.session, + current=self.admin, + ) + runner = _MarkTaskHarness(self.session) + failed_task = DouyuTask( + batch_id="qw-mark-failed", + account_id=self.acc_a.id, + task_type="query_assets_and_bind", + handbook_scope="query", + status="running", + message="", + created_by=self.admin.id, + ) + self.session.add(failed_task) + self.session.commit() + runner._mark_task(self.session, failed_task, "failed", "接口全失败", {}) + assert self._rows()[self.acc_a.id].data_state == "imported" + + ok_task = DouyuTask( + batch_id="qw-mark-ok", + account_id=self.acc_a.id, + task_type="query_assets_and_bind", + handbook_scope="query", + status="running", + message="", + created_by=self.admin.id, + ) + self.session.add(ok_task) + self.session.commit() + runner._mark_task(self.session, ok_task, "success", "查询成功", {"points": 1}) + row = self._rows()[self.acc_a.id] + assert row.data_state == "queried" + assert row.queried_at is not None diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 8d204af..d075a87 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261129_0141" +HEAD_REVISION = "20261130_0142" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( diff --git a/uv.lock b/uv.lock index 08eca9b..e5c407a 100644 --- a/uv.lock +++ b/uv.lock @@ -381,7 +381,7 @@ wheels = [ [[package]] name = "live-hub-py" -version = "0.4.28" +version = "0.4.29" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/web/backend/migrations/migration_manifest.json b/web/backend/migrations/migration_manifest.json index 18ea63d..197bc31 100644 --- a/web/backend/migrations/migration_manifest.json +++ b/web/backend/migrations/migration_manifest.json @@ -565,6 +565,10 @@ "20261129_0141_douyu_slow_query_indexes.py": { "revision": "20261129_0141", "sha256": "537ffb0a472c80d3a499c3c268aa62a2f5235ccc5399a81955a0e14d8721ea1f" + }, + "20261130_0142_douyu_workbench_data_state.py": { + "revision": "20261130_0142", + "sha256": "eb2225861566f91a521edaf290ea29a638d173a833c49d41f3a7e0d9b629f4e6" } } } diff --git a/web/backend/migrations/versions/20261130_0142_douyu_workbench_data_state.py b/web/backend/migrations/versions/20261130_0142_douyu_workbench_data_state.py new file mode 100644 index 0000000..a6a0b87 --- /dev/null +++ b/web/backend/migrations/versions/20261130_0142_douyu_workbench_data_state.py @@ -0,0 +1,109 @@ +"""查询工作台区分「导入后的数据」与「一键查询后的数据」 + +`douyu_workbench_accounts` 之前只记录「哪个账号在这个工作台里」,因此界面无法 +区分某一行是刚导入(只检测过 CK)还是已经跑过一键查询;重登成功后也没法只挑 +重新登录的账号再查一次。 + +新增四列: + +- `data_state`:imported / queried / stale +- `imported_at`:加入工作台的时间 +- `queried_at`:最近一次在本工作台查询成功的时间 +- `relogin_at`:最近一次发起人工重登的时间 + +Revision ID: 20261130_0142 +Revises: 20261129_0141 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261130_0142" +down_revision: str | None = "20261129_0141" +branch_labels: str | None = None +depends_on: str | None = None + + +def _has_column(inspector: sa.Inspector, table: str, column: str) -> bool: + return any(col["name"] == column for col in inspector.get_columns(table)) + + +def _has_index(inspector: sa.Inspector, table: str, index_name: str) -> bool: + return any(idx["name"] == index_name for idx in inspector.get_indexes(table)) + + +def upgrade() -> None: + bind = op.get_bind() + inspector = sa.inspect(bind) + table = "douyu_workbench_accounts" + if not inspector.has_table(table): + return + + if not _has_column(inspector, table, "data_state"): + op.add_column( + table, + sa.Column( + "data_state", + sa.String(length=16), + nullable=False, + server_default="imported", + comment="imported/queried/stale:区分导入数据与一键查询数据", + ), + ) + if not _has_column(inspector, table, "imported_at"): + op.add_column( + table, + sa.Column("imported_at", sa.DateTime(), nullable=True, comment="导入工作台时间"), + ) + if not _has_column(inspector, table, "queried_at"): + op.add_column( + table, + sa.Column("queried_at", sa.DateTime(), nullable=True, comment="最近一次查询成功时间"), + ) + if not _has_column(inspector, table, "relogin_at"): + op.add_column( + table, + sa.Column("relogin_at", sa.DateTime(), nullable=True, comment="最近一次人工重登时间"), + ) + + # 历史行:`created_at` 就是导入时间;已有 `overview_queried_at` 的账号视为已查询过。 + # 用 SQL 分批回填,避免 ORM 逐行加载。 + op.execute( + sa.text( + f"UPDATE {table} SET imported_at = created_at WHERE imported_at IS NULL" + ) + ) + op.execute( + sa.text( + f""" + UPDATE {table} AS w + JOIN accounts AS a ON a.id = w.account_id + SET w.data_state = 'queried', w.queried_at = a.overview_queried_at + WHERE w.data_state = 'imported' + AND a.overview_queried_at IS NOT NULL + """ + ) + ) + + inspector = sa.inspect(bind) + if not _has_index(inspector, table, "ix_douyu_workbench_accounts_state"): + op.create_index( + "ix_douyu_workbench_accounts_state", + table, + ["user_id", "handbook_scope", "data_state"], + ) + + +def downgrade() -> None: + bind = op.get_bind() + inspector = sa.inspect(bind) + table = "douyu_workbench_accounts" + if not inspector.has_table(table): + return + if _has_index(inspector, table, "ix_douyu_workbench_accounts_state"): + op.drop_index("ix_douyu_workbench_accounts_state", table_name=table) + for column in ("relogin_at", "queried_at", "imported_at", "data_state"): + if _has_column(inspector, table, column): + op.drop_column(table, column) diff --git a/web/backend/models.py b/web/backend/models.py index f893c1f..724c4e0 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -549,11 +549,27 @@ class DouyuWorkbenchAccount(Base): Integer, nullable=False, default=0, server_default="0" ) created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow) + # 「导入后的数据」与「一键查询后的数据」必须能区分开: + # imported = 只导入并检测过 CK,资产/换绑仍是导入前的旧值; + # queried = 已在本工作台跑过一键查询; + # stale = 重登成功或 CK 重新生效,账号数据需要重新查询。 + data_state: Mapped[str] = mapped_column( + String(16), nullable=False, default="imported", server_default="imported" + ) + imported_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + queried_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + relogin_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) __table_args__ = ( UniqueConstraint( "user_id", "handbook_scope", "account_id", name="uq_douyu_workbench_account" ), + Index( + "ix_douyu_workbench_accounts_state", + "user_id", + "handbook_scope", + "data_state", + ), ) diff --git a/web/backend/routers/douyu.py b/web/backend/routers/douyu.py index 1b8859a..2190ffa 100644 --- a/web/backend/routers/douyu.py +++ b/web/backend/routers/douyu.py @@ -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))), ] ] ) diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 381ed4c..f062c69 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -2031,6 +2031,12 @@ class DouyuTaskAccountOut(BaseModel): overview_queried_at: datetime | None = None updated_at: datetime | None = None in_flight_login: bool = False + # 查询工作台数据来源(仅 `workbench_scope` 入参时回填): + # imported = 导入未查询,queried = 已查询,stale = 重登后待重查。 + workbench_data_state: str = "" + workbench_imported_at: datetime | None = None + workbench_queried_at: datetime | None = None + workbench_relogin_at: datetime | None = None class DouyuXpdGoodsOut(BaseModel): diff --git a/web/backend/services/douyu_query_workbench.py b/web/backend/services/douyu_query_workbench.py new file mode 100644 index 0000000..3411f1a --- /dev/null +++ b/web/backend/services/douyu_query_workbench.py @@ -0,0 +1,179 @@ +"""斗鱼「查询工作台」的数据状态维护。 + +查询工作台里的一个账号,数据来源必须能区分开: + +- ``imported``:刚导入,只做过 CK 检测;鱼翅/积分/宝典/换绑还是导入前的旧值; +- ``queried``:已在本工作台跑过一键查询,界面展示的是本次查询结果; +- ``stale``:重登成功或 CK 重新生效,账号数据已过期,需要按「重登的账号」单独再查一次。 + +写入口只有三处:导入(`update_workbench_accounts`)、查询成功(任务结束)、 +人工重登(`relogin-invalid`)。读取入口是账号列表与 `pending-ids`。 +""" + +from __future__ import annotations + +import logging +from collections.abc import Iterable +from datetime import UTC, datetime + +from sqlalchemy import or_ +from sqlalchemy.orm import Session + +from ..models import Account, DouyuWorkbenchAccount + +logger = logging.getLogger(__name__) + +DATA_STATE_IMPORTED = "imported" +DATA_STATE_QUERIED = "queried" +DATA_STATE_STALE = "stale" +DATA_STATES = (DATA_STATE_IMPORTED, DATA_STATE_QUERIED, DATA_STATE_STALE) + +QUERY_WORKBENCH_SCOPE = "query" + + +def _normalized_ids(account_ids: Iterable[int]) -> list[int]: + values: list[int] = [] + for raw in account_ids: + try: + account_id = int(raw) + except (TypeError, ValueError): + continue + if account_id > 0: + values.append(account_id) + return list(dict.fromkeys(values)) + + +def _query_workbench_rows( + db: Session, account_ids: list[int], *, user_id: int | None = None +): + query = db.query(DouyuWorkbenchAccount).filter( + DouyuWorkbenchAccount.handbook_scope == QUERY_WORKBENCH_SCOPE, + DouyuWorkbenchAccount.account_id.in_(account_ids), + ) + if user_id is not None: + query = query.filter(DouyuWorkbenchAccount.user_id == user_id) + return query + + +def mark_workbench_queried( + db: Session, + account_ids: Iterable[int], + *, + queried_at: datetime | None = None, + commit: bool = True, +) -> int: + """一键查询成功后把工作台行标记为「已查询」。 + + 只更新已经在查询工作台里的账号;其它工作台(精英/电竞/小店)不参与。 + """ + ids = _normalized_ids(account_ids) + if not ids: + return 0 + moment = queried_at or datetime.now(UTC) + rows = _query_workbench_rows(db, ids).all() + for row in rows: + row.data_state = DATA_STATE_QUERIED + row.queried_at = moment + if rows and commit: + db.commit() + return len(rows) + + +def mark_workbench_stale( + db: Session, + account_ids: Iterable[int], + *, + relogin_at: datetime | None = None, + commit: bool = True, +) -> int: + """人工重登后把工作台行标记为「待重新查询」。 + + 重登可能失败(CK 仍失效),此时界面优先展示 CK 状态,`stale` 只在 CK 恢复 + 有效后才作为「重登成功、待重新查询」参与批量查询。 + """ + ids = _normalized_ids(account_ids) + if not ids: + return 0 + moment = relogin_at or datetime.now(UTC) + rows = _query_workbench_rows(db, ids).all() + for row in rows: + row.data_state = DATA_STATE_STALE + row.relogin_at = moment + if rows and commit: + db.commit() + return len(rows) + + +def pending_query_ids( + db: Session, + *, + user_id: int, + visible_account_ids: Iterable[int] | None = None, +) -> dict[str, list[int] | int]: + """返回本工作台里「需要查询」的账号:导入未查 + 重登待重查,且当前有 CK。 + + 无 CK 的账号查了也会失败,交给重登流程,不进批量查询。 + """ + visible = _normalized_ids(visible_account_ids or []) + query = ( + db.query( + DouyuWorkbenchAccount.account_id, + DouyuWorkbenchAccount.data_state, + Account.cookie, + ) + .join(Account, Account.id == DouyuWorkbenchAccount.account_id) + .filter( + DouyuWorkbenchAccount.user_id == user_id, + DouyuWorkbenchAccount.handbook_scope == QUERY_WORKBENCH_SCOPE, + DouyuWorkbenchAccount.data_state.in_( + (DATA_STATE_IMPORTED, DATA_STATE_STALE) + ), + Account.cookie.isnot(None), + Account.cookie != "", + or_(Account.status.is_(None), Account.status != "invalid"), + or_( + Account.ck_check_status.is_(None), + Account.ck_check_status.notin_(("invalid", "error")), + ), + ) + ) + if visible: + query = query.filter(DouyuWorkbenchAccount.account_id.in_(visible)) + imported_ids: list[int] = [] + stale_ids: list[int] = [] + for account_id, data_state, _cookie in query.order_by( + DouyuWorkbenchAccount.sort_order.asc(), DouyuWorkbenchAccount.id.asc() + ).all(): + if data_state == DATA_STATE_STALE: + stale_ids.append(int(account_id)) + else: + imported_ids.append(int(account_id)) + return { + "imported_ids": imported_ids, + "stale_ids": stale_ids, + "account_ids": imported_ids + stale_ids, + "total": len(imported_ids) + len(stale_ids), + } + + +def workbench_state_map( + db: Session, + *, + user_id: int, + account_ids: Iterable[int], + handbook_scope: str = QUERY_WORKBENCH_SCOPE, +) -> dict[int, DouyuWorkbenchAccount]: + """批量读取工作台行状态,供账号列表回填数据来源标记。""" + ids = _normalized_ids(account_ids) + if not ids: + return {} + rows = ( + db.query(DouyuWorkbenchAccount) + .filter( + DouyuWorkbenchAccount.user_id == user_id, + DouyuWorkbenchAccount.handbook_scope == handbook_scope, + DouyuWorkbenchAccount.account_id.in_(ids), + ) + .all() + ) + return {int(row.account_id): row for row in rows} diff --git a/web/backend/services/douyu_runner_core.py b/web/backend/services/douyu_runner_core.py index 80d4dfa..b7443df 100644 --- a/web/backend/services/douyu_runner_core.py +++ b/web/backend/services/douyu_runner_core.py @@ -452,6 +452,25 @@ class DouyuBatchRunnerCore: message=message, ) db.commit() + if ( + status == "success" + and task.account_id + and str(task.task_type or "") == "query_assets_and_bind" + ): + # 查询工作台靠这行区分「导入后的旧数据」与「一键查询后的新数据」。 + try: + from .douyu_query_workbench import mark_workbench_queried + + mark_workbench_queried( + db, + [int(task.account_id)], + queried_at=task.finished_at, + ) + except Exception: # noqa: BLE001 - 工作台状态不能反噬任务结果 + logger.exception( + "[douyu] 标记查询工作台已查询失败: task_id={}", task_id + ) + db.rollback() self._push_task_event(task) if account is not None and event_context is not None: try: diff --git a/web/frontend/src/api/douyu.ts b/web/frontend/src/api/douyu.ts index 58da117..2c18c05 100644 --- a/web/frontend/src/api/douyu.ts +++ b/web/frontend/src/api/douyu.ts @@ -11,6 +11,7 @@ import type { DouyuQueryWorkbenchInvalidIdsResult, DouyuQueryWorkbenchLookupResult, DouyuQueryWorkbenchManualBudget, + DouyuQueryWorkbenchPendingIdsResult, DouyuQueryWorkbenchReloginResult, DouyuRechargeChannel, DouyuSupplyTarget, @@ -69,14 +70,41 @@ export const douyuApi = { api.put(`/douyu/supply-targets/${targetId}`, data), listAccounts: (params?: { search?: string; tag?: string; ids?: string; include_all?: boolean; ck_status?: string }) => api.get('/douyu/accounts', { params }), - listAccountsPaged: (params: PageParams & { ids?: string; tag?: string; include_all?: boolean; ck_status?: string }) => + listAccountsPaged: (params: PageParams & { + ids?: string; + tag?: string; + include_all?: boolean; + ck_status?: string; + workbench_scope?: 'elite' | 'esports' | 'peace' | 'query'; + workbench_state?: 'imported' | 'queried' | 'stale'; + }) => api.get, PaginatedResponse>('/douyu/accounts', { params }), - listAccountIds: (params: { search?: string; tag?: string; account_names?: string; include_all?: boolean; ck_status?: string } = {}) => + listAccountIds: (params: { + search?: string; + tag?: string; + account_names?: string; + include_all?: boolean; + ck_status?: string; + workbench_scope?: 'elite' | 'esports' | 'peace' | 'query'; + workbench_state?: 'imported' | 'queried' | 'stale'; + } = {}) => api.get<{ account_ids: number[]; total: number }, { account_ids: number[]; total: number }>('/douyu/accounts/ids', { params }), checkAccountsCk: (ids: number[]) => api.post< - { results: Array<{ id: number; valid: boolean; checked_at: string }>; success: boolean }, - { results: Array<{ id: number; valid: boolean; checked_at: string }>; success: boolean } + { + results: Array<{ id: number; valid: boolean; checked_at: string }>; + success: boolean; + checked?: number; + skipped?: number; + message?: string; + }, + { + results: Array<{ id: number; valid: boolean; checked_at: string }>; + success: boolean; + checked?: number; + skipped?: number; + message?: string; + } >('/douyu/accounts/ck-check', null, { params: { ids: ids.join(',') } }), reloginInvalidAccounts: (ids: number[]) => api.post< @@ -92,6 +120,10 @@ export const douyuApi = { api.get( '/douyu/query-workbench/invalid-ids', ), + getQueryWorkbenchPendingIds: () => + api.get( + '/douyu/query-workbench/pending-ids', + ), getQueryWorkbenchManualBudget: () => api.get( '/douyu/query-workbench/manual-budget', @@ -131,7 +163,10 @@ export const douyuApi = { params: { handbook_scope: handbookScope }, }), updateWorkbenchAccounts: (handbookScope: 'elite' | 'esports' | 'peace' | 'query', accountIds: number[]) => - api.put<{ account_ids: number[]; success: boolean }, { account_ids: number[]; success: boolean }>( + api.put< + { account_ids: number[]; imported_account_ids?: number[]; success: boolean }, + { account_ids: number[]; imported_account_ids?: number[]; success: boolean } + >( '/douyu/workbench-accounts', { handbook_scope: handbookScope, account_ids: accountIds }, ), listTasksPaged: (params: PageParams & { batch_id?: string; include_detail?: boolean }) => diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index f1d953b..91b7770 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -803,6 +803,10 @@ export interface DouyuTaskAccountItem { overview_queried_at?: string | null; updated_at?: string | null; in_flight_login?: boolean; + workbench_data_state?: DouyuWorkbenchDataState | ''; + workbench_imported_at?: string | null; + workbench_queried_at?: string | null; + workbench_relogin_at?: string | null; } export interface DouyuSupplyTargetStatus { @@ -1048,6 +1052,15 @@ export interface DouyuQueryWorkbenchLookupResult { total_input: number; } +export type DouyuWorkbenchDataState = 'imported' | 'queried' | 'stale'; + +export interface DouyuQueryWorkbenchPendingIdsResult { + account_ids: number[]; + imported_ids: number[]; + stale_ids: number[]; + total: number; +} + export interface DouyuQueryWorkbenchInvalidIdsResult { account_ids: number[]; invalid_ck_ids: number[]; diff --git a/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx b/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx index 56b2a1e..3965c11 100644 --- a/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx +++ b/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx @@ -59,6 +59,8 @@ type StatusFilterValue = | 'cooldown_ready' | 'cooldown_waiting'; +type DataStateFilterValue = '' | 'imported' | 'queried' | 'stale'; + const STATUS_FILTER_OPTIONS: Array<{ label: string; value: StatusFilterValue }> = [ { label: '全部', value: '' }, { label: 'CK 有效', value: 'valid' }, @@ -68,6 +70,48 @@ const STATUS_FILTER_OPTIONS: Array<{ label: string; value: StatusFilterValue }> { label: '冷却中', value: 'cooldown_waiting' }, ]; +const DATA_STATE_OPTIONS: Array<{ label: string; value: DataStateFilterValue }> = [ + { label: '数据:全部', value: '' }, + { label: '导入未查询', value: 'imported' }, + { label: '已查询', value: 'queried' }, + { label: '重登待重查', value: 'stale' }, +]; + +const DATA_STATE_META: Record< + Exclude, + { label: string; color: string; hint: string } +> = { + imported: { + label: '导入未查询', + color: 'default', + hint: '仅导入并检测过 CK,鱼翅/积分/宝典/换绑仍是导入前的旧数据', + }, + queried: { + label: '已查询', + color: 'success', + hint: '已在本工作台跑过一键查询,展示的是本次查询结果', + }, + stale: { + label: '重登待重查', + color: 'orange', + hint: '重新登录成功或 CK 重新生效,账号数据已过期,需要单独回查', + }, +}; + +/** 账号在本工作台的数据来源:未回填时按「导入未查询」保守处理。 */ +function resolveDataState(account: DouyuTaskAccountItem): Exclude { + const state = account.workbench_data_state; + if (state === 'queried' || state === 'stale') return state; + return 'imported'; +} + +/** 导入后自动检测 CK 的分片大小:单请求 8 线程并发,20 个约几秒。 */ +const IMPORT_CK_CHUNK_SIZE = 20; +/** 任务/登录进行中时的静默轮询间隔:不打断列表,只在后台替换数据。 */ +const POLL_INTERVAL_MS = 2500; +/** 最后一笔活动结束后继续轮询的宽限期,让登录结果落库并回显。 */ +const POLL_GRACE_MS = 12000; + function parseAccountNames(text: string): string[] { const seen = new Set(); return text @@ -134,7 +178,12 @@ export default function DouyuQueryWorkbenchPage() { const [searchText, setSearchText] = useState(''); const [statusFilter, setStatusFilter] = useState(''); + const [dataStateFilter, setDataStateFilter] = useState(''); const [concurrency, setConcurrency] = useState(5); + const [pendingQuery, setPendingQuery] = useState<{ importedIds: number[]; staleIds: number[] }>({ + importedIds: [], + staleIds: [], + }); const [tasks, setTasks] = useState([]); const [runningBatchIds, setRunningBatchIds] = useState>(() => new Set()); @@ -166,6 +215,17 @@ export default function DouyuQueryWorkbenchPage() { const [nowSeconds, setNowSeconds] = useState(() => Math.floor(Date.now() / 1000)); const tasksLoadingRef = useRef(false); + // 指向最新的账号列表加载器:导入后的 CK 刷新不想把整个分页依赖链再串一遍。 + const loadAccountsPageRef = useRef<((options?: { silent?: boolean }) => Promise) | null>( + null, + ); + const reloadAccounts = useCallback(async (options?: { silent?: boolean }) => { + await loadAccountsPageRef.current?.(options); + }, []); + const hasActivityRef = useRef(false); + const pollDeadlineRef = useRef(0); + const [polling, setPolling] = useState(false); + const budgetLoadingRef = useRef(false); useEffect(() => { const timer = window.setInterval(() => { @@ -174,15 +234,31 @@ export default function DouyuQueryWorkbenchPage() { return () => window.clearInterval(timer); }, []); - const loadManualBudget = useCallback(async () => { - setBudgetLoading(true); + const loadManualBudget = useCallback(async (options?: { silent?: boolean }) => { + // 轮询期间复用同一个请求,且不点亮预算 Tag 的 spinner —— 否则每 2.5 秒闪一次。 + if (options?.silent && budgetLoadingRef.current) return; + if (!options?.silent) setBudgetLoading(true); + budgetLoadingRef.current = true; try { const budget = await douyuApi.getQueryWorkbenchManualBudget(); setManualBudget(budget); } catch { // 仅用于顶部展示,失败不阻塞主体查询 } finally { - setBudgetLoading(false); + budgetLoadingRef.current = false; + if (!options?.silent) setBudgetLoading(false); + } + }, []); + + const loadPendingQuery = useCallback(async () => { + try { + const res = await douyuApi.getQueryWorkbenchPendingIds(); + setPendingQuery({ + importedIds: res.imported_ids || [], + staleIds: res.stale_ids || [], + }); + } catch { + // 仅用于按钮计数,失败不影响主流程 } }, []); @@ -202,47 +278,122 @@ export default function DouyuQueryWorkbenchPage() { void loadManualBudget(); }, [loadManualBudget, loadWorkbench]); + useEffect(() => { + if (!workbenchReady) return; + void loadPendingQuery(); + }, [loadPendingQuery, workbenchIds, workbenchReady]); + const saveWorkbenchIds = useCallback(async (nextIds: number[], toast?: string) => { const deduped = Array.from(new Set(nextIds.filter((id) => Number.isInteger(id) && id > 0))); const res = await douyuApi.updateWorkbenchAccounts('query', deduped); setWorkbenchIds(res.account_ids); setSelectedIds((prev) => prev.filter((id) => res.account_ids.includes(id))); if (toast) message.success(toast); - return res.account_ids; + return res; }, []); - const loadAccountsPage = useCallback(async () => { - if (!workbenchReady) return; - if (workbenchIds.length === 0) { - setAccounts([]); - setAccountTotal(0); - return; - } - setLoading(true); + /** + * 导入后默认跑一次 CK 检测(分片并发,带进度)。 + * 失效/无 CK 的账号会在列表上直接标红,用户可勾选后走人工重登。 + */ + const runImportCkCheck = useCallback(async (accountIds: number[]) => { + const ids = Array.from(new Set(accountIds.filter((id) => Number.isInteger(id) && id > 0))); + if (ids.length === 0) return; + const key = 'query-workbench-import-ck'; + const total = ids.length; + let done = 0; + let valid = 0; + let invalid = 0; + setCkCheckingIds((prev) => { + const next = new Set(prev); + ids.forEach((id) => next.add(id)); + return next; + }); try { - const res = await douyuApi.listAccountsPaged({ - ids: workbenchIds.join(','), - search: searchText.trim() || undefined, - ck_status: statusFilter || undefined, - include_all: true, - page: accountPage, - page_size: accountPageSize, - }); - setAccounts(res.items); - setAccountTotal(res.total); - if (accountPage > 1 && res.items.length === 0 && res.total > 0) { - setAccountPage(Math.max(1, Math.ceil(res.total / accountPageSize))); + for (let offset = 0; offset < ids.length; offset += IMPORT_CK_CHUNK_SIZE) { + const chunk = ids.slice(offset, offset + IMPORT_CK_CHUNK_SIZE); + message.open({ + key, + type: 'loading', + duration: 0, + content: `导入完成,正在检测 CK(${Math.min(done, total)}/${total})`, + }); + try { + const res = await douyuApi.checkAccountsCk(chunk); + const results = res.results || []; + valid += results.filter((item) => item.valid).length; + invalid += results.filter((item) => !item.valid).length; + } catch (error) { + // 单片段失败不中断其余片段:CK 检测是导入后的增强步骤 + message.error(`CK 检测失败: ${getErrorMessage(error)}`); + } finally { + done += chunk.length; + setCkCheckingIds((prev) => { + const next = new Set(prev); + chunk.forEach((id) => next.delete(id)); + return next; + }); + } } - } catch (error) { - message.error(`加载账号列表失败: ${getErrorMessage(error)}`); + message.open({ + key, + type: 'success', + duration: 4, + content: `导入后 CK 检测完成:有效 ${valid} 个,失效/异常 ${invalid} 个${invalid > 0 ? '(可勾选后人工重登)' : ''}`, + }); } finally { - setLoading(false); + await reloadAccounts({ silent: true }); + void loadPendingQuery(); } - }, [accountPage, accountPageSize, searchText, statusFilter, workbenchIds, workbenchReady]); + }, [loadPendingQuery, reloadAccounts]); + + const loadAccountsPage = useCallback( + async (options?: { silent?: boolean }) => { + if (!workbenchReady) return; + if (workbenchIds.length === 0) { + setAccounts([]); + setAccountTotal(0); + return; + } + // 静默刷新(轮询)不点亮表格 loading:否则每 2.5 秒整张表变灰闪一下。 + if (!options?.silent) setLoading(true); + try { + const res = await douyuApi.listAccountsPaged({ + ids: workbenchIds.join(','), + search: searchText.trim() || undefined, + ck_status: statusFilter || undefined, + workbench_scope: 'query', + workbench_state: dataStateFilter || undefined, + include_all: true, + page: accountPage, + page_size: accountPageSize, + }); + setAccounts(res.items); + setAccountTotal(res.total); + if (accountPage > 1 && res.items.length === 0 && res.total > 0) { + setAccountPage(Math.max(1, Math.ceil(res.total / accountPageSize))); + } + } catch (error) { + if (!options?.silent) { + message.error(`加载账号列表失败: ${getErrorMessage(error)}`); + } + } finally { + if (!options?.silent) setLoading(false); + } + }, + [ + accountPage, + accountPageSize, + dataStateFilter, + searchText, + statusFilter, + workbenchIds, + workbenchReady, + ], + ); const loadTasks = useCallback(async () => { - if (!workbenchReady || tasksLoadingRef.current) return; - tasksLoadingRef.current = true; + if (!workbenchReady || tasksLoadingRef.current) return; tasksLoadingRef.current = true; try { const data = await douyuApi.listTasks('query', undefined, true, 300); setTasks(data); @@ -260,6 +411,10 @@ export default function DouyuQueryWorkbenchPage() { } }, [workbenchReady]); + useEffect(() => { + loadAccountsPageRef.current = loadAccountsPage; + }, [loadAccountsPage]); + useEffect(() => { void loadAccountsPage(); }, [loadAccountsPage]); @@ -276,15 +431,32 @@ export default function DouyuQueryWorkbenchPage() { [accounts, runningBatchIds, tasks], ); + // 有任何在途任务/登录就开一个轮询窗口;最后一笔活动结束后再宽限片刻, + // 让登录结果(CK 状态、数据状态)落库并回显,避免「刚登录完不再刷新」。 useEffect(() => { - if (!hasInFlightActivity) return undefined; + hasActivityRef.current = hasInFlightActivity; + if (!hasInFlightActivity) return; + pollDeadlineRef.current = Date.now() + POLL_GRACE_MS; + setPolling(true); + }, [hasInFlightActivity]); + + useEffect(() => { + if (!polling) return undefined; const timer = window.setInterval(() => { + if (hasActivityRef.current) { + pollDeadlineRef.current = Date.now() + POLL_GRACE_MS; + } + if (!hasActivityRef.current && Date.now() > pollDeadlineRef.current) { + setPolling(false); + return; + } void loadTasks(); - void loadAccountsPage(); - void loadManualBudget(); - }, 2200); + void loadAccountsPage({ silent: true }); + void loadManualBudget({ silent: true }); + void loadPendingQuery(); + }, POLL_INTERVAL_MS); return () => window.clearInterval(timer); - }, [hasInFlightActivity, loadAccountsPage, loadManualBudget, loadTasks]); + }, [loadAccountsPage, loadManualBudget, loadPendingQuery, loadTasks, polling]); const latestTaskByAccount = useMemo(() => { const map = new Map(); @@ -302,6 +474,9 @@ export default function DouyuQueryWorkbenchPage() { [accounts], ); + const pendingTotal = pendingQuery.importedIds.length + pendingQuery.staleIds.length; + const pendingStaleCount = pendingQuery.staleIds.length; + // 导入弹窗池查询 const loadImportPool = useCallback(async (page = importPage) => { setImportLoading(true); @@ -347,14 +522,15 @@ export default function DouyuQueryWorkbenchPage() { try { const lookup = await douyuApi.lookupQueryWorkbenchAccounts(names); setUnmatchedNames(lookup.unmatched_names || []); + let importedIds: number[] = []; if (lookup.account_ids.length > 0) { const beforeSet = new Set(workbenchIds); - const addedCount = lookup.account_ids.filter((id) => !beforeSet.has(id)).length; - await saveWorkbenchIds([...workbenchIds, ...lookup.account_ids]); + const res = await saveWorkbenchIds([...workbenchIds, ...lookup.account_ids]); + importedIds = (res.imported_account_ids || []).filter((id) => !beforeSet.has(id)); setAccountPage(1); message.success( - addedCount > 0 - ? `已匹配 ${lookup.account_ids.length} 个账号,新导入 ${addedCount} 个到查询工作台` + importedIds.length > 0 + ? `已匹配 ${lookup.account_ids.length} 个账号,新导入 ${importedIds.length} 个到查询工作台` : `已匹配 ${lookup.account_ids.length} 个账号(均已在工作台中)`, ); } else { @@ -364,6 +540,10 @@ export default function DouyuQueryWorkbenchPage() { setPasteNamesText(''); setImportOpen(false); } + // 导入后默认检测一次 CK:失效/无 CK 账号直接标出来,方便人工重登。 + if (importedIds.length > 0) { + await runImportCkCheck(importedIds); + } } catch (error) { message.error(`导入失败: ${getErrorMessage(error)}`); } finally { @@ -378,11 +558,15 @@ export default function DouyuQueryWorkbenchPage() { } const beforeSet = new Set(workbenchIds); const addedCount = importSelectedIds.filter((id) => !beforeSet.has(id)).length; - await saveWorkbenchIds( + const saved = await saveWorkbenchIds( [...workbenchIds, ...importSelectedIds], addedCount > 0 ? `新导入 ${addedCount} 个账号到查询工作台` : '所选账号均已在工作台中', ); setImportOpen(false); + const importedIds = (saved.imported_account_ids || []).filter((id) => !beforeSet.has(id)); + if (importedIds.length > 0) { + await runImportCkCheck(importedIds); + } }; const handleImportAllFiltered = async () => { @@ -400,11 +584,15 @@ export default function DouyuQueryWorkbenchPage() { } const beforeSet = new Set(workbenchIds); const addedCount = res.account_ids.filter((id) => !beforeSet.has(id)).length; - await saveWorkbenchIds( + const saved = await saveWorkbenchIds( [...workbenchIds, ...res.account_ids], `已按筛选导入 ${res.account_ids.length} 个账号(新增 ${addedCount} 个)`, ); setImportOpen(false); + const importedIds = (saved.imported_account_ids || []).filter((id) => !beforeSet.has(id)); + if (importedIds.length > 0) { + await runImportCkCheck(importedIds); + } } catch (error) { message.error(`按筛选导入失败: ${getErrorMessage(error)}`); } finally { @@ -412,8 +600,41 @@ export default function DouyuQueryWorkbenchPage() { } }; + const hasActiveFilter = Boolean( + searchText.trim() || statusFilter || dataStateFilter, + ); + + /** + * 一键查询:优先用勾选,其次用当前筛选结果(跨页),最后才是整个工作台。 + * 这样「数据:重登待重查 + 一键查询」就只会回查重登过的账号。 + */ const handleOneClickQuery = async (overrideIds?: number[]) => { - const rawTargetIds = overrideIds ?? (selectedIds.length > 0 ? selectedIds : workbenchIds); + let rawTargetIds = overrideIds; + if (!rawTargetIds) { + if (selectedIds.length > 0) { + rawTargetIds = selectedIds; + } else if (hasActiveFilter) { + try { + const res = await douyuApi.listAccountIds({ + search: searchText.trim() || undefined, + ck_status: statusFilter || undefined, + workbench_scope: 'query', + workbench_state: dataStateFilter || undefined, + include_all: true, + }); + rawTargetIds = res.account_ids; + if (rawTargetIds.length === 0) { + message.info('当前筛选条件下没有可查询的账号'); + return; + } + } catch (error) { + message.error(`获取筛选账号失败: ${getErrorMessage(error)}`); + return; + } + } else { + rawTargetIds = workbenchIds; + } + } if (rawTargetIds.length === 0) { message.warning('工作台暂无账号,请先导入斗鱼账号'); return; @@ -447,6 +668,19 @@ export default function DouyuQueryWorkbenchPage() { } }; + /** + * 只查「待查询」的账号:导入后未查过 + 重登成功后待重查。 + * 重登成功后点这里就只会回查重新登录的账号,不会把整个工作台重跑一遍。 + */ + const handleQueryPending = async () => { + const targetIds = Array.from(new Set([...pendingQuery.importedIds, ...pendingQuery.staleIds])); + if (targetIds.length === 0) { + message.info('当前没有待查询的账号(导入后待查 / 重登后待重查)'); + return; + } await handleOneClickQuery(targetIds); + void loadPendingQuery(); + }; + const handleCheckCk = async (overrideIds?: number[]) => { const candidateRows = overrideIds ? accounts.filter((a) => overrideIds.includes(a.id)) @@ -568,9 +802,10 @@ export default function DouyuQueryWorkbenchPage() { res.skipped_missing_credentials > 0 ? `缺密码/邮箱 ${res.skipped_missing_credentials}` : '', ].filter(Boolean); message.success( - `已加入人工登录队列:${parts.join(',')}${skipParts.length ? `(${skipParts.join(',')})` : ''}`, + `已加入人工登录队列:${parts.join(',')}${skipParts.length ? `(${skipParts.join(',')})` : ''};登录成功后可点「只查待查询」单独回查这批账号`, ); await loadAccountsPage(); + void loadPendingQuery(); } catch (error) { message.error(`提交重登失败: ${getErrorMessage(error)}`); } finally { @@ -580,6 +815,28 @@ export default function DouyuQueryWorkbenchPage() { }); }; + /** 单行「重登该账号」:走同一人工预算入口,只提交这一行。 */ + const handleReloginSingle = async (account: DouyuTaskAccountItem) => { + if (!canRelogin) { + message.error('无权限发起重登(需超级管理员或 login:batch 权限)'); + return; + } + setReloginSubmitting(true); + try { + const res = await douyuApi.reloginQueryWorkbenchInvalid([account.id], false); + if (res.manual_budget) setManualBudget(res.manual_budget); + message.success( + `已将 ${account.username} 加入人工登录队列(重登 ${res.relogin_count} · 登录 ${res.login_count})`, + ); + await loadAccountsPage({ silent: true }); + void loadPendingQuery(); + } catch (error) { + message.error(`提交重登失败: ${getErrorMessage(error)}`); + } finally { + setReloginSubmitting(false); + } + }; + const handleExportCsv = async () => { if (workbenchIds.length === 0) { message.warning('工作台暂无可导出的账号'); @@ -706,33 +963,74 @@ export default function DouyuQueryWorkbenchPage() { ); }, }, + { + title: '数据来源', + width: 130, + render: (_, record) => { + const state = resolveDataState(record); + const meta = DATA_STATE_META[state]; + const stamp = state === 'queried' + ? record.workbench_queried_at + : state === 'stale' + ? record.workbench_relogin_at + : record.workbench_imported_at; + return ( + + + + {meta.label} + + {stamp ? ( + + {state === 'queried' ? '查询' : state === 'stale' ? '重登' : '导入'}: {formatTime(stamp)} + + ) : null} + + + ); + }, + }, { title: '鱼翅', width: 115, - render: (_, record) => ( - - {record.gold_balance != null ? record.gold_balance : '-'} - {record.exchange_balance != null ? ( - - 兑换: {record.exchange_balance} - - ) : null} - - ), + render: (_, record) => { + const stale = resolveDataState(record) !== 'queried'; + return ( + + + + {record.gold_balance != null ? record.gold_balance : '-'} + + {record.exchange_balance != null ? ( + + 兑换: {record.exchange_balance} + + ) : null} + + + ); + }, }, { title: '积分', width: 145, - render: (_, record) => ( - - {record.points != null ? record.points : '-'} - {record.points_expire_at ? ( - - 到期: {formatTime(record.points_expire_at)} - - ) : null} - - ), + render: (_, record) => { + const stale = resolveDataState(record) !== 'queried'; + return ( + + + + {record.points != null ? record.points : '-'} + + {record.points_expire_at ? ( + + 到期: {formatTime(record.points_expire_at)} + + ) : null} + + + ); + }, }, { title: '宝典状态 / 到期', @@ -909,6 +1207,7 @@ export default function DouyuQueryWorkbenchPage() { width: 110, fixed: 'right', render: (_, record) => { + const needsRelogin = isInvalidOrNoCookie(record); const items: MenuProps['items'] = [ { key: 'copy-username', @@ -923,6 +1222,13 @@ export default function DouyuQueryWorkbenchPage() { disabled: record.has_cookie === false || Boolean(record.in_flight_login), onClick: () => void handleCheckCk([record.id]), }, + { + key: 'relogin', + icon: , + label: record.has_cookie === false ? '人工登录该账号' : '重登该账号(人工预算)', + disabled: !canRelogin || !needsRelogin || Boolean(record.in_flight_login), + onClick: () => void handleReloginSingle(record), + }, { key: 'remove', icon: , @@ -1019,6 +1325,13 @@ export default function DouyuQueryWorkbenchPage() { 斗鱼查询工作台 工作台共 {workbenchIds.length} 个账号 + {pendingTotal > 0 ? ( + + 待查询 {pendingTotal} + + ) : null} {hasInFlightActivity ? ( }> 任务/登录进行中,自动刷新 @@ -1026,7 +1339,8 @@ export default function DouyuQueryWorkbenchPage() { ) : null} - 支持导入斗鱼号(含 CK 失效/无 CK 账号),一键查询鱼翅、积分、宝典状态与换绑时间并导出 CSV;失效 CK 可选中后走人工预算重新登录。 + 支持导入斗鱼号(含 CK 失效/无 CK 账号),导入后自动检测一次 CK,一键查询鱼翅、积分、宝典状态与换绑时间并导出 CSV; + 列表会区分「导入未查询」与「已查询」;失效 CK 可选中后走人工预算重新登录,重登成功后再点「只查待查询」就只回查这些账号。 @@ -1075,7 +1389,9 @@ export default function DouyuQueryWorkbenchPage() { > {selectedIds.length > 0 ? `一键查询已选(${selectedIds.length})` - : '一键查询全部(鱼翅/积分/宝典/换绑)'} + : hasActiveFilter + ? '一键查询筛选结果(鱼翅/积分/宝典/换绑)' + : '一键查询全部(鱼翅/积分/宝典/换绑)'} + void handleOneClickQuery(pendingQuery.importedIds), + }, + { + key: 'stale', + label: `重登待重查(${pendingStaleCount})`, + disabled: pendingStaleCount === 0, + onClick: () => void handleOneClickQuery(pendingQuery.staleIds), + }, + ], + }} + > + + + + @@ -1184,6 +1530,16 @@ export default function DouyuQueryWorkbenchPage() { }} /> +