"""游戏角色绑定启动、确认与刷新。""" from __future__ import annotations import uuid from datetime import timedelta from typing import Any from fastapi import HTTPException from sqlalchemy import case, func from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from starlette.concurrency import run_in_threadpool from ...models import ( Account, AccountEvent, AccountLease, DouyuTask, PlatformFulfillmentEvent, PlatformFulfillmentTask, User, ) from ..account_binding import pending_binding_role_from_result from ..binding_ownership import ( BINDING_TASK_TYPES, fulfillment_lease_for_task, lease_is_active, role_names_match, source_created_within_lease, ) from ..business_events import record_douyu_task_started from ..douyu_account_probe import ( ROLE_BOUND, ROLE_ERROR, ROLE_UNKNOWN, activity_client, config_mapping, elite_action_aliases, persist_probe_result, resolve_elite_role, ) from ..douyu_binding import ( BINDING_OBSERVATION_TASK_TYPES, BINDING_VIEW_CONFIRMED, BINDING_VIEW_PENDING, resolve_douyu_binding, resolve_fulfillment_binding, ) from ..douyu_role_audit import record_role_api_candidates from ..douyu_service import ensure_douyu_config from ..execution_jobs import ( JOB_DOUYU_BINDING, LANE_FULFILLMENT, enqueue_execution_job, ) from .binding_status import ( _binding_failure_issue, _binding_failure_raw_message, _customer_task_message, ) from .common import FLOW_VERSION_CLEAN, SCOPE_ELITE, _has_game_home_profile, _now from .outbox import _emit_order_site_binding_state from .repository import ( _binding_qr_expired, _integration_actor, _load_task, _load_task_for_update, ) from .role_lock import ( ACCOUNT_LOCK_ISSUE, ROLE_LOCK_ISSUE, AccountLock, RoleLock, find_account_lock, find_role_lock, ) from .runtime import ( _append_event, _apply_task_lease_policy, ) from .views import get_task_detail BINDING_SYNC_TASK_TYPES = frozenset( { "get_bind_qr", "query_game_name", "confirm_bind", "prepare_esports_bind", "query_esports_game_name", "confirm_esports_bind", "prepare_xpd_bind", "query_xpd_game_name", "confirm_xpd_bind", } ) PENDING_BINDING_TASK_TYPES = frozenset({"get_bind_qr"}) #: 订单仍可接收绑定证据的阶段。bound / completed / cancelled 一律冻结。 ACTIVE_BINDING_STATUSES = frozenset( { "not_started", "allocated", "preparing", "qr_pending", "waiting_bind", "role_ready", } ) #: 已归属本单的成功确认任务可以让这些状态重新收敛。failed 包含旧二维码已超时, #: 但精英宝典工作台随后已经确认成功的情况。 CONFIRM_EVIDENCE_BINDING_STATUSES = ACTIVE_BINDING_STATUSES | { "confirming", "failed", } #: 订单的权威绑定任务类型。查询任务只能展示,不能结算。 BINDING_EVIDENCE_TASK_TYPES = frozenset({"get_bind_qr", "confirm_bind"}) assert BINDING_EVIDENCE_TASK_TYPES <= BINDING_TASK_TYPES def _can_reuse_existing_account_binding( db: Session, *, task: PlatformFulfillmentTask, account: Account | None, ) -> str: """共享账号若已绑定到本单填写的同一客户角色(且有同租约/7天绑定依据),直接复用绑定。""" customer_role = str(task.customer_role_name or "").strip() if not customer_role or account is None or not task.lease_id: return "" if str(account.role_bind_status or "") != "bound": return "" account_role = str(account.game_name or "").strip() if not account_role or not role_names_match(account_role, customer_role): return "" sibling_bound = ( db.query(PlatformFulfillmentTask.id) .filter( PlatformFulfillmentTask.lease_id == int(task.lease_id), PlatformFulfillmentTask.account_id == int(account.id), PlatformFulfillmentTask.id != int(task.id), PlatformFulfillmentTask.execution_status != "cancelled", PlatformFulfillmentTask.binding_status == "bound", ) .first() ) if sibling_bound is not None: return account_role since = _now() - timedelta(days=7) recent_bind = ( db.query(AccountEvent.id) .filter( AccountEvent.account_id == int(account.id), AccountEvent.event_type == "bind_ok", AccountEvent.subject_type == "elite_role", AccountEvent.subject_key == account_role, AccountEvent.occurred_at >= since, ) .first() ) return account_role if recent_bind is not None else "" def _mark_same_role_reused_bound( db: Session, *, task: PlatformFulfillmentTask, account: Account, role_name: str, lease: AccountLease | None = None, source_task_id: int | None = None, ) -> None: resolved_lease = lease or _lease_for_task(db, task) task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" task.updated_at = _now() detail: dict[str, Any] = { "roleName": role_name[:128], "accountId": int(account.id), "accountName": account.nickname or account.username or "", "reason": "same_role_existing_account", } if source_task_id is not None: detail["sourcePlatformTaskId"] = int(source_task_id) _append_event( db, task.id, "binding_reused_same_role_account", detail=detail, ) _apply_task_lease_policy(db, task, lease=resolved_lease) _emit_order_site_binding_state(db, task.id) def _propagate_same_role_binding_to_siblings( db: Session, *, bound_task: PlatformFulfillmentTask, account: Account | None, role_name: str, ) -> int: """同租约主单绑定成功后,把同角色共享账号的其它在途履约单同步置为 bound。""" if ( not bound_task.lease_id or not bound_task.account_id or account is None or not role_name ): return 0 siblings = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.lease_id == int(bound_task.lease_id), PlatformFulfillmentTask.account_id == int(bound_task.account_id), PlatformFulfillmentTask.id != int(bound_task.id), PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), PlatformFulfillmentTask.binding_status.in_( ACTIVE_BINDING_STATUSES | {"confirming"} ), PlatformFulfillmentTask.customer_role_name != "", ) .all() ) updated = 0 for sibling in siblings: if not role_names_match(sibling.customer_role_name, role_name): continue _mark_same_role_reused_bound( db, task=sibling, account=account, role_name=role_name, source_task_id=int(bound_task.id), ) updated += 1 # 同角色如果有多单但之前因未填角色名被预分配到了不同账号, # 主单确认绑定后把未完成绑定的兄弟单自动释放旧空号并改挂到主账号。 cross_account_siblings = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN, PlatformFulfillmentTask.id != int(bound_task.id), PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.account_id != int(bound_task.account_id), PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), PlatformFulfillmentTask.binding_status.in_(ACTIVE_BINDING_STATUSES), PlatformFulfillmentTask.customer_role_name != "", func.lower(func.trim(PlatformFulfillmentTask.customer_role_name)) == role_name.casefold(), ) .order_by(PlatformFulfillmentTask.id.asc()) .with_for_update(skip_locked=True) .all() ) if cross_account_siblings: from .allocation import try_reallocate_task_to_same_role actor = _integration_actor(db) for sibling in cross_account_siblings: if try_reallocate_task_to_same_role( db, task=sibling, current=actor, role_name=role_name, preferred_account_id=int(bound_task.account_id), trigger="sibling_bound", commit=False, ): updated += 1 return updated def start_binding_sync( db: Session, *, task_id: int, current: User, force_refresh: bool = False, ) -> dict[str, Any]: task = _load_task_for_update(db, task_id) if not task.account_id or not task.lease_id: raise HTTPException(status_code=409, detail="请先分配账号") lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if lease is None or lease.status != "active": raise HTTPException(status_code=409, detail="账号租约已失效,请重新分配") account = db.query(Account).filter(Account.id == task.account_id).first() reused_role = _can_reuse_existing_account_binding( db, task=task, account=account, ) if reused_role and account is not None: if task.binding_status != "bound": task.operator_id = current.id _mark_same_role_reused_bound( db, task=task, account=account, role_name=reused_role, lease=lease, ) db.commit() return get_task_detail(db, task.id) if task.customer_role_name and task.binding_status != "bound": from .allocation import try_reallocate_task_to_same_role if try_reallocate_task_to_same_role( db, task=task, current=current, role_name=task.customer_role_name, trigger="start_binding", commit=True, ): if task.binding_status == "bound": return get_task_detail(db, task.id) lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) if lease is None or lease.status != "active": return get_task_detail(db, task.id) account = db.query(Account).filter(Account.id == task.account_id).first() if task.bind_task_id: existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if existing is not None and existing.platform_task_id not in ( None, int(task.id), ): # 当前指针指向了别的订单的任务:当作没有绑定任务,重新出码。 existing = None if existing: binding = resolve_fulfillment_binding( existing, account=db.get(Account, int(task.account_id)), binding_status=task.binding_status, ) stale_pending = ( binding.reported_ready_for_confirm and not binding.bind_ready_for_confirm ) if binding.status in { BINDING_VIEW_CONFIRMED, BINDING_VIEW_PENDING, }: return get_task_detail(db, task.id) if existing.status in {"planned", "pending", "running"}: return get_task_detail(db, task.id) if ( existing.status == "success" and not _binding_qr_expired(existing) and not stale_pending ): return get_task_detail(db, task.id) if not force_refresh and existing.status not in { "success", "failed", "error", "stopped", }: return get_task_detail(db, task.id) batch_id = f"pfbind-{task.id}-{uuid.uuid4().hex[:8]}" bind_task = DouyuTask( batch_id=batch_id, account_id=task.account_id, account_assigned_to=current.id, task_type="get_bind_qr", handbook_scope="elite", status="planned", message="等待生成绑定二维码", result={ "payload": {}, "expected_role_name": str(task.customer_role_name or "").strip(), "expected_role_required": True, }, created_by=current.id, platform_task_id=task.id, ) db.add(bind_task) try: db.flush() except IntegrityError: # The database uniqueness gate wins a race that started before either # request could acquire the fulfillment row lock. db.rollback() return get_task_detail(db, task_id) account = db.query(Account).filter(Account.id == task.account_id).first() if account is not None: record_douyu_task_started( db, account, task_id=int(bind_task.id), task_type="get_bind_qr", task_label="获取绑定二维码", scope="elite", actor_id=current.id, ) task.bind_task_id = bind_task.id task.binding_status = "preparing" task.execution_status = "waiting_bind" task.issue_code = "" task.last_error = "" task.operator_id = current.id task.updated_at = _now() _apply_task_lease_policy(db, task, lease=lease) _append_event( db, task.id, "binding_started", actor_type="user", actor_id=current.id, detail={"bindTaskId": bind_task.id}, ) _emit_order_site_binding_state(db, task.id) enqueue_execution_job( db, job_type=JOB_DOUYU_BINDING, lane_scope=LANE_FULFILLMENT, batch_id=batch_id, payload={ "task_type": "get_bind_qr", "payload": {}, "concurrency": 1, }, created_by=int(current.id), priority=10, max_attempts=2, ) db.commit() return get_task_detail(db, task.id) async def start_binding( db: Session, *, task_id: int, current: User, force_refresh: bool = False, ) -> dict[str, Any]: """Run the blocking DB/network dispatch path outside the ASGI event loop.""" return await run_in_threadpool( start_binding_sync, db, task_id=task_id, current=current, force_refresh=force_refresh, ) def _frozen(task: PlatformFulfillmentTask) -> bool: """已结束或已绑定的订单不再接受绑定证据回写。""" return ( task.execution_status in {"completed", "cancelled"} or task.binding_status == "bound" ) def _lease_for_task( db: Session, task: PlatformFulfillmentTask, ) -> AccountLease | None: return fulfillment_lease_for_task(db, task) def _pending_role_of(task: DouyuTask | None) -> str: if task is None or not isinstance(task.result, dict): return "" return pending_binding_role_from_result(task.result) def _owned_binding_tasks( db: Session, task: PlatformFulfillmentTask, *, newer_than: int = 0, ) -> list[DouyuTask]: if not task.account_id: return [] return ( db.query(DouyuTask) .filter( DouyuTask.platform_task_id == int(task.id), DouyuTask.account_id == int(task.account_id), DouyuTask.handbook_scope == "elite", DouyuTask.task_type.in_(BINDING_EVIDENCE_TASK_TYPES), DouyuTask.id > int(newer_than), ) .order_by(DouyuTask.id.desc()) .limit(8) .all() ) def sync_customer_role_to_bind_task( db: Session, task: PlatformFulfillmentTask, ) -> bool: """把客户最新提交的目标角色安全写入当前绑定任务并立即重算订单状态。""" customer_role = str(task.customer_role_name or "").strip() if not task.bind_task_id or not customer_role: return False bind_task = ( db.query(DouyuTask) .filter(DouyuTask.id == int(task.bind_task_id)) .with_for_update() .first() ) if bind_task is None or bind_task.task_type not in { "get_bind_qr", "confirm_bind", }: return False result = dict(bind_task.result or {}) result["expected_role_name"] = customer_role result["expected_role_required"] = True bind_task.result = result if ( not _frozen(task) and task.binding_status in ACTIVE_BINDING_STATUSES and bind_task.status == "success" ): return _apply_binding_task( db, task, bind_task, owned=bind_task.platform_task_id is not None, ) return False def _order_target_role( db: Session, task: PlatformFulfillmentTask, *, before_task_id: int | None = None, ) -> str: """订单本次要绑定的目标角色。 优先取当前绑定任务;当前任务已经是确认任务时,从订单自己更新的绑码任务里回看。 只用带订单归属的任务,不看账号历史。 """ current = db.get(DouyuTask, int(task.bind_task_id)) if task.bind_task_id else None role = _pending_role_of(current) if role: return role for row in _owned_binding_tasks(db, task): if before_task_id is not None and int(row.id) >= int(before_task_id): continue if row.status != "success": continue role = _pending_role_of(row) if role: return role return "" def _binding_target_mismatch_message( confirmed_role: str, expected_role: str, ) -> str: if expected_role: return ( f"确认绑定已生效:账号当前角色「{confirmed_role}」" f"与客户填写「{expected_role}」不一致。" "请点击“修改资料”,复制或采用平台当前角色后保存。" ) return ( f"确认绑定已生效:账号当前角色「{confirmed_role}」," "但订单缺少客户目标角色。请点击“修改资料”补齐后保存。" ) def _sync_confirmed_observation( db: Session, observation: DouyuTask, ) -> int: """用租期内更新的“当前已绑定”观测修正 stale 待确认订单。 查询任务本身仍不能替代 actBind;这里只接受同时满足以下条件的结果: - 动作 alias 已返回 bindAct=1; - 账号当前角色和角色绑定状态都已落到该角色; - 订单客户资料明确填写了同一角色; - 观测创建于该订单当前租约内,且晚于订单当前绑定任务。 """ if ( observation.status != "success" or observation.task_type not in BINDING_OBSERVATION_TASK_TYPES or not observation.account_id ): return 0 account = db.get(Account, int(observation.account_id)) if account is None: return 0 binding = resolve_douyu_binding(observation, account=account) if binding.status != BINDING_VIEW_CONFIRMED: return 0 confirmed_role = str(binding.confirmed_role_name or "").strip() if not confirmed_role: return 0 result = observation.result if isinstance(observation.result, dict) else {} action_aliases = { str(value or "").strip() for value in (result.get("action_act_aliases") or []) if str(value or "").strip() } selected_alias = str(result.get("act_alias") or "").strip() if action_aliases and selected_alias not in action_aliases: return 0 account_role = str(account.game_name or "").strip() if ( str(account.role_bind_status or "") != "bound" or not account_role or not role_names_match(account_role, confirmed_role) ): return 0 query = db.query(PlatformFulfillmentTask).filter( PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.account_id == int(observation.account_id), PlatformFulfillmentTask.binding_status == "role_ready", PlatformFulfillmentTask.execution_status.notin_( ("completed", "cancelled", "manual_required") ), PlatformFulfillmentTask.customer_role_name != "", ) if observation.platform_task_id: query = query.filter( PlatformFulfillmentTask.id == int(observation.platform_task_id) ) tasks = query.order_by(PlatformFulfillmentTask.id.desc()).limit(20).all() changed = 0 for task in tasks: target_role = str(task.customer_role_name or "").strip() if not target_role or not role_names_match(target_role, confirmed_role): if observation.platform_task_id: _record_binding_rejection( db, task, observation, reason="target_mismatch" if target_role else "missing_target", confirmed_role=confirmed_role, target_role=target_role, ) continue lease = _lease_for_task(db, task) if ( not lease_is_active(lease) or not source_created_within_lease(lease, observation) or int(observation.id) <= int(task.bind_task_id or 0) ): continue if _block_on_role_lock(db, task, confirmed_role, observation): changed += 1 continue if _block_on_account_lock(db, task, confirmed_role, observation): changed += 1 continue previous_bind_task_id = task.bind_task_id task.bind_task_id = int(observation.id) task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_confirmed_from_observation", detail={ "sourceTaskId": int(observation.id), "sourceTaskType": str(observation.task_type or ""), "previousBindTaskId": previous_bind_task_id, "confirmedRoleName": confirmed_role[:128], "targetRoleName": target_role[:128], "accountId": int(account.id), "accountName": account.nickname or account.username, "accountRoleName": account_role[:128], }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) _propagate_same_role_binding_to_siblings( db, bound_task=task, account=account, role_name=confirmed_role, ) changed += 1 return changed def _latest_observations_for_task( db: Session, task: PlatformFulfillmentTask, *, limit: int = 20, ) -> list[DouyuTask]: if not task.account_id: return [] return ( db.query(DouyuTask) .filter( DouyuTask.account_id == int(task.account_id), DouyuTask.task_type.in_(BINDING_OBSERVATION_TASK_TYPES), DouyuTask.status == "success", DouyuTask.id > int(task.bind_task_id or 0), ( (DouyuTask.platform_task_id == int(task.id)) | DouyuTask.platform_task_id.is_(None) ), ) .order_by(DouyuTask.id.desc()) .limit(max(1, int(limit))) .all() ) def _record_mismatched_scan_events( db: Session, task: PlatformFulfillmentTask, source: DouyuTask, ) -> bool: """把扫码出现的不匹配角色写入时间线(按任务+角色+区服去重)。""" result = source.result if isinstance(source.result, dict) else {} entries = [ item for item in (result.get("mismatched_roles") or []) if isinstance(item, dict) and str(item.get("role_name") or "").strip() ] last_entry = result.get("last_mismatched_role") if ( not entries and isinstance(last_entry, dict) and str(last_entry.get("role_name") or "").strip() ): entries = [last_entry] if not entries: return False existing_events = ( db.query(PlatformFulfillmentEvent.detail_json) .filter( PlatformFulfillmentEvent.task_id == int(task.id), PlatformFulfillmentEvent.event_type == "binding_scanned_role_mismatch", ) .order_by(PlatformFulfillmentEvent.id.desc()) .limit(50) .all() ) seen: set[tuple[int, str, str]] = set() for row in existing_events: detail = row[0] if isinstance(row[0], dict) else {} try: src_id = int(detail.get("sourceTaskId") or 0) except (TypeError, ValueError): src_id = 0 seen.add( ( src_id, str(detail.get("scannedRoleName") or "").strip().casefold(), str(detail.get("channel") or "").strip(), ) ) appended = False for entry in entries: scanned_role = str(entry.get("role_name") or "").strip() if not scanned_role: continue area_name = str(entry.get("area_name") or "").strip() plat_name = str(entry.get("plat_name") or "").strip() channel = " / ".join(part for part in (area_name, plat_name) if part) key = (int(source.id), scanned_role.casefold(), channel) if key in seen: continue seen.add(key) expected_role = str( entry.get("expected_role_name") or task.customer_role_name or "" ).strip() _append_event( db, task.id, "binding_scanned_role_mismatch", detail={ "sourceTaskId": int(source.id), "sourceTaskType": str(source.task_type or ""), "scannedRoleName": scanned_role[:128], "expectedRoleName": expected_role[:128], "channel": channel[:128], "actAlias": str(entry.get("act_alias") or "")[:64], }, ) appended = True return appended def _record_binding_rejection( db: Session, task: PlatformFulfillmentTask, source: DouyuTask, *, reason: str, confirmed_role: str = "", target_role: str = "", ) -> None: """记录一条不采纳的绑定证据;不改变订单状态,供时间线排查。""" exists = ( db.query(PlatformFulfillmentEvent.id) .filter( PlatformFulfillmentEvent.task_id == int(task.id), PlatformFulfillmentEvent.event_type == "binding_sync_rejected", PlatformFulfillmentEvent.detail_json["sourceTaskId"].as_integer() == int(source.id), ) .first() ) if exists is not None: return _append_event( db, task.id, "binding_sync_rejected", detail={ "sourceTaskId": int(source.id), "sourceTaskType": str(source.task_type or ""), "reason": reason, "confirmedRoleName": confirmed_role[:128], "targetRoleName": target_role[:128], "bindingStatus": task.binding_status, "executionStatus": task.execution_status, }, ) def _mark_role_locked( db: Session, task: PlatformFulfillmentTask, source: DouyuTask | None, lock: RoleLock, ) -> bool: """角色 7 天内已绑定其他账号:转人工,不调 actBind。""" if str(task.issue_code or "") == ROLE_LOCK_ISSUE: return False message = lock.message() lease = _lease_for_task(db, task) if source is not None and int(source.id) > int(task.bind_task_id or 0): # 保留本次待确认任务,详情/时间线能看到尝试的角色;状态已转人工, # 不会因为 bind_task_id 变化被自动推回 role_ready。 task.bind_task_id = int(source.id) task.binding_status = "failed" task.execution_status = "manual_required" task.issue_code = ROLE_LOCK_ISSUE task.last_error = message task.updated_at = _now() detail = { "roleName": lock.role_name, "roleLockAccountId": lock.account_id, "roleLockAccountName": lock.account_name, "roleLockBoundAt": lock.bound_at.isoformat(), "roleLockReusableAt": lock.reusable_at.isoformat(), "roleLockLeasePurpose": lock.lease_purpose, "roleLockLeaseBatchId": lock.lease_batch_id, "allocatedAccountId": task.account_id, "message": message, } if source is not None: detail["sourceTaskId"] = int(source.id) detail["sourceTaskType"] = str(source.task_type or "") _append_event(db, task.id, "binding_role_locked_elsewhere", detail=detail) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True def _mark_account_locked( db: Session, task: PlatformFulfillmentTask, source: DouyuTask | None, lock: AccountLock, ) -> bool: """当前分配的账号 7 天内绑过别的角色:转人工,不调 actBind。""" if str(task.issue_code or "") == ACCOUNT_LOCK_ISSUE: return False message = lock.message() lease = _lease_for_task(db, task) if source is not None and int(source.id) > int(task.bind_task_id or 0): task.bind_task_id = int(source.id) task.binding_status = "failed" task.execution_status = "manual_required" task.issue_code = ACCOUNT_LOCK_ISSUE task.last_error = message task.updated_at = _now() detail = { "accountRoleName": lock.role_name, "accountBoundAt": lock.bound_at.isoformat(), "accountReusableAt": lock.reusable_at.isoformat(), "allocatedAccountId": task.account_id, "allocatedAccountName": lock.account_name, "message": message, } if source is not None: detail["sourceTaskId"] = int(source.id) detail["sourceTaskType"] = str(source.task_type or "") _append_event(db, task.id, "binding_account_locked_elsewhere", detail=detail) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True def _block_on_account_lock( db: Session, task: PlatformFulfillmentTask, role_name: str, source: DouyuTask | None = None, ) -> bool: if str(task.issue_code or "") == ACCOUNT_LOCK_ISSUE: return False lock = find_account_lock(db, task.account_id, role_name) if lock is None: return False return _mark_account_locked(db, task, source, lock) def _block_on_role_lock( db: Session, task: PlatformFulfillmentTask, role_name: str, source: DouyuTask | None = None, ) -> bool: """角色已绑在别的账号上时,优先尝试同角色合并改挂,否则把订单转人工。""" if str(task.issue_code or "") == ROLE_LOCK_ISSUE: return False lock = find_role_lock( db, role_name, current_account_id=task.account_id, ) if lock is None: return False from .allocation import try_reallocate_task_to_same_role if try_reallocate_task_to_same_role( db, task=task, current=_integration_actor(db), role_name=role_name, preferred_account_id=int(lock.account_id), allow_pending_role_ready=True, trigger="role_lock_redirect", commit=False, ): return True return _mark_role_locked(db, task, source, lock) def _apply_binding_qr_display( db: Session, task: PlatformFulfillmentTask, source: DouyuTask, *, owned: bool, is_current: bool, phase: str, lease: AccountLease, ) -> bool: """运行中/成功的绑码任务只推进二维码展示,不推进角色状态。""" result = source.result if isinstance(source.result, dict) else {} qr_url = str(result.get("url") or "") if not qr_url or phase == "confirming": return False if not (is_current or (owned and phase in ACTIVE_BINDING_STATUSES)): return False if task.binding_status == "qr_pending" and int(task.bind_task_id or 0) == int( source.id ): return False task.bind_task_id = int(source.id) task.binding_status = "qr_pending" task.execution_status = "waiting_bind" task.issue_code = "" task.last_error = "" task.updated_at = _now() _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True def _same_pair_reuse_role( result: dict[str, Any] | None, account: Account | None, *, customer_role_name: str = "", task_status: str = "", ) -> str: """本次扫码角色已经绑在当前账号上:同一对,直接复用。 只认 **cjm/legacy 上出现的扫码角色**,并且要求动作 alias 上也是同一个 角色且 bindAct=1。动作 alias 上只要出现 bindAct=0 的 pending,就说明客户 扫的是新角色,必须走正常确认,不能复用旧角色。 """ if not isinstance(result, dict) or account is None: return "" # 发码预检/轮询未变化阶段绝不复用账号历史角色,必须等扫码完成或观测到扫码变化。 if ( task_status and task_status != "success" and not bool(result.get("bind_poll_legacy_observed_change")) ): return "" if str(account.role_bind_status or "") != "bound": return "" current = str(account.game_name or "").strip() if not current: return "" customer_role = str(customer_role_name or "").strip() if bool(result.get("expected_role_required")) and not customer_role: return "" if customer_role and not role_names_match(current, customer_role): return "" raw_aliases = result.get("action_act_aliases") action_aliases = ( [str(value).strip() for value in raw_aliases if str(value).strip()] if isinstance(raw_aliases, (list, tuple)) else [] ) candidates = [ raw for raw in (result.get("bind_candidates") or []) if isinstance(raw, dict) ] action_candidates = [ raw for raw in candidates if str(raw.get("act_alias") or raw.get("alias") or "").strip() in action_aliases ] if any( str(raw.get("role_name") or "").strip() and not bool(raw.get("is_bound_act")) for raw in action_candidates ): # 动作 alias 上已有新的 pending:客户扫了新角色,交给正常确认。 return "" selected_alias = str(result.get("act_alias") or "").strip() legacy_role = next( ( str(raw.get("role_name") or "").strip() for raw in candidates if str(raw.get("act_alias") or raw.get("alias") or "").strip() not in action_aliases and str(raw.get("role_name") or "").strip() ), "", ) if selected_alias and selected_alias in action_aliases: scanned_role = legacy_role else: scanned_role = str( result.get("pending_role_name") or result.get("role_name") or legacy_role or "" ).strip() if not scanned_role or scanned_role != current: return "" if action_candidates: action_bound = any( str(raw.get("role_name") or "").strip() == current and bool(raw.get("is_bound_act")) for raw in action_candidates ) return current if action_bound else "" if (not action_aliases or selected_alias not in action_aliases) and str( result.get("current_role_name") or "" ).strip() == current: return current return "" def _mark_reused_pair( db: Session, task: PlatformFulfillmentTask, source: DouyuTask, *, role_name: str, account: Account | None, ) -> bool: lease = _lease_for_task(db, task) task.bind_task_id = int(source.id) task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_reused_existing_pair", detail={ "roleName": role_name[:128], "accountId": task.account_id, "accountName": ( (account.nickname or account.username) if account is not None else "" ), "sourceTaskId": int(source.id), "sourceTaskType": str(source.task_type or ""), "reason": "same_account_same_role", }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) _propagate_same_role_binding_to_siblings( db, bound_task=task, account=account, role_name=role_name, ) return True def operator_confirm_binding_sync( db: Session, *, task_id: int, current: User, ) -> dict[str, Any]: """普通人工代确认:客户已扫码但没点确认,运营代为提交正常 actBind。 不填写角色/备注,不直接标 bound;复用客户确认的同一套确认任务。 当前没有可确认的扫码角色时,要求客户重新扫码。 """ task = _load_task_for_update(db, task_id) if _frozen(task): return get_task_detail(db, task.id) refresh_binding(db, task_id=task.id) task = _load_task(db, task.id) if task.binding_status == "bound": return get_task_detail(db, task.id) if task.binding_status != "role_ready": raise HTTPException( status_code=409, detail="当前没有可代确认的扫码角色,请让客户先扫码。", ) return confirm_binding_sync(db, task_id=task.id, current=current) def _apply_binding_task( db: Session, task: PlatformFulfillmentTask, source: DouyuTask, *, owned: bool, ) -> bool: """把一条绑定任务合并进订单状态。 ``owned=True``:任务带 ``platform_task_id == task.id``,是订单自己的证据; ``owned=False``:只允许订单当前已经挂着的任务(兼容旧数据)。 """ if _frozen(task): return False if str(task.issue_code or "") in {ROLE_LOCK_ISSUE, ACCOUNT_LOCK_ISSUE}: # 7 天锁只能由人工重置后重新进入流程。 return False if not task.account_id or not source.account_id: return False if int(source.account_id) != int(task.account_id): return False if str(source.handbook_scope or "") != "elite": return False lease = _lease_for_task(db, task) if not lease_is_active(lease): return False if not owned and not source_created_within_lease(lease, source): return False if ( not owned and source.platform_task_id is not None and int(source.platform_task_id) != int(task.id) ): # 明确属于另一张订单的任务,不能写到本单。 return False phase = str(task.binding_status or "") is_current = bool(task.bind_task_id) and int(task.bind_task_id) == int(source.id) if not owned and not is_current: return False if not is_current and int(source.id) < int(task.bind_task_id or 0): return False account = db.get(Account, int(task.account_id)) if str(source.task_type or "") == "get_bind_qr" and phase != "confirming": reused_role = _same_pair_reuse_role( source.result, account, customer_role_name=str(task.customer_role_name or ""), task_status=str(source.status or ""), ) if reused_role: return _mark_reused_pair( db, task, source, role_name=reused_role, account=account, ) binding = resolve_fulfillment_binding( source, account=account, binding_status=phase, ) result = source.result if isinstance(source.result, dict) else {} previous_bind_task_id = task.bind_task_id mismatch_recorded = _record_mismatched_scan_events(db, task, source) if source.status in {"failed", "error", "stopped"}: # 只有订单当前挂着的任务失败才允许判失败;工作台额外任务失败不能打死订单。 if not is_current: return mismatch_recorded if phase not in ACTIVE_BINDING_STATUSES | {"confirming", "failed"}: return mismatch_recorded issue_code = _binding_failure_issue(source, result) if ( task.binding_status == "failed" and task.issue_code == issue_code and int(task.bind_task_id or 0) == int(source.id) ): return mismatch_recorded task.binding_status = "failed" task.execution_status = "manual_required" task.issue_code = issue_code last_mismatch = result.get("last_mismatched_role") mismatched_name = ( str(last_mismatch.get("role_name") or "").strip() if isinstance(last_mismatch, dict) else "" ) expected_name = str( ( last_mismatch.get("expected_role_name") if isinstance(last_mismatch, dict) else "" ) or task.customer_role_name or "" ).strip() if issue_code == "binding_failed" and mismatched_name: task.last_error = ( f"已扫到角色「{mismatched_name}」,与下单填写的「{expected_name}」不一致,请核对后修改资料或重扫" if expected_name else f"已扫到不匹配角色「{mismatched_name}」,请核对后重扫" ) else: task.last_error = _customer_task_message(task) task.updated_at = _now() _append_event( db, task.id, "binding_failed", detail={ "issueCode": task.issue_code, "bindTaskId": int(source.id), "bindPhase": str(result.get("bind_phase") or ""), "rawError": _binding_failure_raw_message( task.issue_code, result, fallback=str(source.message or ""), )[:1000], }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True if source.status != "success": # 运行中的绑码任务可以展示二维码,但不能据此推进角色/结算。 return ( _apply_binding_qr_display( db, task, source, owned=owned, is_current=is_current, phase=phase, lease=lease, ) or mismatch_recorded ) if binding.status == BINDING_VIEW_CONFIRMED: confirmed_role = binding.confirmed_role_name customer_role = str(task.customer_role_name or "").strip() explicit_expected = str(result.get("expected_role_name") or "").strip() target_role = _order_target_role( db, task, before_task_id=int(source.id) if source.task_type == "confirm_bind" else None, ) expected_role = customer_role or explicit_expected or target_role if is_current: # 订单自己的当前任务(订单创建的或兼容路径挂上的)回查到 bindAct=1。 # 查询类任务不会走到这里:resolve_fulfillment_binding 会把观测降级。 accepted = source.task_type in BINDING_EVIDENCE_TASK_TYPES and ( not expected_role or role_names_match(confirmed_role, expected_role) ) elif not owned: accepted = False elif phase == "confirming": # 订单已经在确认中,只认它自己当前那条确认任务。 accepted = False elif source.task_type == "confirm_bind": accepted = ( phase in CONFIRM_EVIDENCE_BINDING_STATUSES and bool(expected_role) and role_names_match(confirmed_role, expected_role) ) else: # 订单自己的绑码任务直接被官网确认:有目标时必须一致,无目标视为全新绑定。 accepted = phase in ACTIVE_BINDING_STATUSES and ( not expected_role or role_names_match(confirmed_role, expected_role) ) if not accepted: reason = ( "target_mismatch" if expected_role and not role_names_match(confirmed_role, expected_role) else "missing_target" ) if ( source.task_type == "confirm_bind" and (owned or is_current) and phase in CONFIRM_EVIDENCE_BINDING_STATUSES ): message = _binding_target_mismatch_message( confirmed_role, expected_role, ) if ( int(task.bind_task_id or 0) == int(source.id) and task.binding_status == "role_ready" and task.last_error == message ): return False # 确认动作已经成功,旧 QR 指针必须让位。这里不宣告订单绑定完成, # 而是把实际角色交给运营核对;修改客户资料后会再次结算为 bound。 task.bind_task_id = int(source.id) task.binding_status = "role_ready" task.execution_status = "role_ready" task.issue_code = "" task.last_error = message task.updated_at = _now() _record_binding_rejection( db, task, source, reason=reason, confirmed_role=confirmed_role, target_role=expected_role, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True _record_binding_rejection( db, task, source, reason=( reason if reason != "missing_target" else "untrusted_confirmation" ), confirmed_role=confirmed_role, target_role=expected_role, ) return False task.bind_task_id = int(source.id) task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_confirmed", detail={ "bindTaskId": int(source.id), "previousBindTaskId": previous_bind_task_id, "sourceTaskType": str(source.task_type or ""), "baselineRoleName": str( result.get("baseline_role_name") or result.get("current_role_name") or "" )[:128], "targetRoleName": expected_role[:128], "confirmedRoleName": confirmed_role[:128], "confirmedChannel": binding.confirmed_channel, }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) _propagate_same_role_binding_to_siblings( db, bound_task=task, account=account, role_name=confirmed_role, ) return True if binding.status == BINDING_VIEW_PENDING: role_name = binding.pending_role_name if not role_name: return False # cjm/legacy 先出现的新角色也进入 role_ready:客户页需要能看到角色并 # 发起确认;确认执行器会在 actBind 前重新查询 QYOOB,若动作通道尚未 # 同步会返回可重试失败,而不是让客户卡在“没有待确认角色”。 if phase == "confirming": # 确认任务执行中,后到的扫码结果不能把订单打回待确认、丢掉确认任务指针。 return False if not is_current and phase not in ACTIVE_BINDING_STATUSES: return False if ( task.binding_status == "role_ready" and int(task.bind_task_id or 0) == int(source.id) and not task.issue_code and not task.last_error ): return False if _block_on_role_lock(db, task, role_name, source): return True if _block_on_account_lock(db, task, role_name, source): return True task.bind_task_id = int(source.id) task.binding_status = "role_ready" task.execution_status = "role_ready" task.issue_code = "" task.last_error = "" task.updated_at = _now() if previous_bind_task_id != source.id: _append_event( db, task.id, "binding_pending_task_linked", detail={ "bindTaskId": int(source.id), "previousBindTaskId": previous_bind_task_id, "roleName": role_name[:128], "source": "owned" if owned else "legacy-current", }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True decision = result.get("bind_decision") decision_reason = ( str(decision.get("reason") or "") if isinstance(decision, dict) else "" ) same_role_stale = decision_reason.startswith("same_role_stale") or ( not decision_reason and str(result.get("role_name") or "").strip() == str(result.get("baseline_role_name") or "").strip() ) if ( is_current and str(source.task_type or "") == "get_bind_qr" and bool(result.get("bind_ready_for_confirm")) and not _pending_role_of(source) and same_role_stale ): # 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针,让客户页重新出码。 task.bind_task_id = None task.binding_status = "not_started" task.execution_status = "allocated" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_stale_role_ignored", detail={ "bindTaskId": int(source.id), "previousBindTaskId": previous_bind_task_id, "roleName": str(result.get("role_name") or "")[:100], "baselineRoleName": str( result.get("baseline_role_name") or result.get("current_role_name") or "" )[:100], }, ) _emit_order_site_binding_state(db, task.id) _apply_task_lease_policy(db, task, lease=lease) return True return _apply_binding_qr_display( db, task, source, owned=owned, is_current=is_current, phase=phase, lease=lease, ) def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: """从订单当前挂着的绑定任务刷新订单状态。 只消费订单自己的证据:当前 ``bind_task_id`` 指向的任务、以及显式带 ``platform_task_id`` 的任务。账号上的其它任务不能改写订单。 """ task = _load_task(db, task_id) if _frozen(task): return get_task_detail(db, task.id) # 精英宝典等外部入口可能先创建确认任务,履约订单仍指向更早的扫码任务。 # 刷新时必须主动吸收更新、已归属本单的成功证据,不能只盯着旧指针。 for evidence in _owned_binding_tasks( db, task, newer_than=int(task.bind_task_id or 0), ): if evidence.status != "success": continue if _apply_binding_task(db, task, evidence, owned=True): db.commit() return get_task_detail(db, task.id) if task.binding_status in ACTIVE_BINDING_STATUSES: latest_pending = _latest_pending_binding_task(db, task) if latest_pending is not None and _attach_pending_binding_task( db, task, latest_pending, ): db.commit() task = _load_task(db, task.id) if not task.bind_task_id: return get_task_detail(db, task.id) bind_task = ( db.query(DouyuTask).filter(DouyuTask.id == int(task.bind_task_id)).first() ) if bind_task is None: return get_task_detail(db, task.id) if bind_task.platform_task_id not in (None, int(task.id)): # 数据异常:当前指针指向了别的订单的任务。只记录,不据此改状态。 _record_binding_rejection( db, task, bind_task, reason="foreign_current_task", ) db.commit() return get_task_detail(db, task.id) if ( task.binding_status == "role_ready" and task.account_id and str(task.customer_role_name or "").strip() ): for observation in _latest_observations_for_task(db, task): if _sync_confirmed_observation(db, observation): db.commit() return get_task_detail(db, task.id) owned = bind_task.platform_task_id is not None _apply_binding_task(db, task, bind_task, owned=owned) db.commit() return get_task_detail(db, task.id) def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: """斗鱼绑定任务落库后,把订单自己的绑定证据合并回履约任务。""" douyu_task = db.get(DouyuTask, int(douyu_task_id)) if ( douyu_task is None or not douyu_task.account_id or douyu_task.task_type not in BINDING_SYNC_TASK_TYPES or str(douyu_task.handbook_scope or "") != "elite" ): # 电竞/和平小店任务与精英履约是不同作用域,绝不互相投影。 return 0 linked_task_ids = [ int(row.id) for row in ( db.query(PlatformFulfillmentTask.id) .filter(PlatformFulfillmentTask.bind_task_id == int(douyu_task.id)) .all() ) ] for task_id in linked_task_ids: refresh_binding(db, task_id=task_id) changed = len(linked_task_ids) if douyu_task.task_type in BINDING_OBSERVATION_TASK_TYPES: # 普通观测不能代替确认;只有“动作 alias 已绑 + 账号当前角色 + 客户目标” # 三者同时一致的租期内观测,才允许修正 stale 待确认订单。 changed += _sync_confirmed_observation(db, douyu_task) if changed: db.commit() return changed if douyu_task.platform_task_id: task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == int(douyu_task.platform_task_id)) .with_for_update() .first() ) if ( task is not None and task.id not in linked_task_ids and task.account_id and int(task.account_id) == int(douyu_task.account_id) and not _frozen(task) and _apply_binding_task(db, task, douyu_task, owned=True) ): db.commit() changed += 1 return changed # 兼容旧数据:部署前创建、没有 platform_task_id 的工作台绑定任务。 if ( str(douyu_task.task_type or "") == "get_bind_qr" and douyu_task.status == "success" ): binding = resolve_fulfillment_binding( douyu_task, account=db.get(Account, int(douyu_task.account_id)), binding_status="role_ready", ) if binding.status == BINDING_VIEW_PENDING: active_task = ( db.query(PlatformFulfillmentTask) .join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id) .filter( PlatformFulfillmentTask.account_id == int(douyu_task.account_id), PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.binding_status.in_(ACTIVE_BINDING_STATUSES), PlatformFulfillmentTask.execution_status.notin_( ("completed", "cancelled", "manual_required") ), AccountLease.status == "active", AccountLease.purpose == "platform_fulfillment", ) .order_by( PlatformFulfillmentTask.updated_at.desc(), PlatformFulfillmentTask.id.desc(), ) .with_for_update() .first() ) if active_task is not None and _attach_pending_binding_task( db, active_task, douyu_task, ): _apply_task_lease_policy(db, active_task) _emit_order_site_binding_state(db, active_task.id) db.commit() changed += 1 return changed if ( str(douyu_task.task_type or "") == "confirm_bind" and douyu_task.status == "success" ): changed += sync_active_task_from_account_binding( db, account_id=int(douyu_task.account_id), scope=str(douyu_task.handbook_scope or ""), source_task_id=int(douyu_task.id), ) return changed def _revert_false_same_pair_reuse( db: Session, *, limit: int = 500, ) -> int: """纠偏被预检同对复用误锁为 bound 的未履约订单(未完成兑换且绑定角色 != 客户目标)。""" rows = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.bind_task_id.isnot(None), PlatformFulfillmentTask.binding_status == "bound", PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), PlatformFulfillmentTask.exchange_status.notin_( ("succeeded", "locked", "submitting") ), PlatformFulfillmentTask.customer_role_name != "", ) .order_by(PlatformFulfillmentTask.id.desc()) .limit(max(1, min(limit, 1000))) .all() ) reverted = 0 for task in rows: bind_task = db.get(DouyuTask, int(task.bind_task_id)) if bind_task is None or str(bind_task.task_type or "") != "get_bind_qr": continue result = bind_task.result if isinstance(bind_task.result, dict) else {} if bool(result.get("bind_confirmed")) or bool(result.get("manual_confirmed")): continue reuse_event = ( db.query(PlatformFulfillmentEvent) .filter( PlatformFulfillmentEvent.task_id == int(task.id), PlatformFulfillmentEvent.event_type == "binding_reused_existing_pair", ) .order_by(PlatformFulfillmentEvent.id.desc()) .first() ) if reuse_event is None: continue reused_role = str((reuse_event.detail_json or {}).get("roleName") or "").strip() customer_role = str(task.customer_role_name or "").strip() if not customer_role or ( reused_role and role_names_match(reused_role, customer_role) ): continue lease = _lease_for_task(db, task) task.binding_status = "qr_pending" task.execution_status = "waiting_bind" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_false_reuse_reverted", detail={ "bindTaskId": int(bind_task.id), "reusedRoleName": reused_role[:128], "customerRoleName": customer_role[:128], }, ) applied = _apply_binding_task( db, task, bind_task, owned=bind_task.platform_task_id is not None, ) if not applied: _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) reverted += 1 return reverted def reconcile_binding_observations( db: Session, *, limit: int = 500, ) -> int: """启动时收敛已落库但回调丢失的绑定证据。 只处理订单自己的证据(``platform_task_id``)和兼容路径的旧待确认任务; 账号上的查询任务不再参与订单结算。 """ reconciled = _revert_false_same_pair_reuse(db, limit=limit) tasks = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.binding_status.in_( tuple(ACTIVE_BINDING_STATUSES) + ("confirming", "failed") ), PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), ) .order_by( # role_ready 订单最可能已有新观测可自愈;先处理它们,避免 # 大量历史 failed/manual_required 订单把固定 limit 的名额占满。 case((PlatformFulfillmentTask.binding_status == "role_ready", 0), else_=1), # 其余状态优先收敛最近更新的订单。生产有上千条失败/待扫码历史, # 按 id 正序会把刚确认的新订单挡在启动对账窗口之外。 PlatformFulfillmentTask.updated_at.desc(), PlatformFulfillmentTask.id.desc(), ) .limit(max(1, min(limit, 2000))) .all() ) for task in tasks: if _frozen(task): continue changed = False if ( task.binding_status == "role_ready" and task.account_id and str(task.customer_role_name or "").strip() and any( _sync_confirmed_observation(db, observation) for observation in _latest_observations_for_task(db, task) ) ): changed = True if changed: reconciled += 1 continue current = ( db.get(DouyuTask, int(task.bind_task_id)) if task.bind_task_id else None ) if ( current is not None and current.status == "success" and current.platform_task_id in (None, int(task.id)) ): changed = _apply_binding_task( db, task, current, owned=current.platform_task_id is not None, ) if not changed: for evidence in _owned_binding_tasks( db, task, newer_than=int(task.bind_task_id or 0), ): if evidence.status != "success": continue if _apply_binding_task(db, task, evidence, owned=True): changed = True break if not changed and task.binding_status in ACTIVE_BINDING_STATUSES: latest_pending = _latest_pending_binding_task(db, task) if latest_pending is not None and _attach_pending_binding_task( db, task, latest_pending, ): changed = True if not changed and task.binding_status == "role_ready": # 部署前已经 role_ready 的订单:启动时补一次角色 7 天锁检查。 target_role_name = _order_target_role(db, task) if target_role_name and ( _block_on_role_lock( db, task, target_role_name, current, ) or _block_on_account_lock( db, task, target_role_name, current, ) ): changed = True if changed: reconciled += 1 if reconciled: db.commit() return reconciled def _latest_pending_binding_task( db: Session, task: PlatformFulfillmentTask, ) -> DouyuTask | None: if not task.account_id or task.binding_status not in ACTIVE_BINDING_STATUSES: return None lease = _lease_for_task(db, task) if not lease_is_active(lease): return None rows = ( db.query(DouyuTask) .filter( DouyuTask.account_id == int(task.account_id), DouyuTask.task_type.in_(PENDING_BINDING_TASK_TYPES), DouyuTask.handbook_scope == "elite", DouyuTask.status == "success", DouyuTask.id > int(task.bind_task_id or 0), ( (DouyuTask.platform_task_id == int(task.id)) | DouyuTask.platform_task_id.is_(None) ), ) .order_by(DouyuTask.id.desc()) .limit(20) .all() ) account = db.get(Account, int(task.account_id)) for row in rows: if not source_created_within_lease(lease, row): continue binding = resolve_douyu_binding(row, account=account) if binding.status != BINDING_VIEW_PENDING: continue return row return None def _attach_pending_binding_task( db: Session, task: PlatformFulfillmentTask, bind_task: DouyuTask, ) -> bool: account = db.get(Account, int(task.account_id)) if task.account_id else None lease = _lease_for_task(db, task) binding = resolve_douyu_binding(bind_task, account=account) if ( task.binding_status not in ACTIVE_BINDING_STATUSES or not task.account_id or int(bind_task.account_id or 0) != int(task.account_id) or bind_task.task_type not in PENDING_BINDING_TASK_TYPES or binding.status != BINDING_VIEW_PENDING or not lease_is_active(lease) or not source_created_within_lease(lease, bind_task) or ( bind_task.platform_task_id is not None and int(bind_task.platform_task_id) != int(task.id) ) ): return False customer_role = str(task.customer_role_name or "").strip() if customer_role and not role_names_match(binding.pending_role_name, customer_role): return False current_id = int(task.bind_task_id or 0) if int(bind_task.id) == current_id: return False if current_id and int(bind_task.id) < current_id: return False if str(task.issue_code or "") == ROLE_LOCK_ISSUE: return False if _block_on_role_lock(db, task, binding.pending_role_name, bind_task): return True if _block_on_account_lock(db, task, binding.pending_role_name, bind_task): return True previous_bind_task_id = task.bind_task_id task.bind_task_id = int(bind_task.id) task.binding_status = "role_ready" task.execution_status = "role_ready" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_pending_task_linked", detail={ "bindTaskId": int(bind_task.id), "previousBindTaskId": previous_bind_task_id, "roleName": binding.pending_role_name, "source": "account_workbench", }, ) _emit_order_site_binding_state(db, task.id) return True def sync_active_task_from_account_binding( db: Session, *, account_id: int, scope: str, source_task_id: int | None = None, ) -> int: """兼容旧流程:精英宝典工作台的无归属确认任务结算当前待确认订单。 必须同时满足:订单还在 role_ready、确认任务创建于本订单租约期间、 确认角色等于订单当前待确认角色。任何一条不满足都不改订单,只记录 ``binding_sync_rejected``。 """ if scope != "elite": return 0 source_task = ( db.get(DouyuTask, int(source_task_id)) if source_task_id is not None else None ) if ( source_task is None or source_task.status != "success" or str(source_task.task_type or "") != "confirm_bind" ): return 0 account = db.get(Account, int(account_id)) binding = resolve_douyu_binding(source_task, account=account) if binding.status != BINDING_VIEW_CONFIRMED: return 0 task = ( db.query(PlatformFulfillmentTask) .join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id) .filter( PlatformFulfillmentTask.account_id == int(account_id), PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.binding_status == "role_ready", PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), AccountLease.status == "active", AccountLease.purpose == "platform_fulfillment", ) .order_by( PlatformFulfillmentTask.updated_at.desc(), PlatformFulfillmentTask.id.desc(), ) .with_for_update() .first() ) if task is None: return 0 lease = _lease_for_task(db, task) if not lease_is_active(lease) or not source_created_within_lease( lease, source_task, ): _record_binding_rejection( db, task, source_task, reason="source_outside_lease", confirmed_role=binding.confirmed_role_name, ) db.commit() return 0 target_role = _order_target_role(db, task, before_task_id=int(source_task.id)) if not target_role or not role_names_match( binding.confirmed_role_name, target_role, ): _record_binding_rejection( db, task, source_task, reason="target_mismatch" if target_role else "missing_target", confirmed_role=binding.confirmed_role_name, target_role=target_role, ) db.commit() return 0 task.bind_task_id = int(source_task.id) task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_synced_from_account", detail={ "accountId": int(account_id), "accountName": ( account.nickname or account.username if account is not None else "" ), "roleName": binding.confirmed_role_name, "gameChannel": ( binding.confirmed_channel or binding.effective_channel or binding.current_channel ), "targetRoleName": target_role, "sourceTaskId": int(source_task.id), "roleChangeAvailableAt": ( account.role_change_available_at.isoformat() if account is not None and account.role_change_available_at else None ), }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) db.commit() return 1 def requires_account_binding_sync(task_type: str) -> bool: return str(task_type or "") in BINDING_SYNC_TASK_TYPES def reconcile_binding_state_outbox( db: Session, *, limit: int = 500, after_task_id: int = 0, ) -> dict[str, Any]: """按 ID 游标补齐 active 快照;批次只限制吞吐,不形成永久扫描窗口。""" batch_size = max(1, min(limit, 500)) normalized_after = max(0, int(after_task_id or 0)) task_ids = [ int(row.id) for row in ( db.query(PlatformFulfillmentTask.id) .filter( PlatformFulfillmentTask.id > normalized_after, PlatformFulfillmentTask.execution_status.notin_( ["completed", "cancelled"] ), ) .order_by(PlatformFulfillmentTask.id.asc()) .limit(batch_size) .all() ) ] queued = sum( 1 for task_id in task_ids if _emit_order_site_binding_state(db, task_id) ) db.commit() return { "queued": queued, "nextTaskId": max(task_ids, default=normalized_after), "hasMore": len(task_ids) == batch_size, } def ensure_customer_profile_for_binding(db: Session, *, task_id: int) -> None: task = _load_task(db, task_id) if task.flow_version == FLOW_VERSION_CLEAN and not _has_game_home_profile(task): raise HTTPException(status_code=409, detail="请先提交游戏角色和游戏主页截图") def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[str, Any]: task = _load_task_for_update(db, task_id) task = _load_task(db, refresh_binding(db, task_id=task.id)["task"]["id"]) if str(task.issue_code or "") == ROLE_LOCK_ISSUE: # 刷新时已经判定角色被其他账号占用:直接返回人工状态,不再创建确认任务。 return get_task_detail(db, task.id) if task.binding_status != "role_ready": raise HTTPException(status_code=409, detail="当前没有待确认的游戏角色") if not task.account_id or not task.lease_id: raise HTTPException(status_code=409, detail="账号租约不存在") lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if lease is None or lease.status != "active": raise HTTPException(status_code=409, detail="账号租约已失效") current_bind_task = ( db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if task.bind_task_id else None ) current_bind_result = (current_bind_task.result or {}) if current_bind_task else {} # 兼容部署前已经进入 role_ready 的订单:确认前再查一次角色 7 天锁。 target_role_name = _order_target_role(db, task) if target_role_name and _block_on_role_lock( db, task, target_role_name, current_bind_task, ): db.commit() return get_task_detail(db, task.id) if target_role_name and _block_on_account_lock( db, task, target_role_name, current_bind_task, ): db.commit() return get_task_detail(db, task.id) expected_role_name = str( task.customer_role_name or target_role_name or current_bind_result.get("role_name") or "" ).strip() baseline_role_name = str(current_bind_result.get("current_role_name") or "").strip() batch_id = f"pfconfirm-{task.id}-{uuid.uuid4().hex[:8]}" confirm_task = DouyuTask( batch_id=batch_id, account_id=task.account_id, account_assigned_to=current.id, task_type="confirm_bind", handbook_scope="elite", status="planned", message="等待确认角色绑定", result={ "payload": {}, "expected_role_name": expected_role_name, "baseline_role_name": baseline_role_name, }, created_by=current.id, platform_task_id=task.id, ) db.add(confirm_task) db.flush() account = db.query(Account).filter(Account.id == task.account_id).first() if account is not None: record_douyu_task_started( db, account, task_id=int(confirm_task.id), task_type="confirm_bind", task_label="确认绑定", scope="elite", actor_id=current.id, ) task.bind_task_id = confirm_task.id task.binding_status = "confirming" task.execution_status = "binding_confirming" task.operator_id = current.id task.updated_at = _now() _apply_task_lease_policy(db, task, lease=lease) _append_event( db, task.id, "binding_confirm_started", actor_type="user", actor_id=current.id, detail={"confirmTaskId": confirm_task.id}, ) _emit_order_site_binding_state(db, task.id) enqueue_execution_job( db, job_type=JOB_DOUYU_BINDING, lane_scope=LANE_FULFILLMENT, batch_id=batch_id, payload={ "task_type": "confirm_bind", "payload": {}, "concurrency": 1, }, created_by=int(current.id), priority=10, max_attempts=1, ) db.commit() return get_task_detail(db, task.id) async def confirm_binding( db: Session, *, task_id: int, current: User ) -> dict[str, Any]: return await run_in_threadpool( confirm_binding_sync, db, task_id=task_id, current=current, ) def verify_task_binding_sync( db: Session, *, task_id: int, current: User | None = None, automatic: bool = False, ) -> dict[str, Any]: """确认绑定后,向斗鱼实时复核当前账号绑定状态与角色是否一致。""" task = _load_task(db, task_id) if task.execution_status in {"completed", "cancelled"}: if automatic: return get_task_detail(db, task.id) raise HTTPException(status_code=409, detail="已结束任务无需复核绑定") if task.binding_status != "bound": if automatic: return get_task_detail(db, task.id) raise HTTPException(status_code=409, detail="当前订单尚未绑定确认,无法复核") if not task.account_id: if automatic: return get_task_detail(db, task.id) raise HTTPException(status_code=409, detail="当前任务尚未分配账号") account = db.get(Account, int(task.account_id)) if account is None or not str(account.cookie or "").strip(): if automatic: _append_event( db, task.id, "binding_verify_error", actor_type="system", detail={"error": "账号 Cookie 不可用,跳过自动复核", "automatic": True}, ) db.commit() return get_task_detail(db, task.id) raise HTTPException(status_code=409, detail="账号 Cookie 不可用,无法查询斗鱼") config = config_mapping(ensure_douyu_config(db)) cookie = str(account.cookie or "").strip() bind_task_id = int(task.bind_task_id) if task.bind_task_id else None account_id = int(account.id) client = activity_client(cookie) try: role = resolve_elite_role(client, config) except Exception as exc: # noqa: BLE001 role = {"status": ROLE_ERROR, "errors": [str(exc)], "bind_infos": []} bind_infos = [ item for item in (role.get("bind_infos") or []) if isinstance(item, dict) ] if bind_infos: record_role_api_candidates( db, account_id=account_id, task_id=bind_task_id, candidates=bind_infos, scope=SCOPE_ELITE, stage="fulfillment.verify_binding", source="platform.verify_binding", ) task = _load_task_for_update(db, task_id) account = db.get(Account, int(task.account_id)) if task.account_id else None if ( account is None or task.execution_status in {"completed", "cancelled"} or task.binding_status != "bound" ): if bind_infos: db.commit() return get_task_detail(db, task.id) role_status = str(role.get("status") or "") actor_type = "system" if automatic or current is None else "user" actor_id = None if automatic or current is None else int(current.id) if role_status in {ROLE_ERROR, ROLE_UNKNOWN}: err_text = ( ";".join(str(x) for x in (role.get("errors") or []) if x) or "斗鱼接口查询异常" ) _append_event( db, task.id, "binding_verify_error", actor_type=actor_type, actor_id=actor_id, detail={"error": err_text[:500], "automatic": automatic}, ) db.commit() return get_task_detail(db, task.id) persist_probe_result( db, account, { "probe_id": f"pf-verify:{task.id}", "identity": {"uid": account.uid, "username": account.username}, "session": {}, "elite": {}, "eligibility": {}, "roles": {"elite": role}, "gold": {}, "goods": {}, "errors": {}, }, current=current, source="platform.verify_binding", record_event=False, ) action_aliases = set(elite_action_aliases(config)) action_bound = next( ( item for item in bind_infos if str(item.get("act_alias") or "").strip() in action_aliases and bool(item.get("is_bound_act")) and str(item.get("role_name") or "").strip() ), None, ) actual_role = ( str((action_bound or role).get("role_name") or "").strip() if role_status == ROLE_BOUND else "" ) actual_alias = str( (action_bound or {}).get("act_alias") or role.get("source_alias") or "" ).strip() actual_channel = str(role.get("game_channel") or "").strip() expected_role = str( task.customer_role_name or _order_target_role(db, task) or "" ).strip() verified = bool( role_status == ROLE_BOUND and actual_role and (not expected_role or role_names_match(actual_role, expected_role)) ) if verified: _append_event( db, task.id, "binding_verified", actor_type=actor_type, actor_id=actor_id, detail={ "roleName": actual_role[:128], "expectedRoleName": expected_role[:128], "channel": actual_channel[:128], "actAlias": actual_alias[:64], "automatic": automatic, }, ) db.commit() return get_task_detail(db, task.id) lease = _lease_for_task(db, task) if actual_role and expected_role: mismatch_msg = ( f"斗鱼复核未通过:当前绑定角色为「{actual_role}」," f"与订单目标「{expected_role}」不一致" ) issue_code = "role_changed" else: pending_role = str( role.get("pending_role_name") or role.get("role_name") or "" ).strip() mismatch_msg = ( f"斗鱼复核未通过:角色「{pending_role}」仍处于待确认,尚未绑定生效" if pending_role else "斗鱼复核未通过:斗鱼接口当前显示未绑定生效" ) issue_code = "binding_failed" task.binding_status = "failed" task.execution_status = "manual_required" task.issue_code = issue_code task.last_error = mismatch_msg task.updated_at = _now() _append_event( db, task.id, "binding_verify_failed", actor_type=actor_type, actor_id=actor_id, detail={ "expectedRoleName": expected_role[:128], "actualRoleName": actual_role[:128], "actualStatus": role_status, "channel": actual_channel[:128], "actAlias": actual_alias[:64], "message": mismatch_msg, "automatic": automatic, }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) async def verify_task_binding( db: Session, *, task_id: int, current: User ) -> dict[str, Any]: return await run_in_threadpool( verify_task_binding_sync, db, task_id=task_id, current=current, automatic=False, ) def verify_active_binding_for_douyu_task( db: Session, *, douyu_task_id: int, actor_id: int | None = None, ) -> dict[str, Any] | None: """confirm_bind 完成后,自动向斗鱼再复核一次对应履约订单的绑定结果。""" douyu_task = db.get(DouyuTask, int(douyu_task_id)) if ( douyu_task is None or douyu_task.status != "success" or str(douyu_task.task_type or "") != "confirm_bind" or str(douyu_task.handbook_scope or "") != "elite" ): return None query = db.query(PlatformFulfillmentTask).filter( PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.binding_status == "bound", PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), ) if douyu_task.platform_task_id: task = query.filter( PlatformFulfillmentTask.id == int(douyu_task.platform_task_id) ).first() else: task = ( query.filter(PlatformFulfillmentTask.bind_task_id == int(douyu_task.id)) .order_by(PlatformFulfillmentTask.id.desc()) .first() ) if task is None: return None actor = db.get(User, int(actor_id)) if actor_id is not None else None return verify_task_binding_sync( db, task_id=int(task.id), current=actor, automatic=True, )