fix(douyu): 拆分账号资格活动窗口与库存语义
This commit is contained in:
@@ -457,6 +457,10 @@
|
||||
"20261122_0114_account_commodity_global_available_index.py": {
|
||||
"revision": "20261122_0114",
|
||||
"sha256": "3b0da21df3a48784bf5e204d3fc95fc2e40c0edded4601869c36f1d52fe07d4b"
|
||||
},
|
||||
"20261122_0115_account_commodity_eligibility_split.py": {
|
||||
"revision": "20261122_0115",
|
||||
"sha256": "a66dba263e6b2e9b10b2bd52316ef630890b470a3c2b08f8ab0a07ef0521d0fa"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""split account eligibility, offer window and global stock.
|
||||
|
||||
Revision ID: 20261122_0115
|
||||
Revises: 20261122_0114
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261122_0115"
|
||||
down_revision: str | None = "20261122_0114"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
TABLE = "account_commodity_states"
|
||||
INDEX = "ix_account_commodity_eligibility"
|
||||
|
||||
|
||||
def _columns() -> set[str]:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
if not inspector.has_table(TABLE):
|
||||
return set()
|
||||
return {str(column["name"]) for column in inspector.get_columns(TABLE)}
|
||||
|
||||
|
||||
def _indexes() -> set[str]:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
if not inspector.has_table(TABLE):
|
||||
return set()
|
||||
return {str(index["name"]) for index in inspector.get_indexes(TABLE)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
columns = _columns()
|
||||
additions = (
|
||||
sa.Column(
|
||||
"account_eligibility",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="unknown",
|
||||
),
|
||||
sa.Column(
|
||||
"offer_state",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="unknown",
|
||||
),
|
||||
sa.Column(
|
||||
"stock_state",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="unknown",
|
||||
),
|
||||
sa.Column("stock_count", sa.BigInteger(), nullable=True),
|
||||
sa.Column("store_status", sa.Integer(), nullable=True),
|
||||
sa.Column("open_status", sa.Integer(), nullable=True),
|
||||
)
|
||||
for column in additions:
|
||||
if column.name not in columns:
|
||||
op.add_column(TABLE, column)
|
||||
|
||||
# raw_status 是已经落库的账号级 status,不依赖 JSON 函数即可立即恢复资格。
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
UPDATE {TABLE}
|
||||
SET account_eligibility = CASE
|
||||
WHEN raw_status = '0' THEN 'eligible'
|
||||
WHEN raw_status = '1' THEN 'limited'
|
||||
ELSE 'unknown'
|
||||
END
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name == "mysql":
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
UPDATE {TABLE}
|
||||
SET
|
||||
offer_state = CASE
|
||||
WHEN availability = 'not_offered' THEN 'not_offered'
|
||||
WHEN JSON_UNQUOTE(JSON_EXTRACT(
|
||||
raw_json, '$.openStatus'
|
||||
)) = '0' THEN 'before'
|
||||
WHEN available_from IS NOT NULL
|
||||
AND available_from > UTC_TIMESTAMP() THEN 'before'
|
||||
WHEN available_until IS NOT NULL
|
||||
AND available_until < UTC_TIMESTAMP() THEN 'expired'
|
||||
WHEN availability = 'not_open' THEN 'before'
|
||||
WHEN raw_json IS NULL THEN 'unknown'
|
||||
ELSE 'active'
|
||||
END,
|
||||
stock_count = CASE
|
||||
WHEN JSON_EXTRACT(raw_json, '$.count') IS NULL THEN NULL
|
||||
ELSE CAST(JSON_UNQUOTE(
|
||||
JSON_EXTRACT(raw_json, '$.count')
|
||||
) AS SIGNED)
|
||||
END,
|
||||
store_status = CASE
|
||||
WHEN JSON_EXTRACT(raw_json, '$.storeStatus') IS NULL THEN NULL
|
||||
ELSE CAST(JSON_UNQUOTE(
|
||||
JSON_EXTRACT(raw_json, '$.storeStatus')
|
||||
) AS SIGNED)
|
||||
END,
|
||||
open_status = CASE
|
||||
WHEN JSON_EXTRACT(raw_json, '$.openStatus') IS NULL THEN NULL
|
||||
ELSE CAST(JSON_UNQUOTE(
|
||||
JSON_EXTRACT(raw_json, '$.openStatus')
|
||||
) AS SIGNED)
|
||||
END,
|
||||
stock_state = CASE
|
||||
WHEN raw_json IS NULL THEN 'unknown'
|
||||
WHEN COALESCE(
|
||||
CAST(JSON_UNQUOTE(
|
||||
JSON_EXTRACT(raw_json, '$.storeStatus')
|
||||
) AS SIGNED),
|
||||
1
|
||||
) = 0 THEN 'out_of_stock'
|
||||
WHEN COALESCE(
|
||||
CAST(JSON_UNQUOTE(
|
||||
JSON_EXTRACT(raw_json, '$.count')
|
||||
) AS SIGNED),
|
||||
1
|
||||
) <= 0 THEN 'out_of_stock'
|
||||
ELSE 'in_stock'
|
||||
END
|
||||
"""
|
||||
)
|
||||
)
|
||||
else:
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
UPDATE {TABLE}
|
||||
SET offer_state = CASE
|
||||
WHEN availability = 'not_offered' THEN 'not_offered'
|
||||
WHEN available_from IS NOT NULL
|
||||
AND available_from > CURRENT_TIMESTAMP THEN 'before'
|
||||
WHEN available_until IS NOT NULL
|
||||
AND available_until < CURRENT_TIMESTAMP THEN 'expired'
|
||||
WHEN availability = 'not_open' THEN 'before'
|
||||
WHEN raw_json IS NULL THEN 'unknown'
|
||||
ELSE 'active'
|
||||
END
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
if INDEX not in _indexes():
|
||||
op.create_index(
|
||||
INDEX,
|
||||
TABLE,
|
||||
[
|
||||
"platform",
|
||||
"scope",
|
||||
"commodity_id",
|
||||
"account_eligibility",
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if INDEX in _indexes():
|
||||
op.drop_index(INDEX, table_name=TABLE)
|
||||
columns = _columns()
|
||||
for name in (
|
||||
"open_status",
|
||||
"store_status",
|
||||
"stock_count",
|
||||
"stock_state",
|
||||
"offer_state",
|
||||
"account_eligibility",
|
||||
):
|
||||
if name in columns:
|
||||
op.drop_column(TABLE, name)
|
||||
+28
-1
@@ -1899,10 +1899,27 @@ class AccountCommodityState(Base):
|
||||
commodity_name: Mapped[str] = mapped_column(
|
||||
String(256), nullable=False, default="", server_default=""
|
||||
)
|
||||
# available / limited / no_stock / not_open / not_offered / unknown
|
||||
# 展示和执行用的派生状态;自动选号不再读取本列。
|
||||
# available / limited / no_stock / not_open / not_offered / expired / unknown
|
||||
availability: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="unknown", server_default="unknown"
|
||||
)
|
||||
# 账号级兑换资格,只由 storehome.status 决定。
|
||||
# eligible / limited / unknown
|
||||
account_eligibility: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="unknown", server_default="unknown"
|
||||
)
|
||||
# 商品活动窗口:before / active / expired / not_offered / unknown
|
||||
offer_state: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="unknown", server_default="unknown"
|
||||
)
|
||||
# 官方全局库存,只供展示和兑换执行参考,绝不参与自动选号。
|
||||
stock_state: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="unknown", server_default="unknown"
|
||||
)
|
||||
stock_count: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
|
||||
store_status: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
open_status: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
blocking_reason: Mapped[str] = mapped_column(
|
||||
String(255), nullable=False, default="", server_default=""
|
||||
)
|
||||
@@ -1965,6 +1982,16 @@ class AccountCommodityState(Base):
|
||||
"valid_until",
|
||||
"account_id",
|
||||
),
|
||||
Index(
|
||||
"ix_account_commodity_eligibility",
|
||||
"platform",
|
||||
"scope",
|
||||
"commodity_id",
|
||||
"account_eligibility",
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
),
|
||||
Index(
|
||||
"ix_account_commodity_account",
|
||||
"account_id",
|
||||
|
||||
@@ -1545,6 +1545,7 @@ def account_commodities(
|
||||
account_id: int,
|
||||
scope: str = Query("", max_length=16),
|
||||
availability: str = Query("", max_length=16),
|
||||
eligibility: str = Query("", max_length=16),
|
||||
limit: int = Query(500, ge=1, le=1000),
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
@@ -1570,13 +1571,22 @@ def account_commodities(
|
||||
query = query.filter(
|
||||
AccountCommodityState.availability == availability_value
|
||||
)
|
||||
eligibility_value = eligibility.strip()
|
||||
if eligibility_value:
|
||||
query = query.filter(
|
||||
AccountCommodityState.account_eligibility == eligibility_value
|
||||
)
|
||||
rows = (
|
||||
query.order_by(
|
||||
case(
|
||||
(AccountCommodityState.availability == "available", 0),
|
||||
(AccountCommodityState.availability == "limited", 1),
|
||||
(AccountCommodityState.account_eligibility == "eligible", 0),
|
||||
(AccountCommodityState.account_eligibility == "limited", 1),
|
||||
else_=2,
|
||||
),
|
||||
case(
|
||||
(AccountCommodityState.offer_state == "active", 0),
|
||||
else_=1,
|
||||
),
|
||||
AccountCommodityState.valid_until.desc(),
|
||||
AccountCommodityState.commodity_id.asc(),
|
||||
)
|
||||
@@ -1589,6 +1599,12 @@ def account_commodities(
|
||||
"commodity_id": row.commodity_id,
|
||||
"commodity_name": row.commodity_name,
|
||||
"scope": row.scope,
|
||||
"account_eligibility": row.account_eligibility,
|
||||
"offer_state": row.offer_state,
|
||||
"stock_state": row.stock_state,
|
||||
"stock_count": row.stock_count,
|
||||
"store_status": row.store_status,
|
||||
"open_status": row.open_status,
|
||||
"availability": row.availability,
|
||||
"blocking_reason": row.blocking_reason,
|
||||
"raw_status": row.raw_status,
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -115,7 +115,10 @@ export const accountApi = {
|
||||
exchangeRecords: (id: number) =>
|
||||
api.get<AccountExchangeRecords, AccountExchangeRecords>(`/accounts/${id}/exchange-records`),
|
||||
// 账号 × 商品当前能力索引(查询快照,带最后确认时间)
|
||||
commodities: (id: number, params?: { scope?: string; availability?: string; limit?: number }) =>
|
||||
commodities: (
|
||||
id: number,
|
||||
params?: { scope?: string; availability?: string; eligibility?: string; limit?: number },
|
||||
) =>
|
||||
api.get<AccountCommodityStates, AccountCommodityStates>(`/accounts/${id}/commodities`, { params }),
|
||||
// 时间线(倒序分页),event_type 为空表示全部
|
||||
events: (
|
||||
|
||||
@@ -212,6 +212,12 @@ export interface AccountCommodityState {
|
||||
commodity_id: string;
|
||||
commodity_name: string;
|
||||
scope: string;
|
||||
account_eligibility: 'eligible' | 'limited' | 'unknown';
|
||||
offer_state: 'before' | 'active' | 'expired' | 'not_offered' | 'unknown';
|
||||
stock_state: 'in_stock' | 'out_of_stock' | 'unknown';
|
||||
stock_count: number | null;
|
||||
store_status: number | null;
|
||||
open_status: number | null;
|
||||
availability: AccountCommodityAvailability;
|
||||
blocking_reason: string;
|
||||
raw_status: string;
|
||||
@@ -897,6 +903,8 @@ export interface DouyuAccountPlatformStatus {
|
||||
sync_domains: Record<string, Record<string, number>>;
|
||||
commodities: {
|
||||
by_availability: Record<string, { total: number; fresh: number }>;
|
||||
by_account_eligibility: Record<string, { total: number; fresh: number }>;
|
||||
fresh_eligible: number;
|
||||
fresh_available: number;
|
||||
fresh_limited: number;
|
||||
};
|
||||
@@ -2444,6 +2452,7 @@ export interface PlatformFulfillmentTask {
|
||||
scope: string;
|
||||
commodityMappingId: number | null;
|
||||
commodityId: string;
|
||||
goodsName: string;
|
||||
requiredPoints: number | null;
|
||||
saleMode: 'presale' | 'direct' | 'manual' | 'unknown';
|
||||
campaignKey: string;
|
||||
|
||||
@@ -138,6 +138,34 @@ function commodityStateTag(value: string) {
|
||||
return <Tag color={state.color}>{state.label}</Tag>;
|
||||
}
|
||||
|
||||
const ACCOUNT_ELIGIBILITY: Record<string, { label: string; color: string }> = {
|
||||
eligible: { label: '账号可兑换', color: 'green' },
|
||||
limited: { label: '账号已限兑', color: 'orange' },
|
||||
unknown: { label: '资格待确认', color: 'default' },
|
||||
};
|
||||
|
||||
const OFFER_STATE: Record<string, { label: string; color: string }> = {
|
||||
before: { label: '活动未开始', color: 'gold' },
|
||||
active: { label: '活动进行中', color: 'blue' },
|
||||
expired: { label: '活动已结束', color: 'default' },
|
||||
not_offered: { label: '商品未上架', color: 'default' },
|
||||
unknown: { label: '时间待确认', color: 'default' },
|
||||
};
|
||||
|
||||
const STOCK_STATE: Record<string, { label: string; color: string }> = {
|
||||
in_stock: { label: '有库存', color: 'green' },
|
||||
out_of_stock: { label: '官方无库存', color: 'default' },
|
||||
unknown: { label: '库存未知', color: 'default' },
|
||||
};
|
||||
|
||||
function splitStateTag(
|
||||
value: string,
|
||||
states: Record<string, { label: string; color: string }>,
|
||||
) {
|
||||
const state = states[value] ?? Object.values(states).at(-1);
|
||||
return <Tag color={state?.color}>{state?.label || value}</Tag>;
|
||||
}
|
||||
|
||||
/** 金额展示:充值为正(绿色 ¥),兑换消耗为负(红色积分)。 */
|
||||
function amountText(item: AccountEventItem) {
|
||||
if (item.amount === null || item.amount === undefined) return null;
|
||||
@@ -352,9 +380,33 @@ export default function AccountDetailPage() {
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '当前能力',
|
||||
title: '账号兑换资格',
|
||||
dataIndex: 'account_eligibility',
|
||||
width: 130,
|
||||
render: (value: string) => splitStateTag(value, ACCOUNT_ELIGIBILITY),
|
||||
},
|
||||
{
|
||||
title: '活动状态',
|
||||
dataIndex: 'offer_state',
|
||||
width: 120,
|
||||
render: (value: string) => splitStateTag(value, OFFER_STATE),
|
||||
},
|
||||
{
|
||||
title: '官方库存(仅参考)',
|
||||
width: 150,
|
||||
render: (_value, row) => (
|
||||
<Space direction="vertical" size={0}>
|
||||
{splitStateTag(row.stock_state, STOCK_STATE)}
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
数量 {row.stock_count ?? '-'}
|
||||
</Text>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '兑换执行',
|
||||
dataIndex: 'availability',
|
||||
width: 110,
|
||||
width: 120,
|
||||
render: (value: string) => commodityStateTag(value),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -266,7 +266,7 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
|
||||
return reasons.length ? `${base};后续需要:${reasons.join('、')}` : `${base};可直接兑换`;
|
||||
}
|
||||
if (event.eventType === 'mapping_updated') {
|
||||
return `斗鱼商品 ${String(detail.commodityId || '-')},映射${detail.enabled === false ? '已停用' : '已启用'}`;
|
||||
return `斗鱼商品 ${String(detail.goodsName || detail.commodityId || '-')},映射${detail.enabled === false ? '已停用' : '已启用'}`;
|
||||
}
|
||||
if (event.eventType === 'exchange_eligibility_checked') {
|
||||
return `兑换状态:${exchangeStatusLabel(String(detail.exchangeStatus || ''))};限兑商品 ${String(detail.limitedCount ?? 0)} 个`;
|
||||
@@ -1060,7 +1060,9 @@ export default function PlatformFulfillmentPage() {
|
||||
width: 230,
|
||||
render: (_, task) => (
|
||||
<Space direction="vertical" size={2}>
|
||||
<Text>{task.commodityId || '未映射'}</Text>
|
||||
<Text ellipsis title={task.commodityId}>
|
||||
{task.goodsName || task.skuName || task.internalSkuKey || '未映射'}
|
||||
</Text>
|
||||
<Text type="secondary">{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}</Text>
|
||||
</Space>
|
||||
),
|
||||
@@ -1518,7 +1520,7 @@ export default function PlatformFulfillmentPage() {
|
||||
{selected.internalSkuKey || '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="斗鱼商品" span={2}>
|
||||
{selected.commodityId || '未映射'}
|
||||
{selected.goodsName || selected.skuName || '未映射'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="销售模式">
|
||||
{SALE_MODE_LABELS[selected.saleMode] || selected.saleMode}
|
||||
|
||||
Reference in New Issue
Block a user