feat(douyu): 支持斗鱼预售归档账号安全释放回号库并修复完成归档自动解租 (v0.4.25)

This commit is contained in:
yml
2026-11-30 14:28:00 +08:00
parent efcbd9a691
commit cc78208048
11 changed files with 1927 additions and 9 deletions
+66
View File
@@ -32,6 +32,9 @@ from ..schemas import (
DouyuCollabAccountRecommendRequest,
DouyuCollabAccountRequest,
DouyuCollabAccountUnlinkRequest,
DouyuCollabArchivedAccountReleaseOut,
DouyuCollabArchivedAccountReleasePreviewOut,
DouyuCollabArchivedAccountReleaseRequest,
DouyuCollabArchiveRequest,
DouyuCollabCkExportOut,
DouyuCollabCkExportRequest,
@@ -698,6 +701,69 @@ def unarchive_external_orders(
return result
@router.post(
"/external-orders/archived-account-release/preview",
response_model=DouyuCollabArchivedAccountReleasePreviewOut,
)
def preview_archived_external_order_account_release(
req: DouyuCollabArchivedAccountReleaseRequest,
db: Session = Depends(get_db),
_current: User = Depends(require_permission("douyu:collab:manage")),
):
try:
return collab.preview_archived_account_release(
db,
order_ids=req.order_ids,
all_archived=req.all_archived,
status=req.status,
shop=req.shop,
owner_id=req.owner_id,
gift_name=req.gift_name,
keyword=req.keyword,
ck_status=req.ck_status,
include_void=req.include_void,
include_manual_required=req.include_manual_required,
clear_assigned_to=req.clear_assigned_to,
)
except collab.CollabError as exc:
raise _http_error(exc) from exc
@router.post(
"/external-orders/archived-account-release",
response_model=DouyuCollabArchivedAccountReleaseOut,
)
def release_archived_external_order_accounts(
req: DouyuCollabArchivedAccountReleaseRequest,
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:collab:manage")),
):
try:
result = collab.execute_archived_account_release(
db,
current,
order_ids=req.order_ids,
all_archived=req.all_archived,
status=req.status,
shop=req.shop,
owner_id=req.owner_id,
gift_name=req.gift_name,
keyword=req.keyword,
ck_status=req.ck_status,
include_void=req.include_void,
include_manual_required=req.include_manual_required,
clear_assigned_to=req.clear_assigned_to,
reason=req.reason,
)
except collab.CollabError as exc:
raise _http_error(exc) from exc
if result.get("processed_accounts"):
_publish_change(
current, scope="orders", action="order.archived_account_release"
)
return result
@router.get(
"/external-orders/{order_id}/timeline",
response_model=list[DouyuCollabTimelineOut],
+61
View File
@@ -2946,6 +2946,67 @@ class DouyuCollabArchiveRequest(BaseModel):
reason: str = Field("", max_length=256)
class DouyuCollabArchivedAccountReleaseRequest(BaseModel):
order_ids: list[int] = Field(default_factory=list)
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 = Field("", max_length=256)
class DouyuCollabArchivedAccountReleasePreviewOut(BaseModel):
matched_orders: int = 0
total_accounts: int = 0
releasable_total: int = 0
release_lease_total: int = 0
release_collab_count: int = 0
release_platform_bound_count: int = 0
release_platform_manual_count: int = 0
clear_assigned_count: int = 0
already_free_count: int = 0
skipped_total: int = 0
skipped_active_collab: int = 0
skipped_active_platform: int = 0
skipped_running_task: int = 0
skipped_manual_required: int = 0
cooldown_ready_count: int = 0
cooldown_waiting_count: int = 0
invalid_ck_count: int = 0
include_manual_required: bool = False
clear_assigned_to: bool = True
class DouyuCollabArchivedAccountReleaseOut(BaseModel):
matched_orders: int = 0
total_accounts: int = 0
processed_accounts: int = 0
released_leases: int = 0
release_collab_count: int = 0
release_platform_bound_count: int = 0
release_platform_manual_count: int = 0
closed_platform_tasks: int = 0
cancelled_manual_tasks: int = 0
cleared_assigned_accounts: int = 0
already_free_count: int = 0
skipped_total: int = 0
skipped_active_collab: int = 0
skipped_active_platform: int = 0
skipped_running_task: int = 0
skipped_manual_required: int = 0
cooldown_ready_count: int = 0
cooldown_waiting_count: int = 0
invalid_ck_count: int = 0
include_manual_required: bool = False
clear_assigned_to: bool = True
class DouyuCollabCkExportRequest(BaseModel):
"""勾选多行,导出关联内部账号的 CK 明文(一次最多 50 条)。"""
+851 -4
View File
@@ -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}
+71
View File
@@ -356,6 +356,67 @@ export interface DouyuCollabBatchQueryItem {
message?: string;
}
export interface DouyuCollabArchivedAccountReleaseRequest {
order_ids?: number[];
all_archived?: boolean;
status?: string;
shop?: string;
owner_id?: number;
gift_name?: string;
keyword?: string;
ck_status?: string;
include_void?: boolean;
include_manual_required?: boolean;
clear_assigned_to?: boolean;
reason?: string;
}
export interface DouyuCollabArchivedAccountReleasePreview {
matched_orders: number;
total_accounts: number;
releasable_total: number;
release_lease_total: number;
release_collab_count: number;
release_platform_bound_count: number;
release_platform_manual_count: number;
clear_assigned_count: number;
already_free_count: number;
skipped_total: number;
skipped_active_collab: number;
skipped_active_platform: number;
skipped_running_task: number;
skipped_manual_required: number;
cooldown_ready_count: number;
cooldown_waiting_count: number;
invalid_ck_count: number;
include_manual_required: boolean;
clear_assigned_to: boolean;
}
export interface DouyuCollabArchivedAccountReleaseResult {
matched_orders: number;
total_accounts: number;
processed_accounts: number;
released_leases: number;
release_collab_count: number;
release_platform_bound_count: number;
release_platform_manual_count: number;
closed_platform_tasks: number;
cancelled_manual_tasks: number;
cleared_assigned_accounts: number;
already_free_count: number;
skipped_total: number;
skipped_active_collab: number;
skipped_active_platform: number;
skipped_running_task: number;
skipped_manual_required: number;
cooldown_ready_count: number;
cooldown_waiting_count: number;
invalid_ck_count: number;
include_manual_required: boolean;
clear_assigned_to: boolean;
}
export const douyuCollabApi = {
listOrders: (params: {
page?: number;
@@ -547,6 +608,16 @@ export const douyuCollabApi = {
api.post<{ archived: number }, { archived: number }>('/douyu/external-orders/archive', { ids, reason }),
unarchive: (ids: number[]) =>
api.post<{ unarchived: number }, { unarchived: number }>('/douyu/external-orders/unarchive', ids),
previewArchivedAccountRelease: (data: DouyuCollabArchivedAccountReleaseRequest) =>
api.post<DouyuCollabArchivedAccountReleasePreview, DouyuCollabArchivedAccountReleasePreview>(
'/douyu/external-orders/archived-account-release/preview',
data,
),
releaseArchivedAccounts: (data: DouyuCollabArchivedAccountReleaseRequest) =>
api.post<DouyuCollabArchivedAccountReleaseResult, DouyuCollabArchivedAccountReleaseResult>(
'/douyu/external-orders/archived-account-release',
data,
),
timeline: (id: number) =>
api.get<DouyuCollabTimeline[], DouyuCollabTimeline[]>(`/douyu/external-orders/${id}/timeline`),
metrics: (id: number) =>
+257 -2
View File
@@ -17,6 +17,7 @@ import {
Input,
InputNumber,
Modal,
Radio,
Row,
Select,
Space,
@@ -64,6 +65,7 @@ import type {
DouyuCollabAccountCandidate,
DouyuCollabAccountLookup,
DouyuCollabAccountRecommendation,
DouyuCollabArchivedAccountReleasePreview,
DouyuCollabCkExportResult,
DouyuCollabExchangeRecord,
DouyuCollabExchangeRecordsResponse,
@@ -224,6 +226,17 @@ export default function DouyuCollabPage() {
const [usernameExport, setUsernameExport] =
useState<DouyuCollabUsernameExportResult | null>(null);
const [archivedReleaseOpen, setArchivedReleaseOpen] = useState(false);
const [archivedReleaseScope, setArchivedReleaseScope] = useState<'selected' | 'all_archived'>('all_archived');
const [archivedReleaseIncludeManual, setArchivedReleaseIncludeManual] = useState(false);
const [archivedReleaseClearAssigned, setArchivedReleaseClearAssigned] = useState(true);
const [archivedReleaseReason, setArchivedReleaseReason] = useState('');
const [archivedReleasePreview, setArchivedReleasePreview] =
useState<DouyuCollabArchivedAccountReleasePreview | null>(null);
const [archivedReleaseLoading, setArchivedReleaseLoading] = useState(false);
const [archivedReleaseSubmitting, setArchivedReleaseSubmitting] = useState(false);
const archivedReleaseSeq = useRef(0);
// 切换标签/筛选后旧勾选可能已不在当前结果里,批量操作前必须清空,避免误改其他状态的单。
const resetFilterState = useCallback(() => {
setPage(1);
@@ -317,7 +330,8 @@ export default function DouyuCollabPage() {
ckExportOpen ||
usernameExportOpen ||
unlinkOpen ||
recommendOpen,
recommendOpen ||
archivedReleaseOpen,
);
// 暂停后连 WebSocket 也不建:既不自动重拉,也不做断线兜底轮询。
const realtimeSyncEnabled = canView && !realtimePaused;
@@ -1230,6 +1244,107 @@ export default function DouyuCollabPage() {
}
};
const buildArchivedReleasePayload = useCallback(
(
scopeMode: 'selected' | 'all_archived',
includeManual: boolean,
clearAssigned: boolean,
reasonText = '',
) => ({
order_ids: scopeMode === 'selected' ? selectedIds : [],
all_archived: scopeMode === 'all_archived',
status: statusFilter || undefined,
shop: shopFilter || undefined,
owner_id: ownerFilter,
gift_name: giftFilter || undefined,
keyword: keyword.trim() || undefined,
ck_status: ckFilter || undefined,
include_void: includeVoid,
include_manual_required: includeManual,
clear_assigned_to: clearAssigned,
reason: reasonText.trim() || undefined,
}),
[
selectedIds,
statusFilter,
shopFilter,
ownerFilter,
giftFilter,
keyword,
ckFilter,
includeVoid,
],
);
const loadArchivedReleasePreview = useCallback(
async (
scopeMode: 'selected' | 'all_archived',
includeManual: boolean,
clearAssigned: boolean,
) => {
const seq = ++archivedReleaseSeq.current;
setArchivedReleaseLoading(true);
try {
const preview = await douyuCollabApi.previewArchivedAccountRelease(
buildArchivedReleasePayload(scopeMode, includeManual, clearAssigned),
);
if (seq !== archivedReleaseSeq.current) return;
setArchivedReleasePreview(preview);
} catch (error) {
if (seq === archivedReleaseSeq.current) {
message.error(getErrorMessage(error));
}
} finally {
if (seq === archivedReleaseSeq.current) {
setArchivedReleaseLoading(false);
}
}
},
[buildArchivedReleasePayload],
);
const openArchivedReleaseModal = () => {
const defaultScope: 'selected' | 'all_archived' =
selectedIds.length > 0 ? 'selected' : 'all_archived';
setArchivedReleaseScope(defaultScope);
setArchivedReleaseIncludeManual(false);
setArchivedReleaseClearAssigned(true);
setArchivedReleaseReason('');
setArchivedReleasePreview(null);
setArchivedReleaseOpen(true);
void loadArchivedReleasePreview(defaultScope, false, true);
};
const closeArchivedReleaseModal = () => {
archivedReleaseSeq.current += 1;
setArchivedReleaseOpen(false);
setArchivedReleasePreview(null);
};
const submitArchivedRelease = async () => {
setArchivedReleaseSubmitting(true);
try {
const result = await douyuCollabApi.releaseArchivedAccounts(
buildArchivedReleasePayload(
archivedReleaseScope,
archivedReleaseIncludeManual,
archivedReleaseClearAssigned,
archivedReleaseReason,
),
);
closeArchivedReleaseModal();
message.success(
`已释放 ${result.processed_accounts} 个归档账号回公共号库(解除租约 ${result.released_leases} 个,清空专属归属 ${result.cleared_assigned_accounts} 个;其中 ${result.cooldown_ready_count} 个已过换绑冷却可立即可用)`,
);
setSelectedRowKeys([]);
refreshAll();
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setArchivedReleaseSubmitting(false);
}
};
const batchArchive = () => {
if (!canArchiveSelected) {
message.warning('只有勾选的抢购成功订单才能批量归档');
@@ -1237,7 +1352,7 @@ export default function DouyuCollabPage() {
}
modal.confirm({
title: `归档选中的 ${selectedIds.length} 单?`,
content: '归档后这些订单在「查看归档」里只读展示,需要继续操作时可取消归档。',
content: '归档后这些订单在「查看归档」里只读保留历史记录;若账号没有其他活跃单据,会自动收口来源履约单并释放租约(换绑冷却时间不变),需要继续操作时也可取消归档。',
onOk: async () => {
try {
const result = await douyuCollabApi.archive(selectedIds, '');
@@ -2055,6 +2170,18 @@ export default function DouyuCollabPage() {
批量取消归档{selectedCount > 0 ? `(${selectedCount})` : ''}
</Button>
)}
{canManage && archiveScope === 'archived' && (
<Tooltip title="只解除归档账号的租约和专属客服限制,让账号回到公共号库;历史归档订单、兑换记录与 7 天换绑冷却全部保留">
<Button
type="primary"
icon={<DisconnectOutlined />}
disabled={loading || summary.archived_total === 0}
onClick={openArchivedReleaseModal}
>
释放归档账号回池{selectedCount > 0 ? `(已选 ${selectedCount} 单)` : ''}
</Button>
</Tooltip>
)}
{canEdit && (
<Button icon={<ReloadOutlined />} onClick={() => void refreshGoods()} loading={goodsLoading}>
刷新活动商品
@@ -2804,6 +2931,134 @@ export default function DouyuCollabPage() {
</Space>
</Modal>
<Modal
title="释放归档账号回公共号库"
open={archivedReleaseOpen}
onCancel={closeArchivedReleaseModal}
width={680}
onOk={() => void submitArchivedRelease()}
okText={
archivedReleasePreview
? `确认释放(${archivedReleasePreview.releasable_total} 个账号)`
: '确认释放'
}
okButtonProps={{
disabled:
archivedReleaseLoading ||
!archivedReleasePreview ||
archivedReleasePreview.releasable_total === 0,
}}
confirmLoading={archivedReleaseSubmitting}
destroyOnHidden
>
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Alert
type="info"
showIcon
message="历史记录与换绑冷却全部保留,只解除账号的租约与归属占用限制"
description="不会删除任何归档订单、截图、时间线或兑换记录;会保留 7 天换绑冷却与 365 天同皮肤兑换记录校验。仍在未归档预售单或正在自动绑码/兑换中的账号会自动跳过。"
/>
<div>
<Text strong>处理范围:</Text>
<Radio.Group
style={{ marginLeft: 8 }}
value={archivedReleaseScope}
onChange={(event) => {
const nextScope = event.target.value as 'selected' | 'all_archived';
setArchivedReleaseScope(nextScope);
void loadArchivedReleasePreview(
nextScope,
archivedReleaseIncludeManual,
archivedReleaseClearAssigned,
);
}}
>
<Radio value="selected" disabled={selectedIds.length === 0}>
仅勾选的 {selectedIds.length} 单关联账号
</Radio>
<Radio value="all_archived">当前归档筛选下的全部账号</Radio>
</Radio.Group>
</div>
<Space direction="vertical" size={6}>
<Checkbox
checked={archivedReleaseIncludeManual}
onChange={(event) => {
const checked = event.target.checked;
setArchivedReleaseIncludeManual(checked);
void loadArchivedReleasePreview(
archivedReleaseScope,
checked,
archivedReleaseClearAssigned,
);
}}
>
同时释放历史转人工 / 失败履约占位(会取消对应滞留的人工履约任务并保留取消记录)
</Checkbox>
<Checkbox
checked={archivedReleaseClearAssigned}
onChange={(event) => {
const checked = event.target.checked;
setArchivedReleaseClearAssigned(checked);
void loadArchivedReleasePreview(
archivedReleaseScope,
archivedReleaseIncludeManual,
checked,
);
}}
>
同步清空客服专属归属(直接回到公共号库)
</Checkbox>
</Space>
{archivedReleaseLoading ? (
<Text type="secondary">正在扫描归档账号租约与安全护栏…</Text>
) : archivedReleasePreview ? (
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="涉及归档订单 / 账号">
{archivedReleasePreview.matched_orders} 单 / {archivedReleasePreview.total_accounts} 个去重账号
</Descriptions.Item>
<Descriptions.Item label="本次将释放回池">
<Text strong type={archivedReleasePreview.releasable_total > 0 ? 'success' : undefined}>
{archivedReleasePreview.releasable_total} 个账号
</Text>
(解除租约 {archivedReleasePreview.release_lease_total},清空归属 {archivedReleasePreview.clear_assigned_count})
</Descriptions.Item>
<Descriptions.Item label="租约释放明细">
预售租约 {archivedReleasePreview.release_collab_count} · 履约已绑定收口{' '}
{archivedReleasePreview.release_platform_bound_count} · 转人工占位{' '}
{archivedReleasePreview.release_platform_manual_count}
</Descriptions.Item>
<Descriptions.Item label="回池后冷却状态">
已过冷却可立即可用 <Text strong>{archivedReleasePreview.cooldown_ready_count}</Text> · 冷却中{' '}
{archivedReleasePreview.cooldown_waiting_count} · 需重登/异常 {archivedReleasePreview.invalid_ck_count}
</Descriptions.Item>
<Descriptions.Item label="本已空闲(无限制)">
{archivedReleasePreview.already_free_count} 个
</Descriptions.Item>
<Descriptions.Item label="安全跳过">
共 {archivedReleasePreview.skipped_total} 个(未归档活跃单{' '}
{archivedReleasePreview.skipped_active_collab} · 履约/任务运行中{' '}
{archivedReleasePreview.skipped_active_platform + archivedReleasePreview.skipped_running_task}
{archivedReleasePreview.skipped_manual_required > 0
? ` · 未勾选的转人工占位 ${archivedReleasePreview.skipped_manual_required}`
: ''}
)
</Descriptions.Item>
</Descriptions>
) : null}
<Input.TextArea
rows={2}
maxLength={256}
value={archivedReleaseReason}
placeholder="释放原因备注(可选,例如:活动结束,归档账号统一回公共号池)"
onChange={(event) => setArchivedReleaseReason(event.target.value)}
/>
</Space>
</Modal>
<Drawer
title={
detail ? (
@@ -159,6 +159,7 @@ export const COLLAB_ACTION_LABELS: Record<string, string> = {
'douyu:collab:ck_export': '导出账号与登录凭据',
'douyu:collab:archive': '归档订单',
'douyu:collab:unarchive': '取消归档',
'douyu:collab:archived_pool_release': '归档账号释放回池',
'douyu:collab:sync_from_platform_fulfillment': '同步直播履约单',
'douyu:collab:lease_acquired': '建立账号占用',
'douyu:collab:lease_released': '释放账号占用',