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
@@ -7,7 +7,7 @@ from datetime import datetime, timedelta
from typing import Any
from fastapi import HTTPException
from sqlalchemy import func, select
from sqlalchemy import case, func, or_, select
from sqlalchemy.orm import Session
from ...models import (
@@ -26,6 +26,7 @@ from ..account_capability_service import (
OFFER_STATE_BEFORE,
allocation_availability,
)
from ..account_lifecycle import MANUAL_STATES
from ..account_query_filters import (
active_collab_order_exists,
active_lease_exists,
@@ -40,9 +41,14 @@ from ..account_work_queue import (
active_account_work_count,
enqueue_account_work,
)
from ..binding_ownership import (
active_collab_order_for_account,
role_names_match,
)
from ..douyu_account_state import DouyuLiveAccountState
from . import classification
from .account_selector import (
EXCHANGE_COOLDOWN_DAYS,
AccountCandidate,
CapabilityCandidate,
capability_candidate_rows,
@@ -52,6 +58,7 @@ from .account_selector import (
)
from .common import (
DEFAULT_CAPABILITY_CANDIDATE_LIMIT,
FLOW_VERSION_CLEAN,
LOCAL_CACHE_MISS_RETRY_SECONDS,
LOCAL_LEASE_CONFLICT_RETRY_SECONDS,
LOCAL_STOCK_RETRY_SECONDS,
@@ -62,11 +69,24 @@ from .common import (
_now,
)
from .outbox import _emit_order_site_binding_state
from .policy import (
PRIORITY_KEY_BUNDLE_MATCH,
PRIORITY_KEY_CK_FRESHNESS,
PRIORITY_KEY_POINTS_ASC,
PRIORITY_KEY_PRESERVE_BUNDLE_POOL,
PRIORITY_KEY_RESOURCE_READY,
bundle_requirements_for_commodity,
normalize_allocation_policy,
normalize_priority_order,
protected_bundle_commodities,
)
from .repository import _load_task, _load_task_for_update
from .role_lock import find_account_lock, find_role_lock
from .runtime import (
_append_event,
_apply_task_lease_policy,
_lease_duration_minutes,
get_settings,
)
from .views import get_task_detail
@@ -323,6 +343,432 @@ def _seed_capability_refresh(
return len(accounts)
def _candidate_sort_key(
candidate: CapabilityCandidate,
cached_state: DouyuLiveAccountState,
*,
required_points: int,
priority_order: list[str] | tuple[str, ...],
) -> tuple[Any, ...]:
"""保持与 SQL 查询一致的多维度优先级排序,避免 Python 二次排序打乱保护顺序。"""
account = candidate.account
state = candidate.state
parts: list[Any] = [0 if state.offer_state == OFFER_STATE_ACTIVE else 1]
for key in normalize_priority_order(priority_order):
if key == PRIORITY_KEY_BUNDLE_MATCH:
parts.append(int(state.bundle_missing_count or 0))
elif key == PRIORITY_KEY_PRESERVE_BUNDLE_POOL:
parts.append(1 if state.is_protected_bundle else 0)
elif key == PRIORITY_KEY_RESOURCE_READY:
parts.append(cached_state.readiness_rank(required_points=required_points))
elif key == PRIORITY_KEY_POINTS_ASC:
parts.append(1 if cached_state.points is None else 0)
parts.append(int(cached_state.points or 0))
elif key == PRIORITY_KEY_CK_FRESHNESS:
checked_at = account.ck_checked_at
parts.append(0 if account.ck_check_status == "valid" else 1)
parts.append(0 if account.status == "active" else 1)
parts.append(1 if checked_at is None else 0)
parts.append(-(checked_at.timestamp()) if checked_at is not None else 0.0)
parts.append(int(account.id))
return tuple(parts)
def _apply_allocated_account_state(
db: Session,
*,
task: PlatformFulfillmentTask,
account_id: int,
account_name: str,
lease: AccountLease,
cached_state: DouyuLiveAccountState,
required_points: int,
is_presale: bool,
current: User,
moment: datetime,
allocation_strategy: str,
observed_at: datetime | None = None,
valid_until: datetime | None = None,
extra_event_detail: dict[str, Any] | None = None,
already_bound_role: str = "",
) -> dict[str, Any]:
stale_leases = (
db.query(AccountLease)
.filter(
AccountLease.status == "active",
AccountLease.batch_id == f"pf:{int(task.id)}",
AccountLease.id != int(lease.id),
)
.with_for_update()
.all()
)
for stale in stale_leases:
release_lease(
db,
stale,
reason="allocation_replaced",
commit=False,
)
task.account_id = int(account_id)
task.lease_id = int(lease.id)
task.operator_id = current.id
task.execution_status = "bound" if already_bound_role else "allocated"
task.next_allocate_at = None
task.binding_status = "bound" if already_bound_role else "not_started"
soft_reasons = cached_state.soft_requirement_reasons(
required_points=required_points
)
gate_status, gate_issue, gate_message = _exchange_gate(
cached_state,
task.commodity_id,
allow_not_open=is_presale,
)
if gate_status:
task.exchange_status = gate_status
task.issue_code = gate_issue
task.last_error = gate_message
elif cached_state.elite_opened is not True:
task.exchange_status = "not_opened"
task.issue_code = "elite_not_opened"
task.last_error = "账号尚未开通精英宝典,可开通后继续"
elif cached_state.points is None or cached_state.points < required_points:
task.exchange_status = "points_short"
task.issue_code = "points_short"
task.last_error = "账号积分不足,可充值后继续"
else:
task.exchange_status = "eligible"
task.issue_code = ""
task.last_error = ""
task.updated_at = moment
_apply_task_lease_policy(db, task, lease=lease)
detail: dict[str, Any] = {
"accountId": int(account_id),
"accountName": account_name,
"points": cached_state.points,
"eliteOpened": cached_state.elite_opened,
"softReasons": soft_reasons,
"exchangeStatus": task.exchange_status,
"allocationStrategy": allocation_strategy,
"capabilityObservedAt": _jsonable(observed_at),
"capabilityValidUntil": _jsonable(valid_until),
}
if extra_event_detail:
detail.update(extra_event_detail)
_append_event(
db,
task.id,
"account_allocated",
actor_type="user",
actor_id=current.id,
detail=detail,
)
if already_bound_role:
_append_event(
db,
task.id,
"binding_reused_same_role_account",
detail={
"roleName": already_bound_role[:128],
"accountId": int(account_id),
"accountName": account_name,
"reason": "same_role_existing_account",
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
def _account_meets_commodity_eligibility(
db: Session,
*,
account_id: int,
commodity_id: str,
scope: str,
moment: datetime,
allow_before_open: bool,
) -> AccountCommodityState | None:
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
allowed_offers = (
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
if allow_before_open
else (OFFER_STATE_ACTIVE,)
)
return (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == int(account_id),
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.account_eligibility == "eligible",
AccountCommodityState.offer_state.in_(allowed_offers),
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > moment,
or_(
AccountCommodityState.last_exchange_at.is_(None),
AccountCommodityState.last_exchange_at < since,
),
)
.first()
)
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 天角色锁。"""
if not policy.get("sameRoleReuseEnabled", True):
return None
role = str(task.customer_role_name or "").strip()
if 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)
sibling_rows = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN,
PlatformFulfillmentTask.id != int(task.id),
PlatformFulfillmentTask.account_id.isnot(None),
PlatformFulfillmentTask.execution_status != "cancelled",
func.lower(func.trim(PlatformFulfillmentTask.customer_role_name))
== role.casefold(),
)
.order_by(
case((PlatformFulfillmentTask.lease_id.isnot(None), 0), else_=1),
case((PlatformFulfillmentTask.binding_status == "bound", 0), else_=1),
PlatformFulfillmentTask.updated_at.desc(),
PlatformFulfillmentTask.id.desc(),
)
.limit(10)
.all()
)
candidate_account_ids: list[int] = []
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))
role_lock = find_role_lock(db, role, current_account_id=None, now=moment)
if role_lock is not None and int(role_lock.account_id) not in candidate_account_ids:
candidate_account_ids.append(int(role_lock.account_id))
if not candidate_account_ids:
return None
for candidate_account_id in candidate_account_ids:
account = db.get(Account, int(candidate_account_id))
if account is None:
continue
if (
not bool(account.auto_managed)
or str(account.status or "") in MANUAL_STATES
or not str(account.cookie or "").strip()
or str(account.ck_check_status or "") != "valid"
or account.assigned_to is not None
):
continue
account_role = str(account.game_name or "").strip()
if str(account.role_bind_status or "") == "bound" and (
not account_role or not role_names_match(account_role, role)
):
continue
if find_account_lock(db, account.id, role, now=moment) is not None:
continue
# 同一斗鱼号不能用来兑换两次完全相同的商品。
duplicate_commodity = (
db.query(PlatformFulfillmentTask.id)
.filter(
PlatformFulfillmentTask.account_id == int(account.id),
PlatformFulfillmentTask.id != int(task.id),
PlatformFulfillmentTask.execution_status != "cancelled",
PlatformFulfillmentTask.commodity_id == task.commodity_id,
)
.first()
)
if duplicate_commodity is not None:
continue
primary_state = _account_meets_commodity_eligibility(
db,
account_id=int(account.id),
commodity_id=task.commodity_id,
scope=scope,
moment=moment,
allow_before_open=is_presale,
)
if primary_state is None:
continue
co_missing = any(
_account_meets_commodity_eligibility(
db,
account_id=int(account.id),
commodity_id=co_cid,
scope=scope,
moment=moment,
allow_before_open=True,
)
is None
for co_cid in required_co
)
if co_missing:
continue
recent_exchange = (
db.query(AccountEvent.id)
.filter(
AccountEvent.account_id == int(account.id),
AccountEvent.event_type == "exchange",
AccountEvent.subject_key.in_([task.commodity_id, *required_co]),
AccountEvent.occurred_at >= since_365,
)
.first()
)
if recent_exchange is not None:
continue
active_collab = active_collab_order_for_account(db, int(account.id))
if active_collab is not None:
collab_role = str(active_collab.bind_game_role or "").strip()
if not collab_role and active_collab.source_task_id:
source_task = db.get(
PlatformFulfillmentTask, int(active_collab.source_task_id)
)
if source_task is not None:
collab_role = str(source_task.customer_role_name or "").strip()
if not collab_role or not role_names_match(collab_role, role):
continue
active_lease = (
db.query(AccountLease)
.filter(
AccountLease.account_id == int(account.id),
AccountLease.status == "active",
)
.with_for_update()
.first()
)
reused_existing_lease = False
sibling_ids: list[int] = []
sibling_bound = False
if active_lease is not None:
if active_lease.purpose != "platform_fulfillment":
continue
holders = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.lease_id == int(active_lease.id),
PlatformFulfillmentTask.execution_status != "cancelled",
)
.all()
)
if not holders:
continue
if any(
not str(holder.customer_role_name or "").strip()
or not role_names_match(holder.customer_role_name, role)
or holder.commodity_id == task.commodity_id
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)
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
already_bound_role = ""
if (
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)
)
)
):
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(
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 {}
),
)
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=required_points,
is_presale=is_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={
"sharedLease": reused_existing_lease,
"siblingTaskIds": sibling_ids,
"reusedRoleName": role,
},
already_bound_role=already_bound_role,
)
return None
def _allocate_task_from_capability(
db: Session,
*,
@@ -336,14 +782,31 @@ def _allocate_task_from_capability(
task = _load_task_for_update(db, int(task.id))
if task.account_id and task.lease_id:
current_lease = (
db.query(AccountLease)
.filter(AccountLease.id == int(task.lease_id))
.first()
db.query(AccountLease).filter(AccountLease.id == int(task.lease_id)).first()
)
if current_lease is not None and current_lease.status == "active":
return get_task_detail(db, task.id)
moment = _now()
required_points = int(task.required_points or 0)
policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy"))
required_co, preferred_co = bundle_requirements_for_commodity(
policy,
task.commodity_id,
)
protected_co = protected_bundle_commodities(policy, task.commodity_id)
priority_order = policy.get("priorityOrder") or ()
reused = _try_reuse_same_role_account(
db,
task=task,
current=current,
policy=policy,
required_co=required_co,
moment=moment,
)
if reused is not None:
return reused
try:
candidate_limit = int(
os.getenv(
@@ -363,11 +826,16 @@ def _allocate_task_from_capability(
scope=task.scope or SCOPE_ELITE,
now=moment,
allow_before_open=is_presale,
required_co_commodities=required_co,
preferred_co_commodities=preferred_co,
protected_bundle_commodities=protected_co,
priority_order=priority_order,
)
recent_exchange_ids: set[int] = set()
if capability_candidates:
candidate_ids = [int(item.account.id) for item in capability_candidates]
since = moment - timedelta(days=365)
commodity_check_ids = list(dict.fromkeys([task.commodity_id, *required_co]))
recent_exchange_ids = {
int(account_id)
for (account_id,) in (
@@ -375,7 +843,7 @@ def _allocate_task_from_capability(
.filter(
AccountEvent.account_id.in_(candidate_ids),
AccountEvent.event_type == "exchange",
AccountEvent.subject_key == task.commodity_id,
AccountEvent.subject_key.in_(commodity_check_ids),
AccountEvent.occurred_at >= since,
)
.distinct()
@@ -393,7 +861,7 @@ def _allocate_task_from_capability(
"accountId": account_id,
"accountName": candidate.account.nickname
or candidate.account.username,
"reasons": ["365 天内已有该商品兑换事件"],
"reasons": ["365 天内已有该商品或捆绑商品兑换事件"],
"source": "capability",
}
)
@@ -409,10 +877,11 @@ def _allocate_task_from_capability(
)
qualified.sort(
key=lambda item: (
item[1].readiness_rank(required_points=required_points),
int(item[1].points or 0),
int(item[0].account.id),
key=lambda item: _candidate_sort_key(
item[0],
item[1],
required_points=required_points,
priority_order=priority_order,
)
)
selected: CapabilityCandidate | None = None
@@ -466,6 +935,13 @@ def _allocate_task_from_capability(
availability_counts=availability_counts,
lease_conflict=bool(qualified),
)
if (
required_co
and not capability_candidates
and retry_reason == "lease_conflict"
):
retry_reason = "bundle_co_eligibility_missing"
retry_at = moment + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS)
refresh_queued = (
_seed_capability_refresh(db, task=task, now=moment)
if retry_reason
@@ -473,6 +949,7 @@ def _allocate_task_from_capability(
"capability_cache_miss",
"account_role_cooldown",
"account_pool_busy",
"bundle_co_eligibility_missing",
}
else 0
)
@@ -482,6 +959,11 @@ def _allocate_task_from_capability(
elif retry_reason == "capability_cache_miss":
task.issue_code = "capability_cache_miss"
task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新"
elif retry_reason == "bundle_co_eligibility_missing":
task.issue_code = "bundle_co_eligibility_missing"
task.last_error = (
"已有单个商品可兑账号,但缺少同时具备捆绑商品全部兑换资格的可用账号"
)
elif retry_reason == "lease_conflict":
task.issue_code = "account_lease_conflict"
task.last_error = "已找到候选账号,但刚被其他任务占用"
@@ -512,6 +994,8 @@ def _allocate_task_from_capability(
"matchingMode": "capability",
"strategy": "local_capability",
"capabilityCandidates": len(capability_candidates),
"requiredCoCommodities": list(required_co),
"preferredCoCommodities": list(preferred_co),
"availabilityCounts": availability_counts,
"retryAt": _jsonable(retry_at),
"retryReason": retry_reason,
@@ -524,76 +1008,26 @@ def _allocate_task_from_capability(
return get_task_detail(db, task.id)
selected_account = selected.account
stale_leases = (
db.query(AccountLease)
.filter(
AccountLease.status == "active",
AccountLease.batch_id == f"pf:{int(task.id)}",
AccountLease.id != int(lease.id),
)
.with_for_update()
.all()
)
for stale in stale_leases:
release_lease(
db,
stale,
reason="allocation_replaced",
commit=False,
)
task.account_id = selected_account.id
task.lease_id = lease.id
task.operator_id = current.id
task.execution_status = "allocated"
task.next_allocate_at = None
task.binding_status = "not_started"
soft_reasons = selected_state.soft_requirement_reasons(
required_points=required_points
)
gate_status, gate_issue, gate_message = _exchange_gate(
selected_state,
task.commodity_id,
allow_not_open=is_presale,
)
if gate_status:
task.exchange_status = gate_status
task.issue_code = gate_issue
task.last_error = gate_message
elif selected_state.elite_opened is not True:
task.exchange_status = "not_opened"
task.issue_code = "elite_not_opened"
task.last_error = "账号尚未开通精英宝典,可开通后继续"
elif selected_state.points is None or selected_state.points < required_points:
task.exchange_status = "points_short"
task.issue_code = "points_short"
task.last_error = "账号积分不足,可充值后继续"
else:
task.exchange_status = "eligible"
task.issue_code = ""
task.last_error = ""
task.updated_at = moment
_apply_task_lease_policy(db, task, lease=lease)
_append_event(
return _apply_allocated_account_state(
db,
task.id,
"account_allocated",
actor_type="user",
actor_id=current.id,
detail={
"accountId": selected_account.id,
"accountName": selected_state.account_name,
"points": selected_state.points,
"eliteOpened": selected_state.elite_opened,
"softReasons": soft_reasons,
"exchangeStatus": task.exchange_status,
"allocationStrategy": "local_capability",
"capabilityObservedAt": _jsonable(selected.state.observed_at),
"capabilityValidUntil": _jsonable(selected.state.valid_until),
task=task,
account_id=int(selected_account.id),
account_name=selected_state.account_name,
lease=lease,
cached_state=selected_state,
required_points=required_points,
is_presale=is_presale,
current=current,
moment=moment,
allocation_strategy="local_capability",
observed_at=selected.state.observed_at,
valid_until=selected.state.valid_until,
extra_event_detail={
"requiredCoCommodities": list(required_co),
"preferredCoCommodities": list(preferred_co),
"bundleMissingCount": int(selected.state.bundle_missing_count or 0),
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
def prepare_manual_allocation(