fix(fulfillment): 支持先分配后补角色或撞锁时的同角色自动合并改挂

This commit is contained in:
yml
2026-11-28 16:17:04 +08:00
parent 82f2cc21ac
commit f23ef42e67
5 changed files with 667 additions and 93 deletions
@@ -15,6 +15,7 @@ from ...models import (
AccountCommodityState,
AccountEvent,
AccountLease,
DouyuTask,
PlatformFulfillmentTask,
User,
)
@@ -391,6 +392,7 @@ def _apply_allocated_account_state(
valid_until: datetime | None = None,
extra_event_detail: dict[str, Any] | None = None,
already_bound_role: str = "",
commit: bool = True,
) -> dict[str, Any]:
stale_leases = (
db.query(AccountLease)
@@ -475,6 +477,8 @@ def _apply_allocated_account_state(
},
)
_emit_order_site_binding_state(db, task.id)
if not commit:
return {}
db.commit()
return get_task_detail(db, task.id)
@@ -514,26 +518,23 @@ def _account_meets_commodity_eligibility(
)
def _try_reuse_same_role_account(
def _find_reusable_same_role_target(
db: Session,
*,
task: PlatformFulfillmentTask,
current: User,
role: str,
policy: dict[str, Any],
required_co: tuple[str, ...],
moment: datetime,
preferred_account_ids: tuple[int, ...] = (),
) -> dict[str, Any] | None:
"""同客户角色多单时,优先复用已分配/已绑定的同一斗鱼账号,避免撞 7 天角色锁。"""
if not policy.get("sameRoleReuseEnabled", True):
return None
role = str(task.customer_role_name or "").strip()
if not role:
"""查找可与当前订单同客户角色合并/复用的目标斗鱼账号(不改动当前订单)。"""
if not policy.get("sameRoleReuseEnabled", True) or not role:
return None
scope = task.scope or SCOPE_ELITE
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
required_points = int(task.required_points or 0)
since_365 = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
sibling_rows = (
db.query(PlatformFulfillmentTask)
@@ -555,6 +556,9 @@ def _try_reuse_same_role_account(
.all()
)
candidate_account_ids: list[int] = []
for preferred_id in preferred_account_ids:
if preferred_id and int(preferred_id) not in candidate_account_ids:
candidate_account_ids.append(int(preferred_id))
for row in sibling_rows:
if row.account_id and int(row.account_id) not in candidate_account_ids:
candidate_account_ids.append(int(row.account_id))
@@ -564,7 +568,10 @@ def _try_reuse_same_role_account(
if not candidate_account_ids:
return None
current_account_id = int(task.account_id) if task.account_id else 0
for candidate_account_id in candidate_account_ids:
if current_account_id and int(candidate_account_id) == current_account_id:
continue
account = db.get(Account, int(candidate_account_id))
if account is None:
continue
@@ -660,6 +667,8 @@ def _try_reuse_same_role_account(
reused_existing_lease = False
sibling_ids: list[int] = []
sibling_bound = False
has_active_qr_sibling = False
earliest_sibling_id: int | None = None
if active_lease is not None:
if active_lease.purpose != "platform_fulfillment":
continue
@@ -680,93 +689,330 @@ def _try_reuse_same_role_account(
for holder in holders
):
continue
lease = active_lease
reused_existing_lease = True
sibling_ids = [int(holder.id) for holder in holders]
sibling_bound = any(holder.binding_status == "bound" for holder in holders)
has_active_qr_sibling = any(
holder.binding_status
in {
"preparing",
"qr_pending",
"waiting_bind",
"role_ready",
"confirming",
}
for holder in holders
)
earliest_sibling_id = min(sibling_ids)
elif active_collab is not None:
continue
else:
if active_collab is not None:
continue
candidate_model = AccountCandidate(
account_id=int(account.id),
username=str(account.username or ""),
nickname=str(account.nickname or ""),
points=int(account.points or 0),
gold_balance=account.gold_balance,
points_expire_at=account.points_expire_at,
role_change_available_at=account.role_change_available_at,
)
lease = lease_account(
db,
candidate=candidate_model,
holder_user_id=current.id,
task_id=task.id,
commodity_id=task.commodity_id,
ttl_minutes=_lease_duration_minutes(db),
commit=False,
)
if lease is None:
continue
acc_siblings = [
row
for row in sibling_rows
if int(row.account_id or 0) == int(account.id)
]
if acc_siblings:
sibling_bound = any(
row.binding_status == "bound" for row in acc_siblings
)
earliest_sibling_id = min(int(row.id) for row in acc_siblings)
role_lock_matches = bool(
role_lock is not None and int(role_lock.account_id) == int(account.id)
)
already_bound_role = ""
if (
if sibling_bound:
already_bound_role = account_role or role
elif (
str(account.role_bind_status or "") == "bound"
and account_role
and role_names_match(account_role, role)
and (
sibling_bound
or (
role_lock is not None
and int(role_lock.account_id) == int(account.id)
)
)
and role_lock_matches
):
already_bound_role = account_role
account_name = account.nickname or account.username or f"#{account.id}"
availability = allocation_availability(
primary_state.account_eligibility,
primary_state.offer_state,
)
cached_state = DouyuLiveAccountState(
return {
"account": account,
"primary_state": primary_state,
"active_lease": active_lease,
"reused_existing_lease": reused_existing_lease,
"sibling_ids": sibling_ids,
"sibling_bound": sibling_bound,
"has_active_qr_sibling": has_active_qr_sibling,
"earliest_sibling_id": earliest_sibling_id,
"role_lock_matches": role_lock_matches,
"already_bound_role": already_bound_role,
}
return None
def _attach_task_to_same_role_target(
db: Session,
*,
task: PlatformFulfillmentTask,
target: dict[str, Any],
role: str,
current: User,
moment: datetime,
extra_event_detail: dict[str, Any] | None = None,
commit: bool = True,
) -> dict[str, Any] | None:
account: Account = target["account"]
primary_state: AccountCommodityState = target["primary_state"]
lease: AccountLease | None = target["active_lease"]
reused_existing_lease: bool = bool(target["reused_existing_lease"])
sibling_ids: list[int] = list(target["sibling_ids"])
already_bound_role: str = str(target["already_bound_role"] or "")
if lease is None:
candidate_model = AccountCandidate(
account_id=int(account.id),
account_name=account_name,
checked_at=primary_state.observed_at or moment,
ck_verdict="valid",
ck_message="同角色复用关联账号 CK 有效",
elite_opened=account.elite_opened,
points=account.points,
limited_ids=frozenset(),
username=str(account.username or ""),
nickname=str(account.nickname or ""),
points=int(account.points or 0),
gold_balance=account.gold_balance,
points_expire_at=account.points_expire_at,
role_change_available_at=account.role_change_available_at,
commodity_availability={task.commodity_id: availability},
commodity_blocking_reasons=(
{task.commodity_id: str(primary_state.blocking_reason or "")}
if primary_state.blocking_reason
else {}
),
)
return _apply_allocated_account_state(
lease = lease_account(
db,
candidate=candidate_model,
holder_user_id=current.id,
task_id=task.id,
commodity_id=task.commodity_id,
ttl_minutes=_lease_duration_minutes(db),
commit=False,
)
if lease is None:
return None
account_name = account.nickname or account.username or f"#{account.id}"
availability = allocation_availability(
primary_state.account_eligibility,
primary_state.offer_state,
)
cached_state = DouyuLiveAccountState(
account_id=int(account.id),
account_name=account_name,
checked_at=primary_state.observed_at or moment,
ck_verdict="valid",
ck_message="同角色复用关联账号 CK 有效",
elite_opened=account.elite_opened,
points=account.points,
limited_ids=frozenset(),
role_change_available_at=account.role_change_available_at,
commodity_availability={task.commodity_id: availability},
commodity_blocking_reasons=(
{task.commodity_id: str(primary_state.blocking_reason or "")}
if primary_state.blocking_reason
else {}
),
)
merged_detail = {
"sharedLease": reused_existing_lease,
"siblingTaskIds": sibling_ids,
"reusedRoleName": role,
}
if extra_event_detail:
merged_detail.update(extra_event_detail)
return _apply_allocated_account_state(
db,
task=task,
account_id=int(account.id),
account_name=account_name,
lease=lease,
cached_state=cached_state,
required_points=int(task.required_points or 0),
is_presale=classification.normalize_sale_mode(task.sale_mode) == "presale",
current=current,
moment=moment,
allocation_strategy="same_role_reuse",
observed_at=primary_state.observed_at,
valid_until=primary_state.valid_until,
extra_event_detail=merged_detail,
already_bound_role=already_bound_role,
commit=commit,
)
def _try_reuse_same_role_account(
db: Session,
*,
task: PlatformFulfillmentTask,
current: User,
policy: dict[str, Any],
required_co: tuple[str, ...],
moment: datetime,
) -> dict[str, Any] | None:
"""同客户角色多单时,优先复用已分配/已绑定的同一斗鱼账号,避免撞 7 天角色锁。"""
role = str(task.customer_role_name or "").strip()
target = _find_reusable_same_role_target(
db,
task=task,
role=role,
policy=policy,
required_co=required_co,
moment=moment,
)
if target is None:
return None
return _attach_task_to_same_role_target(
db,
task=task,
target=target,
role=role,
current=current,
moment=moment,
commit=True,
)
def try_reallocate_task_to_same_role(
db: Session,
*,
task: PlatformFulfillmentTask,
current: User,
role_name: str = "",
trigger: str = "role_sync",
preferred_account_id: int | None = None,
allow_pending_role_ready: bool = False,
commit: bool = False,
now: datetime | None = None,
) -> bool:
"""晚提交角色资料或发现同角色已绑他号时,把尚未绑定完成的任务合并到同角色账号。"""
if (
task.flow_version != FLOW_VERSION_CLEAN
or task.execution_status in {"completed", "cancelled"}
or not task.commodity_id
):
return False
allowed_binding_statuses = {
"not_started",
"preparing",
"qr_pending",
"waiting_bind",
}
if allow_pending_role_ready:
allowed_binding_statuses.add("role_ready")
if str(task.binding_status or "") not in allowed_binding_statuses:
return False
role = str(role_name or task.customer_role_name or "").strip()
if not role:
return False
task_role = str(task.customer_role_name or "").strip()
if task_role and not role_names_match(task_role, role):
return False
moment = now or _now()
policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy"))
required_co, _preferred_co = bundle_requirements_for_commodity(
task.commodity_id, policy
)
preferred_ids = (int(preferred_account_id),) if preferred_account_id else ()
target = _find_reusable_same_role_target(
db,
task=task,
role=role,
policy=policy,
required_co=required_co,
moment=moment,
preferred_account_ids=preferred_ids,
)
if target is None:
return False
if task.account_id is not None:
target_is_bound = bool(
target["already_bound_role"]
or target["sibling_bound"]
or target["role_lock_matches"]
)
if not target_is_bound:
if str(task.binding_status or "") != "not_started":
return False
earliest_sibling_id = target["earliest_sibling_id"]
if not target["has_active_qr_sibling"] and (
earliest_sibling_id is None or int(earliest_sibling_id) >= int(task.id)
):
return False
from .lifecycle import _release_or_detach_shared_lease
old_account_id = int(task.account_id)
old_lease = (
db.query(AccountLease).filter(AccountLease.id == int(task.lease_id)).first()
if task.lease_id
else None
)
_release_or_detach_shared_lease(
db,
task=task,
account_id=int(account.id),
account_name=account_name,
lease=lease,
cached_state=cached_state,
required_points=required_points,
is_presale=is_presale,
lease=old_lease,
current=current,
moment=moment,
allocation_strategy="same_role_reuse",
observed_at=primary_state.observed_at,
valid_until=primary_state.valid_until,
extra_event_detail={
"sharedLease": reused_existing_lease,
"siblingTaskIds": sibling_ids,
"reusedRoleName": role,
},
already_bound_role=already_bound_role,
collab_reason=f"same_role_merge:{trigger}",
release_reason=f"same_role_merge:{trigger}",
)
return None
if task.bind_task_id:
old_bind = db.get(DouyuTask, int(task.bind_task_id))
if old_bind is not None and old_bind.status in {
"planned",
"pending",
"running",
}:
shared_bind = (
db.query(PlatformFulfillmentTask.id)
.filter(
PlatformFulfillmentTask.bind_task_id == int(old_bind.id),
PlatformFulfillmentTask.id != int(task.id),
PlatformFulfillmentTask.execution_status != "cancelled",
)
.first()
)
if shared_bind is None:
old_bind.status = "stopped"
old_bind.message = "同角色已改用原绑定账号,终止旧绑码任务"
old_bind.finished_at = moment
old_bind.queue_lane = ""
old_bind.next_run_at = None
task.account_id = None
task.lease_id = None
task.bind_task_id = None
task.execution_status = "ready"
task.binding_status = "not_started"
task.exchange_status = "not_started"
task.issue_code = ""
task.last_error = ""
_append_event(
db,
task.id,
"account_released",
actor_type="system",
detail={
"reason": f"same_role_merge:{trigger}",
"previousAccountId": old_account_id,
"targetAccountId": int(target["account"].id),
},
)
extra_detail = {
"mergedFromAccountId": old_account_id,
"mergeTrigger": trigger,
}
else:
extra_detail = {"mergeTrigger": trigger}
attached = _attach_task_to_same_role_target(
db,
task=task,
target=target,
role=role,
current=current,
moment=moment,
extra_event_detail=extra_detail,
commit=commit,
)
return attached is not None
def _allocate_task_from_capability(