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(
@@ -7,7 +7,7 @@ from datetime import timedelta
from typing import Any
from fastapi import HTTPException
from sqlalchemy import case
from sqlalchemy import case, func
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from starlette.concurrency import run_in_threadpool
@@ -63,6 +63,7 @@ from .common import FLOW_VERSION_CLEAN, SCOPE_ELITE, _has_game_home_profile, _no
from .outbox import _emit_order_site_binding_state
from .repository import (
_binding_qr_expired,
_integration_actor,
_load_task,
_load_task_for_update,
)
@@ -234,6 +235,41 @@ def _propagate_same_role_binding_to_siblings(
source_task_id=int(bound_task.id),
)
updated += 1
# 同角色如果有多单但之前因未填角色名被预分配到了不同账号,
# 主单确认绑定后把未完成绑定的兄弟单自动释放旧空号并改挂到主账号。
cross_account_siblings = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN,
PlatformFulfillmentTask.id != int(bound_task.id),
PlatformFulfillmentTask.account_id.isnot(None),
PlatformFulfillmentTask.account_id != int(bound_task.account_id),
PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")),
PlatformFulfillmentTask.binding_status.in_(ACTIVE_BINDING_STATUSES),
PlatformFulfillmentTask.customer_role_name != "",
func.lower(func.trim(PlatformFulfillmentTask.customer_role_name))
== role_name.casefold(),
)
.order_by(PlatformFulfillmentTask.id.asc())
.with_for_update(skip_locked=True)
.all()
)
if cross_account_siblings:
from .allocation import try_reallocate_task_to_same_role
actor = _integration_actor(db)
for sibling in cross_account_siblings:
if try_reallocate_task_to_same_role(
db,
task=sibling,
current=actor,
role_name=role_name,
preferred_account_id=int(bound_task.account_id),
trigger="sibling_bound",
commit=False,
):
updated += 1
return updated
@@ -268,6 +304,27 @@ def start_binding_sync(
)
db.commit()
return get_task_detail(db, task.id)
if task.customer_role_name and task.binding_status != "bound":
from .allocation import try_reallocate_task_to_same_role
if try_reallocate_task_to_same_role(
db,
task=task,
current=current,
role_name=task.customer_role_name,
trigger="start_binding",
commit=True,
):
if task.binding_status == "bound":
return get_task_detail(db, task.id)
lease = (
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if task.lease_id
else None
)
if lease is None or lease.status != "active":
return get_task_detail(db, task.id)
account = db.query(Account).filter(Account.id == task.account_id).first()
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 (
@@ -875,7 +932,7 @@ def _block_on_role_lock(
role_name: str,
source: DouyuTask | None = None,
) -> bool:
"""角色已绑在别的账号上时,把订单转人工;返回是否拦截。"""
"""角色已绑在别的账号上时,优先尝试同角色合并改挂,否则把订单转人工。"""
if str(task.issue_code or "") == ROLE_LOCK_ISSUE:
return False
lock = find_role_lock(
@@ -885,6 +942,19 @@ def _block_on_role_lock(
)
if lock is None:
return False
from .allocation import try_reallocate_task_to_same_role
if try_reallocate_task_to_same_role(
db,
task=task,
current=_integration_actor(db),
role_name=role_name,
preferred_account_id=int(lock.account_id),
allow_pending_role_ready=True,
trigger="role_lock_redirect",
commit=False,
):
return True
return _mark_role_locked(db, task, source, lock)
@@ -90,8 +90,12 @@ def save_customer_profile(
images.append(
{
"url": url[:2048],
"thumbnailUrl": str(item.get("thumbnail_url") or item.get("thumbnailUrl") or url)[:2048],
"objectKey": str(item.get("object_key") or item.get("objectKey") or "")[:512],
"thumbnailUrl": str(
item.get("thumbnail_url") or item.get("thumbnailUrl") or url
)[:2048],
"objectKey": str(item.get("object_key") or item.get("objectKey") or "")[
:512
],
}
)
if not images:
@@ -115,6 +119,17 @@ def save_customer_profile(
"homeImageCount": len(images),
},
)
if task.account_id and task.customer_role_name:
from .allocation import try_reallocate_task_to_same_role
try_reallocate_task_to_same_role(
db,
task=task,
current=_integration_actor(db),
role_name=task.customer_role_name,
trigger="customer_profile_saved",
commit=False,
)
if commit:
db.commit()
return customer_binding_out(db, task.id)
@@ -135,10 +150,11 @@ async def customer_start_binding(
raise HTTPException(status_code=409, detail="请先提交游戏角色和游戏主页截图")
if not task.account_id or not task.lease_id:
if (
task.execution_status == "manual_required"
and task.issue_code in {"binding_failed", "lease_expired", "role_changed"}
):
if task.execution_status == "manual_required" and task.issue_code in {
"binding_failed",
"lease_expired",
"role_changed",
}:
from .allocation import prepare_manual_allocation
prepare_manual_allocation(
@@ -218,7 +234,9 @@ def update_customer_profile_by_operator(
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="订单已结束,不能修改客户资料")
if task.binding_status == "bound":
raise HTTPException(status_code=409, detail="角色已绑定确认,不能直接修改客户资料")
raise HTTPException(
status_code=409, detail="角色已绑定确认,不能直接修改客户资料"
)
if task.binding_status == "confirming":
raise HTTPException(status_code=409, detail="正在确认绑定中,请稍后再试")
@@ -293,6 +311,17 @@ def update_customer_profile_by_operator(
},
)
_emit_order_site_binding_state(db, task.id)
if task.execution_status != "manual_required" and task.binding_status != "bound":
from .allocation import try_reallocate_task_to_same_role
try_reallocate_task_to_same_role(
db,
task=task,
current=current,
role_name=new_role,
trigger="operator_profile_updated",
commit=False,
)
db.commit()
if reopened and task.execution_status == "ready":
from .auto_allocator import wake_auto_allocator
@@ -60,16 +60,13 @@ def _apply_customer_profile(
if not keys.intersection(snapshot):
return
task.customer_role_name = str(
_snapshot_value(snapshot, "customerRoleName", "customer_role_name")
or ""
_snapshot_value(snapshot, "customerRoleName", "customer_role_name") or ""
)[:128]
task.customer_platform = str(
_snapshot_value(snapshot, "customerPlatform", "customer_platform")
or ""
_snapshot_value(snapshot, "customerPlatform", "customer_platform") or ""
)[:16]
task.customer_system = str(
_snapshot_value(snapshot, "customerSystem", "customer_system")
or ""
_snapshot_value(snapshot, "customerSystem", "customer_system") or ""
)[:16]
raw_images = _snapshot_value(
snapshot,
@@ -83,7 +80,9 @@ def _apply_customer_profile(
if isinstance(item, str):
url = item.strip()
if url:
images.append({"url": url[:2048], "thumbnailUrl": url[:2048], "objectKey": ""})
images.append(
{"url": url[:2048], "thumbnailUrl": url[:2048], "objectKey": ""}
)
continue
if not isinstance(item, dict):
continue
@@ -114,6 +113,24 @@ def _apply_customer_profile(
from .binding import sync_customer_role_to_bind_task
sync_customer_role_to_bind_task(db, task)
if (
db is not None
and task.id is not None
and task.account_id is not None
and task.customer_role_name
and task.binding_status != "bound"
):
from .allocation import try_reallocate_task_to_same_role
from .repository import _integration_actor
try_reallocate_task_to_same_role(
db,
task=task,
current=_integration_actor(db),
role_name=task.customer_role_name,
trigger="order_snapshot_sync",
commit=False,
)
def _upsert_order_snapshot(