diff --git a/tests/test_account_deletion.py b/tests/test_account_deletion.py new file mode 100644 index 0000000..4018f6b --- /dev/null +++ b/tests/test_account_deletion.py @@ -0,0 +1,173 @@ +"""账号删除的活动占用保护与关联清理测试。""" + +from __future__ import annotations + +from datetime import UTC, datetime + +import pytest +from fastapi import HTTPException + +from web.backend.models import ( + Account, + AccountEvent, + AccountLease, + AuditLog, + DouyuTask, + DouyuWorkbenchAccount, + LoginTask, + PlatformFulfillmentTask, + User, +) +from web.backend.routers.accounts import batch_delete_accounts_selection, delete_account +from web.backend.schemas import AccountBulkSelection +from web.backend.services.account_deletion import AccountDeleteBlocked, delete_accounts + + +def _user(db, name: str = "delete-admin") -> User: + user = User( + username=name, + password_hash="h", + role="super_admin", + is_active=True, + ) + db.add(user) + db.commit() + return user + + +def _account(db, name: str) -> Account: + account = Account( + username=name, + password="p", + email=f"{name}@example.com", + email_password="ep", + ) + db.add(account) + db.commit() + return account + + +def _lease(db, account: Account, user: User, status: str = "active") -> AccountLease: + lease = AccountLease( + account_id=account.id, + holder_user_id=user.id, + scope="elite", + purpose="platform_fulfillment", + status=status, + released_at=datetime.now(UTC) if status != "active" else None, + ) + db.add(lease) + db.commit() + return lease + + +def test_active_lease_blocks_single_delete_without_partial_cleanup(db): + user = _user(db) + account = _account(db, "delete-active") + _lease(db, account, user) + event = AccountEvent( + account_id=account.id, + event_type="test", + category="ops", + occurred_at=datetime.now(UTC), + ) + db.add(event) + db.commit() + + with pytest.raises(HTTPException) as exc_info: + delete_account(account.id, db=db, current=user) + + assert exc_info.value.status_code == 409 + assert "活动履约租约" in str(exc_info.value.detail) + assert db.get(Account, account.id) is not None + assert db.get(AccountEvent, event.id) is not None + + +def test_delete_cleans_non_cascade_children_and_keeps_audit(db): + user = _user(db, "delete-history-admin") + account = _account(db, "delete-history") + lease = _lease(db, account, user, status="expired") + task = PlatformFulfillmentTask( + source_order_id="delete-order", + source_order_item_id="delete-item", + platform_order_id="delete-platform-order", + account_id=account.id, + lease_id=lease.id, + execution_status="completed", + binding_status="bound", + exchange_status="not_started", + ) + event = AccountEvent( + account_id=account.id, + event_type="test", + category="business", + occurred_at=datetime.now(UTC), + ) + login = LoginTask( + batch_id="delete-login", + account_id=account.id, + status="success", + created_by=user.id, + ) + douyu = DouyuTask( + batch_id="delete-douyu", + account_id=account.id, + task_type="query_points", + status="success", + created_by=user.id, + ) + workbench = DouyuWorkbenchAccount( + user_id=user.id, + handbook_scope="elite", + account_id=account.id, + ) + db.add_all([task, event, login, douyu, workbench]) + db.commit() + event_id = event.id + lease_id = lease.id + login_id = login.id + douyu_id = douyu.id + workbench_id = workbench.id + task_id = task.id + account_id = account.id + + delete_account(account_id, db=db, current=user) + + assert db.get(Account, account_id) is None + assert db.get(AccountEvent, event_id) is None + assert db.get(AccountLease, lease_id) is None + assert db.get(LoginTask, login_id) is None + assert db.get(DouyuTask, douyu_id) is None + assert db.get(DouyuWorkbenchAccount, workbench_id) is None + refreshed_platform_task = db.get(PlatformFulfillmentTask, task_id) + assert refreshed_platform_task is not None + assert refreshed_platform_task.account_id is None + assert refreshed_platform_task.lease_id is None + audit = ( + db.query(AuditLog) + .filter(AuditLog.action == "account:delete", AuditLog.account_id == account_id) + .one() + ) + assert audit.target == "delete-history" + + +def test_batch_delete_is_atomic_when_one_account_is_active(db): + user = _user(db, "delete-batch-admin") + free = _account(db, "delete-batch-free") + busy = _account(db, "delete-batch-busy") + _lease(db, busy, user) + + with pytest.raises(AccountDeleteBlocked): + delete_accounts(db, account_ids=[free.id, busy.id]) + db.rollback() + + assert db.get(Account, free.id) is not None + assert db.get(Account, busy.id) is not None + + with pytest.raises(HTTPException) as exc_info: + batch_delete_accounts_selection( + AccountBulkSelection(account_ids=[free.id, busy.id]), + db=db, + current=user, + ) + assert exc_info.value.status_code == 409 diff --git a/web/backend/routers/accounts.py b/web/backend/routers/accounts.py index 016e7b1..07e0ce9 100644 --- a/web/backend/routers/accounts.py +++ b/web/backend/routers/accounts.py @@ -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} diff --git a/web/backend/services/account_deletion.py b/web/backend/services/account_deletion.py new file mode 100644 index 0000000..d89a656 --- /dev/null +++ b/web/backend/services/account_deletion.py @@ -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"]