fix(fulfillment): 取消商品限时兑换未开始对提前选号绑定的限制

This commit is contained in:
yml
2026-11-28 20:12:33 +08:00
parent d03eeaee18
commit c8efa6d808
7 changed files with 170 additions and 42 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# 直播账号运营后台 # 直播账号运营后台
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.8)。 斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.9)。
## 能做什么 ## 能做什么
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "live-hub-py" name = "live-hub-py"
version = "0.4.8" version = "0.4.9"
description = "直播账号运营 Web 后台" description = "直播账号运营 Web 后台"
readme = "README.md" readme = "README.md"
requires-python = ">=3.12,<3.13" requires-python = ">=3.12,<3.13"
+156 -4
View File
@@ -1695,8 +1695,8 @@ class TestAccountSelection(_Base):
assert detail["task"]["executionStatus"] == "allocated" assert detail["task"]["executionStatus"] == "allocated"
assert detail["task"]["exchangeStatus"] == "waiting_release" assert detail["task"]["exchangeStatus"] == "waiting_release"
def test_direct_sale_still_blocks_when_commodity_not_open(self): def test_direct_sale_allows_allocation_and_advance_binding_when_not_open(self):
self.account("direct-future", availability="not_open") account = self.account("direct-future", availability="not_open")
task = self.task() task = self.task()
task.sale_mode = "direct" task.sale_mode = "direct"
self.session.commit() self.session.commit()
@@ -1707,8 +1707,9 @@ class TestAccountSelection(_Base):
current=self.admin, current=self.admin,
) )
assert detail["task"]["account"] is None assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "ready" assert detail["task"]["executionStatus"] == "allocated"
assert detail["task"]["exchangeStatus"] == "waiting_release"
assert detail["task"]["issueCode"] == "commodity_not_open" assert detail["task"]["issueCode"] == "commodity_not_open"
def test_capability_pool_includes_future_not_open_for_presale_only(self): def test_capability_pool_includes_future_not_open_for_presale_only(self):
@@ -7141,3 +7142,154 @@ class TestAllocationPolicyAndSameRoleReuse(_Base):
assert t3.execution_status == "bound" assert t3.execution_status == "bound"
assert t3.issue_code != "customer_role_bound_elsewhere" assert t3.issue_code != "customer_role_bound_elsewhere"
assert t3_old_lease.status == "released" assert t3_old_lease.status == "released"
def test_bundle_missing_co_eligibility_not_masked_by_offer_before(self):
partial = self.account("partial-before", points=8000, capability=False)
self._add_commodity_state(partial, TRIO_BAG412, eligibility="eligible")
self._add_commodity_state(partial, TRIO_BAG413, eligibility="eligible")
self._add_commodity_state(partial, TRIO_BAG414, eligibility="limited")
partial_row = (
self.session.query(AccountCommodityState)
.filter_by(account_id=partial.id, commodity_id=TRIO_BAG412)
.one()
)
partial_row.offer_state = "before"
partial_row.availability = "not_open"
partial_row.available_from = NOW + timedelta(days=3)
expired = self.account("expired-trio", points=8000, capability=False)
for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414):
self._add_commodity_state(expired, cid, eligibility="eligible")
row = (
self.session.query(AccountCommodityState)
.filter_by(account_id=expired.id, commodity_id=cid)
.one()
)
row.valid_until = NOW - timedelta(minutes=10)
task = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="trio-before-gap",
role_name="联合缺口玩家",
)
task.sale_mode = "presale"
self.session.commit()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"] is None
assert detail["task"]["executionStatus"] == "ready"
assert detail["task"]["issueCode"] == "bundle_co_eligibility_missing"
queued = (
self.session.query(AccountWorkItem)
.filter(
AccountWorkItem.account_id == expired.id,
AccountWorkItem.work_type == WORK_STOREHOME_SYNC,
)
.all()
)
assert queued
def test_reallocate_same_role_respects_bundle_requirements_and_before_open(self):
acc_partial = self.account("rebind-partial", points=24000, capability=False)
self._add_commodity_state(acc_partial, TRIO_BAG412, eligibility="eligible")
self._add_commodity_state(acc_partial, TRIO_BAG413, eligibility="eligible")
self._add_commodity_state(acc_partial, TRIO_BAG414, eligibility="limited")
acc_full = self.account("rebind-full", points=24000, capability=False)
for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414):
self._add_commodity_state(acc_full, cid, eligibility="eligible")
row = (
self.session.query(AccountCommodityState)
.filter_by(account_id=acc_full.id, commodity_id=cid)
.one()
)
row.offer_state = "before"
row.availability = "not_open"
row.available_from = NOW + timedelta(days=3)
acc_other = self.account("rebind-other", points=24000, capability=False)
self._add_commodity_state(acc_other, TRIO_BAG414, eligibility="eligible")
self._add_commodity_state(acc_other, TRIO_BAG412, eligibility="eligible")
self._add_commodity_state(acc_other, TRIO_BAG413, eligibility="eligible")
t_partial = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="rebind-partial",
role_name="玩家甲",
)
t_partial.account_id = acc_partial.id
t_partial.binding_status = "bound"
t_partial.execution_status = "bound"
lease_partial = AccountLease(
account_id=acc_partial.id,
holder_user_id=self.admin_id,
purpose="platform_fulfillment",
batch_id=f"pf:{t_partial.id}",
status="active",
expires_at=NOW + timedelta(days=7),
)
self.session.add(lease_partial)
self.session.flush()
t_partial.lease_id = lease_partial.id
t_full = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="rebind-full",
role_name="玩家乙",
)
lease_full = AccountLease(
account_id=acc_full.id,
holder_user_id=self.admin_id,
purpose="platform_fulfillment",
batch_id=f"pf:{t_full.id}",
status="active",
expires_at=NOW + timedelta(days=7),
)
self.session.add(lease_full)
self.session.flush()
t_full.account_id = acc_full.id
t_full.lease_id = lease_full.id
t_full.binding_status = "bound"
t_full.execution_status = "bound"
t_target_partial = self._create_commodity_task(
commodity_id=TRIO_BAG414,
order_suffix="rebind-target-partial",
role_name="玩家甲",
)
t_target_partial.sale_mode = "direct"
t_target_partial.account_id = acc_other.id
t_target = self._create_commodity_task(
commodity_id=TRIO_BAG414,
order_suffix="rebind-target",
role_name="玩家乙",
)
t_target.sale_mode = "direct"
t_target.account_id = acc_other.id
self.session.commit()
assert not service.allocation.try_reallocate_task_to_same_role(
self.session,
task=t_target_partial,
current=self.admin,
role_name="玩家甲",
preferred_account_id=acc_partial.id,
)
assert service.allocation.try_reallocate_task_to_same_role(
self.session,
task=t_target,
current=self.admin,
role_name="玩家乙",
preferred_account_id=acc_full.id,
)
self.session.refresh(t_target)
assert t_target.account_id == acc_full.id
assert t_target.binding_status == "bound"
assert t_target.exchange_status == "waiting_release"
Generated
+1 -1
View File
@@ -381,7 +381,7 @@ wheels = [
[[package]] [[package]]
name = "live-hub-py" name = "live-hub-py"
version = "0.4.8" version = "0.4.9"
source = { editable = "." } source = { editable = "." }
dependencies = [ dependencies = [
{ name = "alembic" }, { name = "alembic" },
+1 -1
View File
@@ -517,7 +517,7 @@ def recommend_accounts(
required_points=required, required_points=required,
commodity_id=cid, commodity_id=cid,
scope="elite", scope="elite",
allow_before_open=bool(required_co or preferred_co), allow_before_open=True,
required_co_commodities=required_co, required_co_commodities=required_co,
preferred_co_commodities=preferred_co, preferred_co_commodities=preferred_co,
protected_bundle_commodities=protected_co, protected_bundle_commodities=protected_co,
@@ -47,7 +47,6 @@ from ..binding_ownership import (
role_names_match, role_names_match,
) )
from ..douyu_account_state import DouyuLiveAccountState from ..douyu_account_state import DouyuLiveAccountState
from . import classification
from .account_selector import ( from .account_selector import (
EXCHANGE_COOLDOWN_DAYS, EXCHANGE_COOLDOWN_DAYS,
AccountCandidate, AccountCandidate,
@@ -244,28 +243,15 @@ def _local_allocation_retry_at(
availability_counts: dict[str, int], availability_counts: dict[str, int],
lease_conflict: bool, lease_conflict: bool,
) -> tuple[datetime, str]: ) -> tuple[datetime, str]:
"""按本地状态决定下一轮时间,避免永久无库存任务每 45 秒占槽。""" """按本地状态决定下一轮时间,避免永久无库存任务每 45 秒占槽。
「商品限时兑换未开始(offer:before)」不再阻止提前选号与绑定,也不再掩盖真实的捆绑资格缺口或触发能力刷新。
"""
if lease_conflict: if lease_conflict:
return ( return (
now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS),
"lease_conflict", "lease_conflict",
) )
next_open_at = (
db.query(func.min(AccountCommodityState.available_from))
.filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == (task.scope or SCOPE_ELITE),
AccountCommodityState.commodity_id == task.commodity_id,
AccountCommodityState.offer_state == OFFER_STATE_BEFORE,
AccountCommodityState.available_from.isnot(None),
AccountCommodityState.available_from > now,
)
.scalar()
)
if next_open_at is not None:
return next_open_at + timedelta(seconds=5), "commodity_not_open"
if availability_counts.get(f"offer:{OFFER_STATE_BEFORE}"):
return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_not_open"
has_capability_rows = any( has_capability_rows = any(
int(value or 0) int(value or 0)
for key, value in availability_counts.items() for key, value in availability_counts.items()
@@ -384,7 +370,6 @@ def _apply_allocated_account_state(
lease: AccountLease, lease: AccountLease,
cached_state: DouyuLiveAccountState, cached_state: DouyuLiveAccountState,
required_points: int, required_points: int,
is_presale: bool,
current: User, current: User,
moment: datetime, moment: datetime,
allocation_strategy: str, allocation_strategy: str,
@@ -423,7 +408,7 @@ def _apply_allocated_account_state(
gate_status, gate_issue, gate_message = _exchange_gate( gate_status, gate_issue, gate_message = _exchange_gate(
cached_state, cached_state,
task.commodity_id, task.commodity_id,
allow_not_open=is_presale, allow_not_open=True,
) )
if gate_status: if gate_status:
task.exchange_status = gate_status task.exchange_status = gate_status
@@ -534,7 +519,6 @@ def _find_reusable_same_role_target(
scope = task.scope or SCOPE_ELITE scope = task.scope or SCOPE_ELITE
since_365 = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS) since_365 = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
sibling_rows = ( sibling_rows = (
db.query(PlatformFulfillmentTask) db.query(PlatformFulfillmentTask)
@@ -611,7 +595,7 @@ def _find_reusable_same_role_target(
commodity_id=task.commodity_id, commodity_id=task.commodity_id,
scope=scope, scope=scope,
moment=moment, moment=moment,
allow_before_open=is_presale, allow_before_open=True,
) )
if primary_state is None: if primary_state is None:
continue continue
@@ -824,7 +808,6 @@ def _attach_task_to_same_role_target(
lease=lease, lease=lease,
cached_state=cached_state, cached_state=cached_state,
required_points=int(task.required_points or 0), required_points=int(task.required_points or 0),
is_presale=classification.normalize_sale_mode(task.sale_mode) == "presale",
current=current, current=current,
moment=moment, moment=moment,
allocation_strategy="same_role_reuse", allocation_strategy="same_role_reuse",
@@ -908,7 +891,7 @@ def try_reallocate_task_to_same_role(
moment = now or _now() moment = now or _now()
policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy")) policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy"))
required_co, _preferred_co = bundle_requirements_for_commodity( required_co, _preferred_co = bundle_requirements_for_commodity(
task.commodity_id, policy policy, task.commodity_id
) )
preferred_ids = (int(preferred_account_id),) if preferred_account_id else () preferred_ids = (int(preferred_account_id),) if preferred_account_id else ()
target = _find_reusable_same_role_target( target = _find_reusable_same_role_target(
@@ -1063,7 +1046,6 @@ def _allocate_task_from_capability(
except ValueError: except ValueError:
candidate_limit = DEFAULT_CAPABILITY_CANDIDATE_LIMIT candidate_limit = DEFAULT_CAPABILITY_CANDIDATE_LIMIT
candidate_limit = max(1, min(candidate_limit, 100)) candidate_limit = max(1, min(candidate_limit, 100))
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
capability_candidates = capability_candidate_rows( capability_candidates = capability_candidate_rows(
db, db,
limit=candidate_limit, limit=candidate_limit,
@@ -1071,7 +1053,7 @@ def _allocate_task_from_capability(
commodity_id=task.commodity_id, commodity_id=task.commodity_id,
scope=task.scope or SCOPE_ELITE, scope=task.scope or SCOPE_ELITE,
now=moment, now=moment,
allow_before_open=is_presale, allow_before_open=True,
required_co_commodities=required_co, required_co_commodities=required_co,
preferred_co_commodities=preferred_co, preferred_co_commodities=preferred_co,
protected_bundle_commodities=protected_co, protected_bundle_commodities=protected_co,
@@ -1199,10 +1181,7 @@ def _allocate_task_from_capability(
} }
else 0 else 0
) )
if retry_reason == "commodity_not_open": if retry_reason == "capability_cache_miss":
task.issue_code = "commodity_not_open"
task.last_error = "该商品尚未到开放时间,已按开放时间安排重新选号"
elif retry_reason == "capability_cache_miss":
task.issue_code = "capability_cache_miss" task.issue_code = "capability_cache_miss"
task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新" task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新"
elif retry_reason == "bundle_co_eligibility_missing": elif retry_reason == "bundle_co_eligibility_missing":
@@ -1262,7 +1241,6 @@ def _allocate_task_from_capability(
lease=lease, lease=lease,
cached_state=selected_state, cached_state=selected_state,
required_points=required_points, required_points=required_points,
is_presale=is_presale,
current=current, current=current,
moment=moment, moment=moment,
allocation_strategy="local_capability", allocation_strategy="local_capability",
@@ -45,7 +45,6 @@ from ..external_order_source import (
OrderLookupUnavailable, OrderLookupUnavailable,
lookup_pending_manual_fulfillment, lookup_pending_manual_fulfillment,
) )
from . import classification
from .account_selector import ( from .account_selector import (
release_lease, release_lease,
) )
@@ -331,7 +330,6 @@ def refresh_exchange_eligibility(
] ]
assessments = classify_goods_items(storehome_goods, now=_now()) assessments = classify_goods_items(storehome_goods, now=_now())
assessment = assessments.get(task.commodity_id) assessment = assessments.get(task.commodity_id)
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
if task.commodity_id in limited_ids: if task.commodity_id in limited_ids:
account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED
offer_state = assessment.offer_state if assessment else OFFER_STATE_UNKNOWN offer_state = assessment.offer_state if assessment else OFFER_STATE_UNKNOWN
@@ -368,7 +366,7 @@ def refresh_exchange_eligibility(
gate_status, gate_issue, gate_message = exchange_gate_for_availability( gate_status, gate_issue, gate_message = exchange_gate_for_availability(
availability, availability,
reason=commodity_message, reason=commodity_message,
allow_not_open=is_presale, allow_not_open=True,
) )
if gate_status: if gate_status:
task.exchange_status = gate_status task.exchange_status = gate_status