feat(login-tasks): 按状态导出 CSV + 登录失败写进账号生命周期

一、失败入账号一生(此前完全缺失)
生产实测:`login_ok` 1,456 条、`relogin_failed` 73 条,但**没有 login_failed**,
而 login_tasks 里 attempt_status='failed' 有 247 条 —— 这 247 次失败在账号时间线上
一条痕迹都没有,「这账号为什么一直登录不上」在账号页上无从回答。

- 新增事件类型 login_failed,在 `_mark_attempt_failed` 里写入
- **被停止 / 被中断不写**:分型把「已停止/中断/服务重启」归到 interrupted,
  那不是账号的问题 —— 否则运营按一次停止就能给几十个账号刷满假失败
- 事件带分型(captcha/credential/email_code/email_quota/network),
  同时落进 detail.kind,以后可直接按「验证码失败」筛账号
- 幂等键 login_task:{id}:failed:{ts},与成功路径同构

二、失败分型下沉成共用 service
`classify_failure` 原在 automation/jobs/ck_relogin.py,手动登录也要用。
挪到 services/login_failure.py(job 改为 import,`ck_relogin.classify_failure`
这个名字保留,旧调用方与用例不受影响),并提供型别中文标签与
`is_account_fault` 判据 —— 与仓库既有的「service 不该依赖 job」分层一致。

三、按状态导出 CSV
- 新增 GET /api/login/tasks/export:不分页,导出当前筛选的**全部**匹配记录;
  列:账号/状态/失败原因/失败分型/批次/最近尝试时间(UTC)/标签/归属客服
- 权限与筛选与列表**完全共用**,客服只导出自己名下账号
- 带 UTF-8 BOM(不加 Excel 打开中文表头是乱码),导出动作写审计

四、修一个口径不一致的真 bug
页面「失败 N」= failed + error 之和,但筛选只认 failed ——
所以截图里「失败 389」点进去只有 386 条(差的就是那几条 error);
「清空失败」同样漏删 error。现在把状态组收敛成一份 `_apply_status_filter`,
列表 / 导出 / 批量删除三处共用。

