feat(履约绑定): 支持工作台修改客户资料、扫码不匹配时间线及确认后斗鱼复核

This commit is contained in:
yml
2026-11-26 16:23:30 +08:00
parent ed91fb7549
commit 917c11f203
14 changed files with 1293 additions and 19 deletions
@@ -45,7 +45,7 @@ from .binding_status import (
_binding_failure_raw_message,
_customer_task_message,
)
from .common import FLOW_VERSION_CLEAN, _has_game_home_profile, _now
from .common import FLOW_VERSION_CLEAN, SCOPE_ELITE, _has_game_home_profile, _now
from .outbox import _emit_order_site_binding_state
from .repository import (
_binding_qr_expired,
@@ -65,6 +65,18 @@ from .runtime import (
_apply_task_lease_policy,
)
from .views import get_task_detail
from ..douyu_account_probe import (
ROLE_BOUND,
ROLE_ERROR,
ROLE_UNKNOWN,
activity_client,
config_mapping,
elite_action_aliases,
persist_probe_result,
resolve_elite_role,
)
from ..douyu_role_audit import record_role_api_candidates
from ..douyu_service import ensure_douyu_config
BINDING_SYNC_TASK_TYPES = frozenset(
{
@@ -488,6 +500,85 @@ def _latest_observations_for_task(
)
def _record_mismatched_scan_events(
db: Session,
task: PlatformFulfillmentTask,
source: DouyuTask,
) -> bool:
"""把扫码出现的不匹配角色写入时间线(按任务+角色+区服去重)。"""
result = source.result if isinstance(source.result, dict) else {}
entries = [
item
for item in (result.get("mismatched_roles") or [])
if isinstance(item, dict) and str(item.get("role_name") or "").strip()
]
last_entry = result.get("last_mismatched_role")
if (
not entries
and isinstance(last_entry, dict)
and str(last_entry.get("role_name") or "").strip()
):
entries = [last_entry]
if not entries:
return False
existing_events = (
db.query(PlatformFulfillmentEvent.detail_json)
.filter(
PlatformFulfillmentEvent.task_id == int(task.id),
PlatformFulfillmentEvent.event_type == "binding_scanned_role_mismatch",
)
.order_by(PlatformFulfillmentEvent.id.desc())
.limit(50)
.all()
)
seen: set[tuple[int, str, str]] = set()
for row in existing_events:
detail = row[0] if isinstance(row[0], dict) else {}
try:
src_id = int(detail.get("sourceTaskId") or 0)
except (TypeError, ValueError):
src_id = 0
seen.add(
(
src_id,
str(detail.get("scannedRoleName") or "").strip().casefold(),
str(detail.get("channel") or "").strip(),
)
)
appended = False
for entry in entries:
scanned_role = str(entry.get("role_name") or "").strip()
if not scanned_role:
continue
area_name = str(entry.get("area_name") or "").strip()
plat_name = str(entry.get("plat_name") or "").strip()
channel = " / ".join(part for part in (area_name, plat_name) if part)
key = (int(source.id), scanned_role.casefold(), channel)
if key in seen:
continue
seen.add(key)
expected_role = str(
entry.get("expected_role_name") or task.customer_role_name or ""
).strip()
_append_event(
db,
task.id,
"binding_scanned_role_mismatch",
detail={
"sourceTaskId": int(source.id),
"sourceTaskType": str(source.task_type or ""),
"scannedRoleName": scanned_role[:128],
"expectedRoleName": expected_role[:128],
"channel": channel[:128],
"actAlias": str(entry.get("act_alias") or "")[:64],
},
)
appended = True
return appended
def _record_binding_rejection(
db: Session,
task: PlatformFulfillmentTask,
@@ -1012,24 +1103,43 @@ def _apply_binding_task(
)
result = source.result if isinstance(source.result, dict) else {}
previous_bind_task_id = task.bind_task_id
mismatch_recorded = _record_mismatched_scan_events(db, task, source)
if source.status in {"failed", "error", "stopped"}:
# 只有订单当前挂着的任务失败才允许判失败;工作台额外任务失败不能打死订单。
if not is_current:
return False
return mismatch_recorded
if phase not in ACTIVE_BINDING_STATUSES | {"confirming", "failed"}:
return False
return mismatch_recorded
issue_code = _binding_failure_issue(source, result)
if (
task.binding_status == "failed"
and task.issue_code == issue_code
and int(task.bind_task_id or 0) == int(source.id)
):
return False
return mismatch_recorded
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = issue_code
task.last_error = _customer_task_message(task)
last_mismatch = result.get("last_mismatched_role")
mismatched_name = (
str(last_mismatch.get("role_name") or "").strip()
if isinstance(last_mismatch, dict)
else ""
)
expected_name = str(
(last_mismatch.get("expected_role_name") if isinstance(last_mismatch, dict) else "")
or task.customer_role_name
or ""
).strip()
if issue_code == "binding_failed" and mismatched_name:
task.last_error = (
f"已扫到角色「{mismatched_name}」,与下单填写的「{expected_name}」不一致,请核对后修改资料或重扫"
if expected_name
else f"已扫到不匹配角色「{mismatched_name}」,请核对后重扫"
)
else:
task.last_error = _customer_task_message(task)
task.updated_at = _now()
_append_event(
db,
@@ -1052,14 +1162,17 @@ def _apply_binding_task(
if source.status != "success":
# 运行中的绑码任务可以展示二维码,但不能据此推进角色/结算。
return _apply_binding_qr_display(
db,
task,
source,
owned=owned,
is_current=is_current,
phase=phase,
lease=lease,
return (
_apply_binding_qr_display(
db,
task,
source,
owned=owned,
is_current=is_current,
phase=phase,
lease=lease,
)
or mismatch_recorded
)
if binding.status == BINDING_VIEW_CONFIRMED:
@@ -1957,3 +2070,253 @@ async def confirm_binding(
task_id=task_id,
current=current,
)
def verify_task_binding_sync(
db: Session,
*,
task_id: int,
current: User | None = None,
automatic: bool = False,
) -> dict[str, Any]:
"""确认绑定后,向斗鱼实时复核当前账号绑定状态与角色是否一致。"""
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
if automatic:
return get_task_detail(db, task.id)
raise HTTPException(status_code=409, detail="已结束任务无需复核绑定")
if task.binding_status != "bound":
if automatic:
return get_task_detail(db, task.id)
raise HTTPException(status_code=409, detail="当前订单尚未绑定确认,无法复核")
if not task.account_id:
if automatic:
return get_task_detail(db, task.id)
raise HTTPException(status_code=409, detail="当前任务尚未分配账号")
account = db.get(Account, int(task.account_id))
if account is None or not str(account.cookie or "").strip():
if automatic:
_append_event(
db,
task.id,
"binding_verify_error",
actor_type="system",
detail={"error": "账号 Cookie 不可用,跳过自动复核", "automatic": True},
)
db.commit()
return get_task_detail(db, task.id)
raise HTTPException(status_code=409, detail="账号 Cookie 不可用,无法查询斗鱼")
config = config_mapping(ensure_douyu_config(db))
cookie = str(account.cookie or "").strip()
bind_task_id = int(task.bind_task_id) if task.bind_task_id else None
account_id = int(account.id)
client = activity_client(cookie)
try:
role = resolve_elite_role(client, config)
except Exception as exc: # noqa: BLE001
role = {"status": ROLE_ERROR, "errors": [str(exc)], "bind_infos": []}
bind_infos = [
item for item in (role.get("bind_infos") or []) if isinstance(item, dict)
]
if bind_infos:
record_role_api_candidates(
db,
account_id=account_id,
task_id=bind_task_id,
candidates=bind_infos,
scope=SCOPE_ELITE,
stage="fulfillment.verify_binding",
source="platform.verify_binding",
)
task = _load_task_for_update(db, task_id)
account = db.get(Account, int(task.account_id)) if task.account_id else None
if (
account is None
or task.execution_status in {"completed", "cancelled"}
or task.binding_status != "bound"
):
if bind_infos:
db.commit()
return get_task_detail(db, task.id)
role_status = str(role.get("status") or "")
actor_type = "system" if automatic or current is None else "user"
actor_id = None if automatic or current is None else int(current.id)
if role_status in {ROLE_ERROR, ROLE_UNKNOWN}:
err_text = ";".join(str(x) for x in (role.get("errors") or []) if x) or "斗鱼接口查询异常"
_append_event(
db,
task.id,
"binding_verify_error",
actor_type=actor_type,
actor_id=actor_id,
detail={"error": err_text[:500], "automatic": automatic},
)
db.commit()
return get_task_detail(db, task.id)
persist_probe_result(
db,
account,
{
"probe_id": f"pf-verify:{task.id}",
"identity": {"uid": account.uid, "username": account.username},
"session": {},
"elite": {},
"eligibility": {},
"roles": {"elite": role},
"gold": {},
"goods": {},
"errors": {},
},
current=current,
source="platform.verify_binding",
record_event=False,
)
action_aliases = set(elite_action_aliases(config))
action_bound = next(
(
item
for item in bind_infos
if str(item.get("act_alias") or "").strip() in action_aliases
and bool(item.get("is_bound_act"))
and str(item.get("role_name") or "").strip()
),
None,
)
actual_role = (
str((action_bound or role).get("role_name") or "").strip()
if role_status == ROLE_BOUND
else ""
)
actual_alias = str(
(action_bound or {}).get("act_alias")
or role.get("source_alias")
or ""
).strip()
actual_channel = str(role.get("game_channel") or "").strip()
expected_role = str(
task.customer_role_name or _order_target_role(db, task) or ""
).strip()
verified = bool(
role_status == ROLE_BOUND
and actual_role
and (not expected_role or role_names_match(actual_role, expected_role))
)
if verified:
_append_event(
db,
task.id,
"binding_verified",
actor_type=actor_type,
actor_id=actor_id,
detail={
"roleName": actual_role[:128],
"expectedRoleName": expected_role[:128],
"channel": actual_channel[:128],
"actAlias": actual_alias[:64],
"automatic": automatic,
},
)
db.commit()
return get_task_detail(db, task.id)
lease = _lease_for_task(db, task)
if actual_role and expected_role:
mismatch_msg = (
f"斗鱼复核未通过:当前绑定角色为「{actual_role}」,"
f"与订单目标「{expected_role}」不一致"
)
issue_code = "role_changed"
else:
pending_role = str(role.get("pending_role_name") or role.get("role_name") or "").strip()
mismatch_msg = (
f"斗鱼复核未通过:角色「{pending_role}」仍处于待确认,尚未绑定生效"
if pending_role
else "斗鱼复核未通过:斗鱼接口当前显示未绑定生效"
)
issue_code = "binding_failed"
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = issue_code
task.last_error = mismatch_msg
task.updated_at = _now()
_append_event(
db,
task.id,
"binding_verify_failed",
actor_type=actor_type,
actor_id=actor_id,
detail={
"expectedRoleName": expected_role[:128],
"actualRoleName": actual_role[:128],
"actualStatus": role_status,
"channel": actual_channel[:128],
"actAlias": actual_alias[:64],
"message": mismatch_msg,
"automatic": automatic,
},
)
_apply_task_lease_policy(db, task, lease=lease)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
async def verify_task_binding(
db: Session, *, task_id: int, current: User
) -> dict[str, Any]:
return await run_in_threadpool(
verify_task_binding_sync,
db,
task_id=task_id,
current=current,
automatic=False,
)
def verify_active_binding_for_douyu_task(
db: Session,
*,
douyu_task_id: int,
actor_id: int | None = None,
) -> dict[str, Any] | None:
"""confirm_bind 完成后,自动向斗鱼再复核一次对应履约订单的绑定结果。"""
douyu_task = db.get(DouyuTask, int(douyu_task_id))
if (
douyu_task is None
or douyu_task.status != "success"
or str(douyu_task.task_type or "") != "confirm_bind"
or str(douyu_task.handbook_scope or "") != "elite"
):
return None
query = db.query(PlatformFulfillmentTask).filter(
PlatformFulfillmentTask.scope == "elite",
PlatformFulfillmentTask.binding_status == "bound",
PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")),
)
if douyu_task.platform_task_id:
task = query.filter(
PlatformFulfillmentTask.id == int(douyu_task.platform_task_id)
).first()
else:
task = (
query.filter(PlatformFulfillmentTask.bind_task_id == int(douyu_task.id))
.order_by(PlatformFulfillmentTask.id.desc())
.first()
)
if task is None:
return None
actor = db.get(User, int(actor_id)) if actor_id is not None else None
return verify_task_binding_sync(
db,
task_id=int(task.id),
current=actor,
automatic=True,
)