feat(login): 增加登录任务账号信息与筛选
This commit is contained in:
@@ -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
|
||||||
+160
-18
@@ -15,7 +15,7 @@ from fastapi import (
|
|||||||
)
|
)
|
||||||
from fastapi.responses import StreamingResponse
|
from fastapi.responses import StreamingResponse
|
||||||
from sqlalchemy import and_, func, or_
|
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 ..database import SessionLocal, get_db
|
||||||
from ..deps import authenticate_websocket, get_current_user, require_permission
|
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):
|
def _login_task_summary(query):
|
||||||
"""按状态汇总登录任务,避免概览页拉完整任务列表。"""
|
"""按状态汇总登录任务,避免概览页拉完整任务列表。"""
|
||||||
rows = (
|
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]:
|
def _serialize_tasks(db: Session, rows) -> list[LoginTaskOut]:
|
||||||
"""把任务行拼上账号名后序列化。"""
|
"""把任务行拼上当前账号信息后序列化。"""
|
||||||
account_ids = [t.account_id for t in rows]
|
account_ids = [t.account_id for t in rows]
|
||||||
accounts_map = {}
|
accounts_map: dict[int, tuple] = {}
|
||||||
if account_ids:
|
if account_ids:
|
||||||
accs = (
|
for row in (
|
||||||
db.query(Account)
|
db.query(
|
||||||
.options(load_only(Account.id, Account.username))
|
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))
|
.filter(Account.id.in_(account_ids))
|
||||||
.all()
|
.all()
|
||||||
)
|
):
|
||||||
accounts_map = {a.id: a.username for a in accs}
|
accounts_map[int(row[0])] = row
|
||||||
|
|
||||||
result = []
|
result = []
|
||||||
for t in rows:
|
for t in rows:
|
||||||
attempt_status = t.attempt_status or ""
|
attempt_status = t.attempt_status or ""
|
||||||
|
account = accounts_map.get(int(t.account_id))
|
||||||
result.append(
|
result.append(
|
||||||
LoginTaskOut(
|
LoginTaskOut(
|
||||||
id=t.id,
|
id=t.id,
|
||||||
batch_id=t.attempt_batch_id or t.batch_id,
|
batch_id=t.attempt_batch_id or t.batch_id,
|
||||||
account_id=t.account_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,
|
status=attempt_status or t.status,
|
||||||
cookie="",
|
cookie="",
|
||||||
message=(t.attempt_message if attempt_status else "")
|
message=(t.attempt_message if attempt_status else "")
|
||||||
@@ -254,6 +309,12 @@ def list_tasks(
|
|||||||
page: int | None = None,
|
page: int | None = None,
|
||||||
page_size: int = 50,
|
page_size: int = 50,
|
||||||
status: 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),
|
db: Session = Depends(get_db),
|
||||||
current: User = Depends(get_current_user),
|
current: User = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
@@ -265,7 +326,16 @@ def list_tasks(
|
|||||||
传 `page` 时同时返回 `total`,是为了让前端能「全选所有筛选结果」——
|
传 `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())
|
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:
|
def _fmt_dt(value) -> str:
|
||||||
"""导出用的时间格式。
|
"""导出用的时间格式。
|
||||||
|
|
||||||
@@ -299,6 +398,12 @@ def _fmt_dt(value) -> str:
|
|||||||
def export_tasks(
|
def export_tasks(
|
||||||
batch_id: str | None = None,
|
batch_id: str | None = None,
|
||||||
status: 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),
|
db: Session = Depends(get_db),
|
||||||
current: User = Depends(get_current_user),
|
current: User = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
@@ -313,19 +418,28 @@ def export_tasks(
|
|||||||
- 失败分型复用登录失败那套(`login_failure.classify_failure`),
|
- 失败分型复用登录失败那套(`login_failure.classify_failure`),
|
||||||
与账号时间线上写的是同一份判据,不会出现「页面上算 A、导出算 B」。
|
与账号时间线上写的是同一份判据,不会出现「页面上算 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()
|
rows = query.order_by(LoginTask.id.desc()).all()
|
||||||
|
|
||||||
account_ids = [t.account_id for t in rows]
|
account_ids = [t.account_id for t in rows]
|
||||||
info: dict[int, tuple[str, str, str]] = {}
|
info: dict[int, tuple[str, str, str]] = {}
|
||||||
if account_ids:
|
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)
|
db.query(Account.id, Account.username, Account.tag, User.username)
|
||||||
.outerjoin(User, Account.assigned_to == User.id)
|
.outerjoin(User, Account.assigned_to == User.id)
|
||||||
.filter(Account.id.in_(account_ids))
|
.filter(Account.id.in_(account_ids))
|
||||||
.all()
|
.all()
|
||||||
):
|
):
|
||||||
info[acc_id] = (username or "", tag or "", owner or "")
|
info[acc_id] = (username or "", account_tag or "", owner or "")
|
||||||
|
|
||||||
output = io.StringIO()
|
output = io.StringIO()
|
||||||
writer = csv.writer(output)
|
writer = csv.writer(output)
|
||||||
@@ -380,13 +494,28 @@ def export_tasks(
|
|||||||
|
|
||||||
@router.get("/tasks/summary")
|
@router.get("/tasks/summary")
|
||||||
def 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),
|
db: Session = Depends(get_db),
|
||||||
current: User = Depends(get_current_user),
|
current: User = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
"""登录任务统计。"""
|
"""登录任务统计。"""
|
||||||
query = db.query(LoginTask).join(Account, LoginTask.account_id == Account.id)
|
query = _apply_login_task_filters(
|
||||||
if not user_has_permission(current, "login:view_all"):
|
_visible_tasks_query(db, current, batch_id),
|
||||||
query = query.filter(Account.assigned_to == current.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)
|
return _login_task_summary(query)
|
||||||
|
|
||||||
|
|
||||||
@@ -445,6 +574,12 @@ def delete_tasks(
|
|||||||
task_ids: str = "",
|
task_ids: str = "",
|
||||||
batch_id: str | None = None,
|
batch_id: str | None = None,
|
||||||
status: 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,
|
all_matching: bool = False,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current: User = Depends(require_permission("login:batch")),
|
current: User = Depends(require_permission("login:batch")),
|
||||||
@@ -474,8 +609,15 @@ def delete_tasks(
|
|||||||
# 所以先按权限与筛选条件查出 id,再按主键删。
|
# 所以先按权限与筛选条件查出 id,再按主键删。
|
||||||
# 状态筛选与列表/导出共用一份 —— 「清空失败」以前只删 `failed`、
|
# 状态筛选与列表/导出共用一份 —— 「清空失败」以前只删 `failed`、
|
||||||
# 漏掉 `error`,删完与页面上那个「失败 N」的数还对不上。
|
# 漏掉 `error`,删完与页面上那个「失败 N」的数还对不上。
|
||||||
query = _apply_status_filter(
|
query = _apply_login_task_filters(
|
||||||
_visible_tasks_query(db, current, batch_id), status
|
_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()]
|
ids = [row[0] for row in query.with_entities(LoginTask.id).all()]
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -383,6 +383,13 @@ class LoginTaskOut(BaseModel):
|
|||||||
batch_id: str
|
batch_id: str
|
||||||
account_id: int
|
account_id: int
|
||||||
account_username: str = ""
|
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
|
status: str
|
||||||
cookie: str = ""
|
cookie: str = ""
|
||||||
message: str = ""
|
message: str = ""
|
||||||
@@ -399,6 +406,13 @@ class LoginTaskOut(BaseModel):
|
|||||||
"batch_id": self.batch_id,
|
"batch_id": self.batch_id,
|
||||||
"account_id": self.account_id,
|
"account_id": self.account_id,
|
||||||
"account_username": self.account_username,
|
"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,
|
"status": self.status,
|
||||||
"cookie": self.cookie,
|
"cookie": self.cookie,
|
||||||
"message": self.message,
|
"message": self.message,
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import api from './client';
|
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 {
|
interface CreateBatchParams {
|
||||||
account_ids: number[];
|
account_ids: number[];
|
||||||
@@ -17,35 +20,57 @@ export interface TaskPage {
|
|||||||
page_size: number;
|
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 = {
|
export const loginApi = {
|
||||||
createBatch: (params: CreateBatchParams) =>
|
createBatch: (params: CreateBatchParams) =>
|
||||||
api.post<BatchLoginResult, BatchLoginResult>('/login/batch', params),
|
api.post<BatchLoginResult, BatchLoginResult>('/login/batch', params),
|
||||||
// 不传 page 时后端返回裸数组(老调用方契约),传了才返回 {items,total}。
|
// 不传 page 时后端返回裸数组(老调用方契约),传了才返回 {items,total}。
|
||||||
listTasks: (batch_id?: string) =>
|
listTasks: (batch_id?: string) =>
|
||||||
api.get<LoginTaskItem[], LoginTaskItem[]>('/login/tasks', { params: batch_id ? { batch_id } : {} }),
|
api.get<LoginTaskItem[], LoginTaskItem[]>('/login/tasks', { params: batch_id ? { batch_id } : {} }),
|
||||||
listTasksPaged: (params: { page: number; page_size: number; batch_id?: string; status?: string }) =>
|
listTasksPaged: (params: LoginTaskFilters & { page: number; page_size: number }) =>
|
||||||
api.get<TaskPage, TaskPage>('/login/tasks', { params: { ...params, batch_id: params.batch_id ?? '' } }),
|
api.get<TaskPage, TaskPage>('/login/tasks', { params: { ...params, ...filterParams(params) } }),
|
||||||
tasksSummary: () => api.get<TaskSummary, TaskSummary>('/login/tasks/summary'),
|
taskFilterOptions: () =>
|
||||||
|
api.get<LoginTaskFilterOptions, LoginTaskFilterOptions>('/login/tasks/filters'),
|
||||||
|
tasksSummary: (params: LoginTaskFilters = {}) =>
|
||||||
|
api.get<TaskSummary, TaskSummary>('/login/tasks/summary', { params: filterParams(params) }),
|
||||||
/**
|
/**
|
||||||
* 导出登录任务 CSV(按当前筛选,不分页)。
|
* 导出登录任务 CSV(按当前筛选,不分页)。
|
||||||
*
|
*
|
||||||
* `status` 传 'failed' 时后端会展开成 failed + error —— 页面上「失败」
|
* `status` 传 'failed' 时后端会展开成 failed + error —— 页面上「失败」
|
||||||
* 本来就是一个组,导出与列表口径必须一致。
|
* 本来就是一个组,导出与列表口径必须一致。
|
||||||
*/
|
*/
|
||||||
exportTasks: (params: { batch_id?: string; status?: string }) =>
|
exportTasks: (params: LoginTaskFilters) =>
|
||||||
api.get<Blob, Blob>('/login/tasks/export', {
|
api.get<Blob, Blob>('/login/tasks/export', {
|
||||||
responseType: 'blob',
|
responseType: 'blob',
|
||||||
params: {
|
params: filterParams(params),
|
||||||
batch_id: params.batch_id ?? '',
|
|
||||||
status: params.status ?? '',
|
|
||||||
},
|
|
||||||
}),
|
}),
|
||||||
stop: (batch_id: string) => api.post<MessageResponse, MessageResponse>(`/login/stop/${batch_id}`),
|
stop: (batch_id: string) => api.post<MessageResponse, MessageResponse>(`/login/stop/${batch_id}`),
|
||||||
deleteTask: (id: number) => api.delete<MessageResponse, MessageResponse>(`/login/tasks/${id}`),
|
deleteTask: (id: number) => api.delete<MessageResponse, MessageResponse>(`/login/tasks/${id}`),
|
||||||
deleteTasks: (ids: number[]) => api.delete<MessageDeletedResponse, MessageDeletedResponse>(`/login/tasks`, { params: { task_ids: ids.join(',') } }),
|
deleteTasks: (ids: number[]) => api.delete<MessageDeletedResponse, MessageDeletedResponse>(`/login/tasks`, { params: { task_ids: ids.join(',') } }),
|
||||||
// 跨页全选用:按当前筛选条件删除全部(后端会跳过在途任务)。
|
// 跨页全选用:按当前筛选条件删除全部(后端会跳过在途任务)。
|
||||||
deleteTasksMatching: (params: { batch_id?: string; status?: string }) =>
|
deleteTasksMatching: (params: LoginTaskFilters) =>
|
||||||
api.delete<MessageDeletedResponse, MessageDeletedResponse>('/login/tasks', {
|
api.delete<MessageDeletedResponse, MessageDeletedResponse>('/login/tasks', {
|
||||||
params: { all_matching: true, batch_id: params.batch_id ?? '', status: params.status ?? '' },
|
params: { all_matching: true, ...filterParams(params) },
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -469,6 +469,13 @@ export interface LoginTaskItem {
|
|||||||
batch_id: string;
|
batch_id: string;
|
||||||
account_id: number;
|
account_id: number;
|
||||||
account_username: string;
|
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;
|
status: string;
|
||||||
cookie: string;
|
cookie: string;
|
||||||
message: string;
|
message: string;
|
||||||
@@ -477,6 +484,11 @@ export interface LoginTaskItem {
|
|||||||
finished_at: string | null;
|
finished_at: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface LoginTaskFilterOptions {
|
||||||
|
tags: string[];
|
||||||
|
assigned_users: { id: number; username: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface YybTask {
|
export interface YybTask {
|
||||||
id: number;
|
id: number;
|
||||||
task_id: string;
|
task_id: string;
|
||||||
|
|||||||
@@ -1,19 +1,22 @@
|
|||||||
import { useEffect, useState, useMemo, useCallback, useRef } from 'react';
|
import { useEffect, useState, useMemo, useCallback, useRef } from 'react';
|
||||||
import {
|
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';
|
} from 'antd';
|
||||||
import { message } from '../utils/antdMessage';
|
import { message } from '../utils/antdMessage';
|
||||||
import {
|
import {
|
||||||
PlayCircleOutlined, StopOutlined, FilterOutlined, ReloadOutlined, DeleteOutlined,
|
PlayCircleOutlined, StopOutlined, FilterOutlined, ReloadOutlined, DeleteOutlined,
|
||||||
SettingOutlined, SafetyCertificateOutlined, DownloadOutlined,
|
SettingOutlined, SafetyCertificateOutlined, DownloadOutlined, ClearOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { accountApi, loginApi, type AccountItem, type LoginTaskItem, type TaskSummary } from '../api/modules';
|
import { accountApi, loginApi, type AccountItem, type LoginTaskItem, type TaskSummary } from '../api/modules';
|
||||||
|
import type { LoginTaskFilters } from '../api/login';
|
||||||
import RealtimeLogPanel from '../components/RealtimeLogPanel';
|
import RealtimeLogPanel from '../components/RealtimeLogPanel';
|
||||||
import { usePermissions } from '../hooks/usePermissions';
|
import { usePermissions } from '../hooks/usePermissions';
|
||||||
import { useWebSocketLogs } from '../hooks/useWebSocketLogs';
|
import { useWebSocketLogs } from '../hooks/useWebSocketLogs';
|
||||||
import { formatTime } from '../utils/time';
|
import { formatTime } from '../utils/time';
|
||||||
import { getErrorMessage } from '../utils/error';
|
import { getErrorMessage } from '../utils/error';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
const STATUS_COLORS: Record<string, string> = {
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
pending: 'default',
|
pending: 'default',
|
||||||
running: 'processing',
|
running: 'processing',
|
||||||
@@ -40,6 +43,29 @@ const STATUS_LABELS: Record<string, string> = {
|
|||||||
account_auth_unknown: '认证状态未知',
|
account_auth_unknown: '认证状态未知',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const ACCOUNT_STATUS_LABELS: Record<string, string> = {
|
||||||
|
imported: '未登录',
|
||||||
|
active: '正常',
|
||||||
|
invalid: 'CK 失效',
|
||||||
|
manual: '待人工',
|
||||||
|
disabled: '已停用',
|
||||||
|
archived: '已归档',
|
||||||
|
};
|
||||||
|
|
||||||
|
const CK_STATUS_LABELS: Record<string, string> = {
|
||||||
|
valid: '有效',
|
||||||
|
invalid: '失效',
|
||||||
|
error: '检测异常',
|
||||||
|
'': '未确认',
|
||||||
|
};
|
||||||
|
|
||||||
|
const CK_STATUS_COLORS: Record<string, string> = {
|
||||||
|
valid: 'green',
|
||||||
|
invalid: 'red',
|
||||||
|
error: 'orange',
|
||||||
|
'': 'default',
|
||||||
|
};
|
||||||
|
|
||||||
type BatchMode = 'login' | 'check';
|
type BatchMode = 'login' | 'check';
|
||||||
const ACCOUNT_PAGE_SIZE = 50;
|
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;
|
return v ? Math.max(1, Math.min(500, Number(v) || 50)) : 50;
|
||||||
});
|
});
|
||||||
const [taskStatus, setTaskStatus] = useState<string>('');
|
const [taskStatus, setTaskStatus] = useState<string>('');
|
||||||
|
const [taskSearch, setTaskSearch] = useState('');
|
||||||
|
const [taskTag, setTaskTag] = useState<string | undefined>();
|
||||||
|
const [taskOwnerFilter, setTaskOwnerFilter] = useState<string | undefined>();
|
||||||
|
const [taskCkStatus, setTaskCkStatus] = useState<string | undefined>();
|
||||||
|
const [taskAccountStatus, setTaskAccountStatus] = useState<string | undefined>();
|
||||||
|
const [taskFilterTags, setTaskFilterTags] = useState<string[]>([]);
|
||||||
|
const [taskAssignedUsers, setTaskAssignedUsers] = useState<{ id: number; username: string }[]>([]);
|
||||||
const [taskTotal, setTaskTotal] = useState(0);
|
const [taskTotal, setTaskTotal] = useState(0);
|
||||||
// 全局统计走 /tasks/summary:分页后 tasks 只是当前页,
|
// 全局统计走 /tasks/summary:分页后 tasks 只是当前页,
|
||||||
// 用它算「成功/失败」会和「共 N 个任务」对不上(曾显示「共 8508,成功 48」)。
|
// 用它算「成功/失败」会和「共 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 loadAllAccountsByTag = useCallback(async (tag: string) => {
|
||||||
const items: AccountItem[] = [];
|
const items: AccountItem[] = [];
|
||||||
for (let page = 1; ; page += 1) {
|
for (let page = 1; ; page += 1) {
|
||||||
@@ -209,16 +252,38 @@ export default function LoginTasksPage() {
|
|||||||
}
|
}
|
||||||
}, [loadAllAccountsByTag, selectedTags]);
|
}, [loadAllAccountsByTag, selectedTags]);
|
||||||
|
|
||||||
|
const taskFilterParams = useMemo<LoginTaskFilters>(() => {
|
||||||
|
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 loadTasks = useCallback(async () => {
|
||||||
// 「最新请求获胜」而不是「有请求在跑就丢弃」:轮询请求在途时用户点了翻页,
|
// 「最新请求获胜」而不是「有请求在跑就丢弃」:轮询请求在途时用户点了翻页,
|
||||||
// 旧写法会把这次翻页请求直接吞掉,页面停在上一页直到下次轮询。
|
// 旧写法会把这次翻页请求直接吞掉,页面停在上一页直到下次轮询。
|
||||||
const reqId = ++taskRequestRef.current;
|
const reqId = ++taskRequestRef.current;
|
||||||
try {
|
try {
|
||||||
const data = await loginApi.listTasksPaged({
|
const data = await loginApi.listTasksPaged({
|
||||||
|
...taskFilterParams,
|
||||||
page: taskPage,
|
page: taskPage,
|
||||||
page_size: taskPageSize,
|
page_size: taskPageSize,
|
||||||
batch_id: batchId || undefined,
|
|
||||||
status: taskStatus || undefined,
|
|
||||||
});
|
});
|
||||||
if (reqId !== taskRequestRef.current) return; // 已有更新的请求,丢弃本次结果
|
if (reqId !== taskRequestRef.current) return; // 已有更新的请求,丢弃本次结果
|
||||||
setTasks(data.items);
|
setTasks(data.items);
|
||||||
@@ -226,7 +291,7 @@ export default function LoginTasksPage() {
|
|||||||
} catch {
|
} catch {
|
||||||
// 忽略轮询失败,下一次定时刷新会继续尝试。
|
// 忽略轮询失败,下一次定时刷新会继续尝试。
|
||||||
}
|
}
|
||||||
}, [batchId, taskPage, taskPageSize, taskStatus]);
|
}, [taskFilterParams, taskPage, taskPageSize]);
|
||||||
|
|
||||||
const hasActiveTasks = useMemo(
|
const hasActiveTasks = useMemo(
|
||||||
() => tasks.some((task) => ['pending', 'running'].includes(task.status)),
|
() => tasks.some((task) => ['pending', 'running'].includes(task.status)),
|
||||||
@@ -256,15 +321,16 @@ export default function LoginTasksPage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void loadTags();
|
void loadTags();
|
||||||
|
void loadTaskFilterOptions();
|
||||||
void loadTasks();
|
void loadTasks();
|
||||||
}, [loadTags, loadTasks]);
|
}, [loadTags, loadTaskFilterOptions, loadTasks]);
|
||||||
|
|
||||||
// 全局统计:随任务刷新一起更新,保证与列表同频。
|
// 全局统计:随任务刷新一起更新,保证与列表同频。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let alive = true;
|
let alive = true;
|
||||||
const loadSummary = async () => {
|
const loadSummary = async () => {
|
||||||
try {
|
try {
|
||||||
const data = await loginApi.tasksSummary();
|
const data = await loginApi.tasksSummary(taskFilterParams);
|
||||||
if (alive) setTaskSummary(data);
|
if (alive) setTaskSummary(data);
|
||||||
} catch {
|
} catch {
|
||||||
// 统计失败不影响列表使用
|
// 统计失败不影响列表使用
|
||||||
@@ -276,7 +342,7 @@ export default function LoginTasksPage() {
|
|||||||
alive = false;
|
alive = false;
|
||||||
clearInterval(timer);
|
clearInterval(timer);
|
||||||
};
|
};
|
||||||
}, [taskTotal]);
|
}, [taskFilterParams, taskTotal]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = window.setTimeout(() => {
|
const timer = window.setTimeout(() => {
|
||||||
@@ -376,10 +442,7 @@ export default function LoginTasksPage() {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const res = selectedAllMatching
|
const res = selectedAllMatching
|
||||||
? await loginApi.deleteTasksMatching({
|
? await loginApi.deleteTasksMatching(taskFilterParams)
|
||||||
batch_id: batchId || undefined,
|
|
||||||
status: taskStatus || undefined,
|
|
||||||
})
|
|
||||||
: await loginApi.deleteTasks(selectedRowKeys);
|
: await loginApi.deleteTasks(selectedRowKeys);
|
||||||
message.success(res.message || `已删除 ${res.deleted} 个任务`);
|
message.success(res.message || `已删除 ${res.deleted} 个任务`);
|
||||||
setSelectedRowKeys([]);
|
setSelectedRowKeys([]);
|
||||||
@@ -399,13 +462,15 @@ export default function LoginTasksPage() {
|
|||||||
* 导出的是**全部匹配记录**,不是当前页。
|
* 导出的是**全部匹配记录**,不是当前页。
|
||||||
*/
|
*/
|
||||||
const handleExport = async (scope: 'current' | 'all' | 'success' | 'failed') => {
|
const handleExport = async (scope: 'current' | 'all' | 'success' | 'failed') => {
|
||||||
const status =
|
const params: LoginTaskFilters =
|
||||||
scope === 'current' ? taskStatus : scope === 'all' ? '' : scope;
|
scope === 'all'
|
||||||
|
? { batch_id: batchId || undefined, status: '' }
|
||||||
|
: {
|
||||||
|
...taskFilterParams,
|
||||||
|
status: scope === 'current' ? taskStatus : scope,
|
||||||
|
};
|
||||||
try {
|
try {
|
||||||
const blob = await loginApi.exportTasks({
|
const blob = await loginApi.exportTasks(params);
|
||||||
batch_id: batchId || undefined,
|
|
||||||
status,
|
|
||||||
});
|
|
||||||
const url = URL.createObjectURL(blob instanceof Blob ? blob : new Blob([blob]));
|
const url = URL.createObjectURL(blob instanceof Blob ? blob : new Blob([blob]));
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = url;
|
a.href = url;
|
||||||
@@ -423,7 +488,7 @@ export default function LoginTasksPage() {
|
|||||||
const handleClearFailed = async () => {
|
const handleClearFailed = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await loginApi.deleteTasksMatching({
|
const res = await loginApi.deleteTasksMatching({
|
||||||
batch_id: batchId || undefined,
|
...taskFilterParams,
|
||||||
status: 'failed',
|
status: 'failed',
|
||||||
});
|
});
|
||||||
message.success(res.message || `已删除 ${res.deleted} 个任务`);
|
message.success(res.message || `已删除 ${res.deleted} 个任务`);
|
||||||
@@ -446,6 +511,17 @@ export default function LoginTasksPage() {
|
|||||||
setSelectedRowKeys([]);
|
setSelectedRowKeys([]);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const clearTaskFilters = () => {
|
||||||
|
setTaskSearch('');
|
||||||
|
setTaskTag(undefined);
|
||||||
|
setTaskOwnerFilter(undefined);
|
||||||
|
setTaskCkStatus(undefined);
|
||||||
|
setTaskAccountStatus(undefined);
|
||||||
|
setTaskStatus('');
|
||||||
|
setTaskPage(1);
|
||||||
|
clearSelection();
|
||||||
|
};
|
||||||
|
|
||||||
const successCount = taskSummary?.success ?? 0;
|
const successCount = taskSummary?.success ?? 0;
|
||||||
const failedCount = taskSummary?.failed ?? 0;
|
const failedCount = taskSummary?.failed ?? 0;
|
||||||
const checkedCount = tasks.filter((t) => [
|
const checkedCount = tasks.filter((t) => [
|
||||||
@@ -494,10 +570,39 @@ export default function LoginTasksPage() {
|
|||||||
|
|
||||||
const columns = [
|
const columns = [
|
||||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
{ 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 color="blue">{tag}</Tag> : <Text type="secondary">-</Text>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '当前归属客服',
|
||||||
|
dataIndex: 'assigned_username',
|
||||||
|
width: 130,
|
||||||
|
render: (name: string) => name || <Text type="secondary">未分配</Text>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'CK 状态',
|
||||||
|
dataIndex: 'ck_check_status',
|
||||||
|
width: 100,
|
||||||
|
render: (status: string) => (
|
||||||
|
<Tag color={CK_STATUS_COLORS[status] || 'default'}>
|
||||||
|
{CK_STATUS_LABELS[status] || status || '未确认'}
|
||||||
|
</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '账号状态',
|
||||||
|
dataIndex: 'account_status',
|
||||||
|
width: 100,
|
||||||
|
render: (status: string) => ACCOUNT_STATUS_LABELS[status] || status || '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '任务状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
|
width: 100,
|
||||||
render: (status: string) => <Tag color={STATUS_COLORS[status]}>{STATUS_LABELS[status] || status}</Tag>,
|
render: (status: string) => <Tag color={STATUS_COLORS[status]}>{STATUS_LABELS[status] || status}</Tag>,
|
||||||
},
|
},
|
||||||
{ title: '消息', dataIndex: 'message', ellipsis: true },
|
{ title: '消息', dataIndex: 'message', ellipsis: true },
|
||||||
@@ -536,7 +641,7 @@ export default function LoginTasksPage() {
|
|||||||
<Select
|
<Select
|
||||||
mode="multiple"
|
mode="multiple"
|
||||||
style={{ minWidth: 200, maxWidth: 300 }}
|
style={{ minWidth: 200, maxWidth: 300 }}
|
||||||
placeholder="按标签筛选"
|
placeholder="登录选号标签"
|
||||||
value={selectedTags}
|
value={selectedTags}
|
||||||
onChange={handleTagChange}
|
onChange={handleTagChange}
|
||||||
options={allTags.map((t) => ({ value: t, label: t }))}
|
options={allTags.map((t) => ({ value: t, label: t }))}
|
||||||
@@ -549,7 +654,7 @@ export default function LoginTasksPage() {
|
|||||||
<Select
|
<Select
|
||||||
mode="multiple"
|
mode="multiple"
|
||||||
style={{ minWidth: 280, flex: 1, maxWidth: 500 }}
|
style={{ minWidth: 280, flex: 1, maxWidth: 500 }}
|
||||||
placeholder="选择账号"
|
placeholder="选择要登录的账号"
|
||||||
value={selectedIds}
|
value={selectedIds}
|
||||||
onChange={setSelectedIds}
|
onChange={setSelectedIds}
|
||||||
options={accountSelectOptions}
|
options={accountSelectOptions}
|
||||||
@@ -652,6 +757,116 @@ export default function LoginTasksPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 8 }}>
|
||||||
|
<Input.Search
|
||||||
|
allowClear
|
||||||
|
size="small"
|
||||||
|
placeholder="搜索登录账号"
|
||||||
|
value={taskSearch}
|
||||||
|
onChange={(event) => {
|
||||||
|
setTaskSearch(event.target.value);
|
||||||
|
setTaskPage(1);
|
||||||
|
clearSelection();
|
||||||
|
}}
|
||||||
|
style={{ width: 180 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
showSearch
|
||||||
|
size="small"
|
||||||
|
placeholder="标签"
|
||||||
|
value={taskTag}
|
||||||
|
onChange={(value) => {
|
||||||
|
setTaskTag(value);
|
||||||
|
setTaskPage(1);
|
||||||
|
clearSelection();
|
||||||
|
}}
|
||||||
|
options={taskFilterTags.map((item) => ({ value: item, label: item }))}
|
||||||
|
style={{ width: 140 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
showSearch
|
||||||
|
size="small"
|
||||||
|
placeholder="当前归属客服"
|
||||||
|
value={taskOwnerFilter}
|
||||||
|
onChange={(value) => {
|
||||||
|
setTaskOwnerFilter(value);
|
||||||
|
setTaskPage(1);
|
||||||
|
clearSelection();
|
||||||
|
}}
|
||||||
|
options={[
|
||||||
|
{ value: 'unassigned', label: '未分配' },
|
||||||
|
...taskAssignedUsers.map((user) => ({
|
||||||
|
value: String(user.id),
|
||||||
|
label: user.username,
|
||||||
|
})),
|
||||||
|
]}
|
||||||
|
style={{ width: 150 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
size="small"
|
||||||
|
placeholder="任务状态"
|
||||||
|
value={taskStatus || undefined}
|
||||||
|
onChange={(value) => {
|
||||||
|
setTaskStatus(value || '');
|
||||||
|
setTaskPage(1);
|
||||||
|
clearSelection();
|
||||||
|
}}
|
||||||
|
options={[
|
||||||
|
{ value: 'success', label: '成功' },
|
||||||
|
{ value: 'failed', label: '失败' },
|
||||||
|
{ value: 'pending', label: '等待中' },
|
||||||
|
{ value: 'running', label: '进行中' },
|
||||||
|
{ value: 'stopped', label: '已停止' },
|
||||||
|
]}
|
||||||
|
style={{ width: 125 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
size="small"
|
||||||
|
placeholder="CK 状态"
|
||||||
|
value={taskCkStatus}
|
||||||
|
onChange={(value) => {
|
||||||
|
setTaskCkStatus(value);
|
||||||
|
setTaskPage(1);
|
||||||
|
clearSelection();
|
||||||
|
}}
|
||||||
|
options={[
|
||||||
|
{ value: 'valid', label: '有效' },
|
||||||
|
{ value: 'invalid', label: '失效' },
|
||||||
|
{ value: 'error', label: '检测异常' },
|
||||||
|
{ value: 'unchecked', label: '未确认' },
|
||||||
|
]}
|
||||||
|
style={{ width: 125 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
size="small"
|
||||||
|
placeholder="账号状态"
|
||||||
|
value={taskAccountStatus}
|
||||||
|
onChange={(value) => {
|
||||||
|
setTaskAccountStatus(value);
|
||||||
|
setTaskPage(1);
|
||||||
|
clearSelection();
|
||||||
|
}}
|
||||||
|
options={Object.entries(ACCOUNT_STATUS_LABELS).map(([value, label]) => ({
|
||||||
|
value,
|
||||||
|
label,
|
||||||
|
}))}
|
||||||
|
style={{ width: 125 }}
|
||||||
|
/>
|
||||||
|
{hasVisibleTaskFilters && (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<ClearOutlined />}
|
||||||
|
onClick={clearTaskFilters}
|
||||||
|
>
|
||||||
|
清除筛选
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 概览 + 任务列表区域 */}
|
{/* 概览 + 任务列表区域 */}
|
||||||
@@ -661,22 +876,9 @@ export default function LoginTasksPage() {
|
|||||||
<span>共 <b>{taskTotal}</b> 个任务</span>
|
<span>共 <b>{taskTotal}</b> 个任务</span>
|
||||||
<span>成功 <b style={{ color: token.colorSuccess }}>{successCount}</b></span>
|
<span>成功 <b style={{ color: token.colorSuccess }}>{successCount}</b></span>
|
||||||
<span>失败 <b style={{ color: token.colorError }}>{failedCount}</b></span>
|
<span>失败 <b style={{ color: token.colorError }}>{failedCount}</b></span>
|
||||||
{taskStatus && <span>(筛选后 {taskTotal} 条)</span>}
|
{hasTaskFilters && <span>(筛选后 {taskTotal} 条)</span>}
|
||||||
{checkedCount > 0 && <span>本页检测 <b>{checkedCount}</b></span>}
|
{checkedCount > 0 && <span>本页检测 <b>{checkedCount}</b></span>}
|
||||||
{effectiveBatchId && <span>批次: <b>{effectiveBatchId}</b></span>}
|
{effectiveBatchId && <span>批次: <b>{effectiveBatchId}</b></span>}
|
||||||
<Select
|
|
||||||
size="small"
|
|
||||||
style={{ width: 130 }}
|
|
||||||
value={taskStatus}
|
|
||||||
onChange={(v) => { setTaskStatus(v); setTaskPage(1); clearSelection(); }}
|
|
||||||
options={[
|
|
||||||
{ value: '', label: '全部状态' },
|
|
||||||
{ value: 'success', label: '成功' },
|
|
||||||
{ value: 'failed', label: '失败' },
|
|
||||||
{ value: 'pending', label: '等待中' },
|
|
||||||
{ value: 'running', label: '进行中' },
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
<Dropdown
|
<Dropdown
|
||||||
menu={{
|
menu={{
|
||||||
items: [
|
items: [
|
||||||
|
|||||||
Reference in New Issue
Block a user