fix(accounts): 安全删除账号并保护履约租约
This commit is contained in:
@@ -15,8 +15,6 @@ from ..models import (
|
||||
AccountEvent,
|
||||
AuditLog,
|
||||
DouyuTask,
|
||||
DouyuWorkbenchAccount,
|
||||
LoginTask,
|
||||
User,
|
||||
)
|
||||
from ..permissions import ROLE_LABELS, user_has_permission
|
||||
@@ -35,6 +33,7 @@ from ..schemas import (
|
||||
)
|
||||
from ..services.account_binding import bind_payload
|
||||
from ..services.account_capability_service import account_capability_counts
|
||||
from ..services.account_deletion import AccountDeleteBlocked, delete_accounts
|
||||
from ..services.account_events_service import (
|
||||
CATEGORY_OPS,
|
||||
EVENT_ASSIGNED,
|
||||
@@ -1474,21 +1473,10 @@ def batch_delete_accounts(
|
||||
if not ids:
|
||||
raise HTTPException(status_code=400, detail="无效的账号ID")
|
||||
|
||||
# 先删除关联的登录任务
|
||||
db.query(LoginTask).filter(LoginTask.account_id.in_(ids)).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
db.query(DouyuTask).filter(DouyuTask.account_id.in_(ids)).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
db.query(DouyuWorkbenchAccount).filter(
|
||||
DouyuWorkbenchAccount.account_id.in_(ids)
|
||||
).delete(synchronize_session=False)
|
||||
|
||||
# 删除账号
|
||||
deleted = (
|
||||
db.query(Account).filter(Account.id.in_(ids)).delete(synchronize_session=False)
|
||||
)
|
||||
try:
|
||||
deleted = delete_accounts(db, account_ids=ids)
|
||||
except AccountDeleteBlocked as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
|
||||
# 账号删除会**连带删掉它的事件时间线**(外键),所以留下的痕迹只有审计。
|
||||
# 批量删时 account_id 无法表达 N 个账号,改成把删掉的 id 记进 detail ——
|
||||
@@ -1515,20 +1503,10 @@ def batch_delete_accounts_selection(
|
||||
if not ids:
|
||||
raise HTTPException(status_code=400, detail="请选择账号")
|
||||
|
||||
db.query(LoginTask).filter(LoginTask.account_id.in_(ids)).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
db.query(DouyuTask).filter(DouyuTask.account_id.in_(ids)).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
db.query(DouyuWorkbenchAccount).filter(
|
||||
DouyuWorkbenchAccount.account_id.in_(ids)
|
||||
).delete(synchronize_session=False)
|
||||
deleted = (
|
||||
_visible_accounts_query(db, current)
|
||||
.filter(Account.id.in_(ids))
|
||||
.delete(synchronize_session=False)
|
||||
)
|
||||
try:
|
||||
deleted = delete_accounts(db, account_ids=ids)
|
||||
except AccountDeleteBlocked as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
@@ -1918,21 +1896,10 @@ def delete_account(
|
||||
if not acc:
|
||||
raise HTTPException(status_code=404, detail="账号不存在")
|
||||
|
||||
# 先删除关联的登录任务,避免外键约束失败
|
||||
db.query(LoginTask).filter(LoginTask.account_id == account_id).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
db.query(DouyuTask).filter(DouyuTask.account_id == account_id).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
db.query(DouyuWorkbenchAccount).filter(
|
||||
DouyuWorkbenchAccount.account_id == account_id
|
||||
).delete(synchronize_session=False)
|
||||
# 事件表有指向 accounts 的外键,不清会直接删不掉账号。
|
||||
# 账号都没了,它的时间线也没有保留意义(审计仍在 audit_logs 里,那份不带外键)。
|
||||
db.query(AccountEvent).filter(AccountEvent.account_id == account_id).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
try:
|
||||
delete_accounts(db, account_ids=[account_id])
|
||||
except AccountDeleteBlocked as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
|
||||
db.add(
|
||||
AuditLog(
|
||||
@@ -1943,6 +1910,5 @@ def delete_account(
|
||||
account_id=account_id,
|
||||
)
|
||||
)
|
||||
db.delete(acc)
|
||||
db.commit()
|
||||
return {"message": "已删除", "success": True}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""账号永久删除:活动占用保护与关联数据清理。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import (
|
||||
Account,
|
||||
AccountEvent,
|
||||
AccountLease,
|
||||
AccountWorkItem,
|
||||
DouyuTask,
|
||||
DouyuWorkbenchAccount,
|
||||
LoginTask,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AccountDeleteBlocked(Exception):
|
||||
account_labels: tuple[str, ...]
|
||||
reasons: tuple[str, ...]
|
||||
|
||||
def __str__(self) -> str:
|
||||
accounts = "、".join(self.account_labels[:5])
|
||||
suffix = " 等" if len(self.account_labels) > 5 else ""
|
||||
return (
|
||||
f"账号 {accounts}{suffix} 当前仍被占用:"
|
||||
f"{'、'.join(self.reasons)}。请先停止任务、完成或释放履约租约后再删除"
|
||||
)
|
||||
|
||||
|
||||
def _account_label(account: Account) -> str:
|
||||
return account.nickname or account.username or account.uid or f"#{account.id}"
|
||||
|
||||
|
||||
def delete_accounts(db: Session, *, account_ids: list[int]) -> int:
|
||||
"""原子删除账号及其非级联子数据;任何活动占用都会阻止整批删除。"""
|
||||
normalized = sorted({int(account_id) for account_id in account_ids})
|
||||
if not normalized:
|
||||
return 0
|
||||
accounts = (
|
||||
db.query(Account)
|
||||
.filter(Account.id.in_(normalized))
|
||||
.order_by(Account.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if not accounts:
|
||||
return 0
|
||||
found_ids = [int(account.id) for account in accounts]
|
||||
account_map = {int(account.id): account for account in accounts}
|
||||
|
||||
active_lease_ids = {
|
||||
int(account_id)
|
||||
for (account_id,) in (
|
||||
db.query(AccountLease.account_id)
|
||||
.filter(
|
||||
AccountLease.account_id.in_(found_ids),
|
||||
AccountLease.status == "active",
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
}
|
||||
active_douyu_ids = {
|
||||
int(account_id)
|
||||
for (account_id,) in (
|
||||
db.query(DouyuTask.account_id)
|
||||
.filter(
|
||||
DouyuTask.account_id.in_(found_ids),
|
||||
DouyuTask.status.in_(("planned", "pending", "running")),
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
}
|
||||
active_login_ids = {
|
||||
int(account_id)
|
||||
for (account_id,) in (
|
||||
db.query(LoginTask.account_id)
|
||||
.filter(
|
||||
LoginTask.account_id.in_(found_ids),
|
||||
or_(
|
||||
LoginTask.attempt_status.in_(("pending", "running")),
|
||||
LoginTask.status.in_(("pending", "running")),
|
||||
),
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
}
|
||||
active_work_ids = {
|
||||
int(account_id)
|
||||
for (account_id,) in (
|
||||
db.query(AccountWorkItem.account_id)
|
||||
.filter(
|
||||
AccountWorkItem.account_id.in_(found_ids),
|
||||
AccountWorkItem.status.in_(("pending", "running")),
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
}
|
||||
blocked_ids = (
|
||||
active_lease_ids
|
||||
| active_douyu_ids
|
||||
| active_login_ids
|
||||
| active_work_ids
|
||||
)
|
||||
if blocked_ids:
|
||||
reasons: list[str] = []
|
||||
if active_lease_ids:
|
||||
reasons.append("存在活动履约租约")
|
||||
if active_douyu_ids:
|
||||
reasons.append("存在在途斗鱼任务")
|
||||
if active_login_ids:
|
||||
reasons.append("存在在途登录任务")
|
||||
if active_work_ids:
|
||||
reasons.append("存在在途账号同步工作")
|
||||
raise AccountDeleteBlocked(
|
||||
account_labels=tuple(
|
||||
_account_label(account_map[account_id])
|
||||
for account_id in sorted(blocked_ids)
|
||||
if account_id in account_map
|
||||
),
|
||||
reasons=tuple(reasons),
|
||||
)
|
||||
|
||||
# 以下外键在数据库里是 NO ACTION,必须显式清理。其余子表为 CASCADE,
|
||||
# 保留下来的业务订单/履约单通过 SET NULL 继续存在。
|
||||
db.query(AccountEvent).filter(
|
||||
AccountEvent.account_id.in_(found_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(AccountLease).filter(
|
||||
AccountLease.account_id.in_(found_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(LoginTask).filter(
|
||||
LoginTask.account_id.in_(found_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(DouyuTask).filter(
|
||||
DouyuTask.account_id.in_(found_ids)
|
||||
).delete(synchronize_session=False)
|
||||
db.query(DouyuWorkbenchAccount).filter(
|
||||
DouyuWorkbenchAccount.account_id.in_(found_ids)
|
||||
).delete(synchronize_session=False)
|
||||
for account in accounts:
|
||||
db.delete(account)
|
||||
db.flush()
|
||||
return len(accounts)
|
||||
|
||||
|
||||
__all__ = ["AccountDeleteBlocked", "delete_accounts"]
|
||||
Reference in New Issue
Block a user