diff --git a/tests/test_douyu_binding_state.py b/tests/test_douyu_binding_state.py index 14108dc..443a54f 100644 --- a/tests/test_douyu_binding_state.py +++ b/tests/test_douyu_binding_state.py @@ -12,11 +12,42 @@ from web.backend.services.account_binding import ( BIND_UNBOUND, binding_snapshot, derive_from_bind_info, + is_pending_binding_role, is_role_change_cooling, role_change_available_at, ) +from web.backend.services.douyu_runner_bind import BindMixin ACT_ALIAS = "20260120QYOOB" +LEGACY_ALIAS = "cjm" +ROLE_CONFIG = { + "legacy_act_alias": LEGACY_ALIAS, + "confirm_act_alias": ACT_ALIAS, + "bind_act_alias": ACT_ALIAS, +} + + +class _RolePicker(BindMixin): + pass + + +def _role_candidate( + alias: str, + role_name: str, + *, + bound_act: bool = False, +) -> dict[str, Any]: + return { + "act_alias": alias, + "role_name": role_name, + "area_name": "微信", + "plat_name": "安卓(android)", + "is_bound_account": True, + "is_bound_role": True, + "is_bound_act": bound_act, + "need_bind_act": True, + "need_bind_role": True, + } def _payload( @@ -118,6 +149,92 @@ def test_scanned_role_is_pending_until_act_bind(): assert snapshot["game_channel"] == "微信 / 苹果(iOS)" +def test_existing_pending_role_is_baseline_not_new_scan_result(): + old_role = "狗鼻子弗尼亚bd" + candidates = [ + _role_candidate(LEGACY_ALIAS, old_role), + _role_candidate(ACT_ALIAS, old_role), + ] + picker = _RolePicker() + + baseline = picker._pick_baseline_bind_info(candidates, ROLE_CONFIG) + + assert baseline is not None + assert baseline["act_alias"] == ACT_ALIAS + assert baseline["role_name"] == old_role + assert not is_pending_binding_role( + candidates[0], + baseline_role_name=old_role, + baseline_is_bound_act=False, + ) + assert not is_pending_binding_role( + candidates[1], + baseline_role_name=old_role, + baseline_is_bound_act=False, + ) + + +def test_new_role_wins_when_cjm_and_activity_snapshots_differ(): + old_role = "狗鼻子弗尼亚bd" + new_role = "我是火星人2222" + candidates = [ + _role_candidate(LEGACY_ALIAS, old_role), + _role_candidate(ACT_ALIAS, new_role), + ] + picker = _RolePicker() + + selected = picker._pick_bind_info( + candidates, + baseline_role_name=old_role, + baseline_is_bound_act=False, + prefer_pending=True, + prefer_aliases=[LEGACY_ALIAS, ACT_ALIAS], + ) + target = picker._pick_target_role_info(candidates, ROLE_CONFIG) + + assert selected is not None + assert selected["act_alias"] == ACT_ALIAS + assert selected["role_name"] == new_role + assert target is not None + assert target["role_name"] == new_role + + +def test_changed_cjm_role_wins_over_old_bound_activity_role(): + old_role = "狗鼻子弗尼亚bd" + new_role = "我是火星人2222" + candidates = [ + _role_candidate(LEGACY_ALIAS, new_role), + _role_candidate(ACT_ALIAS, old_role, bound_act=True), + ] + picker = _RolePicker() + + target = picker._pick_target_role_info(candidates, ROLE_CONFIG) + + assert target is not None + assert target["act_alias"] == LEGACY_ALIAS + assert target["role_name"] == new_role + + +def test_expected_role_never_falls_back_to_old_activity_role(): + old_role = "狗鼻子弗尼亚bd" + new_role = "我是火星人2222" + candidates = [ + _role_candidate(LEGACY_ALIAS, new_role), + _role_candidate(ACT_ALIAS, old_role), + ] + picker = _RolePicker() + + selected = picker._pick_role_info_for_aliases( + candidates, + [ACT_ALIAS, LEGACY_ALIAS], + required_role_name=new_role, + ) + + assert selected is not None + assert selected["act_alias"] == LEGACY_ALIAS + assert selected["role_name"] == new_role + + def test_act_bind_is_the_single_final_bound_signal(): can_change_time = 1_795_449_600 parsed = _parse( diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 8fb8187..bee3382 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -16,7 +16,9 @@ from web.backend.models import ( AutomationJob, DouyuGoodsSnapshot, DouyuTask, + IntegrationOutbox, PlatformCommodityMapping, + PlatformFulfillmentEvent, PlatformFulfillmentTask, User, ) @@ -464,6 +466,192 @@ class TestBindingAndCompletion(_Base): assert task.issue_code == "" assert task.last_error == "" + def test_confirm_binding_pins_expected_role_for_two_role_snapshot( + self, monkeypatch + ): + task = self._allocated() + bind_task = DouyuTask( + batch_id="bind-two-roles", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="success", + message="已识别待确认角色", + result={ + "role_name": "我是火星人2222", + "current_role_name": "狗鼻子弗尼亚bd", + "bind_ready_for_confirm": True, + "bind_confirmed": False, + }, + created_by=self.admin_id, + ) + self.session.add(bind_task) + self.session.flush() + task.bind_task_id = bind_task.id + task.binding_status = "role_ready" + task.execution_status = "role_ready" + self.session.commit() + monkeypatch.setattr(service, "start_douyu_batch", lambda **_kwargs: None) + + asyncio.run( + service.confirm_binding( + self.session, + task_id=task.id, + current=self.admin, + ) + ) + + confirm_task = ( + self.session.query(DouyuTask) + .filter(DouyuTask.task_type == "confirm_bind") + .order_by(DouyuTask.id.desc()) + .first() + ) + assert confirm_task is not None + assert confirm_task.result["expected_role_name"] == "我是火星人2222" + assert confirm_task.result["baseline_role_name"] == "狗鼻子弗尼亚bd" + + def test_reset_binding_clears_failed_state_and_keeps_account(self): + task = self._allocated() + bind_task = DouyuTask( + batch_id="bind-reset", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="failed", + message="该游戏角色仍在换绑冷却期", + result={"bind_phase": "confirm_failed"}, + created_by=self.admin_id, + ) + self.session.add(bind_task) + self.session.flush() + task.bind_task_id = bind_task.id + task.binding_status = "failed" + task.execution_status = "manual_required" + task.exchange_status = "not_started" + task.issue_code = "customer_role_cooldown" + task.last_error = "该游戏角色仍在换绑冷却期" + self.session.commit() + account_id = task.account_id + lease_id = task.lease_id + + detail = service.reset_task_binding( + self.session, + task_id=task.id, + current=self.admin, + reason="客服核对后重置角色资料", + ) + + self.session.refresh(task) + assert detail["task"]["executionStatus"] == "allocated" + assert task.account_id == account_id + assert task.lease_id == lease_id + assert task.bind_task_id is None + assert task.binding_status == "not_started" + assert task.issue_code == "" + assert task.last_error == "" + event = ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="binding_reset") + .one() + ) + assert event.detail_json["customerProfileReset"] is True + outbox = ( + self.session.query(IntegrationOutbox) + .order_by(IntegrationOutbox.id.desc()) + .first() + ) + assert outbox is not None + assert outbox.payload_json["items"][0]["customerProfileReset"] is True + + def test_reset_binding_rejects_running_bind_task(self): + task = self._allocated() + bind_task = DouyuTask( + batch_id="bind-running", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="running", + message="等待客户扫码", + result={"url": "https://example.com/qr"}, + created_by=self.admin_id, + ) + self.session.add(bind_task) + self.session.flush() + task.bind_task_id = bind_task.id + task.binding_status = "failed" + task.execution_status = "waiting_bind" + self.session.commit() + + with pytest.raises(HTTPException) as exc_info: + service.reset_task_binding( + self.session, + task_id=task.id, + current=self.admin, + ) + + assert exc_info.value.status_code == 409 + assert "仍在执行" in str(exc_info.value.detail) + + def test_cancel_releases_account_and_terminal_state_cannot_be_refreshed_back( + self, monkeypatch + ): + task = self._allocated() + bind_task = DouyuTask( + batch_id="bind-cancel", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="running", + message="等待客户扫码", + result={"url": "https://example.com/qr"}, + created_by=self.admin_id, + ) + self.session.add(bind_task) + self.session.flush() + task.bind_task_id = bind_task.id + task.binding_status = "qr_pending" + task.execution_status = "waiting_bind" + self.session.commit() + account_id = task.account_id + lease_id = task.lease_id + stopped: list[str] = [] + monkeypatch.setattr( + service, + "stop_douyu_batches", + lambda batch_ids: stopped.extend(batch_ids) or len(batch_ids), + ) + + detail = service.cancel_task( + self.session, + task_id=task.id, + current=self.admin, + reason="运营取消并释放账号", + ) + + self.session.refresh(task) + self.session.refresh(bind_task) + lease = self.session.query(AccountLease).filter_by(id=lease_id).one() + assert detail["task"]["executionStatus"] == "cancelled" + assert task.account_id is None + assert task.lease_id is None + assert task.bind_task_id is None + assert task.binding_status == "not_started" + assert task.exchange_status == "not_started" + assert account_id is not None + assert lease.status == "released" + assert bind_task.status == "stopped" + assert stopped == ["bind-cancel"] + + refreshed = service.refresh_binding(self.session, task_id=task.id) + assert refreshed["task"]["executionStatus"] == "cancelled" + self.session.refresh(task) + assert task.execution_status == "cancelled" + def test_refresh_binding_maps_role_ready(self, monkeypatch): notified: list[int] = [] monkeypatch.setattr( @@ -556,6 +744,11 @@ class TestBindingAndCompletion(_Base): assert detail["task"]["executionStatus"] == "manual_required" assert "截图" in detail["task"]["lastError"] assert "联系客服" in detail["task"]["lastError"] + live = service.customer_binding_out(self.session, task.id) + assert live["bindingStatus"] == "failed" + assert live["executionStatus"] == "manual_required" + assert live["bindReadyForConfirm"] is False + assert live["bindConfirmed"] is False def test_refresh_binding_classifies_account_role_cooldown(self): task = self._allocated() @@ -585,6 +778,8 @@ class TestBindingAndCompletion(_Base): assert detail["task"]["issueCode"] == "account_role_cooldown" assert detail["task"]["executionStatus"] == "manual_required" assert "截图" in detail["task"]["lastError"] + live = service.customer_binding_out(self.session, task.id) + assert live["bindReadyForConfirm"] is False def test_list_hides_qr_but_detail_returns_it(self): task = self._allocated() diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index 16755e8..5175930 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -183,6 +183,30 @@ def refresh_binding( return service.refresh_binding(db, task_id=task_id) +@router.post("/tasks/{task_id}/bind/reset") +def reset_binding( + task_id: int, + req: PlatformFulfillmentReasonRequest, + db: Session = Depends(get_db), + current: User = Depends(require_permission("platform_fulfillment:use")), +) -> dict[str, Any]: + result = service.reset_task_binding( + db, + task_id=task_id, + current=current, + reason=req.reason, + ) + record_audit( + db, + current, + action="platform_fulfillment:binding:reset", + target=f"platform_fulfillment_task:{task_id}", + detail={"reason": req.reason}, + ) + db.commit() + return result + + @router.post("/tasks/{task_id}/bind/confirm") async def confirm_binding( task_id: int, diff --git a/web/backend/services/douyu_batch_launcher.py b/web/backend/services/douyu_batch_launcher.py index 67476f8..da6a52e 100644 --- a/web/backend/services/douyu_batch_launcher.py +++ b/web/backend/services/douyu_batch_launcher.py @@ -37,4 +37,16 @@ def start_douyu_batch( threading.Thread(target=runner.run, daemon=True).start() -__all__ = ["start_douyu_batch"] +def stop_douyu_batches(batch_ids: list[str]) -> int: + """向仍在运行的批次发送停止信号,返回实际命中的批次数。""" + stopped = 0 + for batch_id in dict.fromkeys(value for value in batch_ids if value): + batch = douyu_batch_registry.get(batch_id) + if not batch or batch.get("finished"): + continue + batch["runner"].stop() + stopped += 1 + return stopped + + +__all__ = ["start_douyu_batch", "stop_douyu_batches"] diff --git a/web/backend/services/douyu_runner_bind.py b/web/backend/services/douyu_runner_bind.py index 29fe0a2..c7e777f 100644 --- a/web/backend/services/douyu_runner_bind.py +++ b/web/backend/services/douyu_runner_bind.py @@ -267,6 +267,78 @@ class BindMixin: results.append(info) return results + def _role_alias_priority(self, config: dict, primary_alias: str = "") -> list[str]: + """角色来源优先级:当前动作 alias > cjm/legacy 最新态。""" + ordered = [ + primary_alias, + str(config.get("confirm_act_alias") or "").strip(), + str(config.get("bind_act_alias") or "").strip(), + str(config.get("legacy_act_alias") or "").strip(), + ] + aliases: list[str] = [] + for alias in ordered: + if alias and alias not in aliases: + aliases.append(alias) + return aliases + + def _pick_role_info_for_aliases( + self, + candidates: list[dict], + aliases: list[str], + *, + pending_only: bool = False, + exclude_role_name: str = "", + required_role_name: str = "", + ) -> dict | None: + """按 alias 优先级取角色;可排除指定旧角色,只找发生变化的角色。""" + excluded = exclude_role_name.strip().casefold() + required = required_role_name.strip().casefold() + for alias in aliases: + for info in candidates: + if str(info.get("act_alias") or "") != alias: + continue + role_name = str(info.get("role_name") or "").strip() + if not role_name: + continue + if pending_only and self._is_bound_act(info): + continue + if excluded and role_name.casefold() == excluded: + continue + if required and role_name.casefold() != required: + continue + return info + return None + + def _pick_target_role_info( + self, + candidates: list[dict], + config: dict, + *, + primary_alias: str = "", + ) -> dict | None: + """选本次操作要确认的角色,优先使用活动 alias 上的新待确认角色。""" + if not candidates: + return None + bound = self._pick_current_bound_info( + candidates, + config, + extra_prefer_aliases=[primary_alias] if primary_alias else None, + ) + aliases = self._role_alias_priority(config, primary_alias) + if bound is not None: + changed_pending = self._pick_role_info_for_aliases( + candidates, + aliases, + pending_only=True, + exclude_role_name=str(bound.get("role_name") or ""), + ) + return changed_pending or bound + return self._pick_role_info_for_aliases( + candidates, + aliases, + pending_only=True, + ) or self._pick_role_info_for_aliases(candidates, aliases) + def _pick_bind_info( self, candidates: list[dict], @@ -345,15 +417,21 @@ class BindMixin: candidates: list[dict], config: dict, ) -> dict | None: - """选“扫码前当前已绑定角色”作为 baseline。 + """选“扫码前当前角色”作为 baseline。 - 活动 alias(20260120QYOOB)只反映当前已绑定; - cjm 才是换绑最新态。baseline 应优先活动 alias 的已绑定结果, - 避免把 cjm 上的待确认新角色误当成扫码前旧角色。 + 活动 alias(20260120QYOOB)上的已绑定或已选待确认角色都可能是 + 上一次残留。baseline 必须覆盖这两种状态,否则旧角色会被误判成 + 本次扫码产生的新角色。 """ if not candidates: return None - return self._pick_current_bound_info(candidates, config) + current_bound = self._pick_current_bound_info(candidates, config) + if current_bound is not None: + return current_bound + return self._pick_role_info_for_aliases( + candidates, + self._role_alias_priority(config), + ) def _wait_bind_role_result( self, @@ -694,28 +772,59 @@ class BindMixin: db, task, "failed", "查询绑定信息失败,请检查 Cookie 或 actAlias" ) return - before = ( - self._pick_bind_info( - before_candidates, - baseline_role_name="", - baseline_is_bound_act=False, - prefer_pending=True, - prefer_aliases=query_aliases, - ) - or before_candidates[0] - ) - before_snapshot = self._bind_snapshot(before) - role_name = before_snapshot["role_name"] - query_alias = str(before.get("act_alias") or "") # 确认前“已生效绑定”角色(bound_act=1),确认失败/回查失败时写库用,避免待确认角色污染 game_name before_bound = self._pick_current_bound_info( before_candidates, config, extra_prefer_aliases=[confirm_alias], ) + expected_role_name = str( + (task.result or {}).get("expected_role_name") or "" + ).strip() + if expected_role_name: + before = self._pick_role_info_for_aliases( + before_candidates, + self._role_alias_priority(config, confirm_alias), + required_role_name=expected_role_name, + ) + else: + before = self._pick_target_role_info( + before_candidates, + config, + primary_alias=confirm_alias, + ) + before = before or before_bound or before_candidates[0] + before_snapshot = self._bind_snapshot(before) + role_name = before_snapshot["role_name"] + query_alias = str(before.get("act_alias") or "") + if expected_role_name and role_name.casefold() != expected_role_name.casefold(): + self._mark_task( + db, + task, + "failed", + f"待确认角色已变化,未找到: {expected_role_name}", + { + "act_alias": confirm_alias, + "query_act_aliases": query_aliases, + "expected_role_name": expected_role_name, + "bind_ready_for_confirm": False, + "bind_confirmed": False, + "bind_phase": "confirm_failed", + "bind_candidates": [ + { + "act_alias": item.get("act_alias"), + "role_name": item.get("role_name"), + "is_bound_act": self._is_bound_act(item), + } + for item in before_candidates + ], + }, + ) + return self._push_log( "info", f"确认前状态 confirm_act={confirm_alias or '-'} hit={query_alias or '-'} " + f"expected={expected_role_name or '-'} " f"{self._format_bind_summary(before)}", ) if not role_name: @@ -1131,10 +1240,14 @@ class BindMixin: bound_info = self._pick_current_bound_info(candidates, config) # 2) 待确认角色(cjm 扫码后未确认;无已绑定时也用于首次绑定展示) pending_info = ( - self._pick_bind_info( + self._pick_role_info_for_aliases( candidates, - prefer_pending=True, - prefer_aliases=query_aliases, + self._role_alias_priority(config), + pending_only=True, + ) + or self._pick_role_info_for_aliases( + candidates, + self._role_alias_priority(config), ) or candidates[0] ) diff --git a/web/backend/services/platform_fulfillment/order_site_notifier.py b/web/backend/services/platform_fulfillment/order_site_notifier.py index 71e55e9..5ae2cef 100644 --- a/web/backend/services/platform_fulfillment/order_site_notifier.py +++ b/web/backend/services/platform_fulfillment/order_site_notifier.py @@ -29,6 +29,7 @@ def _state_dedupe_key(payload: dict[str, Any]) -> str: "platName": payload.get("platName"), "bindReadyForConfirm": payload.get("bindReadyForConfirm"), "bindConfirmed": payload.get("bindConfirmed"), + "customerProfileReset": payload.get("customerProfileReset"), } digest = hashlib.sha256( json.dumps(state, ensure_ascii=False, sort_keys=True).encode("utf-8") diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index db8d669..f6a31db 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -26,7 +26,7 @@ from ...models import ( ) from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state from ..douyu_activity_query import activity_client, query_exchange_eligibility -from ..douyu_batch_launcher import start_douyu_batch +from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches from ..douyu_service import douyu_config_value, ensure_douyu_config from ..external_order_source import ( OrderLookupUnavailable, @@ -228,11 +228,19 @@ def _append_event( ) -def _emit_order_site_binding_state(db: Session, task_id: int) -> bool: +def _emit_order_site_binding_state( + db: Session, + task_id: int, + *, + extra: dict[str, Any] | None = None, +) -> bool: """当前事务内写 Outbox;HTTP 投递由独立 worker 完成。""" + payload = customer_binding_out(db, task_id) + if extra: + payload.update(extra) return enqueue_order_site_binding_state( db, - customer_binding_out(db, task_id), + payload, ) @@ -573,7 +581,11 @@ def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str: message = str(bind_task.message or "") if phase == "change_waiting" or "暂不能换绑" in message: task_issue = "account_role_cooldown" - elif phase == "confirm_failed" or "待绑定游戏账号" in message or "未到换绑时间" in message: + elif ( + phase == "confirm_failed" + or "待绑定游戏账号" in message + or "未到换绑时间" in message + ): task_issue = "customer_role_cooldown" else: return "binding_failed" @@ -599,6 +611,8 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]: else None ) lease_ready = bool(task.account_id and lease and lease.status == "active") + binding_failed = task.binding_status == "failed" + binding_confirmed = task.binding_status == "bound" return { "sessionId": task.id, "platformOrderId": task.platform_order_id, @@ -622,8 +636,10 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]: ), "areaName": str(bind_result.get("area_name") or ""), "platName": str(bind_result.get("plat_name") or ""), - "bindReadyForConfirm": bool(bind_result.get("bind_ready_for_confirm")), - "bindConfirmed": bool(bind_result.get("bind_confirmed")), + "bindReadyForConfirm": ( + bool(bind_result.get("bind_ready_for_confirm")) and not binding_failed + ), + "bindConfirmed": bool(bind_result.get("bind_confirmed")) and binding_confirmed, "completedAt": _jsonable(task.completed_at), "updatedAt": _jsonable(task.updated_at), } @@ -1015,6 +1031,80 @@ def release_task_account( return get_task_detail(db, task.id) +def reset_task_binding( + db: Session, + *, + task_id: int, + current: User, + reason: str = "客服重置角色绑定", +) -> dict[str, Any]: + """清空本单旧绑定与客户资料,保留账号租约供客户重新扫码。""" + task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + raise HTTPException(status_code=409, detail="已结束任务不能重置绑定") + if task.binding_status != "failed": + raise HTTPException( + status_code=409, detail="只有绑定失败的任务可以重置角色资料" + ) + if not task.account_id or not task.lease_id: + raise HTTPException(status_code=409, detail="当前任务没有可保留的履约账号") + + lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if lease is None or lease.status != "active": + raise HTTPException( + status_code=409, detail="账号租约已失效,请释放账号后重新选号" + ) + + previous_bind_task_id = task.bind_task_id + previous_bind_task = ( + db.query(DouyuTask).filter(DouyuTask.id == previous_bind_task_id).first() + if previous_bind_task_id + else None + ) + if previous_bind_task and previous_bind_task.status in { + "planned", + "pending", + "running", + }: + raise HTTPException(status_code=409, detail="当前绑定任务仍在执行,不能重置") + + previous_binding_status = task.binding_status + previous_issue_code = task.issue_code + task.bind_task_id = None + task.binding_status = "not_started" + task.execution_status = "allocated" + task.exchange_status = "not_started" + task.issue_code = "" + task.last_error = "" + task.operator_id = current.id + task.updated_at = _now() + renew_lease(db, lease, ttl_minutes=_lease_duration_minutes(db)) + _append_event( + db, + task.id, + "binding_reset", + actor_type="user", + actor_id=current.id, + detail={ + "reason": reason.strip()[:1000], + "previousBindTaskId": previous_bind_task_id, + "previousBindingStatus": previous_binding_status, + "previousIssueCode": previous_issue_code, + "customerProfileReset": True, + }, + ) + _emit_order_site_binding_state( + db, + task.id, + extra={ + "customerProfileReset": True, + "resetReason": reason.strip()[:1000], + }, + ) + db.commit() + return get_task_detail(db, task.id) + + async def start_binding( db: Session, *, @@ -1095,6 +1185,8 @@ async def start_binding( def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + return get_task_detail(db, task.id) if not task.bind_task_id: return get_task_detail(db, task.id) bind_task = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() @@ -1137,10 +1229,7 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: ) if after != before: task.updated_at = _now() - if task.issue_code in { - "account_role_cooldown", - "customer_role_cooldown", - }: + if task.binding_status == "failed": _append_event( db, task.id, @@ -1208,6 +1297,14 @@ async def confirm_binding( if lease is None or lease.status != "active": raise HTTPException(status_code=409, detail="账号租约已失效") + current_bind_task = ( + db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + if task.bind_task_id + else None + ) + current_bind_result = (current_bind_task.result or {}) if current_bind_task else {} + expected_role_name = str(current_bind_result.get("role_name") or "").strip() + baseline_role_name = str(current_bind_result.get("current_role_name") or "").strip() batch_id = f"pfconfirm-{task.id}-{uuid.uuid4().hex[:8]}" confirm_task = DouyuTask( batch_id=batch_id, @@ -1217,7 +1314,11 @@ async def confirm_binding( handbook_scope="elite", status="planned", message="等待确认角色绑定", - result={"payload": {}}, + result={ + "payload": {}, + "expected_role_name": expected_role_name, + "baseline_role_name": baseline_role_name, + }, created_by=current.id, ) db.add(confirm_task) @@ -1399,13 +1500,45 @@ def cancel_task( reason: str, ) -> dict[str, Any]: task = _load_task(db, task_id) + if task.execution_status == "cancelled": + return get_task_detail(db, task.id) + if task.execution_status == "completed": + raise HTTPException(status_code=409, detail="已完成任务不能取消") + account_id = task.account_id + lease_id = task.lease_id lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) + linked_tasks = ( + db.query(DouyuTask) + .filter( + DouyuTask.id.in_( + [value for value in [task.bind_task_id, task.exchange_task_id] if value] + ) + ) + .all() + if task.bind_task_id or task.exchange_task_id + else [] + ) + stopped_batches = stop_douyu_batches( + [str(linked_task.batch_id or "") for linked_task in linked_tasks] + ) + for linked_task in linked_tasks: + if linked_task.status in {"planned", "pending", "running"}: + linked_task.status = "stopped" + linked_task.message = "履约任务已取消" + linked_task.finished_at = _now() release_lease(db, lease, reason="platform_fulfillment_cancelled") + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.exchange_task_id = None + task.binding_status = "not_started" task.execution_status = "cancelled" + task.exchange_status = "not_started" + task.issue_code = "" task.operator_id = current.id task.last_error = reason.strip()[:2000] task.updated_at = _now() @@ -1415,7 +1548,12 @@ def cancel_task( "task_cancelled", actor_type="user", actor_id=current.id, - detail={"reason": task.last_error}, + detail={ + "reason": task.last_error, + "releasedAccountId": account_id, + "releasedLeaseId": lease_id, + "stoppedBatches": stopped_batches, + }, ) _emit_order_site_binding_state(db, task.id) db.commit() @@ -1436,6 +1574,7 @@ __all__ = [ "refresh_binding", "refresh_exchange_eligibility", "release_task_account", + "reset_task_binding", "start_binding", "sync_pending_tasks", "sync_pending_tasks_if_due", diff --git a/web/frontend/src/api/platformFulfillment.ts b/web/frontend/src/api/platformFulfillment.ts index abe6202..76bfa96 100644 --- a/web/frontend/src/api/platformFulfillment.ts +++ b/web/frontend/src/api/platformFulfillment.ts @@ -64,6 +64,11 @@ export const platformFulfillmentApi = { api.post( `/platform-fulfillment/tasks/${taskId}/bind/refresh`, ), + resetBinding: (taskId: number, reason = '客服重置角色绑定') => + api.post( + `/platform-fulfillment/tasks/${taskId}/bind/reset`, + { reason }, + ), confirmBinding: (taskId: number) => api.post( `/platform-fulfillment/tasks/${taskId}/bind/confirm`, diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 5d47e61..d7a4f04 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useState } from 'react'; import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd'; -import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons'; +import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons'; import type { ColumnsType } from 'antd/es/table'; import { douyuApi, platformFulfillmentApi } from '../api/modules'; import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules'; @@ -76,6 +76,7 @@ const EVENT_LABELS: Record = { binding_started: '开始绑定游戏角色', binding_confirm_started: '提交角色绑定确认', binding_failed: '游戏角色绑定失败', + binding_reset: '重置角色资料和绑定记录', eligibility_check_failed: '兑换资格查询失败', exchange_eligibility_checked: '刷新兑换资格', manual_exchange_completed: '人工兑换完成', @@ -211,6 +212,9 @@ function eventDescription(event: { eventType: string; detail: Record { + Modal.confirm({ + title: '重置角色资料和绑定记录?', + content: + '将清空本订单已填写的游戏角色、旧二维码和绑定失败状态,保留当前账号与租约。客户需要重新打开领取链接并填写角色资料。平台换绑冷却不会被绕过。', + okText: '确认重置', + okButtonProps: { danger: true }, + cancelText: '取消', + onOk: () => + runTaskAction(() => + platformFulfillmentApi.resetBinding(task.id, '客服重置角色资料和绑定记录'), + ), + }); + }; + + const cancelTask = (task: PlatformFulfillmentTask) => { + Modal.confirm({ + title: '确认取消履约任务?', + content: + '取消后会立即停止当前绑定或兑换任务,释放已占用的斗鱼账号,并通知订单侧更新为已取消。该操作不可撤销。', + okText: '确认取消并释放账号', + okButtonProps: { danger: true }, + cancelText: '返回', + onOk: () => + runTaskAction(() => + platformFulfillmentApi.cancel(task.id, '运营取消并释放账号'), + ), + }); + }; + const runDouyuAccountAction = async (taskType: string) => { if (!selected?.account) { message.warning('当前履约任务还没有分配斗鱼账号'); @@ -643,6 +684,16 @@ export default function PlatformFulfillmentPage() { 确认绑定 ) : null} + {canResetBinding(task) ? ( + + ) : null} {task.executionStatus === 'bound' ? ( <> ) : null} {selected.account ? : null} + {canResetBinding(selected) ? ( + + ) : null} {selected.executionStatus !== 'completed' && selected.executionStatus !== 'cancelled' ? ( - ) : null}