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
+13 -1
View File
@@ -37,4 +37,16 @@ def start_douyu_batch(
threading.Thread(target=runner.run, daemon=True).start()
__all__ = ["start_douyu_batch"]
def stop_douyu_batches(batch_ids: list[str]) -> int:
"""向仍在运行的批次发送停止信号,返回实际命中的批次数。"""
stopped = 0
for batch_id in dict.fromkeys(value for value in batch_ids if value):
batch = douyu_batch_registry.get(batch_id)
if not batch or batch.get("finished"):
continue
batch["runner"].stop()
stopped += 1
return stopped
__all__ = ["start_douyu_batch", "stop_douyu_batches"]
+134 -21
View File
@@ -267,6 +267,78 @@ class BindMixin:
results.append(info)
return results
def _role_alias_priority(self, config: dict, primary_alias: str = "") -> list[str]:
"""角色来源优先级:当前动作 alias > cjm/legacy 最新态。"""
ordered = [
primary_alias,
str(config.get("confirm_act_alias") or "").strip(),
str(config.get("bind_act_alias") or "").strip(),
str(config.get("legacy_act_alias") or "").strip(),
]
aliases: list[str] = []
for alias in ordered:
if alias and alias not in aliases:
aliases.append(alias)
return aliases
def _pick_role_info_for_aliases(
self,
candidates: list[dict],
aliases: list[str],
*,
pending_only: bool = False,
exclude_role_name: str = "",
required_role_name: str = "",
) -> dict | None:
"""按 alias 优先级取角色;可排除指定旧角色,只找发生变化的角色。"""
excluded = exclude_role_name.strip().casefold()
required = required_role_name.strip().casefold()
for alias in aliases:
for info in candidates:
if str(info.get("act_alias") or "") != alias:
continue
role_name = str(info.get("role_name") or "").strip()
if not role_name:
continue
if pending_only and self._is_bound_act(info):
continue
if excluded and role_name.casefold() == excluded:
continue
if required and role_name.casefold() != required:
continue
return info
return None
def _pick_target_role_info(
self,
candidates: list[dict],
config: dict,
*,
primary_alias: str = "",
) -> dict | None:
"""选本次操作要确认的角色,优先使用活动 alias 上的新待确认角色。"""
if not candidates:
return None
bound = self._pick_current_bound_info(
candidates,
config,
extra_prefer_aliases=[primary_alias] if primary_alias else None,
)
aliases = self._role_alias_priority(config, primary_alias)
if bound is not None:
changed_pending = self._pick_role_info_for_aliases(
candidates,
aliases,
pending_only=True,
exclude_role_name=str(bound.get("role_name") or ""),
)
return changed_pending or bound
return self._pick_role_info_for_aliases(
candidates,
aliases,
pending_only=True,
) or self._pick_role_info_for_aliases(candidates, aliases)
def _pick_bind_info(
self,
candidates: list[dict],
@@ -345,15 +417,21 @@ class BindMixin:
candidates: list[dict],
config: dict,
) -> dict | None:
"""选“扫码前当前已绑定角色”作为 baseline。
"""选“扫码前当前角色”作为 baseline。
活动 alias(20260120QYOOB)只反映当前已绑定;
cjm 才是换绑最新态。baseline 应优先活动 alias 的已绑定结果,
避免把 cjm 上的待确认新角色误当成扫码前旧角色。
活动 alias(20260120QYOOB)上的已绑定或已选待确认角色都可能是
上一次残留。baseline 必须覆盖这两种状态,否则旧角色会被误判成
本次扫码产生的新角色。
"""
if not candidates:
return None
return self._pick_current_bound_info(candidates, config)
current_bound = self._pick_current_bound_info(candidates, config)
if current_bound is not None:
return current_bound
return self._pick_role_info_for_aliases(
candidates,
self._role_alias_priority(config),
)
def _wait_bind_role_result(
self,
@@ -694,28 +772,59 @@ class BindMixin:
db, task, "failed", "查询绑定信息失败,请检查 Cookie 或 actAlias"
)
return
before = (
self._pick_bind_info(
before_candidates,
baseline_role_name="",
baseline_is_bound_act=False,
prefer_pending=True,
prefer_aliases=query_aliases,
)
or before_candidates[0]
)
before_snapshot = self._bind_snapshot(before)
role_name = before_snapshot["role_name"]
query_alias = str(before.get("act_alias") or "")
# 确认前“已生效绑定”角色(bound_act=1),确认失败/回查失败时写库用,避免待确认角色污染 game_name
before_bound = self._pick_current_bound_info(
before_candidates,
config,
extra_prefer_aliases=[confirm_alias],
)
expected_role_name = str(
(task.result or {}).get("expected_role_name") or ""
).strip()
if expected_role_name:
before = self._pick_role_info_for_aliases(
before_candidates,
self._role_alias_priority(config, confirm_alias),
required_role_name=expected_role_name,
)
else:
before = self._pick_target_role_info(
before_candidates,
config,
primary_alias=confirm_alias,
)
before = before or before_bound or before_candidates[0]
before_snapshot = self._bind_snapshot(before)
role_name = before_snapshot["role_name"]
query_alias = str(before.get("act_alias") or "")
if expected_role_name and role_name.casefold() != expected_role_name.casefold():
self._mark_task(
db,
task,
"failed",
f"待确认角色已变化,未找到: {expected_role_name}",
{
"act_alias": confirm_alias,
"query_act_aliases": query_aliases,
"expected_role_name": expected_role_name,
"bind_ready_for_confirm": False,
"bind_confirmed": False,
"bind_phase": "confirm_failed",
"bind_candidates": [
{
"act_alias": item.get("act_alias"),
"role_name": item.get("role_name"),
"is_bound_act": self._is_bound_act(item),
}
for item in before_candidates
],
},
)
return
self._push_log(
"info",
f"确认前状态 confirm_act={confirm_alias or '-'} hit={query_alias or '-'} "
f"expected={expected_role_name or '-'} "
f"{self._format_bind_summary(before)}",
)
if not role_name:
@@ -1131,10 +1240,14 @@ class BindMixin:
bound_info = self._pick_current_bound_info(candidates, config)
# 2) 待确认角色(cjm 扫码后未确认;无已绑定时也用于首次绑定展示)
pending_info = (
self._pick_bind_info(
self._pick_role_info_for_aliases(
candidates,
prefer_pending=True,
prefer_aliases=query_aliases,
self._role_alias_priority(config),
pending_only=True,
)
or self._pick_role_info_for_aliases(
candidates,
self._role_alias_priority(config),
)
or candidates[0]
)
@@ -29,6 +29,7 @@ def _state_dedupe_key(payload: dict[str, Any]) -> str:
"platName": payload.get("platName"),
"bindReadyForConfirm": payload.get("bindReadyForConfirm"),
"bindConfirmed": payload.get("bindConfirmed"),
"customerProfileReset": payload.get("customerProfileReset"),
}
digest = hashlib.sha256(
json.dumps(state, ensure_ascii=False, sort_keys=True).encode("utf-8")
@@ -26,7 +26,7 @@ from ...models import (
)
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
from ..douyu_activity_query import activity_client, query_exchange_eligibility
from ..douyu_batch_launcher import start_douyu_batch
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
from ..douyu_service import douyu_config_value, ensure_douyu_config
from ..external_order_source import (
OrderLookupUnavailable,
@@ -228,11 +228,19 @@ def _append_event(
)
def _emit_order_site_binding_state(db: Session, task_id: int) -> bool:
def _emit_order_site_binding_state(
db: Session,
task_id: int,
*,
extra: dict[str, Any] | None = None,
) -> bool:
"""当前事务内写 Outbox;HTTP 投递由独立 worker 完成。"""
payload = customer_binding_out(db, task_id)
if extra:
payload.update(extra)
return enqueue_order_site_binding_state(
db,
customer_binding_out(db, task_id),
payload,
)
@@ -573,7 +581,11 @@ def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str:
message = str(bind_task.message or "")
if phase == "change_waiting" or "暂不能换绑" in message:
task_issue = "account_role_cooldown"
elif phase == "confirm_failed" or "待绑定游戏账号" in message or "未到换绑时间" in message:
elif (
phase == "confirm_failed"
or "待绑定游戏账号" in message
or "未到换绑时间" in message
):
task_issue = "customer_role_cooldown"
else:
return "binding_failed"
@@ -599,6 +611,8 @@ 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"
return {
"sessionId": task.id,
"platformOrderId": task.platform_order_id,
@@ -622,8 +636,10 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
),
"areaName": str(bind_result.get("area_name") or ""),
"platName": str(bind_result.get("plat_name") or ""),
"bindReadyForConfirm": bool(bind_result.get("bind_ready_for_confirm")),
"bindConfirmed": bool(bind_result.get("bind_confirmed")),
"bindReadyForConfirm": (
bool(bind_result.get("bind_ready_for_confirm")) and not binding_failed
),
"bindConfirmed": bool(bind_result.get("bind_confirmed")) and binding_confirmed,
"completedAt": _jsonable(task.completed_at),
"updatedAt": _jsonable(task.updated_at),
}
@@ -1015,6 +1031,80 @@ def release_task_account(
return get_task_detail(db, task.id)
def reset_task_binding(
db: Session,
*,
task_id: int,
current: User,
reason: str = "客服重置角色绑定",
) -> dict[str, Any]:
"""清空本单旧绑定与客户资料,保留账号租约供客户重新扫码。"""
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="已结束任务不能重置绑定")
if task.binding_status != "failed":
raise HTTPException(
status_code=409, detail="只有绑定失败的任务可以重置角色资料"
)
if not task.account_id or not task.lease_id:
raise HTTPException(status_code=409, detail="当前任务没有可保留的履约账号")
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if lease is None or lease.status != "active":
raise HTTPException(
status_code=409, detail="账号租约已失效,请释放账号后重新选号"
)
previous_bind_task_id = task.bind_task_id
previous_bind_task = (
db.query(DouyuTask).filter(DouyuTask.id == previous_bind_task_id).first()
if previous_bind_task_id
else None
)
if previous_bind_task and previous_bind_task.status in {
"planned",
"pending",
"running",
}:
raise HTTPException(status_code=409, detail="当前绑定任务仍在执行,不能重置")
previous_binding_status = task.binding_status
previous_issue_code = task.issue_code
task.bind_task_id = None
task.binding_status = "not_started"
task.execution_status = "allocated"
task.exchange_status = "not_started"
task.issue_code = ""
task.last_error = ""
task.operator_id = current.id
task.updated_at = _now()
renew_lease(db, lease, ttl_minutes=_lease_duration_minutes(db))
_append_event(
db,
task.id,
"binding_reset",
actor_type="user",
actor_id=current.id,
detail={
"reason": reason.strip()[:1000],
"previousBindTaskId": previous_bind_task_id,
"previousBindingStatus": previous_binding_status,
"previousIssueCode": previous_issue_code,
"customerProfileReset": True,
},
)
_emit_order_site_binding_state(
db,
task.id,
extra={
"customerProfileReset": True,
"resetReason": reason.strip()[:1000],
},
)
db.commit()
return get_task_detail(db, task.id)
async def start_binding(
db: Session,
*,
@@ -1095,6 +1185,8 @@ async def start_binding(
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)
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()
@@ -1137,10 +1229,7 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
)
if after != before:
task.updated_at = _now()
if task.issue_code in {
"account_role_cooldown",
"customer_role_cooldown",
}:
if task.binding_status == "failed":
_append_event(
db,
task.id,
@@ -1208,6 +1297,14 @@ async def confirm_binding(
if lease is None or lease.status != "active":
raise HTTPException(status_code=409, detail="账号租约已失效")
current_bind_task = (
db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
if task.bind_task_id
else None
)
current_bind_result = (current_bind_task.result or {}) if current_bind_task else {}
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]}"
confirm_task = DouyuTask(
batch_id=batch_id,
@@ -1217,7 +1314,11 @@ async def confirm_binding(
handbook_scope="elite",
status="planned",
message="等待确认角色绑定",
result={"payload": {}},
result={
"payload": {},
"expected_role_name": expected_role_name,
"baseline_role_name": baseline_role_name,
},
created_by=current.id,
)
db.add(confirm_task)
@@ -1399,13 +1500,45 @@ def cancel_task(
reason: str,
) -> dict[str, Any]:
task = _load_task(db, task_id)
if task.execution_status == "cancelled":
return get_task_detail(db, task.id)
if task.execution_status == "completed":
raise HTTPException(status_code=409, detail="已完成任务不能取消")
account_id = task.account_id
lease_id = task.lease_id
lease = (
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if task.lease_id
else None
)
linked_tasks = (
db.query(DouyuTask)
.filter(
DouyuTask.id.in_(
[value for value in [task.bind_task_id, task.exchange_task_id] if value]
)
)
.all()
if task.bind_task_id or task.exchange_task_id
else []
)
stopped_batches = stop_douyu_batches(
[str(linked_task.batch_id or "") for linked_task in linked_tasks]
)
for linked_task in linked_tasks:
if linked_task.status in {"planned", "pending", "running"}:
linked_task.status = "stopped"
linked_task.message = "履约任务已取消"
linked_task.finished_at = _now()
release_lease(db, lease, reason="platform_fulfillment_cancelled")
task.account_id = None
task.lease_id = None
task.bind_task_id = None
task.exchange_task_id = None
task.binding_status = "not_started"
task.execution_status = "cancelled"
task.exchange_status = "not_started"
task.issue_code = ""
task.operator_id = current.id
task.last_error = reason.strip()[:2000]
task.updated_at = _now()
@@ -1415,7 +1548,12 @@ def cancel_task(
"task_cancelled",
actor_type="user",
actor_id=current.id,
detail={"reason": task.last_error},
detail={
"reason": task.last_error,
"releasedAccountId": account_id,
"releasedLeaseId": lease_id,
"stoppedBatches": stopped_batches,
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
@@ -1436,6 +1574,7 @@ __all__ = [
"refresh_binding",
"refresh_exchange_eligibility",
"release_task_account",
"reset_task_binding",
"start_binding",
"sync_pending_tasks",
"sync_pending_tasks_if_due",