fix(fulfillment): 修正直播账号履约绑定与取消流程

- 按活动 alias 与 cjm 双角色快照建立绑定 baseline,避免旧角色被误判为本次扫码
- 确认绑定任务固化目标角色,禁止回退确认旧角色
- 绑定失败状态优先于旧待确认标记,并支持客服重置客户角色资料
- 取消任务改为终态幂等操作,停止关联批次并默认释放账号和租约
- 补充双角色选择、重置绑定和取消释放账号测试
This commit is contained in:
yml
2026-11-18 10:59:20 +08:00
parent 8ba6379687
commit 1abc0dfdce
9 changed files with 698 additions and 36 deletions
+117
View File
@@ -12,11 +12,42 @@ from web.backend.services.account_binding import (
BIND_UNBOUND,
binding_snapshot,
derive_from_bind_info,
is_pending_binding_role,
is_role_change_cooling,
role_change_available_at,
)
from web.backend.services.douyu_runner_bind import BindMixin
ACT_ALIAS = "20260120QYOOB"
LEGACY_ALIAS = "cjm"
ROLE_CONFIG = {
"legacy_act_alias": LEGACY_ALIAS,
"confirm_act_alias": ACT_ALIAS,
"bind_act_alias": ACT_ALIAS,
}
class _RolePicker(BindMixin):
pass
def _role_candidate(
alias: str,
role_name: str,
*,
bound_act: bool = False,
) -> dict[str, Any]:
return {
"act_alias": alias,
"role_name": role_name,
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": bound_act,
"need_bind_act": True,
"need_bind_role": True,
}
def _payload(
@@ -118,6 +149,92 @@ def test_scanned_role_is_pending_until_act_bind():
assert snapshot["game_channel"] == "微信 / 苹果(iOS)"
def test_existing_pending_role_is_baseline_not_new_scan_result():
old_role = "狗鼻子弗尼亚bd"
candidates = [
_role_candidate(LEGACY_ALIAS, old_role),
_role_candidate(ACT_ALIAS, old_role),
]
picker = _RolePicker()
baseline = picker._pick_baseline_bind_info(candidates, ROLE_CONFIG)
assert baseline is not None
assert baseline["act_alias"] == ACT_ALIAS
assert baseline["role_name"] == old_role
assert not is_pending_binding_role(
candidates[0],
baseline_role_name=old_role,
baseline_is_bound_act=False,
)
assert not is_pending_binding_role(
candidates[1],
baseline_role_name=old_role,
baseline_is_bound_act=False,
)
def test_new_role_wins_when_cjm_and_activity_snapshots_differ():
old_role = "狗鼻子弗尼亚bd"
new_role = "我是火星人2222"
candidates = [
_role_candidate(LEGACY_ALIAS, old_role),
_role_candidate(ACT_ALIAS, new_role),
]
picker = _RolePicker()
selected = picker._pick_bind_info(
candidates,
baseline_role_name=old_role,
baseline_is_bound_act=False,
prefer_pending=True,
prefer_aliases=[LEGACY_ALIAS, ACT_ALIAS],
)
target = picker._pick_target_role_info(candidates, ROLE_CONFIG)
assert selected is not None
assert selected["act_alias"] == ACT_ALIAS
assert selected["role_name"] == new_role
assert target is not None
assert target["role_name"] == new_role
def test_changed_cjm_role_wins_over_old_bound_activity_role():
old_role = "狗鼻子弗尼亚bd"
new_role = "我是火星人2222"
candidates = [
_role_candidate(LEGACY_ALIAS, new_role),
_role_candidate(ACT_ALIAS, old_role, bound_act=True),
]
picker = _RolePicker()
target = picker._pick_target_role_info(candidates, ROLE_CONFIG)
assert target is not None
assert target["act_alias"] == LEGACY_ALIAS
assert target["role_name"] == new_role
def test_expected_role_never_falls_back_to_old_activity_role():
old_role = "狗鼻子弗尼亚bd"
new_role = "我是火星人2222"
candidates = [
_role_candidate(LEGACY_ALIAS, new_role),
_role_candidate(ACT_ALIAS, old_role),
]
picker = _RolePicker()
selected = picker._pick_role_info_for_aliases(
candidates,
[ACT_ALIAS, LEGACY_ALIAS],
required_role_name=new_role,
)
assert selected is not None
assert selected["act_alias"] == LEGACY_ALIAS
assert selected["role_name"] == new_role
def test_act_bind_is_the_single_final_bound_signal():
can_change_time = 1_795_449_600
parsed = _parse(
+195
View File
@@ -16,7 +16,9 @@ from web.backend.models import (
AutomationJob,
DouyuGoodsSnapshot,
DouyuTask,
IntegrationOutbox,
PlatformCommodityMapping,
PlatformFulfillmentEvent,
PlatformFulfillmentTask,
User,
)
@@ -464,6 +466,192 @@ class TestBindingAndCompletion(_Base):
assert task.issue_code == ""
assert task.last_error == ""
def test_confirm_binding_pins_expected_role_for_two_role_snapshot(
self, monkeypatch
):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-two-roles",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
message="已识别待确认角色",
result={
"role_name": "我是火星人2222",
"current_role_name": "狗鼻子弗尼亚bd",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
monkeypatch.setattr(service, "start_douyu_batch", lambda **_kwargs: None)
asyncio.run(
service.confirm_binding(
self.session,
task_id=task.id,
current=self.admin,
)
)
confirm_task = (
self.session.query(DouyuTask)
.filter(DouyuTask.task_type == "confirm_bind")
.order_by(DouyuTask.id.desc())
.first()
)
assert confirm_task is not None
assert confirm_task.result["expected_role_name"] == "我是火星人2222"
assert confirm_task.result["baseline_role_name"] == "狗鼻子弗尼亚bd"
def test_reset_binding_clears_failed_state_and_keeps_account(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-reset",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="failed",
message="该游戏角色仍在换绑冷却期",
result={"bind_phase": "confirm_failed"},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "failed"
task.execution_status = "manual_required"
task.exchange_status = "not_started"
task.issue_code = "customer_role_cooldown"
task.last_error = "该游戏角色仍在换绑冷却期"
self.session.commit()
account_id = task.account_id
lease_id = task.lease_id
detail = service.reset_task_binding(
self.session,
task_id=task.id,
current=self.admin,
reason="客服核对后重置角色资料",
)
self.session.refresh(task)
assert detail["task"]["executionStatus"] == "allocated"
assert task.account_id == account_id
assert task.lease_id == lease_id
assert task.bind_task_id is None
assert task.binding_status == "not_started"
assert task.issue_code == ""
assert task.last_error == ""
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_reset")
.one()
)
assert event.detail_json["customerProfileReset"] is True
outbox = (
self.session.query(IntegrationOutbox)
.order_by(IntegrationOutbox.id.desc())
.first()
)
assert outbox is not None
assert outbox.payload_json["items"][0]["customerProfileReset"] is True
def test_reset_binding_rejects_running_bind_task(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-running",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
message="等待客户扫码",
result={"url": "https://example.com/qr"},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "failed"
task.execution_status = "waiting_bind"
self.session.commit()
with pytest.raises(HTTPException) as exc_info:
service.reset_task_binding(
self.session,
task_id=task.id,
current=self.admin,
)
assert exc_info.value.status_code == 409
assert "仍在执行" in str(exc_info.value.detail)
def test_cancel_releases_account_and_terminal_state_cannot_be_refreshed_back(
self, monkeypatch
):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-cancel",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
message="等待客户扫码",
result={"url": "https://example.com/qr"},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
account_id = task.account_id
lease_id = task.lease_id
stopped: list[str] = []
monkeypatch.setattr(
service,
"stop_douyu_batches",
lambda batch_ids: stopped.extend(batch_ids) or len(batch_ids),
)
detail = service.cancel_task(
self.session,
task_id=task.id,
current=self.admin,
reason="运营取消并释放账号",
)
self.session.refresh(task)
self.session.refresh(bind_task)
lease = self.session.query(AccountLease).filter_by(id=lease_id).one()
assert detail["task"]["executionStatus"] == "cancelled"
assert task.account_id is None
assert task.lease_id is None
assert task.bind_task_id is None
assert task.binding_status == "not_started"
assert task.exchange_status == "not_started"
assert account_id is not None
assert lease.status == "released"
assert bind_task.status == "stopped"
assert stopped == ["bind-cancel"]
refreshed = service.refresh_binding(self.session, task_id=task.id)
assert refreshed["task"]["executionStatus"] == "cancelled"
self.session.refresh(task)
assert task.execution_status == "cancelled"
def test_refresh_binding_maps_role_ready(self, monkeypatch):
notified: list[int] = []
monkeypatch.setattr(
@@ -556,6 +744,11 @@ class TestBindingAndCompletion(_Base):
assert detail["task"]["executionStatus"] == "manual_required"
assert "截图" in detail["task"]["lastError"]
assert "联系客服" in detail["task"]["lastError"]
live = service.customer_binding_out(self.session, task.id)
assert live["bindingStatus"] == "failed"
assert live["executionStatus"] == "manual_required"
assert live["bindReadyForConfirm"] is False
assert live["bindConfirmed"] is False
def test_refresh_binding_classifies_account_role_cooldown(self):
task = self._allocated()
@@ -585,6 +778,8 @@ class TestBindingAndCompletion(_Base):
assert detail["task"]["issueCode"] == "account_role_cooldown"
assert detail["task"]["executionStatus"] == "manual_required"
assert "截图" in detail["task"]["lastError"]
live = service.customer_binding_out(self.session, task.id)
assert live["bindReadyForConfirm"] is False
def test_list_hides_qr_but_detail_returns_it(self):
task = self._allocated()