fix(douyu): unify binding state and scheduler health
This commit is contained in:
@@ -537,7 +537,15 @@ class TestAutomationApi(_Base):
|
||||
|
||||
return api
|
||||
|
||||
def test_list_jobs_exposes_scheduler_and_job_state(self):
|
||||
def test_list_jobs_exposes_scheduler_and_job_state(
|
||||
self,
|
||||
monkeypatch,
|
||||
tmp_path,
|
||||
):
|
||||
monkeypatch.setenv(
|
||||
"BACKGROUND_RUNTIME_HEARTBEAT_PATH",
|
||||
str(tmp_path / "background_runtime.json"),
|
||||
)
|
||||
api = self._api()
|
||||
payload = api.list_jobs(db=self.session, current=self.admin)
|
||||
# 心跳(轮询间隔)与作业周期是两个概念,接口都要暴露出来:
|
||||
@@ -557,6 +565,41 @@ class TestAutomationApi(_Base):
|
||||
assert job["batch_size"] == 200
|
||||
assert job["latest_run"] is None
|
||||
|
||||
def test_list_jobs_uses_background_process_scheduler_heartbeat(
|
||||
self,
|
||||
monkeypatch,
|
||||
):
|
||||
api = self._api()
|
||||
monkeypatch.setattr(
|
||||
api,
|
||||
"scheduler_status",
|
||||
lambda: {
|
||||
"enabled": True,
|
||||
"running": False,
|
||||
"tick_seconds": 5,
|
||||
"job_interval_seconds": 300,
|
||||
"registered": [],
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"web.backend.background_runtime.background_runtime_status",
|
||||
lambda: {
|
||||
"running": True,
|
||||
"heartbeatAt": "2026-11-23T12:00:00+00:00",
|
||||
"ageSeconds": 3.0,
|
||||
"staleAfterSeconds": 30,
|
||||
"pid": 123,
|
||||
"scheduler": {"enabled": True, "running": True},
|
||||
},
|
||||
)
|
||||
|
||||
payload = api.list_jobs(db=self.session, current=self.admin)
|
||||
|
||||
assert payload["scheduler"]["running"] is True
|
||||
assert payload["scheduler"]["process"] == "background"
|
||||
assert payload["scheduler"]["pid"] == 123
|
||||
assert payload["runtime"]["background_runtime"]["ageSeconds"] == 3.0
|
||||
|
||||
def test_update_job_persists_and_schedules_next_run(self):
|
||||
api = self._api()
|
||||
api.update_job(
|
||||
|
||||
@@ -2,11 +2,16 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from web.backend import background_runtime
|
||||
|
||||
|
||||
def test_background_services_start_and_stop_once(monkeypatch):
|
||||
def test_background_services_start_and_stop_once(monkeypatch, tmp_path):
|
||||
calls: list[str] = []
|
||||
heartbeat_path = tmp_path / "background_runtime.json"
|
||||
monkeypatch.setenv("BACKGROUND_RUNTIME_HEARTBEAT_PATH", str(heartbeat_path))
|
||||
|
||||
def mark(name: str):
|
||||
return lambda *_args, **_kwargs: calls.append(name) or True
|
||||
@@ -84,6 +89,7 @@ def test_background_services_start_and_stop_once(monkeypatch):
|
||||
assert background_runtime.start_background_services() is False
|
||||
background_runtime.stop_background_services()
|
||||
background_runtime.stop_background_services()
|
||||
assert not heartbeat_path.exists()
|
||||
|
||||
assert calls == [
|
||||
"execution",
|
||||
@@ -104,9 +110,13 @@ def test_background_services_start_and_stop_once(monkeypatch):
|
||||
]
|
||||
|
||||
|
||||
def test_execution_only_worker_can_disable_control_plane(monkeypatch):
|
||||
def test_execution_only_worker_can_disable_control_plane(monkeypatch, tmp_path):
|
||||
calls: list[str] = []
|
||||
monkeypatch.setenv("BACKGROUND_CONTROL_PLANE_ENABLED", "false")
|
||||
monkeypatch.setenv(
|
||||
"BACKGROUND_RUNTIME_HEARTBEAT_PATH",
|
||||
str(tmp_path / "background_runtime.json"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.execution_worker.start_execution_job_worker",
|
||||
lambda: calls.append("start") or True,
|
||||
@@ -124,3 +134,30 @@ def test_execution_only_worker_can_disable_control_plane(monkeypatch):
|
||||
background_runtime.stop_background_services()
|
||||
|
||||
assert calls == ["start", "stop"]
|
||||
|
||||
|
||||
def test_background_runtime_heartbeat_reports_scheduler_process(
|
||||
monkeypatch,
|
||||
tmp_path,
|
||||
):
|
||||
heartbeat_path = tmp_path / "background_runtime.json"
|
||||
monkeypatch.setenv("BACKGROUND_RUNTIME_HEARTBEAT_PATH", str(heartbeat_path))
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.automation.scheduler.scheduler_status",
|
||||
lambda: {
|
||||
"enabled": True,
|
||||
"running": True,
|
||||
"tick_seconds": 5,
|
||||
"job_interval_seconds": 300,
|
||||
"registered": ["ck_relogin"],
|
||||
},
|
||||
)
|
||||
|
||||
background_runtime._write_runtime_heartbeat()
|
||||
status = background_runtime.background_runtime_status()
|
||||
payload = json.loads(Path(heartbeat_path).read_text(encoding="utf-8"))
|
||||
|
||||
assert status["running"] is True
|
||||
assert status["pid"] == payload["pid"]
|
||||
assert status["scheduler"]["running"] is True
|
||||
assert status["ageSeconds"] is not None
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import Any
|
||||
import pytest
|
||||
|
||||
from core.douyu import DouyuActivityClient, DouyuActivityError
|
||||
from web.backend.models import Account
|
||||
from web.backend.models import Account, DouyuTask
|
||||
from web.backend.services.account_binding import (
|
||||
BIND_BOUND,
|
||||
BIND_PENDING,
|
||||
@@ -24,6 +24,13 @@ from web.backend.services.account_binding import (
|
||||
pending_binding_role_from_result,
|
||||
role_change_available_at,
|
||||
)
|
||||
from web.backend.services.douyu_binding import (
|
||||
BINDING_VIEW_CONFIRMED,
|
||||
BINDING_VIEW_FAILED,
|
||||
BINDING_VIEW_NONE,
|
||||
BINDING_VIEW_PENDING,
|
||||
resolve_douyu_binding,
|
||||
)
|
||||
from web.backend.services.douyu_runner_bind import BindMixin
|
||||
|
||||
ACT_ALIAS = "20260120QYOOB"
|
||||
@@ -362,6 +369,124 @@ def test_task_result_helpers_accept_existing_action_alias_pending():
|
||||
assert binding_role_from_result(result) == "只为爱杰宝"
|
||||
|
||||
|
||||
def _binding_task(*, status: str, result: dict[str, Any]) -> DouyuTask:
|
||||
return DouyuTask(
|
||||
id=101,
|
||||
batch_id="binding-view",
|
||||
account_id=1,
|
||||
created_by=1,
|
||||
task_type="get_bind_qr",
|
||||
handbook_scope="elite",
|
||||
status=status,
|
||||
result=result,
|
||||
)
|
||||
|
||||
|
||||
def _binding_account() -> Account:
|
||||
return Account(
|
||||
username="binding-view",
|
||||
password="p",
|
||||
email="binding-view@example.com",
|
||||
email_password="ep",
|
||||
status="active",
|
||||
game_name="当前生效角色",
|
||||
game_channel="微信 · 苹果(iOS)",
|
||||
role_bind_status=BIND_BOUND,
|
||||
)
|
||||
|
||||
|
||||
def test_binding_view_keeps_pending_role_separate_from_account_binding():
|
||||
task = _binding_task(
|
||||
status="success",
|
||||
result={
|
||||
"role_name": "本次待确认角色",
|
||||
"area_name": "手Q",
|
||||
"plat_name": "苹果(iOS)",
|
||||
"baseline_role_name": "当前生效角色",
|
||||
"before_bind_info": {
|
||||
"act_alias": ACT_ALIAS,
|
||||
"role_name": "当前生效角色",
|
||||
"is_bound_act": True,
|
||||
"need_bind_act": True,
|
||||
},
|
||||
"act_alias": ACT_ALIAS,
|
||||
"need_bind_act": True,
|
||||
"is_bound_act": False,
|
||||
"bind_ready_for_confirm": True,
|
||||
"bind_confirmed": False,
|
||||
"bind_phase": "role_ready",
|
||||
},
|
||||
)
|
||||
account = _binding_account()
|
||||
|
||||
binding = resolve_douyu_binding(task, account=account)
|
||||
|
||||
assert binding.status == BINDING_VIEW_PENDING
|
||||
assert binding.pending_role_name == "本次待确认角色"
|
||||
assert binding.pending_channel == "手Q / 苹果(iOS)"
|
||||
assert binding.current_role_name == "当前生效角色"
|
||||
assert binding.current_channel == "微信 · 苹果(iOS)"
|
||||
assert binding.effective_role_name == "本次待确认角色"
|
||||
assert binding.bind_confirmed is False
|
||||
assert binding.bind_ready_for_confirm is True
|
||||
assert binding.account_bind_status == BIND_BOUND
|
||||
|
||||
|
||||
def test_binding_view_confirms_only_from_confirmation_task_result():
|
||||
task = _binding_task(
|
||||
status="success",
|
||||
result={
|
||||
"role_name": "本次已确认角色",
|
||||
"area_name": "微信",
|
||||
"plat_name": "安卓(android)",
|
||||
"is_bound_act": True,
|
||||
"bind_confirmed": True,
|
||||
"bind_phase": "confirmed",
|
||||
},
|
||||
)
|
||||
task.task_type = "confirm_bind"
|
||||
account = _binding_account()
|
||||
|
||||
binding = resolve_douyu_binding(task, account=account)
|
||||
|
||||
assert binding.status == BINDING_VIEW_CONFIRMED
|
||||
assert binding.confirmed_role_name == "本次已确认角色"
|
||||
assert binding.confirmed_channel == "微信 / 安卓(android)"
|
||||
assert binding.current_role_name == "当前生效角色"
|
||||
assert binding.effective_role_name == "本次已确认角色"
|
||||
assert binding.bind_confirmed is True
|
||||
assert binding.bind_ready_for_confirm is False
|
||||
|
||||
|
||||
def test_binding_view_failure_never_becomes_confirmed():
|
||||
task = _binding_task(
|
||||
status="failed",
|
||||
result={
|
||||
"role_name": "未生效角色",
|
||||
"bind_ready_for_confirm": True,
|
||||
"bind_confirmed": True,
|
||||
"bind_phase": "confirm_failed",
|
||||
},
|
||||
)
|
||||
|
||||
binding = resolve_douyu_binding(task, account=_binding_account())
|
||||
|
||||
assert binding.status == BINDING_VIEW_FAILED
|
||||
assert binding.bind_confirmed is False
|
||||
assert binding.bind_ready_for_confirm is False
|
||||
|
||||
|
||||
def test_account_binding_without_task_does_not_confirm_fulfillment_order():
|
||||
account = _binding_account()
|
||||
|
||||
binding = resolve_douyu_binding(None, account=account)
|
||||
|
||||
assert binding.status == BINDING_VIEW_NONE
|
||||
assert binding.current_role_name == "当前生效角色"
|
||||
assert binding.account_bind_status == BIND_BOUND
|
||||
assert binding.bind_confirmed is False
|
||||
|
||||
|
||||
def test_confirmed_new_role_replaces_account_current_role():
|
||||
account = Account(
|
||||
username="replace-role",
|
||||
|
||||
+145
-1
@@ -44,7 +44,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261123_0126"
|
||||
HEAD_REVISION = "20261123_0127"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
@@ -582,6 +582,150 @@ class TestMigrationSmoke:
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
||||
|
||||
def test_0127_links_latest_pending_account_workbench_role(self):
|
||||
creds = get_mysql_credentials()
|
||||
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
|
||||
mig_url = (
|
||||
f"mysql+pymysql://{quote_plus(creds['user'])}:"
|
||||
f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/"
|
||||
f"{mig_db}?charset=utf8mb4"
|
||||
)
|
||||
admin_engine = get_test_engine()
|
||||
mig_engine = create_engine(mig_url)
|
||||
original_url = database_module.DATABASE_URL
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
f"CREATE DATABASE `{mig_db}` "
|
||||
"CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
|
||||
)
|
||||
)
|
||||
try:
|
||||
database_module.DATABASE_URL = mig_url
|
||||
cfg = _migration_config()
|
||||
cfg.set_main_option("sqlalchemy.url", mig_url)
|
||||
command.upgrade(cfg, "20261123_0126")
|
||||
with Session(mig_engine) as session:
|
||||
user = User(
|
||||
username="pending-link-user",
|
||||
password_hash="hash",
|
||||
role="super_admin",
|
||||
is_active=True,
|
||||
)
|
||||
account = Account(
|
||||
username="pending-link-account",
|
||||
password="password",
|
||||
email="pending-link@example.com",
|
||||
email_password="mail-password",
|
||||
cookie="acf_uid=1",
|
||||
role_bind_status="bound",
|
||||
game_name="历史角色",
|
||||
status="active",
|
||||
)
|
||||
session.add_all([user, account])
|
||||
session.flush()
|
||||
lease = AccountLease(
|
||||
account_id=account.id,
|
||||
holder_user_id=user.id,
|
||||
status="active",
|
||||
purpose="platform_fulfillment",
|
||||
)
|
||||
old_bind_task = DouyuTask(
|
||||
batch_id="pending-link-old",
|
||||
account_id=account.id,
|
||||
account_assigned_to=user.id,
|
||||
task_type="get_bind_qr",
|
||||
handbook_scope="elite",
|
||||
status="success",
|
||||
result={"role_name": "旧待确认角色"},
|
||||
created_by=user.id,
|
||||
)
|
||||
latest_bind_task = DouyuTask(
|
||||
batch_id="pending-link-latest",
|
||||
account_id=account.id,
|
||||
account_assigned_to=user.id,
|
||||
task_type="get_bind_qr",
|
||||
handbook_scope="elite",
|
||||
status="success",
|
||||
result={
|
||||
"role_name": "最新待确认角色",
|
||||
"baseline_role_name": "历史角色",
|
||||
"before_bind_info": {
|
||||
"act_alias": "20260120QYOOB",
|
||||
"role_name": "历史角色",
|
||||
"is_bound_act": True,
|
||||
"need_bind_act": True,
|
||||
},
|
||||
"act_alias": "20260120QYOOB",
|
||||
"need_bind_act": True,
|
||||
"bind_ready_for_confirm": True,
|
||||
"bind_confirmed": False,
|
||||
"bind_phase": "role_ready",
|
||||
},
|
||||
created_by=user.id,
|
||||
)
|
||||
session.add_all([lease, old_bind_task, latest_bind_task])
|
||||
session.flush()
|
||||
stale_bind_task = DouyuTask(
|
||||
batch_id="pending-link-stale",
|
||||
account_id=account.id,
|
||||
account_assigned_to=user.id,
|
||||
task_type="get_bind_qr",
|
||||
handbook_scope="elite",
|
||||
status="success",
|
||||
result={
|
||||
"role_name": "历史角色",
|
||||
"baseline_role_name": "历史角色",
|
||||
"bind_ready_for_confirm": True,
|
||||
"bind_confirmed": False,
|
||||
"bind_phase": "role_ready",
|
||||
},
|
||||
created_by=user.id,
|
||||
)
|
||||
session.add(stale_bind_task)
|
||||
session.flush()
|
||||
task = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="PENDING-LINK-ORDER",
|
||||
source_order_item_id="PENDING-LINK-ITEM",
|
||||
platform_order_id="PENDING-LINK-PLATFORM",
|
||||
internal_sku_key="待确认角色回接",
|
||||
sku_name="待确认角色回接",
|
||||
scope="elite",
|
||||
account_id=account.id,
|
||||
lease_id=lease.id,
|
||||
bind_task_id=old_bind_task.id,
|
||||
binding_status="role_ready",
|
||||
execution_status="role_ready",
|
||||
)
|
||||
session.add(task)
|
||||
session.commit()
|
||||
task_id = int(task.id)
|
||||
latest_bind_task_id = int(latest_bind_task.id)
|
||||
old_bind_task_id = int(old_bind_task.id)
|
||||
|
||||
command.upgrade(cfg, "head")
|
||||
|
||||
with Session(mig_engine) as session:
|
||||
task = session.get(PlatformFulfillmentTask, task_id)
|
||||
event = (
|
||||
session.query(PlatformFulfillmentEvent)
|
||||
.filter_by(
|
||||
task_id=task_id,
|
||||
event_type="binding_pending_task_linked",
|
||||
)
|
||||
.one()
|
||||
)
|
||||
assert task.bind_task_id == latest_bind_task_id
|
||||
assert task.binding_status == "role_ready"
|
||||
assert event.detail_json["previousBindTaskId"] == old_bind_task_id
|
||||
assert event.detail_json["roleName"] == "最新待确认角色"
|
||||
finally:
|
||||
database_module.DATABASE_URL = original_url
|
||||
mig_engine.dispose()
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
||||
|
||||
def test_0125_preserves_shop_names_without_automatic_aliases(self):
|
||||
creds = get_mysql_credentials()
|
||||
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
|
||||
|
||||
@@ -1889,6 +1889,50 @@ class TestBindingAndCompletion(_Base):
|
||||
assert task.bind_task_id == confirm_task.id
|
||||
assert event.detail_json["roleName"] == "新角色"
|
||||
|
||||
def test_account_bound_does_not_confirm_unconfirmed_confirmation_task(self):
|
||||
task = self._allocated()
|
||||
account = self.session.get(Account, task.account_id)
|
||||
account.role_bind_status = "bound"
|
||||
account.game_name = "账号当前角色"
|
||||
task.binding_status = "role_ready"
|
||||
task.execution_status = "role_ready"
|
||||
confirm_task = DouyuTask(
|
||||
batch_id="unconfirmed-confirm-task",
|
||||
account_id=task.account_id,
|
||||
account_assigned_to=self.admin_id,
|
||||
task_type="confirm_bind",
|
||||
handbook_scope="elite",
|
||||
status="success",
|
||||
result={
|
||||
"role_name": "账号当前角色",
|
||||
"is_bound_act": True,
|
||||
"bind_confirmed": False,
|
||||
"bind_phase": "waiting_role",
|
||||
},
|
||||
created_by=self.admin_id,
|
||||
)
|
||||
self.session.add(confirm_task)
|
||||
self.session.commit()
|
||||
|
||||
synced = service.sync_task_from_binding_runner(
|
||||
self.session,
|
||||
douyu_task_id=confirm_task.id,
|
||||
)
|
||||
|
||||
self.session.refresh(task)
|
||||
assert synced == 0
|
||||
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_synced_from_account",
|
||||
)
|
||||
.count()
|
||||
== 0
|
||||
)
|
||||
|
||||
def test_bind_qr_success_does_not_promote_existing_account_binding(self):
|
||||
task = self._allocated()
|
||||
account = self.session.get(Account, task.account_id)
|
||||
@@ -1954,6 +1998,133 @@ class TestBindingAndCompletion(_Base):
|
||||
== 0
|
||||
)
|
||||
|
||||
def test_standalone_pending_bind_task_links_to_active_fulfillment_task(self):
|
||||
task = self._allocated()
|
||||
old_bind_task = DouyuTask(
|
||||
batch_id="bind-old-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": "旧待确认角色",
|
||||
"current_role_name": "历史角色",
|
||||
"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(old_bind_task)
|
||||
self.session.flush()
|
||||
task.bind_task_id = old_bind_task.id
|
||||
task.binding_status = "role_ready"
|
||||
task.execution_status = "role_ready"
|
||||
latest_bind_task = DouyuTask(
|
||||
batch_id="account-workbench-new-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": "最新待确认角色",
|
||||
"current_role_name": "历史角色",
|
||||
"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(latest_bind_task)
|
||||
self.session.commit()
|
||||
|
||||
synced = service.sync_task_from_binding_runner(
|
||||
self.session,
|
||||
douyu_task_id=latest_bind_task.id,
|
||||
)
|
||||
self.session.refresh(task)
|
||||
detail = service.get_task_detail(self.session, task.id)
|
||||
|
||||
assert synced == 1
|
||||
assert task.bind_task_id == latest_bind_task.id
|
||||
assert task.binding_status == "role_ready"
|
||||
assert detail["task"]["bindTask"]["roleName"] == "最新待确认角色"
|
||||
event = (
|
||||
self.session.query(PlatformFulfillmentEvent)
|
||||
.filter_by(
|
||||
task_id=task.id,
|
||||
event_type="binding_pending_task_linked",
|
||||
)
|
||||
.one()
|
||||
)
|
||||
assert event.detail_json["previousBindTaskId"] == old_bind_task.id
|
||||
assert event.detail_json["bindTaskId"] == latest_bind_task.id
|
||||
|
||||
def test_refresh_binding_attaches_latest_pending_account_workbench_role(self):
|
||||
task = self._allocated()
|
||||
old_bind_task = DouyuTask(
|
||||
batch_id="refresh-old-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": "旧待确认角色", "bind_ready_for_confirm": True},
|
||||
created_by=self.admin_id,
|
||||
)
|
||||
latest_bind_task = DouyuTask(
|
||||
batch_id="refresh-latest-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": "最新待确认角色",
|
||||
"current_role_name": "历史角色",
|
||||
"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_all([old_bind_task, latest_bind_task])
|
||||
self.session.flush()
|
||||
task.bind_task_id = old_bind_task.id
|
||||
task.binding_status = "role_ready"
|
||||
task.execution_status = "role_ready"
|
||||
self.session.commit()
|
||||
|
||||
detail = service.refresh_binding(self.session, task_id=task.id)
|
||||
|
||||
self.session.refresh(task)
|
||||
assert task.bind_task_id == latest_bind_task.id
|
||||
assert detail["task"]["bindTask"]["roleName"] == "最新待确认角色"
|
||||
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is True
|
||||
|
||||
def test_customer_start_mapping_missing_is_idempotent(self, monkeypatch):
|
||||
task = self.task(mapped=False)
|
||||
task.issue_code = "mapping_missing"
|
||||
|
||||
@@ -2,13 +2,23 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from .database import SessionLocal
|
||||
|
||||
_started = False
|
||||
_heartbeat_thread: threading.Thread | None = None
|
||||
_heartbeat_stop = threading.Event()
|
||||
_heartbeat_lock = threading.Lock()
|
||||
_HEARTBEAT_INTERVAL_SECONDS = 5
|
||||
_HEARTBEAT_STALE_SECONDS = 30
|
||||
|
||||
|
||||
def _control_plane_enabled() -> bool:
|
||||
@@ -20,6 +30,103 @@ def _control_plane_enabled() -> bool:
|
||||
}
|
||||
|
||||
|
||||
def _runtime_heartbeat_path() -> Path:
|
||||
configured = os.getenv("BACKGROUND_RUNTIME_HEARTBEAT_PATH", "").strip()
|
||||
if configured:
|
||||
return Path(configured)
|
||||
return Path(__file__).resolve().parents[2] / "data" / "background_runtime.json"
|
||||
|
||||
|
||||
def _runtime_heartbeat_payload() -> dict[str, Any]:
|
||||
from .services.automation.scheduler import scheduler_status
|
||||
|
||||
return {
|
||||
"pid": os.getpid(),
|
||||
"updatedAt": datetime.now(UTC).isoformat(),
|
||||
"scheduler": scheduler_status(),
|
||||
}
|
||||
|
||||
|
||||
def _write_runtime_heartbeat() -> None:
|
||||
path = _runtime_heartbeat_path()
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(f"{path.suffix}.tmp")
|
||||
temporary.write_text(
|
||||
json.dumps(_runtime_heartbeat_payload(), ensure_ascii=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temporary.replace(path)
|
||||
except Exception: # noqa: BLE001 - heartbeat must not stop background services
|
||||
logger.exception("写入后台运行时心跳失败: {}", path)
|
||||
|
||||
|
||||
def _heartbeat_loop() -> None:
|
||||
while not _heartbeat_stop.wait(_HEARTBEAT_INTERVAL_SECONDS):
|
||||
_write_runtime_heartbeat()
|
||||
|
||||
|
||||
def _start_runtime_heartbeat() -> None:
|
||||
global _heartbeat_thread
|
||||
with _heartbeat_lock:
|
||||
if _heartbeat_thread is not None and _heartbeat_thread.is_alive():
|
||||
return
|
||||
_heartbeat_stop.clear()
|
||||
_write_runtime_heartbeat()
|
||||
_heartbeat_thread = threading.Thread(
|
||||
target=_heartbeat_loop,
|
||||
name="background-runtime-heartbeat",
|
||||
daemon=True,
|
||||
)
|
||||
_heartbeat_thread.start()
|
||||
|
||||
|
||||
def _stop_runtime_heartbeat() -> None:
|
||||
global _heartbeat_thread
|
||||
with _heartbeat_lock:
|
||||
thread = _heartbeat_thread
|
||||
_heartbeat_thread = None
|
||||
_heartbeat_stop.set()
|
||||
if thread is not None and thread.is_alive():
|
||||
thread.join(timeout=2)
|
||||
try:
|
||||
_runtime_heartbeat_path().unlink(missing_ok=True)
|
||||
except OSError:
|
||||
logger.exception("清理后台运行时心跳失败")
|
||||
|
||||
|
||||
def background_runtime_status() -> dict[str, Any]:
|
||||
"""读取独立后台进程心跳;API 进程据此展示真实调度状态。"""
|
||||
path = _runtime_heartbeat_path()
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
heartbeat_at = datetime.fromisoformat(str(payload.get("updatedAt") or ""))
|
||||
if heartbeat_at.tzinfo is None:
|
||||
heartbeat_at = heartbeat_at.replace(tzinfo=UTC)
|
||||
age_seconds = max(
|
||||
0.0,
|
||||
(datetime.now(UTC) - heartbeat_at).total_seconds(),
|
||||
)
|
||||
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
||||
return {
|
||||
"running": False,
|
||||
"heartbeatAt": None,
|
||||
"ageSeconds": None,
|
||||
"staleAfterSeconds": _HEARTBEAT_STALE_SECONDS,
|
||||
"pid": None,
|
||||
"scheduler": {},
|
||||
}
|
||||
scheduler = payload.get("scheduler")
|
||||
return {
|
||||
"running": age_seconds <= _HEARTBEAT_STALE_SECONDS,
|
||||
"heartbeatAt": heartbeat_at.isoformat(),
|
||||
"ageSeconds": round(age_seconds, 1),
|
||||
"staleAfterSeconds": _HEARTBEAT_STALE_SECONDS,
|
||||
"pid": payload.get("pid"),
|
||||
"scheduler": scheduler if isinstance(scheduler, dict) else {},
|
||||
}
|
||||
|
||||
|
||||
def recover_orphaned_work() -> None:
|
||||
"""进程启动时收敛上次中断的任务和运行记录。"""
|
||||
from .models import ExecutionJob
|
||||
@@ -111,6 +218,7 @@ def start_background_services() -> bool:
|
||||
start_platform_fulfillment_auto_allocator()
|
||||
start_binding_poll_scheduler()
|
||||
start_payment_poll_scheduler()
|
||||
_start_runtime_heartbeat()
|
||||
_started = True
|
||||
logger.info("后台服务已启动")
|
||||
return True
|
||||
@@ -140,11 +248,13 @@ def stop_background_services() -> None:
|
||||
stop_integration_outbox_worker()
|
||||
stop_scheduler()
|
||||
stop_execution_job_worker()
|
||||
_stop_runtime_heartbeat()
|
||||
_started = False
|
||||
logger.info("后台服务已停止")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"background_runtime_status",
|
||||
"recover_orphaned_work",
|
||||
"start_background_services",
|
||||
"stop_background_services",
|
||||
|
||||
@@ -505,6 +505,10 @@
|
||||
"20261123_0126_repair_false_binding_sync.py": {
|
||||
"revision": "20261123_0126",
|
||||
"sha256": "86c201d2298845f7f3eb3e733760fe46911638dc1ef046d4518c02172cfaba6f"
|
||||
},
|
||||
"20261123_0127_link_latest_pending_binding.py": {
|
||||
"revision": "20261123_0127",
|
||||
"sha256": "cedfe2928e80a2d530906621b52373aab280afc19101311318512021cc093df7"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
"""link latest account-workbench pending role to active fulfillment tasks.
|
||||
|
||||
Revision ID: 20261123_0127
|
||||
Revises: 20261123_0126
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
from web.backend.services.account_binding import pending_binding_role_from_result
|
||||
|
||||
revision: str = "20261123_0127"
|
||||
down_revision: str | None = "20261123_0126"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
tasks = bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT
|
||||
t.id AS task_id,
|
||||
t.account_id,
|
||||
t.bind_task_id,
|
||||
a.username,
|
||||
a.nickname
|
||||
FROM platform_fulfillment_tasks AS t
|
||||
JOIN accounts AS a ON a.id = t.account_id
|
||||
JOIN account_leases AS l ON l.id = t.lease_id
|
||||
WHERE t.scope = 'elite'
|
||||
AND t.binding_status IN ('allocated', 'waiting_bind', 'role_ready')
|
||||
AND t.execution_status NOT IN ('completed', 'cancelled', 'manual_required')
|
||||
AND l.status = 'active'
|
||||
"""
|
||||
)
|
||||
).mappings().all()
|
||||
now = datetime.now(UTC).replace(tzinfo=None)
|
||||
for task in tasks:
|
||||
candidates = bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT id, result
|
||||
FROM douyu_tasks
|
||||
WHERE account_id = :account_id
|
||||
AND task_type = 'get_bind_qr'
|
||||
AND handbook_scope = 'elite'
|
||||
AND status = 'success'
|
||||
AND id > :current_bind_task_id
|
||||
ORDER BY id DESC
|
||||
LIMIT 20
|
||||
"""
|
||||
),
|
||||
{
|
||||
"account_id": int(task["account_id"]),
|
||||
"current_bind_task_id": int(task["bind_task_id"] or 0),
|
||||
},
|
||||
).mappings().all()
|
||||
latest: dict[str, object] | None = None
|
||||
role_name = ""
|
||||
for candidate in candidates:
|
||||
result = candidate["result"]
|
||||
if isinstance(result, str):
|
||||
try:
|
||||
result = json.loads(result)
|
||||
except json.JSONDecodeError:
|
||||
result = {}
|
||||
if not isinstance(result, dict):
|
||||
continue
|
||||
role_name = pending_binding_role_from_result(result)
|
||||
if role_name:
|
||||
latest = dict(candidate)
|
||||
break
|
||||
if latest is None:
|
||||
continue
|
||||
task_id = int(task["task_id"])
|
||||
bind_task_id = int(latest["id"])
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE platform_fulfillment_tasks
|
||||
SET bind_task_id = :bind_task_id,
|
||||
binding_status = 'role_ready',
|
||||
execution_status = 'role_ready',
|
||||
issue_code = '',
|
||||
last_error = '',
|
||||
updated_at = :now
|
||||
WHERE id = :task_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"task_id": task_id,
|
||||
"bind_task_id": bind_task_id,
|
||||
"now": now,
|
||||
},
|
||||
)
|
||||
detail = {
|
||||
"accountId": int(task["account_id"]),
|
||||
"accountName": str(task["nickname"] or task["username"] or ""),
|
||||
"bindTaskId": bind_task_id,
|
||||
"previousBindTaskId": int(task["bind_task_id"] or 0),
|
||||
"roleName": role_name,
|
||||
"source": "account_workbench",
|
||||
"backfilled": True,
|
||||
}
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
INSERT INTO platform_fulfillment_events (
|
||||
task_id,
|
||||
event_type,
|
||||
actor_type,
|
||||
actor_id,
|
||||
detail_json,
|
||||
created_at
|
||||
) VALUES (
|
||||
:task_id,
|
||||
'binding_pending_task_linked',
|
||||
'system',
|
||||
'',
|
||||
:detail_json,
|
||||
:created_at
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"task_id": task_id,
|
||||
"detail_json": json.dumps(detail, ensure_ascii=False),
|
||||
"created_at": now,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""数据修复不回退,避免履约任务重新指向过期待确认角色。"""
|
||||
@@ -143,6 +143,7 @@ def list_jobs(
|
||||
# 巡检与重登是两个作业,但通过数据库联动:巡检把行标成 invalid,重登作业的
|
||||
# 候选条件正是这个字段。这里把「当前有多少条等着重登」一并返回,页面才能把
|
||||
# 这层上下游关系显示出来,而不是让人以为两个开关互不相干。
|
||||
from ..background_runtime import background_runtime_status
|
||||
from ..database import worker_engine
|
||||
from ..services.automation.jobs.ck_relogin import count_pending_relogin
|
||||
from ..services.binding_poll_scheduler import (
|
||||
@@ -155,9 +156,31 @@ def list_jobs(
|
||||
from ..services.task_runtime import lane_stats
|
||||
|
||||
pending_relogin = count_pending_relogin(db)
|
||||
scheduler_state = scheduler_status()
|
||||
background_runtime = background_runtime_status()
|
||||
background_scheduler = background_runtime.get("scheduler")
|
||||
if (
|
||||
not scheduler_state["running"]
|
||||
and background_runtime["running"]
|
||||
and isinstance(background_scheduler, dict)
|
||||
and background_scheduler.get("running") is True
|
||||
):
|
||||
scheduler_state = {
|
||||
**scheduler_state,
|
||||
"running": True,
|
||||
"process": "background",
|
||||
"pid": background_runtime.get("pid"),
|
||||
"heartbeatAt": background_runtime.get("heartbeatAt"),
|
||||
}
|
||||
else:
|
||||
scheduler_state = {
|
||||
**scheduler_state,
|
||||
"process": "api" if scheduler_state["running"] else "none",
|
||||
"heartbeatAt": background_runtime.get("heartbeatAt"),
|
||||
}
|
||||
|
||||
return {
|
||||
"scheduler": scheduler_status(),
|
||||
"scheduler": scheduler_state,
|
||||
"runtime": {
|
||||
"task_lanes": lane_stats(),
|
||||
"worker_db_pool": getattr(worker_engine.pool, "status", lambda: "")()
|
||||
@@ -166,6 +189,7 @@ def list_jobs(
|
||||
"binding_poll": binding_poll_status(),
|
||||
"payment_poll": payment_poll_status(),
|
||||
"execution_jobs": execution_job_worker_status(),
|
||||
"background_runtime": background_runtime,
|
||||
},
|
||||
"pending_relogin": pending_relogin,
|
||||
"jobs": [
|
||||
|
||||
@@ -1778,6 +1778,7 @@ class DouyuTaskOut(BaseModel):
|
||||
handbook_scope: str = "legacy"
|
||||
status: str
|
||||
message: str = ""
|
||||
binding: dict[str, Any] = Field(default_factory=dict)
|
||||
result: dict[str, Any] | None = None
|
||||
created_by: int
|
||||
created_at: datetime | None = None
|
||||
@@ -1798,6 +1799,7 @@ class DouyuTaskOut(BaseModel):
|
||||
"handbook_scope": self.handbook_scope,
|
||||
"status": self.status,
|
||||
"message": self.message,
|
||||
"binding": self.binding,
|
||||
"result": self.result,
|
||||
"created_by": self.created_by,
|
||||
"created_at": _isoformat(self.created_at),
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""斗鱼绑定任务的唯一读取模型。
|
||||
|
||||
``DouyuTask.result`` 是任务级绑定事实的来源:
|
||||
|
||||
- 本次扫码识别出的待确认角色只属于这个任务;
|
||||
- ``bind_confirmed`` 表示这个任务是否已经把角色确认生效;
|
||||
- ``accounts.game_name`` / ``role_bind_status`` 只表示账号当前状态,
|
||||
不能拿来判断某个履约订单是否已经确认。
|
||||
|
||||
精英宝典、履约详情、客户页和履约刷新都必须消费这里的结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import Any
|
||||
|
||||
from ..models import Account, DouyuTask
|
||||
from .account_binding import (
|
||||
binding_channel,
|
||||
get_bind_status,
|
||||
pending_binding_role_from_result,
|
||||
)
|
||||
|
||||
BINDING_VIEW_NONE = "none"
|
||||
BINDING_VIEW_WAITING_SCAN = "waiting_scan"
|
||||
BINDING_VIEW_PENDING = "pending"
|
||||
BINDING_VIEW_CONFIRMED = "confirmed"
|
||||
BINDING_VIEW_FAILED = "failed"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DouyuBindingView:
|
||||
"""供所有绑定入口共享的稳定视图。"""
|
||||
|
||||
source_task_id: int | None
|
||||
source_task_type: str
|
||||
source_task_status: str
|
||||
status: str
|
||||
bind_phase: str
|
||||
pending_role_name: str
|
||||
pending_area_name: str
|
||||
pending_plat_name: str
|
||||
pending_channel: str
|
||||
confirmed_role_name: str
|
||||
confirmed_area_name: str
|
||||
confirmed_plat_name: str
|
||||
confirmed_channel: str
|
||||
effective_role_name: str
|
||||
effective_area_name: str
|
||||
effective_plat_name: str
|
||||
effective_channel: str
|
||||
current_role_name: str
|
||||
current_area_name: str
|
||||
current_plat_name: str
|
||||
current_channel: str
|
||||
qr_url: str
|
||||
reported_ready_for_confirm: bool
|
||||
bind_confirmed: bool
|
||||
bind_ready_for_confirm: bool
|
||||
account_bind_status: str
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def resolve_douyu_binding(
|
||||
task: DouyuTask | None,
|
||||
*,
|
||||
account: Account | None = None,
|
||||
) -> DouyuBindingView:
|
||||
"""从任务结果和账号当前状态生成唯一绑定视图。"""
|
||||
result = task.result if task is not None and isinstance(task.result, dict) else {}
|
||||
source_status = str(task.status or "") if task is not None else ""
|
||||
successful_task = source_status == "success"
|
||||
pending_role = pending_binding_role_from_result(result)
|
||||
bind_confirmed = successful_task and bool(result.get("bind_confirmed"))
|
||||
if pending_role:
|
||||
bind_confirmed = False
|
||||
|
||||
pending_area = str(result.get("area_name") or "").strip() if pending_role else ""
|
||||
pending_plat = str(result.get("plat_name") or "").strip() if pending_role else ""
|
||||
pending_channel = binding_channel(
|
||||
{
|
||||
"area_name": pending_area,
|
||||
"plat_name": pending_plat,
|
||||
}
|
||||
)
|
||||
|
||||
confirmed_role = (
|
||||
str(result.get("role_name") or result.get("current_role_name") or "").strip()
|
||||
if bind_confirmed
|
||||
else ""
|
||||
)
|
||||
confirmed_area = str(result.get("area_name") or "").strip() if bind_confirmed else ""
|
||||
confirmed_plat = str(result.get("plat_name") or "").strip() if bind_confirmed else ""
|
||||
confirmed_channel = binding_channel(
|
||||
{
|
||||
"area_name": confirmed_area,
|
||||
"plat_name": confirmed_plat,
|
||||
}
|
||||
)
|
||||
|
||||
account_bind_status = get_bind_status(account, "elite") if account else ""
|
||||
current_role = str(account.game_name or "").strip() if account else ""
|
||||
current_area = str(result.get("current_area_name") or "").strip()
|
||||
current_plat = str(result.get("current_plat_name") or "").strip()
|
||||
current_channel = str(account.game_channel or "").strip() if account else ""
|
||||
if not current_role:
|
||||
current_role = str(
|
||||
result.get("current_role_name") or result.get("baseline_role_name") or ""
|
||||
).strip()
|
||||
if not current_channel:
|
||||
current_channel = binding_channel(
|
||||
{
|
||||
"area_name": result.get("current_area_name"),
|
||||
"plat_name": result.get("current_plat_name"),
|
||||
}
|
||||
)
|
||||
|
||||
effective_role = pending_role or confirmed_role
|
||||
effective_area = pending_area or confirmed_area
|
||||
effective_plat = pending_plat or confirmed_plat
|
||||
effective_channel = pending_channel or confirmed_channel
|
||||
qr_url = str(result.get("url") or "")
|
||||
|
||||
if source_status in {"failed", "error", "stopped"}:
|
||||
status = BINDING_VIEW_FAILED
|
||||
elif bind_confirmed:
|
||||
status = BINDING_VIEW_CONFIRMED
|
||||
elif pending_role:
|
||||
status = BINDING_VIEW_PENDING
|
||||
elif qr_url:
|
||||
status = BINDING_VIEW_WAITING_SCAN
|
||||
else:
|
||||
status = BINDING_VIEW_NONE
|
||||
|
||||
return DouyuBindingView(
|
||||
source_task_id=int(task.id) if task is not None else None,
|
||||
source_task_type=str(task.task_type or "") if task is not None else "",
|
||||
source_task_status=source_status,
|
||||
status=status,
|
||||
bind_phase=str(result.get("bind_phase") or ""),
|
||||
pending_role_name=pending_role,
|
||||
pending_area_name=pending_area,
|
||||
pending_plat_name=pending_plat,
|
||||
pending_channel=pending_channel,
|
||||
confirmed_role_name=confirmed_role,
|
||||
confirmed_area_name=confirmed_area,
|
||||
confirmed_plat_name=confirmed_plat,
|
||||
confirmed_channel=confirmed_channel,
|
||||
effective_role_name=effective_role,
|
||||
effective_area_name=effective_area,
|
||||
effective_plat_name=effective_plat,
|
||||
effective_channel=effective_channel,
|
||||
current_role_name=current_role,
|
||||
current_area_name=current_area,
|
||||
current_plat_name=current_plat,
|
||||
current_channel=current_channel,
|
||||
qr_url=qr_url,
|
||||
reported_ready_for_confirm=bool(result.get("bind_ready_for_confirm")),
|
||||
bind_confirmed=status == BINDING_VIEW_CONFIRMED,
|
||||
bind_ready_for_confirm=status == BINDING_VIEW_PENDING,
|
||||
account_bind_status=account_bind_status,
|
||||
)
|
||||
@@ -41,10 +41,6 @@ from ..models import (
|
||||
User,
|
||||
)
|
||||
from ..permissions import user_has_permission
|
||||
from .account_binding import (
|
||||
binding_channel,
|
||||
binding_role_from_result,
|
||||
)
|
||||
from .account_events_service import (
|
||||
CATEGORY_OPS,
|
||||
EVENT_COLLAB_SYNCED,
|
||||
|
||||
@@ -17,9 +17,9 @@ from ..models import (
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from .account_binding import binding_channel, binding_role_from_result
|
||||
from .account_events_service import EVENT_COLLAB_SYNCED
|
||||
from .audit_service import record_account_action, record_audit
|
||||
from .douyu_binding import BINDING_VIEW_CONFIRMED, resolve_douyu_binding
|
||||
from .douyu_collab_common import (
|
||||
POINTS_THRESHOLD_DEFAULT,
|
||||
SOURCE_TYPE_PLATFORM_FULFILLMENT,
|
||||
@@ -101,15 +101,18 @@ def _apply_platform_fulfillment_binding(
|
||||
if task.bind_task_id
|
||||
else None
|
||||
)
|
||||
result = (
|
||||
bind_task.result if bind_task and isinstance(bind_task.result, dict) else None
|
||||
)
|
||||
role = binding_role_from_result(result)
|
||||
if not role:
|
||||
if bind_task is None:
|
||||
return
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
account=db.get(Account, int(task.account_id)) if task.account_id else None,
|
||||
)
|
||||
if binding.status != BINDING_VIEW_CONFIRMED:
|
||||
return
|
||||
role = binding.confirmed_role_name
|
||||
if overwrite or not order.bind_game_role:
|
||||
order.bind_game_role = _text(role, max_length=128)
|
||||
channel = binding_channel(result)
|
||||
channel = binding.confirmed_channel
|
||||
if channel and (overwrite or not order.bind_game_channel):
|
||||
order.bind_game_channel = _text(channel, max_length=128)
|
||||
if overwrite or not order.bind_snapshot_at:
|
||||
|
||||
@@ -15,6 +15,7 @@ from core.douyu.cookie_utils import cookie_value
|
||||
from ..models import Account, DouyuConfig, DouyuTask
|
||||
from . import account_query_filters as account_filters
|
||||
from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk
|
||||
from .douyu_binding import resolve_douyu_binding
|
||||
|
||||
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = account_filters.LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
|
||||
cookie_holding_filter = account_filters.cookie_holding_filter
|
||||
@@ -682,6 +683,7 @@ def sanitize_douyu_task_result(
|
||||
def douyu_task_payload(task: DouyuTask, *, include_detail: bool = False) -> dict:
|
||||
"""生成 REST 与 WebSocket 共用的斗鱼任务载荷。"""
|
||||
account = task.account
|
||||
binding = resolve_douyu_binding(task, account=account).as_dict()
|
||||
|
||||
def isoformat(value: datetime | None) -> str | None:
|
||||
if value is None:
|
||||
@@ -701,6 +703,7 @@ def douyu_task_payload(task: DouyuTask, *, include_detail: bool = False) -> dict
|
||||
"handbook_scope": task.handbook_scope or "legacy",
|
||||
"status": task.status or "",
|
||||
"message": task.message or "",
|
||||
"binding": binding,
|
||||
"result": sanitize_douyu_task_result(
|
||||
task.result if isinstance(task.result, dict) else None,
|
||||
task.task_type or "",
|
||||
|
||||
@@ -17,10 +17,12 @@ from ...models import (
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from ..account_binding import (
|
||||
pending_binding_role_from_result,
|
||||
)
|
||||
from ..business_events import record_douyu_task_started
|
||||
from ..douyu_binding import (
|
||||
BINDING_VIEW_CONFIRMED,
|
||||
BINDING_VIEW_PENDING,
|
||||
resolve_douyu_binding,
|
||||
)
|
||||
from ..execution_jobs import (
|
||||
JOB_DOUYU_BINDING,
|
||||
LANE_FULFILLMENT,
|
||||
@@ -64,6 +66,10 @@ ACCOUNT_CONFIRMATION_TASK_TYPES = frozenset(
|
||||
"confirm_xpd_bind",
|
||||
}
|
||||
)
|
||||
PENDING_BINDING_TASK_TYPES = frozenset({"get_bind_qr"})
|
||||
ACTIVE_PENDING_TASK_STATUSES = frozenset(
|
||||
{"allocated", "waiting_bind", "role_ready"}
|
||||
)
|
||||
|
||||
|
||||
def start_binding_sync(
|
||||
@@ -82,12 +88,18 @@ def start_binding_sync(
|
||||
if task.bind_task_id:
|
||||
existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
|
||||
if existing:
|
||||
result = existing.result or {}
|
||||
pending_role = pending_binding_role_from_result(result)
|
||||
stale_pending = (
|
||||
bool(result.get("bind_ready_for_confirm")) and not pending_role
|
||||
binding = resolve_douyu_binding(
|
||||
existing,
|
||||
account=db.get(Account, int(task.account_id)),
|
||||
)
|
||||
if bool(result.get("bind_confirmed")) or pending_role:
|
||||
stale_pending = (
|
||||
binding.reported_ready_for_confirm
|
||||
and not binding.bind_ready_for_confirm
|
||||
)
|
||||
if binding.status in {
|
||||
BINDING_VIEW_CONFIRMED,
|
||||
BINDING_VIEW_PENDING,
|
||||
}:
|
||||
return get_task_detail(db, task.id)
|
||||
if existing.status in {"planned", "pending", "running"}:
|
||||
return get_task_detail(db, task.id)
|
||||
@@ -193,6 +205,14 @@ 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)
|
||||
latest_pending = _latest_pending_binding_task(db, task)
|
||||
if latest_pending is not None and _attach_pending_binding_task(
|
||||
db,
|
||||
task,
|
||||
latest_pending,
|
||||
):
|
||||
db.commit()
|
||||
task = _load_task(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()
|
||||
@@ -206,23 +226,26 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
|
||||
task.last_error,
|
||||
)
|
||||
result = bind_task.result or {}
|
||||
pending_role = pending_binding_role_from_result(result)
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
account=db.get(Account, int(task.account_id)) if task.account_id else None,
|
||||
)
|
||||
if bind_task.status in {"failed", "error", "stopped"}:
|
||||
task.binding_status = "failed"
|
||||
task.execution_status = "manual_required"
|
||||
task.issue_code = _binding_failure_issue(bind_task, result)
|
||||
task.last_error = _customer_task_message(task)
|
||||
elif bool(result.get("bind_confirmed")):
|
||||
elif binding.status == BINDING_VIEW_CONFIRMED:
|
||||
task.binding_status = "bound"
|
||||
task.execution_status = "bound"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
elif pending_role:
|
||||
elif binding.status == BINDING_VIEW_PENDING:
|
||||
task.binding_status = "role_ready"
|
||||
task.execution_status = "role_ready"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
elif bool(result.get("bind_ready_for_confirm")):
|
||||
elif binding.reported_ready_for_confirm:
|
||||
# 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针后,客户页会
|
||||
# 回到已分配状态,并在下一次刷新时自动生成新二维码、重新开始轮询。
|
||||
previous_bind_task_id = task.bind_task_id
|
||||
@@ -250,7 +273,7 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
|
||||
_apply_task_lease_policy(db, task)
|
||||
db.commit()
|
||||
return get_task_detail(db, task.id)
|
||||
elif result.get("url"):
|
||||
elif binding.qr_url:
|
||||
task.binding_status = "qr_pending"
|
||||
task.execution_status = "waiting_bind"
|
||||
task.issue_code = ""
|
||||
@@ -301,15 +324,55 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
|
||||
douyu_task = db.get(DouyuTask, int(douyu_task_id))
|
||||
if douyu_task is None or douyu_task.task_type not in BINDING_SYNC_TASK_TYPES:
|
||||
return len(task_ids)
|
||||
result = douyu_task.result or {}
|
||||
binding = resolve_douyu_binding(
|
||||
douyu_task,
|
||||
account=db.get(Account, int(douyu_task.account_id))
|
||||
if douyu_task.account_id
|
||||
else None,
|
||||
)
|
||||
if (
|
||||
douyu_task.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES
|
||||
or result.get("bind_confirmed") is not True
|
||||
or binding.status != BINDING_VIEW_CONFIRMED
|
||||
):
|
||||
# 查询/出码任务只能证明“账号历史绑定是什么”,不能证明本次订单已经确认。
|
||||
# 只有明确执行成功并回查到 bind_confirmed 的确认任务,才允许把账号权威
|
||||
# 绑定投影到履约任务。
|
||||
return len(task_ids)
|
||||
# 只有明确执行成功并回查到 bind_confirmed 的确认任务,才允许把任务级
|
||||
# 确认事实投影到履约任务。
|
||||
linked = 0
|
||||
if (
|
||||
douyu_task.task_type in PENDING_BINDING_TASK_TYPES
|
||||
and binding.status == BINDING_VIEW_PENDING
|
||||
):
|
||||
active_task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.account_id == int(douyu_task.account_id),
|
||||
PlatformFulfillmentTask.scope == "elite",
|
||||
PlatformFulfillmentTask.binding_status.in_(
|
||||
ACTIVE_PENDING_TASK_STATUSES
|
||||
),
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
("completed", "cancelled", "manual_required")
|
||||
),
|
||||
AccountLease.status == "active",
|
||||
)
|
||||
.order_by(
|
||||
PlatformFulfillmentTask.updated_at.desc(),
|
||||
PlatformFulfillmentTask.id.desc(),
|
||||
)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if active_task is not None and _attach_pending_binding_task(
|
||||
db,
|
||||
active_task,
|
||||
douyu_task,
|
||||
):
|
||||
_apply_task_lease_policy(db, active_task)
|
||||
_emit_order_site_binding_state(db, active_task.id)
|
||||
db.commit()
|
||||
linked = 1
|
||||
return len(task_ids) + linked
|
||||
return len(task_ids) + sync_active_task_from_account_binding(
|
||||
db,
|
||||
account_id=int(douyu_task.account_id),
|
||||
@@ -318,6 +381,83 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
|
||||
)
|
||||
|
||||
|
||||
def _latest_pending_binding_task(
|
||||
db: Session,
|
||||
task: PlatformFulfillmentTask,
|
||||
) -> DouyuTask | None:
|
||||
if (
|
||||
not task.account_id
|
||||
or task.binding_status not in ACTIVE_PENDING_TASK_STATUSES
|
||||
):
|
||||
return None
|
||||
rows = (
|
||||
db.query(DouyuTask)
|
||||
.filter(
|
||||
DouyuTask.account_id == int(task.account_id),
|
||||
DouyuTask.task_type.in_(PENDING_BINDING_TASK_TYPES),
|
||||
DouyuTask.handbook_scope == "elite",
|
||||
DouyuTask.status == "success",
|
||||
)
|
||||
.order_by(DouyuTask.id.desc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
account = db.get(Account, int(task.account_id))
|
||||
for row in rows:
|
||||
if resolve_douyu_binding(
|
||||
row,
|
||||
account=account,
|
||||
).status == BINDING_VIEW_PENDING:
|
||||
return row
|
||||
return None
|
||||
|
||||
|
||||
def _attach_pending_binding_task(
|
||||
db: Session,
|
||||
task: PlatformFulfillmentTask,
|
||||
bind_task: DouyuTask,
|
||||
) -> bool:
|
||||
account = (
|
||||
db.get(Account, int(task.account_id))
|
||||
if task.account_id
|
||||
else None
|
||||
)
|
||||
binding = resolve_douyu_binding(bind_task, account=account)
|
||||
if (
|
||||
task.binding_status not in ACTIVE_PENDING_TASK_STATUSES
|
||||
or not task.account_id
|
||||
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
|
||||
):
|
||||
return False
|
||||
current_id = int(task.bind_task_id or 0)
|
||||
if int(bind_task.id) == current_id:
|
||||
return False
|
||||
if current_id and int(bind_task.id) < current_id:
|
||||
return False
|
||||
previous_bind_task_id = task.bind_task_id
|
||||
task.bind_task_id = int(bind_task.id)
|
||||
task.binding_status = "role_ready"
|
||||
task.execution_status = "role_ready"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
task.updated_at = _now()
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"binding_pending_task_linked",
|
||||
detail={
|
||||
"bindTaskId": int(bind_task.id),
|
||||
"previousBindTaskId": previous_bind_task_id,
|
||||
"roleName": binding.pending_role_name,
|
||||
"source": "account_workbench",
|
||||
},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
return True
|
||||
|
||||
|
||||
def sync_active_task_from_account_binding(
|
||||
db: Session,
|
||||
*,
|
||||
@@ -325,11 +465,12 @@ def sync_active_task_from_account_binding(
|
||||
scope: str,
|
||||
source_task_id: int | None = None,
|
||||
) -> int:
|
||||
"""账号权威绑定已确认时,把当前活跃履约任务同步到 bound。
|
||||
"""确认任务成功后,把当前活跃履约任务同步到 bound。
|
||||
|
||||
精英宝典工作台发出的确认任务不挂在履约任务上,因此不能只看
|
||||
``PlatformFulfillmentTask.bind_task_id``。账号上的绑定状态才是最终事实。
|
||||
只在任务已经识别出待确认角色后同步,避免把账号历史绑定误当成当前订单结果。
|
||||
``PlatformFulfillmentTask.bind_task_id``。这里的唯一事实是确认任务的
|
||||
``result``:只有 ``resolve_douyu_binding`` 返回 confirmed 才允许投影。
|
||||
账号上的 ``role_bind_status`` 只描述当前生效角色,不能证明本订单已确认。
|
||||
"""
|
||||
if scope != "elite":
|
||||
return 0
|
||||
@@ -338,15 +479,19 @@ def sync_active_task_from_account_binding(
|
||||
if source_task_id is not None
|
||||
else None
|
||||
)
|
||||
account = db.get(Account, int(account_id))
|
||||
binding = (
|
||||
resolve_douyu_binding(source_task, account=account)
|
||||
if source_task is not None
|
||||
else None
|
||||
)
|
||||
if (
|
||||
source_task is None
|
||||
or binding is None
|
||||
or source_task.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES
|
||||
or (source_task.result or {}).get("bind_confirmed") is not True
|
||||
or binding.status != BINDING_VIEW_CONFIRMED
|
||||
):
|
||||
return 0
|
||||
account = db.get(Account, int(account_id))
|
||||
if account is None or account.role_bind_status != "bound":
|
||||
return 0
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id)
|
||||
@@ -379,13 +524,25 @@ def sync_active_task_from_account_binding(
|
||||
task.id,
|
||||
"binding_synced_from_account",
|
||||
detail={
|
||||
"accountId": int(account.id),
|
||||
"accountName": account.nickname or account.username,
|
||||
"roleName": str(account.game_name or ""),
|
||||
"gameChannel": str(account.game_channel or ""),
|
||||
"accountId": int(account_id),
|
||||
"accountName": (
|
||||
account.nickname or account.username
|
||||
if account is not None
|
||||
else ""
|
||||
),
|
||||
"roleName": (
|
||||
binding.confirmed_role_name
|
||||
or binding.effective_role_name
|
||||
or binding.current_role_name
|
||||
),
|
||||
"gameChannel": (
|
||||
binding.confirmed_channel
|
||||
or binding.effective_channel
|
||||
or binding.current_channel
|
||||
),
|
||||
"roleChangeAvailableAt": (
|
||||
account.role_change_available_at.isoformat()
|
||||
if account.role_change_available_at
|
||||
if account is not None and account.role_change_available_at
|
||||
else None
|
||||
),
|
||||
"sourceTaskId": source_task_id,
|
||||
|
||||
@@ -24,9 +24,11 @@ from ...models import (
|
||||
User,
|
||||
)
|
||||
from ...permissions import ROLE_LABELS
|
||||
from ..account_binding import (
|
||||
binding_role_from_result,
|
||||
pending_binding_role_from_result,
|
||||
from ..douyu_binding import (
|
||||
BINDING_VIEW_CONFIRMED,
|
||||
BINDING_VIEW_FAILED,
|
||||
BINDING_VIEW_PENDING,
|
||||
resolve_douyu_binding,
|
||||
)
|
||||
from ..file_service import build_file_url
|
||||
from . import classification
|
||||
@@ -362,11 +364,9 @@ def _task_out(
|
||||
)
|
||||
collab_order = resolved.collab_orders.get(int(task.id))
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
bind_result_confirmed = bool(bind_result.get("bind_confirmed"))
|
||||
account_binding_confirmed = bool(
|
||||
bind_result_confirmed
|
||||
and account is not None
|
||||
and account.role_bind_status == "bound"
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
account=account,
|
||||
)
|
||||
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
||||
effective_last_error = _effective_task_message(task, effective_issue)
|
||||
@@ -382,12 +382,6 @@ def _task_out(
|
||||
.limit(1)
|
||||
.scalar()
|
||||
)
|
||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||
pending_role = (
|
||||
""
|
||||
if account_binding_confirmed or task.binding_status == "bound"
|
||||
else pending_binding_role_from_result(bind_result)
|
||||
)
|
||||
sale_mode = classification.normalize_sale_mode(task.sale_mode)
|
||||
availability = classification.availability_state(
|
||||
sale_mode=sale_mode,
|
||||
@@ -486,20 +480,13 @@ def _task_out(
|
||||
"taskType": bind_task.task_type,
|
||||
"status": bind_task.status,
|
||||
"message": bind_task.message,
|
||||
"qrUrl": str(bind_result.get("url") or "") if include_qr else "",
|
||||
"roleName": (
|
||||
str(account.game_name or "")
|
||||
if account_binding_confirmed and account is not None
|
||||
else binding_role_from_result(bind_result)
|
||||
),
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindPhase": str(bind_result.get("bind_phase") or ""),
|
||||
"bindReadyForConfirm": bool(pending_role),
|
||||
"bindConfirmed": bool(
|
||||
account_binding_confirmed
|
||||
or bind_result.get("bind_confirmed")
|
||||
),
|
||||
"qrUrl": binding.qr_url if include_qr else "",
|
||||
"roleName": binding.effective_role_name,
|
||||
"areaName": binding.effective_area_name,
|
||||
"platName": binding.effective_plat_name,
|
||||
"bindPhase": binding.bind_phase,
|
||||
"bindReadyForConfirm": binding.status == BINDING_VIEW_PENDING,
|
||||
"bindConfirmed": binding.bind_confirmed,
|
||||
}
|
||||
if bind_task
|
||||
else None
|
||||
@@ -612,19 +599,24 @@ def _customer_binding_queue_state(
|
||||
return "failed", 0
|
||||
if bind_task is None:
|
||||
return "ready_to_start", 0
|
||||
result = bind_task.result or {}
|
||||
if bool(result.get("bind_confirmed")) or task.binding_status == "bound":
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
)
|
||||
if binding.status == BINDING_VIEW_CONFIRMED:
|
||||
return "confirmed", 0
|
||||
if pending_binding_role_from_result(result):
|
||||
if binding.status == BINDING_VIEW_PENDING:
|
||||
return "role_ready", 0
|
||||
if bind_task.status in {"failed", "error", "stopped"}:
|
||||
if binding.status == BINDING_VIEW_FAILED:
|
||||
return "failed", 0
|
||||
if task.binding_status == "confirming":
|
||||
return "confirming", 1000
|
||||
if bind_task.status in {"planned", "pending"}:
|
||||
return "qr_queued", 1000
|
||||
if result.get("url"):
|
||||
return "waiting_scan", 5000 if result.get("bind_polling") else 0
|
||||
if binding.qr_url:
|
||||
return (
|
||||
"waiting_scan",
|
||||
5000 if (bind_task.result or {}).get("bind_polling") else 0,
|
||||
)
|
||||
return "preparing", 1000
|
||||
|
||||
|
||||
@@ -638,16 +630,9 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
)
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
account = db.get(Account, int(task.account_id)) if task.account_id else None
|
||||
bind_result_confirmed = bool(bind_result.get("bind_confirmed"))
|
||||
account_binding_confirmed = bool(
|
||||
bind_result_confirmed
|
||||
and account is not None
|
||||
and account.role_bind_status == "bound"
|
||||
)
|
||||
pending_role = (
|
||||
""
|
||||
if account_binding_confirmed or task.binding_status == "bound"
|
||||
else pending_binding_role_from_result(bind_result)
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
account=account,
|
||||
)
|
||||
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
||||
lease = (
|
||||
@@ -656,8 +641,6 @@ 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"
|
||||
queue_state, retry_after_ms = _customer_binding_queue_state(
|
||||
task,
|
||||
bind_task,
|
||||
@@ -685,18 +668,11 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
"qrUrl": str(bind_result.get("url") or ""),
|
||||
"qrGeneratedAt": str(bind_result.get("qr_generated_at") or ""),
|
||||
"qrExpiresAt": str(bind_result.get("qr_expires_at") or ""),
|
||||
"roleName": (
|
||||
str(account.game_name or "")
|
||||
if account_binding_confirmed and account is not None
|
||||
else binding_role_from_result(bind_result)
|
||||
),
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindReadyForConfirm": (bool(pending_role) and not binding_failed),
|
||||
"bindConfirmed": bool(
|
||||
binding_confirmed
|
||||
and (account_binding_confirmed or bind_result.get("bind_confirmed"))
|
||||
),
|
||||
"roleName": binding.effective_role_name,
|
||||
"areaName": binding.effective_area_name,
|
||||
"platName": binding.effective_plat_name,
|
||||
"bindReadyForConfirm": binding.status == BINDING_VIEW_PENDING,
|
||||
"bindConfirmed": binding.bind_confirmed,
|
||||
"queueState": queue_state,
|
||||
"retryAfterMs": retry_after_ms,
|
||||
"queueLane": bind_task.queue_lane if bind_task else "",
|
||||
|
||||
@@ -985,12 +985,42 @@ export interface DouyuTaskItem {
|
||||
handbook_scope: "elite" | "esports" | "peace" | "legacy";
|
||||
status: string;
|
||||
message: string;
|
||||
binding: DouyuBindingView;
|
||||
result: Record<string, unknown> | null;
|
||||
created_by: number;
|
||||
created_at: string | null;
|
||||
finished_at: string | null;
|
||||
}
|
||||
|
||||
export interface DouyuBindingView {
|
||||
source_task_id: number | null;
|
||||
source_task_type: string;
|
||||
source_task_status: string;
|
||||
status: 'none' | 'waiting_scan' | 'pending' | 'confirmed' | 'failed';
|
||||
bind_phase: string;
|
||||
pending_role_name: string;
|
||||
pending_area_name: string;
|
||||
pending_plat_name: string;
|
||||
pending_channel: string;
|
||||
confirmed_role_name: string;
|
||||
confirmed_area_name: string;
|
||||
confirmed_plat_name: string;
|
||||
confirmed_channel: string;
|
||||
effective_role_name: string;
|
||||
effective_area_name: string;
|
||||
effective_plat_name: string;
|
||||
effective_channel: string;
|
||||
current_role_name: string;
|
||||
current_area_name: string;
|
||||
current_plat_name: string;
|
||||
current_channel: string;
|
||||
qr_url: string;
|
||||
reported_ready_for_confirm: boolean;
|
||||
bind_confirmed: boolean;
|
||||
bind_ready_for_confirm: boolean;
|
||||
account_bind_status: string;
|
||||
}
|
||||
|
||||
export interface DouyuExchangeResultImage {
|
||||
object_key: string;
|
||||
url: string;
|
||||
|
||||
@@ -130,6 +130,7 @@ const EVENT_LABELS: Record<string, string> = {
|
||||
binding_stale_role_ignored: '忽略账号旧角色',
|
||||
binding_synced_from_account: '同步账号最新角色绑定',
|
||||
binding_false_confirmation_reverted: '纠正误判的账号历史绑定',
|
||||
binding_pending_task_linked: '关联最新待确认角色',
|
||||
eligibility_check_failed: '兑换资格查询失败',
|
||||
eligibility_auto_refresh_failed: '自动刷新兑换资格失败',
|
||||
exchange_eligibility_checked: '刷新兑换资格',
|
||||
@@ -399,6 +400,7 @@ export default function PlatformFulfillmentPage() {
|
||||
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||
const [detail, setDetail] = useState<PlatformFulfillmentDetail | null>(null);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
const [bindingRefreshing, setBindingRefreshing] = useState(false);
|
||||
const [qrOpen, setQrOpen] = useState(false);
|
||||
const [bindingQrImage, setBindingQrImage] = useState('');
|
||||
const [bindingQrLoading, setBindingQrLoading] = useState(false);
|
||||
@@ -827,6 +829,27 @@ export default function PlatformFulfillmentPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const refreshSelectedBinding = async () => {
|
||||
if (!selectedId) return;
|
||||
setBindingRefreshing(true);
|
||||
try {
|
||||
const result = await platformFulfillmentApi.refreshBinding(selectedId);
|
||||
setDetail(result);
|
||||
await loadTasks(true);
|
||||
if (result.task.bindTask?.bindReadyForConfirm) {
|
||||
message.success(
|
||||
`当前待确认角色:${result.task.bindTask.roleName || '-'}`,
|
||||
);
|
||||
} else {
|
||||
message.success('角色绑定状态已刷新');
|
||||
}
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setBindingRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const closeDouyuAction = () => {
|
||||
setDouyuActionBatchId('');
|
||||
setDouyuActionTask(null);
|
||||
@@ -1666,8 +1689,8 @@ export default function PlatformFulfillmentPage() {
|
||||
<Button
|
||||
icon={<SyncOutlined />}
|
||||
disabled={!selected.account || !can('douyu:task')}
|
||||
loading={douyuActionLoading === 'query_game_name'}
|
||||
onClick={() => void runDouyuAccountAction('query_game_name')}
|
||||
loading={bindingRefreshing}
|
||||
onClick={() => void refreshSelectedBinding()}
|
||||
>
|
||||
刷新角色绑定
|
||||
</Button>
|
||||
|
||||
@@ -338,6 +338,17 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
return map;
|
||||
}, [tasks]);
|
||||
|
||||
const latestEliteBindingTaskByAccount = useMemo(() => {
|
||||
const map = new Map<number, DouyuTaskItem>();
|
||||
for (const task of tasks) {
|
||||
if (!['get_bind_qr', 'confirm_bind', 'query_game_name', 'query_change_bind_time']
|
||||
.includes(task.task_type)) continue;
|
||||
const previous = map.get(task.account_id);
|
||||
if (!previous || task.id > previous.id) map.set(task.account_id, task);
|
||||
}
|
||||
return map;
|
||||
}, [tasks]);
|
||||
|
||||
const latestXpdQueryTaskByAccount = useMemo(() => {
|
||||
const map = new Map<number, DouyuTaskItem>();
|
||||
for (const task of tasks) {
|
||||
@@ -400,10 +411,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
&& task.task_type === 'confirm_bind'
|
||||
&& (
|
||||
task.status !== 'success'
|
||||
|| !(
|
||||
resultFlag(task.result, 'bind_confirmed')
|
||||
|| resultFlag(task.result, 'is_bound_act')
|
||||
)
|
||||
|| task.binding?.status !== 'confirmed'
|
||||
)
|
||||
) continue;
|
||||
const wait = resultNumber(task.result, 'change_role_wait_time');
|
||||
@@ -1611,19 +1619,25 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
|
||||
// ---- QR panel derived state ----
|
||||
const qrResult = qrTask?.result || null;
|
||||
const qrUrl = resultText(qrResult, 'url');
|
||||
const qrMiniQrcodeImage = qrTask
|
||||
? (qrImageByTaskId[qrTask.id] || resultText(qrResult, 'mini_qrcode_image'))
|
||||
: '';
|
||||
const qrBindPhase = resultText(qrResult, 'bind_phase');
|
||||
const qrAutoPolling = qrTask?.status === 'running' && qrResult?.bind_polling === true;
|
||||
const isXpdBindTask = qrTask?.task_type === 'get_xpd_bind_qr';
|
||||
const qrBinding = !isXpdBindTask ? qrTask?.binding : null;
|
||||
const qrUrl = !isXpdBindTask
|
||||
? (qrBinding?.qr_url || resultText(qrResult, 'url'))
|
||||
: resultText(qrResult, 'url');
|
||||
const qrBindPhase = !isXpdBindTask
|
||||
? (qrBinding?.bind_phase || resultText(qrResult, 'bind_phase'))
|
||||
: resultText(qrResult, 'bind_phase');
|
||||
const qrQueryTask = qrTask
|
||||
? (isXpdBindTask
|
||||
? (latestXpdQueryTaskByAccount.get(qrTask.account_id) || null)
|
||||
: (latestQueryGameTaskByAccount.get(qrTask.account_id) || null))
|
||||
: null;
|
||||
const qrQueryResult = qrTask && qrQueryTask && qrQueryTask.id > qrTask.id ? qrQueryTask.result : null;
|
||||
const qrQueryBinding = !isXpdBindTask && qrQueryResult ? qrQueryTask?.binding : null;
|
||||
const qrQueryRunning = Boolean(
|
||||
qrQueryTask
|
||||
&& qrTask
|
||||
@@ -1638,7 +1652,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
const qrQueryRoleName = resultText(qrQueryResult, 'role_name');
|
||||
const qrQueryPendingRoleName = resultText(qrQueryResult, 'pending_role_name');
|
||||
const qrQueryIsBoundAct = resultFlag(qrQueryResult, 'is_bound_act') || resultFlag(qrQueryResult, 'bind_confirmed');
|
||||
const qrQueryPending = !isXpdBindTask && Boolean(
|
||||
const qrQueryPending = isXpdBindTask && Boolean(
|
||||
qrQueryResult
|
||||
&& (
|
||||
qrQueryPendingRoleName
|
||||
@@ -1651,44 +1665,43 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
)
|
||||
),
|
||||
);
|
||||
const qrBindReady = (bindReadyForConfirm(qrTask) || qrQueryPending) && !qrXpdBound;
|
||||
const qrQueryConfirmed = isXpdBindTask
|
||||
? qrQueryIsBoundAct
|
||||
: qrQueryBinding?.status === 'confirmed';
|
||||
const qrDisplayBinding = isXpdBindTask
|
||||
? null
|
||||
: (qrBinding?.status === 'pending'
|
||||
? qrBinding
|
||||
: qrQueryBinding?.status === 'pending'
|
||||
? qrQueryBinding
|
||||
: qrBinding?.status === 'confirmed'
|
||||
? qrBinding
|
||||
: null);
|
||||
const qrBindReady = isXpdBindTask
|
||||
? (bindReadyForConfirm(qrTask) || qrQueryPending) && !qrXpdBound
|
||||
: Boolean(qrBinding?.status === 'pending' || qrQueryBinding?.status === 'pending');
|
||||
const qrRoleSourceResult = qrQueryPending
|
||||
? qrQueryResult
|
||||
: ((bindReadyForConfirm(qrTask) || qrXpdBound) ? qrResult : null);
|
||||
// 待确认角色优先用 pending_* 字段(已绑定角色之外的扫码新角色)
|
||||
const qrRoleName = resultText(qrRoleSourceResult, 'pending_role_name') || resultText(qrRoleSourceResult, 'role_name');
|
||||
const qrAreaName = resultText(qrRoleSourceResult, 'pending_area_name') || resultText(qrRoleSourceResult, 'area_name');
|
||||
const qrPlatName = resultText(qrRoleSourceResult, 'pending_plat_name') || resultText(qrRoleSourceResult, 'plat_name');
|
||||
const qrRoleName = isXpdBindTask
|
||||
? (resultText(qrRoleSourceResult, 'pending_role_name') || resultText(qrRoleSourceResult, 'role_name'))
|
||||
: qrDisplayBinding?.effective_role_name || '';
|
||||
const qrAreaName = isXpdBindTask
|
||||
? (resultText(qrRoleSourceResult, 'pending_area_name') || resultText(qrRoleSourceResult, 'area_name'))
|
||||
: qrDisplayBinding?.effective_area_name || '';
|
||||
const qrPlatName = isXpdBindTask
|
||||
? (resultText(qrRoleSourceResult, 'pending_plat_name') || resultText(qrRoleSourceResult, 'plat_name'))
|
||||
: qrDisplayBinding?.effective_plat_name || '';
|
||||
const qrCurrentRoleName = isXpdBindTask
|
||||
? resultText(qrResult, 'before_role_name')
|
||||
: (qrQueryRoleName
|
||||
|| resultText(qrResult, 'current_role_name')
|
||||
|| (
|
||||
resultFlag(qrResult, 'is_bound_act')
|
||||
? resultText(qrResult, 'role_name')
|
||||
: ''
|
||||
)
|
||||
|| (qrQueryIsBoundAct ? qrQueryRoleName : ''));
|
||||
: (qrQueryBinding?.current_role_name || qrBinding?.current_role_name || '');
|
||||
const qrCurrentAreaName = isXpdBindTask
|
||||
? resultText(qrResult, 'before_area_name')
|
||||
: (resultText(qrQueryResult, 'area_name')
|
||||
|| resultText(qrResult, 'current_area_name')
|
||||
|| (
|
||||
resultFlag(qrResult, 'is_bound_act')
|
||||
? resultText(qrResult, 'area_name')
|
||||
: ''
|
||||
)
|
||||
|| (qrQueryIsBoundAct ? resultText(qrQueryResult, 'area_name') : ''));
|
||||
: (qrQueryBinding?.current_area_name || qrBinding?.current_area_name || '');
|
||||
const qrCurrentPlatName = isXpdBindTask
|
||||
? resultText(qrResult, 'before_plat_name')
|
||||
: (resultText(qrQueryResult, 'plat_name')
|
||||
|| resultText(qrResult, 'current_plat_name')
|
||||
|| (
|
||||
resultFlag(qrResult, 'is_bound_act')
|
||||
? resultText(qrResult, 'plat_name')
|
||||
: ''
|
||||
)
|
||||
|| (qrQueryIsBoundAct ? resultText(qrQueryResult, 'plat_name') : ''));
|
||||
: (qrQueryBinding?.current_plat_name || qrBinding?.current_plat_name || '');
|
||||
const qrRoleLine = qrBindReady
|
||||
? [qrPlatName, qrAreaName, qrRoleName].filter(Boolean).join(' - ')
|
||||
: '';
|
||||
@@ -1707,7 +1720,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
? '已识别角色,待确认'
|
||||
: qrQueryRunning
|
||||
? '查询角色中'
|
||||
: qrQueryTask && qrQueryTask.id > (qrTask?.id || 0) && qrQueryTask.status === 'success' && qrQueryIsBoundAct
|
||||
: qrQueryTask && qrQueryTask.id > (qrTask?.id || 0) && qrQueryTask.status === 'success' && qrQueryConfirmed
|
||||
? '查询结果:仍是当前绑定角色'
|
||||
: bindPhaseText(qrBindPhase, qrAutoPolling);
|
||||
const qrAccountName = qrTask
|
||||
@@ -1799,14 +1812,23 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
// 只能取刚跑完的那条查询任务 —— 这不影响「是否已绑定」的判断(那个读账号)。
|
||||
const queryTask = isEsportsHandbook
|
||||
? latestEsportsStateTaskByAccount.get(record.id) || null
|
||||
: latestQueryGameTaskByAccount.get(record.id) || null;
|
||||
: latestEliteBindingTaskByAccount.get(record.id) || null;
|
||||
const queryResult = queryTask?.result || null;
|
||||
const pendingRoleName = scopeState === 'bound' ? '' : resultText(queryResult, 'pending_role_name');
|
||||
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'
|
||||
? ''
|
||||
: [resultText(queryResult, 'pending_area_name'), resultText(queryResult, 'pending_plat_name')]
|
||||
.filter(Boolean)
|
||||
.join(' / ');
|
||||
: (isEsportsHandbook
|
||||
? [resultText(queryResult, 'pending_area_name'), resultText(queryResult, 'pending_plat_name')]
|
||||
.filter(Boolean)
|
||||
.join(' / ')
|
||||
: pendingBinding?.pending_channel || '');
|
||||
|
||||
if (!roleName && !pendingRoleName) {
|
||||
return (
|
||||
|
||||
@@ -170,7 +170,9 @@ export function resultFlag(result: Record<string, unknown> | null | undefined, k
|
||||
// 提取任务结果中的二维码 URL:绑定/电竞绑定用 url,支付类用 pay_url
|
||||
export function taskQrUrl(task: DouyuTaskItem | null | undefined): string {
|
||||
if (!task) return '';
|
||||
if (task.task_type === 'get_bind_qr') return resultText(task.result, 'url');
|
||||
if (task.task_type === 'get_bind_qr') {
|
||||
return task.binding?.qr_url || resultText(task.result, 'url');
|
||||
}
|
||||
if (task.task_type === 'get_xpd_bind_qr') return resultText(task.result, 'url');
|
||||
if (DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type)) {
|
||||
return resultText(task.result, 'pay_url');
|
||||
@@ -183,25 +185,25 @@ export function taskQrUrl(task: DouyuTaskItem | null | undefined): string {
|
||||
|
||||
export function bindReadyForConfirm(task: DouyuTaskItem | null | undefined): boolean {
|
||||
if (!task) return false;
|
||||
if (task.task_type === 'get_bind_qr') {
|
||||
return task.binding?.status === 'pending';
|
||||
}
|
||||
if (task.task_type === 'get_xpd_bind_qr') {
|
||||
if (resultFlag(task.result, 'xpd_bound') || resultFlag(task.result, 'bind_confirmed')) return false;
|
||||
// 轮询识别到角色后停在待确认(xpd_pending_confirm),有角色名即可确认绑定
|
||||
return Boolean(resultText(task.result, 'role_name'));
|
||||
}
|
||||
if (task.task_type !== 'get_bind_qr') return false;
|
||||
if (task.result?.bind_ready_for_confirm === true) return true;
|
||||
const roleName = resultText(task.result, 'role_name');
|
||||
if (!roleName) return false;
|
||||
// 已确认绑定的角色不能再次直接确认
|
||||
if (resultFlag(task.result, 'bind_confirmed') || resultFlag(task.result, 'is_bound_act')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function hasBindQrcode(task: DouyuTaskItem | null | undefined): boolean {
|
||||
if (!task) return false;
|
||||
if (!['get_bind_qr', 'get_xpd_bind_qr'].includes(task.task_type)) return false;
|
||||
if (task.task_type === 'get_bind_qr') {
|
||||
return Boolean(task.binding?.qr_url)
|
||||
|| task.binding?.status === 'pending'
|
||||
|| task.binding?.status === 'confirmed';
|
||||
}
|
||||
// 有二维码,或已有待确认角色(无需再扫码)都应可展示绑定面板
|
||||
return Boolean(resultText(task.result, 'url'))
|
||||
|| bindReadyForConfirm(task)
|
||||
|
||||
Reference in New Issue
Block a user