Files
live-hub-py/web/backend/services/douyu_collab_leases.py
T

616 lines
19 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""斗鱼预售台账的账号占用、平台租约接管与释放。"""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
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_LEASE_ACQUIRED,
emit,
)
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_FAILED,
STATUS_POINTS_ERROR,
STATUS_ROLE_ERROR,
CollabError,
)
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",
)
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
def _release_order_account_lease(
db: Session,
current: User,
order: DouyuExternalOrder,
*,
reason: str,
account_id: int | None = None,
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
lease = active_lease_for_account(db, target_account_id)
if lease is None or lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB:
return False
released = release_lease(db, lease, reason=reason, commit=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 = "",
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,
)
_release_order_account_lease(
db,
current,
order,
reason=reason,
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