Author SHA1 Message Date
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
10 changed files with 191 additions and 15 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 = (
+37 -12
View File
@@ -69,6 +69,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,
@@ -3732,6 +3745,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 +3767,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 +3793,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 +3806,17 @@ 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_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(
@@ -5051,7 +5078,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 +5105,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 +5129,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
@@ -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:
@@ -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,
@@ -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,6 +127,8 @@ 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:
from .auto_allocator import wake_auto_allocator from .auto_allocator import wake_auto_allocator
@@ -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(),
@@ -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'].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' &&