diff --git a/docs/斗鱼/履约绑定状态机与踩坑复盘.md b/docs/斗鱼/履约绑定状态机与踩坑复盘.md index 43e66f9..5793394 100644 --- a/docs/斗鱼/履约绑定状态机与踩坑复盘.md +++ b/docs/斗鱼/履约绑定状态机与踩坑复盘.md @@ -336,3 +336,54 @@ WHERE t.binding_status = 'bound' 仍未做:命中后**自动切回原账号 A**。A 往往被协作单占用,是否等待/复用需要 产品规则;当前先交给人工,避免继续产生 doomed `actBind`。 + +### 9.6 绑定事实拆分与自动复用(2026-11-24 第二轮) + +**1. 详情页“绑定判定”面板** + +- `binding_evidence.py` 把一个绑定任务拆成互不混淆的几层: + - `actionCurrent`:QYOOB 上 `bindAct=1` 的当前角色; + - `actionPending`:QYOOB 上 `bindAct=0`、本次可确认的角色; + - `legacyLatest`:cjm 最新角色(仅参考,不能确认); + - `accountCurrentRole`:账号表当前角色(覆盖式); + - `roleLock` / `accountLock`:角色侧 / 账号侧 7 天锁。 +- 前端“绑定判定(QYOOB / cjm / 7 天锁)”卡片直接展示这些行;当 cjm 有角色 + 但 QYOOB 没有 pending 时,明确提示“不要直接确认”。 + +**2. 订单目标只认动作 alias** + +- `_actionable_pending_role`:结果里 `action_act_aliases` 非空、且选中的 + `act_alias` 不在其中时,不把该角色作为订单目标。 +- `_apply_binding_task`、`_attach_pending_binding_task`、`_latest_pending_binding_task`、 + `_order_target_role`、确认入口都执行这条约束;cjm-only pending 不再推进订单。 +- 兼容部署前已 `role_ready` 的订单:确认入口返回 + “当前动作通道没有待确认角色,请客户重新扫码后再确认”。 + +**3. 同账号同角色复用** + +- `_same_pair_reuse_role`:只有 **cjm 上有本次扫码角色**、QYOOB 同一角色 + `bindAct=1`、且账号当前角色也是该角色时,才复用。 +- 命中后直接 `bound`,写 `binding_reused_existing_pair`,不再等新 pending、 + 不再调 `actBind`。覆盖二维码过期里 `same_role_stale` 的主体。 +- 没有扫码角色(只有 `already_bound` 旧角色)不复用,避免把上一单角色套给新订单。 + +**4. 账号侧 7 天本地检查** + +- `find_account_lock`:当前账号最近 7 天 `bind_ok` 的是**别的角色**时,命中 + `account_role_bound_elsewhere`,订单转人工并记录账号上一角色/时间; +- 同一角色(同一对)不算锁;超过 7 天放行; +- pending、确认前、启动对账都会检查。 + +**5. 回归用例** + +- `test_binding_evidence_separates_qyoob_cjm_and_locks` +- `test_binding_evidence_marks_same_account_same_role` +- `test_cjm_only_pending_keeps_order_waiting_action_alias` +- `test_same_account_same_role_is_reused_as_bound` +- `test_already_bound_without_scan_does_not_reuse` +- `test_pending_role_blocked_by_account_seven_day_lock` +- `test_account_seven_day_lock_older_than_seven_days_allows_binding` + +仍未解决:本地没有任何 `bind_ok` 证据的**外部角色锁**(生产上新确认失败里 +5/7 属于这类),只能让客服/客户使用原账号或等待;CK 失效、二维码过期、 +17 单启动转人工和 2 单误结算仍需运营处理。 diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index a916b3a..c2b62f1 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -2762,6 +2762,406 @@ class TestBindingAndCompletion(_Base): assert task.execution_status == "manual_required" assert task.issue_code == "customer_role_bound_elsewhere" + def test_binding_evidence_separates_qyoob_cjm_and_locks(self): + task = self._allocated() + account = self.session.get(Account, task.account_id) + account.game_name = "旧账号角色" + account.role_bind_status = "bound" + lock_account = self.account("evidence-role-holder", capability=False) + self._role_lock_event(lock_account, "新扫角色") + # 当前分配的账号 7 天内绑过旧角色:账号侧锁 + self._role_lock_event(account, "旧账号角色") + qr_task = DouyuTask( + batch_id="evidence-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": "cjm", + "query_act_alias": "cjm", + "role_name": "新扫角色", + "current_role_name": "旧账号角色", + "baseline_role_name": "旧账号角色", + "action_act_aliases": ["20260120QYOOB"], + "bind_ready_for_confirm": True, + "bind_confirmed": False, + "bind_phase": "role_ready", + "bind_decision": { + "alias": "cjm", + "role_name": "新扫角色", + "reason": "role_changed", + "confirmable": True, + "actionable_alias": False, + }, + "bind_candidates": [ + { + "act_alias": "cjm", + "role_name": "新扫角色", + "is_bound_act": False, + "is_bound_role": True, + "reason": "role_changed", + "confirmable": True, + "actionable_alias": False, + }, + { + "act_alias": "20260120QYOOB", + "role_name": "旧账号角色", + "is_bound_act": True, + "is_bound_role": True, + "reason": "already_bound", + "confirmable": False, + "actionable_alias": 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() + + detail = service.get_task_detail(self.session, task.id) + evidence = detail["task"]["bindingEvidence"] + + assert evidence is not None + assert evidence["actionAliases"] == ["20260120QYOOB"] + assert evidence["actionCurrent"]["roleName"] == "旧账号角色" + assert evidence["actionCurrent"]["bindAct"] is True + assert evidence["actionPending"] is None + assert evidence["legacyLatest"]["roleName"] == "新扫角色" + assert evidence["selectedAlias"] == "cjm" + assert evidence["selectedActionable"] is False + 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"] == "旧账号角色" + + def test_binding_evidence_marks_same_account_same_role(self): + task = self._allocated() + account = self.session.get(Account, task.account_id) + account.game_name = "同对角色" + account.role_bind_status = "bound" + qr_task = DouyuTask( + batch_id="evidence-same-pair", + 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": "cjm", + "role_name": "同对角色", + "current_role_name": "同对角色", + "baseline_role_name": "同对角色", + "action_act_aliases": ["20260120QYOOB"], + "bind_ready_for_confirm": False, + "bind_confirmed": False, + "bind_phase": "waiting_scan", + "bind_decision": { + "alias": "cjm", + "role_name": "同对角色", + "reason": "same_role_stale", + "confirmable": False, + "actionable_alias": False, + }, + "bind_candidates": [ + { + "act_alias": "cjm", + "role_name": "同对角色", + "is_bound_act": False, + "is_bound_role": True, + "reason": "same_role_stale", + "confirmable": False, + "actionable_alias": False, + }, + { + "act_alias": "20260120QYOOB", + "role_name": "同对角色", + "is_bound_act": True, + "is_bound_role": True, + "reason": "already_bound", + "confirmable": False, + "actionable_alias": 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() + + detail = service.get_task_detail(self.session, task.id) + evidence = detail["task"]["bindingEvidence"] + + assert evidence is not None + assert evidence["samePair"] is True + assert evidence["actionCurrent"]["roleName"] == "同对角色" + assert evidence["legacyLatest"]["roleName"] == "同对角色" + assert evidence["targetRole"] == "" + assert evidence["confirmable"] is False + + def test_cjm_only_pending_keeps_order_waiting_action_alias(self): + task = self._allocated() + qr_task = DouyuTask( + batch_id="cjm-only-pending", + 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": "cjm", + "role_name": "cjm新角色", + "current_role_name": "旧角色", + "baseline_role_name": "旧角色", + "action_act_aliases": ["20260120QYOOB"], + "bind_ready_for_confirm": True, + "bind_confirmed": False, + "bind_phase": "role_ready", + "bind_decision": { + "alias": "cjm", + "role_name": "cjm新角色", + "reason": "role_changed", + "confirmable": True, + "actionable_alias": False, + }, + "bind_candidates": [ + { + "act_alias": "cjm", + "role_name": "cjm新角色", + "is_bound_act": False, + "is_bound_role": True, + "reason": "role_changed", + "confirmable": True, + "actionable_alias": False, + }, + { + "act_alias": "20260120QYOOB", + "role_name": "旧角色", + "is_bound_act": True, + "is_bound_role": True, + "reason": "already_bound", + "confirmable": False, + "actionable_alias": 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() + + service.refresh_binding(self.session, task_id=task.id) + + self.session.refresh(task) + detail = service.get_task_detail(self.session, task.id) + evidence = detail["task"]["bindingEvidence"] + assert task.binding_status == "qr_pending" + assert task.execution_status == "waiting_bind" + assert evidence["targetRole"] == "" + assert evidence["legacyLatest"]["roleName"] == "cjm新角色" + assert evidence["actionCurrent"]["roleName"] == "旧角色" + + # 兼容部署前已经 role_ready 的订单:确认入口也要拦住 cjm-only 角色。 + task.binding_status = "role_ready" + task.execution_status = "role_ready" + self.session.commit() + with pytest.raises(HTTPException) as exc_info: + service.confirm_binding_sync( + self.session, + task_id=task.id, + current=self.admin, + ) + assert exc_info.value.status_code == 409 + assert "动作通道" in str(exc_info.value.detail) + assert ( + self.session.query(DouyuTask) + .filter_by(task_type="confirm_bind") + .count() + == 0 + ) + + def _same_pair_qr_task(self, task, include_legacy: bool = True): + candidates = [ + { + "act_alias": "20260120QYOOB", + "role_name": "同对角色", + "is_bound_act": True, + "is_bound_role": True, + "reason": "already_bound", + "confirmable": False, + "actionable_alias": True, + } + ] + if include_legacy: + candidates.insert( + 0, + { + "act_alias": "cjm", + "role_name": "同对角色", + "is_bound_act": False, + "is_bound_role": True, + "reason": "same_role_stale", + "confirmable": False, + "actionable_alias": False, + }, + ) + return DouyuTask( + batch_id=f"reuse-qr-{task.id}", + 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": "cjm" if include_legacy else "20260120QYOOB", + "role_name": "同对角色", + "current_role_name": "同对角色", + "baseline_role_name": "同对角色", + "action_act_aliases": ["20260120QYOOB"], + "bind_ready_for_confirm": False, + "bind_confirmed": False, + "bind_phase": "waiting_scan", + "bind_decision": { + "alias": "cjm" if include_legacy else "20260120QYOOB", + "role_name": "同对角色", + "reason": "same_role_stale" if include_legacy else "already_bound", + "confirmable": False, + "actionable_alias": not include_legacy, + }, + "bind_candidates": candidates, + }, + created_by=self.admin_id, + ) + + def test_same_account_same_role_is_reused_as_bound(self): + task = self._allocated() + account = self.session.get(Account, task.account_id) + account.game_name = "同对角色" + account.role_bind_status = "bound" + qr_task = self._same_pair_qr_task(task, include_legacy=True) + 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() + + 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_reused_existing_pair") + .one() + ) + assert task.binding_status == "bound" + assert task.execution_status == "bound" + assert task.bind_task_id == qr_task.id + assert event.detail_json["roleName"] == "同对角色" + assert event.detail_json["reason"] == "same_account_same_role" + assert ( + self.session.query(DouyuTask) + .filter_by(task_type="confirm_bind") + .count() + == 0 + ) + + def test_already_bound_without_scan_does_not_reuse(self): + task = self._allocated() + account = self.session.get(Account, task.account_id) + account.game_name = "同对角色" + account.role_bind_status = "bound" + qr_task = self._same_pair_qr_task(task, include_legacy=False) + 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() + + service.refresh_binding(self.session, task_id=task.id) + + self.session.refresh(task) + assert task.binding_status == "qr_pending" + assert task.execution_status == "waiting_bind" + assert ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="binding_reused_existing_pair") + .count() + == 0 + ) + + def test_pending_role_blocked_by_account_seven_day_lock(self): + task = self._allocated() + account = self.session.get(Account, task.account_id) + account.game_name = "账号旧角色" + account.role_bind_status = "bound" + self._role_lock_event(account, "账号上一角色") + qr_task = self._role_lock_pending_task(task, "本次新角色") + self.session.add(qr_task) + self.session.commit() + + service.sync_task_from_binding_runner( + self.session, + douyu_task_id=qr_task.id, + ) + + self.session.refresh(task) + event = ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="binding_account_locked_elsewhere") + .one() + ) + assert task.binding_status == "failed" + assert task.execution_status == "manual_required" + assert task.issue_code == "account_role_bound_elsewhere" + assert "账号上一角色" in task.last_error + assert event.detail_json["accountRoleName"] == "账号上一角色" + assert event.detail_json["sourceTaskId"] == qr_task.id + + def test_account_seven_day_lock_older_than_seven_days_allows_binding(self): + task = self._allocated() + account = self.session.get(Account, task.account_id) + account.game_name = "账号旧角色" + account.role_bind_status = "bound" + self._role_lock_event( + account, + "账号上一角色", + occurred_at=NOW - timedelta(days=8), + ) + qr_task = self._role_lock_pending_task(task, "本次新角色") + self.session.add(qr_task) + self.session.commit() + + service.sync_task_from_binding_runner( + self.session, + douyu_task_id=qr_task.id, + ) + + self.session.refresh(task) + assert task.binding_status == "role_ready" + assert task.execution_status == "role_ready" + def test_refresh_binding_attaches_latest_pending_account_workbench_role(self): task = self._allocated() old_bind_task = DouyuTask( diff --git a/web/backend/services/platform_fulfillment/binding.py b/web/backend/services/platform_fulfillment/binding.py index 8b29925..b69bfdb 100644 --- a/web/backend/services/platform_fulfillment/binding.py +++ b/web/backend/services/platform_fulfillment/binding.py @@ -51,7 +51,14 @@ from .repository import ( _load_task, _load_task_for_update, ) -from .role_lock import ROLE_LOCK_ISSUE, RoleLock, find_role_lock +from .role_lock import ( + ACCOUNT_LOCK_ISSUE, + ROLE_LOCK_ISSUE, + AccountLock, + RoleLock, + find_account_lock, + find_role_lock, +) from .runtime import ( _append_event, _apply_task_lease_policy, @@ -239,10 +246,37 @@ def _lease_for_task( return fulfillment_lease_for_task(db, task) +def _actionable_pending_role( + result: dict[str, Any] | None, + role_name: str, +) -> str: + """只有动作 alias 上的 pending 才能作为订单目标。 + + cjm/legacy 上先出现的角色只能提示,不能直接确认;否则 actBind 会对 + QYOOB 调一个未生效的 pending(11.22 抓包 -200001 的根因)。 + """ + role = str(role_name or "").strip() + if not role or not isinstance(result, dict): + return "" + raw_aliases = result.get("action_act_aliases") + action_aliases = ( + [str(value).strip() for value in raw_aliases if str(value).strip()] + if isinstance(raw_aliases, (list, tuple)) + else [] + ) + selected_alias = str(result.get("act_alias") or "").strip() + if action_aliases and selected_alias and selected_alias not in action_aliases: + return "" + return role + + def _pending_role_of(task: DouyuTask | None) -> str: if task is None or not isinstance(task.result, dict): return "" - return pending_binding_role_from_result(task.result) + return _actionable_pending_role( + task.result, + pending_binding_role_from_result(task.result), + ) def _owned_binding_tasks( @@ -376,6 +410,55 @@ def _mark_role_locked( return True +def _mark_account_locked( + db: Session, + task: PlatformFulfillmentTask, + source: DouyuTask | None, + lock: AccountLock, +) -> bool: + """当前分配的账号 7 天内绑过别的角色:转人工,不调 actBind。""" + if str(task.issue_code or "") == ACCOUNT_LOCK_ISSUE: + return False + message = lock.message() + lease = _lease_for_task(db, task) + if source is not None and int(source.id) > int(task.bind_task_id or 0): + task.bind_task_id = int(source.id) + task.binding_status = "failed" + task.execution_status = "manual_required" + task.issue_code = ACCOUNT_LOCK_ISSUE + task.last_error = message + task.updated_at = _now() + detail = { + "accountRoleName": lock.role_name, + "accountBoundAt": lock.bound_at.isoformat(), + "accountReusableAt": lock.reusable_at.isoformat(), + "allocatedAccountId": task.account_id, + "allocatedAccountName": lock.account_name, + "message": message, + } + if source is not None: + detail["sourceTaskId"] = int(source.id) + detail["sourceTaskType"] = str(source.task_type or "") + _append_event(db, task.id, "binding_account_locked_elsewhere", detail=detail) + _apply_task_lease_policy(db, task, lease=lease) + _emit_order_site_binding_state(db, task.id) + return True + + +def _block_on_account_lock( + db: Session, + task: PlatformFulfillmentTask, + role_name: str, + source: DouyuTask | None = None, +) -> bool: + if str(task.issue_code or "") == ACCOUNT_LOCK_ISSUE: + return False + lock = find_account_lock(db, task.account_id, role_name) + if lock is None: + return False + return _mark_account_locked(db, task, source, lock) + + def _block_on_role_lock( db: Session, task: PlatformFulfillmentTask, @@ -427,6 +510,121 @@ def _apply_binding_qr_display( return True +def _same_pair_reuse_role( + result: dict[str, Any] | None, + account: Account | None, +) -> str: + """本次扫码角色已经绑在当前账号上:同一对,直接复用。 + + 只认 **cjm/legacy 上出现的扫码角色**,并且要求动作 alias 上也是同一个 + 角色且 bindAct=1。动作 alias 上只要出现 bindAct=0 的 pending,就说明客户 + 扫的是新角色,必须走正常确认,不能复用旧角色。 + """ + if not isinstance(result, dict) or account is None: + return "" + if str(account.role_bind_status or "") != "bound": + return "" + current = str(account.game_name or "").strip() + if not current: + return "" + raw_aliases = result.get("action_act_aliases") + action_aliases = ( + [str(value).strip() for value in raw_aliases if str(value).strip()] + if isinstance(raw_aliases, (list, tuple)) + else [] + ) + candidates = [ + raw + for raw in (result.get("bind_candidates") or []) + if isinstance(raw, dict) + ] + action_candidates = [ + raw + for raw in candidates + if str(raw.get("act_alias") or raw.get("alias") or "").strip() + in action_aliases + ] + if any( + str(raw.get("role_name") or "").strip() + and not bool(raw.get("is_bound_act")) + for raw in action_candidates + ): + # 动作 alias 上已有新的 pending:客户扫了新角色,交给正常确认。 + return "" + selected_alias = str(result.get("act_alias") or "").strip() + legacy_role = next( + ( + str(raw.get("role_name") or "").strip() + for raw in candidates + if str(raw.get("act_alias") or raw.get("alias") or "").strip() + not in action_aliases + and str(raw.get("role_name") or "").strip() + ), + "", + ) + if selected_alias and selected_alias in action_aliases: + scanned_role = legacy_role + else: + scanned_role = str( + result.get("pending_role_name") + or result.get("role_name") + or legacy_role + or "" + ).strip() + if not scanned_role or scanned_role != current: + return "" + if action_candidates: + action_bound = any( + str(raw.get("role_name") or "").strip() == current + and bool(raw.get("is_bound_act")) + for raw in action_candidates + ) + return current if action_bound else "" + if ( + (not action_aliases or selected_alias not in action_aliases) + and str(result.get("current_role_name") or "").strip() == current + ): + return current + return "" + + +def _mark_reused_pair( + db: Session, + task: PlatformFulfillmentTask, + source: DouyuTask, + *, + role_name: str, + account: Account | None, +) -> bool: + lease = _lease_for_task(db, task) + task.bind_task_id = int(source.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_reused_existing_pair", + detail={ + "roleName": role_name[:128], + "accountId": task.account_id, + "accountName": ( + (account.nickname or account.username) + if account is not None + else "" + ), + "sourceTaskId": int(source.id), + "sourceTaskType": str(source.task_type or ""), + "reason": "same_account_same_role", + }, + ) + _apply_task_lease_policy(db, task, lease=lease) + _emit_order_site_binding_state(db, task.id) + return True + + def _apply_binding_task( db: Session, task: PlatformFulfillmentTask, @@ -441,8 +639,8 @@ def _apply_binding_task( """ if _frozen(task): return False - if str(task.issue_code or "") == ROLE_LOCK_ISSUE: - # 角色 7 天锁只能由人工重置后重新进入流程。 + if str(task.issue_code or "") in {ROLE_LOCK_ISSUE, ACCOUNT_LOCK_ISSUE}: + # 7 天锁只能由人工重置后重新进入流程。 return False if not task.account_id or not source.account_id: return False @@ -471,6 +669,16 @@ def _apply_binding_task( return False account = db.get(Account, int(task.account_id)) + if str(source.task_type or "") == "get_bind_qr" and phase != "confirming": + reused_role = _same_pair_reuse_role(source.result, account) + if reused_role: + return _mark_reused_pair( + db, + task, + source, + role_name=reused_role, + account=account, + ) binding = resolve_fulfillment_binding( source, account=account, @@ -601,6 +809,9 @@ def _apply_binding_task( role_name = binding.pending_role_name if not role_name: return False + if not _actionable_pending_role(source.result, role_name): + # cjm/legacy 先出现的新角色:订单继续保持等待动作通道。 + return False if phase == "confirming": # 确认任务执行中,后到的扫码结果不能把订单打回待确认、丢掉确认任务指针。 return False @@ -615,6 +826,8 @@ def _apply_binding_task( return False if _block_on_role_lock(db, task, role_name, source): return True + if _block_on_account_lock(db, task, role_name, source): + return True task.bind_task_id = int(source.id) task.binding_status = "role_ready" task.execution_status = "role_ready" @@ -891,11 +1104,19 @@ def reconcile_binding_observations( if not changed and task.binding_status == "role_ready": # 部署前已经 role_ready 的订单:启动时补一次角色 7 天锁检查。 target_role_name = _order_target_role(db, task) - if target_role_name and _block_on_role_lock( - db, - task, - target_role_name, - current, + if target_role_name and ( + _block_on_role_lock( + db, + task, + target_role_name, + current, + ) + or _block_on_account_lock( + db, + task, + target_role_name, + current, + ) ): changed = True if changed: @@ -938,7 +1159,10 @@ def _latest_pending_binding_task( for row in rows: if not source_created_within_lease(lease, row): continue - if resolve_douyu_binding(row, account=account).status == BINDING_VIEW_PENDING: + binding = resolve_douyu_binding(row, account=account) + if binding.status != BINDING_VIEW_PENDING: + continue + if _actionable_pending_role(row.result, binding.pending_role_name): return row return None @@ -961,6 +1185,10 @@ def _attach_pending_binding_task( or int(bind_task.account_id or 0) != int(task.account_id) or bind_task.task_type not in PENDING_BINDING_TASK_TYPES or binding.status != BINDING_VIEW_PENDING + or not _actionable_pending_role( + bind_task.result if isinstance(bind_task.result, dict) else {}, + binding.pending_role_name, + ) or not lease_is_active(lease) or not source_created_within_lease(lease, bind_task) or ( @@ -978,6 +1206,8 @@ def _attach_pending_binding_task( return False if _block_on_role_lock(db, task, binding.pending_role_name, bind_task): return True + if _block_on_account_lock(db, task, binding.pending_role_name, bind_task): + return True previous_bind_task_id = task.bind_task_id task.bind_task_id = int(bind_task.id) task.binding_status = "role_ready" @@ -1187,7 +1417,23 @@ def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[st ): db.commit() return get_task_detail(db, task.id) + if target_role_name and _block_on_account_lock( + db, + task, + target_role_name, + current_bind_task, + ): + db.commit() + return get_task_detail(db, task.id) expected_role_name = str(current_bind_result.get("role_name") or "").strip() + if expected_role_name and not _actionable_pending_role( + current_bind_result, + expected_role_name, + ): + raise HTTPException( + status_code=409, + detail="当前动作通道没有待确认角色,请客户重新扫码后再确认", + ) 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( diff --git a/web/backend/services/platform_fulfillment/binding_evidence.py b/web/backend/services/platform_fulfillment/binding_evidence.py new file mode 100644 index 0000000..e566110 --- /dev/null +++ b/web/backend/services/platform_fulfillment/binding_evidence.py @@ -0,0 +1,278 @@ +"""履约绑定判定的只读证据。 + +把一个 DouyuTask 的结果拆成互不混淆的几层事实: + +- ``actionCurrent``:动作 alias(QYOOB)上已经 bindAct=1 的角色; +- ``actionPending``:动作 alias 上 bindAct=0、可确认的本次待确认角色; +- ``legacyLatest``:legacy(cjm)上的最新角色,只能提示,不能单独确认; +- ``accountCurrentRole``:账号表当前生效角色(覆盖式,不代表本次); +- ``roleLock`` / ``accountLock``:7 天锁,是“能不能绑”的资格,不是角色识别。 + +这个模块只读,不改变订单状态。页面用它把“新扫的 / 旧的 / cjm 的 / 7 天锁的” +分开显示,避免再把它们混成一个“待确认角色”。 +""" + +from __future__ import annotations + +from datetime import datetime +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 .role_lock import AccountLock, RoleLock, find_account_lock, find_role_lock + + +def _text(value: Any) -> str: + return str(value or "").strip() + + +def _bool(value: Any) -> bool: + return bool(value) + + +def _channel(area: str, plat: str) -> str: + return " / ".join(value for value in (area, plat) if value) + + +def _candidate(raw: dict[str, Any]) -> dict[str, Any]: + alias = _text(raw.get("act_alias") or raw.get("alias")) + area = _text(raw.get("area_name")) + plat = _text(raw.get("plat_name")) + return { + "alias": alias, + "roleName": _text(raw.get("role_name")), + "areaName": area, + "platName": plat, + "channel": _channel(area, plat), + "bindAct": _bool(raw.get("is_bound_act") or raw.get("bind_act")), + "bindRole": _bool(raw.get("is_bound_role") or raw.get("bind_role")), + "needBindAct": _bool(raw.get("need_bind_act")), + "actionableAlias": _bool( + raw.get("actionable_alias") or raw.get("actionableAlias") + ), + "confirmable": _bool(raw.get("confirmable")), + "reason": _text(raw.get("reason")), + } + + +def _candidate_from_info( + info: Any, + action_aliases: list[str], +) -> dict[str, Any] | None: + if not isinstance(info, dict): + return None + raw = { + **info, + "act_alias": info.get("act_alias") or info.get("alias"), + } + candidate = _candidate(raw) + candidate["actionableAlias"] = candidate["alias"] in action_aliases + return candidate if candidate["roleName"] else None + + +def _lock_out(lock: RoleLock | AccountLock | None) -> dict[str, Any] | None: + if lock is None: + return None + data = { + "roleName": lock.role_name, + "accountId": lock.account_id, + "accountName": lock.account_name, + "boundAt": lock.bound_at.isoformat(), + "reusableAt": lock.reusable_at.isoformat(), + "message": lock.message(), + } + if isinstance(lock, RoleLock): + data["leasePurpose"] = lock.lease_purpose + data["leaseBatchId"] = lock.lease_batch_id + return data + + +def _account_current_candidate( + account: Account | None, + action_alias: str, +) -> dict[str, Any] | None: + if account is None or not _text(account.game_name): + return None + if str(account.role_bind_status or "") != "bound": + return None + channel = _text(account.game_channel) + area, _, plat = channel.partition(" · ") + return { + "alias": action_alias, + "roleName": _text(account.game_name), + "areaName": area, + "platName": plat, + "channel": channel, + "bindAct": True, + "bindRole": True, + "needBindAct": False, + "actionableAlias": bool(action_alias), + "confirmable": False, + "reason": "account_current_bound", + } + + +def build_binding_evidence( + db: Session, + task: PlatformFulfillmentTask, + bind_task: DouyuTask | None, + account: Account | None, + *, + now: datetime | None = None, +) -> dict[str, Any] | None: + """构建页面用的绑定判定快照;无绑定任务时返回 None。""" + if bind_task is None: + return None + result = bind_task.result if isinstance(bind_task.result, dict) else {} + action_aliases = [ + _text(value) + for value in (result.get("action_act_aliases") or []) + if _text(value) + ] + candidates = [ + _candidate(raw) + for raw in (result.get("bind_candidates") or []) + if isinstance(raw, dict) + ] + candidates = [item for item in candidates if item["alias"]] + 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 {} + selected_actionable = bool( + decision.get("actionable_alias") + or (selected_alias and selected_alias in action_aliases) + ) + + action_current = next( + ( + item + for item in candidates + if item["alias"] in action_aliases + and item["bindAct"] + and item["roleName"] + ), + None, + ) + if action_current is None: + action_current = _account_current_candidate( + account, + action_aliases[0] if action_aliases else "", + ) + action_pending = next( + ( + item + for item in candidates + if item["alias"] in action_aliases + and item["roleName"] + and not item["bindAct"] + ), + None, + ) + if ( + action_pending is None + and selected_info_candidate is not None + and selected_info_candidate["alias"] in action_aliases + and selected_info_candidate["roleName"] + and not selected_info_candidate["bindAct"] + ): + action_pending = selected_info_candidate + legacy_latest = next( + ( + item + for item in candidates + if item["alias"] not in action_aliases and item["roleName"] + ), + None, + ) + if ( + legacy_latest is None + and selected_info_candidate is not None + and selected_info_candidate["alias"] not in action_aliases + and selected_info_candidate["roleName"] + ): + legacy_latest = selected_info_candidate + + pending_role = pending_binding_role_from_result(result) + scanned_role = _text( + decision.get("role_name") + or result.get("role_name") + or (legacy_latest or {}).get("roleName") + or pending_role + ) + target_role = pending_role if selected_actionable else "" + account_current_role = _text(account.game_name) if account is not None else "" + same_pair = bool( + scanned_role + and account_current_role + and scanned_role == account_current_role + and action_current is not None + and action_current.get("bindAct") + and action_current.get("roleName") == scanned_role + ) + bound = str(bind_task.status or "") == "success" and bool( + result.get("bind_confirmed") + ) + confirmable = bool( + target_role + and str(bind_task.status or "") == "success" + and task.binding_status == "role_ready" + and not bound + ) + role_lock = ( + find_role_lock( + db, + scanned_role, + current_account_id=task.account_id, + now=now, + ) + if scanned_role + else None + ) + account_lock = find_account_lock( + db, + task.account_id, + scanned_role, + now=now, + ) + return { + "sourceTaskId": int(bind_task.id), + "sourceTaskType": str(bind_task.task_type or ""), + "sourceTaskStatus": str(bind_task.status or ""), + "actionAliases": action_aliases, + "selectedAlias": selected_alias, + "selectedActionable": selected_actionable, + "decisionReason": _text( + decision.get("reason") or result.get("bind_phase") + ), + "confirmable": confirmable, + "targetRole": target_role, + "scannedRole": scanned_role, + "samePair": same_pair, + "actionCurrent": action_current, + "actionPending": action_pending, + "legacyLatest": legacy_latest, + "accountCurrentRole": account_current_role, + "accountBindStatus": ( + str(account.role_bind_status or "") if account is not None else "" + ), + "roleLock": _lock_out(role_lock), + "accountLock": _lock_out(account_lock), + } + + +__all__ = ["build_binding_evidence"] diff --git a/web/backend/services/platform_fulfillment/binding_status.py b/web/backend/services/platform_fulfillment/binding_status.py index 44aecb1..ce36245 100644 --- a/web/backend/services/platform_fulfillment/binding_status.py +++ b/web/backend/services/platform_fulfillment/binding_status.py @@ -27,6 +27,7 @@ def _customer_task_message_for(issue_code: str) -> str: "account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理", "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", "customer_role_bound_elsewhere": "该游戏角色 7 天内已绑定其他斗鱼账号,请使用原账号或等待", + "account_role_bound_elsewhere": "当前斗鱼账号 7 天内已绑定其他角色,请换号或等待", "eligibility_check_failed": "状态查询异常,请稍后刷新", "manual_required": "当前需要人工处理,请联系客服", } diff --git a/web/backend/services/platform_fulfillment/classification.py b/web/backend/services/platform_fulfillment/classification.py index d54e1e0..3d44c5f 100644 --- a/web/backend/services/platform_fulfillment/classification.py +++ b/web/backend/services/platform_fulfillment/classification.py @@ -78,6 +78,7 @@ def manual_reason(issue_code: str, exchange_status: str) -> str: "account_role_cooldown", "customer_role_cooldown", "customer_role_bound_elsewhere", + "account_role_bound_elsewhere", }: return "binding_failed" if issue in {"lease_expired", "manual_required"}: diff --git a/web/backend/services/platform_fulfillment/role_lock.py b/web/backend/services/platform_fulfillment/role_lock.py index e0d416b..21a3730 100644 --- a/web/backend/services/platform_fulfillment/role_lock.py +++ b/web/backend/services/platform_fulfillment/role_lock.py @@ -27,6 +27,9 @@ from ...models import Account, AccountEvent, AccountLease #: 新的履约 issue code:用户角色 7 天内已绑定其他斗鱼账号。 ROLE_LOCK_ISSUE = "customer_role_bound_elsewhere" +#: 新的履约 issue code:当前分配的斗鱼账号 7 天内已绑定其他角色。 +ACCOUNT_LOCK_ISSUE = "account_role_bound_elsewhere" + #: 官方规则窗口。 ROLE_LOCK_WINDOW = timedelta(days=7) @@ -39,6 +42,23 @@ _LEASE_PURPOSE_LABELS = { } +@dataclass(frozen=True) +class AccountLock: + role_name: str + account_id: int + account_name: str + bound_at: datetime + reusable_at: datetime + + def message(self) -> str: + return ( + f"该斗鱼账号 7 天内已绑定角色({self.role_name})," + f"绑定时间 {_beijing_text(self.bound_at)}," + f"预计 {_beijing_text(self.reusable_at)} 后可再次换绑;" + "如需绑定新角色请换号或等待。" + ) + + @dataclass(frozen=True) class RoleLock: role_name: str @@ -143,9 +163,68 @@ def find_role_lock( ) +def find_account_lock( + db: Session, + account_id: int | None, + scanned_role: str, + *, + now: datetime | None = None, +) -> AccountLock | None: + """当前分配的斗鱼账号 7 天内是否已经绑定过别的角色。 + + 同一角色(同一对)不算锁:复用已有绑定即可。 + """ + role = str(scanned_role or "").strip() + if account_id is None or not role: + return None + moment = now or datetime.now(UTC) + since = moment - ROLE_LOCK_WINDOW + event = ( + db.query(AccountEvent) + .filter( + AccountEvent.event_type == "bind_ok", + AccountEvent.subject_type == "elite_role", + AccountEvent.account_id == int(account_id), + AccountEvent.occurred_at >= since, + AccountEvent.occurred_at <= moment, + ) + .order_by(AccountEvent.occurred_at.desc(), AccountEvent.id.desc()) + .first() + ) + if event is None: + return None + bound_role = str(event.subject_key or "").strip() + if not bound_role or bound_role == role: + return None + account = db.get(Account, int(account_id)) + account_name = ( + ( + str(account.nickname or "").strip() + or str(account.username or "").strip() + or f"账号#{account.id}" + ) + if account is not None + else f"账号#{account_id}" + ) + bound_at = ( + event.occurred_at + if event.occurred_at.tzinfo is not None + else event.occurred_at.replace(tzinfo=UTC) + ) + return AccountLock( + role_name=bound_role, + account_id=int(account_id), + account_name=account_name, + bound_at=bound_at, + reusable_at=bound_at + ROLE_LOCK_WINDOW, + ) + + __all__ = [ "ROLE_LOCK_ISSUE", "ROLE_LOCK_WINDOW", + "AccountLock", "RoleLock", + "find_account_lock", "find_role_lock", ] diff --git a/web/backend/services/platform_fulfillment/views.py b/web/backend/services/platform_fulfillment/views.py index 6069246..c086d85 100644 --- a/web/backend/services/platform_fulfillment/views.py +++ b/web/backend/services/platform_fulfillment/views.py @@ -33,6 +33,7 @@ from ..douyu_binding import ( ) 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, @@ -493,6 +494,11 @@ def _task_out( 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": ( { diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 797c375..ec0fa55 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -2477,6 +2477,52 @@ export interface PlatformFulfillmentBindTask { bindConfirmed: boolean; } +export interface PlatformFulfillmentBindingCandidate { + alias: string; + roleName: string; + areaName: string; + platName: string; + channel: string; + bindAct: boolean; + bindRole: boolean; + needBindAct: boolean; + actionableAlias: boolean; + confirmable: boolean; + reason: string; +} + +export interface PlatformFulfillmentBindingLock { + roleName: string; + accountId: number; + accountName: string; + boundAt: string; + reusableAt: string; + message: string; + leasePurpose?: string; + leaseBatchId?: string; +} + +export interface PlatformFulfillmentBindingEvidence { + sourceTaskId: number; + sourceTaskType: string; + sourceTaskStatus: string; + actionAliases: string[]; + selectedAlias: string; + selectedActionable: boolean; + decisionReason: string; + confirmable: boolean; + targetRole: string; + scannedRole: string; + samePair: boolean; + actionCurrent: PlatformFulfillmentBindingCandidate | null; + actionPending: PlatformFulfillmentBindingCandidate | null; + legacyLatest: PlatformFulfillmentBindingCandidate | null; + accountCurrentRole: string; + accountBindStatus: string; + roleLock: PlatformFulfillmentBindingLock | null; + accountLock: PlatformFulfillmentBindingLock | null; +} + export interface PlatformFulfillmentTask { id: number; sourceSystem: string; @@ -2526,6 +2572,7 @@ export interface PlatformFulfillmentTask { account: PlatformFulfillmentAccount | null; lease: { id: number; status: string; expiresAt: string | null } | null; bindTask: PlatformFulfillmentBindTask | null; + bindingEvidence: PlatformFulfillmentBindingEvidence | null; exchangeTaskId: number | null; exchangeResultImage: { objectKey: string; diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 2c49bb1..d12ccdc 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -134,6 +134,7 @@ const EVENT_LABELS: Record = { binding_pending_task_linked: '关联最新待确认角色', binding_pending_observation_superseded: '旧待确认角色已被最新绑定替换', binding_role_locked_elsewhere: '用户角色已被其他账号占用', + binding_account_locked_elsewhere: '斗鱼账号 7 天内已绑定其他角色', binding_observation_confirmed: '账号观测确认角色绑定', binding_confirmed: '履约绑定已确认', binding_sync_rejected: '忽略不匹配的绑定证据', @@ -171,6 +172,7 @@ const ISSUE_LABELS: Record = { account_role_cooldown: '斗鱼账号仍在换绑冷却期', customer_role_cooldown: '游戏角色仍在换绑冷却期', customer_role_bound_elsewhere: '用户角色 7 天内已绑定其他斗鱼账号', + account_role_bound_elsewhere: '斗鱼账号 7 天内已绑定其他角色', lease_expired: '账号租约已过期', manual_required: '需要人工处理', source_cancelled: '来源订单已取消', @@ -365,6 +367,9 @@ function eventDescription(event: { eventType: string; detail: Record { const bindTaskId = selected?.bindTask?.id; @@ -1694,17 +1693,6 @@ export default function PlatformFulfillmentPage() { {selected.account.gameChannel || '-'} - {pendingBindRoleName ? ( - - - 待确认 - {pendingBindRoleName} - {pendingBindRoleChannel ? ( - {pendingBindRoleChannel} - ) : null} - - - ) : null} {formatTime(selected.account.roleChangeAvailableAt) || '无冷却'} @@ -1718,6 +1706,103 @@ export default function PlatformFulfillmentPage() { + + {selected.bindingEvidence ? ( + + {!selected.bindingEvidence.selectedActionable && selected.bindingEvidence.legacyLatest ? ( + + ) : null} + + + {selected.bindingEvidence.actionAliases.join(' / ') || '-'} + + {' '}系统选中:{selected.bindingEvidence.selectedAlias || '-'} + {selected.bindingEvidence.selectedActionable ? '(动作通道)' : '(非动作通道)'} + + + + {selected.bindingEvidence.actionCurrent ? ( + + bindAct=1 + {selected.bindingEvidence.actionCurrent.roleName} + {selected.bindingEvidence.actionCurrent.channel ? ( + {selected.bindingEvidence.actionCurrent.channel} + ) : null} + + ) : ( + 未识别 + )} + + + {selected.bindingEvidence.actionPending ? ( + + bindAct=0 + {selected.bindingEvidence.actionPending.roleName} + {selected.bindingEvidence.actionPending.channel ? ( + {selected.bindingEvidence.actionPending.channel} + ) : null} + + ) : ( + 未出现(等待动作通道) + )} + + + {selected.bindingEvidence.legacyLatest ? ( + + legacy + {selected.bindingEvidence.legacyLatest.roleName} + 不能直接确认 + + ) : ( + - + )} + + + + + {selected.bindingEvidence.confirmable ? '可以确认' : '不可确认'} + + + {selected.bindingEvidence.decisionReason || '-'} + + {selected.bindingEvidence.samePair ? ( + 同账号同角色,已绑定可复用 + ) : null} + + + + {selected.bindingEvidence.roleLock ? ( + + {selected.bindingEvidence.roleLock.roleName} 已绑{' '} + {selected.bindingEvidence.roleLock.accountName}, + {formatTime(selected.bindingEvidence.roleLock.reusableAt)} 后可复用 + + ) : ( + 未发现(仅本系统记录) + )} + + + {selected.bindingEvidence.accountLock ? ( + + 7 天内绑过 {selected.bindingEvidence.accountLock.roleName}, + {formatTime(selected.bindingEvidence.accountLock.reusableAt)} 后可换绑 + + ) : ( + 未发现(仅本系统记录) + )} + + + + ) : ( + 暂无绑定证据 + )} + +