修复(履约绑定): 修复候选快照丢失与全链路绑定校验一致性

This commit is contained in:
yml
2026-11-26 13:50:10 +08:00
parent 49498e88f2
commit 554d399358
10 changed files with 851 additions and 70 deletions
+64
View File
@@ -1278,3 +1278,67 @@ def test_livelink_mini_qrcode_uses_har_query_and_headers(monkeypatch):
assert calls[0]["headers"]["Gap-Act-Id"] == "16046"
assert calls[0]["headers"]["Gap-Plat-Id"] == "douyu"
assert calls[0]["headers"]["Origin"] == "https://livelink.qq.com"
def test_pending_binding_role_hydrates_stripped_action_candidate_without_baseline():
"""历史任务 bind_candidates 缺少 need_bind_act 时,应从 bind_info / decisions 补全。"""
result = {
"act_alias": ACT_ALIAS,
"action_act_aliases": [ACT_ALIAS],
"baseline_role_name": "",
"baseline_is_bound_act": False,
"before_bind_info": {},
"expected_role_name": "欧美真心",
"expected_role_required": True,
"role_name": "欧美真心",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_info": {
"act_alias": ACT_ALIAS,
"role_name": "欧美真心",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
},
"bind_candidates": [
{
"act_alias": LEGACY_ALIAS,
"role_name": "欧美真心",
"is_bound_act": False,
},
{
"act_alias": ACT_ALIAS,
"role_name": "欧美真心",
"is_bound_act": False,
},
],
"bind_candidate_decisions": [
{
"alias": ACT_ALIAS,
"role_name": "欧美真心",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
"actionable_alias": True,
"confirmable": True,
"reason": "existing_actionable_pending",
},
{
"alias": LEGACY_ALIAS,
"role_name": "欧美真心",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": False,
"need_bind_role": True,
"actionable_alias": False,
"confirmable": False,
"reason": "pending_without_baseline",
},
],
}
assert pending_binding_role_from_result(result) == "欧美真心"
+229
View File
@@ -1494,6 +1494,98 @@ def test_workbench_rebind_detects_new_cjm_scan_without_expected_role(
assert pending_binding_role_from_result(task.result) == "巫师基尔斯84"
def test_binding_poll_empty_baseline_preserves_need_bind_act_on_candidates(
db, monkeypatch
):
"""扫码前双方都为空、扫码后动作通道出现 pending 时,bind_candidates 不能丢弃 need_bind_act。"""
_, account, task = _fixtures(db, status="running")
task.queue_lane = "binding_poll"
task.next_run_at = datetime.now(UTC)
task.run_deadline_at = datetime.now(UTC) + timedelta(minutes=10)
empty_legacy = {
"act_alias": "cjm",
"role_name": "",
"is_bound_act": False,
"is_bound_role": False,
"need_bind_act": False,
"need_bind_role": True,
}
empty_action = {
"act_alias": "20260120QYOOB",
"role_name": "",
"is_bound_act": False,
"is_bound_role": False,
"need_bind_act": True,
"need_bind_role": True,
}
pending_legacy = {
"act_alias": "cjm",
"role_name": "欧美真心",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": False,
"need_bind_role": True,
}
pending_action = {
"act_alias": "20260120QYOOB",
"role_name": "欧美真心",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
}
stage = {"candidates": [empty_legacy, empty_action]}
client = type(
"Client",
(),
{"get_bind_qr": lambda self, _alias: {"url": "https://example.test/qr"}},
)()
runner = DouyuBatchRunner(
db,
task.batch_id,
"get_bind_qr",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: client)
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda _client, aliases: [
item
for alias in aliases
for item in stage["candidates"]
if item["act_alias"] == alias
],
)
config = {
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
}
runner._execute_get_bind_qr(db, task, account, "PHPSESSID=x", config)
stage["candidates"] = [pending_legacy, pending_action]
runner.poll_bind_role_once(db, task, account, config)
db.refresh(task)
assert task.status == "success"
assert task.result["bind_phase"] == "role_ready"
action_cand = next(
item
for item in task.result["bind_candidates"]
if item["act_alias"] == "20260120QYOOB"
)
assert action_cand["need_bind_act"] is True
assert action_cand["is_bound_role"] is True
assert action_cand["area_name"] == "手Q"
assert action_cand["plat_name"] == "苹果(iOS)"
assert pending_binding_role_from_result(task.result) == "欧美真心"
def test_binding_poll_preserves_concurrently_written_expected_role(
db, monkeypatch
):
@@ -1801,3 +1893,140 @@ def test_mysql_lock_wait_timeout_is_bounded():
).scalar()
assert value is not None
assert int(value) <= 10
def test_confirm_bind_rejects_when_after_bound_role_mismatches_expected(
db, monkeypatch
):
"""actBind 后动作通道仍绑定旧角色而非目标角色时,必须判失败且保留 action_act_aliases。"""
_, account, task = _fixtures(db, status="running")
old_role = "历史旧角色"
target_role = "目标新角色"
task.task_type = "confirm_bind"
task.result = {
"expected_role_name": target_role,
"expected_role_required": True,
"baseline_role_name": old_role,
}
account.game_name = old_role
account.role_bind_status = "bound"
db.commit()
old_bound = {
"act_alias": "20260120QYOOB",
"role_name": old_role,
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": True,
"need_bind_act": True,
"need_bind_role": True,
}
cjm_target = {
**old_bound,
"act_alias": "cjm",
"role_name": target_role,
"is_bound_act": False,
"need_bind_act": False,
}
class Client:
@staticmethod
def confirm_bind(_alias):
return {"ctn": "ctn", "raw": {"error": 0, "msg": "ok"}}
runner = DouyuBatchRunner(
db,
task.batch_id,
"confirm_bind",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: Client())
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda *_args: [cjm_target, old_bound],
)
runner._execute_confirm_bind(
db,
task,
account,
"PHPSESSID=x",
{
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
},
)
db.refresh(task)
db.refresh(account)
assert task.status == "failed"
assert task.result["issue_code"] == "role_changed"
assert task.result["bind_confirmed"] is False
assert task.result["action_act_aliases"] == ["20260120QYOOB"]
assert len(task.result["bind_candidates"]) == 2
assert account.game_name == old_role
def test_query_esports_game_name_uses_valid_bind_status_enums(db, monkeypatch):
"""电竞手册未确认或未绑定时,查询角色不能向 set_bind_status 传入旧自由文本。"""
_, account, task = _fixtures(db, status="running")
task.task_type = "query_esports_game_name"
task.handbook_scope = "esports"
db.commit()
states = iter(
[
{
"role_name": "电竞待确认角色",
"area_name": "微信",
"plat_name": "苹果(iOS)",
"esports_bound": False,
"is_bound_act": False,
"is_bound_role": True,
"game_id": "pel",
},
{
"role_name": "",
"area_name": "",
"plat_name": "",
"esports_bound": False,
"is_bound_act": False,
"is_bound_role": False,
"game_id": "pel",
},
]
)
runner = DouyuBatchRunner(
db,
task.batch_id,
"query_esports_game_name",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: object())
monkeypatch.setattr(runner, "_esports_bind_state", lambda *_args: next(states))
runner._execute_query_esports_game_name(
db,
task,
account,
"PHPSESSID=x",
{"esports_act_alias": "ESPORTS_ACT"},
)
db.refresh(account)
db.refresh(task)
assert task.status == "success"
assert account.esports_bind_status == "pending"
runner._execute_query_esports_game_name(
db,
task,
account,
"PHPSESSID=x",
{"esports_act_alias": "ESPORTS_ACT"},
)
db.refresh(account)
assert account.esports_bind_status == "unbound"
+251
View File
@@ -5491,3 +5491,254 @@ class TestBindingAndCompletion(_Base):
task_id=task.id,
current=self.admin,
)
def test_empty_baseline_stripped_bind_candidates_reconciles_to_role_ready(self):
"""历史无 baseline 且 bind_candidates 被裁剪的扫码任务,刷新/对账后应收敛为待确认。"""
task = self._allocated()
task.customer_role_name = "欧美真心"
account = self.session.get(Account, task.account_id)
account.game_name = "曲奇小诺゛"
account.role_bind_status = "bound"
qr_task = DouyuTask(
batch_id="stripped-pending-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
message="已识别角色: 欧美真心,待确认绑定",
platform_task_id=task.id,
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"baseline_role_name": "",
"baseline_is_bound_act": False,
"before_bind_info": {},
"expected_role_name": "欧美真心",
"expected_role_required": True,
"role_name": "欧美真心",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"url": "https://livelink.example/qr",
"bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "欧美真心",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
},
"bind_decision": {
"alias": "20260120QYOOB",
"role_name": "欧美真心",
"actionable_alias": True,
"confirmable": True,
"reason": "existing_actionable_pending",
},
"bind_candidates": [
{
"act_alias": "cjm",
"role_name": "欧美真心",
"is_bound_act": False,
},
{
"act_alias": "20260120QYOOB",
"role_name": "欧美真心",
"is_bound_act": False,
},
],
"bind_candidate_decisions": [
{
"alias": "20260120QYOOB",
"role_name": "欧美真心",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
"actionable_alias": True,
"confirmable": True,
"reason": "existing_actionable_pending",
}
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session)
self.session.commit()
detail = service.get_task_detail(self.session, task.id)
item = detail["task"]
assert reconciled >= 1
assert item["bindingStatus"] == "role_ready"
assert item["executionStatus"] == "role_ready"
assert item["bindTask"]["roleName"] == "欧美真心"
assert item["bindTask"]["bindReadyForConfirm"] is True
assert item["bindingEvidence"]["scannedRole"] == "欧美真心"
assert item["bindingEvidence"]["baselineRole"] == ""
assert item["bindingEvidence"]["confirmable"] is True
assert item["bindingEvidence"]["actionPending"]["needBindAct"] is True
assert item["bindingEvidence"]["actionPending"]["channel"] == "手Q / 苹果(iOS)"
def test_current_confirm_bind_with_mismatched_customer_role_is_rejected(self):
"""即使 bind_task_id 已指向 confirm_bind,确认出非客户目标角色也必须拒绝。"""
task = self._allocated()
task.customer_role_name = "客户指定角色"
confirm_task = DouyuTask(
batch_id="current-mismatched-confirm",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"role_name": "账号旧角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.flush()
task.bind_task_id = confirm_task.id
task.binding_status = "confirming"
task.execution_status = "binding_confirming"
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=confirm_task.id,
)
self.session.refresh(task)
rejection = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_sync_rejected")
.one()
)
assert synced >= 0
assert task.binding_status != "bound"
assert rejection.detail_json["reason"] == "target_mismatch"
def test_save_customer_profile_immediately_reconciles_existing_qr_candidates(self):
"""先出码扫码、后提交客户资料时,保存资料应立即把订单收敛到 role_ready。"""
task = self._allocated()
task.customer_role_name = ""
qr_task = DouyuTask(
batch_id="profile-late-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"expected_role_name": "",
"expected_role_required": True,
"role_name": "后补角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"url": "https://livelink.example/qr",
"bind_candidates": [
{
"act_alias": "20260120QYOOB",
"role_name": "后补角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
}
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
out = service.save_customer_profile(
self.session,
task_id=task.id,
customer_role_name="后补角色",
platform="qq",
system="ios",
home_images=[{"url": "https://img.example/1.png"}],
)
self.session.refresh(task)
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert out["bindingStatus"] == "role_ready"
assert out["roleName"] == "后补角色"
assert out["bindReadyForConfirm"] is True
def test_unlinked_workbench_qr_with_wrong_role_is_not_attached(self):
"""工作台无归属扫码任务若角色与客户目标不一致,绝不能挂到订单上。"""
task = self._allocated()
task.customer_role_name = "客户目标角色"
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
workbench_qr = DouyuTask(
batch_id="workbench-wrong-role",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"role_name": "工作台别的号角色",
"area_name": "微信",
"plat_name": "安卓(android)",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"bind_candidates": [
{
"act_alias": "20260120QYOOB",
"role_name": "工作台别的号角色",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
}
],
},
created_by=self.admin_id,
)
self.session.add(workbench_qr)
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session)
self.session.refresh(task)
assert reconciled == 0
assert task.binding_status == "qr_pending"
assert task.bind_task_id is None
+82 -5
View File
@@ -673,6 +673,87 @@ def resolve_binding_candidates(
}
def hydrate_bind_candidates_from_result(
result: dict[str, Any] | None,
) -> list[dict[str, Any]]:
"""补全历史结果 ``bind_candidates`` 中缺失的状态标记和区服字段。"""
if not isinstance(result, dict):
return []
raw_candidates = [
dict(item)
for item in (result.get("bind_candidates") or [])
if isinstance(item, dict)
]
if not raw_candidates:
return []
decisions_by_alias: dict[str, dict[str, Any]] = {}
for decision in result.get("bind_candidate_decisions") or []:
if not isinstance(decision, dict):
continue
alias = str(decision.get("alias") or decision.get("act_alias") or "").strip()
if alias and alias not in decisions_by_alias:
decisions_by_alias[alias] = decision
bind_info = result.get("bind_info")
bind_info_dict = bind_info if isinstance(bind_info, dict) else {}
bind_info_alias = str(
bind_info_dict.get("act_alias") or result.get("act_alias") or ""
).strip()
hydrated: list[dict[str, Any]] = []
for candidate in raw_candidates:
alias = str(candidate.get("act_alias") or candidate.get("alias") or "").strip()
role_name = str(candidate.get("role_name") or "").strip()
decision = decisions_by_alias.get(alias)
if decision is not None and (
not role_name
or not str(decision.get("role_name") or "").strip()
or str(decision.get("role_name") or "").strip().casefold()
== role_name.casefold()
):
for key in (
"is_bound_act",
"is_bound_role",
"need_bind_act",
"need_bind_role",
"actionable_alias",
"confirmable",
"reason",
):
if key not in candidate and key in decision:
candidate[key] = decision[key]
if (
bind_info_dict
and alias
and alias == bind_info_alias
and (
not role_name
or not str(bind_info_dict.get("role_name") or "").strip()
or str(bind_info_dict.get("role_name") or "").strip().casefold()
== role_name.casefold()
)
):
snap = binding_snapshot(bind_info_dict)
for key in ("area_name", "plat_name", "partition_name"):
if not candidate.get(key) and snap.get(key):
candidate[key] = snap[key]
for key in (
"is_bound_act",
"is_bound_role",
"need_bind_act",
"need_bind_role",
"is_bound_account",
):
if key not in candidate and key in snap:
candidate[key] = snap[key]
hydrated.append(candidate)
return hydrated
def pending_binding_role_from_result(result: dict[str, Any] | None) -> str:
"""从执行器结果中提取“本次扫码产生的待确认角色”。
@@ -702,11 +783,7 @@ def pending_binding_role_from_result(result: dict[str, Any] | None) -> str:
require_expected_role = bool(result.get("expected_role_required"))
if require_expected_role and not expected_role_name:
return ""
raw_candidates = [
dict(item)
for item in (result.get("bind_candidates") or [])
if isinstance(item, dict)
]
raw_candidates = hydrate_bind_candidates_from_result(result)
if raw_candidates:
resolution = resolve_binding_candidates(
raw_candidates,
+25
View File
@@ -19,6 +19,7 @@ from ..models import Account, DouyuTask
from .account_binding import (
binding_channel,
get_bind_status,
hydrate_bind_candidates_from_result,
pending_binding_role_from_result,
)
@@ -97,6 +98,30 @@ def resolve_douyu_binding(
pending_area = str(result.get("area_name") or "").strip() if pending_role else ""
pending_plat = str(result.get("plat_name") or "").strip() if pending_role else ""
if pending_role and (not pending_area or not pending_plat):
action_aliases = {
str(value or "").strip()
for value in (result.get("action_act_aliases") or [])
if str(value or "").strip()
}
matching_candidates = [
item
for item in hydrate_bind_candidates_from_result(result)
if str(item.get("role_name") or "").strip().casefold()
== pending_role.casefold()
and (item.get("area_name") or item.get("plat_name"))
]
matching_candidates.sort(
key=lambda item: (
0
if str(item.get("act_alias") or item.get("alias") or "").strip()
in action_aliases
else 1
)
)
if matching_candidates:
pending_area = pending_area or str(matching_candidates[0].get("area_name") or "").strip()
pending_plat = pending_plat or str(matching_candidates[0].get("plat_name") or "").strip()
pending_channel = binding_channel(
{
"area_name": pending_area,
+97 -25
View File
@@ -324,6 +324,39 @@ class BindMixin:
def _bind_snapshot(self, bind_info: dict | None) -> dict:
return binding_snapshot(bind_info)
def _serialize_bind_candidates(
self, candidates: list[dict[str, Any]]
) -> list[dict[str, Any]]:
"""序列化各通道候选快照,保留待确认判定所需的核心布尔标记和区服。"""
serialized: list[dict[str, Any]] = []
for item in candidates:
snapshot = self._bind_snapshot(item)
serialized.append(
{
"act_alias": item.get("act_alias") or item.get("alias") or "",
"role_name": str(
snapshot.get("role_name") or item.get("role_name") or ""
),
"area_name": str(
snapshot.get("area_name") or item.get("area_name") or ""
),
"plat_name": str(
snapshot.get("plat_name") or item.get("plat_name") or ""
),
"partition_name": str(
snapshot.get("partition_name") or item.get("partition_name") or ""
),
"is_bound_act": bool(
snapshot.get("is_bound_act", self._is_bound_act(item))
),
"is_bound_role": bool(snapshot.get("is_bound_role")),
"need_bind_act": bool(snapshot.get("need_bind_act")),
"need_bind_role": bool(snapshot.get("need_bind_role")),
"is_bound_account": bool(snapshot.get("is_bound_account")),
}
)
return serialized
def _format_bind_summary(
self, bind_info: dict | None, *, pending: bool | None = None
) -> str:
@@ -884,14 +917,7 @@ class BindMixin:
"bind_polling": False,
"poll_count": poll_count,
"bind_summary": summary,
"bind_candidates": [
{
"act_alias": item.get("act_alias"),
"role_name": item.get("role_name"),
"is_bound_act": self._is_bound_act(item),
}
for item in candidates
],
"bind_candidates": self._serialize_bind_candidates(candidates),
}
)
role_name = snapshot["role_name"]
@@ -935,6 +961,7 @@ class BindMixin:
"bind_polling": True,
"poll_count": poll_count,
"bind_summary": summary,
"bind_candidates": self._serialize_bind_candidates(candidates),
}
)
self._update_task_progress(
@@ -1056,6 +1083,7 @@ class BindMixin:
"bind_polling": False,
"bind_ready_for_confirm": False,
"bind_phase": "role_timeout",
"action_act_aliases": self._action_act_aliases(config),
}
)
task.last_run_at = now
@@ -1288,6 +1316,7 @@ class BindMixin:
"bind_polling": False,
"poll_count": poll_number,
"bind_summary": summary,
"bind_candidates": self._serialize_bind_candidates(candidates),
"action_act_aliases": action_aliases,
"bind_decision": selected_decision,
"bind_candidate_decisions": candidate_decisions,
@@ -1320,14 +1349,7 @@ class BindMixin:
"pending_role_name": snapshot["role_name"],
"poll_count": poll_number,
"bind_summary": summary,
"bind_candidates": [
{
"act_alias": item.get("act_alias"),
"role_name": item.get("role_name"),
"is_bound_act": self._is_bound_act(item),
}
for item in candidates
],
"bind_candidates": self._serialize_bind_candidates(candidates),
"action_act_aliases": action_aliases,
"bind_decision": selected_decision,
"bind_candidate_decisions": candidate_decisions,
@@ -1369,6 +1391,7 @@ class BindMixin:
"bind_polling": True,
"poll_count": poll_number,
"bind_summary": summary,
"bind_candidates": self._serialize_bind_candidates(candidates),
"action_act_aliases": action_aliases,
"bind_decision": selected_decision,
"bind_candidate_decisions": candidate_decisions,
@@ -1510,8 +1533,10 @@ class BindMixin:
or before.get("act_alias"),
"query_act_alias": cooldown.get("act_alias") or before.get("act_alias"),
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"before_bind_info": before,
"cooldown_bind_info": cooldown_info,
"bind_candidates": self._serialize_bind_candidates(before_candidates),
**cooldown_snapshot,
"current_role_name": role_label
if role_label != "当前角色"
@@ -1592,6 +1617,7 @@ class BindMixin:
"expected_role_name": expected_role_name,
"expected_role_required": require_expected_role,
"action_act_aliases": action_aliases,
"bind_candidates": self._serialize_bind_candidates(before_candidates),
"bind_decision": pending_decision,
"bind_candidate_decisions": candidate_decisions,
"poll_count": 0,
@@ -1722,7 +1748,9 @@ class BindMixin:
{
"act_alias": confirm_alias,
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"expected_role_required": True,
"bind_candidates": self._serialize_bind_candidates(before_candidates),
"bind_ready_for_confirm": False,
"bind_confirmed": False,
"bind_phase": "waiting_customer_role",
@@ -1772,18 +1800,12 @@ class BindMixin:
{
"act_alias": confirm_alias,
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"expected_role_name": expected_role_name,
"bind_ready_for_confirm": False,
"bind_confirmed": False,
"bind_phase": "confirm_failed",
"bind_candidates": [
{
"act_alias": item.get("act_alias"),
"role_name": item.get("role_name"),
"is_bound_act": self._is_bound_act(item),
}
for item in before_candidates
],
"bind_candidates": self._serialize_bind_candidates(before_candidates),
},
)
return
@@ -1803,7 +1825,9 @@ class BindMixin:
"act_alias": confirm_alias or query_alias,
"query_act_alias": query_alias,
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"before_bind_info": before,
"bind_candidates": self._serialize_bind_candidates(before_candidates),
**before_snapshot,
"bind_ready_for_confirm": False,
"bind_confirmed": False,
@@ -1833,7 +1857,9 @@ class BindMixin:
"act_alias": confirm_alias or query_alias,
"query_act_alias": query_alias,
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"before_bind_info": before_bound,
"bind_candidates": self._serialize_bind_candidates(before_candidates),
**self._bind_snapshot(before_bound),
"bind_ready_for_confirm": True,
"bind_confirmed": True,
@@ -1905,11 +1931,13 @@ class BindMixin:
"act_alias": use_confirm_alias,
"query_act_alias": query_alias,
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"before_bind_info": before,
"before_bound_bind_info": before_bound,
"before_bound_snapshot": (
before_bound_snapshot if before_bound is not None else None
),
"bind_candidates": self._serialize_bind_candidates(before_candidates),
**before_snapshot,
"confirm_error": confirm_msg,
"confirm_error_code": confirm_code,
@@ -1988,9 +2016,13 @@ class BindMixin:
"act_alias": use_confirm_alias,
"query_act_alias": query_alias,
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"before_bind_info": before,
"confirm": confirm_result,
"after_bind_info": None,
"bind_candidates": self._serialize_bind_candidates(
after_candidates or before_candidates
),
**before_snapshot,
"bind_ready_for_confirm": True,
"bind_confirmed": False,
@@ -2033,8 +2065,10 @@ class BindMixin:
"act_alias": use_confirm_alias,
"query_act_alias": query_alias,
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"before_bind_info": before,
"confirm": confirm_result,
"bind_candidates": self._serialize_bind_candidates(before_candidates),
**before_snapshot,
"bind_ready_for_confirm": True,
"bind_confirmed": True,
@@ -2046,6 +2080,40 @@ class BindMixin:
after_snapshot = self._bind_snapshot(after)
final_role_name = after_snapshot["role_name"] or role_name
if (
expected_role_name
and final_role_name.casefold() != expected_role_name.casefold()
):
if before_bound is not None:
self._apply_bind_info_to_account(account, before_bound, BIND_BOUND)
else:
account.updated_at = datetime.now(UTC)
self._mark_task(
db,
task,
"failed",
f"确认后已生效角色({final_role_name})与目标角色({expected_role_name})不一致,请重新扫码绑定",
{
"act_alias": use_confirm_alias,
"query_act_alias": after.get("act_alias") or query_alias,
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"expected_role_name": expected_role_name,
"before_bind_info": before,
"before_bound_bind_info": before_bound,
"confirm": confirm_result,
"after_bind_info": after,
"bind_candidates": self._serialize_bind_candidates(
after_candidates or before_candidates
),
**after_snapshot,
"issue_code": "role_changed",
"bind_ready_for_confirm": False,
"bind_confirmed": False,
"bind_phase": "confirm_failed",
},
)
return
self._apply_bind_info_to_account(account, after, BIND_BOUND)
# 强事实:确认接口成功 + 回查命中已生效绑定。
# ⚠️ 上面还有一条 success 是「检测到账号**本来就已经绑定**」(什么都没做),
@@ -2069,9 +2137,13 @@ class BindMixin:
"act_alias": use_confirm_alias,
"query_act_alias": after.get("act_alias") or query_alias,
"query_act_aliases": query_aliases,
"action_act_aliases": action_aliases,
"before_bind_info": before,
"confirm": confirm_result,
"after_bind_info": after,
"bind_candidates": self._serialize_bind_candidates(
after_candidates or before_candidates
),
**after_snapshot,
"bind_ready_for_confirm": True,
"bind_confirmed": True,
@@ -2248,7 +2320,7 @@ class BindMixin:
state,
BIND_BOUND
if is_bound
else ("esports_bind_ready" if role_name else "game_not_bound"),
else (BIND_PENDING if role_name else BIND_UNBOUND),
)
result = {
**state,
@@ -280,6 +280,43 @@ def _owned_binding_tasks(
)
def sync_customer_role_to_bind_task(
db: Session,
task: PlatformFulfillmentTask,
) -> bool:
"""把客户最新提交的目标角色安全写入当前绑定任务并立即重算订单状态。"""
customer_role = str(task.customer_role_name or "").strip()
if not task.bind_task_id or not customer_role:
return False
bind_task = (
db.query(DouyuTask)
.filter(DouyuTask.id == int(task.bind_task_id))
.with_for_update()
.first()
)
if bind_task is None or bind_task.task_type not in {
"get_bind_qr",
"confirm_bind",
}:
return False
result = dict(bind_task.result or {})
result["expected_role_name"] = customer_role
result["expected_role_required"] = True
bind_task.result = result
if (
not _frozen(task)
and task.binding_status in ACTIVE_BINDING_STATUSES
and bind_task.status == "success"
):
return _apply_binding_task(
db,
task,
bind_task,
owned=bind_task.platform_task_id is not None,
)
return False
def _order_target_role(
db: Session,
task: PlatformFulfillmentTask,
@@ -1014,10 +1051,14 @@ def _apply_binding_task(
task,
before_task_id=int(source.id) if source.task_type == "confirm_bind" else None,
)
customer_role = str(task.customer_role_name or "").strip()
expected_role = target_role or customer_role
if is_current:
# 订单自己的当前任务(订单创建的或兼容路径挂上的)回查到 bindAct=1。
# 查询类任务不会走到这里:resolve_fulfillment_binding 会把观测降级。
accepted = source.task_type in BINDING_EVIDENCE_TASK_TYPES
accepted = source.task_type in BINDING_EVIDENCE_TASK_TYPES and (
not expected_role or role_names_match(confirmed_role, expected_role)
)
elif not owned:
accepted = False
elif phase == "confirming":
@@ -1026,13 +1067,13 @@ def _apply_binding_task(
elif source.task_type == "confirm_bind":
accepted = (
phase in CONFIRMABLE_BINDING_STATUSES
and bool(target_role)
and role_names_match(confirmed_role, target_role)
and bool(expected_role)
and role_names_match(confirmed_role, expected_role)
)
else:
# 订单自己的绑码任务直接被官网确认:有目标时必须一致,无目标视为全新绑定。
accepted = phase in ACTIVE_BINDING_STATUSES and (
not target_role or role_names_match(confirmed_role, target_role)
not expected_role or role_names_match(confirmed_role, expected_role)
)
if not accepted:
_record_binding_rejection(
@@ -1041,11 +1082,11 @@ def _apply_binding_task(
source,
reason=(
"target_mismatch"
if target_role and not role_names_match(confirmed_role, target_role)
if expected_role and not role_names_match(confirmed_role, expected_role)
else "untrusted_confirmation"
),
confirmed_role=confirmed_role,
target_role=target_role,
target_role=expected_role,
)
return False
task.bind_task_id = int(source.id)
@@ -1504,6 +1545,9 @@ def _attach_pending_binding_task(
)
):
return False
customer_role = str(task.customer_role_name or "").strip()
if customer_role and not role_names_match(binding.pending_role_name, customer_role):
return False
current_id = int(task.bind_task_id or 0)
if int(bind_task.id) == current_id:
return False
@@ -1738,7 +1782,9 @@ def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[st
):
db.commit()
return get_task_detail(db, task.id)
expected_role_name = str(current_bind_result.get("role_name") or "").strip()
expected_role_name = str(
task.customer_role_name or target_role_name or current_bind_result.get("role_name") or ""
).strip()
baseline_role_name = str(current_bind_result.get("current_role_name") or "").strip()
batch_id = f"pfconfirm-{task.id}-{uuid.uuid4().hex[:8]}"
confirm_task = DouyuTask(
@@ -20,7 +20,10 @@ from typing import Any
from sqlalchemy.orm import Session
from ...models import Account, DouyuTask, PlatformFulfillmentTask
from ..account_binding import pending_binding_role_from_result
from ..account_binding import (
hydrate_bind_candidates_from_result,
pending_binding_role_from_result,
)
from .role_lock import AccountLock, RoleLock, find_account_lock, find_role_lock
@@ -133,26 +136,39 @@ def build_binding_evidence(
]
candidates = [
_candidate(raw)
for raw in (result.get("bind_candidates") or [])
if isinstance(raw, dict)
for raw in hydrate_bind_candidates_from_result(result)
]
candidates = [item for item in candidates if item["alias"]]
decision = result.get("bind_decision")
decision = decision if isinstance(decision, dict) else {}
if not action_aliases:
action_aliases = [
item["alias"] for item in candidates if item["actionableAlias"]
]
selected_info = result.get("bind_info") or result.get("before_bind_info")
selected_info_candidate = _candidate_from_info(selected_info, action_aliases)
if not candidates and selected_info_candidate is not None:
candidates = [selected_info_candidate]
selected_alias = _text(
result.get("act_alias")
or (selected_info or {}).get("act_alias")
or (candidates[0]["alias"] if candidates else "")
)
decision = result.get("bind_decision")
decision = decision if isinstance(decision, dict) else {}
if (
not action_aliases
and selected_alias
and bool(decision.get("actionable_alias"))
):
action_aliases = [selected_alias]
selected_info_candidate = _candidate_from_info(selected_info, action_aliases)
if not candidates and selected_info_candidate is not None:
candidates = [selected_info_candidate]
if action_aliases:
for item in candidates:
if item["alias"] in action_aliases:
item["actionableAlias"] = True
if (
selected_info_candidate is not None
and selected_info_candidate["alias"] in action_aliases
):
selected_info_candidate["actionableAlias"] = True
selected_actionable = bool(
decision.get("actionable_alias")
or (selected_alias and selected_alias in action_aliases)
@@ -173,6 +189,7 @@ def build_binding_evidence(
account,
action_aliases[0] if action_aliases else "",
)
pending_role = pending_binding_role_from_result(result)
action_pending = next(
(
item
@@ -180,6 +197,14 @@ def build_binding_evidence(
if item["alias"] in action_aliases
and item["roleName"]
and not item["bindAct"]
and (
item["needBindAct"]
or item["confirmable"]
or (
pending_role
and item["roleName"].casefold() == pending_role.casefold()
)
)
),
None,
)
@@ -189,6 +214,15 @@ def build_binding_evidence(
and selected_info_candidate["alias"] in action_aliases
and selected_info_candidate["roleName"]
and not selected_info_candidate["bindAct"]
and (
selected_info_candidate["needBindAct"]
or selected_info_candidate["confirmable"]
or (
pending_role
and selected_info_candidate["roleName"].casefold()
== pending_role.casefold()
)
)
):
action_pending = selected_info_candidate
legacy_latest = next(
@@ -207,7 +241,6 @@ def build_binding_evidence(
):
legacy_latest = selected_info_candidate
pending_role = pending_binding_role_from_result(result)
legacy_role = _text((legacy_latest or {}).get("roleName"))
account_current_role = _text(account.game_name) if account is not None else ""
# scannedRole 只认“本次新扫码”:
@@ -231,10 +264,10 @@ def build_binding_evidence(
# 取消 QYOOB-only 门禁后,cjm 的新角色同样可以成为客户确认目标;
# 这里展示真实本次扫码角色,避免详情说“不可确认”但客户页可以确认。
target_role = scanned_role
before_info = result.get("before_bind_info")
baseline_role = _text(
result.get("baseline_role_name")
or (selected_info or {}).get("role_name")
or (result.get("before_bind_info") or {}).get("role_name")
or (before_info if isinstance(before_info, dict) else {}).get("role_name")
)
same_pair = bool(
scanned_role
@@ -10,13 +10,13 @@ from sqlalchemy.orm import Session
from ...models import (
AccountLease,
DouyuTask,
PlatformFulfillmentTask,
)
from .binding import (
confirm_binding,
refresh_binding,
start_binding,
sync_customer_role_to_bind_task,
)
from .common import FLOW_VERSION_CLEAN, _has_game_home_profile
from .order_sync import sync_order_item_ids
@@ -100,16 +100,7 @@ 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
result["expected_role_required"] = True
bind_task.result = result
sync_customer_role_to_bind_task(db, task)
_append_event(
db,
task.id,
@@ -11,7 +11,6 @@ from fastapi import HTTPException
from sqlalchemy.orm import Session
from ...models import (
DouyuTask,
PlatformCommodityMapping,
PlatformFulfillmentTask,
)
@@ -112,15 +111,9 @@ def _apply_customer_profile(
)
)
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
result["expected_role_required"] = True
bind_task.result = result
from .binding import sync_customer_role_to_bind_task
sync_customer_role_to_bind_task(db, task)
def _upsert_order_snapshot(