feat(fulfillment): 支持选号优先级、三皮肤联合资格捆绑与同角色共享租约

This commit is contained in:
yml
2026-11-28 11:26:24 +08:00
parent ef226c9041
commit 20314a2f1d
24 changed files with 2504 additions and 495 deletions
@@ -3,6 +3,7 @@
from __future__ import annotations
import uuid
from datetime import timedelta
from typing import Any
from fastapi import HTTPException
@@ -13,6 +14,7 @@ from starlette.concurrency import run_in_threadpool
from ...models import (
Account,
AccountEvent,
AccountLease,
DouyuTask,
PlatformFulfillmentEvent,
@@ -115,6 +117,126 @@ BINDING_EVIDENCE_TASK_TYPES = frozenset({"get_bind_qr", "confirm_bind"})
assert BINDING_EVIDENCE_TASK_TYPES <= BINDING_TASK_TYPES
def _can_reuse_existing_account_binding(
db: Session,
*,
task: PlatformFulfillmentTask,
account: Account | None,
) -> str:
"""共享账号若已绑定到本单填写的同一客户角色(且有同租约/7天绑定依据),直接复用绑定。"""
customer_role = str(task.customer_role_name or "").strip()
if not customer_role or account is None or not task.lease_id:
return ""
if str(account.role_bind_status or "") != "bound":
return ""
account_role = str(account.game_name or "").strip()
if not account_role or not role_names_match(account_role, customer_role):
return ""
sibling_bound = (
db.query(PlatformFulfillmentTask.id)
.filter(
PlatformFulfillmentTask.lease_id == int(task.lease_id),
PlatformFulfillmentTask.account_id == int(account.id),
PlatformFulfillmentTask.id != int(task.id),
PlatformFulfillmentTask.execution_status != "cancelled",
PlatformFulfillmentTask.binding_status == "bound",
)
.first()
)
if sibling_bound is not None:
return account_role
since = _now() - timedelta(days=7)
recent_bind = (
db.query(AccountEvent.id)
.filter(
AccountEvent.account_id == int(account.id),
AccountEvent.event_type == "bind_ok",
AccountEvent.subject_type == "elite_role",
AccountEvent.subject_key == account_role,
AccountEvent.occurred_at >= since,
)
.first()
)
return account_role if recent_bind is not None else ""
def _mark_same_role_reused_bound(
db: Session,
*,
task: PlatformFulfillmentTask,
account: Account,
role_name: str,
lease: AccountLease | None = None,
source_task_id: int | None = None,
) -> None:
resolved_lease = lease or _lease_for_task(db, task)
task.binding_status = "bound"
task.execution_status = "bound"
task.issue_code = ""
task.last_error = ""
task.updated_at = _now()
detail: dict[str, Any] = {
"roleName": role_name[:128],
"accountId": int(account.id),
"accountName": account.nickname or account.username or "",
"reason": "same_role_existing_account",
}
if source_task_id is not None:
detail["sourcePlatformTaskId"] = int(source_task_id)
_append_event(
db,
task.id,
"binding_reused_same_role_account",
detail=detail,
)
_apply_task_lease_policy(db, task, lease=resolved_lease)
_emit_order_site_binding_state(db, task.id)
def _propagate_same_role_binding_to_siblings(
db: Session,
*,
bound_task: PlatformFulfillmentTask,
account: Account | None,
role_name: str,
) -> int:
"""同租约主单绑定成功后,把同角色共享账号的其它在途履约单同步置为 bound。"""
if (
not bound_task.lease_id
or not bound_task.account_id
or account is None
or not role_name
):
return 0
siblings = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.lease_id == int(bound_task.lease_id),
PlatformFulfillmentTask.account_id == int(bound_task.account_id),
PlatformFulfillmentTask.id != int(bound_task.id),
PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")),
PlatformFulfillmentTask.binding_status.in_(
ACTIVE_BINDING_STATUSES | {"confirming"}
),
PlatformFulfillmentTask.customer_role_name != "",
)
.all()
)
updated = 0
for sibling in siblings:
if not role_names_match(sibling.customer_role_name, role_name):
continue
_mark_same_role_reused_bound(
db,
task=sibling,
account=account,
role_name=role_name,
source_task_id=int(bound_task.id),
)
updated += 1
return updated
def start_binding_sync(
db: Session,
*,
@@ -128,9 +250,30 @@ def start_binding_sync(
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="账号租约已失效,请重新分配")
account = db.query(Account).filter(Account.id == task.account_id).first()
reused_role = _can_reuse_existing_account_binding(
db,
task=task,
account=account,
)
if reused_role and account is not None:
if task.binding_status != "bound":
task.operator_id = current.id
_mark_same_role_reused_bound(
db,
task=task,
account=account,
role_name=reused_role,
lease=lease,
)
db.commit()
return get_task_detail(db, task.id)
if task.bind_task_id:
existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
if existing is not None and existing.platform_task_id not in (None, int(task.id)):
if existing is not None and existing.platform_task_id not in (
None,
int(task.id),
):
# 当前指针指向了别的订单的任务:当作没有绑定任务,重新出码。
existing = None
if existing:
@@ -344,11 +487,7 @@ def _order_target_role(
优先取当前绑定任务;当前任务已经是确认任务时,从订单自己更新的绑码任务里回看。
只用带订单归属的任务,不看账号历史。
"""
current = (
db.get(DouyuTask, int(task.bind_task_id))
if task.bind_task_id
else None
)
current = db.get(DouyuTask, int(task.bind_task_id)) if task.bind_task_id else None
role = _pending_role_of(current)
if role:
return role
@@ -446,9 +585,7 @@ def _sync_confirmed_observation(
db,
task,
observation,
reason="target_mismatch"
if target_role
else "missing_target",
reason="target_mismatch" if target_role else "missing_target",
confirmed_role=confirmed_role,
target_role=target_role,
)
@@ -490,6 +627,12 @@ def _sync_confirmed_observation(
)
_apply_task_lease_policy(db, task, lease=lease)
_emit_order_site_binding_state(db, task.id)
_propagate_same_role_binding_to_siblings(
db,
bound_task=task,
account=account,
role_name=confirmed_role,
)
changed += 1
return changed
@@ -793,8 +936,10 @@ def _same_pair_reuse_role(
if not isinstance(result, dict) or account is None:
return ""
# 发码预检/轮询未变化阶段绝不复用账号历史角色,必须等扫码完成或观测到扫码变化。
if task_status and task_status != "success" and not bool(
result.get("bind_poll_legacy_observed_change")
if (
task_status
and task_status != "success"
and not bool(result.get("bind_poll_legacy_observed_change"))
):
return ""
if str(account.role_bind_status or "") != "bound":
@@ -814,19 +959,15 @@ def _same_pair_reuse_role(
else []
)
candidates = [
raw
for raw in (result.get("bind_candidates") or [])
if isinstance(raw, dict)
raw for raw in (result.get("bind_candidates") or []) if isinstance(raw, dict)
]
action_candidates = [
raw
for raw in candidates
if str(raw.get("act_alias") or raw.get("alias") or "").strip()
in action_aliases
if str(raw.get("act_alias") or raw.get("alias") or "").strip() in action_aliases
]
if any(
str(raw.get("role_name") or "").strip()
and not bool(raw.get("is_bound_act"))
str(raw.get("role_name") or "").strip() and not bool(raw.get("is_bound_act"))
for raw in action_candidates
):
# 动作 alias 上已有新的 pending:客户扫了新角色,交给正常确认。
@@ -860,10 +1001,9 @@ def _same_pair_reuse_role(
for raw in action_candidates
)
return current if action_bound else ""
if (
(not action_aliases or selected_alias not in action_aliases)
and str(result.get("current_role_name") or "").strip() == current
):
if (not action_aliases or selected_alias not in action_aliases) and str(
result.get("current_role_name") or ""
).strip() == current:
return current
return ""
@@ -891,9 +1031,7 @@ def _mark_reused_pair(
"roleName": role_name[:128],
"accountId": task.account_id,
"accountName": (
(account.nickname or account.username)
if account is not None
else ""
(account.nickname or account.username) if account is not None else ""
),
"sourceTaskId": int(source.id),
"sourceTaskType": str(source.task_type or ""),
@@ -902,6 +1040,12 @@ def _mark_reused_pair(
)
_apply_task_lease_policy(db, task, lease=lease)
_emit_order_site_binding_state(db, task.id)
_propagate_same_role_binding_to_siblings(
db,
bound_task=task,
account=account,
role_name=role_name,
)
return True
@@ -1022,7 +1166,11 @@ def _apply_binding_task(
else ""
)
expected_name = str(
(last_mismatch.get("expected_role_name") if isinstance(last_mismatch, dict) else "")
(
last_mismatch.get("expected_role_name")
if isinstance(last_mismatch, dict)
else ""
)
or task.customer_role_name
or ""
).strip()
@@ -1076,7 +1224,9 @@ def _apply_binding_task(
target_role = _order_target_role(
db,
task,
before_task_id=int(source.id) if source.task_type == "confirm_bind" else None,
before_task_id=int(source.id)
if source.task_type == "confirm_bind"
else None,
)
expected_role = customer_role or explicit_expected or target_role
if is_current:
@@ -1146,9 +1296,7 @@ def _apply_binding_task(
task,
source,
reason=(
reason
if reason != "missing_target"
else "untrusted_confirmation"
reason if reason != "missing_target" else "untrusted_confirmation"
),
confirmed_role=confirmed_role,
target_role=expected_role,
@@ -1180,6 +1328,12 @@ def _apply_binding_task(
)
_apply_task_lease_policy(db, task, lease=lease)
_emit_order_site_binding_state(db, task.id)
_propagate_same_role_binding_to_siblings(
db,
bound_task=task,
account=account,
role_name=confirmed_role,
)
return True
if binding.status == BINDING_VIEW_PENDING:
@@ -1374,9 +1528,7 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
if douyu_task.platform_task_id:
task = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.id == int(douyu_task.platform_task_id)
)
.filter(PlatformFulfillmentTask.id == int(douyu_task.platform_task_id))
.with_for_update()
.first()
)
@@ -1408,9 +1560,7 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
.filter(
PlatformFulfillmentTask.account_id == int(douyu_task.account_id),
PlatformFulfillmentTask.scope == "elite",
PlatformFulfillmentTask.binding_status.in_(
ACTIVE_BINDING_STATUSES
),
PlatformFulfillmentTask.binding_status.in_(ACTIVE_BINDING_STATUSES),
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled", "manual_required")
),
@@ -1460,9 +1610,7 @@ def _revert_false_same_pair_reuse(
PlatformFulfillmentTask.account_id.isnot(None),
PlatformFulfillmentTask.bind_task_id.isnot(None),
PlatformFulfillmentTask.binding_status == "bound",
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled")
),
PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")),
PlatformFulfillmentTask.exchange_status.notin_(
("succeeded", "locked", "submitting")
),
@@ -1491,9 +1639,7 @@ def _revert_false_same_pair_reuse(
)
if reuse_event is None:
continue
reused_role = str(
(reuse_event.detail_json or {}).get("roleName") or ""
).strip()
reused_role = str((reuse_event.detail_json or {}).get("roleName") or "").strip()
customer_role = str(task.customer_role_name or "").strip()
if not customer_role or (
reused_role and role_names_match(reused_role, customer_role)
@@ -1547,9 +1693,7 @@ def reconcile_binding_observations(
PlatformFulfillmentTask.binding_status.in_(
tuple(ACTIVE_BINDING_STATUSES) + ("confirming", "failed")
),
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled")
),
PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")),
)
.order_by(
# role_ready 订单最可能已有新观测可自愈;先处理它们,避免
@@ -1581,9 +1725,7 @@ def reconcile_binding_observations(
reconciled += 1
continue
current = (
db.get(DouyuTask, int(task.bind_task_id))
if task.bind_task_id
else None
db.get(DouyuTask, int(task.bind_task_id)) if task.bind_task_id else None
)
if (
current is not None
@@ -1644,10 +1786,7 @@ def _latest_pending_binding_task(
db: Session,
task: PlatformFulfillmentTask,
) -> DouyuTask | None:
if (
not task.account_id
or task.binding_status not in ACTIVE_BINDING_STATUSES
):
if not task.account_id or task.binding_status not in ACTIVE_BINDING_STATUSES:
return None
lease = _lease_for_task(db, task)
if not lease_is_active(lease):
@@ -1685,11 +1824,7 @@ def _attach_pending_binding_task(
task: PlatformFulfillmentTask,
bind_task: DouyuTask,
) -> bool:
account = (
db.get(Account, int(task.account_id))
if task.account_id
else None
)
account = db.get(Account, int(task.account_id)) if task.account_id else None
lease = _lease_for_task(db, task)
binding = resolve_douyu_binding(bind_task, account=account)
if (
@@ -1758,9 +1893,7 @@ def sync_active_task_from_account_binding(
if scope != "elite":
return 0
source_task = (
db.get(DouyuTask, int(source_task_id))
if source_task_id is not None
else None
db.get(DouyuTask, int(source_task_id)) if source_task_id is not None else None
)
if (
source_task is None
@@ -1779,9 +1912,7 @@ def sync_active_task_from_account_binding(
PlatformFulfillmentTask.account_id == int(account_id),
PlatformFulfillmentTask.scope == "elite",
PlatformFulfillmentTask.binding_status == "role_ready",
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled")
),
PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")),
AccountLease.status == "active",
AccountLease.purpose == "platform_fulfillment",
)
@@ -1836,9 +1967,7 @@ def sync_active_task_from_account_binding(
detail={
"accountId": int(account_id),
"accountName": (
account.nickname or account.username
if account is not None
else ""
account.nickname or account.username if account is not None else ""
),
"roleName": binding.confirmed_role_name,
"gameChannel": (
@@ -1860,6 +1989,7 @@ def sync_active_task_from_account_binding(
db.commit()
return 1
def requires_account_binding_sync(task_type: str) -> bool:
return str(task_type or "") in BINDING_SYNC_TASK_TYPES
@@ -1944,7 +2074,10 @@ def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[st
db.commit()
return get_task_detail(db, task.id)
expected_role_name = str(
task.customer_role_name or target_role_name or current_bind_result.get("role_name") or ""
task.customer_role_name
or target_role_name
or 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]}"
@@ -2096,7 +2229,10 @@ def verify_task_binding_sync(
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 "斗鱼接口查询异常"
err_text = (
";".join(str(x) for x in (role.get("errors") or []) if x)
or "斗鱼接口查询异常"
)
_append_event(
db,
task.id,
@@ -2144,9 +2280,7 @@ def verify_task_binding_sync(
else ""
)
actual_alias = str(
(action_bound or {}).get("act_alias")
or role.get("source_alias")
or ""
(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(
@@ -2184,7 +2318,9 @@ def verify_task_binding_sync(
)
issue_code = "role_changed"
else:
pending_role = str(role.get("pending_role_name") or role.get("role_name") or "").strip()
pending_role = str(
role.get("pending_role_name") or role.get("role_name") or ""
).strip()
mismatch_msg = (
f"斗鱼复核未通过:角色「{pending_role}」仍处于待确认,尚未绑定生效"
if pending_role