测试:684 passed, 6 skipped(本次新增 13 个);三条关键断言做了反向验证
(去掉 stopped 判断 / 失败组去掉 error / 去掉 BOM,对应用例均变红)。
This commit is contained in:
yml2213
2026-10-07 12:54:57 +08:00
parent 281769b440
commit d11fa1032d
8 changed files with 598 additions and 49 deletions
+152 -22
View File
@@ -1,7 +1,10 @@
"""登录任务路由 + WebSocket 实时日志"""
import asyncio
import csv
import io
import threading
from datetime import UTC, datetime
from fastapi import (
APIRouter,
@@ -10,6 +13,7 @@ from fastapi import (
WebSocket,
WebSocketDisconnect,
)
from fastapi.responses import StreamingResponse
from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session, load_only
@@ -20,6 +24,7 @@ from ..models import ProxyConfig as ProxyConfigModel
from ..permissions import get_user_permissions, user_has_permission
from ..schemas import LoginBatchRequest, LoginTaskOut
from ..services.audit_service import record_audit
from ..services.login_failure import classify_failure, failure_kind_label
from ..services.login_service import LoginBatchRunner, batch_registry
router = APIRouter(prefix="/api/login", tags=["登录任务"])
@@ -37,6 +42,53 @@ def _effective_attempt_status():
)
#: 页面上「失败」是一个**组**:库里 `failed` 与 `error` 分两列存,但用户眼里都是失败。
#: 汇总口径早就是两者相加(见 `_login_task_summary`),筛选却只认 `failed` ——
#: 于是「失败 389」点进去只剩 386 条(差的就是那几条 `error`)。
#: 这里统一成组,列表 / 导出 / 批量删除共用一份,避免三处各写一遍再漂移。
STATUS_GROUPS: dict[str, tuple[str, ...]] = {
"failed": ("failed", "error"),
}
#: 导出 CSV 用的中文状态。与前端 `LoginTasksPage.STATUS_LABELS` 同源同义;
#: 后端要自己出一份是因为 CSV 在服务端生成,拿不到前端的表。
LOGIN_STATUS_LABELS: dict[str, str] = {
"pending": "等待中",
"running": "登录中",
"success": "成功",
"failed": "失败",
"error": "异常",
"stopped": "已停止",
"account_cancelled": "账号已注销",
"password_wrong": "账号密码错误",
"account_unverified": "账号未认证",
"account_verified": "账号已认证",
"account_auth_unknown": "认证状态未知",
}
def _status_values(status: str) -> tuple[str, ...]:
"""把页面上的状态名展开成库里真正的取值集合。"""
return STATUS_GROUPS.get(status, (status,))
def _apply_status_filter(query, status: str | None):
"""按「最近一次尝试的状态」筛选(与列表序列化口径一致)。
优先看 `attempt_status`,为空时回退到 `status` —— 两者分开是刻意的:
`status` 只表示这条记录是否持有可用 CK(见 `_effective_attempt_status`)。
"""
if not status:
return query
wanted = _status_values(status)
return query.filter(
or_(
and_(LoginTask.attempt_status != "", LoginTask.attempt_status.in_(wanted)),
and_(LoginTask.attempt_status == "", LoginTask.status.in_(wanted)),
)
)
def _login_task_summary(query):
"""按状态汇总登录任务,避免概览页拉完整任务列表。"""
rows = (
@@ -213,17 +265,7 @@ def list_tasks(
传 `page` 时同时返回 `total`,是为了让前端能「全选所有筛选结果」——
否则跨页选择无从下手,而任务量早就过了单页能装下的规模。
"""
query = _visible_tasks_query(db, current, batch_id)
if status:
# 前端看到的是「最近一次尝试」的状态,与列表序列化口径保持一致。
query = query.filter(
or_(
and_(
LoginTask.attempt_status != "", LoginTask.attempt_status == status
),
and_(LoginTask.attempt_status == "", LoginTask.status == status),
)
)
query = _apply_status_filter(_visible_tasks_query(db, current, batch_id), status)
ordered = query.order_by(LoginTask.id.desc())
@@ -242,6 +284,100 @@ def list_tasks(
}
def _fmt_dt(value) -> str:
"""导出用的时间格式。
统一输出 **UTC**,并在表头写明 —— 服务端猜本地时区迟早会错,
而错的时间在人工筛选时是看不出来的。
"""
if value is None:
return ""
return value.strftime("%Y-%m-%d %H:%M:%S")
@router.get("/tasks/export")
def export_tasks(
batch_id: str | None = None,
status: str | None = None,
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""按当前筛选导出登录任务 CSV(账号名 / 状态 / 失败原因 / 分型 / 批次 / 时间 / 标签 / 归属客服)。
几个刻意的选择:
- **不分页**:导出的用途就是「拿去 Excel 人工筛」,只给一页没有意义;
- **筛选与权限跟列表完全共用**(`_visible_tasks_query` + `_apply_status_filter`),
所以「客服只能导出自己名下账号」这条不需要在这里重写一遍;
- **带 UTF-8 BOM**:不加的话 Excel 打开中文表头是乱码;
- 失败分型复用登录失败那套(`login_failure.classify_failure`),
与账号时间线上写的是同一份判据,不会出现「页面上算 A、导出算 B」。
"""
query = _apply_status_filter(_visible_tasks_query(db, current, batch_id), 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 (
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 "")
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(
[
"账号",
"状态",
"失败原因",
"失败分型",
"批次",
"最近尝试时间(UTC)",
"标签",
"归属客服",
]
)
for task in rows:
attempt_status = task.attempt_status or ""
effective = attempt_status or task.status or ""
message = (task.attempt_message if attempt_status else "") or task.message or ""
kind = classify_failure(message) if effective in {"failed", "error"} else ""
username, tag, owner = info.get(task.account_id, ("", "", ""))
writer.writerow(
[
username,
LOGIN_STATUS_LABELS.get(effective, effective),
message,
failure_kind_label(kind) if kind else "",
task.attempt_batch_id or task.batch_id or "",
_fmt_dt(task.attempt_at or task.finished_at or task.created_at),
tag,
owner,
]
)
content = "\ufeff" + output.getvalue()
stamp = datetime.now(UTC).strftime("%Y%m%d_%H%M")
filename = f"login_tasks_{status or 'all'}_{stamp}.csv"
record_audit(
db,
current,
action="login:tasks:export",
target=f"status={status or 'all'}",
detail={"rows": len(rows), "batch_id": batch_id or ""},
)
db.commit()
return StreamingResponse(
iter([content]),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f"attachment; filename={filename}"},
)
@router.get("/tasks/summary")
def tasks_summary(
db: Session = Depends(get_db),
@@ -336,17 +472,11 @@ def delete_tasks(
elif all_matching:
# 带 join 的 query 不能直接 bulk delete(SQLAlchemy 会拒绝),
# 所以先按权限与筛选条件查出 id,再按主键删。
query = _visible_tasks_query(db, current, batch_id)
if status:
query = query.filter(
or_(
and_(
LoginTask.attempt_status != "",
LoginTask.attempt_status == status,
),
and_(LoginTask.attempt_status == "", LoginTask.status == status),
)
)
# 状态筛选与列表/导出共用一份 —— 「清空失败」以前只删 `failed`、
# 漏掉 `error`,删完与页面上那个「失败 N」的数还对不上。
query = _apply_status_filter(
_visible_tasks_query(db, current, batch_id), status
)
ids = [row[0] for row in query.with_entities(LoginTask.id).all()]
else:
raise HTTPException(status_code=400, detail="请指定任务ID或 all_matching=true")