From 8869e427d23f53fdf2fa5e580bc3de804ccccfab Mon Sep 17 00:00:00 2001 From: yml Date: Fri, 20 Nov 2026 20:58:25 +0800 Subject: [PATCH] =?UTF-8?q?feat(login):=20=E5=A2=9E=E5=8A=A0=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E4=BB=BB=E5=8A=A1=E8=B4=A6=E5=8F=B7=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E4=B8=8E=E7=AD=9B=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_login_task_filters.py | 190 +++++++++++++++ web/backend/routers/login.py | 178 ++++++++++++-- web/backend/schemas.py | 14 ++ web/frontend/src/api/login.ts | 47 +++- web/frontend/src/api/types.ts | 12 + web/frontend/src/pages/LoginTasksPage.tsx | 276 +++++++++++++++++++--- 6 files changed, 651 insertions(+), 66 deletions(-) create mode 100644 tests/test_login_task_filters.py diff --git a/tests/test_login_task_filters.py b/tests/test_login_task_filters.py new file mode 100644 index 0000000..b73240e --- /dev/null +++ b/tests/test_login_task_filters.py @@ -0,0 +1,190 @@ +"""登录任务列表的账号信息与统一筛选口径。""" + +from __future__ import annotations + +import asyncio +from datetime import UTC, datetime + +from tests.support.db import get_test_engine, make_test_session +from web.backend.models import Account, LoginTask, User +from web.backend.routers.login import ( + delete_tasks, + export_tasks, + list_tasks, + task_filter_options, + tasks_summary, +) + +NOW = datetime(2026, 11, 20, 12, 0, 0, tzinfo=UTC) + + +async def _read_body(response) -> str: + chunks: list[bytes] = [] + async for chunk in response.body_iterator: + chunks.append(chunk if isinstance(chunk, bytes) else str(chunk).encode()) + return b"".join(chunks).decode("utf-8") + + +class TestLoginTaskFilters: + def setup_method(self): + self.engine = get_test_engine() + self.db = make_test_session(self.engine) + self.admin = User( + username="login-filter-admin", + password_hash="h", + role="super_admin", + is_active=True, + ) + self.support = User( + username="login-filter-kf", + password_hash="h", + role="support", + is_active=True, + ) + self.other = User( + username="login-filter-kf2", + password_hash="h", + role="support", + is_active=True, + ) + self.db.add_all([self.admin, self.support, self.other]) + self.db.flush() + self.account_a = self._account( + "task-account-a", + tag="A组", + assigned_to=self.support.id, + status="active", + ck_check_status="valid", + ) + self.account_b = self._account( + "task-account-b", + tag="A组", + assigned_to=self.other.id, + status="invalid", + ck_check_status="invalid", + ) + self.account_c = self._account( + "task-account-c", + tag="B组", + assigned_to=None, + status="imported", + ck_check_status="", + ) + self.task_a = self._task(self.account_a, "success", "登录成功") + self.task_b = self._task(self.account_b, "failed", "账号密码错误") + self.task_c = self._task(self.account_c, "success", "登录成功") + self.db.commit() + + def teardown_method(self): + self.db.close() + + def _account(self, username: str, **kwargs) -> Account: + account = Account( + username=username, + password="p", + email=f"{username}@example.com", + email_password="ep", + cookie=kwargs.pop("cookie", "acf_uid=1"), + ck_checked_at=kwargs.pop("ck_checked_at", NOW), + cookie_updated_at=kwargs.pop( + "cookie_updated_at", datetime(2026, 11, 20, 11, 59, tzinfo=UTC) + ), + **kwargs, + ) + self.db.add(account) + self.db.flush() + return account + + def _task(self, account: Account, status: str, message: str) -> LoginTask: + task = LoginTask( + batch_id="login-filter-batch", + attempt_batch_id="login-filter-batch", + account_id=account.id, + status=status, + attempt_status=status, + attempt_message=message, + message=message, + created_by=self.admin.id, + ) + self.db.add(task) + self.db.flush() + return task + + def _names(self, **kwargs) -> list[str]: + result = list_tasks( + page=1, + page_size=50, + db=self.db, + current=self.admin, + **kwargs, + ) + return [item.account_username for item in result["items"]] + + def test_list_returns_current_account_metadata(self): + result = list_tasks( + page=1, + page_size=10, + search="task-account-a", + db=self.db, + current=self.admin, + ) + + item = result["items"][0] + assert item.account_tag == "A组" + assert item.assigned_to == self.support.id + assert item.assigned_username == "login-filter-kf" + assert item.account_status == "active" + assert item.ck_check_status == "valid" + assert item.ck_checked_at is not None + assert item.cookie_updated_at is not None + + def test_account_filters_are_combined(self): + assert self._names(tag="A组") == ["task-account-b", "task-account-a"] + assert self._names(tag="A组", assigned_user_id=self.support.id) == [ + "task-account-a" + ] + assert self._names(assign_status="unassigned") == ["task-account-c"] + assert self._names(ck_status="invalid") == ["task-account-b"] + assert self._names(ck_status="unchecked") == ["task-account-c"] + assert self._names(account_status="invalid") == ["task-account-b"] + + def test_summary_uses_the_same_filters(self): + summary = tasks_summary(tag="A组", db=self.db, current=self.admin) + + assert summary["total"] == 2 + assert summary["success"] == 1 + assert summary["failed"] == 1 + + def test_filter_options_only_include_visible_task_accounts(self): + options = task_filter_options(db=self.db, current=self.admin) + + assert options["tags"] == ["A组", "B组"] + assert {item["username"] for item in options["assigned_users"]} == { + "login-filter-kf", + "login-filter-kf2", + } + + def test_export_and_bulk_delete_share_filters(self): + response = export_tasks( + tag="A组", + status="failed", + db=self.db, + current=self.admin, + ) + body = asyncio.run(_read_body(response)) + assert "task-account-b" in body + assert "task-account-a" not in body + assert "login-filter-kf2" in body + + task_b_id = self.task_b.id + task_a_id = self.task_a.id + result = delete_tasks( + all_matching=True, + tag="A组", + status="failed", + db=self.db, + current=self.admin, + ) + assert result["deleted"] == 1 + assert self.db.get(LoginTask, task_b_id) is None + assert self.db.get(LoginTask, task_a_id) is not None diff --git a/web/backend/routers/login.py b/web/backend/routers/login.py index 4e5ef10..b7229d1 100644 --- a/web/backend/routers/login.py +++ b/web/backend/routers/login.py @@ -15,7 +15,7 @@ from fastapi import ( ) from fastapi.responses import StreamingResponse from sqlalchemy import and_, func, or_ -from sqlalchemy.orm import Session, load_only +from sqlalchemy.orm import Session from ..database import SessionLocal, get_db from ..deps import authenticate_websocket, get_current_user, require_permission @@ -89,6 +89,43 @@ def _apply_status_filter(query, status: str | None): ) +def _apply_login_task_filters( + query, + *, + status: str | None = None, + search: str = "", + tag: str = "", + assigned_user_id: int | None = None, + assign_status: str = "", + ck_status: str = "", + account_status: str = "", +): + """给登录任务查询叠加账号维度筛选,列表/统计/导出/批删共用。""" + query = _apply_status_filter(query, status) + search_text = (search or "").strip() + if search_text: + query = query.filter(Account.username.ilike(f"%{search_text}%")) + tag_text = (tag or "").strip() + if tag_text: + query = query.filter(Account.tag == tag_text) + assign_scope = (assign_status or "").strip() + if assign_scope == "unassigned": + query = query.filter(Account.assigned_to.is_(None)) + elif isinstance(assigned_user_id, int) and not isinstance(assigned_user_id, bool): + query = query.filter(Account.assigned_to == assigned_user_id) + ck_text = (ck_status or "").strip() + if ck_text == "unchecked": + query = query.filter( + or_(Account.ck_check_status.is_(None), Account.ck_check_status == "") + ) + elif ck_text: + query = query.filter(Account.ck_check_status == ck_text) + account_status_text = (account_status or "").strip() + if account_status_text: + query = query.filter(Account.status == account_status_text) + return query + + def _login_task_summary(query): """按状态汇总登录任务,避免概览页拉完整任务列表。""" rows = ( @@ -212,27 +249,45 @@ def _visible_tasks_query(db: Session, current: User, batch_id: str | None): def _serialize_tasks(db: Session, rows) -> list[LoginTaskOut]: - """把任务行拼上账号名后序列化。""" + """把任务行拼上当前账号信息后序列化。""" account_ids = [t.account_id for t in rows] - accounts_map = {} + accounts_map: dict[int, tuple] = {} if account_ids: - accs = ( - db.query(Account) - .options(load_only(Account.id, Account.username)) + for row in ( + db.query( + Account.id, + Account.username, + Account.tag, + Account.assigned_to, + Account.status, + Account.ck_check_status, + Account.ck_checked_at, + Account.cookie_updated_at, + User.username, + ) + .outerjoin(User, Account.assigned_to == User.id) .filter(Account.id.in_(account_ids)) .all() - ) - accounts_map = {a.id: a.username for a in accs} + ): + accounts_map[int(row[0])] = row result = [] for t in rows: attempt_status = t.attempt_status or "" + account = accounts_map.get(int(t.account_id)) result.append( LoginTaskOut( id=t.id, batch_id=t.attempt_batch_id or t.batch_id, account_id=t.account_id, - account_username=accounts_map.get(t.account_id, ""), + account_username=(account[1] if account else "") or "", + account_tag=(account[2] if account else "") or "", + assigned_to=(account[3] if account else None), + assigned_username=(account[8] if account else "") or "", + account_status=(account[4] if account else "") or "", + ck_check_status=(account[5] if account else "") or "", + ck_checked_at=(account[6] if account else None), + cookie_updated_at=(account[7] if account else None), status=attempt_status or t.status, cookie="", message=(t.attempt_message if attempt_status else "") @@ -254,6 +309,12 @@ def list_tasks( page: int | None = None, page_size: int = 50, status: str | None = None, + search: str = "", + tag: str = "", + assigned_user_id: int | None = None, + assign_status: str = "", + ck_status: str = "", + account_status: str = "", db: Session = Depends(get_db), current: User = Depends(get_current_user), ): @@ -265,7 +326,16 @@ def list_tasks( 传 `page` 时同时返回 `total`,是为了让前端能「全选所有筛选结果」—— 否则跨页选择无从下手,而任务量早就过了单页能装下的规模。 """ - query = _apply_status_filter(_visible_tasks_query(db, current, batch_id), status) + query = _apply_login_task_filters( + _visible_tasks_query(db, current, batch_id), + status=status, + search=search, + tag=tag, + assigned_user_id=assigned_user_id, + assign_status=assign_status, + ck_status=ck_status, + account_status=account_status, + ) ordered = query.order_by(LoginTask.id.desc()) @@ -284,6 +354,35 @@ def list_tasks( } +@router.get("/tasks/filters") +def task_filter_options( + db: Session = Depends(get_db), + current: User = Depends(get_current_user), +): + """登录任务列表可用的标签与当前归属客服。""" + base = _visible_tasks_query(db, current, None) + tags = [ + row[0] + for row in base.with_entities(Account.tag) + .filter(Account.tag.isnot(None), Account.tag != "") + .distinct() + .order_by(Account.tag.asc()) + .all() + ] + assigned_users = [ + {"id": int(user_id), "username": username or ""} + for user_id, username in ( + base.with_entities(User.id, User.username) + .join(User, Account.assigned_to == User.id) + .filter(User.role == "support") + .distinct() + .order_by(User.username.asc()) + .all() + ) + ] + return {"tags": tags, "assigned_users": assigned_users} + + def _fmt_dt(value) -> str: """导出用的时间格式。 @@ -299,6 +398,12 @@ def _fmt_dt(value) -> str: def export_tasks( batch_id: str | None = None, status: str | None = None, + search: str = "", + tag: str = "", + assigned_user_id: int | None = None, + assign_status: str = "", + ck_status: str = "", + account_status: str = "", db: Session = Depends(get_db), current: User = Depends(get_current_user), ): @@ -313,19 +418,28 @@ def export_tasks( - 失败分型复用登录失败那套(`login_failure.classify_failure`), 与账号时间线上写的是同一份判据,不会出现「页面上算 A、导出算 B」。 """ - query = _apply_status_filter(_visible_tasks_query(db, current, batch_id), status) + query = _apply_login_task_filters( + _visible_tasks_query(db, current, batch_id), + status=status, + search=search, + tag=tag, + assigned_user_id=assigned_user_id, + assign_status=assign_status, + ck_status=ck_status, + account_status=account_status, + ) rows = query.order_by(LoginTask.id.desc()).all() account_ids = [t.account_id for t in rows] info: dict[int, tuple[str, str, str]] = {} if account_ids: - for acc_id, username, tag, owner in ( + for acc_id, username, account_tag, owner in ( db.query(Account.id, Account.username, Account.tag, User.username) .outerjoin(User, Account.assigned_to == User.id) .filter(Account.id.in_(account_ids)) .all() ): - info[acc_id] = (username or "", tag or "", owner or "") + info[acc_id] = (username or "", account_tag or "", owner or "") output = io.StringIO() writer = csv.writer(output) @@ -380,13 +494,28 @@ def export_tasks( @router.get("/tasks/summary") def tasks_summary( + batch_id: str | None = None, + status: str | None = None, + search: str = "", + tag: str = "", + assigned_user_id: int | None = None, + assign_status: str = "", + ck_status: str = "", + account_status: str = "", db: Session = Depends(get_db), current: User = Depends(get_current_user), ): """登录任务统计。""" - query = db.query(LoginTask).join(Account, LoginTask.account_id == Account.id) - if not user_has_permission(current, "login:view_all"): - query = query.filter(Account.assigned_to == current.id) + query = _apply_login_task_filters( + _visible_tasks_query(db, current, batch_id), + status=status, + search=search, + tag=tag, + assigned_user_id=assigned_user_id, + assign_status=assign_status, + ck_status=ck_status, + account_status=account_status, + ) return _login_task_summary(query) @@ -445,6 +574,12 @@ def delete_tasks( task_ids: str = "", batch_id: str | None = None, status: str | None = None, + search: str = "", + tag: str = "", + assigned_user_id: int | None = None, + assign_status: str = "", + ck_status: str = "", + account_status: str = "", all_matching: bool = False, db: Session = Depends(get_db), current: User = Depends(require_permission("login:batch")), @@ -474,8 +609,15 @@ def delete_tasks( # 所以先按权限与筛选条件查出 id,再按主键删。 # 状态筛选与列表/导出共用一份 —— 「清空失败」以前只删 `failed`、 # 漏掉 `error`,删完与页面上那个「失败 N」的数还对不上。 - query = _apply_status_filter( - _visible_tasks_query(db, current, batch_id), status + query = _apply_login_task_filters( + _visible_tasks_query(db, current, batch_id), + status=status, + search=search, + tag=tag, + assigned_user_id=assigned_user_id, + assign_status=assign_status, + ck_status=ck_status, + account_status=account_status, ) ids = [row[0] for row in query.with_entities(LoginTask.id).all()] else: diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 7429b20..be7effb 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -383,6 +383,13 @@ class LoginTaskOut(BaseModel): batch_id: str account_id: int account_username: str = "" + account_tag: str = "" + assigned_to: int | None = None + assigned_username: str = "" + account_status: str = "" + ck_check_status: str = "" + ck_checked_at: datetime | None = None + cookie_updated_at: datetime | None = None status: str cookie: str = "" message: str = "" @@ -399,6 +406,13 @@ class LoginTaskOut(BaseModel): "batch_id": self.batch_id, "account_id": self.account_id, "account_username": self.account_username, + "account_tag": self.account_tag, + "assigned_to": self.assigned_to, + "assigned_username": self.assigned_username, + "account_status": self.account_status, + "ck_check_status": self.ck_check_status, + "ck_checked_at": _isoformat(self.ck_checked_at), + "cookie_updated_at": _isoformat(self.cookie_updated_at), "status": self.status, "cookie": self.cookie, "message": self.message, diff --git a/web/frontend/src/api/login.ts b/web/frontend/src/api/login.ts index a81c0eb..9f55df9 100644 --- a/web/frontend/src/api/login.ts +++ b/web/frontend/src/api/login.ts @@ -1,5 +1,8 @@ import api from './client'; -import type { BatchLoginResult, LoginTaskItem, MessageDeletedResponse, MessageResponse, TaskSummary } from './types'; +import type { + BatchLoginResult, LoginTaskFilterOptions, LoginTaskItem, MessageDeletedResponse, + MessageResponse, TaskSummary, +} from './types'; interface CreateBatchParams { account_ids: number[]; @@ -17,35 +20,57 @@ export interface TaskPage { page_size: number; } +export interface LoginTaskFilters { + batch_id?: string; + status?: string; + search?: string; + tag?: string; + assigned_user_id?: number; + assign_status?: string; + ck_status?: string; + account_status?: string; +} + +const filterParams = (params: LoginTaskFilters) => ({ + batch_id: params.batch_id ?? '', + status: params.status ?? '', + search: params.search ?? '', + tag: params.tag ?? '', + assigned_user_id: params.assigned_user_id, + assign_status: params.assign_status ?? '', + ck_status: params.ck_status ?? '', + account_status: params.account_status ?? '', +}); + export const loginApi = { createBatch: (params: CreateBatchParams) => api.post('/login/batch', params), // 不传 page 时后端返回裸数组(老调用方契约),传了才返回 {items,total}。 listTasks: (batch_id?: string) => api.get('/login/tasks', { params: batch_id ? { batch_id } : {} }), - listTasksPaged: (params: { page: number; page_size: number; batch_id?: string; status?: string }) => - api.get('/login/tasks', { params: { ...params, batch_id: params.batch_id ?? '' } }), - tasksSummary: () => api.get('/login/tasks/summary'), + listTasksPaged: (params: LoginTaskFilters & { page: number; page_size: number }) => + api.get('/login/tasks', { params: { ...params, ...filterParams(params) } }), + taskFilterOptions: () => + api.get('/login/tasks/filters'), + tasksSummary: (params: LoginTaskFilters = {}) => + api.get('/login/tasks/summary', { params: filterParams(params) }), /** * 导出登录任务 CSV(按当前筛选,不分页)。 * * `status` 传 'failed' 时后端会展开成 failed + error —— 页面上「失败」 * 本来就是一个组,导出与列表口径必须一致。 */ - exportTasks: (params: { batch_id?: string; status?: string }) => + exportTasks: (params: LoginTaskFilters) => api.get('/login/tasks/export', { responseType: 'blob', - params: { - batch_id: params.batch_id ?? '', - status: params.status ?? '', - }, + params: filterParams(params), }), stop: (batch_id: string) => api.post(`/login/stop/${batch_id}`), deleteTask: (id: number) => api.delete(`/login/tasks/${id}`), deleteTasks: (ids: number[]) => api.delete(`/login/tasks`, { params: { task_ids: ids.join(',') } }), // 跨页全选用:按当前筛选条件删除全部(后端会跳过在途任务)。 - deleteTasksMatching: (params: { batch_id?: string; status?: string }) => + deleteTasksMatching: (params: LoginTaskFilters) => api.delete('/login/tasks', { - params: { all_matching: true, batch_id: params.batch_id ?? '', status: params.status ?? '' }, + params: { all_matching: true, ...filterParams(params) }, }), }; diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index cb9fd6d..d0727ac 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -469,6 +469,13 @@ export interface LoginTaskItem { batch_id: string; account_id: number; account_username: string; + account_tag: string; + assigned_to: number | null; + assigned_username: string; + account_status: string; + ck_check_status: string; + ck_checked_at: string | null; + cookie_updated_at: string | null; status: string; cookie: string; message: string; @@ -477,6 +484,11 @@ export interface LoginTaskItem { finished_at: string | null; } +export interface LoginTaskFilterOptions { + tags: string[]; + assigned_users: { id: number; username: string }[]; +} + export interface YybTask { id: number; task_id: string; diff --git a/web/frontend/src/pages/LoginTasksPage.tsx b/web/frontend/src/pages/LoginTasksPage.tsx index d3eae32..98981f4 100644 --- a/web/frontend/src/pages/LoginTasksPage.tsx +++ b/web/frontend/src/pages/LoginTasksPage.tsx @@ -1,19 +1,22 @@ import { useEffect, useState, useMemo, useCallback, useRef } from 'react'; import { - Table, Button, Select, Tag, Space, InputNumber, Tooltip, Popconfirm, theme, Modal, Form, Dropdown, + Table, Button, Select, Tag, Space, Input, InputNumber, Tooltip, Popconfirm, theme, Modal, Form, Dropdown, Typography, } from 'antd'; import { message } from '../utils/antdMessage'; import { PlayCircleOutlined, StopOutlined, FilterOutlined, ReloadOutlined, DeleteOutlined, - SettingOutlined, SafetyCertificateOutlined, DownloadOutlined, + SettingOutlined, SafetyCertificateOutlined, DownloadOutlined, ClearOutlined, } from '@ant-design/icons'; import { accountApi, loginApi, type AccountItem, type LoginTaskItem, type TaskSummary } from '../api/modules'; +import type { LoginTaskFilters } from '../api/login'; import RealtimeLogPanel from '../components/RealtimeLogPanel'; import { usePermissions } from '../hooks/usePermissions'; import { useWebSocketLogs } from '../hooks/useWebSocketLogs'; import { formatTime } from '../utils/time'; import { getErrorMessage } from '../utils/error'; +const { Text } = Typography; + const STATUS_COLORS: Record = { pending: 'default', running: 'processing', @@ -40,6 +43,29 @@ const STATUS_LABELS: Record = { account_auth_unknown: '认证状态未知', }; +const ACCOUNT_STATUS_LABELS: Record = { + imported: '未登录', + active: '正常', + invalid: 'CK 失效', + manual: '待人工', + disabled: '已停用', + archived: '已归档', +}; + +const CK_STATUS_LABELS: Record = { + valid: '有效', + invalid: '失效', + error: '检测异常', + '': '未确认', +}; + +const CK_STATUS_COLORS: Record = { + valid: 'green', + invalid: 'red', + error: 'orange', + '': 'default', +}; + type BatchMode = 'login' | 'check'; const ACCOUNT_PAGE_SIZE = 50; @@ -98,6 +124,13 @@ export default function LoginTasksPage() { return v ? Math.max(1, Math.min(500, Number(v) || 50)) : 50; }); const [taskStatus, setTaskStatus] = useState(''); + const [taskSearch, setTaskSearch] = useState(''); + const [taskTag, setTaskTag] = useState(); + const [taskOwnerFilter, setTaskOwnerFilter] = useState(); + const [taskCkStatus, setTaskCkStatus] = useState(); + const [taskAccountStatus, setTaskAccountStatus] = useState(); + const [taskFilterTags, setTaskFilterTags] = useState([]); + const [taskAssignedUsers, setTaskAssignedUsers] = useState<{ id: number; username: string }[]>([]); const [taskTotal, setTaskTotal] = useState(0); // 全局统计走 /tasks/summary:分页后 tasks 只是当前页, // 用它算「成功/失败」会和「共 N 个任务」对不上(曾显示「共 8508,成功 48」)。 @@ -159,6 +192,16 @@ export default function LoginTasksPage() { } }, []); + const loadTaskFilterOptions = useCallback(async () => { + try { + const data = await loginApi.taskFilterOptions(); + setTaskFilterTags(data.tags); + setTaskAssignedUsers(data.assigned_users); + } catch { + // 筛选项加载失败不影响任务列表本身。 + } + }, []); + const loadAllAccountsByTag = useCallback(async (tag: string) => { const items: AccountItem[] = []; for (let page = 1; ; page += 1) { @@ -209,16 +252,38 @@ export default function LoginTasksPage() { } }, [loadAllAccountsByTag, selectedTags]); + const taskFilterParams = useMemo(() => { + const owner = taskOwnerFilter || ''; + return { + batch_id: batchId || undefined, + status: taskStatus || undefined, + search: taskSearch.trim() || undefined, + tag: taskTag || undefined, + assigned_user_id: owner && owner !== 'unassigned' ? Number(owner) : undefined, + assign_status: owner === 'unassigned' ? 'unassigned' : undefined, + ck_status: taskCkStatus || undefined, + account_status: taskAccountStatus || undefined, + }; + }, [batchId, taskStatus, taskSearch, taskTag, taskOwnerFilter, taskCkStatus, taskAccountStatus]); + + const hasTaskFilters = useMemo( + () => Object.values(taskFilterParams).some((value) => value !== undefined && value !== ''), + [taskFilterParams], + ); + const hasVisibleTaskFilters = useMemo( + () => Boolean(taskSearch || taskTag || taskOwnerFilter || taskCkStatus || taskAccountStatus || taskStatus), + [taskSearch, taskTag, taskOwnerFilter, taskCkStatus, taskAccountStatus, taskStatus], + ); + const loadTasks = useCallback(async () => { // 「最新请求获胜」而不是「有请求在跑就丢弃」:轮询请求在途时用户点了翻页, // 旧写法会把这次翻页请求直接吞掉,页面停在上一页直到下次轮询。 const reqId = ++taskRequestRef.current; try { const data = await loginApi.listTasksPaged({ + ...taskFilterParams, page: taskPage, page_size: taskPageSize, - batch_id: batchId || undefined, - status: taskStatus || undefined, }); if (reqId !== taskRequestRef.current) return; // 已有更新的请求,丢弃本次结果 setTasks(data.items); @@ -226,7 +291,7 @@ export default function LoginTasksPage() { } catch { // 忽略轮询失败,下一次定时刷新会继续尝试。 } - }, [batchId, taskPage, taskPageSize, taskStatus]); + }, [taskFilterParams, taskPage, taskPageSize]); const hasActiveTasks = useMemo( () => tasks.some((task) => ['pending', 'running'].includes(task.status)), @@ -256,15 +321,16 @@ export default function LoginTasksPage() { useEffect(() => { void loadTags(); + void loadTaskFilterOptions(); void loadTasks(); - }, [loadTags, loadTasks]); + }, [loadTags, loadTaskFilterOptions, loadTasks]); // 全局统计:随任务刷新一起更新,保证与列表同频。 useEffect(() => { let alive = true; const loadSummary = async () => { try { - const data = await loginApi.tasksSummary(); + const data = await loginApi.tasksSummary(taskFilterParams); if (alive) setTaskSummary(data); } catch { // 统计失败不影响列表使用 @@ -276,7 +342,7 @@ export default function LoginTasksPage() { alive = false; clearInterval(timer); }; - }, [taskTotal]); + }, [taskFilterParams, taskTotal]); useEffect(() => { const timer = window.setTimeout(() => { @@ -376,10 +442,7 @@ export default function LoginTasksPage() { } try { const res = selectedAllMatching - ? await loginApi.deleteTasksMatching({ - batch_id: batchId || undefined, - status: taskStatus || undefined, - }) + ? await loginApi.deleteTasksMatching(taskFilterParams) : await loginApi.deleteTasks(selectedRowKeys); message.success(res.message || `已删除 ${res.deleted} 个任务`); setSelectedRowKeys([]); @@ -399,13 +462,15 @@ export default function LoginTasksPage() { * 导出的是**全部匹配记录**,不是当前页。 */ const handleExport = async (scope: 'current' | 'all' | 'success' | 'failed') => { - const status = - scope === 'current' ? taskStatus : scope === 'all' ? '' : scope; + const params: LoginTaskFilters = + scope === 'all' + ? { batch_id: batchId || undefined, status: '' } + : { + ...taskFilterParams, + status: scope === 'current' ? taskStatus : scope, + }; try { - const blob = await loginApi.exportTasks({ - batch_id: batchId || undefined, - status, - }); + const blob = await loginApi.exportTasks(params); const url = URL.createObjectURL(blob instanceof Blob ? blob : new Blob([blob])); const a = document.createElement('a'); a.href = url; @@ -423,7 +488,7 @@ export default function LoginTasksPage() { const handleClearFailed = async () => { try { const res = await loginApi.deleteTasksMatching({ - batch_id: batchId || undefined, + ...taskFilterParams, status: 'failed', }); message.success(res.message || `已删除 ${res.deleted} 个任务`); @@ -446,6 +511,17 @@ export default function LoginTasksPage() { setSelectedRowKeys([]); }; + const clearTaskFilters = () => { + setTaskSearch(''); + setTaskTag(undefined); + setTaskOwnerFilter(undefined); + setTaskCkStatus(undefined); + setTaskAccountStatus(undefined); + setTaskStatus(''); + setTaskPage(1); + clearSelection(); + }; + const successCount = taskSummary?.success ?? 0; const failedCount = taskSummary?.failed ?? 0; const checkedCount = tasks.filter((t) => [ @@ -494,10 +570,39 @@ export default function LoginTasksPage() { const columns = [ { title: 'ID', dataIndex: 'id', width: 60 }, - { title: '账号', dataIndex: 'account_username' }, + { title: '登录账号', dataIndex: 'account_username' }, { - title: '状态', + title: '标签', + dataIndex: 'account_tag', + width: 110, + render: (tag: string) => tag ? {tag} : -, + }, + { + title: '当前归属客服', + dataIndex: 'assigned_username', + width: 130, + render: (name: string) => name || 未分配, + }, + { + title: 'CK 状态', + dataIndex: 'ck_check_status', + width: 100, + render: (status: string) => ( + + {CK_STATUS_LABELS[status] || status || '未确认'} + + ), + }, + { + title: '账号状态', + dataIndex: 'account_status', + width: 100, + render: (status: string) => ACCOUNT_STATUS_LABELS[status] || status || '-', + }, + { + title: '任务状态', dataIndex: 'status', + width: 100, render: (status: string) => {STATUS_LABELS[status] || status}, }, { title: '消息', dataIndex: 'message', ellipsis: true }, @@ -536,7 +641,7 @@ export default function LoginTasksPage() { )} +
+ { + setTaskSearch(event.target.value); + setTaskPage(1); + clearSelection(); + }} + style={{ width: 180 }} + /> + { + setTaskOwnerFilter(value); + setTaskPage(1); + clearSelection(); + }} + options={[ + { value: 'unassigned', label: '未分配' }, + ...taskAssignedUsers.map((user) => ({ + value: String(user.id), + label: user.username, + })), + ]} + style={{ width: 150 }} + /> + { + setTaskCkStatus(value); + setTaskPage(1); + clearSelection(); + }} + options={[ + { value: 'valid', label: '有效' }, + { value: 'invalid', label: '失效' }, + { value: 'error', label: '检测异常' }, + { value: 'unchecked', label: '未确认' }, + ]} + style={{ width: 125 }} + /> + { setTaskStatus(v); setTaskPage(1); clearSelection(); }} - options={[ - { value: '', label: '全部状态' }, - { value: 'success', label: '成功' }, - { value: 'failed', label: '失败' }, - { value: 'pending', label: '等待中' }, - { value: 'running', label: '进行中' }, - ]} - />