Author SHA1 Message Date
yml d1c8580cf3 修复(履约绑定): 后台人工绑定也必须先有客户游戏资料
- 工作台 start/confirm/代确认/强制确认入口统一校验角色和主页截图
- 仅 clean 任务强制,历史任务保持兼容
- 补充后台绑定资料校验测试
2026-11-25 14:35:20 +08:00
yml 3d8a3ff0fc 修复(履约确认): 扫码角色消失不再误报客户冷却
- confirm 找不到已识别角色时归为 role_changed
- 客户页/工作台允许刷新二维码重新扫码
- 保留账号,避免角色变化被当成换绑冷却
- 补充角色消失分类测试
2026-11-25 14:22:58 +08:00
yml 2d7f605270 Revert "修复(履约选号): 按客户QQ/微信、iOS/安卓和角色优先选号"
This reverts commit 522ab9310c.
2026-11-25 14:14:30 +08:00
yml 522ab9310c 修复(履约选号): 按客户QQ/微信、iOS/安卓和角色优先选号
- 候选账号按客户登录方式和系统过滤,避免微信账号接QQ角色
- 客户角色已绑定的账号优先,且不再被未来换绑时间误排除
- 自动选号传入客户资料
- 补充渠道/角色选择测试
2026-11-25 14:10:42 +08:00
yml eab1d1937a 修复(履约重试): 绑定失败无账号任务允许重新选号
- prepare_manual_allocation 支持 binding_failed/lease_expired 的人工重新选号
- 客户刷新时把任务重置为 ready 并唤醒选号
- 保留客户资料,分配成功后继续启动绑定
- 补充重试测试
2026-11-25 14:04:50 +08:00
yml 18df3443d8 优化(履约租约): 绑定失败保留账号直到人工释放
- clean 任务 binding_failed 租约改为无限期保留
- Reaper 不再自动释放 clean 绑定失败账号,只保留历史任务旧策略
- 迁移 0133 清理存量 clean 绑定失败租约到期时间
- 工作台显示账号保留中并提供人工释放
- 补充租约/回收测试
2026-11-25 13:47:34 +08:00
yml adf2e9a066 优化(履约工作台): 绑定失败且账号已释放时支持重新选号并绑定 2026-11-25 13:37:38 +08:00
yml 8aa4ea7342 修复(履约绑定): 客户资料不全时禁止开始绑定
- 自动选号后不再在缺少游戏主页截图时启动绑定
- 补启动查询只挑资料完整的任务,避免阻塞后续任务
- 客户绑定启动接口校验角色/登录方式/系统/截图
2026-11-25 10:07:14 +08:00
15 changed files with 344 additions and 17 deletions
+1 -1
View File
@@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261124_0132" HEAD_REVISION = "20261125_0133"
# 迁移新增、但不声明在模型里的复合查询索引。 # 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = ( EXTRA_INDEXES = (
+101 -13
View File
@@ -38,6 +38,10 @@ from web.backend.services.automation.jobs import (
platform_fulfillment_lease_reaper as reaper, platform_fulfillment_lease_reaper as reaper,
) )
from web.backend.services.platform_fulfillment import account_selector, service, views from web.backend.services.platform_fulfillment import account_selector, service, views
from web.backend.services.platform_fulfillment.binding_status import (
_binding_failure_issue,
_binding_failure_raw_message,
)
from web.backend.services.platform_fulfillment.order_sync import _apply_customer_profile from web.backend.services.platform_fulfillment.order_sync import _apply_customer_profile
NOW = datetime.now(UTC).replace(microsecond=0) NOW = datetime.now(UTC).replace(microsecond=0)
@@ -69,6 +73,19 @@ class _Base:
views.invalidate_task_list_count_cache() views.invalidate_task_list_count_cache()
self.session.close() self.session.close()
def complete_customer_profile(self, task: PlatformFulfillmentTask) -> None:
task.customer_role_name = "小淋笨"
task.customer_platform = "wechat"
task.customer_system = "android"
task.customer_home_images = [
{
"url": "https://example.com/game-home.png",
"thumbnailUrl": "https://example.com/game-home-thumb.png",
"objectKey": "game-home.png",
}
]
self.session.commit()
def account( def account(
self, self,
name: str, name: str,
@@ -1319,6 +1336,33 @@ class TestAccountSelection(_Base):
assert task.next_allocate_at is not None assert task.next_allocate_at is not None
assert old_retry_at is None or task.next_allocate_at >= old_retry_at assert old_retry_at is None or task.next_allocate_at >= old_retry_at
def test_manual_allocation_allows_rebind_after_released_binding_failure(self):
task = self.task()
task.execution_status = "manual_required"
task.binding_status = "failed"
task.issue_code = "binding_failed"
task.last_error = "绑定二维码已过期"
self.session.commit()
detail = service.prepare_manual_allocation(
self.session,
task_id=task.id,
current=self.admin,
)
self.session.refresh(task)
assert detail["task"]["executionStatus"] == "ready"
assert task.execution_status == "ready"
assert task.binding_status == "not_started"
assert task.issue_code == ""
assert task.next_allocate_at is not None
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_retry_requested")
.count()
== 1
)
def test_capability_match_uses_local_index_without_live_probe(self): def test_capability_match_uses_local_index_without_live_probe(self):
account = self.account("capability-fast", capability=False) account = self.account("capability-fast", capability=False)
task = self.task() task = self.task()
@@ -3347,6 +3391,25 @@ class TestBindingAndCompletion(_Base):
assert detail["customerProfile"]["channelMatched"] is True assert detail["customerProfile"]["channelMatched"] is True
def test_confirm_role_disappeared_is_not_customer_cooldown(self):
result = {
"bind_phase": "confirm_failed",
"expected_role_name": "再说就一坨儿",
"bind_candidates": [
{"act_alias": "cjm", "role_name": ""},
{"act_alias": "20260120QYOOB", "role_name": "小无恩"},
],
}
task = DouyuTask(
message="待确认角色已变化,未找到: 再说就一坨儿",
result=result,
)
assert _binding_failure_issue(task, result) == "role_changed"
assert "扫码角色已失效" in _binding_failure_raw_message(
"role_changed", result
)
def test_customer_profile_requires_home_image(self): def test_customer_profile_requires_home_image(self):
task = self._allocated() task = self._allocated()
with pytest.raises(HTTPException) as exc_info: with pytest.raises(HTTPException) as exc_info:
@@ -3732,6 +3795,7 @@ class TestBindingAndCompletion(_Base):
def test_customer_start_queues_allocation_without_sync_network(self, monkeypatch): def test_customer_start_queues_allocation_without_sync_network(self, monkeypatch):
task = self.task() task = self.task()
self.complete_customer_profile(task)
calls: list[list[int]] = [] calls: list[list[int]] = []
monkeypatch.setattr( monkeypatch.setattr(
"web.backend.services.platform_fulfillment.auto_allocator.wake_auto_allocator", "web.backend.services.platform_fulfillment.auto_allocator.wake_auto_allocator",
@@ -3753,6 +3817,7 @@ class TestBindingAndCompletion(_Base):
def test_customer_start_creates_one_binding_task_and_links_platform(self, monkeypatch): def test_customer_start_creates_one_binding_task_and_links_platform(self, monkeypatch):
task = self._allocated() task = self._allocated()
self.complete_customer_profile(task)
monkeypatch.setattr( monkeypatch.setattr(
service.binding, service.binding,
"enqueue_execution_job", "enqueue_execution_job",
@@ -3778,6 +3843,7 @@ class TestBindingAndCompletion(_Base):
def test_customer_started_binding_does_not_capture_request_loop(self, monkeypatch): def test_customer_started_binding_does_not_capture_request_loop(self, monkeypatch):
task = self._allocated() task = self._allocated()
self.complete_customer_profile(task)
captured: dict[str, object] = {} captured: dict[str, object] = {}
monkeypatch.setattr( monkeypatch.setattr(
service.binding, service.binding,
@@ -3790,6 +3856,26 @@ class TestBindingAndCompletion(_Base):
assert captured["job_type"] == "douyu_binding" assert captured["job_type"] == "douyu_binding"
assert captured["batch_id"].startswith(f"pfbind-{task.id}-") assert captured["batch_id"].startswith(f"pfbind-{task.id}-")
def test_admin_binding_requires_game_home_profile(self):
task = self._allocated()
with pytest.raises(HTTPException) as exc_info:
service.ensure_customer_profile_for_binding(self.session, task_id=task.id)
assert exc_info.value.status_code == 409
self.complete_customer_profile(task)
service.ensure_customer_profile_for_binding(self.session, task_id=task.id)
def test_customer_start_requires_game_home_profile(self):
task = self._allocated()
with pytest.raises(HTTPException) as exc_info:
asyncio.run(
service.customer_start_binding(self.session, task_id=task.id)
)
assert exc_info.value.status_code == 409
assert "游戏主页截图" in str(exc_info.value.detail)
def test_concurrent_start_binding_creates_one_task(self, monkeypatch): def test_concurrent_start_binding_creates_one_task(self, monkeypatch):
task = self._allocated() task = self._allocated()
monkeypatch.setattr( monkeypatch.setattr(
@@ -3799,6 +3885,9 @@ class TestBindingAndCompletion(_Base):
) )
barrier = threading.Barrier(2) barrier = threading.Barrier(2)
errors: list[BaseException] = [] errors: list[BaseException] = []
first_session = make_test_session(self.engine)
first_admin = first_session.get(User, self.admin_id)
assert first_admin is not None
other_session = make_test_session(self.engine) other_session = make_test_session(self.engine)
other_admin = other_session.get(User, self.admin_id) other_admin = other_session.get(User, self.admin_id)
assert other_admin is not None assert other_admin is not None
@@ -3816,12 +3905,13 @@ class TestBindingAndCompletion(_Base):
except BaseException as exc: # noqa: BLE001 - surfaced below except BaseException as exc: # noqa: BLE001 - surfaced below
errors.append(exc) errors.append(exc)
first = threading.Thread(target=start, args=(self.session, self.admin)) first = threading.Thread(target=start, args=(first_session, first_admin))
second = threading.Thread(target=start, args=(other_session, other_admin)) second = threading.Thread(target=start, args=(other_session, other_admin))
first.start() first.start()
second.start() second.start()
first.join(timeout=10) first.join(timeout=10)
second.join(timeout=10) second.join(timeout=10)
first_session.close()
other_session.close() other_session.close()
assert not first.is_alive() assert not first.is_alive()
@@ -5051,7 +5141,7 @@ class TestBindingAndCompletion(_Base):
assert task.execution_status == "manual_required" assert task.execution_status == "manual_required"
assert task.issue_code == "lease_expired" assert task.issue_code == "lease_expired"
def test_binding_failed_lease_uses_bounded_cleanup_ttl(self): def test_clean_binding_failed_lease_is_held_without_expiry(self):
task = self._allocated() task = self._allocated()
account = self.session.get(Account, task.account_id) account = self.session.get(Account, task.account_id)
account.role_bind_status = "unbound" account.role_bind_status = "unbound"
@@ -5078,11 +5168,10 @@ class TestBindingAndCompletion(_Base):
lease = self.session.query(AccountLease).one() lease = self.session.query(AccountLease).one()
self.session.refresh(task) self.session.refresh(task)
assert task.issue_code == "binding_failed" assert task.issue_code == "binding_failed"
assert lease.expires_at is not None assert task.flow_version == 2
assert lease.expires_at >= datetime.now(UTC) + timedelta(minutes=119) assert lease.expires_at is None
assert lease.expires_at <= datetime.now(UTC) + timedelta(minutes=121)
def test_reaper_recovers_stale_binding_failed_unbound_lease(self): def test_reaper_does_not_release_clean_binding_failed_lease(self):
task = self._allocated() task = self._allocated()
lease = self.session.query(AccountLease).one() lease = self.session.query(AccountLease).one()
account = self.session.get(Account, task.account_id) account = self.session.get(Account, task.account_id)
@@ -5103,13 +5192,12 @@ class TestBindingAndCompletion(_Base):
self.session.refresh(task) self.session.refresh(task)
self.session.refresh(lease) self.session.refresh(lease)
assert result["stale_binding_recovered"] == 1 assert result["stale_binding_recovered"] == 0
assert result["expired"] == 1 assert result["expired"] == 0
assert lease.status == "expired" assert lease.status == "active"
assert task.account_id is None assert task.account_id is not None
assert task.lease_id is None assert task.lease_id is not None
assert task.bind_task_id is None assert task.issue_code == "binding_failed"
assert task.issue_code == "lease_expired"
def test_unlimited_lease_is_ignored_by_reaper(self): def test_unlimited_lease_is_ignored_by_reaper(self):
task = self._allocated() task = self._allocated()
@@ -529,6 +529,10 @@
"20261124_0132_fulfillment_flow_version.py": { "20261124_0132_fulfillment_flow_version.py": {
"revision": "20261124_0132", "revision": "20261124_0132",
"sha256": "c32ae403de640251e4ae8d86bd0948c189c3580141f1454490b4798bb286e3a3" "sha256": "c32ae403de640251e4ae8d86bd0948c189c3580141f1454490b4798bb286e3a3"
},
"20261125_0133_binding_failed_hold.py": {
"revision": "20261125_0133",
"sha256": "d282e42776fd9501b5293c2a116ad1467df0ddb1847d950b477086e3ae5440a7"
} }
} }
} }
@@ -0,0 +1,37 @@
"""绑定失败 clean 任务保留账号,取消旧的 120 分钟过期。
只清理 clean 任务已经写入的绑定失败租约到期时间;不改任务状态。
历史任务继续沿用旧策略。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261125_0133"
down_revision: str | None = "20261124_0132"
branch_labels: str | None = None
depends_on: str | None = None
def upgrade() -> None:
op.execute(
sa.text(
"""
UPDATE account_leases l
JOIN platform_fulfillment_tasks t ON t.lease_id = l.id
SET l.expires_at = NULL
WHERE l.purpose = 'platform_fulfillment'
AND l.status = 'active'
AND t.flow_version = 2
AND t.execution_status = 'manual_required'
AND t.issue_code = 'binding_failed'
"""
)
)
def downgrade() -> None:
# 数据策略迁移无法可靠恢复旧的 120 分钟到期时间,保留当前保留策略。
pass
@@ -403,6 +403,7 @@ async def start_binding(
db: Session = Depends(get_db), db: Session = Depends(get_db),
current: User = Depends(require_permission("platform_fulfillment:use")), current: User = Depends(require_permission("platform_fulfillment:use")),
) -> dict[str, Any]: ) -> dict[str, Any]:
service.ensure_customer_profile_for_binding(db, task_id=task_id)
result = await service.start_binding(db, task_id=task_id, current=current) result = await service.start_binding(db, task_id=task_id, current=current)
record_audit( record_audit(
db, db,
@@ -455,6 +456,7 @@ async def confirm_binding(
db: Session = Depends(get_db), db: Session = Depends(get_db),
current: User = Depends(require_permission("platform_fulfillment:use")), current: User = Depends(require_permission("platform_fulfillment:use")),
) -> dict[str, Any]: ) -> dict[str, Any]:
service.ensure_customer_profile_for_binding(db, task_id=task_id)
result = await service.confirm_binding(db, task_id=task_id, current=current) result = await service.confirm_binding(db, task_id=task_id, current=current)
record_audit( record_audit(
db, db,
@@ -474,6 +476,7 @@ def operator_confirm_binding(
current: User = Depends(require_permission("platform_fulfillment:use")), current: User = Depends(require_permission("platform_fulfillment:use")),
) -> dict[str, Any]: ) -> dict[str, Any]:
"""普通人工代确认:客户已扫码但没点确认,运营代为提交正常 actBind。""" """普通人工代确认:客户已扫码但没点确认,运营代为提交正常 actBind。"""
service.ensure_customer_profile_for_binding(db, task_id=task_id)
result = service.operator_confirm_binding_sync( result = service.operator_confirm_binding_sync(
db, db,
task_id=task_id, task_id=task_id,
@@ -498,6 +501,7 @@ def manual_confirm_binding(
current: User = Depends(require_permission("platform_fulfillment:use")), current: User = Depends(require_permission("platform_fulfillment:use")),
) -> dict[str, Any]: ) -> dict[str, Any]:
"""运营人工确认绑定:用于客户已在别处绑定、或账号当前角色已确认的场景。""" """运营人工确认绑定:用于客户已在别处绑定、或账号当前角色已确认的场景。"""
service.ensure_customer_profile_for_binding(db, task_id=task_id)
result = service.manual_confirm_binding_sync( result = service.manual_confirm_binding_sync(
db, db,
task_id=task_id, task_id=task_id,
@@ -13,6 +13,7 @@ from ...platform_fulfillment.account_selector import (
expire_platform_fulfillment_leases, expire_platform_fulfillment_leases,
release_lease, release_lease,
) )
from ...platform_fulfillment.common import FLOW_VERSION_CLEAN
from ...platform_fulfillment.service import binding_failed_lease_ttl_minutes from ...platform_fulfillment.service import binding_failed_lease_ttl_minutes
JOB_KEY = "platform_fulfillment_lease_reaper" JOB_KEY = "platform_fulfillment_lease_reaper"
@@ -41,6 +42,8 @@ def run_platform_fulfillment_lease_reaper(
AccountLease.expires_at.is_(None), AccountLease.expires_at.is_(None),
PlatformFulfillmentTask.execution_status == "manual_required", PlatformFulfillmentTask.execution_status == "manual_required",
PlatformFulfillmentTask.issue_code == "binding_failed", PlatformFulfillmentTask.issue_code == "binding_failed",
# 新流程绑定失败账号保留到人工释放;只清理历史存量。
PlatformFulfillmentTask.flow_version != FLOW_VERSION_CLEAN,
PlatformFulfillmentTask.updated_at <= stale_binding_cutoff, PlatformFulfillmentTask.updated_at <= stale_binding_cutoff,
Account.role_bind_status == "unbound", Account.role_bind_status == "unbound",
) )
@@ -67,6 +70,31 @@ def run_platform_fulfillment_lease_reaper(
.limit(max(1, int(job.batch_size or 500))) .limit(max(1, int(job.batch_size or 500)))
.all() .all()
) )
held_leases: list[AccountLease] = []
if candidate_leases:
held_tasks = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.lease_id.in_(
[int(lease.id) for lease in candidate_leases]
),
PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN,
PlatformFulfillmentTask.execution_status == "manual_required",
PlatformFulfillmentTask.issue_code == "binding_failed",
)
.all()
)
held_lease_ids = {int(task.lease_id) for task in held_tasks if task.lease_id}
held_leases = [
lease for lease in candidate_leases if int(lease.id) in held_lease_ids
]
candidate_leases = [
lease for lease in candidate_leases if int(lease.id) not in held_lease_ids
]
for lease in held_leases:
lease.expires_at = None
if held_leases:
db.flush()
released_ids = {int(lease.id) for lease in candidate_leases} released_ids = {int(lease.id) for lease in candidate_leases}
converted_tasks: dict[int, PlatformFulfillmentTask] = {} converted_tasks: dict[int, PlatformFulfillmentTask] = {}
if candidate_leases: if candidate_leases:
@@ -616,6 +616,34 @@ def prepare_manual_allocation(
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if lease and lease.status == "active": if lease and lease.status == "active":
return get_task_detail(db, task.id) return get_task_detail(db, task.id)
if (
task.execution_status == "manual_required"
and not task.account_id
and not task.lease_id
and task.issue_code in {"binding_failed", "lease_expired", "role_changed"}
):
# 绑定失败账号已释放后,人工触发一次重新选号;
# 客户资料保留,分配成功后 auto allocator 会继续启动绑定。
task.execution_status = "ready"
task.binding_status = "not_started"
task.bind_task_id = None
task.issue_code = ""
task.last_error = ""
task.next_allocate_at = _now()
task.operator_id = current.id
task.updated_at = _now()
task.state_version = int(task.state_version or 0) + 1
_append_event(
db,
task.id,
"binding_retry_requested",
actor_type="user",
actor_id=current.id,
detail={"reason": "manual_reallocate_after_binding_failure"},
)
_emit_order_site_binding_state(db, task.id)
db.flush()
return get_task_detail(db, task.id)
if task.execution_status != "ready": if task.execution_status != "ready":
raise HTTPException(status_code=409, detail="只有待分配任务可以重新选号") raise HTTPException(status_code=409, detail="只有待分配任务可以重新选号")
task.next_allocate_at = _now() task.next_allocate_at = _now()
@@ -10,13 +10,13 @@ from datetime import UTC, datetime, timedelta
from typing import Any from typing import Any
from loguru import logger from loguru import logger
from sqlalchemy import or_ from sqlalchemy import func, or_
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ...database import WorkerSessionLocal from ...database import WorkerSessionLocal
from ...models import PlatformFulfillmentTask from ...models import PlatformFulfillmentTask
from . import service from . import service
from .common import FLOW_VERSION_CLEAN from .common import FLOW_VERSION_CLEAN, _has_game_home_profile
DEFAULT_INTERVAL_SECONDS = 20 DEFAULT_INTERVAL_SECONDS = 20
DEFAULT_MIN_INTERVAL_SECONDS = 5 DEFAULT_MIN_INTERVAL_SECONDS = 5
@@ -194,6 +194,8 @@ def run_auto_allocation_once(
if allocated_task is not None: if allocated_task is not None:
allocated_task.next_allocate_at = None allocated_task.next_allocate_at = None
db.commit() db.commit()
if not _has_game_home_profile(allocated_task):
continue
try: try:
service.start_binding_sync( service.start_binding_sync(
db, db,
@@ -280,6 +282,10 @@ def start_allocated_bindings_once(
PlatformFulfillmentTask.binding_status == "not_started", PlatformFulfillmentTask.binding_status == "not_started",
PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.account_id.isnot(None),
PlatformFulfillmentTask.lease_id.isnot(None), PlatformFulfillmentTask.lease_id.isnot(None),
PlatformFulfillmentTask.customer_role_name != "",
PlatformFulfillmentTask.customer_platform != "",
PlatformFulfillmentTask.customer_system != "",
func.json_length(PlatformFulfillmentTask.customer_home_images) > 0,
) )
.order_by( .order_by(
PlatformFulfillmentTask.updated_at.asc(), PlatformFulfillmentTask.id.asc() PlatformFulfillmentTask.updated_at.asc(), PlatformFulfillmentTask.id.asc()
@@ -292,6 +298,8 @@ def start_allocated_bindings_once(
actor = service._integration_actor(db) actor = service._integration_actor(db)
started = 0 started = 0
for task in rows: for task in rows:
if not _has_game_home_profile(task):
continue
try: try:
service.start_binding_sync( service.start_binding_sync(
db, db,
@@ -44,7 +44,7 @@ from .binding_status import (
_binding_failure_raw_message, _binding_failure_raw_message,
_customer_task_message, _customer_task_message,
) )
from .common import _now from .common import FLOW_VERSION_CLEAN, _has_game_home_profile, _now
from .outbox import _emit_order_site_binding_state from .outbox import _emit_order_site_binding_state
from .repository import ( from .repository import (
_binding_qr_expired, _binding_qr_expired,
@@ -1494,6 +1494,12 @@ def reconcile_binding_state_outbox(
} }
def ensure_customer_profile_for_binding(db: Session, *, task_id: int) -> None:
task = _load_task(db, task_id)
if task.flow_version == FLOW_VERSION_CLEAN and not _has_game_home_profile(task):
raise HTTPException(status_code=409, detail="请先提交游戏角色和游戏主页截图")
def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[str, Any]: def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[str, Any]:
task = _load_task_for_update(db, task_id) task = _load_task_for_update(db, task_id)
task = _load_task(db, refresh_binding(db, task_id=task.id)["task"]["id"]) task = _load_task(db, refresh_binding(db, task_id=task.id)["task"]["id"])
@@ -24,6 +24,7 @@ def _customer_task_message_for(issue_code: str) -> str:
"points_short": "账号正在补充积分,请稍后重试", "points_short": "账号正在补充积分,请稍后重试",
"commodity_limit_reached": "当前商品暂时无法兑换,请联系客服", "commodity_limit_reached": "当前商品暂时无法兑换,请联系客服",
"binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码", "binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码",
"role_changed": "扫码角色已失效,请刷新二维码后重新扫码",
"account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理", "account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理",
"customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理",
"customer_role_bound_elsewhere": "该游戏角色 7 天内已绑定其他斗鱼账号,请使用原账号或等待", "customer_role_bound_elsewhere": "该游戏角色 7 天内已绑定其他斗鱼账号,请使用原账号或等待",
@@ -38,6 +39,32 @@ def _customer_task_message(task: PlatformFulfillmentTask) -> str:
return _customer_task_message_for(task.issue_code) return _customer_task_message_for(task.issue_code)
def _is_role_changed_failure(
phase: str,
message: str,
confirm_error: str,
result: dict[str, Any],
) -> bool:
"""确认时角色凭空消失,不等于客户角色处于换绑冷却。"""
if phase != "confirm_failed":
return False
text = f"{message} {confirm_error}"
if "未找到" in text or "角色已变化" in text or "待确认角色已变化" in text:
return True
expected = str(result.get("expected_role_name") or "").strip()
candidates = result.get("bind_candidates")
if expected and isinstance(candidates, list):
roles = {
str(item.get("role_name") or "").strip().casefold()
for item in candidates
if isinstance(item, dict)
}
roles.discard("")
if roles and expected.casefold() not in roles:
return True
return False
def _binding_failure_raw_message( def _binding_failure_raw_message(
issue_code: str, issue_code: str,
result: dict[str, Any], result: dict[str, Any],
@@ -51,6 +78,9 @@ def _binding_failure_raw_message(
else "" else ""
) )
role_name = str(result.get("role_name") or "") role_name = str(result.get("role_name") or "")
if issue_code == "role_changed":
expected = str(result.get("expected_role_name") or role_name or "-")
return f"扫码角色已失效(原角色: {expected}),请刷新二维码重新扫码"
if issue_code == "account_role_cooldown": if issue_code == "account_role_cooldown":
role_label = before_bound_role or role_name or "当前角色" role_label = before_bound_role or role_name or "当前角色"
return ( return (
@@ -70,6 +100,13 @@ def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str:
message = str(bind_task.message or "") message = str(bind_task.message or "")
confirm_error = str(result.get("confirm_error") or "") confirm_error = str(result.get("confirm_error") or "")
confirm_code = result.get("confirm_error_code") confirm_code = result.get("confirm_error_code")
if _is_role_changed_failure(
phase,
message,
f"{confirm_error} {result.get('bind_phase') or ''}",
result,
):
return "role_changed"
# 原始接口文案是分类的第一事实源。历史任务可能已经写入了错误的 # 原始接口文案是分类的第一事实源。历史任务可能已经写入了错误的
# derived issue_code,不能在刷新时继续让错误派生值覆盖原始响应。 # derived issue_code,不能在刷新时继续让错误派生值覆盖原始响应。
cooldown_kind = classify_bind_cooldown(None, confirm_error) cooldown_kind = classify_bind_cooldown(None, confirm_error)
@@ -141,6 +141,21 @@ def _order_snapshot_from_event(payload: dict[str, Any]) -> dict[str, Any]:
return data if isinstance(data, dict) else payload return data if isinstance(data, dict) else payload
def _has_game_home_profile(task: PlatformFulfillmentTask) -> bool:
"""Clean 任务必须同时有游戏角色、登录方式、系统和至少一张主页截图。"""
images = task.customer_home_images or []
return bool(
str(task.customer_role_name or "").strip()
and str(task.customer_platform or "").strip() in {"wechat", "qq"}
and str(task.customer_system or "").strip() in {"ios", "android"}
and isinstance(images, list)
and any(
isinstance(item, dict) and str(item.get("url") or "").strip()
for item in images
)
)
def _order_match_started_at(db: Session) -> datetime | None: def _order_match_started_at(db: Session) -> datetime | None:
row = ( row = (
db.query(PlatformFulfillmentSetting) db.query(PlatformFulfillmentSetting)
@@ -17,6 +17,7 @@ from .binding import (
refresh_binding, refresh_binding,
start_binding, start_binding,
) )
from .common import FLOW_VERSION_CLEAN, _has_game_home_profile
from .order_sync import sync_order_item_ids from .order_sync import sync_order_item_ids
from .repository import ( from .repository import (
_find_customer_task, _find_customer_task,
@@ -126,8 +127,22 @@ async def customer_start_binding(
return customer_binding_out(db, task.id) return customer_binding_out(db, task.id)
if task.issue_code == "mapping_missing": if task.issue_code == "mapping_missing":
return customer_binding_out(db, task.id) return customer_binding_out(db, task.id)
if task.flow_version == FLOW_VERSION_CLEAN and not _has_game_home_profile(task):
raise HTTPException(status_code=409, detail="请先提交游戏角色和游戏主页截图")
if not task.account_id or not task.lease_id: if not task.account_id or not task.lease_id:
if (
task.execution_status == "manual_required"
and task.issue_code in {"binding_failed", "lease_expired", "role_changed"}
):
from .allocation import prepare_manual_allocation
prepare_manual_allocation(
db,
task_id=task.id,
current=_integration_actor(db),
)
db.commit()
from .auto_allocator import wake_auto_allocator from .auto_allocator import wake_auto_allocator
wake_auto_allocator([int(task.id)]) wake_auto_allocator([int(task.id)])
@@ -28,6 +28,7 @@ from .binding_status import (
) )
from .common import ( from .common import (
BINDING_COOLDOWN_ISSUES, BINDING_COOLDOWN_ISSUES,
FLOW_VERSION_CLEAN,
_jsonable, _jsonable,
_now, _now,
binding_failed_lease_ttl_minutes, binding_failed_lease_ttl_minutes,
@@ -92,6 +93,9 @@ def _lease_policy_for_task(
return "cancelled", 0 return "cancelled", 0
if status == "manual_required": if status == "manual_required":
if task.issue_code == "binding_failed": if task.issue_code == "binding_failed":
# Clean 任务绑定失败时保留账号,直到绑定成功或人工释放。
if task.flow_version == FLOW_VERSION_CLEAN:
return "binding_failed_hold", None
return ( return (
"binding_failed_cleanup", "binding_failed_cleanup",
binding_failed_lease_ttl_minutes(), binding_failed_lease_ttl_minutes(),
@@ -29,6 +29,7 @@ from .allocation import ( # noqa: F401
from .binding import ( # noqa: F401 from .binding import ( # noqa: F401
confirm_binding, confirm_binding,
confirm_binding_sync, confirm_binding_sync,
ensure_customer_profile_for_binding,
manual_confirm_binding_sync, manual_confirm_binding_sync,
operator_confirm_binding_sync, operator_confirm_binding_sync,
reconcile_binding_observations, reconcile_binding_observations,
@@ -457,6 +457,15 @@ function canRefreshBindingQr(task: PlatformFulfillmentTask) {
return !['role_ready', 'bound', 'completed', 'cancelled'].includes(task.executionStatus); return !['role_ready', 'bound', 'completed', 'cancelled'].includes(task.executionStatus);
} }
function canReallocateAndBind(task: PlatformFulfillmentTask) {
return Boolean(
!task.account &&
task.customerProfile &&
task.executionStatus === 'manual_required' &&
['binding_failed', 'lease_expired', 'role_changed'].includes(task.issueCode),
);
}
function canManualConfirmBinding(task: PlatformFulfillmentTask) { function canManualConfirmBinding(task: PlatformFulfillmentTask) {
if (!task.account) return false; if (!task.account) return false;
return !['bound', 'completed', 'cancelled'].includes(task.executionStatus); return !['bound', 'completed', 'cancelled'].includes(task.executionStatus);
@@ -793,6 +802,19 @@ export default function PlatformFulfillmentPage() {
} }
}; };
const releaseHeldAccount = (task: PlatformFulfillmentTask) => {
Modal.confirm({
title: `释放任务 #${task.id} 的保留账号?`,
content:
'绑定失败账号默认保留到绑定成功或人工释放。释放后任务会回到待分配,客户需要重新选号后刷新二维码。',
okText: '释放账号',
okButtonProps: { danger: true },
cancelText: '取消',
onOk: () =>
runTaskAction(() => platformFulfillmentApi.release(task.id)),
});
};
const requestAllocation = async (task: PlatformFulfillmentTask) => { const requestAllocation = async (task: PlatformFulfillmentTask) => {
if (allocatingTaskId !== null) return; if (allocatingTaskId !== null) return;
setAllocatingTaskId(task.id); setAllocatingTaskId(task.id);
@@ -1381,6 +1403,9 @@ export default function PlatformFulfillmentPage() {
<Tag color={bindingStatusColor(task.bindingStatus)}> <Tag color={bindingStatusColor(task.bindingStatus)}>
{bindingStatusLabel(task.bindingStatus)} {bindingStatusLabel(task.bindingStatus)}
</Tag> </Tag>
{task.account && task.bindingStatus === 'failed' ? (
<Tag color="orange">账号保留中</Tag>
) : null}
<Text>{task.bindTask?.roleName || (task.bindTask?.bindPhase === 'role_ready' ? '角色待确认' : '-')}</Text> <Text>{task.bindTask?.roleName || (task.bindTask?.bindPhase === 'role_ready' ? '角色待确认' : '-')}</Text>
{task.bindingStatus === 'bound' ? ( {task.bindingStatus === 'bound' ? (
<Text type="secondary" style={{ fontSize: 12 }}> <Text type="secondary" style={{ fontSize: 12 }}>
@@ -1515,6 +1540,23 @@ export default function PlatformFulfillmentPage() {
刷新二维码 刷新二维码
</Button> </Button>
) : null} ) : null}
{canReallocateAndBind(task) ? (
<Button
size="small"
type="primary"
icon={<UserSwitchOutlined />}
loading={allocatingTaskId === task.id}
disabled={allocatingTaskId !== null && allocatingTaskId !== task.id}
onClick={() => void requestAllocation(task)}
>
重新选号并绑定
</Button>
) : null}
{task.account && task.bindingStatus === 'failed' ? (
<Button size="small" danger onClick={() => releaseHeldAccount(task)}>
释放账号
</Button>
) : null}
{task.executionStatus === 'role_ready' ? ( {task.executionStatus === 'role_ready' ? (
<Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))}> <Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))}>
代客户确认 代客户确认
@@ -1591,6 +1633,16 @@ export default function PlatformFulfillmentPage() {
刷新二维码 刷新二维码
</Button> </Button>
) : null} ) : null}
{selected && canReallocateAndBind(selected) ? (
<Button
type="primary"
icon={<UserSwitchOutlined />}
loading={allocatingTaskId === selected.id}
onClick={() => void requestAllocation(selected)}
>
重新选号并绑定
</Button>
) : null}
{selected && {selected &&
selected.executionStatus !== 'role_ready' && selected.executionStatus !== 'role_ready' &&
selected.executionStatus !== 'bound' && selected.executionStatus !== 'bound' &&