fix(douyu): 拆分账号资格活动窗口与库存语义

This commit is contained in:
yml
2026-11-22 20:04:49 +08:00
parent d78437c6ac
commit 1906f924bc
26 changed files with 896 additions and 174 deletions
@@ -24,6 +24,20 @@ AVAILABILITY_NOT_OFFERED = "not_offered"
AVAILABILITY_EXPIRED = "expired"
AVAILABILITY_UNKNOWN = "unknown"
ACCOUNT_ELIGIBILITY_ELIGIBLE = "eligible"
ACCOUNT_ELIGIBILITY_LIMITED = "limited"
ACCOUNT_ELIGIBILITY_UNKNOWN = "unknown"
OFFER_STATE_BEFORE = "before"
OFFER_STATE_ACTIVE = "active"
OFFER_STATE_EXPIRED = "expired"
OFFER_STATE_NOT_OFFERED = "not_offered"
OFFER_STATE_UNKNOWN = "unknown"
STOCK_STATE_IN_STOCK = "in_stock"
STOCK_STATE_OUT_OF_STOCK = "out_of_stock"
STOCK_STATE_UNKNOWN = "unknown"
DEFAULT_CAPABILITY_TTL_SECONDS = 15 * 60
DEFAULT_STABLE_CAPABILITY_TTL_SECONDS = 6 * 60 * 60
DEFAULT_LIMITED_CAPABILITY_TTL_SECONDS = 24 * 60 * 60
@@ -174,16 +188,26 @@ def goods_time_window(
)
def classify_goods_item(
@dataclass(frozen=True)
class GoodsAssessment:
account_eligibility: str
offer_state: str
stock_state: str
availability: str
blocking_reason: str
raw_status: str
stock_count: int | None
store_status: int | None
open_status: int | None
window: GoodsTimeWindow
def classify_goods_item_assessment(
item: dict[str, Any],
*,
now: datetime | None = None,
) -> tuple[str, str, str]:
"""把官方 storehome 商品项归一成能力状态。
返回 ``(availability, blocking_reason, raw_status)``。只有官方明确给出的
账号级 ``status`` 才允许写成 available / limited;缺字段一律 unknown。
"""
) -> GoodsAssessment:
"""拆分账号资格、活动窗口和全局库存,禁止三种语义互相覆盖。"""
moment = now or datetime.now(UTC)
window = goods_time_window(item, now=moment)
raw_status = str(item.get("status") if item.get("status") is not None else "")
@@ -200,32 +224,77 @@ def classify_goods_item(
)
count = _to_int(item.get("count"))
if window.state == "before":
return (
AVAILABILITY_NOT_OPEN,
f"限时兑换未开始,开始于 {window.start.isoformat() if window.start else '未知时间'}",
raw_status,
)
if window.state == "after":
return AVAILABILITY_EXPIRED, "限时兑换已结束", raw_status
if status == 1:
return AVAILABILITY_LIMITED, "该账号已达此商品兑换上限", raw_status
if store_status == 0:
return AVAILABILITY_NO_STOCK, "官方商城当前无库存", raw_status
if count is not None and count <= 0:
return AVAILABILITY_NO_STOCK, "官方商城当前无库存", raw_status
if open_status == 0:
return AVAILABILITY_NOT_OPEN, "活动尚未开放兑换", raw_status
if status == 0:
return AVAILABILITY_AVAILABLE, "", raw_status
return AVAILABILITY_UNKNOWN, "官方商品列表未返回可判定的账号状态", raw_status
account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED
elif status == 0:
account_eligibility = ACCOUNT_ELIGIBILITY_ELIGIBLE
else:
account_eligibility = ACCOUNT_ELIGIBILITY_UNKNOWN
if open_status == 0 or window.state == "before":
offer_state = OFFER_STATE_BEFORE
elif window.state == "after":
offer_state = OFFER_STATE_EXPIRED
elif window.state == "active" or window.state == "":
offer_state = OFFER_STATE_ACTIVE
else:
offer_state = OFFER_STATE_UNKNOWN
if store_status == 0 or (count is not None and count <= 0):
stock_state = STOCK_STATE_OUT_OF_STOCK
elif store_status is not None or count is not None:
stock_state = STOCK_STATE_IN_STOCK
else:
stock_state = STOCK_STATE_UNKNOWN
if account_eligibility == ACCOUNT_ELIGIBILITY_LIMITED:
availability = AVAILABILITY_LIMITED
reason = "该账号已达此商品兑换上限"
elif account_eligibility == ACCOUNT_ELIGIBILITY_UNKNOWN:
availability = AVAILABILITY_UNKNOWN
reason = "官方商品列表未返回可判定的账号兑换资格"
elif offer_state == OFFER_STATE_BEFORE:
availability = AVAILABILITY_NOT_OPEN
reason = (
f"限时兑换未开始,开始于 {window.start.isoformat()}"
if window.start
else "活动尚未开放兑换"
)
elif offer_state == OFFER_STATE_EXPIRED:
availability = AVAILABILITY_EXPIRED
reason = "限时兑换已结束"
elif stock_state == STOCK_STATE_OUT_OF_STOCK:
availability = AVAILABILITY_NO_STOCK
reason = "官方商城当前无库存"
else:
availability = AVAILABILITY_AVAILABLE
reason = ""
return GoodsAssessment(
account_eligibility=account_eligibility,
offer_state=offer_state,
stock_state=stock_state,
availability=availability,
blocking_reason=reason,
raw_status=raw_status,
stock_count=count,
store_status=store_status,
open_status=open_status,
window=window,
)
@dataclass(frozen=True)
class GoodsAssessment:
availability: str
blocking_reason: str
raw_status: str
def classify_goods_item(
item: dict[str, Any],
*,
now: datetime | None = None,
) -> tuple[str, str, str]:
"""兼容旧调用:返回派生展示状态,不用于自动选号。"""
assessment = classify_goods_item_assessment(item, now=now)
return (
assessment.availability,
assessment.blocking_reason,
assessment.raw_status,
)
def classify_goods_items(
@@ -243,12 +312,7 @@ def classify_goods_items(
).strip()
if not commodity_id:
continue
availability, reason, raw_status = classify_goods_item(item, now=now)
assessments[commodity_id] = GoodsAssessment(
availability=availability,
blocking_reason=reason,
raw_status=raw_status,
)
assessments[commodity_id] = classify_goods_item_assessment(item, now=now)
return assessments
@@ -293,6 +357,24 @@ def exchange_gate_for_availability(
return "not_available", issue_code, reason or fallback
def allocation_availability(
account_eligibility: str,
offer_state: str,
) -> str:
"""自动选号只消费账号资格与活动窗口,明确忽略全局库存。"""
if account_eligibility == ACCOUNT_ELIGIBILITY_LIMITED:
return AVAILABILITY_LIMITED
if account_eligibility != ACCOUNT_ELIGIBILITY_ELIGIBLE:
return AVAILABILITY_UNKNOWN
if offer_state == OFFER_STATE_BEFORE:
return AVAILABILITY_NOT_OPEN
if offer_state == OFFER_STATE_EXPIRED:
return AVAILABILITY_EXPIRED
if offer_state == OFFER_STATE_NOT_OFFERED:
return AVAILABILITY_NOT_OFFERED
return AVAILABILITY_AVAILABLE
def _exchange_stats(
db: Session,
*,
@@ -416,19 +498,25 @@ def sync_account_goods_states(
db.add(state)
by_commodity[commodity_id] = state
availability, reason, raw_status = classify_goods_item(item, now=moment)
window = goods_time_window(item, now=moment)
assessment = classify_goods_item_assessment(item, now=moment)
window = assessment.window
ttl_valid_until = moment + timedelta(
seconds=capability_ttl_seconds(availability)
seconds=capability_ttl_seconds(assessment.availability)
)
last_exchange_at, exchange_count = exchange_stats.get(
commodity_id,
(None, 0),
)
state.commodity_name = _commodity_name(item)[:256]
state.availability = availability
state.blocking_reason = reason[:255]
state.raw_status = raw_status[:16]
state.account_eligibility = assessment.account_eligibility
state.offer_state = assessment.offer_state
state.stock_state = assessment.stock_state
state.stock_count = assessment.stock_count
state.store_status = assessment.store_status
state.open_status = assessment.open_status
state.availability = assessment.availability
state.blocking_reason = assessment.blocking_reason[:255]
state.raw_status = assessment.raw_status[:16]
state.raw_json = dict(item)
state.time_limited = window.time_limited
state.available_from = window.start
@@ -458,6 +546,12 @@ def sync_account_goods_states(
):
continue
state.availability = AVAILABILITY_NOT_OFFERED
state.account_eligibility = ACCOUNT_ELIGIBILITY_UNKNOWN
state.offer_state = OFFER_STATE_NOT_OFFERED
state.stock_state = STOCK_STATE_UNKNOWN
state.stock_count = None
state.store_status = None
state.open_status = None
state.blocking_reason = "官方商品列表本次未返回该商品"
state.raw_json = None
state.time_limited = False
@@ -483,6 +577,12 @@ def record_account_commodity_state(
*,
commodity_id: str,
availability: str,
account_eligibility: str | None = None,
offer_state: str | None = None,
stock_state: str | None = None,
stock_count: int | None = None,
store_status: int | None = None,
open_status: int | None = None,
blocking_reason: str = "",
raw_status: str = "",
observed_at: datetime | None = None,
@@ -493,6 +593,26 @@ def record_account_commodity_state(
) -> AccountCommodityState:
"""写入单个商品的实时检查结论,供下一轮匹配直接使用。"""
moment = observed_at or datetime.now(UTC)
if account_eligibility is None:
account_eligibility = {
AVAILABILITY_LIMITED: ACCOUNT_ELIGIBILITY_LIMITED,
AVAILABILITY_UNKNOWN: ACCOUNT_ELIGIBILITY_UNKNOWN,
AVAILABILITY_NOT_OFFERED: ACCOUNT_ELIGIBILITY_UNKNOWN,
}.get(availability, ACCOUNT_ELIGIBILITY_ELIGIBLE)
if offer_state is None:
offer_state = {
AVAILABILITY_NOT_OPEN: OFFER_STATE_BEFORE,
AVAILABILITY_EXPIRED: OFFER_STATE_EXPIRED,
AVAILABILITY_NOT_OFFERED: OFFER_STATE_NOT_OFFERED,
AVAILABILITY_AVAILABLE: OFFER_STATE_ACTIVE,
AVAILABILITY_NO_STOCK: OFFER_STATE_ACTIVE,
}.get(availability, OFFER_STATE_UNKNOWN)
if stock_state is None:
stock_state = (
STOCK_STATE_OUT_OF_STOCK
if availability == AVAILABILITY_NO_STOCK
else STOCK_STATE_UNKNOWN
)
ttl = (
capability_ttl_seconds(availability)
if valid_for_seconds is None
@@ -523,6 +643,12 @@ def record_account_commodity_state(
now=moment,
)
last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (None, 0))
state.account_eligibility = account_eligibility
state.offer_state = offer_state
state.stock_state = stock_state
state.stock_count = stock_count
state.store_status = store_status
state.open_status = open_status
state.availability = availability
state.blocking_reason = blocking_reason[:255]
state.raw_status = raw_status[:16]
@@ -574,6 +700,7 @@ def mark_commodity_exchanged(
last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (moment, 1))
if commodity_name:
state.commodity_name = commodity_name[:256]
state.account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED
state.availability = AVAILABILITY_LIMITED
state.blocking_reason = "该账号已兑换过此商品,365 天内不可重复分配"
state.observed_at = moment
@@ -600,10 +727,12 @@ def invalidate_account_commodity_states(
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.availability == AVAILABILITY_AVAILABLE,
AccountCommodityState.account_eligibility
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
)
.update(
{
AccountCommodityState.account_eligibility: ACCOUNT_ELIGIBILITY_UNKNOWN,
AccountCommodityState.availability: AVAILABILITY_UNKNOWN,
AccountCommodityState.blocking_reason: reason[:255],
AccountCommodityState.observed_at: moment,
@@ -664,13 +793,51 @@ def account_capability_counts(
or 0
)
result["fresh_available"] = int(fresh_available)
eligibility_rows = (
db.query(
AccountCommodityState.account_eligibility,
func.count(AccountCommodityState.id),
)
.filter(AccountCommodityState.account_id == account_id)
.group_by(AccountCommodityState.account_eligibility)
.all()
)
for eligibility, count in eligibility_rows:
result[f"eligibility_{eligibility}"] = int(count or 0)
result["fresh_eligible"] = int(
db.query(func.count(AccountCommodityState.id))
.filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.account_eligibility
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > moment,
)
.scalar()
or 0
)
result["total"] = sum(
value for key, value in result.items() if key not in {"fresh_available", "total"}
value
for key, value in result.items()
if key
not in {
"fresh_available",
"fresh_eligible",
"total",
*{f"eligibility_{item}" for item in (
ACCOUNT_ELIGIBILITY_ELIGIBLE,
ACCOUNT_ELIGIBILITY_LIMITED,
ACCOUNT_ELIGIBILITY_UNKNOWN,
)},
}
)
return result
__all__ = [
"ACCOUNT_ELIGIBILITY_ELIGIBLE",
"ACCOUNT_ELIGIBILITY_LIMITED",
"ACCOUNT_ELIGIBILITY_UNKNOWN",
"AVAILABILITY_AVAILABLE",
"AVAILABILITY_EXPIRED",
"AVAILABILITY_LIMITED",
@@ -678,10 +845,20 @@ __all__ = [
"AVAILABILITY_NOT_OPEN",
"AVAILABILITY_NO_STOCK",
"AVAILABILITY_UNKNOWN",
"OFFER_STATE_ACTIVE",
"OFFER_STATE_BEFORE",
"OFFER_STATE_EXPIRED",
"OFFER_STATE_NOT_OFFERED",
"OFFER_STATE_UNKNOWN",
"STOCK_STATE_IN_STOCK",
"STOCK_STATE_OUT_OF_STOCK",
"STOCK_STATE_UNKNOWN",
"GoodsAssessment",
"account_capability_counts",
"allocation_availability",
"capability_ttl_seconds",
"classify_goods_item",
"classify_goods_item_assessment",
"classify_goods_items",
"exchange_gate_for_availability",
"goods_time_window",
@@ -387,6 +387,28 @@ def account_platform_status(
}
fresh_available = int(commodities.get(AVAILABILITY_AVAILABLE, {}).get("fresh", 0))
fresh_limited = int(commodities.get(AVAILABILITY_LIMITED, {}).get("fresh", 0))
eligibility_rows = (
db.query(
AccountCommodityState.account_eligibility,
func.count(AccountCommodityState.id),
func.sum(
case(
(AccountCommodityState.valid_until > moment, 1),
else_=0,
)
),
)
.filter(AccountCommodityState.platform == "douyu")
.group_by(AccountCommodityState.account_eligibility)
.all()
)
eligibility = {
str(state): {
"total": int(total or 0),
"fresh": int(fresh or 0),
}
for state, total, fresh in eligibility_rows
}
inventories = evaluate_supply_targets(db, now=moment)
supply_targets: list[dict[str, Any]] = []
@@ -529,6 +551,8 @@ def account_platform_status(
"sync_domains": sync_domains,
"commodities": {
"by_availability": commodities,
"by_account_eligibility": eligibility,
"fresh_eligible": int(eligibility.get("eligible", {}).get("fresh", 0)),
"fresh_available": fresh_available,
"fresh_limited": fresh_limited,
},
+13 -35
View File
@@ -14,8 +14,9 @@ from ..models import (
User,
)
from .account_capability_service import (
AVAILABILITY_AVAILABLE,
AVAILABILITY_NOT_OPEN,
ACCOUNT_ELIGIBILITY_ELIGIBLE,
OFFER_STATE_ACTIVE,
OFFER_STATE_BEFORE,
)
from .account_lifecycle import MANUAL_STATES
@@ -101,45 +102,22 @@ def fresh_ck_cutoff(now: datetime) -> datetime:
return now - timedelta(seconds=CK_FRESH_SECONDS)
def fresh_available_state_filter(
def fresh_eligible_state_filter(
now: datetime,
*,
allow_not_open: bool = False,
allow_before_open: bool = False,
):
allowed = (
(AVAILABILITY_AVAILABLE, AVAILABILITY_NOT_OPEN)
if allow_not_open
else (AVAILABILITY_AVAILABLE,)
)
available_window = and_(
AccountCommodityState.availability == AVAILABILITY_AVAILABLE,
or_(
AccountCommodityState.available_from.is_(None),
AccountCommodityState.available_from <= now,
),
or_(
AccountCommodityState.available_until.is_(None),
AccountCommodityState.available_until >= now,
),
)
if not allow_not_open:
return and_(
AccountCommodityState.availability.in_(allowed),
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
available_window,
)
not_open_window = and_(
AccountCommodityState.availability == AVAILABILITY_NOT_OPEN,
or_(
AccountCommodityState.available_until.is_(None),
AccountCommodityState.available_until >= now,
),
allowed_offer_states = (
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
if allow_before_open
else (OFFER_STATE_ACTIVE,)
)
return and_(
AccountCommodityState.account_eligibility
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
AccountCommodityState.offer_state.in_(allowed_offer_states),
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
or_(available_window, not_open_window),
)
@@ -152,8 +130,8 @@ __all__ = [
"assigned_to_pool_filter",
"automatable_account_filter",
"cookie_present_filter",
"fresh_available_state_filter",
"fresh_ck_cutoff",
"fresh_eligible_state_filter",
"pool_owner_ids",
"role_change_ready_filter",
"valid_ck_filter",
@@ -22,8 +22,8 @@ from .account_query_filters import (
assigned_to_pool_filter,
automatable_account_filter,
cookie_present_filter,
fresh_available_state_filter,
fresh_ck_cutoff,
fresh_eligible_state_filter,
role_change_ready_filter,
valid_ck_filter,
)
@@ -128,8 +128,8 @@ def _allocatable_filter(now: datetime):
)
def _fresh_available_filter(now: datetime):
return fresh_available_state_filter(now)
def _fresh_eligible_filter(now: datetime):
return fresh_eligible_state_filter(now, allow_before_open=True)
def _commodity_query(
@@ -230,7 +230,7 @@ def _global_inventory_totals(
base_filter,
AccountCommodityState.platform == platform,
AccountCommodityState.scope == scope,
_fresh_available_filter(now),
_fresh_eligible_filter(now),
)
.group_by(value_class)
.all()
@@ -297,7 +297,7 @@ def evaluate_supply_target(
if target.commodity_id:
base = _commodity_query(db, now=moment, target=target)
covered = base.count()
available_query = base.filter(_fresh_available_filter(moment))
available_query = base.filter(_fresh_eligible_filter(moment))
available = available_query.count()
allocatable = available_query.filter(_allocatable_filter(moment)).count()
else:
+2 -2
View File
@@ -62,7 +62,7 @@ def serialize_goods(raw: Mapping[str, Any]) -> dict[str, Any]:
"mark": mark,
"count": _to_int(_first_value(raw, "count")),
"elite_limited": _to_int(_first_value(raw, "eliteLimited")),
"is_limited": bool(mark) or open_status == 0,
"is_limited": str(status_value or "") == "1",
"raw": _json_safe(dict(raw)),
}
@@ -86,7 +86,7 @@ def serialize_snapshot(row: DouyuGoodsSnapshot) -> dict[str, Any]:
"mark": mark,
"count": _to_int(_first_value(raw, "count")),
"elite_limited": _to_int(_first_value(raw, "eliteLimited")),
"is_limited": bool(mark) or open_status == 0,
"is_limited": str(row.status or "") == "1",
"raw": raw,
}
@@ -19,9 +19,7 @@ from ...models import (
AccountEvent,
AccountLease,
)
from ..account_capability_service import (
AVAILABILITY_AVAILABLE,
)
from ..account_capability_service import OFFER_STATE_ACTIVE
from ..account_events_service import (
CATEGORY_OPS,
EVENT_LEASE_ACQUIRED,
@@ -34,7 +32,7 @@ from ..account_query_filters import (
assigned_to_pool_filter,
automatable_account_filter,
cookie_present_filter,
fresh_available_state_filter,
fresh_eligible_state_filter,
role_change_ready_filter,
valid_ck_filter,
)
@@ -238,16 +236,16 @@ def _capability_candidate_query(
scope: str = "elite",
limit: int = 20,
now: datetime | None = None,
allow_not_open: bool = False,
allow_before_open: bool = False,
):
commodity = commodity_id.strip()
if not commodity:
return None
moment = _now(now)
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
availability_filter = fresh_available_state_filter(
eligibility_filter = fresh_eligible_state_filter(
moment,
allow_not_open=allow_not_open,
allow_before_open=allow_before_open,
)
return (
db.query(Account, AccountCommodityState)
@@ -259,7 +257,7 @@ def _capability_candidate_query(
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity,
availability_filter,
eligibility_filter,
or_(
AccountCommodityState.last_exchange_at.is_(None),
AccountCommodityState.last_exchange_at < since,
@@ -274,7 +272,7 @@ def _capability_candidate_query(
)
.order_by(
case(
(AccountCommodityState.availability == AVAILABILITY_AVAILABLE, 0),
(AccountCommodityState.offer_state == OFFER_STATE_ACTIVE, 0),
else_=1,
),
case((Account.ck_check_status == "valid", 0), else_=1),
@@ -300,7 +298,7 @@ def capability_candidate_rows(
scope: str = "elite",
limit: int = 20,
now: datetime | None = None,
allow_not_open: bool = False,
allow_before_open: bool = False,
) -> list[CapabilityCandidate]:
"""读取账号与能力快照;只访问本地数据库,不触发官网请求。"""
query = _capability_candidate_query(
@@ -310,7 +308,7 @@ def capability_candidate_rows(
scope=scope,
limit=limit,
now=now,
allow_not_open=allow_not_open,
allow_before_open=allow_before_open,
)
if query is None:
return []
@@ -328,7 +326,7 @@ def capability_candidate_accounts(
scope: str = "elite",
limit: int = 20,
now: datetime | None = None,
allow_not_open: bool = False,
allow_before_open: bool = False,
) -> list[Account]:
"""从新鲜的商品能力索引读取候选账号,不产生外部请求。"""
return [
@@ -340,7 +338,7 @@ def capability_candidate_accounts(
scope=scope,
limit=limit,
now=now,
allow_not_open=allow_not_open,
allow_before_open=allow_before_open,
)
]
@@ -37,11 +37,17 @@ from ..account_binding import (
pending_binding_role_from_result,
)
from ..account_capability_service import (
ACCOUNT_ELIGIBILITY_LIMITED,
ACCOUNT_ELIGIBILITY_UNKNOWN,
AVAILABILITY_AVAILABLE,
AVAILABILITY_LIMITED,
AVAILABILITY_NO_STOCK,
AVAILABILITY_NOT_OFFERED,
AVAILABILITY_NOT_OPEN,
OFFER_STATE_BEFORE,
OFFER_STATE_NOT_OFFERED,
OFFER_STATE_UNKNOWN,
STOCK_STATE_UNKNOWN,
allocation_availability,
classify_goods_items,
exchange_gate_for_availability,
record_account_commodity_state,
@@ -1365,6 +1371,27 @@ def _task_out(
include_qr: bool = False,
include_exchange_task: bool = False,
) -> dict[str, Any]:
mapping = (
db.query(PlatformCommodityMapping)
.filter(PlatformCommodityMapping.id == task.commodity_mapping_id)
.first()
if task.commodity_mapping_id
else None
)
goods = (
db.query(DouyuGoodsSnapshot)
.filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id)
.order_by(DouyuGoodsSnapshot.id.desc())
.first()
if task.commodity_id
else None
)
goods_name = (
str(getattr(mapping, "goods_name", "") or "")
or str(getattr(goods, "name", "") or "")
or task.sku_name
or task.internal_sku_key
)
account = (
db.query(Account).filter(Account.id == task.account_id).first()
if task.account_id
@@ -1435,6 +1462,7 @@ def _task_out(
"scope": task.scope,
"commodityMappingId": task.commodity_mapping_id,
"commodityId": task.commodity_id,
"goodsName": goods_name,
"requiredPoints": task.required_points,
"saleMode": sale_mode,
"campaignKey": task.campaign_key,
@@ -1974,6 +2002,7 @@ def _reapply_mapping_tasks(
detail={
"mappingId": row.id,
"commodityId": row.commodity_id,
"goodsName": row.goods_name,
"saleMode": row.sale_mode,
"campaignKey": row.campaign_key,
"enabled": row.enabled,
@@ -2296,7 +2325,22 @@ def _cached_capability_state(
"""把新鲜本地能力快照转换成统一的履约状态,不访问斗鱼官网。"""
account = candidate.account
state = candidate.state
reason = str(state.blocking_reason or "")
availability = allocation_availability(
state.account_eligibility,
state.offer_state,
)
if availability == AVAILABILITY_AVAILABLE:
reason = ""
elif availability == AVAILABILITY_LIMITED:
reason = "该账号已达此商品兑换上限"
elif availability == AVAILABILITY_NOT_OPEN:
reason = (
f"限时兑换未开始,开始于 {state.available_from.isoformat()}"
if state.available_from
else "活动尚未开放兑换"
)
else:
reason = str(state.blocking_reason or "")
return DouyuLiveAccountState(
account_id=int(account.id),
account_name=account.nickname or account.username or f"#{account.id}",
@@ -2307,7 +2351,7 @@ def _cached_capability_state(
points=account.points,
limited_ids=frozenset(),
role_change_available_at=account.role_change_available_at,
commodity_availability={commodity_id: state.availability},
commodity_availability={commodity_id: availability},
commodity_blocking_reasons=(
{commodity_id: reason} if reason else {}
),
@@ -2321,8 +2365,23 @@ def _capability_availability_counts(
scope: str,
now: datetime,
) -> dict[str, int]:
rows = (
db.query(AccountCommodityState.availability, func.count(AccountCommodityState.id))
base = db.query(AccountCommodityState).filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
eligibility_rows = (
base.with_entities(
AccountCommodityState.account_eligibility,
func.count(AccountCommodityState.id),
)
.group_by(AccountCommodityState.account_eligibility)
.all()
)
offer_rows = (
db.query(AccountCommodityState.offer_state, func.count(AccountCommodityState.id))
.filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
@@ -2330,10 +2389,29 @@ def _capability_availability_counts(
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
.group_by(AccountCommodityState.availability)
.group_by(AccountCommodityState.offer_state)
.all()
)
return {str(availability): int(count or 0) for availability, count in rows}
stock_rows = (
db.query(AccountCommodityState.stock_state, func.count(AccountCommodityState.id))
.filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
.group_by(AccountCommodityState.stock_state)
.all()
)
return {
**{
f"eligibility:{key}": int(count or 0)
for key, count in eligibility_rows
},
**{f"offer:{key}": int(count or 0) for key, count in offer_rows},
**{f"stock:{key}": int(count or 0) for key, count in stock_rows},
}
def _local_allocation_retry_at(
@@ -2356,7 +2434,7 @@ def _local_allocation_retry_at(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == (task.scope or SCOPE_ELITE),
AccountCommodityState.commodity_id == task.commodity_id,
AccountCommodityState.availability == AVAILABILITY_NOT_OPEN,
AccountCommodityState.offer_state == OFFER_STATE_BEFORE,
AccountCommodityState.available_from.isnot(None),
AccountCommodityState.available_from > now,
)
@@ -2364,11 +2442,11 @@ def _local_allocation_retry_at(
)
if next_open_at is not None:
return next_open_at + timedelta(seconds=5), "commodity_not_open"
if availability_counts.get(AVAILABILITY_NOT_OPEN):
if availability_counts.get(f"offer:{OFFER_STATE_BEFORE}"):
return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_not_open"
if availability_counts.get(AVAILABILITY_NO_STOCK):
return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_no_stock"
if availability_counts:
if availability_counts.get("eligibility:eligible"):
return now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), "lease_conflict"
return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "no_eligible_account"
return now + timedelta(seconds=LOCAL_CACHE_MISS_RETRY_SECONDS), "capability_cache_miss"
@@ -2465,7 +2543,7 @@ def _allocate_task_from_capability(
commodity_id=task.commodity_id,
scope=task.scope or SCOPE_ELITE,
now=moment,
allow_not_open=is_presale,
allow_before_open=is_presale,
)
recent_exchange_ids: set[int] = set()
if capability_candidates:
@@ -2577,12 +2655,9 @@ def _allocate_task_from_capability(
if retry_reason == "commodity_not_open":
task.issue_code = "commodity_not_open"
task.last_error = "该商品尚未到开放时间,已按开放时间安排重新选号"
elif retry_reason == "commodity_no_stock":
task.issue_code = "commodity_no_stock"
task.last_error = "本地能力池显示该商品当前无库存,稍后自动重试"
elif retry_reason == "capability_cache_miss":
task.issue_code = "capability_cache_miss"
task.last_error = "暂无该商品的新鲜能力快照,等待后台补货刷新"
task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新"
elif retry_reason == "lease_conflict":
task.issue_code = "account_lease_conflict"
task.last_error = "已找到候选账号,但刚被其他任务占用"
@@ -3541,15 +3616,35 @@ def refresh_exchange_eligibility(
assessment = assessments.get(task.commodity_id)
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
if task.commodity_id in limited_ids:
account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED
offer_state = assessment.offer_state if assessment else OFFER_STATE_UNKNOWN
stock_state = assessment.stock_state if assessment else STOCK_STATE_UNKNOWN
availability = AVAILABILITY_LIMITED
commodity_message = "该账号已达到此商品兑换上限"
elif assessments and assessment is None:
account_eligibility = ACCOUNT_ELIGIBILITY_UNKNOWN
offer_state = OFFER_STATE_NOT_OFFERED
stock_state = STOCK_STATE_UNKNOWN
availability = AVAILABILITY_NOT_OFFERED
commodity_message = "官方商品列表本次未返回该商品,可能已下架"
elif assessment is not None and assessment.availability != AVAILABILITY_AVAILABLE:
account_eligibility = assessment.account_eligibility
offer_state = assessment.offer_state
stock_state = assessment.stock_state
availability = assessment.availability
commodity_message = assessment.blocking_reason
else:
account_eligibility = (
assessment.account_eligibility
if assessment is not None
else ACCOUNT_ELIGIBILITY_UNKNOWN
)
offer_state = (
assessment.offer_state if assessment is not None else OFFER_STATE_UNKNOWN
)
stock_state = (
assessment.stock_state if assessment is not None else STOCK_STATE_UNKNOWN
)
availability = AVAILABILITY_AVAILABLE
commodity_message = ""
@@ -3579,6 +3674,12 @@ def refresh_exchange_eligibility(
account,
commodity_id=task.commodity_id,
availability=availability,
account_eligibility=account_eligibility,
offer_state=offer_state,
stock_state=stock_state,
stock_count=assessment.stock_count if assessment is not None else None,
store_status=assessment.store_status if assessment is not None else None,
open_status=assessment.open_status if assessment is not None else None,
blocking_reason=commodity_message,
raw_status=(
assessment.raw_status
@@ -3601,6 +3702,9 @@ def refresh_exchange_eligibility(
"commodity_id": task.commodity_id,
"exchange_status": task.exchange_status,
"limited": task.commodity_id in limited_ids,
"account_eligibility": account_eligibility,
"offer_state": offer_state,
"stock_state": stock_state,
"availability": availability,
"issue_code": task.issue_code,
"points": account.points,