"""直播账号履约作业服务:订单同步、映射、选号、绑码和人工完成。""" from __future__ import annotations import os import time import uuid from datetime import UTC, datetime, timedelta from threading import Lock from typing import Any from fastapi import HTTPException from loguru import logger from sqlalchemy import or_ from sqlalchemy.orm import Session from ...models import ( Account, AccountLease, DouyuExternalOrder, DouyuGoodsSnapshot, DouyuTask, PlatformCommodityMapping, PlatformFulfillmentEvent, PlatformFulfillmentSetting, PlatformFulfillmentTask, User, ) from ...permissions import ROLE_LABELS from ..account_binding import ( binding_role_from_result, pending_binding_role_from_result, ) from ..account_capability_service import ( AVAILABILITY_AVAILABLE, AVAILABILITY_LIMITED, record_account_commodity_state, ) from ..business_events import record_account_query, record_douyu_task_started from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state from ..douyu_activity_query import activity_client, query_exchange_eligibility from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches from ..douyu_service import ( SUPPORTED_DOUYU_TASK_TYPES, douyu_config_value, ensure_douyu_config, ) from ..external_order_source import ( OrderLookupUnavailable, list_pending_manual_fulfillments, lookup_pending_manual_fulfillment, ) from .account_selector import ( AccountCandidate, capability_candidate_accounts, has_recent_exchange, lease_account, live_candidate_accounts, release_lease, renew_lease, ) from .order_site_notifier import enqueue_order_site_binding_state TARGET_PLATFORM = "douyu" SCOPE_ELITE = "elite" ACTIVE_STATUSES = { "ready", "allocated", "waiting_bind", "role_ready", "binding_confirming", "bound", "manual_required", } BINDING_QR_TTL_SECONDS = int(os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "600")) AUTO_SYNC_INTERVAL_SECONDS = 900.0 DEFAULT_LIVE_CANDIDATE_LIMIT = 20 def _matching_mode() -> str: mode = os.getenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid").strip().lower() return mode if mode in {"legacy", "hybrid", "capability"} else "hybrid" _SYNC_LOCK = Lock() _AUTO_SYNC_LOCK = Lock() _AUTO_SYNC_LAST_ATTEMPT = float("-inf") def _now() -> datetime: return datetime.now(UTC) def _jsonable(value: Any) -> Any: if isinstance(value, datetime): return value.isoformat() if isinstance(value, dict): return {str(key): _jsonable(item) for key, item in value.items()} if isinstance(value, (list, tuple)): return [_jsonable(item) for item in value] if isinstance(value, (str, int, float, bool)) or value is None: return value return str(value) def _mapping_for_sku( db: Session, internal_sku_key: str ) -> PlatformCommodityMapping | None: return ( db.query(PlatformCommodityMapping) .filter( PlatformCommodityMapping.target_platform == TARGET_PLATFORM, PlatformCommodityMapping.internal_sku_key == internal_sku_key, PlatformCommodityMapping.enabled.is_(True), ) .first() ) def _parse_snapshot_datetime(value: Any) -> datetime | None: if isinstance(value, datetime): return value if value.tzinfo is not None else value.replace(tzinfo=UTC) text = str(value or "").strip() if not text: return None try: parsed = datetime.fromisoformat(text) except ValueError: return None return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC) def _snapshot_value(data: dict[str, Any], *names: str, default: Any = "") -> Any: for name in names: if name in data and data[name] is not None: return data[name] return default def _order_snapshot_from_event(payload: dict[str, Any]) -> dict[str, Any]: data = payload.get("data") return data if isinstance(data, dict) else payload def _upsert_order_snapshot( db: Session, snapshot: dict[str, Any], *, mapping: PlatformCommodityMapping | None, ) -> tuple[PlatformFulfillmentTask | None, bool, bool]: """应用一条订单项快照,返回 (task, created, ignored)。""" item_id = str( _snapshot_value(snapshot, "sourceOrderItemId", "source_order_item_id", default="") ).strip() if not item_id: return None, False, True paid_at = _parse_snapshot_datetime( _snapshot_value(snapshot, "paidAt", "paid_at", default=None) ) order_created_at = _parse_snapshot_datetime( _snapshot_value( snapshot, "orderCreatedAt", "order_created_at", default=None, ) ) order_status = str( _snapshot_value(snapshot, "orderStatus", "order_status", default="") ) pay_status = str( _snapshot_value(snapshot, "payStatus", "pay_status", default="paid") ) terminal_order = order_status in {"refunded", "cancelled", "closed"} if not terminal_order and pay_status != "paid": return None, False, True cutoff = _order_match_started_at(db) match_basis_at = paid_at or order_created_at if ( match_basis_at is not None and cutoff is not None and match_basis_at < cutoff ): return None, False, True task = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.source_system == "order_site", PlatformFulfillmentTask.source_order_item_id == item_id, ) .first() ) created = task is None if task is None: task = PlatformFulfillmentTask( source_system="order_site", source_order_id=str( _snapshot_value( snapshot, "sourceOrderId", "source_order_id", "orderId", default="", ) ), source_order_item_id=item_id, source_fulfillment_id=str( _snapshot_value( snapshot, "sourceFulfillmentId", "source_fulfillment_id", "fulfillmentId", default="", ) ), target_platform=TARGET_PLATFORM, scope=SCOPE_ELITE, created_at=_now(), updated_at=_now(), ) db.add(task) db.flush() _append_event( db, task.id, "task_created", detail={ "platformOrderId": _snapshot_value( snapshot, "platformOrderId", "platform_order_id", default="" ) }, ) before = ( task.platform_order_id, task.source_order_id, task.source_fulfillment_id, task.provider, task.shop_id, task.shop_name, task.sku_code, task.sku_name, task.internal_sku_key, task.quantity, task.order_amount_fen, task.paid_at, task.execution_status, task.commodity_mapping_id, task.commodity_id, task.required_points, task.issue_code, ) if task.execution_status in {"completed", "cancelled"}: task.source_snapshot_json = _jsonable(snapshot) return task, created, False previous_execution_status = task.execution_status terminal = ( terminal_order or _snapshot_value( snapshot, "fulfillmentStatus", "fulfillment_status", default="", ) == "archived" or _snapshot_value( snapshot, "configEnabled", "config_enabled", default=True, ) is False or _snapshot_value( snapshot, "douyuFulfillmentEnabled", "douyu_fulfillment_enabled", default=True, ) is False ) task.platform_order_id = str( _snapshot_value(snapshot, "platformOrderId", "platform_order_id", default="") ) task.source_order_id = str( _snapshot_value( snapshot, "sourceOrderId", "source_order_id", "orderId", default=task.source_order_id, ) ) task.source_fulfillment_id = str( _snapshot_value( snapshot, "sourceFulfillmentId", "source_fulfillment_id", "fulfillmentId", default=task.source_fulfillment_id, ) ) task.provider = str( _snapshot_value(snapshot, "provider", default=task.provider) ) task.shop_id = str( _snapshot_value(snapshot, "shopId", "shop_id", default="") ) task.shop_name = str( _snapshot_value(snapshot, "shopName", "shop_name", default="") ) task.sku_code = str( _snapshot_value(snapshot, "skuCode", "sku_code", default="") ) task.sku_name = str( _snapshot_value(snapshot, "skuName", "sku_name", default="") ) task.internal_sku_key = str( _snapshot_value( snapshot, "internalSkuKey", "internal_sku_key", default="", ) ).strip() task.quantity = max( 1, int(_snapshot_value(snapshot, "quantity", default=1) or 1), ) task.order_amount_fen = int( _snapshot_value( snapshot, "revenueAmountFen", "revenue_amount_fen", "totalAmountFen", "total_amount", default=0, ) or 0 ) task.paid_at = paid_at task.source_snapshot_json = _jsonable(snapshot) task.updated_at = _now() if terminal: task.execution_status = "cancelled" task.issue_code = "source_cancelled" task.last_error = "订单已关闭或直播履约配置已停用" task.next_allocate_at = None else: # 订单快照会被重复投递。只有未分配任务从「待映射」进入「待分配」时 # 才允许改生命周期状态;已分配任务不能被快照更新打回 pending。 update_execution_status = task.account_id is None and ( previous_execution_status == "pending_mapping" or mapping is None ) _apply_mapping( task, mapping, update_execution_status=update_execution_status, ) if task.account_id is not None: task.next_allocate_at = None elif task.execution_status == "ready": if previous_execution_status != "ready" or task.next_allocate_at is None: task.next_allocate_at = _now() else: task.next_allocate_at = None after = ( task.platform_order_id, task.source_order_id, task.source_fulfillment_id, task.provider, task.shop_id, task.shop_name, task.sku_code, task.sku_name, task.internal_sku_key, task.quantity, task.order_amount_fen, task.paid_at, task.execution_status, task.commodity_mapping_id, task.commodity_id, task.required_points, task.issue_code, ) changed = created or before != after if changed: _emit_order_site_binding_state(db, task.id) return task, created, False def _mapping_map(db: Session) -> dict[str, PlatformCommodityMapping]: rows = ( db.query(PlatformCommodityMapping) .filter( PlatformCommodityMapping.target_platform == TARGET_PLATFORM, PlatformCommodityMapping.enabled.is_(True), ) .all() ) return { str(row.internal_sku_key or "").strip(): row for row in rows if str(row.internal_sku_key or "").strip() } def sync_order_snapshot( db: Session, payload: dict[str, Any], *, commit: bool = True, ) -> dict[str, Any]: """消费 order_site 订单项快照;正常路径不再读取 order_site 数据库。""" snapshot = _order_snapshot_from_event(payload) mapping_by_sku = _mapping_map(db) mapping = mapping_by_sku.get( str( _snapshot_value( snapshot, "internalSkuKey", "internal_sku_key", default="", ) ).strip() ) task, created, ignored = _upsert_order_snapshot(db, snapshot, mapping=mapping) if commit: db.commit() return { "fetched": 1, "created": int(created), "updated": int(task is not None and not created), "ignored": int(ignored), "taskIds": [int(task.id)] if task is not None else [], } def sync_order_item_ids( db: Session, source_order_item_ids: list[str], *, commit: bool = True, ) -> dict[str, Any]: """兼容旧版事件:只定向读取明确订单项,不再走最近 500 条窗口。""" mapping_by_sku = _mapping_map(db) created = 0 updated = 0 ignored = 0 task_ids: list[int] = [] for item_id in dict.fromkeys(str(item or "").strip() for item in source_order_item_ids): if not item_id: ignored += 1 continue snapshot = lookup_pending_manual_fulfillment(item_id) if snapshot is None: ignored += 1 continue mapping = mapping_by_sku.get(str(snapshot.get("internal_sku_key") or "").strip()) task, was_created, was_ignored = _upsert_order_snapshot( db, snapshot, mapping=mapping, ) if task is None: ignored += int(was_ignored) continue created += int(was_created) updated += int(not was_created) task_ids.append(int(task.id)) if commit: db.commit() return { "fetched": len(task_ids), "created": created, "updated": updated, "ignored": ignored, "taskIds": task_ids, } def get_settings(db: Session) -> dict[str, Any]: now = _now() row = ( db.query(PlatformFulfillmentSetting) .filter(PlatformFulfillmentSetting.id == 1) .first() ) if row is None: row = PlatformFulfillmentSetting( id=1, lease_duration_minutes=None, order_match_started_at=now, ) db.add(row) db.commit() db.refresh(row) return { "leaseDurationMinutes": row.lease_duration_minutes, "orderMatchStartedAt": _jsonable(row.order_match_started_at), "updatedAt": _jsonable(row.updated_at), } def update_settings( db: Session, *, lease_duration_minutes: int | None, order_match_started_at: datetime | None = None, current: User, ) -> dict[str, Any]: row = ( db.query(PlatformFulfillmentSetting) .filter(PlatformFulfillmentSetting.id == 1) .first() ) now = _now() if row is None: row = PlatformFulfillmentSetting( id=1, order_match_started_at=order_match_started_at or now, ) db.add(row) elif order_match_started_at is not None: row.order_match_started_at = order_match_started_at row.lease_duration_minutes = lease_duration_minutes row.updated_by = current.id row.updated_at = now active_leases = ( db.query(AccountLease) .filter( AccountLease.purpose == "platform_fulfillment", AccountLease.status == "active", ) .all() ) for lease in active_leases: lease.expires_at = ( None if lease_duration_minutes is None else now + timedelta(minutes=lease_duration_minutes) ) db.commit() return { "leaseDurationMinutes": row.lease_duration_minutes, "orderMatchStartedAt": _jsonable(row.order_match_started_at), "updatedAt": _jsonable(row.updated_at), } def _lease_duration_minutes(db: Session) -> int | None: return get_settings(db)["leaseDurationMinutes"] def _order_match_started_at(db: Session) -> datetime | None: row = ( db.query(PlatformFulfillmentSetting) .filter(PlatformFulfillmentSetting.id == 1) .first() ) return row.order_match_started_at if row is not None else None def _apply_order_match_cutoff( query, match_started_at: datetime | None, ): if match_started_at is None: return query return query.filter(PlatformFulfillmentTask.paid_at >= match_started_at) def _integration_actor(db: Session) -> User: raw_user_id = os.getenv("PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID", "").strip() query = db.query(User).filter(User.is_active.is_(True)) if raw_user_id: try: user = query.filter(User.id == int(raw_user_id)).first() except ValueError: user = None else: user = query.filter(User.role == "super_admin").order_by(User.id.asc()).first() if user is None: raise HTTPException( status_code=503, detail="未配置可用的直播账号履约集成操作人", ) return user def _find_customer_task( db: Session, *, source_order_item_id: str, platform_order_id: str = "", ) -> PlatformFulfillmentTask | None: item_id = str(source_order_item_id or "").strip() if not item_id: return None query = db.query(PlatformFulfillmentTask).filter( PlatformFulfillmentTask.source_system == "order_site", PlatformFulfillmentTask.source_order_item_id == item_id, ) query = _apply_order_match_cutoff(query, _order_match_started_at(db)) order_no = str(platform_order_id or "").strip() if order_no: query = query.filter(PlatformFulfillmentTask.platform_order_id == order_no) return query.first() def _binding_qr_expired(bind_task: DouyuTask, now: datetime | None = None) -> bool: result = bind_task.result or {} raw_expires_at = str(result.get("qr_expires_at") or "").strip() if raw_expires_at: try: expires_at = datetime.fromisoformat(raw_expires_at) except ValueError: expires_at = None if expires_at is not None: if expires_at.tzinfo is None: expires_at = expires_at.replace(tzinfo=UTC) return expires_at <= (now or _now()) created_at = bind_task.created_at if created_at.tzinfo is None: created_at = created_at.replace(tzinfo=UTC) return created_at + timedelta(seconds=BINDING_QR_TTL_SECONDS) <= (now or _now()) def _append_event( db: Session, task_id: int, event_type: str, *, actor_type: str = "system", actor_id: int | str | None = None, detail: dict[str, Any] | None = None, ) -> None: db.add( PlatformFulfillmentEvent( task_id=task_id, event_type=event_type, actor_type=actor_type, actor_id=str(actor_id or ""), detail_json=detail or {}, created_at=_now(), ) ) def record_douyu_operation_started( db: Session, task: PlatformFulfillmentTask, *, current: User, batch_id: str, task_type: str, douyu_task_ids: list[int], payload: dict[str, Any] | None = None, ) -> None: """记录履约上下文发起的斗鱼操作,账号任务结果由执行器补写。""" _append_event( db, task.id, "douyu_operation_started", actor_type="user", actor_id=current.id, detail={ "batchId": batch_id, "douyuTaskIds": douyu_task_ids, "taskType": task_type, "taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get(task_type, task_type), "accountId": task.account_id, "payload": payload or {}, }, ) db.commit() def record_douyu_operation_result( db: Session, douyu_task: DouyuTask, *, status: str, message: str, ) -> None: """把履约上下文的斗鱼任务终态投影到履约时间线。""" if not douyu_task.platform_task_id: return event_type = { "success": "douyu_operation_succeeded", "stopped": "douyu_operation_stopped", }.get(status, "douyu_operation_failed") exists = ( db.query(PlatformFulfillmentEvent.id) .filter( PlatformFulfillmentEvent.task_id == int(douyu_task.platform_task_id), PlatformFulfillmentEvent.event_type == event_type, PlatformFulfillmentEvent.detail_json["douyuTaskId"].as_integer() == int(douyu_task.id), ) .first() ) if exists is not None: return _append_event( db, int(douyu_task.platform_task_id), event_type, detail={ "batchId": douyu_task.batch_id, "douyuTaskId": int(douyu_task.id), "taskType": douyu_task.task_type, "taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get( douyu_task.task_type, douyu_task.task_type, ), "accountId": douyu_task.account_id, "status": status, "message": (message or "")[:1000], }, ) def _emit_order_site_binding_state( db: Session, task_id: int, *, extra: dict[str, Any] | None = None, ) -> bool: """当前事务内写 Outbox;HTTP 投递由独立 worker 完成。""" task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == int(task_id)) .with_for_update() .one() ) next_state_version = int(task.state_version or 0) + 1 payload = customer_binding_out(db, task_id) payload["stateVersion"] = next_state_version if extra: payload.update(extra) enqueued = enqueue_order_site_binding_state( db, payload, ) if enqueued: task.state_version = next_state_version db.flush() return enqueued def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask: task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == int(task_id)) .first() ) if task is None: raise HTTPException(status_code=404, detail="直播账号履约任务不存在") return task def _apply_mapping( task: PlatformFulfillmentTask, mapping: PlatformCommodityMapping | None, *, update_execution_status: bool = True, ) -> None: if mapping is not None: task.commodity_mapping_id = mapping.id task.commodity_id = mapping.commodity_id task.required_points = mapping.required_points else: task.commodity_mapping_id = None task.commodity_id = "" task.required_points = None if not update_execution_status: return if mapping is None: task.execution_status = "pending_mapping" task.issue_code = "mapping_missing" task.last_error = "内部 SKU 尚未配置斗鱼商品映射" return task.execution_status = "ready" task.issue_code = "" task.last_error = "" def _sync_pending_tasks( db: Session, *, limit: int = 100, commit: bool = True, ) -> dict[str, Any]: """只拉取已配置商品映射的人工待履约订单项并生成本地作业。""" match_started_at = _order_match_started_at(db) mappings = ( db.query(PlatformCommodityMapping) .filter( PlatformCommodityMapping.target_platform == TARGET_PLATFORM, PlatformCommodityMapping.enabled.is_(True), ) .all() ) mappings_by_sku = { str(mapping.internal_sku_key or "").strip(): mapping for mapping in mappings if str(mapping.internal_sku_key or "").strip() } if not mappings_by_sku: if commit: db.commit() return { "fetched": 0, "created": 0, "updated": 0, "skippedUnmapped": 0, "configuredSkuCount": 0, } try: rows = list_pending_manual_fulfillments( limit=limit, internal_sku_keys=list(mappings_by_sku), paid_at_from=match_started_at, ) except OrderLookupUnavailable as exc: raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc created = 0 updated = 0 skipped_unmapped = 0 task_ids: list[int] = [] for row in rows: item_id = str(row.get("source_order_item_id") or "") if not item_id: continue internal_sku_key = str(row.get("internal_sku_key") or "").strip() mapping = mappings_by_sku.get(internal_sku_key) if mapping is None: skipped_unmapped += 1 continue task = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.source_system == "order_site", PlatformFulfillmentTask.source_order_item_id == item_id, ) .first() ) if task is None: task = PlatformFulfillmentTask( source_system="order_site", source_order_id=str(row.get("source_order_id") or ""), source_order_item_id=item_id, source_fulfillment_id=str(row.get("source_fulfillment_id") or ""), created_at=_now(), updated_at=_now(), ) db.add(task) db.flush() created += 1 _append_event( db, task.id, "task_created", detail={"platformOrderId": row.get("platform_order_id")}, ) else: updated += 1 if task.execution_status in {"completed", "cancelled"}: continue task.platform_order_id = str(row.get("platform_order_id") or "") task.provider = str(row.get("provider") or "") task.shop_id = str(row.get("shop_id") or "") task.shop_name = str(row.get("shop_name") or "") task.sku_code = str(row.get("sku_code") or "") task.sku_name = str(row.get("sku_name") or "") task.internal_sku_key = internal_sku_key task.quantity = 1 if isinstance(row.get("paid_at"), datetime): task.paid_at = row["paid_at"] task.order_amount_fen = int( row.get("revenue_amount_fen") or row.get("total_amount") or 0 ) task.target_platform = TARGET_PLATFORM task.scope = SCOPE_ELITE task.source_snapshot_json = _jsonable(row) task.updated_at = _now() if ( task.account_id is None and task.execution_status in {"pending_mapping", "ready"} ): _apply_mapping(task, mapping) if task.execution_status == "ready" and task.account_id is None: task.next_allocate_at = _now() _emit_order_site_binding_state(db, task.id) task_ids.append(int(task.id)) if commit: db.commit() return { "fetched": len(rows), "created": created, "updated": updated, "skippedUnmapped": skipped_unmapped, "configuredSkuCount": len(mappings_by_sku), "orderMatchStartedAt": _jsonable(match_started_at), "taskIds": task_ids, } def sync_pending_tasks( db: Session, *, limit: int = 100, commit: bool = True, ) -> dict[str, Any]: """串行同步订单,避免自动同步与人工同步并发创建重复任务。""" with _SYNC_LOCK: return _sync_pending_tasks(db, limit=limit, commit=commit) def sync_pending_tasks_if_due( db: Session, *, limit: int = 100, now: float | None = None, ) -> dict[str, Any] | None: """工作台读取时自动同步;按进程节流,不阻塞每 5 秒一次的列表轮询。""" global _AUTO_SYNC_LAST_ATTEMPT if not _AUTO_SYNC_LOCK.acquire(blocking=False): return None try: current = time.monotonic() if now is None else now if current - _AUTO_SYNC_LAST_ATTEMPT < AUTO_SYNC_INTERVAL_SECONDS: return None _AUTO_SYNC_LAST_ATTEMPT = current try: return sync_pending_tasks(db, limit=limit) except Exception: _AUTO_SYNC_LAST_ATTEMPT = float("-inf") raise finally: _AUTO_SYNC_LOCK.release() def list_tasks( db: Session, *, status: str = "", keyword: str = "", page: int = 1, page_size: int = 20, ) -> dict[str, Any]: query = db.query(PlatformFulfillmentTask) query = _apply_order_match_cutoff(query, _order_match_started_at(db)) query = query.filter( or_( PlatformFulfillmentTask.commodity_mapping_id.isnot(None), PlatformFulfillmentTask.commodity_id != "", ) ) if status: if status == "unfinished": query = query.filter( PlatformFulfillmentTask.execution_status.notin_( ["completed", "cancelled"] ) ) else: query = query.filter(PlatformFulfillmentTask.execution_status == status) text = keyword.strip() if text: pattern = f"%{text}%" query = query.filter( or_( PlatformFulfillmentTask.platform_order_id.ilike(pattern), PlatformFulfillmentTask.sku_name.ilike(pattern), PlatformFulfillmentTask.sku_code.ilike(pattern), PlatformFulfillmentTask.internal_sku_key.ilike(pattern), PlatformFulfillmentTask.commodity_id.ilike(pattern), ) ) total = query.count() rows = ( query.order_by( PlatformFulfillmentTask.paid_at.desc(), PlatformFulfillmentTask.id.desc(), ) .offset((max(1, page) - 1) * max(1, page_size)) .limit(max(1, min(page_size, 100))) .all() ) return { "items": [_task_out(db, row) for row in rows], "pagination": { "page": max(1, page), "pageSize": max(1, page_size), "total": total, }, } def _task_out( db: Session, task: PlatformFulfillmentTask, *, include_qr: bool = False, ) -> dict[str, Any]: account = ( db.query(Account).filter(Account.id == task.account_id).first() if task.account_id else None ) lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) bind_task = ( db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if task.bind_task_id else None ) collab_order = ( db.query(DouyuExternalOrder) .filter(DouyuExternalOrder.source_task_id == task.id) .first() ) bind_result = (bind_task.result or {}) if bind_task else {} # 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。 pending_role = pending_binding_role_from_result(bind_result) return { "id": task.id, "sourceSystem": task.source_system, "sourceOrderId": task.source_order_id, "sourceOrderItemId": task.source_order_item_id, "sourceFulfillmentId": task.source_fulfillment_id, "platformOrderId": task.platform_order_id, "provider": task.provider, "shopId": task.shop_id, "shopName": task.shop_name, "skuCode": task.sku_code, "skuName": task.sku_name, "internalSkuKey": task.internal_sku_key, "quantity": task.quantity, "orderAmountFen": task.order_amount_fen, "targetPlatform": task.target_platform, "scope": task.scope, "commodityMappingId": task.commodity_mapping_id, "commodityId": task.commodity_id, "requiredPoints": task.required_points, "bindingStatus": task.binding_status, "executionStatus": task.execution_status, "exchangeStatus": task.exchange_status, "issueCode": task.issue_code, "lastError": task.last_error, "operatorId": task.operator_id, "completedAt": task.completed_at, "paidAt": task.paid_at, "createdAt": task.created_at, "updatedAt": task.updated_at, "collabOrder": ( { "id": collab_order.id, "orderNo": collab_order.order_no, "status": collab_order.status, "lastSyncedAt": collab_order.last_synced_at, } if collab_order else None ), "account": ( { "id": account.id, "username": account.username, "nickname": account.nickname or "", "points": account.points, "goldBalance": account.gold_balance, "eliteOpened": account.elite_opened, "ckCheckStatus": account.ck_check_status, "roleBindStatus": account.role_bind_status, "gameName": account.game_name, "gameChannel": account.game_channel, "roleChangeAvailableAt": account.role_change_available_at, } if account else None ), "lease": ( { "id": lease.id, "status": lease.status, "expiresAt": lease.expires_at, } if lease else None ), "bindTask": ( { "id": bind_task.id, "taskType": bind_task.task_type, "status": bind_task.status, "message": bind_task.message, "qrUrl": str(bind_result.get("url") or "") if include_qr else "", "roleName": binding_role_from_result(bind_result), "areaName": str(bind_result.get("area_name") or ""), "platName": str(bind_result.get("plat_name") or ""), "bindPhase": str(bind_result.get("bind_phase") or ""), "bindReadyForConfirm": bool(pending_role), "bindConfirmed": bool(bind_result.get("bind_confirmed")), } if bind_task else None ), } def get_task_detail(db: Session, task_id: int) -> dict[str, Any]: task = _load_task(db, task_id) events = ( db.query(PlatformFulfillmentEvent) .filter(PlatformFulfillmentEvent.task_id == task.id) .order_by(PlatformFulfillmentEvent.id.desc()) .limit(200) .all() ) actor_ids = { int(event.actor_id) for event in events if event.actor_type == "user" and str(event.actor_id or "").isdigit() } actors = { int(user.id): user for user in db.query(User).filter(User.id.in_(actor_ids)).all() } if actor_ids else {} return { "task": _task_out(db, task, include_qr=True), "events": [ { "id": event.id, "eventType": event.event_type, "actorType": event.actor_type, "actorId": event.actor_id, "actorName": ( actors[int(event.actor_id)].deleted_username or actors[int(event.actor_id)].username ) if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors else "", "actorRole": actors[int(event.actor_id)].role if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors else "", "actorRoleLabel": ROLE_LABELS.get( actors[int(event.actor_id)].role, actors[int(event.actor_id)].role, ) if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors else "", "detail": event.detail_json or {}, "createdAt": event.created_at, } for event in events ], } def _customer_task_message(task: PlatformFulfillmentTask) -> str: messages = { "mapping_missing": "商品正在准备中,请稍后重试", "no_eligible_account": "正在准备可用账号,请稍后重试", "elite_not_opened": "账号正在准备精英宝典,请稍后重试", "points_short": "账号正在补充积分,请稍后重试", "commodity_limit_reached": "当前商品暂时无法兑换,请联系客服", "binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码", "account_role_cooldown": "当前绑定账号暂不可换绑,请截图本页面并联系客服处理", "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", "eligibility_check_failed": "状态查询异常,请稍后刷新", "manual_required": "当前需要人工处理,请联系客服", } return messages.get(task.issue_code, "") if task.issue_code else "" def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str: phase = str(result.get("bind_phase") or "") message = str(bind_task.message or "") if phase == "change_waiting" or "暂不能换绑" in message: task_issue = "account_role_cooldown" elif ( phase == "confirm_failed" or "待绑定游戏账号" in message or "未到换绑时间" in message ): task_issue = "customer_role_cooldown" else: return "binding_failed" messages = { "account_role_cooldown": "当前绑定账号暂不可换绑,请截图本页面并联系客服处理", "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", } return task_issue if messages.get(task_issue) else "binding_failed" def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]: """面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。""" task = _load_task(db, task_id) bind_task = ( db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if task.bind_task_id else None ) bind_result = (bind_task.result or {}) if bind_task else {} pending_role = pending_binding_role_from_result(bind_result) lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) lease_ready = bool(task.account_id and lease and lease.status == "active") binding_failed = task.binding_status == "failed" binding_confirmed = task.binding_status == "bound" return { "sessionId": task.id, "platformOrderId": task.platform_order_id, "sourceOrderItemId": task.source_order_item_id, "productName": task.sku_name, "quantity": task.quantity, "executionStatus": task.execution_status, "bindingStatus": task.binding_status, "exchangeStatus": task.exchange_status, "issueCode": task.issue_code, "message": _customer_task_message(task), "accountReady": lease_ready, "bindTaskId": bind_task.id if bind_task else None, "bindTaskStatus": bind_task.status if bind_task else "", "bindPhase": str(bind_result.get("bind_phase") or ""), "qrUrl": str(bind_result.get("url") or ""), "qrGeneratedAt": str(bind_result.get("qr_generated_at") or ""), "qrExpiresAt": str(bind_result.get("qr_expires_at") or ""), "roleName": binding_role_from_result(bind_result), "areaName": str(bind_result.get("area_name") or ""), "platName": str(bind_result.get("plat_name") or ""), "bindReadyForConfirm": (bool(pending_role) and not binding_failed), "bindConfirmed": bool(bind_result.get("bind_confirmed")) and binding_confirmed, "stateVersion": int(task.state_version or 0), "completedAt": _jsonable(task.completed_at), "updatedAt": _jsonable(task.updated_at), } def ensure_customer_session( db: Session, *, source_order_item_id: str, platform_order_id: str = "", ) -> dict[str, Any]: """按订单项幂等准备客户绑定会话;必要时同步订单并自动分配账号。""" task = _find_customer_task( db, source_order_item_id=source_order_item_id, platform_order_id=platform_order_id, ) if task is None: sync_order_item_ids( db, [source_order_item_id], commit=True, ) task = _find_customer_task( db, source_order_item_id=source_order_item_id, platform_order_id=platform_order_id, ) if task is None: raise HTTPException(status_code=404, detail="订单尚未进入直播账号履约队列") if task.execution_status in {"completed", "cancelled"}: return customer_binding_out(db, task.id) if task.execution_status in {"pending_mapping", "ready", "manual_required"}: if task.issue_code == "mapping_missing": return customer_binding_out(db, task.id) actor = _integration_actor(db) allocate_task(db, task_id=task.id, current=actor) return customer_binding_out(db, task.id) async def customer_start_binding( db: Session, *, task_id: int, force_refresh: bool = False, ) -> dict[str, Any]: task = _load_task(db, task_id) actor = _integration_actor(db) if task.execution_status not in {"completed", "cancelled"} and ( not task.account_id or not task.lease_id ): allocate_task(db, task_id=task.id, current=actor) await start_binding( db, task_id=task.id, current=actor, force_refresh=force_refresh, ) return customer_binding_out(db, task.id) def customer_refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: refresh_binding(db, task_id=task_id) return customer_binding_out(db, task_id) def customer_refresh_bindings(db: Session, *, task_ids: list[int]) -> dict[str, Any]: items: list[dict[str, Any]] = [] for task_id in dict.fromkeys(task_ids): task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == task_id) .first() ) if task is None: continue refresh_binding(db, task_id=task.id) items.append(customer_binding_out(db, task.id)) return {"items": items} async def customer_confirm_binding(db: Session, *, task_id: int) -> dict[str, Any]: refresh_binding(db, task_id=task_id) await confirm_binding(db, task_id=task_id, current=_integration_actor(db)) return customer_binding_out(db, task_id) def list_mappings(db: Session, *, keyword: str = "") -> list[dict[str, Any]]: query = db.query(PlatformCommodityMapping) text = keyword.strip() if text: pattern = f"%{text}%" query = query.filter( or_( PlatformCommodityMapping.internal_sku_key.ilike(pattern), PlatformCommodityMapping.commodity_id.ilike(pattern), PlatformCommodityMapping.goods_name.ilike(pattern), ) ) rows = query.order_by(PlatformCommodityMapping.updated_at.desc()).limit(300).all() return [ { "id": row.id, "targetPlatform": row.target_platform, "internalSkuKey": row.internal_sku_key, "commodityId": row.commodity_id, "goodsName": row.goods_name, "requiredPoints": row.required_points, "scope": row.scope, "enabled": row.enabled, "updatedAt": row.updated_at, } for row in rows ] def upsert_mapping( db: Session, *, internal_sku_key: str, commodity_id: str, goods_name: str, required_points: int | None, enabled: bool, current: User, ) -> dict[str, Any]: sku_key = internal_sku_key.strip() commodity = commodity_id.strip() if not sku_key or not commodity: raise HTTPException(status_code=400, detail="内部 SKU 和斗鱼商品 ID 不能为空") goods = ( db.query(DouyuGoodsSnapshot) .filter(DouyuGoodsSnapshot.commodity_id == commodity) .order_by(DouyuGoodsSnapshot.id.desc()) .first() ) row = ( db.query(PlatformCommodityMapping) .filter( PlatformCommodityMapping.target_platform == TARGET_PLATFORM, PlatformCommodityMapping.internal_sku_key == sku_key, ) .first() ) if row is None: row = PlatformCommodityMapping( target_platform=TARGET_PLATFORM, internal_sku_key=sku_key, created_by=current.id, created_at=_now(), ) db.add(row) row.commodity_id = commodity row.goods_name = (goods_name or (goods.name if goods else "")).strip() row.required_points = ( int(required_points) if required_points is not None else (int(goods.score) if goods and goods.score is not None else None) ) row.scope = SCOPE_ELITE row.enabled = bool(enabled) row.updated_at = _now() db.flush() pending = db.query(PlatformFulfillmentTask).filter( PlatformFulfillmentTask.internal_sku_key == sku_key, PlatformFulfillmentTask.account_id.is_(None), PlatformFulfillmentTask.execution_status.in_( ["pending_mapping", "ready", "manual_required"] ), ) pending = _apply_order_match_cutoff(pending, _order_match_started_at(db)) pending = pending.all() task_ids: list[int] = [] for task in pending: _apply_mapping(task, row if row.enabled else None) task.updated_at = _now() task.next_allocate_at = ( _now() if task.execution_status == "ready" and task.account_id is None else None ) _append_event( db, task.id, "mapping_updated", actor_type="user", actor_id=current.id, detail={"commodityId": row.commodity_id, "enabled": row.enabled}, ) _emit_order_site_binding_state(db, task.id) task_ids.append(int(task.id)) db.commit() if task_ids: from .auto_allocator import wake_auto_allocator wake_auto_allocator(task_ids) return next( item for item in list_mappings(db, keyword=sku_key) if item["id"] == row.id ) def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]: task = _load_task(db, task_id) if task.execution_status in {"completed", "cancelled"}: raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") if not task.commodity_id or not task.required_points: raise HTTPException(status_code=409, detail="请先完成商品映射") required_points = int(task.required_points) if task.account_id and task.lease_id: lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if lease and lease.status == "active": return get_task_detail(db, task.id) config = ensure_douyu_config(db) lease_duration_minutes = _lease_duration_minutes(db) manual_id = str(douyu_config_value("manual_id", config.manual_id)) rid = str(douyu_config_value("rid", config.rid)) act_alias = str(douyu_config_value("bind_act_alias", config.bind_act_alias)) try: candidate_limit = int( os.getenv( "PLATFORM_FULFILLMENT_LIVE_CANDIDATE_LIMIT", str(DEFAULT_LIVE_CANDIDATE_LIMIT), ) ) except ValueError: candidate_limit = DEFAULT_LIVE_CANDIDATE_LIMIT candidate_limit = max(1, min(candidate_limit, 100)) mode = _matching_mode() capability_candidates = ( capability_candidate_accounts( db, limit=candidate_limit, required_points=required_points, commodity_id=task.commodity_id, scope=task.scope or SCOPE_ELITE, ) if mode in {"hybrid", "capability"} else [] ) capability_first = bool(capability_candidates) candidates = capability_candidates if not candidates and mode != "capability": # hybrid 模式下能力索引为空或全部过期时,保留旧逻辑兜底。 candidates = live_candidate_accounts( db, limit=candidate_limit, required_points=required_points, commodity_id=task.commodity_id, ) diagnostics: list[dict[str, Any]] = [] qualified: list[tuple[Account, DouyuLiveAccountState]] = [] selected: AccountCandidate | None = None selected_state: DouyuLiveAccountState | None = None lease = None def inspect_candidate( account: Account, *, source: str, ) -> tuple[Account, DouyuLiveAccountState] | None: live_state = refresh_douyu_account_state( db, account, manual_id=manual_id, rid=rid, act_alias=act_alias, ) limited = task.commodity_id in live_state.limited_ids recent_exchange = has_recent_exchange( db, account_id=int(account.id), commodity_id=task.commodity_id, ) reasons = live_state.blocking_reasons(commodity_id=task.commodity_id) if recent_exchange: reasons.append("365 天内已有该商品兑换事件") if live_state.ck_verdict == "valid" and not live_state.error: try: record_account_commodity_state( db, account, commodity_id=task.commodity_id, availability=( AVAILABILITY_LIMITED if limited else AVAILABILITY_AVAILABLE ), blocking_reason=( "该账号已达此商品兑换上限" if limited else "" ), raw_status="1" if limited else "0", observed_at=live_state.checked_at, source="live_check", scope=task.scope or SCOPE_ELITE, ) except Exception as exc: # noqa: BLE001 - 派生索引不能阻止本次选号 logger.warning( "写入选号商品能力失败 account_id={} commodity_id={}: {}", account.id, task.commodity_id, exc, ) if reasons: diagnostics.append( { "accountId": int(account.id), "accountName": live_state.account_name, "ck": live_state.ck_verdict, "eliteOpened": live_state.elite_opened, "points": live_state.points, "reasons": reasons, "source": source, } ) return None return account, live_state def inspect_batch( batch: list[Account], *, source: str, ) -> None: # 能力索引已按成本排序,首个确认通过即可;旧兜底最多比较 3 个。 for account in batch: inspected = inspect_candidate(account, source=source) if inspected is None: continue qualified.append(inspected) if source == "capability" or len(qualified) >= 3: return if capability_candidates: inspect_batch(capability_candidates, source="capability") elif mode != "capability": inspect_batch(candidates, source="live") if not qualified and capability_first and mode == "hybrid": checked_ids = {int(account.id) for account in capability_candidates} fallback_candidates = [ account for account in live_candidate_accounts( db, limit=candidate_limit, required_points=required_points, commodity_id=task.commodity_id, ) if int(account.id) not in checked_ids ] candidates = [*candidates, *fallback_candidates] inspect_batch(fallback_candidates, source="live_fallback") # 积分和宝典开通不淘汰账号,只影响后续处理成本。优先选已经可直接兑换的账号, # 其次是只需充值、只需开通、两者都需要的账号。 qualified.sort( key=lambda item: ( item[1].readiness_rank(required_points=required_points), int(item[1].points or 0), int(item[0].id), ) ) for account, live_state in qualified: candidate = AccountCandidate( account_id=int(account.id), username=str(account.username or ""), nickname=str(account.nickname or ""), points=int(live_state.points or 0), gold_balance=account.gold_balance, points_expire_at=account.points_expire_at, role_change_available_at=live_state.role_change_available_at, ) lease = lease_account( db, candidate=candidate, holder_user_id=current.id, task_id=task.id, commodity_id=task.commodity_id, ttl_minutes=lease_duration_minutes, ) if lease is not None: selected = candidate selected_state = live_state break diagnostics.append( { "accountId": int(account.id), "accountName": live_state.account_name, "ck": live_state.ck_verdict, "eliteOpened": live_state.elite_opened, "points": live_state.points, "reasons": ["账号刚被其他任务占用"], "source": "capability" if capability_first else "live", } ) if selected is None or selected_state is None or lease is None: task.execution_status = "ready" task.next_allocate_at = _now() + timedelta(seconds=45) task.issue_code = "no_eligible_account" if not candidates: task.last_error = ( "商品能力池暂无可用账号" if mode == "capability" else "没有带 CK、允许自动管理且未停用的斗鱼账号" ) else: summary = ";".join( f"{item['accountName']}: {', '.join(item['reasons'][:3])}" for item in diagnostics[:5] ) task.last_error = ( f"已实时检测 {len(diagnostics)} 个账号,当前没有可用账号" + (f"。{summary}" if summary else "") )[:500] task.updated_at = _now() _append_event( db, task.id, "account_allocation_failed", detail={ "candidateCount": len(candidates), "matchingMode": mode, "capabilityCandidates": len(capability_candidates), "diagnostics": diagnostics, }, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) task.account_id = selected.account_id task.lease_id = lease.id task.operator_id = current.id task.execution_status = "allocated" task.next_allocate_at = None task.binding_status = "not_started" soft_reasons = selected_state.soft_requirement_reasons( required_points=required_points ) if task.commodity_id in selected_state.limited_ids: task.exchange_status = "limited" task.issue_code = "commodity_limit_reached" task.last_error = "该账号已达到此商品兑换上限" elif selected_state.elite_opened is not True: task.exchange_status = "not_opened" task.issue_code = "elite_not_opened" task.last_error = "账号尚未开通精英宝典,可开通后继续" elif selected_state.points is None or selected_state.points < required_points: task.exchange_status = "points_short" task.issue_code = "points_short" task.last_error = "账号积分不足,可充值后继续" else: task.exchange_status = "eligible" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "account_allocated", actor_type="user", actor_id=current.id, detail={ "accountId": selected.account_id, "accountName": selected.display_name, "points": selected.points, "eliteOpened": selected_state.elite_opened, "softReasons": soft_reasons, "exchangeStatus": task.exchange_status, }, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) def release_task_account( db: Session, *, task_id: int, current: User, reason: str = "manual_release", ) -> dict[str, Any]: task = _load_task(db, task_id) lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) release_lease(db, lease, reason=reason) task.account_id = None task.lease_id = None task.bind_task_id = None task.execution_status = "ready" task.binding_status = "not_started" task.exchange_status = "not_started" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "account_released", actor_type="user", actor_id=current.id, detail={"reason": reason}, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) def reset_task_binding( db: Session, *, task_id: int, current: User, reason: str = "客服重置角色绑定", ) -> dict[str, Any]: """清空本单旧绑定与客户资料,保留账号租约供客户重新扫码。""" task = _load_task(db, task_id) if task.execution_status in {"completed", "cancelled"}: raise HTTPException(status_code=409, detail="已结束任务不能重置绑定") if task.binding_status != "failed": 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="账号租约已失效,请释放账号后重新选号" ) previous_bind_task_id = task.bind_task_id previous_bind_task = ( db.query(DouyuTask).filter(DouyuTask.id == previous_bind_task_id).first() if previous_bind_task_id else None ) if previous_bind_task and previous_bind_task.status in { "planned", "pending", "running", }: raise HTTPException(status_code=409, detail="当前绑定任务仍在执行,不能重置") previous_binding_status = task.binding_status previous_issue_code = task.issue_code task.bind_task_id = None task.binding_status = "not_started" task.execution_status = "allocated" task.exchange_status = "not_started" task.issue_code = "" task.last_error = "" task.operator_id = current.id task.updated_at = _now() renew_lease(db, lease, ttl_minutes=_lease_duration_minutes(db)) _append_event( db, task.id, "binding_reset", actor_type="user", actor_id=current.id, detail={ "reason": reason.strip()[:1000], "previousBindTaskId": previous_bind_task_id, "previousBindingStatus": previous_binding_status, "previousIssueCode": previous_issue_code, "customerProfileReset": True, }, ) _emit_order_site_binding_state( db, task.id, extra={ "customerProfileReset": True, "resetReason": reason.strip()[:1000], }, ) 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]: task = _load_task(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="账号租约已失效,请重新分配") if task.bind_task_id: existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if existing: result = existing.result or {} pending_role = pending_binding_role_from_result(result) stale_pending = ( bool(result.get("bind_ready_for_confirm")) and not pending_role ) if bool(result.get("bind_confirmed")) or pending_role: 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": {}}, created_by=current.id, ) db.add(bind_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(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() renew_lease( db, lease, ttl_minutes=_lease_duration_minutes(db), ) _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) db.commit() start_douyu_batch( batch_id=batch_id, task_type="get_bind_qr", payload={}, concurrency=1, ) return get_task_detail(db, task.id) def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: task = _load_task(db, task_id) if task.execution_status in {"completed", "cancelled"}: return get_task_detail(db, task.id) if not task.bind_task_id: return get_task_detail(db, task.id) bind_task = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if bind_task is None: return get_task_detail(db, task.id) before = ( task.binding_status, task.execution_status, task.exchange_status, task.issue_code, task.last_error, ) result = bind_task.result or {} pending_role = pending_binding_role_from_result(result) if bind_task.status in {"failed", "error", "stopped"}: task.binding_status = "failed" task.execution_status = "manual_required" task.issue_code = _binding_failure_issue(bind_task, result) task.last_error = _customer_task_message(task) elif bool(result.get("bind_confirmed")): task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" elif pending_role: task.binding_status = "role_ready" task.execution_status = "role_ready" task.issue_code = "" task.last_error = "" elif bool(result.get("bind_ready_for_confirm")): # 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针后,客户页会 # 回到已分配状态,并在下一次刷新时自动生成新二维码、重新开始轮询。 previous_bind_task_id = task.bind_task_id 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": 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) db.commit() return get_task_detail(db, task.id) elif result.get("url"): task.binding_status = "qr_pending" task.execution_status = "waiting_bind" task.issue_code = "" task.last_error = "" after = ( task.binding_status, task.execution_status, task.exchange_status, task.issue_code, task.last_error, ) if after != before: task.updated_at = _now() if task.binding_status == "failed": _append_event( db, task.id, "binding_failed", detail={ "issueCode": task.issue_code, "bindTaskId": bind_task.id, "bindPhase": str(result.get("bind_phase") or ""), "rawError": str(bind_task.message or "")[:1000], }, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: """斗鱼绑定任务落库后,把关联履约任务和 Outbox 一并刷新。""" 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 task_ids: refresh_binding(db, task_id=task_id) return len(task_ids) 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, } async def confirm_binding( db: Session, *, task_id: int, current: User ) -> dict[str, Any]: task = _load_task(db, task_id) task = _load_task(db, refresh_binding(db, task_id=task.id)["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 {} expected_role_name = str(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, ) 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() renew_lease(db, lease, ttl_minutes=_lease_duration_minutes(db)) _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) db.commit() start_douyu_batch( batch_id=batch_id, task_type="confirm_bind", payload={}, concurrency=1, ) return get_task_detail(db, task.id) def refresh_exchange_eligibility( db: Session, *, task_id: int, current: User ) -> dict[str, Any]: task = _load_task(db, task_id) if task.binding_status != "bound": raise HTTPException(status_code=409, detail="请先确认游戏角色绑定") account = db.query(Account).filter(Account.id == task.account_id).first() if account is None or not account.cookie: raise HTTPException(status_code=409, detail="账号 CK 不可用") config = ensure_douyu_config(db) try: cookie = str(account.cookie) client = activity_client(cookie) eligibility = query_exchange_eligibility( client, cookie=cookie, manual_id=str(douyu_config_value("manual_id", config.manual_id)), rid=str(douyu_config_value("rid", config.rid)), uid=str(account.uid or ""), ) account.elite_opened = bool(eligibility.elite_user_info.get("manual_type")) account.points = eligibility.points except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败 record_account_query( db, account, query_type="exchange_eligibility", title="刷新兑换资格", ok=False, detail={"error": str(exc)[:1000], "commodity_id": task.commodity_id}, actor_id=current.id, ) task.execution_status = "manual_required" task.exchange_status = "check_failed" task.issue_code = "eligibility_check_failed" task.last_error = str(exc) task.updated_at = _now() _append_event( db, task.id, "eligibility_check_failed", actor_type="user", actor_id=current.id, detail={"error": str(exc)}, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) if task.commodity_id in eligibility.limited_ids: task.exchange_status = "limited" task.issue_code = "commodity_limit_reached" task.last_error = "该账号已达到此商品兑换上限" elif not account.elite_opened: task.exchange_status = "not_opened" task.issue_code = "elite_not_opened" task.last_error = "该账号精英宝典未开通" elif task.required_points and int(account.points or 0) < int(task.required_points): task.exchange_status = "points_short" task.issue_code = "points_short" task.last_error = "该账号精英积分不足,需人工充值" else: task.exchange_status = "eligible" task.issue_code = "" task.last_error = "" record_account_commodity_state( db, account, commodity_id=task.commodity_id, availability=( AVAILABILITY_LIMITED if task.commodity_id in eligibility.limited_ids else AVAILABILITY_AVAILABLE ), blocking_reason=( "该账号已达此商品兑换上限" if task.commodity_id in eligibility.limited_ids else "" ), raw_status="1" if task.commodity_id in eligibility.limited_ids else "0", observed_at=_now(), source="eligibility_check", scope=task.scope or SCOPE_ELITE, ) record_account_query( db, account, query_type="exchange_eligibility", title="刷新兑换资格", ok=True, detail={ "commodity_id": task.commodity_id, "exchange_status": task.exchange_status, "limited": task.commodity_id in eligibility.limited_ids, "points": account.points, "elite_opened": account.elite_opened, }, actor_id=current.id, ) # 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留, # 后续充值/开通/解除限兑后刷新资格即可。 task.execution_status = "bound" task.updated_at = _now() account.updated_at = _now() _append_event( db, task.id, "exchange_eligibility_checked", actor_type="user", actor_id=current.id, detail={ "exchangeStatus": task.exchange_status, "limitedCount": len(eligibility.limited_ids), }, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) def complete_manual_exchange( db: Session, *, task_id: int, current: User, note: str = "", ) -> dict[str, Any]: task = _load_task(db, task_id) if task.binding_status != "bound": raise HTTPException(status_code=409, detail="游戏角色尚未确认绑定") if task.exchange_status not in {"eligible", "manual_done"}: raise HTTPException( status_code=409, detail="当前兑换资格不是可兑换状态,请先刷新检查结果", ) lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) task.exchange_status = "manual_done" task.execution_status = "completed" task.completed_at = _now() task.operator_id = current.id task.last_error = "" task.issue_code = "" task.updated_at = _now() release_lease(db, lease, reason="manual_exchange_completed") _append_event( db, task.id, "manual_exchange_completed", actor_type="user", actor_id=current.id, detail={"note": note[:1000]}, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) def mark_manual_required( db: Session, *, task_id: int, current: User, reason: str, ) -> dict[str, Any]: task = _load_task(db, task_id) task.execution_status = "manual_required" task.operator_id = current.id task.last_error = reason.strip()[:2000] task.issue_code = task.issue_code or "manual_required" task.updated_at = _now() _append_event( db, task.id, "marked_manual_required", actor_type="user", actor_id=current.id, detail={"reason": task.last_error}, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) def cancel_task( db: Session, *, task_id: int, current: User, reason: str, ) -> dict[str, Any]: task = _load_task(db, task_id) if task.execution_status == "cancelled": return get_task_detail(db, task.id) if task.execution_status == "completed": raise HTTPException(status_code=409, detail="已完成任务不能取消") account_id = task.account_id lease_id = task.lease_id previous_execution_status = task.execution_status previous_binding_status = task.binding_status previous_exchange_status = task.exchange_status lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) linked_tasks = ( db.query(DouyuTask) .filter( DouyuTask.id.in_( [value for value in [task.bind_task_id, task.exchange_task_id] if value] ) ) .all() if task.bind_task_id or task.exchange_task_id else [] ) stopped_batches = stop_douyu_batches( [str(linked_task.batch_id or "") for linked_task in linked_tasks] ) for linked_task in linked_tasks: if linked_task.status in {"planned", "pending", "running"}: linked_task.status = "stopped" linked_task.message = "履约任务已取消" linked_task.finished_at = _now() release_lease(db, lease, reason="platform_fulfillment_cancelled") task.account_id = None task.lease_id = None task.bind_task_id = None task.exchange_task_id = None task.binding_status = "not_started" task.execution_status = "cancelled" task.exchange_status = "not_started" task.issue_code = "" task.operator_id = current.id task.last_error = reason.strip()[:2000] task.updated_at = _now() _append_event( db, task.id, "task_cancelled", actor_type="user", actor_id=current.id, detail={ "reason": task.last_error, "previousExecutionStatus": previous_execution_status, "previousBindingStatus": previous_binding_status, "previousExchangeStatus": previous_exchange_status, "releasedAccountId": account_id, "releasedLeaseId": lease_id, "stoppedBatches": stopped_batches, }, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) def restore_cancelled_task( db: Session, *, task_id: int, current: User, reason: str, ) -> dict[str, Any]: """仅恢复人工误取消、且来源订单仍可履约的任务;不复用旧租约。""" task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == int(task_id)) .with_for_update() .first() ) if task is None: raise HTTPException(status_code=404, detail="直播账号履约任务不存在") if task.execution_status != "cancelled": raise HTTPException(status_code=409, detail="只有已取消任务可以恢复") if task.issue_code == "source_cancelled": raise HTTPException(status_code=409, detail="来源订单已取消,不能恢复") manual_cancel = ( db.query(PlatformFulfillmentEvent.id) .filter( PlatformFulfillmentEvent.task_id == task.id, PlatformFulfillmentEvent.event_type == "task_cancelled", PlatformFulfillmentEvent.actor_type == "user", ) .first() ) if manual_cancel is None: raise HTTPException(status_code=409, detail="只有人工取消的任务可以恢复") try: source = lookup_pending_manual_fulfillment(task.source_order_item_id) except OrderLookupUnavailable as exc: raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc if source is None: raise HTTPException(status_code=409, detail="来源订单不存在或已不可履约") if ( str(source.get("order_status") or "") in {"refunded", "cancelled", "closed"} or str(source.get("pay_status") or "") != "paid" or str(source.get("fulfillment_issue_code") or "") in {"user_refund", "platform_cancelled"} ): raise HTTPException(status_code=409, detail="来源订单已退款、关闭或取消,不能恢复") restore_reason = reason.strip() if len(restore_reason) < 2: raise HTTPException(status_code=400, detail="请填写恢复原因") restored_collab = ( db.query(DouyuExternalOrder) .filter(DouyuExternalOrder.source_task_id == task.id) .first() ) if restored_collab is not None and ( restored_collab.status not in {"incomplete", "void"} or restored_collab.bind_game_role or restored_collab.home_images ): raise HTTPException( status_code=409, detail="关联外部协作单已在人工处理,请继续使用外部协作单", ) mapping = _mapping_for_sku(db, task.internal_sku_key) _apply_mapping(task, mapping) task.account_id = None task.lease_id = None task.bind_task_id = None task.exchange_task_id = None task.binding_status = "not_started" task.exchange_status = "not_started" task.completed_at = None task.next_allocate_at = _now() if task.execution_status == "ready" else None task.operator_id = current.id task.updated_at = _now() restored_collab_status = "" if restored_collab is not None and restored_collab.status == "void": restored_collab.status = "incomplete" restored_collab.void_reason = "" restored_collab.updated_by = current.id restored_collab.updated_at = _now() restored_collab.version = int(restored_collab.version or 0) + 1 restored_collab_status = restored_collab.status _append_event( db, task.id, "task_restored", actor_type="user", actor_id=current.id, detail={ "reason": restore_reason, "restoredExecutionStatus": task.execution_status, "restoredCollabOrderId": ( int(restored_collab.id) if restored_collab is not None else None ), "restoredCollabStatus": restored_collab_status, }, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) def release_task_to_manual( db: Session, *, task_id: int, current: User, reason: str, ) -> dict[str, Any]: """释放履约账号并转人工,不再进入自动选号。""" task = _load_task(db, task_id) if task.execution_status in {"completed", "cancelled"}: raise HTTPException(status_code=409, detail="已结束任务不能转人工") manual_reason = reason.strip()[:2000] or "以外部单协作人工处理为准" account_id = task.account_id lease_id = task.lease_id lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) release_lease(db, lease, reason="platform_fulfillment_manual") task.account_id = None task.lease_id = None task.bind_task_id = None task.exchange_task_id = None task.execution_status = "manual_required" task.binding_status = "not_started" task.exchange_status = "not_started" task.issue_code = "manual_required" task.next_allocate_at = None task.operator_id = current.id task.last_error = manual_reason task.updated_at = _now() _append_event( db, task.id, "released_to_manual", actor_type="user", actor_id=current.id, detail={ "reason": manual_reason, "releasedAccountId": account_id, "releasedLeaseId": lease_id, }, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) __all__ = [ "allocate_task", "cancel_task", "complete_manual_exchange", "confirm_binding", "customer_refresh_bindings", "get_task_detail", "list_mappings", "list_tasks", "mark_manual_required", "reconcile_binding_state_outbox", "record_douyu_operation_result", "record_douyu_operation_started", "refresh_binding", "refresh_exchange_eligibility", "release_task_account", "release_task_to_manual", "reset_task_binding", "restore_cancelled_task", "start_binding", "sync_order_item_ids", "sync_order_snapshot", "sync_pending_tasks", "sync_pending_tasks_if_due", "sync_task_from_binding_runner", "upsert_mapping", ]