feat(douyu): 支持斗鱼预售归档账号安全释放回号库并修复完成归档自动解租 (v0.4.25)
This commit is contained in:
@@ -2,9 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
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 (
|
||||
@@ -18,9 +20,11 @@ from ..models import (
|
||||
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 (
|
||||
@@ -28,10 +32,13 @@ from .douyu_collab_common import (
|
||||
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,
|
||||
@@ -442,6 +449,241 @@ def _ensure_order_account_lease(
|
||||
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,
|
||||
@@ -449,6 +691,7 @@ def _release_order_account_lease(
|
||||
*,
|
||||
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)
|
||||
@@ -456,10 +699,22 @@ def _release_order_account_lease(
|
||||
return False
|
||||
if _active_collab_order(db, target_account_id, exclude_order_id=int(order.id)):
|
||||
return False
|
||||
lease = active_lease_for_account(db, target_account_id)
|
||||
if lease is None or lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB:
|
||||
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
|
||||
released = release_lease(db, lease, reason=reason, commit=False)
|
||||
if released:
|
||||
_audit_lease_action(
|
||||
db,
|
||||
@@ -488,6 +743,7 @@ def _sync_order_lease(
|
||||
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):
|
||||
@@ -525,11 +781,15 @@ def _sync_order_lease(
|
||||
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
|
||||
@@ -638,3 +898,590 @@ def retain_lease_for_active_collab(
|
||||
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),
|
||||
}
|
||||
|
||||
@@ -156,6 +156,8 @@ from .douyu_collab_leases import (
|
||||
_ensure_order_account_lease,
|
||||
_release_order_account_lease,
|
||||
_sync_order_lease,
|
||||
execute_archived_account_release,
|
||||
preview_archived_account_release,
|
||||
retain_lease_for_active_collab,
|
||||
)
|
||||
from .douyu_collab_query import (
|
||||
@@ -1647,6 +1649,7 @@ def set_status(
|
||||
current,
|
||||
order,
|
||||
reuse_active_lease=True,
|
||||
allow_close_platform_bound=(target == STATUS_DONE),
|
||||
reason=(
|
||||
"douyu_collab_done"
|
||||
if target == STATUS_DONE
|
||||
@@ -2349,6 +2352,7 @@ def archive_orders(
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_archived",
|
||||
allow_close_platform_bound=True,
|
||||
)
|
||||
db.commit()
|
||||
return {"archived": archived}
|
||||
|
||||
Reference in New Issue
Block a user