From 204cbd5d82761e7f5348a4e48f1df91ddde911d9 Mon Sep 17 00:00:00 2001 From: yml Date: Thu, 26 Nov 2026 01:03:22 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D(=E5=B1=A5=E7=BA=A6=E7=BB=91?= =?UTF-8?q?=E5=AE=9A):=20=E6=94=B6=E6=95=9B=E6=B4=BB=E5=8A=A8=E5=88=AB?= =?UTF-8?q?=E5=90=8D=E4=B8=AD=E7=9A=84=E7=9E=AC=E6=97=B6=E5=8E=86=E5=8F=B2?= =?UTF-8?q?=E8=A7=92=E8=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_douyu_account_probe.py | 7 +- tests/test_douyu_binding_state.py | 64 +++++- tests/test_platform_fulfillment.py | 153 ++++++++++--- web/backend/services/account_binding.py | 32 +++ web/backend/services/douyu_account_probe.py | 9 + web/backend/services/douyu_runner_bind.py | 91 +++++++- .../services/platform_fulfillment/binding.py | 209 +++++++++++++++++- .../platform_fulfillment/binding_evidence.py | 30 ++- .../services/platform_fulfillment/customer.py | 10 + .../platform_fulfillment/order_sync.py | 16 +- 10 files changed, 574 insertions(+), 47 deletions(-) diff --git a/tests/test_douyu_account_probe.py b/tests/test_douyu_account_probe.py index 8a0f7ba..dd8d3ff 100644 --- a/tests/test_douyu_account_probe.py +++ b/tests/test_douyu_account_probe.py @@ -57,11 +57,12 @@ def _bind( } -def test_role_resolver_prefers_current_bound_and_reports_pending_legacy(): +def test_role_resolver_does_not_report_legacy_history_as_pending(): + """cjm 可能返回同斗鱼账号历史绑过的另一个游戏角色,不能盖过当前活动角色。""" client = RoleClient( { "current-alias": _bind("当前角色", bound_act=True, bound_role=True), - "cjm": _bind("新角色", bound_role=True), + "cjm": _bind("历史其他账号角色", bound_role=True), } ) @@ -70,7 +71,7 @@ def test_role_resolver_prefers_current_bound_and_reports_pending_legacy(): assert result["status"] == ROLE_BOUND assert result["role_name"] == "当前角色" assert result["source_alias"] == "current-alias" - assert result["pending_role_name"] == "新角色" + assert result["pending_role_name"] == "" assert client.calls == ["current-alias", "cjm"] diff --git a/tests/test_douyu_binding_state.py b/tests/test_douyu_binding_state.py index 863909c..e700cf0 100644 --- a/tests/test_douyu_binding_state.py +++ b/tests/test_douyu_binding_state.py @@ -660,20 +660,74 @@ def test_new_role_wins_when_cjm_and_activity_snapshots_differ(): assert target["role_name"] == new_role -def test_changed_cjm_role_wins_over_old_bound_activity_role(): +def test_legacy_cjm_change_waits_for_activity_alias_transition(): + """latest HAR 中 cjm 会返回同斗鱼号历史绑过的另一 QQ 角色,不能直接当 pending。""" old_role = "狗鼻子弗尼亚bd" - new_role = "我是火星人2222" + transient_role = "我是火星人2222" candidates = [ - _role_candidate(LEGACY_ALIAS, new_role), + _role_candidate(LEGACY_ALIAS, transient_role), _role_candidate(ACT_ALIAS, old_role, bound_act=True), ] picker = _RolePicker() target = picker._pick_target_role_info(candidates, ROLE_CONFIG) + decisions = picker._binding_candidate_decisions( + candidates, + baseline_role_name=old_role, + baseline_is_bound_act=True, + actionable_aliases=[ACT_ALIAS], + ) assert target is not None - assert target["act_alias"] == LEGACY_ALIAS - assert target["role_name"] == new_role + assert target["act_alias"] == ACT_ALIAS + assert target["role_name"] == old_role + legacy_decision = next( + item for item in decisions if item["alias"] == LEGACY_ALIAS + ) + assert legacy_decision["confirmable"] is False + assert legacy_decision["reason"] == "legacy_superseded_by_action_alias" + + +def test_expected_customer_role_rejects_transient_pending_candidate(): + old_role = "真心似有若无" + transient_role = "TuT小玉" + expected_role = "丛未停息的雨" + candidate = _role_candidate(LEGACY_ALIAS, transient_role) + + decision = binding_pending_decision( + candidate, + baseline_role_name=old_role, + baseline_is_bound_act=True, + actionable_aliases=[ACT_ALIAS], + expected_role_name=expected_role, + ) + + assert decision["confirmable"] is False + assert decision["reason"] == "expected_role_mismatch" + + +def test_result_rejects_legacy_role_when_action_alias_still_has_role(): + result = { + "role_name": "TuT小玉", + "act_alias": LEGACY_ALIAS, + "action_act_aliases": [ACT_ALIAS], + "bind_ready_for_confirm": True, + "bind_confirmed": False, + "bind_candidates": [ + { + "act_alias": LEGACY_ALIAS, + "role_name": "TuT小玉", + "is_bound_act": False, + }, + { + "act_alias": ACT_ALIAS, + "role_name": "真心似有若无", + "is_bound_act": True, + }, + ], + } + + assert pending_binding_role_from_result(result) == "" def test_expected_role_never_falls_back_to_old_activity_role(): diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index b477614..993438b 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -1969,6 +1969,38 @@ class TestBindingAndCompletion(_Base): assert task.issue_code == "" assert task.last_error == "" + def test_customer_profile_updates_active_bind_expected_role(self): + task = self._allocated() + bind_task = DouyuTask( + batch_id="late-customer-profile", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="running", + platform_task_id=task.id, + result={"expected_role_name": "", "bind_polling": True}, + created_by=self.admin_id, + ) + self.session.add(bind_task) + self.session.flush() + task.bind_task_id = bind_task.id + task.binding_status = "waiting_bind" + task.execution_status = "waiting_bind" + self.session.commit() + + service.save_customer_profile( + self.session, + task_id=task.id, + customer_role_name="丛未停息的雨", + platform="qq", + system="ios", + home_images=[{"url": "https://example.com/home.png"}], + ) + + self.session.refresh(bind_task) + assert bind_task.result["expected_role_name"] == "丛未停息的雨" + def test_standalone_account_confirmation_syncs_active_fulfillment_task(self): task = self._allocated() old_bind_task = DouyuTask( @@ -2323,6 +2355,83 @@ class TestBindingAndCompletion(_Base): == 0 ) + def test_target_matching_observation_repairs_stale_pending_role(self): + """租期内后续查询已绑定客户目标时,必须收敛旧的瞬时 cjm 角色。""" + task = self._allocated() + task.customer_role_name = "丛未停息的雨" + account = self.session.get(Account, task.account_id) + account.game_name = "丛未停息的雨" + account.game_channel = "手Q · 苹果(iOS)" + account.role_bind_status = "bound" + pending_task = DouyuTask( + batch_id="stale-transient-pending", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="success", + result={ + "role_name": "TuT小玉", + "baseline_role_name": "真心似有若无", + "before_bind_info": { + "act_alias": "20260120QYOOB", + "role_name": "真心似有若无", + "is_bound_act": True, + "need_bind_act": True, + }, + "bind_ready_for_confirm": True, + "bind_confirmed": False, + "bind_phase": "role_ready", + }, + created_by=self.admin_id, + ) + self.session.add(pending_task) + self.session.flush() + task.bind_task_id = pending_task.id + task.binding_status = "role_ready" + task.execution_status = "role_ready" + observation = DouyuTask( + batch_id="confirmed-target-observation", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="query_game_name", + handbook_scope="elite", + status="success", + platform_task_id=None, + result={ + "act_alias": "20260120QYOOB", + "action_act_aliases": ["20260120QYOOB"], + "role_name": "丛未停息的雨", + "area_name": "手Q", + "plat_name": "苹果(iOS)", + "is_bound_act": True, + "bind_confirmed": True, + "bind_phase": "confirmed", + }, + created_by=self.admin_id, + ) + self.session.add(observation) + self.session.commit() + + detail = service.refresh_binding(self.session, task_id=task.id) + + self.session.refresh(task) + event = ( + self.session.query(PlatformFulfillmentEvent) + .filter_by( + task_id=task.id, + event_type="binding_confirmed_from_observation", + ) + .one() + ) + assert task.binding_status == "bound" + assert task.execution_status == "bound" + assert task.bind_task_id == observation.id + assert detail["task"]["bindTask"]["roleName"] == "丛未停息的雨" + assert detail["task"]["bindTask"]["bindConfirmed"] is True + assert event.detail_json["previousBindTaskId"] == pending_task.id + assert event.detail_json["targetRoleName"] == "丛未停息的雨" + def test_startup_recovers_lost_confirm_callback(self): """确认任务已成功落库但回调丢失时,启动对账能收敛为 bound。""" task = self._allocated() @@ -3003,12 +3112,12 @@ class TestBindingAndCompletion(_Base): assert evidence["legacyLatest"]["roleName"] == "新扫角色" assert evidence["selectedAlias"] == "cjm" assert evidence["selectedActionable"] is False - assert evidence["targetRole"] == "新扫角色" - assert evidence["scannedRole"] == "新扫角色" + assert evidence["targetRole"] == "" + assert evidence["scannedRole"] == "" assert evidence["confirmable"] is False assert evidence["samePair"] is False - assert evidence["roleLock"]["accountId"] == lock_account.id - assert evidence["accountLock"]["roleName"] == "旧账号角色" + assert evidence["roleLock"] is None + assert evidence["accountLock"] is None def test_binding_evidence_marks_same_account_same_role(self): task = self._allocated() @@ -3226,10 +3335,14 @@ class TestBindingAndCompletion(_Base): assert detail["task"]["executionStatus"] == "bound" assert task.binding_status == "bound" assert task.execution_status == "bound" - assert qr_task.status == "stopped" + assert qr_task.status == "success" assert "人工确认绑定" in qr_task.message + assert detail["task"]["bindTask"]["roleName"] == "兔稚儿" + assert detail["task"]["bindTask"]["bindConfirmed"] is True assert qr_task.result["manual_confirmed"] is True assert qr_task.result["manual_confirmed_role"] == "兔稚儿" + assert qr_task.result["role_name"] == "兔稚儿" + assert qr_task.result["bind_ready_for_confirm"] is False event = ( self.session.query(PlatformFulfillmentEvent) .filter_by(task_id=task.id, event_type="binding_manually_confirmed") @@ -3468,7 +3581,7 @@ class TestBindingAndCompletion(_Base): == 0 ) - def test_cjm_only_new_role_enters_role_ready_for_customer_confirm(self): + def test_cjm_only_transient_role_waits_for_action_alias_sync(self): task = self._allocated() qr_task = DouyuTask( batch_id="cjm-only-pending", @@ -3533,30 +3646,20 @@ class TestBindingAndCompletion(_Base): self.session.refresh(task) detail = service.get_task_detail(self.session, task.id) evidence = detail["task"]["bindingEvidence"] - assert task.binding_status == "role_ready" - assert task.execution_status == "role_ready" - assert evidence["targetRole"] == "cjm新角色" - assert evidence["confirmable"] is True - assert views.customer_binding_out(self.session, task.id)["bindReadyForConfirm"] is True + assert task.binding_status == "qr_pending" + assert task.execution_status == "waiting_bind" + assert evidence["targetRole"] == "" + assert evidence["confirmable"] is False + assert evidence["scannedRole"] == "" + assert views.customer_binding_out(self.session, task.id)["bindReadyForConfirm"] is False assert evidence["legacyLatest"]["roleName"] == "cjm新角色" assert evidence["actionCurrent"]["roleName"] == "旧角色" - - # cjm-only 的新角色也必须能进入客户确认:确认执行器会在 actBind 前 - # 重新查询 QYOOB,动作通道未同步时返回可重试失败,而不是把客户卡死。 - task.binding_status = "role_ready" - task.execution_status = "role_ready" - self.session.commit() - service.confirm_binding_sync( - self.session, - task_id=task.id, - current=self.admin, - ) - confirm_task = ( + assert ( self.session.query(DouyuTask) .filter_by(task_type="confirm_bind") - .one() + .count() + == 0 ) - assert confirm_task.result["expected_role_name"] == "cjm新角色" def _same_pair_qr_task(self, task, include_legacy: bool = True): candidates = [ diff --git a/web/backend/services/account_binding.py b/web/backend/services/account_binding.py index 55d676c..d7ad727 100644 --- a/web/backend/services/account_binding.py +++ b/web/backend/services/account_binding.py @@ -370,6 +370,7 @@ def binding_pending_decision( baseline_is_bound_act: bool = False, baseline_info: dict | None = None, actionable_aliases: Sequence[str] = (), + expected_role_name: str = "", ) -> dict[str, Any]: """解释一个绑定候选是否可进入确认阶段。 @@ -398,6 +399,7 @@ def binding_pending_decision( "same_alias": False, "role_changed": False, "actionable_alias": False, + "expected_role_name": str(expected_role_name or "").strip(), "confirmable": False, "reason": "no_candidate", } @@ -423,6 +425,10 @@ def binding_pending_decision( if not role_name: result["reason"] = "no_role" return result + expected = str(expected_role_name or "").strip() + if expected and role_name.casefold() != expected.casefold(): + result["reason"] = "expected_role_mismatch" + return result if snapshot["is_bound_act"]: # 2026-11-22 换绑失败 HAR:历史角色会长期返回 bindAct=1 + needBindAct=1。 # 这表示当前绑定仍生效,不是待确认;若官方在扫码后直接完成绑定,轮询层 @@ -500,6 +506,7 @@ def is_pending_binding_role( baseline_is_bound_act: bool = False, baseline_info: dict | None = None, actionable_aliases: Sequence[str] = (), + expected_role_name: str = "", ) -> bool: """兼容布尔调用;详细原因统一由 :func:`binding_pending_decision` 给出。""" return bool( @@ -509,6 +516,7 @@ def is_pending_binding_role( baseline_is_bound_act=baseline_is_bound_act, baseline_info=baseline_info, actionable_aliases=actionable_aliases, + expected_role_name=expected_role_name, )["confirmable"] ) @@ -538,12 +546,36 @@ def pending_binding_role_from_result(result: dict[str, Any] | None) -> str: ] if not action_aliases and result.get("act_alias"): action_aliases = [str(result["act_alias"])] + action_alias_set = set(action_aliases) + selected_alias = str(result.get("act_alias") or "").strip() + action_evidence = [ + item + for item in [ + *(result.get("bind_candidates") or []), + *(result.get("bind_candidate_decisions") or []), + ] + if isinstance(item, dict) + and str(item.get("act_alias") or item.get("alias") or "").strip() + in action_alias_set + and str(item.get("role_name") or "").strip() + ] + if ( + action_alias_set + and selected_alias + and selected_alias not in action_alias_set + and action_evidence + ): + # legacy(cjm) 可能返回同一斗鱼账号历史绑过的另一个游戏角色。 + # 动作 alias 仍有明确角色时,legacy 的 role_name 不能成为本单 pending。 + return "" + expected_role_name = str(result.get("expected_role_name") or "").strip() if is_pending_binding_role( result, baseline_role_name=baseline, baseline_is_bound_act=bool(result.get("baseline_is_bound_act")), baseline_info=baseline_info, actionable_aliases=action_aliases, + expected_role_name=expected_role_name, ): return role_name return "" diff --git a/web/backend/services/douyu_account_probe.py b/web/backend/services/douyu_account_probe.py index 8a80858..ce96cb7 100644 --- a/web/backend/services/douyu_account_probe.py +++ b/web/backend/services/douyu_account_probe.py @@ -303,9 +303,18 @@ def resolve_elite_role( pending_info = None pending_decision: dict[str, Any] | None = None baseline_role = str((bound_info or {}).get("role_name") or "").strip() + action_alias_has_role = any( + str(info.get("act_alias") or "") in action_aliases + and str(info.get("role_name") or "").strip() + for info in candidates_info + ) def find_pending(*, changed_role_only: bool) -> tuple[dict | None, dict | None]: for alias in ordered_aliases: + if action_alias_has_role and alias not in action_aliases: + # cjm 可能返回同斗鱼账号历史上另一个 QQ/WX 游戏角色,不能盖过 + # 当前动作 alias 已经存在的绑定角色。 + continue for info in candidates_info: if str(info.get("act_alias") or "") != alias: continue diff --git a/web/backend/services/douyu_runner_bind.py b/web/backend/services/douyu_runner_bind.py index 6ae82ae..403e5d7 100644 --- a/web/backend/services/douyu_runner_bind.py +++ b/web/backend/services/douyu_runner_bind.py @@ -174,6 +174,7 @@ class BindMixin: baseline_is_bound_act: bool = False, baseline_info: dict | None = None, actionable_aliases: tuple[str, ...] | list[str] = (), + expected_role_name: str = "", ) -> bool: """判断是否出现了可确认的扫码角色。 @@ -190,6 +191,7 @@ class BindMixin: baseline_is_bound_act=baseline_is_bound_act, baseline_info=baseline_info, actionable_aliases=actionable_aliases, + expected_role_name=expected_role_name, ) @classmethod @@ -216,9 +218,23 @@ class BindMixin: *, baseline_role_name: str, baseline_is_bound_act: bool, + expected_role_name: str = "", + actionable_aliases: tuple[str, ...] | list[str] = (), ) -> dict | None: """Find a scan result that the official API already confirmed.""" + expected = expected_role_name.strip().casefold() + aliases = { + str(value or "").strip() + for value in actionable_aliases + if str(value or "").strip() + } for candidate in candidates: + alias = str(candidate.get("act_alias") or "").strip() + if aliases and alias not in aliases: + continue + role_name = str(candidate.get("role_name") or "").strip() + if expected and role_name.casefold() != expected: + continue if cls._is_newly_confirmed_binding( binding_snapshot(candidate), baseline_role_name=baseline_role_name, @@ -332,18 +348,48 @@ class BindMixin: baseline_is_bound_act: bool = False, baseline_info: dict | None = None, actionable_aliases: list[str] | tuple[str, ...] = (), + expected_role_name: str = "", ) -> list[dict[str, Any]]: """按同一规则解释每个 actAlias 候选,供任务结果和日志复盘。""" - return [ + decisions = [ binding_pending_decision( info, baseline_role_name=baseline_role_name, baseline_is_bound_act=baseline_is_bound_act, baseline_info=baseline_info, actionable_aliases=actionable_aliases, + expected_role_name=expected_role_name, ) for info in candidates ] + alias_set = { + str(value or "").strip() + for value in actionable_aliases + if str(value or "").strip() + } + action_alias_has_role = any( + str(info.get("act_alias") or "").strip() in alias_set + and str(info.get("role_name") or "").strip() + for info in candidates + ) + action_roles = { + str(info.get("role_name") or "").strip() + for info in candidates + if str(info.get("act_alias") or "").strip() in alias_set + and str(info.get("role_name") or "").strip() + } + if action_alias_has_role: + for info, decision in zip(candidates, decisions, strict=True): + alias = str(info.get("act_alias") or "").strip() + role_name = str(info.get("role_name") or "").strip() + if alias not in alias_set and role_name not in action_roles: + decision.update( + { + "confirmable": False, + "reason": "legacy_superseded_by_action_alias", + } + ) + return decisions def _push_binding_decision_log( self, @@ -582,6 +628,7 @@ class BindMixin: prefer_pending: bool = True, prefer_aliases: list[str] | None = None, actionable_aliases: list[str] | tuple[str, ...] = (), + expected_role_name: str = "", ) -> dict | None: """从多个 alias 结果里挑最有用的绑定信息。 @@ -601,6 +648,7 @@ class BindMixin: baseline_is_bound_act=baseline_is_bound_act, baseline_info=baseline_info, actionable_aliases=actionable_aliases, + expected_role_name=expected_role_name, ) if pending is not None: return pending @@ -640,6 +688,7 @@ class BindMixin: baseline_is_bound_act: bool = False, baseline_info: dict | None = None, actionable_aliases: list[str] | tuple[str, ...] = (), + expected_role_name: str = "", ) -> dict | None: """唯一的新角色候选选择入口。 @@ -648,26 +697,50 @@ class BindMixin: """ ordered = self._ordered_bind_candidates(candidates, prefer_aliases) baseline = baseline_role_name.strip().casefold() + expected = expected_role_name.strip().casefold() + alias_set = { + str(value or "").strip() + for value in actionable_aliases + if str(value or "").strip() + } + action_alias_has_role = any( + str(info.get("act_alias") or "").strip() in alias_set + and str(info.get("role_name") or "").strip() + for info in candidates + ) if baseline: for info in ordered: role_name = str(info.get("role_name") or "").strip() if not role_name or role_name.casefold() == baseline: continue + alias = str(info.get("act_alias") or "").strip() + if action_alias_has_role and alias not in alias_set: + continue + if expected and role_name.casefold() != expected: + continue if self._is_pending_role( info, baseline_role_name=baseline_role_name, baseline_is_bound_act=baseline_is_bound_act, baseline_info=baseline_info, actionable_aliases=actionable_aliases, + expected_role_name=expected_role_name, ): return info for info in ordered: + role_name = str(info.get("role_name") or "").strip() + alias = str(info.get("act_alias") or "").strip() + if action_alias_has_role and alias not in alias_set: + continue + if expected and role_name.casefold() != expected: + continue if self._is_pending_role( info, baseline_role_name=baseline_role_name, baseline_is_bound_act=baseline_is_bound_act, baseline_info=baseline_info, actionable_aliases=actionable_aliases, + expected_role_name=expected_role_name, ): return info return None @@ -743,6 +816,7 @@ class BindMixin: result["baseline_role_name"] = baseline_role_name result["baseline_is_bound_act"] = baseline_is_bound_act result["query_act_aliases"] = query_aliases + expected_role_name = str(result.get("expected_role_name") or "").strip() action_aliases = [ str(value) for value in (result.get("action_act_aliases") or []) @@ -782,6 +856,7 @@ class BindMixin: prefer_pending=True, prefer_aliases=query_aliases, actionable_aliases=action_aliases, + expected_role_name=expected_role_name, ) or candidates[0] ) @@ -792,6 +867,7 @@ class BindMixin: baseline_is_bound_act=baseline_is_bound_act, baseline_info=baseline_info, actionable_aliases=action_aliases, + expected_role_name=expected_role_name, ) query_alias = str(bind_info.get("act_alias") or "") summary = ( @@ -909,6 +985,7 @@ class BindMixin: task.last_run_at = now task.attempt_count = int(task.attempt_count or 0) + 1 result = dict(task.result or {}) + expected_role_name = str(result.get("expected_role_name") or "").strip() query_aliases = [ str(value) for value in (result.get("query_act_aliases") or []) @@ -1043,6 +1120,7 @@ class BindMixin: prefer_pending=True, prefer_aliases=query_aliases, actionable_aliases=action_aliases, + expected_role_name=expected_role_name, ) or candidates[0] ) @@ -1053,6 +1131,7 @@ class BindMixin: baseline_is_bound_act=baseline_is_bound_act, baseline_info=baseline_info, actionable_aliases=action_aliases, + expected_role_name=expected_role_name, ) selected_decision = binding_pending_decision( bind_info, @@ -1060,6 +1139,7 @@ class BindMixin: baseline_is_bound_act=baseline_is_bound_act, baseline_info=baseline_info, actionable_aliases=action_aliases, + expected_role_name=expected_role_name, ) is_pending_role = bool(selected_decision["confirmable"]) query_alias = str(bind_info.get("act_alias") or "") @@ -1081,6 +1161,8 @@ class BindMixin: candidates, baseline_role_name=baseline_role_name, baseline_is_bound_act=baseline_is_bound_act, + expected_role_name=expected_role_name, + actionable_aliases=action_aliases, ) if directly_confirmed is not None: bind_info = directly_confirmed @@ -1215,6 +1297,9 @@ class BindMixin: self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict ): client = self._client(cookie) + expected_role_name = str( + (task.result or {}).get("expected_role_name") or "" + ).strip() qr_act_alias = self._bind_qr_act_alias(config) query_aliases = self._query_bind_act_aliases(config) action_aliases = self._action_act_aliases(config) @@ -1253,6 +1338,7 @@ class BindMixin: prefer_pending=True, prefer_aliases=query_aliases, actionable_aliases=action_aliases, + expected_role_name=expected_role_name, ) or before or before_candidates[0] @@ -1263,6 +1349,7 @@ class BindMixin: baseline_is_bound_act=self._is_bound_act(before), baseline_info=before, actionable_aliases=action_aliases, + expected_role_name=expected_role_name, ) pending_decision = binding_pending_decision( pending_before, @@ -1270,6 +1357,7 @@ class BindMixin: baseline_is_bound_act=self._is_bound_act(before), baseline_info=before, actionable_aliases=action_aliases, + expected_role_name=expected_role_name, ) before_snapshot = self._bind_snapshot(before) cooldown_snapshot = self._bind_snapshot(cooldown_info) @@ -1382,6 +1470,7 @@ class BindMixin: ).isoformat(), "baseline_role_name": current_role_name, "baseline_is_bound_act": before_snapshot["is_bound_act"], + "expected_role_name": expected_role_name, "action_act_aliases": action_aliases, "bind_decision": pending_decision, "bind_candidate_decisions": candidate_decisions, diff --git a/web/backend/services/platform_fulfillment/binding.py b/web/backend/services/platform_fulfillment/binding.py index d2cafed..a250ac2 100644 --- a/web/backend/services/platform_fulfillment/binding.py +++ b/web/backend/services/platform_fulfillment/binding.py @@ -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 diff --git a/web/backend/services/platform_fulfillment/binding_evidence.py b/web/backend/services/platform_fulfillment/binding_evidence.py index 88543b3..384958f 100644 --- a/web/backend/services/platform_fulfillment/binding_evidence.py +++ b/web/backend/services/platform_fulfillment/binding_evidence.py @@ -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 diff --git a/web/backend/services/platform_fulfillment/customer.py b/web/backend/services/platform_fulfillment/customer.py index 68a001b..8a99ae0 100644 --- a/web/backend/services/platform_fulfillment/customer.py +++ b/web/backend/services/platform_fulfillment/customer.py @@ -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, diff --git a/web/backend/services/platform_fulfillment/order_sync.py b/web/backend/services/platform_fulfillment/order_sync.py index 4019dc6..0c48b5b 100644 --- a/web/backend/services/platform_fulfillment/order_sync.py +++ b/web/backend/services/platform_fulfillment/order_sync.py @@ -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",