修复(履约绑定): 收敛活动别名中的瞬时历史角色

This commit is contained in:
yml
2026-11-26 01:03:22 +08:00
parent 4198f7ab39
commit 204cbd5d82
10 changed files with 574 additions and 47 deletions
@@ -156,7 +156,10 @@ def start_binding_sync(
handbook_scope="elite",
status="planned",
message="等待生成绑定二维码",
result={"payload": {}},
result={
"payload": {},
"expected_role_name": str(task.customer_role_name or "").strip(),
},
created_by=current.id,
platform_task_id=task.id,
)
@@ -305,6 +308,147 @@ def _order_target_role(
return ""
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)
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_binding_rejection(
db: Session,
task: PlatformFulfillmentTask,
@@ -684,24 +828,37 @@ def manual_confirm_binding_sync(
if task.bind_task_id
else None
)
if bind_task is not None and str(bind_task.status or "") in {
"planned",
"pending",
"running",
}:
if bind_task is not None:
result = dict(bind_task.result or {})
previous_pending_role = str(
result.get("pending_role_name") or result.get("role_name") or ""
).strip()
account_channel = str(account.game_channel or "").strip()
area_name, _, plat_name = account_channel.partition(" · ")
result.update(
{
"manual_confirmed": True,
"manual_confirmed_role": confirmed_role,
"manual_confirmed_by": int(current.id),
"manual_confirm_note": note,
"previous_pending_role_name": previous_pending_role[:128],
"bind_phase": "manual_confirmed",
"bind_polling": False,
"bind_ready_for_confirm": False,
"bind_confirmed": True,
"pending_role_name": "",
"role_name": confirmed_role,
"current_role_name": confirmed_role,
"area_name": area_name,
"plat_name": plat_name,
"is_bound_act": True,
"is_bound_role": True,
}
)
bind_task.status = "stopped"
bind_task.status = "success"
bind_task.queue_lane = ""
bind_task.next_run_at = None
bind_task.run_deadline_at = None
bind_task.message = f"人工确认绑定: {confirmed_role}"[:512]
bind_task.finished_at = _now()
bind_task.result = result
@@ -962,11 +1119,21 @@ def _apply_binding_task(
_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
@@ -1040,6 +1207,15 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
)
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()
@@ -1069,7 +1245,11 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
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 = (
@@ -1178,6 +1358,19 @@ def reconcile_binding_observations(
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
@@ -211,18 +211,43 @@ def build_binding_evidence(
action_pending_role = (
_text((action_pending or {}).get("roleName")) if action_pending else ""
)
legacy_role = _text((legacy_latest or {}).get("roleName"))
action_alias_has_role = any(
item["alias"] in action_aliases and item["roleName"]
for item in candidates
)
account_current_role = _text(account.game_name) if account is not None else ""
# scannedRole 只认“本次新扫码”:
# - 新 pending(QYOOB bindAct=0 / 可确认角色);
# - legacy(cjm) 上出现的扫码角色;
# - decision 明确可确认时的角色。
# 不能用 result.role_name / before_bind_info 的 baseline 兜底,否则会把
# 账号上一单的旧角色误报成本次扫码,详情就会和列表的“待扫码”冲突。
decision_role = (
_text(decision.get("role_name"))
if decision.get("confirmable")
and (
selected_alias in action_aliases
or not action_alias_has_role
)
else ""
)
scanned_role = _text(
pending_role
or (legacy_latest or {}).get("roleName")
or action_pending_role
or (decision.get("role_name") if decision.get("confirmable") else "")
or decision_role
)
if (
not scanned_role
and action_current is not None
and account_current_role
and legacy_role
and legacy_role == account_current_role
and _text(action_current.get("roleName")) == account_current_role
):
scanned_role = account_current_role
if not scanned_role and not action_alias_has_role:
scanned_role = legacy_role
# 取消 QYOOB-only 门禁后,cjm 的新角色同样可以成为客户确认目标;
# 这里展示真实本次扫码角色,避免详情说“不可确认”但客户页可以确认。
target_role = scanned_role
@@ -231,7 +256,6 @@ def build_binding_evidence(
or (selected_info or {}).get("role_name")
or (result.get("before_bind_info") or {}).get("role_name")
)
account_current_role = _text(account.game_name) if account is not None else ""
same_pair = bool(
scanned_role
and account_current_role
@@ -10,6 +10,7 @@ from sqlalchemy.orm import Session
from ...models import (
AccountLease,
DouyuTask,
PlatformFulfillmentTask,
)
from .binding import (
@@ -99,6 +100,15 @@ def save_customer_profile(
task.customer_home_images = images
task.customer_profile_updated_at = datetime.now(UTC)
task.updated_at = datetime.now(UTC)
if task.bind_task_id and task.customer_role_name:
bind_task = db.get(DouyuTask, int(task.bind_task_id))
if bind_task is not None and bind_task.task_type in {
"get_bind_qr",
"confirm_bind",
}:
result = dict(bind_task.result or {})
result["expected_role_name"] = task.customer_role_name
bind_task.result = result
_append_event(
db,
task.id,
@@ -11,6 +11,7 @@ from fastapi import HTTPException
from sqlalchemy.orm import Session
from ...models import (
DouyuTask,
PlatformCommodityMapping,
PlatformFulfillmentTask,
)
@@ -47,6 +48,8 @@ _AUTO_SYNC_LAST_ATTEMPT = float("-inf")
def _apply_customer_profile(
task: PlatformFulfillmentTask,
snapshot: dict[str, Any],
*,
db: Session | None = None,
) -> None:
"""order_site contractVersion=3 快照里的客户资料和主页截图。"""
keys = {
@@ -108,6 +111,15 @@ def _apply_customer_profile(
default=None,
)
)
if db is not None and task.bind_task_id and task.customer_role_name:
bind_task = db.get(DouyuTask, int(task.bind_task_id))
if bind_task is not None and bind_task.task_type in {
"get_bind_qr",
"confirm_bind",
}:
result = dict(bind_task.result or {})
result["expected_role_name"] = task.customer_role_name
bind_task.result = result
def _upsert_order_snapshot(
@@ -227,7 +239,7 @@ def _upsert_order_snapshot(
task.required_points,
task.issue_code,
)
_apply_customer_profile(task, snapshot)
_apply_customer_profile(task, snapshot, db=db)
terminal = (
terminal_order
or _snapshot_value(
@@ -583,7 +595,7 @@ def _sync_pending_tasks(
task.target_platform = TARGET_PLATFORM
task.scope = SCOPE_ELITE
task.source_snapshot_json = _jsonable(row)
_apply_customer_profile(task, row)
_apply_customer_profile(task, row, db=db)
task.updated_at = _now()
if task.account_id is None and task.execution_status in {
"pending_mapping",