fix(fulfillment): 角色 7 天锁命中时转人工

- 角色 pending 时查 7 天内是否已绑定其他斗鱼账号
- 命中不调 actBind,订单转 manual_required
- 时间线记录原账号、绑定时间、可复用时间和占用业务
- 确认前和启动对账补充校验,避免存量订单继续尝试
- 补充同账号、超窗口、确认前和启动对账回归测试
This commit is contained in:
yml
2026-11-24 02:10:07 +08:00
parent efb140cf27
commit ad6c31729d
7 changed files with 519 additions and 1 deletions
@@ -279,3 +279,60 @@ WHERE t.binding_status = 'bound'
3. 失败分类把 alias 问题报成“客户角色冷却”,客服无法据此处理。
这三项是下一步修复对象;不要再用“账号级观测”兜底。
### 9.4 修正结论:量的主体是「账号-角色对」的 7 天双边限制
2026-11-24 与业务确认:斗鱼账号 7 天内只能绑定一个角色,用户游戏角色 7 天内
也只能绑定一个斗鱼账号,**两边都限制,约束的是「账号 + 角色」这一对**。
审计证据:
- 订单 7574(履约账号 5616,角色 `半摇枝`)确认失败;
`半摇枝` 已在 2026-11-23 04:08:42 绑定到账号 4454(`bind_ok`,`act_alias=QYOOB`),
4454 当时持有有效的 `douyu_collab` 租约;
- 订单 7605(履约账号 25407,角色 `萌兔界最高的山`)确认失败;
该角色已在 2026-11-23 02:22:39 绑定到账号 4249,4249 当时也持有
`douyu_collab` 租约;
- 近 7 天 381 条“该账号未到可换绑时间”的确认失败中,73 条能在
`account_events.bind_ok` 中找到同一角色在另一账号 7 天内的绑定记录;
14 条能找到同一账号 7 天内绑定过其他角色;0 条是同一账号+同一角色。
(事件缺失的绑定不会出现在这个统计里,73 是下限,不是全量。)
所以精英宝典/协作能“有旧角色也绑定成功”,是因为它在**已经绑定该角色的那个
账号**上操作(同一对);履约每次都按商品能力重新选一个**新的斗鱼账号**,
客户扫码后才第一次知道角色,于是产生了一个新的「账号 + 角色」对,必然撞上
角色侧的 7 天限制。错误分类 `customer_role_cooldown` 本身是对的,错的是履约
**不该用新账号去绑一个已经绑定在别的账号上的角色**。
修复方向(需要产品确认):
1. pending 识别到角色 R 后,先查 R 当前绑定在哪个账号 A(跨履约/协作/精英,
查 `accounts.game_name` + `account_events.bind_ok` + `role_change_available_at`);
2. A 可用 → 把订单切到 A,复用同一对,不再调 `actBind`;
3. A 不可用(被协作单占用)→ 不调 `actBind`,进入等待/人工,并给出 A 和
可复用时间;
4. 账号侧同理:选号前检查 B 最近 7 天是否绑定过其他角色,不能只信
`role_change_available_at`(这些失败账号该字段多为 NULL)。
### 9.5 止血实现(2026-11-24)
先做“命中角色锁 → 转人工”,不做自动切号:
- 新增 `platform_fulfillment/role_lock.py`,`ROLE_LOCK_ISSUE =
customer_role_bound_elsewhere`;
- 角色首次进入 pending、兼容旧 pending 挂接、确认前、启动对账四个入口都会
查:该角色最近 7 天是否已绑在**另一个账号**上;
- 命中即把订单置为 `failed / manual_required`,写事件
`binding_role_locked_elsewhere`,并在 `last_error` 里带上:
原账号、绑定时间、可复用时间、原账号当前被协作单/履约单占用;
- **不再创建确认任务、不调 `actBind`**;人工状态下刷新不会把订单推回 role_ready;
- 同一账号(同一对)和超过 7 天的情况放行,不误伤正常绑定;
- 回归用例:`tests/test_platform_fulfillment.py` 的
`test_pending_role_locked_to_other_account_goes_manual`、
`test_pending_role_bound_to_same_account_is_allowed`、
`test_role_lock_older_than_seven_days_is_allowed`、
`test_confirm_rejects_role_locked_to_other_account`、
`test_startup_reconcile_locks_legacy_role_ready_order`。
仍未做:命中后**自动切回原账号 A**。A 往往被协作单占用,是否等待/复用需要
产品规则;当前先交给人工,避免继续产生 doomed `actBind`。
+207
View File
@@ -2555,6 +2555,213 @@ class TestBindingAndCompletion(_Base):
assert task.bind_task_id == qr_task.id
assert rejection.detail_json["reason"] == "target_mismatch"
def _role_lock_event(self, account, role_name, *, occurred_at=None):
self.session.add(
AccountEvent(
account_id=account.id,
event_type="bind_ok",
category="business",
occurred_at=occurred_at or NOW,
subject_type="elite_role",
subject_key=role_name,
detail={
"scope": "elite",
"role_name": role_name,
"act_alias": "20260120QYOOB",
"rebind": True,
"confirmed": True,
},
source="test",
actor_type="system",
)
)
def _role_lock_pending_task(self, task, role_name):
return DouyuTask(
batch_id=f"role-lock-qr-{task.id}",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"role_name": role_name,
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"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,
)
def test_pending_role_locked_to_other_account_goes_manual(self):
task = self._allocated()
lock_account = self.account("role-lock-holder", capability=False)
lock_account.game_name = "跨账号角色"
lock_account.role_bind_status = "bound"
self.session.add(
AccountLease(
account_id=lock_account.id,
holder_user_id=self.admin_id,
scope="elite",
purpose="douyu_collab",
batch_id="collab:role-lock",
status="active",
)
)
self._role_lock_event(lock_account, "跨账号角色")
self.session.commit()
qr_task = self._role_lock_pending_task(task, "跨账号角色")
self.session.add(qr_task)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=qr_task.id,
)
self.session.refresh(task)
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_role_locked_elsewhere")
.one()
)
assert synced == 1
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
assert task.issue_code == "customer_role_bound_elsewhere"
assert "role-lock-holder" in task.last_error
assert "协作单" in task.last_error
assert event.detail_json["roleLockAccountId"] == lock_account.id
assert event.detail_json["roleLockAccountName"] == "role-lock-holder"
assert event.detail_json["roleLockLeasePurpose"] == "douyu_collab"
assert event.detail_json["sourceTaskId"] == qr_task.id
assert (
self.session.query(DouyuTask)
.filter_by(task_type="confirm_bind")
.count()
== 0
)
# 人工状态下刷新不能把它推回 role_ready。
service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
assert task.issue_code == "customer_role_bound_elsewhere"
def test_pending_role_bound_to_same_account_is_allowed(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "同账号角色"
account.role_bind_status = "bound"
self._role_lock_event(account, "同账号角色")
qr_task = self._role_lock_pending_task(task, "同账号角色")
self.session.add(qr_task)
self.session.commit()
service.sync_task_from_binding_runner(
self.session,
douyu_task_id=qr_task.id,
)
self.session.refresh(task)
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert task.issue_code == ""
def test_role_lock_older_than_seven_days_is_allowed(self):
task = self._allocated()
lock_account = self.account("old-role-holder", capability=False)
lock_account.game_name = "旧锁角色"
lock_account.role_bind_status = "bound"
self._role_lock_event(
lock_account,
"旧锁角色",
occurred_at=NOW - timedelta(days=8),
)
qr_task = self._role_lock_pending_task(task, "旧锁角色")
self.session.add(qr_task)
self.session.commit()
service.sync_task_from_binding_runner(
self.session,
douyu_task_id=qr_task.id,
)
self.session.refresh(task)
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
def test_confirm_rejects_role_locked_to_other_account(self):
task = self._allocated()
lock_account = self.account("confirm-lock-holder", capability=False)
lock_account.game_name = "确认锁角色"
lock_account.role_bind_status = "bound"
self._role_lock_event(lock_account, "确认锁角色")
qr_task = self._role_lock_pending_task(task, "确认锁角色")
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
confirm_count = (
self.session.query(DouyuTask)
.filter_by(task_type="confirm_bind")
.count()
)
detail = service.confirm_binding_sync(
self.session,
task_id=task.id,
current=self.admin,
)
self.session.refresh(task)
assert (
self.session.query(DouyuTask)
.filter_by(task_type="confirm_bind")
.count()
== confirm_count
)
assert detail["task"]["bindingStatus"] == "failed"
assert detail["task"]["issueCode"] == "customer_role_bound_elsewhere"
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
def test_startup_reconcile_locks_legacy_role_ready_order(self):
task = self._allocated()
lock_account = self.account("startup-lock-holder", capability=False)
lock_account.game_name = "启动锁角色"
lock_account.role_bind_status = "bound"
self._role_lock_event(lock_account, "启动锁角色")
qr_task = self._role_lock_pending_task(task, "启动锁角色")
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session)
self.session.refresh(task)
assert reconciled == 1
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
assert task.issue_code == "customer_role_bound_elsewhere"
def test_refresh_binding_attaches_latest_pending_account_workbench_role(self):
task = self._allocated()
old_bind_task = DouyuTask(
@@ -51,6 +51,7 @@ from .repository import (
_load_task,
_load_task_for_update,
)
from .role_lock import ROLE_LOCK_ISSUE, RoleLock, find_role_lock
from .runtime import (
_append_event,
_apply_task_lease_policy,
@@ -335,6 +336,65 @@ def _record_binding_rejection(
)
def _mark_role_locked(
db: Session,
task: PlatformFulfillmentTask,
source: DouyuTask | None,
lock: RoleLock,
) -> bool:
"""角色 7 天内已绑定其他账号:转人工,不调 actBind。"""
if str(task.issue_code or "") == ROLE_LOCK_ISSUE:
return False
message = lock.message()
lease = _lease_for_task(db, task)
if source is not None and int(source.id) > int(task.bind_task_id or 0):
# 保留本次待确认任务,详情/时间线能看到尝试的角色;状态已转人工,
# 不会因为 bind_task_id 变化被自动推回 role_ready。
task.bind_task_id = int(source.id)
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = ROLE_LOCK_ISSUE
task.last_error = message
task.updated_at = _now()
detail = {
"roleName": lock.role_name,
"roleLockAccountId": lock.account_id,
"roleLockAccountName": lock.account_name,
"roleLockBoundAt": lock.bound_at.isoformat(),
"roleLockReusableAt": lock.reusable_at.isoformat(),
"roleLockLeasePurpose": lock.lease_purpose,
"roleLockLeaseBatchId": lock.lease_batch_id,
"allocatedAccountId": task.account_id,
"message": message,
}
if source is not None:
detail["sourceTaskId"] = int(source.id)
detail["sourceTaskType"] = str(source.task_type or "")
_append_event(db, task.id, "binding_role_locked_elsewhere", detail=detail)
_apply_task_lease_policy(db, task, lease=lease)
_emit_order_site_binding_state(db, task.id)
return True
def _block_on_role_lock(
db: Session,
task: PlatformFulfillmentTask,
role_name: str,
source: DouyuTask | None = None,
) -> bool:
"""角色已绑在别的账号上时,把订单转人工;返回是否拦截。"""
if str(task.issue_code or "") == ROLE_LOCK_ISSUE:
return False
lock = find_role_lock(
db,
role_name,
current_account_id=task.account_id,
)
if lock is None:
return False
return _mark_role_locked(db, task, source, lock)
def _apply_binding_qr_display(
db: Session,
task: PlatformFulfillmentTask,
@@ -381,6 +441,9 @@ def _apply_binding_task(
"""
if _frozen(task):
return False
if str(task.issue_code or "") == ROLE_LOCK_ISSUE:
# 角色 7 天锁只能由人工重置后重新进入流程。
return False
if not task.account_id or not source.account_id:
return False
if int(source.account_id) != int(task.account_id):
@@ -550,6 +613,8 @@ def _apply_binding_task(
and not task.last_error
):
return False
if _block_on_role_lock(db, task, role_name, source):
return True
task.bind_task_id = int(source.id)
task.binding_status = "role_ready"
task.execution_status = "role_ready"
@@ -823,6 +888,16 @@ def reconcile_binding_observations(
latest_pending,
):
changed = True
if not changed and task.binding_status == "role_ready":
# 部署前已经 role_ready 的订单:启动时补一次角色 7 天锁检查。
target_role_name = _order_target_role(db, task)
if target_role_name and _block_on_role_lock(
db,
task,
target_role_name,
current,
):
changed = True
if changed:
reconciled += 1
if reconciled:
@@ -899,6 +974,10 @@ def _attach_pending_binding_task(
return False
if current_id and int(bind_task.id) < current_id:
return False
if str(task.issue_code or "") == ROLE_LOCK_ISSUE:
return False
if _block_on_role_lock(db, task, binding.pending_role_name, bind_task):
return True
previous_bind_task_id = task.bind_task_id
task.bind_task_id = int(bind_task.id)
task.binding_status = "role_ready"
@@ -1081,6 +1160,9 @@ def reconcile_binding_state_outbox(
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(db, refresh_binding(db, task_id=task.id)["task"]["id"])
if str(task.issue_code or "") == ROLE_LOCK_ISSUE:
# 刷新时已经判定角色被其他账号占用:直接返回人工状态,不再创建确认任务。
return get_task_detail(db, task.id)
if task.binding_status != "role_ready":
raise HTTPException(status_code=409, detail="当前没有待确认的游戏角色")
if not task.account_id or not task.lease_id:
@@ -1095,6 +1177,16 @@ def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[st
else None
)
current_bind_result = (current_bind_task.result or {}) if current_bind_task else {}
# 兼容部署前已经进入 role_ready 的订单:确认前再查一次角色 7 天锁。
target_role_name = _order_target_role(db, task)
if target_role_name and _block_on_role_lock(
db,
task,
target_role_name,
current_bind_task,
):
db.commit()
return get_task_detail(db, task.id)
expected_role_name = str(current_bind_result.get("role_name") or "").strip()
baseline_role_name = str(current_bind_result.get("current_role_name") or "").strip()
batch_id = f"pfconfirm-{task.id}-{uuid.uuid4().hex[:8]}"
@@ -26,6 +26,7 @@ def _customer_task_message_for(issue_code: str) -> str:
"binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码",
"account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理",
"customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理",
"customer_role_bound_elsewhere": "该游戏角色 7 天内已绑定其他斗鱼账号,请使用原账号或等待",
"eligibility_check_failed": "状态查询异常,请稍后刷新",
"manual_required": "当前需要人工处理,请联系客服",
}
@@ -73,7 +73,12 @@ def manual_reason(issue_code: str, exchange_status: str) -> str:
return "elite_not_opened"
if issue == "commodity_limit_reached" or exchange == "limited":
return "limit_reached"
if issue in {"binding_failed", "account_role_cooldown", "customer_role_cooldown"}:
if issue in {
"binding_failed",
"account_role_cooldown",
"customer_role_cooldown",
"customer_role_bound_elsewhere",
}:
return "binding_failed"
if issue in {"lease_expired", "manual_required"}:
return "account_cooldown"
@@ -0,0 +1,151 @@
"""用户游戏角色的 7 天绑定锁。
斗鱼的绑定限制是**双向**的:
- 一个斗鱼账号 7 天内只能绑定一个游戏角色;
- 一个游戏角色 7 天内也只能绑定一个斗鱼账号。
两个限制约束的都是「账号 + 角色」这一对。履约如果给同一个角色换一个新账号,
就会撞上角色侧限制;精英/协作之所以正常,是因为它们在**已经绑定该角色的那个
账号**上操作,没有产生新的对。
这里只做一件事:在角色已知(二维码识别出 pending)时,查这个角色最近 7 天是否
已经绑在**另一个账号**上。命中就不调 ``actBind``,直接把订单转人工,并把原账号
和可复用时间带给客服。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
from sqlalchemy.orm import Session
from ...models import Account, AccountEvent, AccountLease
#: 新的履约 issue code:用户角色 7 天内已绑定其他斗鱼账号。
ROLE_LOCK_ISSUE = "customer_role_bound_elsewhere"
#: 官方规则窗口。
ROLE_LOCK_WINDOW = timedelta(days=7)
_BEIJING = ZoneInfo("Asia/Shanghai")
_LEASE_PURPOSE_LABELS = {
"douyu_collab": "协作单",
"platform_fulfillment": "履约单",
"exchange": "兑换单",
}
@dataclass(frozen=True)
class RoleLock:
role_name: str
account_id: int
account_name: str
bound_at: datetime
reusable_at: datetime
lease_purpose: str = ""
lease_batch_id: str = ""
@property
def lease_label(self) -> str:
return _LEASE_PURPOSE_LABELS.get(self.lease_purpose, "其他业务")
def message(self) -> str:
bound_at = _beijing_text(self.bound_at)
reusable_at = _beijing_text(self.reusable_at)
if not self.lease_purpose:
lease_text = "原账号当前空闲,可直接复用"
else:
lease_text = f"原账号当前被{self.lease_label}占用"
return (
f"该游戏角色({self.role_name})在 7 天内已绑定斗鱼账号"
f"({self.account_name},{lease_text}),"
f"绑定时间 {bound_at},预计 {reusable_at} 后可再次绑定;"
"请复用原账号或等待。"
)
def _beijing_text(value: datetime) -> str:
moment = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
return moment.astimezone(_BEIJING).strftime("%Y-%m-%d %H:%M")
def find_role_lock(
db: Session,
role_name: str,
*,
current_account_id: int | None,
now: datetime | None = None,
) -> RoleLock | None:
"""返回该角色最近 7 天绑定到的其他账号;同账号/超过 7 天返回 None。"""
role = str(role_name or "").strip()
if not role:
return None
moment = now or datetime.now(UTC)
since = moment - ROLE_LOCK_WINDOW
# 命中 ix_account_events_event_type;bind_ok 只有一万多条,按二维码 pending
# 的频率(每个订单一次)足够。后续量上来再加 (event_type, subject_key,
# occurred_at) 复合索引。
event = (
db.query(AccountEvent)
.filter(
AccountEvent.event_type == "bind_ok",
AccountEvent.subject_type == "elite_role",
AccountEvent.subject_key == role,
AccountEvent.occurred_at >= since,
AccountEvent.occurred_at <= moment,
)
.order_by(AccountEvent.occurred_at.desc(), AccountEvent.id.desc())
.first()
)
if event is None:
return None
if (
current_account_id is not None
and int(event.account_id) == int(current_account_id)
):
# 角色已经绑在本单当前账号上,是同一对,不拦。
return None
account = db.get(Account, int(event.account_id))
if account is not None:
account_name = (
str(account.nickname or "").strip()
or str(account.username or "").strip()
or f"账号#{account.id}"
)
else:
account_name = f"账号#{event.account_id}"
lease = (
db.query(AccountLease)
.filter(
AccountLease.account_id == int(event.account_id),
AccountLease.status == "active",
)
.order_by(AccountLease.leased_at.desc(), AccountLease.id.desc())
.first()
)
bound_at = (
event.occurred_at
if event.occurred_at.tzinfo is not None
else event.occurred_at.replace(tzinfo=UTC)
)
return RoleLock(
role_name=role,
account_id=int(event.account_id),
account_name=account_name,
bound_at=bound_at,
reusable_at=bound_at + ROLE_LOCK_WINDOW,
lease_purpose=str(lease.purpose or "") if lease is not None else "",
lease_batch_id=str(lease.batch_id or "") if lease is not None else "",
)
__all__ = [
"ROLE_LOCK_ISSUE",
"ROLE_LOCK_WINDOW",
"RoleLock",
"find_role_lock",
]
@@ -133,6 +133,7 @@ const EVENT_LABELS: Record<string, string> = {
binding_false_confirmation_reverted: '纠正误判的账号历史绑定',
binding_pending_task_linked: '关联最新待确认角色',
binding_pending_observation_superseded: '旧待确认角色已被最新绑定替换',
binding_role_locked_elsewhere: '用户角色已被其他账号占用',
binding_observation_confirmed: '账号观测确认角色绑定',
binding_confirmed: '履约绑定已确认',
binding_sync_rejected: '忽略不匹配的绑定证据',
@@ -169,6 +170,7 @@ const ISSUE_LABELS: Record<string, string> = {
binding_failed: '绑定失败',
account_role_cooldown: '斗鱼账号仍在换绑冷却期',
customer_role_cooldown: '游戏角色仍在换绑冷却期',
customer_role_bound_elsewhere: '用户角色 7 天内已绑定其他斗鱼账号',
lease_expired: '账号租约已过期',
manual_required: '需要人工处理',
source_cancelled: '来源订单已取消',
@@ -363,6 +365,9 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
const channel = String(detail.confirmedChannel || '');
return `已确认订单角色 ${String(detail.confirmedRoleName || '-')}${channel ? `(${channel})` : ''}`;
}
if (event.eventType === 'binding_role_locked_elsewhere') {
return String(detail.message || `用户角色已被其他账号占用,请复用原账号或等待`);
}
if (event.eventType === 'binding_sync_rejected') {
const reason = String(detail.reason || '');
if (reason === 'target_mismatch') {