Files
live-hub-py/web/backend/services/account_capability_service.py
T

569 lines
18 KiB
Python

"""账号商品能力索引。
``accounts`` 回答“账号整体能不能用”,本模块回答“账号对具体商品现在能不能换”。
能力索引只保存查询投影;兑换等不可变事实仍写 ``account_events``。
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import case, func
from sqlalchemy.orm import Session
from ..models import Account, AccountCommodityState, AccountEvent
AVAILABILITY_AVAILABLE = "available"
AVAILABILITY_LIMITED = "limited"
AVAILABILITY_NO_STOCK = "no_stock"
AVAILABILITY_NOT_OPEN = "not_open"
AVAILABILITY_NOT_OFFERED = "not_offered"
AVAILABILITY_EXPIRED = "expired"
AVAILABILITY_UNKNOWN = "unknown"
DEFAULT_CAPABILITY_TTL_SECONDS = 15 * 60
def _env_positive_int(name: str, default: int) -> int:
try:
value = int(os.getenv(name, str(default)))
except ValueError:
return default
return value if value > 0 else default
def capability_ttl_seconds() -> int:
return _env_positive_int(
"ACCOUNT_COMMODITY_STATE_TTL_SECONDS",
DEFAULT_CAPABILITY_TTL_SECONDS,
)
def _to_int(value: Any) -> int | None:
if value is None or value == "":
return None
try:
return int(float(value))
except (TypeError, ValueError):
return None
def _to_datetime(value: Any) -> datetime | None:
timestamp = _to_int(value)
if timestamp is None or timestamp <= 0:
return None
if timestamp > 10_000_000_000:
timestamp //= 1000
return datetime.fromtimestamp(timestamp, tz=UTC)
@dataclass(frozen=True)
class GoodsTimeWindow:
time_limited: bool
start: datetime | None
end: datetime | None
state: str
next_boundary: datetime | None
schedule: list[dict[str, Any]]
def goods_time_window(
item: dict[str, Any],
*,
now: datetime | None = None,
) -> GoodsTimeWindow:
"""解析商品限时窗口。
``status`` 是账号维度的限兑;时间窗口是商品维度的开放区间。两者必须同时
判断。``specTimes`` 优先于外层 start/end,用于一天多场或分阶段开放。
"""
moment = now or datetime.now(UTC)
intervals: list[tuple[datetime, datetime]] = []
schedule: list[dict[str, Any]] = []
raw_spec_times = item.get("specTimes")
if isinstance(raw_spec_times, list):
for raw in raw_spec_times:
if not isinstance(raw, dict):
continue
schedule.append(dict(raw))
start = _to_datetime(raw.get("startTime"))
end = _to_datetime(raw.get("endTime"))
if start is not None and end is not None and end >= start:
intervals.append((start, end))
if not intervals:
start = _to_datetime(item.get("startTime"))
end = _to_datetime(item.get("endTime"))
if start is not None and end is not None and end >= start:
intervals.append((start, end))
time_limited = bool(_to_int(item.get("timeLimited")))
if not intervals:
return GoodsTimeWindow(
time_limited=time_limited,
start=None,
end=None,
state="",
next_boundary=None,
schedule=schedule,
)
intervals.sort(key=lambda value: value[0])
for start, end in intervals:
if start <= moment <= end:
return GoodsTimeWindow(
time_limited=time_limited,
start=start,
end=end,
state="active",
next_boundary=end,
schedule=schedule,
)
for start, end in intervals:
if start > moment:
return GoodsTimeWindow(
time_limited=time_limited,
start=start,
end=end,
state="before",
next_boundary=start,
schedule=schedule,
)
start, end = intervals[-1]
return GoodsTimeWindow(
time_limited=time_limited,
start=start,
end=end,
state="after",
next_boundary=None,
schedule=schedule,
)
def classify_goods_item(
item: dict[str, Any],
*,
now: datetime | None = None,
) -> tuple[str, str, str]:
"""把官方 storehome 商品项归一成能力状态。
返回 ``(availability, blocking_reason, raw_status)``。只有官方明确给出的
账号级 ``status`` 才允许写成 available / limited;缺字段一律 unknown。
"""
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 "")
status = _to_int(item.get("status"))
store_status = _to_int(
item.get("storeStatus")
if item.get("storeStatus") is not None
else item.get("store_status")
)
open_status = _to_int(
item.get("openStatus")
if item.get("openStatus") is not None
else item.get("open_status")
)
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
def _exchange_stats(
db: Session,
*,
account_id: int,
now: datetime,
) -> dict[str, tuple[datetime | None, int]]:
since = now - timedelta(days=365)
recent_rows = (
db.query(
AccountEvent.subject_key,
func.max(AccountEvent.occurred_at),
func.count(AccountEvent.id),
)
.filter(
AccountEvent.account_id == account_id,
AccountEvent.event_type == "exchange",
AccountEvent.subject_key != "",
AccountEvent.occurred_at >= since,
)
.group_by(AccountEvent.subject_key)
.all()
)
latest_rows = (
db.query(
AccountEvent.subject_key,
func.max(AccountEvent.occurred_at),
)
.filter(
AccountEvent.account_id == account_id,
AccountEvent.event_type == "exchange",
AccountEvent.subject_key != "",
)
.group_by(AccountEvent.subject_key)
.all()
)
latest = {
str(key or ""): value
for key, value in latest_rows
if str(key or "")
}
stats: dict[str, tuple[datetime | None, int]] = {}
for key, recent_at, recent_count in recent_rows:
commodity_id = str(key or "")
if not commodity_id:
continue
stats[commodity_id] = (
latest.get(commodity_id) or recent_at,
int(recent_count or 0),
)
for commodity_id, value in latest.items():
stats.setdefault(commodity_id, (value, 0))
return stats
def _commodity_id(item: dict[str, Any]) -> str:
return str(
item.get("commodityId")
or item.get("commodity_id")
or item.get("id")
or ""
).strip()
def _commodity_name(item: dict[str, Any]) -> str:
return str(
item.get("name")
or item.get("commodityName")
or item.get("commodity_name")
or ""
).strip()
def sync_account_goods_states(
db: Session,
account: Account,
goods_items: list[dict[str, Any]],
*,
scope: str = "elite",
observed_at: datetime | None = None,
source: str = "overview",
replace_missing: bool = True,
) -> int:
"""用一次完整官方商品列表刷新账号商品能力。
只在整份商品列表查询成功时调用。单项/整份失败时不要调用本函数,避免把
“没查到”误写成“不可兑换”。
"""
if not goods_items or account.id is None:
return 0
moment = observed_at or datetime.now(UTC)
valid_until = moment + timedelta(seconds=capability_ttl_seconds())
existing_rows = (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
)
.all()
)
by_commodity = {row.commodity_id: row for row in existing_rows}
exchange_stats = _exchange_stats(db, account_id=int(account.id), now=moment)
seen: set[str] = set()
changed = 0
for item in goods_items:
if not isinstance(item, dict):
continue
commodity_id = _commodity_id(item)
if not commodity_id:
continue
seen.add(commodity_id)
state = by_commodity.get(commodity_id)
if state is None:
state = AccountCommodityState(
account_id=int(account.id),
platform="douyu",
scope=scope,
commodity_id=commodity_id,
created_at=moment,
)
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)
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.time_limited = window.time_limited
state.available_from = window.start
state.available_until = window.end
state.schedule_json = window.schedule or None
state.observed_at = moment
state.valid_until = valid_until
state.next_check_at = (
min(valid_until, window.next_boundary)
if window.next_boundary is not None
else valid_until
)
state.last_exchange_at = last_exchange_at
state.exchange_count_365d = int(exchange_count)
state.source = source[:24]
state.error_code = ""
state.updated_at = moment
changed += 1
if replace_missing:
for commodity_id, state in by_commodity.items():
if commodity_id in seen:
continue
if (
state.availability == AVAILABILITY_NOT_OFFERED
and state.blocking_reason == "官方商品列表本次未返回该商品"
):
continue
state.availability = AVAILABILITY_NOT_OFFERED
state.blocking_reason = "官方商品列表本次未返回该商品"
state.observed_at = moment
state.valid_until = None
state.next_check_at = valid_until
state.source = source[:24]
state.updated_at = moment
changed += 1
db.flush()
return changed
def record_account_commodity_state(
db: Session,
account: Account,
*,
commodity_id: str,
availability: str,
blocking_reason: str = "",
raw_status: str = "",
observed_at: datetime | None = None,
source: str = "live_check",
scope: str = "elite",
valid_for_seconds: int | None = None,
error_code: str = "",
) -> AccountCommodityState:
"""写入单个商品的实时检查结论,供下一轮匹配直接使用。"""
moment = observed_at or datetime.now(UTC)
ttl = (
capability_ttl_seconds()
if valid_for_seconds is None
else max(1, int(valid_for_seconds))
)
state = (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
)
.first()
)
if state is None:
state = AccountCommodityState(
account_id=int(account.id),
platform="douyu",
scope=scope,
commodity_id=commodity_id,
created_at=moment,
)
db.add(state)
exchange_stats = _exchange_stats(
db,
account_id=int(account.id),
now=moment,
)
last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (None, 0))
state.availability = availability
state.blocking_reason = blocking_reason[:255]
state.raw_status = raw_status[:16]
state.observed_at = moment
state.valid_until = moment + timedelta(seconds=ttl)
state.next_check_at = state.valid_until
state.last_exchange_at = last_exchange_at
state.exchange_count_365d = int(exchange_count)
state.source = source[:24]
state.error_code = error_code[:64]
state.updated_at = moment
db.flush()
return state
def mark_commodity_exchanged(
db: Session,
*,
account_id: int,
commodity_id: str,
occurred_at: datetime | None = None,
scope: str = "elite",
commodity_name: str = "",
) -> None:
"""实际兑换后立即更新匹配投影,避免下一单再次选中。"""
if not commodity_id:
return
moment = occurred_at or datetime.now(UTC)
state = (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
)
.first()
)
if state is None:
state = AccountCommodityState(
account_id=account_id,
platform="douyu",
scope=scope,
commodity_id=commodity_id,
created_at=moment,
)
db.add(state)
exchange_stats = _exchange_stats(db, account_id=account_id, now=moment)
last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (moment, 1))
if commodity_name:
state.commodity_name = commodity_name[:256]
state.availability = AVAILABILITY_LIMITED
state.blocking_reason = "该账号已兑换过此商品,365 天内不可重复分配"
state.observed_at = moment
state.valid_until = None
state.next_check_at = moment + timedelta(days=365)
state.last_exchange_at = last_exchange_at
state.exchange_count_365d = max(1, int(exchange_count))
state.source = "exchange"
state.error_code = ""
state.updated_at = moment
db.flush()
def invalidate_account_commodity_states(
db: Session,
*,
account_id: int,
reason: str,
observed_at: datetime | None = None,
) -> int:
"""CK 失效等全局风险发生时,立即作废所有可匹配能力。"""
moment = observed_at or datetime.now(UTC)
changed = (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.availability == AVAILABILITY_AVAILABLE,
)
.update(
{
AccountCommodityState.availability: AVAILABILITY_UNKNOWN,
AccountCommodityState.blocking_reason: reason[:255],
AccountCommodityState.observed_at: moment,
AccountCommodityState.valid_until: None,
AccountCommodityState.next_check_at: moment,
AccountCommodityState.updated_at: moment,
},
synchronize_session=False,
)
)
return int(changed or 0)
def account_capability_counts(
db: Session,
*,
account_id: int,
now: datetime | None = None,
) -> dict[str, int]:
moment = now or datetime.now(UTC)
rows = (
db.query(
AccountCommodityState.availability,
func.count(AccountCommodityState.id),
func.sum(
case(
(
AccountCommodityState.availability
== AVAILABILITY_AVAILABLE,
1,
),
else_=0,
)
),
)
.filter(AccountCommodityState.account_id == account_id)
.group_by(AccountCommodityState.availability)
.all()
)
result = {str(status): int(count or 0) for status, count, _ in rows}
fresh_available = (
db.query(func.count(AccountCommodityState.id))
.filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.availability == AVAILABILITY_AVAILABLE,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > moment,
)
.scalar()
or 0
)
result["fresh_available"] = int(fresh_available)
result["total"] = sum(
value for key, value in result.items() if key not in {"fresh_available", "total"}
)
return result
__all__ = [
"AVAILABILITY_AVAILABLE",
"AVAILABILITY_EXPIRED",
"AVAILABILITY_LIMITED",
"AVAILABILITY_NOT_OFFERED",
"AVAILABILITY_NOT_OPEN",
"AVAILABILITY_NO_STOCK",
"AVAILABILITY_UNKNOWN",
"account_capability_counts",
"capability_ttl_seconds",
"classify_goods_item",
"goods_time_window",
"invalidate_account_commodity_states",
"mark_commodity_exchanged",
"record_account_commodity_state",
"sync_account_goods_states",
]