diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 2a1a546..764f8b4 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -5742,3 +5742,157 @@ class TestBindingAndCompletion(_Base): assert reconciled == 0 assert task.binding_status == "qr_pending" assert task.bind_task_id is None + + def test_waiting_scan_preflight_same_pair_with_different_customer_role_does_not_reuse( + self, + ): + """发码预检阶段 cjm 残留旧角色且与客户提交角色不同时,绝不能提前误标为 bound。""" + 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="preflight-old-cjm", + 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={ + "act_alias": "20260120QYOOB", + "action_act_aliases": ["20260120QYOOB"], + "expected_role_name": "妳总固执任性", + "expected_role_required": True, + "current_role_name": "强者不屑质疑", + "baseline_role_name": "强者不屑质疑", + "role_name": "", + "bind_ready_for_confirm": False, + "bind_confirmed": False, + "bind_phase": "waiting_scan", + "url": "https://livelink.example/qr", + "bind_candidates": [ + { + "act_alias": "cjm", + "role_name": "强者不屑质疑", + "is_bound_act": False, + "is_bound_role": True, + "need_bind_act": False, + }, + { + "act_alias": "20260120QYOOB", + "role_name": "强者不屑质疑", + "is_bound_act": True, + "is_bound_role": True, + "need_bind_act": True, + }, + ], + }, + created_by=self.admin_id, + ) + self.session.add(qr_task) + self.session.flush() + task.bind_task_id = qr_task.id + task.binding_status = "preparing" + task.execution_status = "waiting_bind" + self.session.commit() + + service.sync_task_from_binding_runner(self.session, douyu_task_id=qr_task.id) + detail = service.get_task_detail(self.session, task.id) + + self.session.refresh(task) + assert task.binding_status == "qr_pending" + assert task.execution_status == "waiting_bind" + assert detail["task"]["bindingEvidence"]["scannedRole"] == "" + assert ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="binding_reused_existing_pair") + .count() + == 0 + ) + + def test_reconcile_reverts_false_same_pair_reuse_and_promotes_scanned_role(self): + """已被历史同对复用误锁为 bound 但尚未兑换的订单,重启对账后应自动回退并推进真实扫码角色。""" + 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="false-reuse-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", + "action_act_aliases": ["20260120QYOOB"], + "expected_role_name": "妳总固执任性", + "expected_role_required": True, + "current_role_name": "强者不屑质疑", + "baseline_role_name": "强者不屑质疑", + "role_name": "妳总固执任性", + "area_name": "手Q", + "plat_name": "安卓(android)", + "bind_ready_for_confirm": True, + "bind_confirmed": False, + "bind_phase": "role_ready", + "url": "https://livelink.example/qr", + "bind_candidates": [ + { + "act_alias": "cjm", + "role_name": "妳总固执任性", + "area_name": "手Q", + "plat_name": "安卓(android)", + "is_bound_act": False, + "is_bound_role": True, + "need_bind_act": False, + }, + { + "act_alias": "20260120QYOOB", + "role_name": "强者不屑质疑", + "area_name": "微信", + "plat_name": "安卓(android)", + "is_bound_act": True, + "is_bound_role": True, + "need_bind_act": True, + }, + ], + }, + created_by=self.admin_id, + ) + self.session.add(qr_task) + self.session.flush() + task.bind_task_id = qr_task.id + task.binding_status = "bound" + task.execution_status = "bound" + self.session.add( + PlatformFulfillmentEvent( + task_id=task.id, + event_type="binding_reused_existing_pair", + actor_type="system", + actor_id="", + detail_json={ + "roleName": "强者不屑质疑", + "sourceTaskId": qr_task.id, + "reason": "same_account_same_role", + }, + ) + ) + self.session.commit() + + reconciled = service.reconcile_binding_observations(self.session) + + self.session.refresh(task) + assert reconciled >= 1 + assert task.binding_status == "role_ready" + assert task.execution_status == "role_ready" + assert ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="binding_false_reuse_reverted") + .count() + == 1 + ) diff --git a/web/backend/services/platform_fulfillment/binding.py b/web/backend/services/platform_fulfillment/binding.py index 680a17d..295054b 100644 --- a/web/backend/services/platform_fulfillment/binding.py +++ b/web/backend/services/platform_fulfillment/binding.py @@ -669,6 +669,9 @@ def _apply_binding_qr_display( def _same_pair_reuse_role( result: dict[str, Any] | None, account: Account | None, + *, + customer_role_name: str = "", + task_status: str = "", ) -> str: """本次扫码角色已经绑在当前账号上:同一对,直接复用。 @@ -678,11 +681,21 @@ def _same_pair_reuse_role( """ if not isinstance(result, dict) or account is None: return "" + # 发码预检/轮询未变化阶段绝不复用账号历史角色,必须等扫码完成或观测到扫码变化。 + if task_status and task_status != "success" and not bool( + result.get("bind_poll_legacy_observed_change") + ): + return "" if str(account.role_bind_status or "") != "bound": return "" current = str(account.game_name or "").strip() if not current: return "" + customer_role = str(customer_role_name or "").strip() + if bool(result.get("expected_role_required")) and not customer_role: + return "" + if customer_role and not role_names_match(current, customer_role): + return "" raw_aliases = result.get("action_act_aliases") action_aliases = ( [str(value).strip() for value in raw_aliases if str(value).strip()] @@ -978,7 +991,12 @@ def _apply_binding_task( 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) + reused_role = _same_pair_reuse_role( + source.result, + account, + customer_role_name=str(task.customer_role_name or ""), + task_status=str(source.status or ""), + ) if reused_role: return _mark_reused_pair( db, @@ -1370,6 +1388,87 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: return changed +def _revert_false_same_pair_reuse( + db: Session, + *, + limit: int = 500, +) -> int: + """纠偏被预检同对复用误锁为 bound 的未履约订单(未完成兑换且绑定角色 != 客户目标)。""" + rows = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.scope == "elite", + PlatformFulfillmentTask.account_id.isnot(None), + PlatformFulfillmentTask.bind_task_id.isnot(None), + PlatformFulfillmentTask.binding_status == "bound", + PlatformFulfillmentTask.execution_status.notin_( + ("completed", "cancelled") + ), + PlatformFulfillmentTask.exchange_status.notin_( + ("succeeded", "locked", "submitting") + ), + PlatformFulfillmentTask.customer_role_name != "", + ) + .order_by(PlatformFulfillmentTask.id.desc()) + .limit(max(1, min(limit, 1000))) + .all() + ) + reverted = 0 + for task in rows: + bind_task = db.get(DouyuTask, int(task.bind_task_id)) + if bind_task is None or str(bind_task.task_type or "") != "get_bind_qr": + continue + result = bind_task.result if isinstance(bind_task.result, dict) else {} + if bool(result.get("bind_confirmed")) or bool(result.get("manual_confirmed")): + continue + reuse_event = ( + db.query(PlatformFulfillmentEvent) + .filter( + PlatformFulfillmentEvent.task_id == int(task.id), + PlatformFulfillmentEvent.event_type == "binding_reused_existing_pair", + ) + .order_by(PlatformFulfillmentEvent.id.desc()) + .first() + ) + if reuse_event is None: + continue + reused_role = str( + (reuse_event.detail_json or {}).get("roleName") or "" + ).strip() + customer_role = str(task.customer_role_name or "").strip() + if not customer_role or ( + reused_role and role_names_match(reused_role, customer_role) + ): + continue + lease = _lease_for_task(db, task) + task.binding_status = "qr_pending" + task.execution_status = "waiting_bind" + task.issue_code = "" + task.last_error = "" + task.updated_at = _now() + _append_event( + db, + task.id, + "binding_false_reuse_reverted", + detail={ + "bindTaskId": int(bind_task.id), + "reusedRoleName": reused_role[:128], + "customerRoleName": customer_role[:128], + }, + ) + applied = _apply_binding_task( + db, + task, + bind_task, + owned=bind_task.platform_task_id is not None, + ) + if not applied: + _apply_task_lease_policy(db, task, lease=lease) + _emit_order_site_binding_state(db, task.id) + reverted += 1 + return reverted + + def reconcile_binding_observations( db: Session, *, @@ -1380,6 +1479,7 @@ def reconcile_binding_observations( 只处理订单自己的证据(``platform_task_id``)和兼容路径的旧待确认任务; 账号上的查询任务不再参与订单结算。 """ + reconciled = _revert_false_same_pair_reuse(db, limit=limit) tasks = ( db.query(PlatformFulfillmentTask) .filter( @@ -1401,7 +1501,6 @@ def reconcile_binding_observations( .limit(max(1, min(limit, 2000))) .all() ) - reconciled = 0 for task in tasks: if _frozen(task): continue diff --git a/web/backend/services/platform_fulfillment/binding_evidence.py b/web/backend/services/platform_fulfillment/binding_evidence.py index 8506280..de2e269 100644 --- a/web/backend/services/platform_fulfillment/binding_evidence.py +++ b/web/backend/services/platform_fulfillment/binding_evidence.py @@ -252,8 +252,21 @@ def build_binding_evidence( # scannedRole 必须和列表、客户页、提交确认共用同一个权威 pending 判定。 # actionPending/decision 只保留为诊断字段,不能绕过客户目标校验。 scanned_role = _text(pending_role) + customer_role = _text(task.customer_role_name) + same_pair_target_ok = ( + not customer_role + and not bool(result.get("expected_role_required")) + ) or ( + bool(customer_role) + and account_current_role.casefold() == customer_role.casefold() + ) if ( not scanned_role + and same_pair_target_ok + and ( + str(bind_task.status or "") == "success" + or bool(result.get("bind_poll_legacy_observed_change")) + ) and action_current is not None and account_current_role and legacy_role diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 1b676c5..1f21917 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -1401,6 +1401,7 @@ export default function PlatformFulfillmentPage() { render: (_, task) => { const customerRole = task.customerProfile?.roleName?.trim() || ''; const scannedRole = task.bindTask?.roleName?.trim() || ''; + const scannedChannel = [task.bindTask?.areaName, task.bindTask?.platName].filter(Boolean).join(' / '); return ( @@ -1416,9 +1417,10 @@ export default function PlatformFulfillmentPage() { type={scannedRole ? undefined : 'secondary'} style={{ fontSize: 12 }} ellipsis - title={scannedRole || '未识别'} + title={scannedRole ? (scannedChannel ? `${scannedRole} (${scannedChannel})` : scannedRole) : '未识别'} > 扫码绑定角色:{scannedRole || '未识别'} + {scannedRole && scannedChannel ? ` · ${scannedChannel}` : ''} {task.bindingStatus === 'bound' ? ( @@ -2191,7 +2193,7 @@ export default function PlatformFulfillmentPage() { rowKey="id" pagination={false} dataSource={detail.bindingLogs} - scroll={{ x: 980, y: 260 }} + scroll={{ x: 1180, y: 260 }} columns={[ { title: '时间', @@ -2200,18 +2202,29 @@ export default function PlatformFulfillmentPage() { render: (value: string) => formatTime(value), }, { title: '阶段', dataIndex: 'stage', width: 170 }, - { title: '通道', dataIndex: 'actAlias', width: 140 }, - { title: '角色', dataIndex: 'roleName', width: 120 }, + { title: '通道', dataIndex: 'actAlias', width: 135 }, + { title: '角色', dataIndex: 'roleName', width: 120, render: (v: string) => v || '-' }, { - title: 'bindAct', - dataIndex: 'bindAct', - width: 76, - render: (value: boolean) => (value ? '1' : '0'), + title: '区服平台', + key: 'channel', + width: 145, + render: (_: unknown, row: PlatformFulfillmentBindingLog) => + [row.areaName, row.platName].filter(Boolean).join(' / ') || '-', + }, + { + title: '标志 (act/role/needAct/needRole)', + key: 'flags', + width: 185, + render: (_: unknown, row: PlatformFulfillmentBindingLog) => ( + + {`${row.bindAct ? 1 : 0}/${row.bindRole ? 1 : 0}/${row.needBindAct ? 1 : 0}/${row.needBindRole ? 1 : 0}`} + + ), }, { title: '换绑等待', dataIndex: 'changeRoleWaitTime', - width: 96, + width: 90, render: (value: number | null) => value ?? '-', }, { diff --git a/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx b/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx index ff6a4db..aa982cd 100644 --- a/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx +++ b/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx @@ -1837,18 +1837,22 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) const pendingBinding = !isEsportsHandbook && queryTask?.binding?.status === 'pending' ? queryTask.binding : null; - const pendingRoleName = scopeState === 'bound' - ? '' - : (isEsportsHandbook - ? resultText(queryResult, 'pending_role_name') - : pendingBinding?.pending_role_name || ''); - const pendingChannel = scopeState === 'bound' - ? '' - : (isEsportsHandbook + const rawPendingRoleName = isEsportsHandbook + ? (scopeState === 'bound' ? '' : resultText(queryResult, 'pending_role_name')) + : (pendingBinding?.pending_role_name || ''); + const pendingRoleName = ( + rawPendingRoleName + && (scopeState !== 'bound' || rawPendingRoleName.toLowerCase() !== roleName.toLowerCase()) + ) + ? rawPendingRoleName + : ''; + const pendingChannel = pendingRoleName + ? (isEsportsHandbook ? [resultText(queryResult, 'pending_area_name'), resultText(queryResult, 'pending_plat_name')] .filter(Boolean) .join(' / ') - : pendingBinding?.pending_channel || ''); + : pendingBinding?.pending_channel || '') + : ''; if (!roleName && !pendingRoleName) { return (