修复(履约与分配): 封堵工作台换绑、预售共号与分配中心越权占用

This commit is contained in:
yml
2026-11-27 13:42:28 +08:00
parent 9100991cb1
commit 5006367217
13 changed files with 1031 additions and 34 deletions
+82 -11
View File
@@ -20,6 +20,7 @@ from ..models import (
AuditLog,
DouyuExternalOrder,
DouyuTask,
PlatformFulfillmentTask,
User,
)
from ..permissions import ROLE_LABELS, user_has_permission
@@ -75,6 +76,8 @@ from ..services.account_query_filters import (
ACTIVE_COLLAB_STATUSES,
active_collab_order_exists,
active_lease_exists,
recent_elite_bind_lock_exists,
role_change_ready_filter,
)
from ..services.account_service import parse_and_build_accounts
from ..services.account_value import (
@@ -184,6 +187,28 @@ def _visible_accounts_query(db: Session, current: User):
raise HTTPException(status_code=403, detail="无权查看账号")
def _active_platform_fulfillment_exists():
return (
select(PlatformFulfillmentTask.id)
.where(
PlatformFulfillmentTask.account_id == Account.id,
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled")
),
)
.exists()
)
def _unoccupied_for_assign_filter():
"""可分配给客服的安全兜底:无活动租约、无活跃预售单、无未结束履约任务。"""
return and_(
~active_lease_exists(),
~active_collab_order_exists(),
~_active_platform_fulfillment_exists(),
)
def _assignable_account_filter():
"""分配池口径:当前 Cookie 必须有一次不早于它的有效 CK 检测。"""
return and_(
@@ -430,15 +455,15 @@ def _filter_accounts_query(
if bind_change_value == "available":
query = query.filter(
Account.role_bind_status == "bound",
or_(
Account.role_change_available_at.is_(None),
Account.role_change_available_at <= now,
),
role_change_ready_filter(now),
)
elif bind_change_value == "cooldown":
query = query.filter(
Account.role_bind_status == "bound",
Account.role_change_available_at > now,
or_(
Account.role_change_available_at > now,
recent_elite_bind_lock_exists(now),
),
)
elif bind_change_value == "unbound":
query = query.filter(Account.role_bind_status == "unbound")
@@ -465,14 +490,15 @@ def _filter_accounts_query(
if occupancy_value:
has_lease = active_lease_exists()
in_collab = active_collab_order_exists()
in_fulfillment = _active_platform_fulfillment_exists()
if occupancy_value == "free":
query = query.filter(~has_lease, ~in_collab)
query = query.filter(~has_lease, ~in_collab, ~in_fulfillment)
elif occupancy_value == "no_lease":
query = query.filter(~has_lease)
query = query.filter(~has_lease, ~in_fulfillment)
elif occupancy_value == "no_collab":
query = query.filter(~in_collab)
elif occupancy_value == "leased":
query = query.filter(has_lease)
query = query.filter(or_(has_lease, in_fulfillment))
elif occupancy_value == "collab":
query = query.filter(in_collab)
@@ -1459,6 +1485,19 @@ def assign_account(
status_code=400,
detail="该账号尚未通过有效 CK 检测,无法分配",
)
is_free = (
db.query(Account.id)
.filter(
Account.id == account_id,
_unoccupied_for_assign_filter(),
)
.first()
)
if not is_free:
raise HTTPException(
status_code=409,
detail="该账号当前被履约订单、预售台账或活动租约占用,禁止分配给客服",
)
if acc.assigned_to != req.assigned_to:
acc.assigned_to = req.assigned_to
@@ -1527,6 +1566,33 @@ def batch_assign_accounts(
status_code=400,
detail=f"以下账号尚未通过有效 CK 检测,无法分配:{name_list}{suffix}",
)
free_ids = {
int(account_id)
for (account_id,) in (
db.query(Account.id)
.filter(
Account.id.in_(ids),
_unoccupied_for_assign_filter(),
)
.all()
)
}
occupied_ids = [account_id for account_id in ids if account_id not in free_ids]
if occupied_ids:
names = (
db.query(Account.username)
.filter(Account.id.in_(occupied_ids))
.all()
)
name_list = ", ".join([n[0] for n in names[:5]])
suffix = "..." if len(occupied_ids) > 5 else ""
raise HTTPException(
status_code=409,
detail=(
f"以下账号当前被履约订单、预售台账或活动租约占用,"
f"禁止分配给客服:{name_list}{suffix}"
),
)
# 先取出账号对象(批量时间线要逐个写事件,光有 count 不够)。
# 「撤回」只处理当前确实有归属的账号;显式勾选里混入未分配账号时,
@@ -1612,6 +1678,7 @@ def dispatch_assignments(
.filter(
Account.assigned_to.is_(None),
_assignable_account_filter(),
_unoccupied_for_assign_filter(),
)
)
if req.strategy == "points":
@@ -1772,6 +1839,7 @@ def assignment_options(
]
has_lease = active_lease_exists()
in_collab = active_collab_order_exists()
in_fulfillment = _active_platform_fulfillment_exists()
def count_with(*filters) -> int:
return int(
@@ -1783,10 +1851,10 @@ def assignment_options(
occupancy = {
"assignable": count_with(),
"free": count_with(~has_lease, ~in_collab),
"no_lease": count_with(~has_lease),
"free": count_with(~has_lease, ~in_collab, ~in_fulfillment),
"no_lease": count_with(~has_lease, ~in_fulfillment),
"no_collab": count_with(~in_collab),
"leased": count_with(has_lease),
"leased": count_with(or_(has_lease, in_fulfillment)),
"collab": count_with(in_collab),
}
presets = {
@@ -1795,12 +1863,14 @@ def assignment_options(
Account.points <= 0,
~has_lease,
~in_collab,
~in_fulfillment,
),
"elite_points": count_with(
Account.elite_opened.is_(True),
Account.points > 0,
~has_lease,
~in_collab,
~in_fulfillment,
),
"high_value": count_with(
or_(
@@ -1809,6 +1879,7 @@ def assignment_options(
),
~has_lease,
~in_collab,
~in_fulfillment,
),
}
+2 -1
View File
@@ -105,6 +105,7 @@ from ..services.douyu_service import (
DOUYU_HANDBOOK_TASK_TYPES,
SUPPORTED_DOUYU_TASK_TYPES,
DouyuActivePaymentError,
DouyuLeaseConflictError,
DouyuTaskBackpressureError,
apply_douyu_config_defaults,
cleanup_orphan_douyu_tasks,
@@ -1541,7 +1542,7 @@ def _prepare_task_batch(
recharge_channel=recharge_channel,
recharge_amount=recharge_amount,
)
except DouyuActivePaymentError as exc:
except (DouyuActivePaymentError, DouyuLeaseConflictError) as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
except DouyuTaskBackpressureError as exc:
raise HTTPException(
+141 -14
View File
@@ -27,7 +27,14 @@ from datetime import UTC, datetime, timedelta
from sqlalchemy import or_
from sqlalchemy.orm import Session
from ..models import AccountLease, DouyuTask, PlatformFulfillmentTask
from ..models import (
Account,
AccountLease,
DouyuExternalOrder,
DouyuTask,
PlatformFulfillmentTask,
)
from .account_query_filters import ACTIVE_COLLAB_STATUSES
#: 允许把工作台任务挂到订单上的绑定阶段。已 bound / manual_required 的订单
#: 不再接受自动归属,避免工作台的一次手工操作改写已完成订单。
@@ -46,30 +53,59 @@ BINDING_LINKABLE_STATUSES = frozenset(
#: 不在此列:查询只能证明账号当前状态,不能证明某个订单的绑定已经确认。
BINDING_TASK_TYPES = frozenset({"get_bind_qr", "confirm_bind"})
#: 精英工作台会改写兑换资格或消耗积分的写操作任务类型。
WORKBENCH_GOODS_MUTATION_TYPES = frozenset(
{"lock_goods", "pay_locked_order", "exchange_goods"}
)
#: 任务创建时间与租约起点的容差。两者由不同事务写入,允许几秒偏差;
#: 不允许跨租约归属(上一个订单的任务不能算到下一张订单上)。
LEASE_CLOCK_TOLERANCE = timedelta(seconds=5)
def active_account_lease(
db: Session,
account_id: int,
*,
purpose: str | None = None,
) -> AccountLease | None:
"""账号当前生效且未过期的租约;可按 ``purpose`` 过滤。"""
query = db.query(AccountLease).filter(
AccountLease.account_id == int(account_id),
AccountLease.status == "active",
or_(
AccountLease.expires_at.is_(None),
AccountLease.expires_at > datetime.now(UTC),
),
)
if purpose is not None:
query = query.filter(AccountLease.purpose == purpose)
return query.order_by(AccountLease.leased_at.desc(), AccountLease.id.desc()).first()
def active_fulfillment_lease(
db: Session,
account_id: int,
) -> AccountLease | None:
"""账号当前生效的履约租约;没有则返回 ``None``。"""
return (
db.query(AccountLease)
.filter(
AccountLease.account_id == int(account_id),
AccountLease.status == "active",
AccountLease.purpose == "platform_fulfillment",
or_(
AccountLease.expires_at.is_(None),
AccountLease.expires_at > datetime.now(UTC),
),
)
.order_by(AccountLease.leased_at.desc(), AccountLease.id.desc())
.first()
return active_account_lease(db, account_id, purpose="platform_fulfillment")
def active_collab_order_for_account(
db: Session,
account_id: int,
*,
exclude_order_id: int | None = None,
) -> DouyuExternalOrder | None:
"""账号当前未结束、未归档的预售台账订单。"""
query = db.query(DouyuExternalOrder).filter(
DouyuExternalOrder.account_id == int(account_id),
DouyuExternalOrder.status.in_(ACTIVE_COLLAB_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()).first()
def active_fulfillment_binding_task_id(
@@ -149,10 +185,100 @@ def role_names_match(left: object, right: object) -> bool:
return bool(left_key) and left_key == right_key
def _account_display_label(account: Account) -> str:
return (
str(account.nickname or "").strip()
or str(account.username or "").strip()
or str(account.uid or "").strip()
or f"#{account.id}"
)
def workbench_task_occupation_error(
db: Session,
account: Account,
*,
task_type: str,
handbook_scope: str,
platform_task_id: int | None,
allow_auto_link: bool = False,
) -> str | None:
"""检查工作台无归属任务是否会误改已占用账号的角色或库存。
仅拦截未绑定 ``platform_task_id`` 的精英宝典写操作:
- 绑码/换绑(``get_bind_qr`` / ``confirm_bind``):若未命中可自动归属的
待绑定履约单,禁止在任意活动租约(平台履约、预售台账等)或活跃预售单期间执行;
- 锁单/支付/兑换:账号处于平台履约租约期间,只能由履约订单带 ``platform_task_id`` 发起。
"""
if handbook_scope != "elite" or platform_task_id is not None:
return None
label = _account_display_label(account)
lease = active_account_lease(db, account.id)
if task_type in BINDING_TASK_TYPES:
if allow_auto_link and active_fulfillment_binding_task_id(db, account.id) is not None:
return None
if lease is not None:
if lease.purpose == "platform_fulfillment":
return (
f"账号 {label} 当前有已绑定、人工处理中或已完成的平台履约订单"
f"(批次 {lease.batch_id or '-'}),禁止从工作台发起绑定或换绑"
)
if lease.purpose == "douyu_collab":
return (
f"账号 {label} 当前由斗鱼预售台账占用,"
"禁止从工作台发起绑定或换绑"
)
return (
f"账号 {label} 当前已被业务租约占用({lease.purpose}),"
"禁止从工作台发起绑定或换绑"
)
collab = active_collab_order_for_account(db, account.id)
if collab is not None:
return (
f"账号 {label} 存在未完成的斗鱼预售台账订单({collab.order_no}),"
"禁止从工作台发起绑定或换绑"
)
bound_fulfillment = (
db.query(PlatformFulfillmentTask.id)
.filter(
PlatformFulfillmentTask.account_id == int(account.id),
PlatformFulfillmentTask.scope == "elite",
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled")
),
PlatformFulfillmentTask.binding_status.notin_(
BINDING_LINKABLE_STATUSES
),
)
.first()
)
if bound_fulfillment is not None:
return (
f"账号 {label} 当前有关联的已绑定或待人工处理平台履约单(#{bound_fulfillment[0]}),"
"禁止从工作台发起绑定或换绑"
)
return None
if (
task_type in WORKBENCH_GOODS_MUTATION_TYPES
and lease is not None
and lease.purpose == "platform_fulfillment"
):
return (
f"账号 {label} 当前由平台履约订单占用"
f"(批次 {lease.batch_id or '-'}),请从履约订单内发起锁单或兑换"
)
return None
__all__ = [
"BINDING_LINKABLE_STATUSES",
"BINDING_TASK_TYPES",
"LEASE_CLOCK_TOLERANCE",
"WORKBENCH_GOODS_MUTATION_TYPES",
"active_account_lease",
"active_collab_order_for_account",
"active_fulfillment_binding_task_id",
"active_fulfillment_lease",
"fulfillment_lease_for_task",
@@ -160,4 +286,5 @@ __all__ = [
"normalize_role_name",
"role_names_match",
"source_created_within_lease",
"workbench_task_occupation_error",
]
+108 -4
View File
@@ -8,6 +8,7 @@ from typing import Any
from sqlalchemy.orm import Session
from ..models import (
Account,
AccountLease,
DouyuExternalOrder,
DouyuTask,
@@ -21,11 +22,15 @@ from .account_events_service import (
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 (
@@ -43,12 +48,12 @@ def _order_occupies_account(order: DouyuExternalOrder) -> bool:
)
def _active_collab_order(
def _active_collab_orders(
db: Session,
account_id: int,
*,
exclude_order_id: int | None = None,
) -> DouyuExternalOrder | None:
) -> list[DouyuExternalOrder]:
query = db.query(DouyuExternalOrder).filter(
DouyuExternalOrder.account_id == int(account_id),
DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES),
@@ -56,7 +61,88 @@ def _active_collab_order(
)
if exclude_order_id is not None:
query = query.filter(DouyuExternalOrder.id != int(exclude_order_id))
return query.order_by(DouyuExternalOrder.updated_at.desc()).first()
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(
@@ -256,6 +342,7 @@ def _ensure_order_account_lease(
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)
@@ -264,6 +351,13 @@ def _ensure_order_account_lease(
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:
@@ -368,11 +462,20 @@ def _sync_order_lease(
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:
lease = _lock_active_lease_for_account(db, int(order.account_id or 0))
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
@@ -394,6 +497,7 @@ def _sync_order_lease(
current,
order,
force_active=force_active,
incoming_role=incoming_role,
commit=commit,
)
_release_order_account_lease(
+97 -2
View File
@@ -27,6 +27,7 @@ from core.douyu import DouyuActivityClient
from ..models import (
Account,
AccountEvent,
AccountLease,
AuditLog,
DouyuCollabGift,
@@ -52,6 +53,7 @@ from .account_query_filters import ACTIVE_COLLAB_STATUSES
from .account_sync_runner import WORK_STOREHOME_SYNC
from .account_work_queue import enqueue_account_work
from .audit_service import record_account_action, record_audit
from .binding_ownership import role_names_match
from .business_events import record_account_query
from .collab_common import (
count_archived,
@@ -1030,6 +1032,7 @@ def update_order(
account_id=int(account.id),
force_active=order.status in COLLAB_LEASE_STATUSES,
takeover_platform_lease=takeover_platform_lease,
incoming_role=_text(probe.get("bind_game_role")),
)
apply_probe_snapshot(
db,
@@ -1134,6 +1137,7 @@ def set_account(
account_id=int(account.id),
force_active=order.status in COLLAB_LEASE_STATUSES,
takeover_platform_lease=takeover_platform_lease,
incoming_role=_text(probe.get("bind_game_role")),
)
apply_probe_snapshot(
db,
@@ -1232,7 +1236,68 @@ def _status_audit_target(order: DouyuExternalOrder) -> str:
return f"douyu_external_order:{order.id}"
def _collab_order_role_mismatch_reason(
db: Session,
order: DouyuExternalOrder,
account: Account | None = None,
*,
records: Sequence[Mapping[str, Any]] = (),
) -> str | None:
"""校验订单目标角色与账号当前实际绑定角色、兑换记录角色是否一致。"""
expected = _text(order.bind_game_role)
if not expected:
return None
acc = account or account_by_id(db, order.account_id) or account_by_username(
db, order.account_username
)
if acc is not None:
current_role = _text(acc.game_name)
if current_role and not role_names_match(expected, current_role):
return (
f"账号当前绑定角色({current_role})"
f"与订单目标角色({expected})不一致"
)
if str(acc.role_bind_status or "") == "unbound":
return f"账号当前未绑定任何游戏角色,与订单目标角色({expected})不一致"
if isinstance(order.bind_snapshot_at, datetime):
rebind_event = (
db.query(AccountEvent)
.filter(
AccountEvent.account_id == int(acc.id),
AccountEvent.event_type == "bind_ok",
AccountEvent.subject_type == "elite_role",
AccountEvent.occurred_at > order.bind_snapshot_at,
)
.order_by(AccountEvent.occurred_at.desc(), AccountEvent.id.desc())
.first()
)
if (
rebind_event is not None
and _text(rebind_event.subject_key)
and not role_names_match(expected, rebind_event.subject_key)
):
return (
f"账号在快照后已换绑为({_text(rebind_event.subject_key)}),"
f"与订单目标角色({expected})不一致"
)
for record in records:
if not isinstance(record, Mapping):
continue
record_role = _text(
record.get("roleName")
or record.get("role_name")
or record.get("bindRoleName")
)
if record_role and not role_names_match(expected, record_role):
return (
f"兑换记录角色({record_role})"
f"与订单目标角色({expected})不一致"
)
return None
def _assert_ready_for_recharge(
db: Session,
order: DouyuExternalOrder,
*,
entering_waiting: bool,
@@ -1253,6 +1318,13 @@ def _assert_ready_for_recharge(
f"{action}还缺:{'、'.join(missing)}",
code="recharge_precondition",
)
mismatch = _collab_order_role_mismatch_reason(db, order)
if mismatch:
raise CollabError(
f"{mismatch},禁止推进或完成订单,请先核实角色或切换为账号角色异常",
status_code=409,
code="role_mismatch",
)
def _restore_void_status(
@@ -1277,6 +1349,7 @@ def _restore_void_status(
target_index = STAGE_INDEX.get(target)
if target_index is not None and target_index >= STAGE_INDEX[STATUS_TO_RECHARGE]:
_assert_ready_for_recharge(
db,
order,
entering_waiting=target == STATUS_TO_RECHARGE,
allow_missing_role=target == STATUS_RECHARGED,
@@ -1462,6 +1535,7 @@ def set_status(
raise CollabError("回退状态必须显式确认", code="rollback_required")
if target_index >= STAGE_INDEX[STATUS_TO_RECHARGE]:
_assert_ready_for_recharge(
db,
order,
entering_waiting=target == STATUS_TO_RECHARGE,
allow_missing_role=target == STATUS_RECHARGED,
@@ -1738,6 +1812,7 @@ def query_activity(
matched = 0
matched_records: list[dict[str, Any]] = []
role_mismatch: str | None = None
now = _now()
if not include_records:
verdict = VERDICT_UNKNOWN
@@ -1752,8 +1827,18 @@ def query_activity(
matched_records = _matching_exchange_records(loaded_records, order)
matched = len(matched_records)
if matched:
verdict = VERDICT_SUCCESS
message = f"兑换记录命中「{order.gift_name}」{matched} 条"
role_mismatch = _collab_order_role_mismatch_reason(
db, order, account, records=matched_records
)
if role_mismatch:
verdict = VERDICT_FAILED
message = (
f"兑换记录命中「{order.gift_name}」{matched} 条,"
f"但{role_mismatch},禁止自动标记成功"
)
else:
verdict = VERDICT_SUCCESS
message = f"兑换记录命中「{order.gift_name}」{matched} 条"
elif order.status not in (STATUS_SCRIPTED, STATUS_FAILED):
verdict = VERDICT_UNKNOWN
message = "订单当前状态不再由兑换记录自动判定"
@@ -1844,6 +1929,16 @@ def query_activity(
expected_version=None,
commit=False,
)
elif order.status in (STATUS_SCRIPTED, STATUS_FAILED) and role_mismatch:
set_status(
db,
current,
order,
status=STATUS_ROLE_ERROR,
reason=message,
expected_version=None,
commit=False,
)
elif order.status == STATUS_SCRIPTED and verdict == VERDICT_FAILED:
set_status(
db,
+37
View File
@@ -30,6 +30,7 @@ from .account_binding import (
role_change_available_at,
set_bind_status,
)
from .binding_ownership import role_names_match, workbench_task_occupation_error
from .business_events import record_bind
from .douyu_account_probe import (
ROLE_BOUND,
@@ -1340,6 +1341,20 @@ class BindMixin:
"bind_candidate_decisions": candidate_decisions,
}
)
if (
snapshot["role_name"]
and not role_names_match(baseline_role_name, snapshot["role_name"])
):
record_bind(
db,
account,
task_id=task.id,
scope="elite",
role_name=snapshot["role_name"],
act_alias=query_alias,
rebind=bool(str(baseline_role_name or "").strip()),
actor_id=int(task.created_by),
)
self._apply_bind_info_to_account(account, bind_info, BIND_BOUND)
self._mark_task(
db,
@@ -1488,6 +1503,17 @@ class BindMixin:
def _execute_get_bind_qr(
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
):
occupation_error = workbench_task_occupation_error(
db,
account,
task_type="get_bind_qr",
handbook_scope=str(task.handbook_scope or ""),
platform_task_id=task.platform_task_id,
allow_auto_link=False,
)
if occupation_error:
self._mark_task(db, task, "failed", occupation_error)
return
client = self._client(cookie)
expected_role_name = str(
(task.result or {}).get("expected_role_name") or ""
@@ -1758,6 +1784,17 @@ class BindMixin:
def _execute_confirm_bind(
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
):
occupation_error = workbench_task_occupation_error(
db,
account,
task_type="confirm_bind",
handbook_scope=str(task.handbook_scope or ""),
platform_task_id=task.platform_task_id,
allow_auto_link=False,
)
if occupation_error:
self._mark_task(db, task, "failed", occupation_error)
return
client = self._client(cookie)
confirm_alias = self._confirm_act_alias(config)
query_aliases = self._query_bind_act_aliases(config)
@@ -13,6 +13,7 @@ from core.douyu import DouyuActivityClient, DouyuActivityError
from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask
from .account_exchange_sync_service import sync_exchange_records
from .binding_ownership import workbench_task_occupation_error
from .business_events import record_exchange
from .douyu_activity_query import (
query_activity_goods,
@@ -328,6 +329,17 @@ class GoodsMixin:
def _execute_exchange_goods(
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
):
occupation_error = workbench_task_occupation_error(
db,
account,
task_type=str(task.task_type or "exchange_goods"),
handbook_scope=str(task.handbook_scope or ""),
platform_task_id=task.platform_task_id,
allow_auto_link=False,
)
if occupation_error:
self._mark_task(db, task, "failed", occupation_error)
return
payload = self._task_payload(task)
commodity_id = str(
payload.get("commodity_id") or payload.get("commodityId") or ""
+26 -1
View File
@@ -15,7 +15,12 @@ from core.douyu.cookie_utils import cookie_value
from ..models import Account, DouyuConfig, DouyuTask
from . import account_query_filters as account_filters
from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk
from .binding_ownership import BINDING_TASK_TYPES, active_fulfillment_binding_task_id
from .binding_ownership import (
BINDING_TASK_TYPES,
WORKBENCH_GOODS_MUTATION_TYPES,
active_fulfillment_binding_task_id,
workbench_task_occupation_error,
)
from .douyu_binding import resolve_douyu_binding
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = account_filters.LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
@@ -168,6 +173,10 @@ class DouyuActivePaymentError(ValueError):
"""同一账号已有未结束的充值任务。"""
class DouyuLeaseConflictError(ValueError):
"""账号当前被履约订单或预售台账占用,禁止从工作台发起冲突操作。"""
class DouyuTaskBackpressureError(ValueError):
"""全局活跃斗鱼任务超过安全上限。"""
@@ -362,6 +371,22 @@ def create_douyu_planned_tasks(
accounts = visible_douyu_task_accounts(db, account_ids)
_ensure_active_task_budget(db, len(accounts))
_lock_payment_accounts(db, accounts, task_type)
if (
platform_task_id is None
and handbook_scope == "elite"
and task_type in (BINDING_TASK_TYPES | WORKBENCH_GOODS_MUTATION_TYPES)
):
for account in accounts:
occupation_error = workbench_task_occupation_error(
db,
account,
task_type=task_type,
handbook_scope=handbook_scope,
platform_task_id=platform_task_id,
allow_auto_link=True,
)
if occupation_error:
raise DouyuLeaseConflictError(occupation_error)
if (
task_type in {"refresh_esports_goods", "refresh_xpd_goods"}
and accounts