- 回滚 QYOOB-only 门禁,扫到新角色即进入 role_ready - 客户页 readiness 与平台任务 role_ready 对齐,避免确认接口 409 - 绑定证据 baseline 不再冒充本次扫码 - 新增人工确认绑定接口与按钮(角色、备注、操作人事件) - 补充客户确认、证据口径和人工确认回归测试
711 lines
24 KiB
Python
711 lines
24 KiB
Python
"""履约任务列表、详情和面客绑定视图。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
import weakref
|
|
from dataclasses import dataclass
|
|
from datetime import UTC, datetime
|
|
from typing import Any
|
|
|
|
from sqlalchemy import or_
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ...models import (
|
|
Account,
|
|
AccountLease,
|
|
DouyuExternalOrder,
|
|
DouyuGoodsSnapshot,
|
|
DouyuTask,
|
|
PlatformCommodityMapping,
|
|
PlatformFulfillmentEvent,
|
|
PlatformFulfillmentTask,
|
|
User,
|
|
)
|
|
from ...permissions import ROLE_LABELS
|
|
from ..douyu_binding import (
|
|
BINDING_OBSERVATION_TASK_TYPES,
|
|
BINDING_VIEW_CONFIRMED,
|
|
BINDING_VIEW_FAILED,
|
|
BINDING_VIEW_PENDING,
|
|
resolve_fulfillment_binding,
|
|
)
|
|
from ..file_service import build_file_url
|
|
from . import classification
|
|
from .binding_evidence import build_binding_evidence
|
|
from .binding_status import (
|
|
_customer_task_message,
|
|
_customer_task_message_for,
|
|
_effective_binding_issue,
|
|
_effective_task_message,
|
|
_normalized_event_detail,
|
|
)
|
|
from .common import (
|
|
_apply_order_match_cutoff,
|
|
_jsonable,
|
|
_order_match_started_at,
|
|
)
|
|
from .repository import _load_task
|
|
|
|
_TASK_COUNT_CACHE_TTL_SECONDS = 15.0
|
|
_TASK_COUNT_CACHE_MAX_ENTRIES = 512
|
|
_TASK_COUNT_CACHE: weakref.WeakKeyDictionary[
|
|
Any, dict[tuple[Any, ...], tuple[float, int]]
|
|
] = weakref.WeakKeyDictionary()
|
|
_TASK_COUNT_CACHE_LOCK = threading.Lock()
|
|
|
|
|
|
@dataclass
|
|
class _TaskOutputContext:
|
|
mappings: dict[int, PlatformCommodityMapping]
|
|
goods: dict[str, DouyuGoodsSnapshot]
|
|
accounts: dict[int, Account]
|
|
leases: dict[int, AccountLease]
|
|
bind_tasks: dict[int, DouyuTask]
|
|
collab_orders: dict[int, DouyuExternalOrder]
|
|
|
|
|
|
def invalidate_task_list_count_cache() -> None:
|
|
"""任务写入后清空分页总数缓存,最多 15 秒的跨进程陈旧由 TTL 兜底。"""
|
|
with _TASK_COUNT_CACHE_LOCK:
|
|
_TASK_COUNT_CACHE.clear()
|
|
|
|
|
|
def _count_cache_key(
|
|
*,
|
|
cutoff: datetime | None,
|
|
status: str,
|
|
queue_bucket: str,
|
|
sale_mode: str,
|
|
keyword: str,
|
|
) -> tuple[Any, ...]:
|
|
return (
|
|
cutoff,
|
|
status,
|
|
queue_bucket,
|
|
sale_mode,
|
|
keyword.strip(),
|
|
)
|
|
|
|
|
|
def _cached_task_count(
|
|
db: Session,
|
|
query,
|
|
*,
|
|
key: tuple[Any, ...],
|
|
) -> int:
|
|
moment = time.monotonic()
|
|
bind = db.get_bind()
|
|
with _TASK_COUNT_CACHE_LOCK:
|
|
engine_cache = _TASK_COUNT_CACHE.setdefault(bind, {})
|
|
cached = engine_cache.get(key)
|
|
if cached and moment - cached[0] < _TASK_COUNT_CACHE_TTL_SECONDS:
|
|
return cached[1]
|
|
total = int(query.count())
|
|
with _TASK_COUNT_CACHE_LOCK:
|
|
engine_cache = _TASK_COUNT_CACHE.setdefault(bind, {})
|
|
if len(engine_cache) >= _TASK_COUNT_CACHE_MAX_ENTRIES:
|
|
expired_before = moment - _TASK_COUNT_CACHE_TTL_SECONDS
|
|
for cache_key, (cached_at, _) in list(engine_cache.items()):
|
|
if cached_at < expired_before:
|
|
engine_cache.pop(cache_key, None)
|
|
if len(engine_cache) >= _TASK_COUNT_CACHE_MAX_ENTRIES:
|
|
engine_cache.pop(next(iter(engine_cache)), None)
|
|
engine_cache[key] = (moment, total)
|
|
return total
|
|
|
|
|
|
def _load_task_output_context(
|
|
db: Session,
|
|
tasks: list[PlatformFulfillmentTask],
|
|
) -> _TaskOutputContext:
|
|
mapping_ids = {
|
|
int(task.commodity_mapping_id)
|
|
for task in tasks
|
|
if task.commodity_mapping_id
|
|
}
|
|
commodity_ids = {
|
|
str(task.commodity_id)
|
|
for task in tasks
|
|
if task.commodity_id
|
|
}
|
|
account_ids = {int(task.account_id) for task in tasks if task.account_id}
|
|
lease_ids = {int(task.lease_id) for task in tasks if task.lease_id}
|
|
bind_task_ids = {int(task.bind_task_id) for task in tasks if task.bind_task_id}
|
|
task_ids = {int(task.id) for task in tasks}
|
|
|
|
mappings = (
|
|
{
|
|
int(row.id): row
|
|
for row in db.query(PlatformCommodityMapping)
|
|
.filter(PlatformCommodityMapping.id.in_(mapping_ids))
|
|
.all()
|
|
}
|
|
if mapping_ids
|
|
else {}
|
|
)
|
|
goods: dict[str, DouyuGoodsSnapshot] = {}
|
|
if commodity_ids:
|
|
for row in (
|
|
db.query(DouyuGoodsSnapshot)
|
|
.filter(DouyuGoodsSnapshot.commodity_id.in_(commodity_ids))
|
|
.order_by(DouyuGoodsSnapshot.id.desc())
|
|
.all()
|
|
):
|
|
goods.setdefault(str(row.commodity_id), row)
|
|
accounts = (
|
|
{
|
|
int(row.id): row
|
|
for row in db.query(Account).filter(Account.id.in_(account_ids)).all()
|
|
}
|
|
if account_ids
|
|
else {}
|
|
)
|
|
leases = (
|
|
{
|
|
int(row.id): row
|
|
for row in db.query(AccountLease)
|
|
.filter(AccountLease.id.in_(lease_ids))
|
|
.all()
|
|
}
|
|
if lease_ids
|
|
else {}
|
|
)
|
|
bind_tasks = (
|
|
{
|
|
int(row.id): row
|
|
for row in db.query(DouyuTask)
|
|
.filter(DouyuTask.id.in_(bind_task_ids))
|
|
.all()
|
|
}
|
|
if bind_task_ids
|
|
else {}
|
|
)
|
|
collab_orders: dict[int, DouyuExternalOrder] = {}
|
|
if task_ids:
|
|
for row in (
|
|
db.query(DouyuExternalOrder)
|
|
.filter(DouyuExternalOrder.source_task_id.in_(task_ids))
|
|
.order_by(DouyuExternalOrder.id.desc())
|
|
.all()
|
|
):
|
|
if row.source_task_id is not None:
|
|
collab_orders.setdefault(int(row.source_task_id), row)
|
|
return _TaskOutputContext(
|
|
mappings=mappings,
|
|
goods=goods,
|
|
accounts=accounts,
|
|
leases=leases,
|
|
bind_tasks=bind_tasks,
|
|
collab_orders=collab_orders,
|
|
)
|
|
|
|
|
|
def list_tasks(
|
|
db: Session,
|
|
*,
|
|
status: str = "",
|
|
queue_bucket: str = "",
|
|
sale_mode: str = "",
|
|
keyword: str = "",
|
|
page: int = 1,
|
|
page_size: int = 20,
|
|
) -> dict[str, Any]:
|
|
cutoff = _order_match_started_at(db)
|
|
query = db.query(PlatformFulfillmentTask)
|
|
query = _apply_order_match_cutoff(query, cutoff)
|
|
query = query.filter(
|
|
or_(
|
|
PlatformFulfillmentTask.commodity_mapping_id.isnot(None),
|
|
PlatformFulfillmentTask.commodity_id != "",
|
|
)
|
|
)
|
|
mode_filter = classification.normalize_sale_mode(sale_mode)
|
|
if sale_mode and mode_filter != "unknown":
|
|
query = query.filter(PlatformFulfillmentTask.sale_mode == mode_filter)
|
|
elif sale_mode == "unknown":
|
|
query = query.filter(PlatformFulfillmentTask.sale_mode == "unknown")
|
|
if queue_bucket:
|
|
now = datetime.now(UTC)
|
|
if queue_bucket == classification.QUEUE_CANCELLED:
|
|
query = query.filter(
|
|
PlatformFulfillmentTask.execution_status == "cancelled"
|
|
)
|
|
elif queue_bucket == classification.QUEUE_COMPLETED:
|
|
query = query.filter(
|
|
PlatformFulfillmentTask.execution_status == "completed"
|
|
)
|
|
elif queue_bucket == classification.QUEUE_PENDING_MAPPING:
|
|
query = query.filter(
|
|
PlatformFulfillmentTask.execution_status == "pending_mapping"
|
|
)
|
|
elif queue_bucket == classification.QUEUE_NEEDS_ACTION:
|
|
query = query.filter(
|
|
PlatformFulfillmentTask.execution_status == "manual_required"
|
|
)
|
|
elif queue_bucket == classification.QUEUE_PRESALE_WAITING:
|
|
query = query.filter(
|
|
PlatformFulfillmentTask.execution_status.notin_(
|
|
["completed", "cancelled", "pending_mapping", "manual_required"]
|
|
),
|
|
PlatformFulfillmentTask.sale_mode == "presale",
|
|
or_(
|
|
PlatformFulfillmentTask.offer_available_from.is_(None),
|
|
PlatformFulfillmentTask.offer_available_from > now,
|
|
),
|
|
)
|
|
elif queue_bucket == classification.QUEUE_READY:
|
|
query = query.filter(
|
|
PlatformFulfillmentTask.execution_status.notin_(
|
|
["completed", "cancelled", "pending_mapping", "manual_required"]
|
|
),
|
|
or_(
|
|
PlatformFulfillmentTask.sale_mode != "presale",
|
|
PlatformFulfillmentTask.offer_available_from.is_(None),
|
|
PlatformFulfillmentTask.offer_available_from <= now,
|
|
),
|
|
)
|
|
else:
|
|
query = query.filter(
|
|
PlatformFulfillmentTask.execution_status.notin_(
|
|
["completed", "cancelled"]
|
|
)
|
|
)
|
|
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.outerjoin(
|
|
Account,
|
|
Account.id == PlatformFulfillmentTask.account_id,
|
|
).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),
|
|
Account.username.ilike(pattern),
|
|
Account.nickname.ilike(pattern),
|
|
Account.uid.ilike(pattern),
|
|
)
|
|
)
|
|
total = _cached_task_count(
|
|
db,
|
|
query,
|
|
key=_count_cache_key(
|
|
cutoff=cutoff,
|
|
status=status,
|
|
queue_bucket=queue_bucket,
|
|
sale_mode=sale_mode,
|
|
keyword=keyword,
|
|
),
|
|
)
|
|
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()
|
|
)
|
|
context = _load_task_output_context(db, rows)
|
|
return {
|
|
"items": [_task_out(db, row, context=context) 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,
|
|
include_exchange_task: bool = False,
|
|
context: _TaskOutputContext | None = None,
|
|
) -> dict[str, Any]:
|
|
resolved = context or _load_task_output_context(db, [task])
|
|
mapping = (
|
|
resolved.mappings.get(int(task.commodity_mapping_id))
|
|
if task.commodity_mapping_id
|
|
else None
|
|
)
|
|
goods = (
|
|
resolved.goods.get(str(task.commodity_id))
|
|
if task.commodity_id
|
|
else None
|
|
)
|
|
goods_name = (
|
|
str(getattr(mapping, "goods_name", "") or "")
|
|
or str(getattr(goods, "name", "") or "")
|
|
or task.sku_name
|
|
or task.internal_sku_key
|
|
)
|
|
account = (
|
|
resolved.accounts.get(int(task.account_id)) if task.account_id else None
|
|
)
|
|
lease = resolved.leases.get(int(task.lease_id)) if task.lease_id else None
|
|
bind_task = (
|
|
resolved.bind_tasks.get(int(task.bind_task_id))
|
|
if task.bind_task_id
|
|
else None
|
|
)
|
|
collab_order = resolved.collab_orders.get(int(task.id))
|
|
bind_result = (bind_task.result or {}) if bind_task else {}
|
|
binding = resolve_fulfillment_binding(
|
|
bind_task,
|
|
account=account,
|
|
binding_status=task.binding_status,
|
|
)
|
|
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
|
effective_last_error = _effective_task_message(task, effective_issue)
|
|
exchange_task_id = task.exchange_task_id
|
|
if exchange_task_id is None and include_exchange_task:
|
|
exchange_task_id = (
|
|
db.query(DouyuTask.id)
|
|
.filter(
|
|
DouyuTask.platform_task_id == task.id,
|
|
DouyuTask.task_type == "exchange_goods",
|
|
)
|
|
.order_by(DouyuTask.id.desc())
|
|
.limit(1)
|
|
.scalar()
|
|
)
|
|
sale_mode = classification.normalize_sale_mode(task.sale_mode)
|
|
availability = classification.availability_state(
|
|
sale_mode=sale_mode,
|
|
available_from=task.offer_available_from,
|
|
available_until=task.offer_available_until,
|
|
)
|
|
queue_bucket = classification.queue_bucket(
|
|
execution_status=task.execution_status,
|
|
sale_mode=sale_mode,
|
|
availability=availability,
|
|
)
|
|
manual_reason = (
|
|
classification.manual_reason(effective_issue, task.exchange_status)
|
|
if task.execution_status == "manual_required"
|
|
else ""
|
|
)
|
|
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,
|
|
"goodsName": goods_name,
|
|
"requiredPoints": task.required_points,
|
|
"saleMode": sale_mode,
|
|
"campaignKey": task.campaign_key,
|
|
"campaignName": task.campaign_name,
|
|
"offerAvailableFrom": task.offer_available_from,
|
|
"offerAvailableUntil": task.offer_available_until,
|
|
"availabilityState": availability,
|
|
"queueBucket": queue_bucket,
|
|
"manualReason": manual_reason,
|
|
"classificationSource": task.classification_source,
|
|
"bindingStatus": task.binding_status,
|
|
"executionStatus": task.execution_status,
|
|
"exchangeStatus": task.exchange_status,
|
|
"issueCode": effective_issue,
|
|
"lastError": effective_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": binding.qr_url if include_qr else "",
|
|
"roleName": binding.effective_role_name,
|
|
"areaName": binding.effective_area_name,
|
|
"platName": binding.effective_plat_name,
|
|
"bindPhase": binding.bind_phase,
|
|
# 客户页的“可确认”必须与确认接口读的同一层事实一致:
|
|
# 绑定任务 pending 且平台任务已经进入 role_ready,才显示确认按钮。
|
|
# 否则会出现客户页让确认、确认接口报“没有待确认角色”的错位。
|
|
"bindReadyForConfirm": (
|
|
binding.status == BINDING_VIEW_PENDING
|
|
and str(task.binding_status or "") == "role_ready"
|
|
),
|
|
"bindConfirmed": binding.bind_confirmed,
|
|
}
|
|
if bind_task
|
|
else None
|
|
),
|
|
"bindingEvidence": (
|
|
build_binding_evidence(db, task, bind_task, account)
|
|
if include_qr and bind_task is not None
|
|
else None
|
|
),
|
|
"exchangeTaskId": exchange_task_id,
|
|
"exchangeResultImage": (
|
|
{
|
|
"objectKey": task.exchange_result_image_key,
|
|
"url": build_file_url(task.exchange_result_image_key),
|
|
"savedAt": task.exchange_result_image_saved_at,
|
|
}
|
|
if task.exchange_result_image_key
|
|
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 {}
|
|
)
|
|
bind_task_ids: set[int] = set()
|
|
for event in events:
|
|
detail = event.detail_json or {}
|
|
raw_id = (
|
|
detail.get("douyuTaskId")
|
|
if event.event_type.startswith("douyu_operation_")
|
|
else detail.get("bindTaskId")
|
|
)
|
|
try:
|
|
bind_task_id = int(raw_id) if raw_id is not None else 0
|
|
except (TypeError, ValueError):
|
|
bind_task_id = 0
|
|
if bind_task_id:
|
|
bind_task_ids.add(bind_task_id)
|
|
bind_tasks = (
|
|
{
|
|
int(row.id): row
|
|
for row in db.query(DouyuTask).filter(DouyuTask.id.in_(bind_task_ids)).all()
|
|
}
|
|
if bind_task_ids
|
|
else {}
|
|
)
|
|
return {
|
|
"task": _task_out(db, task, include_qr=True, include_exchange_task=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": _normalized_event_detail(event, bind_tasks),
|
|
"createdAt": event.created_at,
|
|
}
|
|
for event in events
|
|
],
|
|
}
|
|
|
|
|
|
def _customer_binding_queue_state(
|
|
task: PlatformFulfillmentTask,
|
|
bind_task: DouyuTask | None,
|
|
*,
|
|
lease_ready: bool,
|
|
) -> tuple[str, int]:
|
|
if task.execution_status == "completed":
|
|
return "completed", 0
|
|
if task.execution_status == "cancelled":
|
|
return "cancelled", 0
|
|
if task.issue_code == "mapping_missing":
|
|
return "mapping_missing", 0
|
|
if not task.account_id or not task.lease_id:
|
|
return "allocation_queued", 2000
|
|
if not lease_ready:
|
|
return "lease_inactive", 0
|
|
if task.binding_status == "failed":
|
|
return "failed", 0
|
|
if bind_task is None:
|
|
return "ready_to_start", 0
|
|
if (
|
|
bind_task.task_type in BINDING_OBSERVATION_TASK_TYPES
|
|
and task.binding_status != "bound"
|
|
):
|
|
return "ready_to_start", 0
|
|
binding = resolve_fulfillment_binding(
|
|
bind_task,
|
|
account=None,
|
|
binding_status=task.binding_status,
|
|
)
|
|
if binding.status == BINDING_VIEW_CONFIRMED:
|
|
return "confirmed", 0
|
|
if binding.status == BINDING_VIEW_PENDING:
|
|
return "role_ready", 0
|
|
if binding.status == BINDING_VIEW_FAILED:
|
|
return "failed", 0
|
|
if task.binding_status == "confirming":
|
|
return "confirming", 1000
|
|
if bind_task.status in {"planned", "pending"}:
|
|
return "qr_queued", 1000
|
|
if binding.qr_url:
|
|
return (
|
|
"waiting_scan",
|
|
5000 if (bind_task.result or {}).get("bind_polling") else 0,
|
|
)
|
|
return "preparing", 1000
|
|
|
|
|
|
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 {}
|
|
account = db.get(Account, int(task.account_id)) if task.account_id else None
|
|
binding = resolve_fulfillment_binding(
|
|
bind_task,
|
|
account=account,
|
|
binding_status=task.binding_status,
|
|
)
|
|
effective_issue = _effective_binding_issue(task, bind_task, 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")
|
|
queue_state, retry_after_ms = _customer_binding_queue_state(
|
|
task,
|
|
bind_task,
|
|
lease_ready=lease_ready,
|
|
)
|
|
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": effective_issue,
|
|
"message": (
|
|
_customer_task_message_for(effective_issue)
|
|
if effective_issue != task.issue_code
|
|
else _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.effective_role_name,
|
|
"areaName": binding.effective_area_name,
|
|
"platName": binding.effective_plat_name,
|
|
# 客户页的“可确认”必须与确认接口读的同一层事实一致:
|
|
# 绑定任务 pending 且平台任务已经进入 role_ready,才显示确认按钮。
|
|
"bindReadyForConfirm": (
|
|
binding.status == BINDING_VIEW_PENDING
|
|
and str(task.binding_status or "") == "role_ready"
|
|
),
|
|
"bindConfirmed": binding.bind_confirmed,
|
|
"queueState": queue_state,
|
|
"retryAfterMs": retry_after_ms,
|
|
"queueLane": bind_task.queue_lane if bind_task else "",
|
|
"accepted": False,
|
|
"stateVersion": int(task.state_version or 0),
|
|
"completedAt": _jsonable(task.completed_at),
|
|
"updatedAt": _jsonable(task.updated_at),
|
|
}
|