"""斗鱼预售台账的账号占用、平台租约接管与释放。""" from __future__ import annotations from collections.abc import Mapping, Sequence from datetime import UTC, datetime from typing import Any from sqlalchemy import func from sqlalchemy.orm import Session from ..models import ( Account, AccountLease, DouyuExternalOrder, DouyuTask, PlatformFulfillmentTask, User, ) from ..permissions import user_has_permission from .account_events_service import ( CATEGORY_OPS, EVENT_ASSIGNED, EVENT_LEASE_ACQUIRED, emit, ) from .account_sync_service import lock_account_row from .audit_service import record_audit from .binding_ownership import role_names_match from .douyu_collab_common import ( COLLAB_LEASE_STATUSES, LEASE_PURPOSE_DOUYU_COLLAB, PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES, SOURCE_TYPE_PLATFORM_FULFILLMENT, STATUS_DONE, STATUS_FAILED, STATUS_POINTS_ERROR, STATUS_ROLE_ERROR, CollabError, _now, _text, ) from .platform_fulfillment.account_selector import ( acquire_account_lease, active_lease_for_account, release_lease, ) def _order_occupies_account(order: DouyuExternalOrder) -> bool: return ( bool(order.account_id) and order.archived_at is None and order.status in COLLAB_LEASE_STATUSES ) def _active_collab_orders( db: Session, account_id: int, *, exclude_order_id: int | None = None, ) -> list[DouyuExternalOrder]: query = db.query(DouyuExternalOrder).filter( DouyuExternalOrder.account_id == int(account_id), DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), DouyuExternalOrder.archived_at.is_(None), ) if exclude_order_id is not None: query = query.filter(DouyuExternalOrder.id != int(exclude_order_id)) return query.order_by(DouyuExternalOrder.updated_at.desc()).all() def _active_collab_order( db: Session, account_id: int, *, exclude_order_id: int | None = None, ) -> DouyuExternalOrder | None: orders = _active_collab_orders( db, account_id, exclude_order_id=exclude_order_id, ) return orders[0] if orders else None def _collab_order_expected_role( db: Session, order: DouyuExternalOrder, *, incoming_role: str = "", ) -> str: explicit = str(incoming_role or order.bind_game_role or "").strip() if explicit: return explicit if order.source_type == SOURCE_TYPE_PLATFORM_FULFILLMENT and order.source_task_id: task = db.get(PlatformFulfillmentTask, int(order.source_task_id)) if task is not None and task.customer_role_name: return str(task.customer_role_name or "").strip() return "" def _assert_collab_account_role_compatible( db: Session, order: DouyuExternalOrder, target_account_id: int, *, incoming_role: str = "", ) -> None: """防止不同游戏角色/客户的预售单共享同一个斗鱼账号,或复用已换绑的账号。""" exclude_id = int(order.id) if order.id else None candidate_role = _collab_order_expected_role( db, order, incoming_role=incoming_role, ) existing_orders = _active_collab_orders( db, target_account_id, exclude_order_id=exclude_id, ) if candidate_role: for existing in existing_orders: existing_role = _collab_order_expected_role(db, existing) if existing_role and not role_names_match(existing_role, candidate_role): raise CollabError( f"该账号已有进行中的预售单 {existing.order_no}" f"(绑定角色:{existing_role}),与当前角色({candidate_role})" "不一致,禁止共用同一账号", status_code=409, code="collab_role_conflict", ) if ( not str(incoming_role or "").strip() and str(order.bind_game_role or "").strip() and str(order.status or "") not in {STATUS_FAILED, STATUS_POINTS_ERROR, STATUS_ROLE_ERROR} ): account = db.get(Account, int(target_account_id)) current_role = str(account.game_name or "").strip() if account else "" order_bound_role = str(order.bind_game_role or "").strip() if current_role and not role_names_match(current_role, order_bound_role): raise CollabError( f"账号当前绑定角色({current_role})与预售单绑定角色" f"({order_bound_role})不一致,禁止继续占用该账号", status_code=409, code="collab_role_conflict", ) def _platform_lease_matches_source( db: Session, lease: AccountLease, order: DouyuExternalOrder, ) -> bool: if ( lease.purpose != "platform_fulfillment" or order.source_type != SOURCE_TYPE_PLATFORM_FULFILLMENT or not order.source_task_id ): return False task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == int(order.source_task_id)) .first() ) return bool( task is not None and (task.lease_id == lease.id or lease.batch_id == f"pf:{int(task.id)}") ) def _lock_active_lease_for_account( db: Session, account_id: int, ) -> AccountLease | None: return ( db.query(AccountLease) .filter( AccountLease.account_id == int(account_id), AccountLease.status == "active", ) .with_for_update() .first() ) def _platform_task_for_lease( db: Session, lease: AccountLease, ) -> PlatformFulfillmentTask | None: task_id = 0 if lease.batch_id.startswith("pf:"): try: task_id = int(lease.batch_id.removeprefix("pf:")) except ValueError: task_id = 0 query = db.query(PlatformFulfillmentTask).with_for_update() if task_id: task = query.filter(PlatformFulfillmentTask.id == task_id).first() if task is not None: return task return query.filter(PlatformFulfillmentTask.lease_id == int(lease.id)).first() def _takeover_platform_lease_for_collab( db: Session, current: User, order: DouyuExternalOrder, lease: AccountLease, ) -> AccountLease: """预售单显式接管平台租约,并在同一事务内把平台任务转人工。""" if not user_has_permission(current, "platform_fulfillment:use"): raise CollabError( "没有接管平台履约账号的权限", status_code=403, code="platform_takeover_forbidden", ) platform_task = _platform_task_for_lease(db, lease) if platform_task is None: raise CollabError( "平台履约任务不存在,请刷新后重试", status_code=409, code="account_lease_conflict", ) if platform_task.execution_status in {"completed", "cancelled"}: raise CollabError( f"平台履约任务 #{platform_task.id} 已结束,不能由预售单接管", status_code=409, code="platform_task_not_takeoverable", ) if ( platform_task.account_id != lease.account_id or platform_task.lease_id != lease.id ): raise CollabError( f"平台履约任务 #{platform_task.id} 与账号租约不一致,请先核对", status_code=409, code="account_lease_conflict", ) all_lease_tasks = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.lease_id == int(lease.id), PlatformFulfillmentTask.execution_status != "cancelled", ) .with_for_update() .all() ) active_siblings = [ item for item in all_lease_tasks if int(item.id) != int(platform_task.id) and item.execution_status not in {"completed", "cancelled"} ] if active_siblings: sibling_ids = ", ".join(f"#{item.id}" for item in active_siblings) raise CollabError( f"该账号同时被同角色其他进行中履约任务({sibling_ids})共享占用,暂不能直接接管", status_code=409, code="account_lease_conflict", ) for item in all_lease_tasks: if ( int(item.id) != int(platform_task.id) and item.execution_status == "completed" ): item.lease_id = None blocking = ( db.query(DouyuTask) .filter( DouyuTask.platform_task_id == int(platform_task.id), DouyuTask.status.in_(("planned", "pending", "running")), DouyuTask.task_type.in_(PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES), ) .order_by(DouyuTask.id.desc()) .first() ) if blocking is not None: raise CollabError( f"平台履约任务 #{platform_task.id} 正在执行资金/兑换操作,请先停止任务", status_code=409, code="platform_task_running", ) from .platform_fulfillment import service as platform_service platform_service.prepare_platform_task_for_collab_takeover( db, task=platform_task, current=current, collab_order_no=order.order_no, ) previous_task_id = int(platform_task.id) lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB lease.batch_id = f"collab:{int(lease.account_id)}"[:64] lease.commodity_id = "" lease.holder_user_id = int(current.id) lease.expires_at = None lease.released_at = None lease.release_reason = "" emit( db, account_id=int(lease.account_id), event_type=EVENT_LEASE_ACQUIRED, title=f"预售单接管平台履约账号:{order.order_no}", category=CATEGORY_OPS, detail={ "lease_id": lease.id, "order_id": order.id, "order_no": order.order_no, "platform_task_id": previous_task_id, "reason": "collab_manual_takeover", }, source="lease", subject_type="order", subject_key=order.order_no, actor_type="user", actor_id=int(current.id), source_ref=f"account_lease_collab_takeover:{lease.id}", ) _audit_lease_action( db, current, order=order, account_id=int(lease.account_id), action="douyu:collab:lease_takeover", lease=lease, detail={ "lease_id": lease.id, "order_id": order.id, "order_no": order.order_no, "platform_task_id": previous_task_id, "reason": "collab_manual_takeover", }, ) return lease def _audit_lease_action( db: Session, current: User, *, order: DouyuExternalOrder | None, account_id: int, action: str, lease: AccountLease, detail: Mapping[str, Any], ) -> None: entry = record_audit( db, current, action=action, target=( ( f"douyu_external_order:{order.id}" if order.id else f"douyu_external_order_no:{order.order_no}" ) if order is not None else f"account:{account_id}" ), detail=detail, ) entry.account_id = account_id def _ensure_order_account_lease( db: Session, current: User, order: DouyuExternalOrder, *, account_id: int | None = None, force_active: bool = False, takeover_platform_lease: bool = False, incoming_role: str = "", commit: bool = False, ) -> AccountLease | None: target_account_id = int(account_id or order.account_id or 0) if not target_account_id: return None if not force_active and not _order_occupies_account(order): return None _assert_collab_account_role_compatible( db, order, target_account_id, incoming_role=incoming_role, ) lease = _lock_active_lease_for_account(db, target_account_id) if lease is not None: if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: return lease if takeover_platform_lease: return _takeover_platform_lease_for_collab( db, current, order, lease, ) if _platform_lease_matches_source(db, lease, order): return lease platform_task = _platform_task_for_lease(db, lease) task_label = ( f"平台履约任务 #{platform_task.id}" if platform_task is not None else "平台履约任务" ) raise CollabError( f"该账号当前被{task_label}占用,请确认转人工后再使用", status_code=409, code="account_lease_conflict", ) lease = acquire_account_lease( db, account_id=target_account_id, holder_user_id=int(current.id), scope="elite", purpose=LEASE_PURPOSE_DOUYU_COLLAB, batch_id=f"collab:{target_account_id}", commit=False, ) if lease is None: raise CollabError( "该账号刚被其他业务占用,请刷新后重试", status_code=409, code="account_lease_conflict", ) _audit_lease_action( db, current, order=order, account_id=target_account_id, action="douyu:collab:lease_acquired", lease=lease, detail={ "lease_id": lease.id, "account_id": target_account_id, "purpose": lease.purpose, "batch_id": lease.batch_id, }, ) if commit: db.commit() return lease _DOUYU_TASK_INFLIGHT_STATUSES = ("planned", "pending", "running") _PF_SAFE_TERMINABLE_STATUSES = frozenset({"bound", "completed", "cancelled"}) _PF_MANUAL_STATUSES = frozenset({"manual_required"}) _ARCHIVED_POOL_RELEASE_REASON = "archived_collab_pool_release" _ARCHIVED_RELEASE_CHUNK_SIZE = 100 def _complete_platform_task_from_collab( db: Session, current: User, *, task: PlatformFulfillmentTask, now: datetime, reason: str, order: DouyuExternalOrder | None = None, ) -> None: """预售台账完成/归档/回池时,联动收口处于 bound 的来源履约任务。""" from .platform_fulfillment.outbox import _emit_order_site_binding_state from .platform_fulfillment.runtime import _append_event task.execution_status = "completed" if str(task.exchange_status or "") not in {"auto_done", "manual_done"}: task.exchange_status = "manual_done" if task.completed_at is None: task.completed_at = now task.issue_code = "" task.last_error = "" task.operator_id = int(current.id) task.updated_at = now task.lease_id = None _append_event( db, int(task.id), "collab_order_completed", actor_type="user", actor_id=int(current.id), detail={ "orderId": int(order.id) if order is not None and order.id else None, "orderNo": str(order.order_no or "") if order is not None else "", "reason": reason, }, ) _emit_order_site_binding_state(db, int(task.id)) def _cancel_manual_platform_task_from_archived_release( db: Session, current: User, *, task: PlatformFulfillmentTask, now: datetime, reason: str, ) -> None: """归档账号批量回池时,收口滞留的 manual_required 履约任务。""" from .douyu_batch_launcher import stop_douyu_batches from .platform_fulfillment.outbox import _emit_order_site_binding_state from .platform_fulfillment.runtime import _append_event previous_execution_status = task.execution_status previous_binding_status = task.binding_status previous_exchange_status = task.exchange_status previous_account_id = task.account_id previous_lease_id = task.lease_id linked_ids = [ int(value) for value in (task.bind_task_id, task.exchange_task_id) if value is not None ] linked_tasks = ( db.query(DouyuTask).filter(DouyuTask.id.in_(linked_ids)).all() if linked_ids else [] ) stopped_batches = stop_douyu_batches( [str(linked_task.batch_id or "") for linked_task in linked_tasks] ) for linked_task in linked_tasks: if linked_task.status in _DOUYU_TASK_INFLIGHT_STATUSES: linked_task.status = "stopped" linked_task.message = reason[:512] linked_task.finished_at = now task.account_id = None task.lease_id = None task.bind_task_id = None task.exchange_task_id = None task.binding_status = "not_started" task.execution_status = "cancelled" task.exchange_status = "not_started" task.issue_code = "" task.operator_id = int(current.id) task.last_error = reason[:2000] task.updated_at = now _append_event( db, int(task.id), "task_cancelled", actor_type="user", actor_id=int(current.id), detail={ "reason": task.last_error, "previousExecutionStatus": previous_execution_status, "previousBindingStatus": previous_binding_status, "previousExchangeStatus": previous_exchange_status, "releasedAccountId": previous_account_id, "releasedLeaseId": previous_lease_id, "stoppedBatches": stopped_batches, "source": _ARCHIVED_POOL_RELEASE_REASON, }, ) _emit_order_site_binding_state(db, int(task.id)) def _locked_platform_holders_for_lease( db: Session, lease: AccountLease, ) -> list[PlatformFulfillmentTask]: holders = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.lease_id == int(lease.id), PlatformFulfillmentTask.execution_status != "cancelled", ) .order_by(PlatformFulfillmentTask.id.asc()) .with_for_update() .all() ) holder_ids = {int(item.id) for item in holders} if lease.batch_id.startswith("pf:"): try: batch_task_id = int(lease.batch_id.removeprefix("pf:")) except ValueError: batch_task_id = 0 if batch_task_id and batch_task_id not in holder_ids: fallback = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == batch_task_id) .with_for_update() .first() ) if ( fallback is not None and fallback.execution_status != "cancelled" and ( fallback.lease_id == int(lease.id) or fallback.account_id == int(lease.account_id) ) ): holders.append(fallback) return holders def _try_release_platform_lease_from_collab( db: Session, current: User, order: DouyuExternalOrder, lease: AccountLease, *, reason: str, ) -> bool: """当预售单完成/归档时,若来源履约任务仅停在 bound 或已 completed,联动收口并释放租约。""" from .platform_fulfillment.runtime import _apply_task_lease_policy now = _now() holders = _locked_platform_holders_for_lease(db, lease) holder_by_id = {int(item.id): item for item in holders} source_task: PlatformFulfillmentTask | None = None if order.source_type == SOURCE_TYPE_PLATFORM_FULFILLMENT and order.source_task_id: source_id = int(order.source_task_id) source_task = holder_by_id.get(source_id) if source_task is None: candidate = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == source_id) .with_for_update() .first() ) if candidate is not None and ( candidate.lease_id == int(lease.id) or lease.batch_id == f"pf:{source_id}" ): source_task = candidate if candidate.execution_status != "cancelled": holder_by_id[source_id] = candidate holders.append(candidate) all_holder_ids = list(holder_by_id.keys()) if all_holder_ids: running_douyu_task = ( db.query(DouyuTask.id) .filter( DouyuTask.platform_task_id.in_(all_holder_ids), DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), ) .first() ) if running_douyu_task is not None: return False source_is_bound = bool( source_task is not None and source_task.execution_status == "bound" ) other_active_holders = [ item for item in holders if (not source_is_bound or int(item.id) != int(source_task.id)) # type: ignore[union-attr] and str(item.execution_status or "") not in {"completed", "cancelled"} ] if source_is_bound and source_task is not None: _complete_platform_task_from_collab( db, current, task=source_task, now=now, reason=reason, order=order, ) if other_active_holders: next_holder = min( other_active_holders, key=lambda item: int(item.id), ) if lease.batch_id == f"pf:{int(source_task.id)}": lease.batch_id = f"pf:{int(next_holder.id)}"[:64] _apply_task_lease_policy(db, next_holder, lease=lease, now=now) return False elif not holders or other_active_holders: return False for item in holders: if item.execution_status == "completed" and item.lease_id == int(lease.id): item.lease_id = None return release_lease(db, lease, reason=reason, now=now, commit=False) def _release_order_account_lease( db: Session, current: User, order: DouyuExternalOrder, *, reason: str, account_id: int | None = None, allow_close_platform_bound: bool = False, commit: bool = False, ) -> bool: target_account_id = int(account_id or order.account_id or 0) if not target_account_id: return False if _active_collab_order(db, target_account_id, exclude_order_id=int(order.id)): return False lock_account_row(db, target_account_id) lease = _lock_active_lease_for_account(db, target_account_id) if lease is None: return False if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: released = release_lease(db, lease, reason=reason, commit=False) elif lease.purpose == "platform_fulfillment" and allow_close_platform_bound: released = _try_release_platform_lease_from_collab( db, current, order, lease, reason=reason, ) else: return False if released: _audit_lease_action( db, current, order=order, account_id=target_account_id, action="douyu:collab:lease_released", lease=lease, detail={ "lease_id": lease.id, "account_id": target_account_id, "reason": reason, }, ) if commit: db.commit() return released def _sync_order_lease( db: Session, current: User, order: DouyuExternalOrder, *, reason: str, force_active: bool = False, reuse_active_lease: bool = False, incoming_role: str = "", allow_close_platform_bound: bool = False, commit: bool = False, ) -> AccountLease | None: if force_active or _order_occupies_account(order): if reuse_active_lease: target_account_id = int(order.account_id or 0) if target_account_id: _assert_collab_account_role_compatible( db, order, target_account_id, incoming_role=incoming_role, ) lease = _lock_active_lease_for_account(db, target_account_id) if lease is not None: if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: return lease if _platform_lease_matches_source(db, lease, order): return lease platform_task = _platform_task_for_lease(db, lease) task_label = ( f"平台履约任务 #{platform_task.id}" if platform_task is not None else "平台履约任务" ) raise CollabError( f"该账号当前被{task_label}占用,请先由预售单确认接管", status_code=409, code="account_lease_conflict", ) return _ensure_order_account_lease( db, current, order, force_active=force_active, incoming_role=incoming_role, commit=commit, ) should_close_pf = allow_close_platform_bound or ( order.status == STATUS_DONE or order.archived_at is not None ) _release_order_account_lease( db, current, order, reason=reason, allow_close_platform_bound=should_close_pf, commit=commit, ) return None def retain_lease_for_active_collab( db: Session, *, account_id: int, holder_user_id: int, current: User | None = None, lease: AccountLease | None = None, source_task_id: int | None = None, reason: str = "platform_release_to_collab", commit: bool = False, ) -> AccountLease | None: """平台释放账号时,把仍在活动的协作占用接续为统一协作租约。""" active_lease = lease or active_lease_for_account(db, account_id) if active_lease is not None and active_lease.status != "active": return None query = db.query(DouyuExternalOrder).filter( DouyuExternalOrder.account_id == int(account_id), DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), DouyuExternalOrder.archived_at.is_(None), ) if source_task_id: preferred = ( query.filter(DouyuExternalOrder.source_task_id == int(source_task_id)) .order_by(DouyuExternalOrder.updated_at.desc()) .first() ) order = ( preferred or query.order_by(DouyuExternalOrder.updated_at.desc()).first() ) else: order = query.order_by(DouyuExternalOrder.updated_at.desc()).first() if order is None: return None holder_id = int( holder_user_id or (order.owner_id if order.owner_id else 0) or (active_lease.holder_user_id if active_lease else 0) ) if not holder_id: return None if active_lease is None: active_lease = acquire_account_lease( db, account_id=int(account_id), holder_user_id=holder_id, scope="elite", purpose=LEASE_PURPOSE_DOUYU_COLLAB, batch_id=f"collab:{int(account_id)}", commit=False, ) if active_lease is None: return None elif active_lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB: previous_purpose = active_lease.purpose active_lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB active_lease.batch_id = f"collab:{int(account_id)}"[:64] active_lease.commodity_id = "" active_lease.expires_at = None active_lease.release_reason = "" active_lease.holder_user_id = holder_id emit( db, account_id=int(account_id), event_type=EVENT_LEASE_ACQUIRED, title=f"预售单接管账号占用:{order.order_no}", category=CATEGORY_OPS, detail={ "lease_id": active_lease.id, "order_id": order.id, "order_no": order.order_no, "purpose": active_lease.purpose, "previous_purpose": previous_purpose, "reason": reason, }, source="lease", subject_type="order", subject_key=order.order_no, actor_type="user" if current is not None else "system", actor_id=int(current.id) if current is not None else None, source_ref=f"account_lease_collab_takeover:{active_lease.id}", ) if current is not None: _audit_lease_action( db, current, order=order, account_id=int(account_id), action="douyu:collab:lease_takeover", lease=active_lease, detail={ "lease_id": active_lease.id, "order_id": order.id, "order_no": order.order_no, "reason": reason, }, ) if commit: db.commit() return active_lease def _as_utc(value: datetime | None) -> datetime | None: if value is None: return None return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC) def _chunked(values: Sequence[int], size: int) -> list[list[int]]: return [list(values[idx : idx + size]) for idx in range(0, len(values), size)] def _parse_pf_batch_task_id(batch_id: str | None) -> int: text = str(batch_id or "") if not text.startswith("pf:"): return 0 try: return int(text.removeprefix("pf:")) except ValueError: return 0 def _resolve_archived_target_scope( db: Session, *, order_ids: Sequence[int] = (), all_archived: bool = False, status: str = "", shop: str = "", owner_id: int | None = None, gift_name: str = "", keyword: str = "", ck_status: str = "", include_void: bool = False, ) -> tuple[int, list[int]]: from .douyu_collab_query import _apply_order_filters, _base_order_query if all_archived: query = _apply_order_filters( db, _base_order_query(db), include_void=include_void, archive_scope="archived", status=status, shop=shop, owner_id=owner_id, gift_name=gift_name, keyword=keyword, ck_status=ck_status, ).filter(DouyuExternalOrder.archived_at.isnot(None)) else: clean_ids = [int(item) for item in order_ids if int(item) > 0] if not clean_ids: raise CollabError( "请先勾选已归档订单,或选择释放当前筛选下全部归档账号", code="order_ids_required", ) query = db.query(DouyuExternalOrder).filter( DouyuExternalOrder.id.in_(clean_ids), DouyuExternalOrder.archived_at.isnot(None), ) matched_orders = ( query.order_by(None).with_entities(func.count(DouyuExternalOrder.id)).scalar() or 0 ) account_rows = ( query.order_by(None) .filter(DouyuExternalOrder.account_id.isnot(None)) .with_entities(DouyuExternalOrder.account_id) .distinct() .all() ) account_ids = sorted({int(row[0]) for row in account_rows if row[0]}) return int(matched_orders), account_ids def _analyze_archived_accounts_plan( db: Session, account_ids: Sequence[int], *, include_manual_required: bool, clear_assigned_to: bool, now: datetime, ) -> dict[str, Any]: counts: dict[str, int] = { "total_accounts": 0, "releasable_total": 0, "release_lease_total": 0, "release_collab_count": 0, "release_platform_bound_count": 0, "release_platform_manual_count": 0, "clear_assigned_count": 0, "already_free_count": 0, "skipped_total": 0, "skipped_active_collab": 0, "skipped_active_platform": 0, "skipped_running_task": 0, "skipped_manual_required": 0, "cooldown_ready_count": 0, "cooldown_waiting_count": 0, "invalid_ck_count": 0, } actionable_account_ids: list[int] = [] if not account_ids: return {**counts, "actionable_account_ids": actionable_account_ids} now_utc = _as_utc(now) or now accounts_by_id: dict[int, Account] = {} active_collab_ids: set[int] = set() running_task_account_ids: set[int] = set() active_leases_by_account: dict[int, AccountLease] = {} for chunk in _chunked(list(account_ids), 1000): for acc in db.query(Account).filter(Account.id.in_(chunk)).all(): accounts_by_id[int(acc.id)] = acc for (aid,) in ( db.query(DouyuExternalOrder.account_id) .filter( DouyuExternalOrder.account_id.in_(chunk), DouyuExternalOrder.archived_at.is_(None), DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), ) .distinct() .all() ): if aid: active_collab_ids.add(int(aid)) for (aid,) in ( db.query(DouyuTask.account_id) .filter( DouyuTask.account_id.in_(chunk), DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), ) .distinct() .all() ): if aid: running_task_account_ids.add(int(aid)) for lease in ( db.query(AccountLease) .filter( AccountLease.account_id.in_(chunk), AccountLease.status == "active", ) .all() ): active_leases_by_account[int(lease.account_id)] = lease lease_ids = [int(lease.id) for lease in active_leases_by_account.values()] batch_task_ids = { parsed for lease in active_leases_by_account.values() if lease.purpose == "platform_fulfillment" and (parsed := _parse_pf_batch_task_id(lease.batch_id)) > 0 } holders_by_lease: dict[int, list[PlatformFulfillmentTask]] = {} pf_tasks_by_id: dict[int, PlatformFulfillmentTask] = {} if lease_ids: for chunk in _chunked(lease_ids, 1000): for task in ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.lease_id.in_(chunk), PlatformFulfillmentTask.execution_status != "cancelled", ) .all() ): pf_tasks_by_id[int(task.id)] = task if task.lease_id: holders_by_lease.setdefault(int(task.lease_id), []).append(task) missing_batch_ids = sorted(batch_task_ids - set(pf_tasks_by_id.keys())) if missing_batch_ids: for chunk in _chunked(missing_batch_ids, 1000): for task in ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.id.in_(chunk), PlatformFulfillmentTask.execution_status != "cancelled", ) .all() ): pf_tasks_by_id[int(task.id)] = task running_pf_task_ids: set[int] = set() if pf_tasks_by_id: for chunk in _chunked(list(pf_tasks_by_id.keys()), 1000): for (pt_id,) in ( db.query(DouyuTask.platform_task_id) .filter( DouyuTask.platform_task_id.in_(chunk), DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), ) .distinct() .all() ): if pt_id: running_pf_task_ids.add(int(pt_id)) for account_id in account_ids: account = accounts_by_id.get(int(account_id)) if account is None: continue counts["total_accounts"] += 1 if int(account_id) in active_collab_ids: counts["skipped_active_collab"] += 1 counts["skipped_total"] += 1 continue if int(account_id) in running_task_account_ids: counts["skipped_running_task"] += 1 counts["skipped_total"] += 1 continue lease = active_leases_by_account.get(int(account_id)) lease_action = "none" if lease is not None: if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: lease_action = "release_collab" elif lease.purpose == "platform_fulfillment": holders = list(holders_by_lease.get(int(lease.id), ())) batch_tid = _parse_pf_batch_task_id(lease.batch_id) if batch_tid and all(int(t.id) != batch_tid for t in holders): fallback = pf_tasks_by_id.get(batch_tid) if fallback is not None and ( fallback.lease_id == int(lease.id) or fallback.account_id == int(account_id) ): holders.append(fallback) if any(int(t.id) in running_pf_task_ids for t in holders): counts["skipped_running_task"] += 1 counts["skipped_total"] += 1 continue statuses = {str(t.execution_status or "") for t in holders} non_terminable = ( statuses - _PF_SAFE_TERMINABLE_STATUSES - _PF_MANUAL_STATUSES ) if non_terminable: counts["skipped_active_platform"] += 1 counts["skipped_total"] += 1 continue if statuses & _PF_MANUAL_STATUSES: if include_manual_required: lease_action = "release_platform_manual" else: counts["skipped_manual_required"] += 1 counts["skipped_total"] += 1 continue else: lease_action = "release_platform_bound" else: counts["skipped_active_platform"] += 1 counts["skipped_total"] += 1 continue needs_clear_assigned = bool( clear_assigned_to and account.assigned_to is not None ) if lease_action == "none" and not needs_clear_assigned: counts["already_free_count"] += 1 continue actionable_account_ids.append(int(account_id)) counts["releasable_total"] += 1 if lease_action != "none": counts["release_lease_total"] += 1 counts[f"{lease_action}_count"] += 1 if needs_clear_assigned: counts["clear_assigned_count"] += 1 if account.status == "active" and account.ck_check_status == "valid": cooldown_at = _as_utc(account.role_change_available_at) if cooldown_at is None or cooldown_at <= now_utc: counts["cooldown_ready_count"] += 1 else: counts["cooldown_waiting_count"] += 1 else: counts["invalid_ck_count"] += 1 return {**counts, "actionable_account_ids": actionable_account_ids} def preview_archived_account_release( db: Session, *, order_ids: Sequence[int] = (), all_archived: bool = False, status: str = "", shop: str = "", owner_id: int | None = None, gift_name: str = "", keyword: str = "", ck_status: str = "", include_void: bool = False, include_manual_required: bool = False, clear_assigned_to: bool = True, ) -> dict[str, Any]: now = _now() matched_orders, account_ids = _resolve_archived_target_scope( db, order_ids=order_ids, all_archived=all_archived, status=status, shop=shop, owner_id=owner_id, gift_name=gift_name, keyword=keyword, ck_status=ck_status, include_void=include_void, ) plan = _analyze_archived_accounts_plan( db, account_ids, include_manual_required=include_manual_required, clear_assigned_to=clear_assigned_to, now=now, ) plan.pop("actionable_account_ids", None) return { "matched_orders": matched_orders, "include_manual_required": bool(include_manual_required), "clear_assigned_to": bool(clear_assigned_to), **plan, } def execute_archived_account_release( db: Session, current: User, *, order_ids: Sequence[int] = (), all_archived: bool = False, status: str = "", shop: str = "", owner_id: int | None = None, gift_name: str = "", keyword: str = "", ck_status: str = "", include_void: bool = False, include_manual_required: bool = False, clear_assigned_to: bool = True, reason: str = "", ) -> dict[str, Any]: now = _now() now_utc = _as_utc(now) or now current_id = int(current.id) clean_reason = _text(reason, max_length=256) or "活动结束,归档账号批量释放回号池" matched_orders, account_ids = _resolve_archived_target_scope( db, order_ids=order_ids, all_archived=all_archived, status=status, shop=shop, owner_id=owner_id, gift_name=gift_name, keyword=keyword, ck_status=ck_status, include_void=include_void, ) plan = _analyze_archived_accounts_plan( db, account_ids, include_manual_required=include_manual_required, clear_assigned_to=clear_assigned_to, now=now, ) actionable_ids: list[int] = list(plan.get("actionable_account_ids") or []) released_leases = 0 release_collab_count = 0 release_platform_bound_count = 0 release_platform_manual_count = 0 closed_platform_tasks = 0 cancelled_manual_tasks = 0 cleared_assigned_accounts = 0 processed_accounts = 0 cooldown_ready_count = 0 cooldown_waiting_count = 0 invalid_ck_count = 0 skipped_active_collab = int(plan["skipped_active_collab"]) skipped_active_platform = int(plan["skipped_active_platform"]) skipped_running_task = int(plan["skipped_running_task"]) skipped_manual_required = int(plan["skipped_manual_required"]) already_free_count = int(plan["already_free_count"]) for chunk in _chunked(actionable_ids, _ARCHIVED_RELEASE_CHUNK_SIZE): actor = db.get(User, current_id) or current chunk_now = _now() for account_id in chunk: lock_account_row(db, account_id) account = db.get(Account, int(account_id)) if account is None: continue if _active_collab_order(db, account_id) is not None: skipped_active_collab += 1 continue running_account_task = ( db.query(DouyuTask.id) .filter( DouyuTask.account_id == int(account_id), DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), ) .first() ) if running_account_task is not None: skipped_running_task += 1 continue lease = _lock_active_lease_for_account(db, account_id) released_here = False if lease is not None: if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: if release_lease( db, lease, reason=_ARCHIVED_POOL_RELEASE_REASON, now=chunk_now, commit=False, ): released_here = True released_leases += 1 release_collab_count += 1 elif lease.purpose == "platform_fulfillment": holders = _locked_platform_holders_for_lease(db, lease) holder_ids = [int(item.id) for item in holders] if holder_ids: running_pf = ( db.query(DouyuTask.id) .filter( DouyuTask.platform_task_id.in_(holder_ids), DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), ) .first() ) if running_pf is not None: skipped_running_task += 1 continue statuses = {str(item.execution_status or "") for item in holders} non_terminable = ( statuses - _PF_SAFE_TERMINABLE_STATUSES - _PF_MANUAL_STATUSES ) if non_terminable: skipped_active_platform += 1 continue has_manual = bool(statuses & _PF_MANUAL_STATUSES) if has_manual and not include_manual_required: skipped_manual_required += 1 continue for holder in holders: if holder.execution_status == "bound": _complete_platform_task_from_collab( db, actor, task=holder, now=chunk_now, reason=clean_reason, ) closed_platform_tasks += 1 elif ( holder.execution_status == "manual_required" and include_manual_required ): _cancel_manual_platform_task_from_archived_release( db, actor, task=holder, now=chunk_now, reason=clean_reason, ) cancelled_manual_tasks += 1 elif ( holder.execution_status == "completed" and holder.lease_id == int(lease.id) ): holder.lease_id = None if release_lease( db, lease, reason=_ARCHIVED_POOL_RELEASE_REASON, now=chunk_now, commit=False, ): released_here = True released_leases += 1 if has_manual: release_platform_manual_count += 1 else: release_platform_bound_count += 1 else: skipped_active_platform += 1 continue cleared_here = False if clear_assigned_to and account.assigned_to is not None: previous_assigned = int(account.assigned_to) account.assigned_to = None db.query(DouyuTask).filter( DouyuTask.account_id == int(account.id) ).update( {DouyuTask.account_assigned_to: None}, synchronize_session=False, ) emit( db, account_id=int(account.id), event_type=EVENT_ASSIGNED, title="归档账号释放回公共号池", category=CATEGORY_OPS, detail={ "previous_assigned_to": previous_assigned, "assigned_to": None, "reason": clean_reason, }, source="lease", actor_type="user", actor_id=current_id, ) cleared_here = True cleared_assigned_accounts += 1 if released_here or cleared_here: processed_accounts += 1 if account.status == "active" and account.ck_check_status == "valid": cooldown_at = _as_utc(account.role_change_available_at) if cooldown_at is None or cooldown_at <= now_utc: cooldown_ready_count += 1 else: cooldown_waiting_count += 1 else: invalid_ck_count += 1 else: already_free_count += 1 db.commit() actor = db.get(User, current_id) or current skipped_total = ( skipped_active_collab + skipped_active_platform + skipped_running_task + skipped_manual_required ) record_audit( db, actor, action="douyu:collab:archived_pool_release", target="douyu_collab:archived_pool_release", detail={ "matched_orders": matched_orders, "total_accounts": int(plan["total_accounts"]), "processed_accounts": processed_accounts, "released_leases": released_leases, "release_collab_count": release_collab_count, "release_platform_bound_count": release_platform_bound_count, "release_platform_manual_count": release_platform_manual_count, "closed_platform_tasks": closed_platform_tasks, "cancelled_manual_tasks": cancelled_manual_tasks, "cleared_assigned_accounts": cleared_assigned_accounts, "skipped_total": skipped_total, "include_manual_required": bool(include_manual_required), "clear_assigned_to": bool(clear_assigned_to), "reason": clean_reason, }, ) db.commit() return { "matched_orders": matched_orders, "total_accounts": int(plan["total_accounts"]), "processed_accounts": processed_accounts, "released_leases": released_leases, "release_collab_count": release_collab_count, "release_platform_bound_count": release_platform_bound_count, "release_platform_manual_count": release_platform_manual_count, "closed_platform_tasks": closed_platform_tasks, "cancelled_manual_tasks": cancelled_manual_tasks, "cleared_assigned_accounts": cleared_assigned_accounts, "already_free_count": already_free_count, "skipped_total": skipped_total, "skipped_active_collab": skipped_active_collab, "skipped_active_platform": skipped_active_platform, "skipped_running_task": skipped_running_task, "skipped_manual_required": skipped_manual_required, "cooldown_ready_count": cooldown_ready_count, "cooldown_waiting_count": cooldown_waiting_count, "invalid_ck_count": invalid_ck_count, "include_manual_required": bool(include_manual_required), "clear_assigned_to": bool(clear_assigned_to), }