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

870 lines
28 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, or_
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"
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
DEFAULT_NO_STOCK_CAPABILITY_TTL_SECONDS = 15 * 60
DEFAULT_UNKNOWN_CAPABILITY_TTL_SECONDS = 5 * 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(availability: str | None = None) -> int:
"""按能力稳定性返回快照 TTL。
30k 级账号池无法在 15 分钟内全量刷新一遍。把稳定的“可兑换/未开放”
仍按 15 分钟处理,会让本地能力池长期处于过期状态,选号又退化到逐个
实时扫描。库存和未知状态变化快,因此保持短 TTL;账号是否具备活动资格、
是否达到限兑上限则使用长 TTL,兑换前仍会再做实时复核。
"""
generic = _env_positive_int(
"ACCOUNT_COMMODITY_STATE_TTL_SECONDS",
DEFAULT_CAPABILITY_TTL_SECONDS,
)
if availability in {AVAILABILITY_AVAILABLE, AVAILABILITY_NOT_OPEN}:
return _env_positive_int(
"ACCOUNT_COMMODITY_STABLE_TTL_SECONDS",
DEFAULT_STABLE_CAPABILITY_TTL_SECONDS,
)
if availability == AVAILABILITY_LIMITED:
return _env_positive_int(
"ACCOUNT_COMMODITY_LIMITED_TTL_SECONDS",
DEFAULT_LIMITED_CAPABILITY_TTL_SECONDS,
)
if availability == AVAILABILITY_NO_STOCK:
return _env_positive_int(
"ACCOUNT_COMMODITY_NO_STOCK_TTL_SECONDS",
DEFAULT_NO_STOCK_CAPABILITY_TTL_SECONDS,
)
if availability == AVAILABILITY_UNKNOWN:
return _env_positive_int(
"ACCOUNT_COMMODITY_UNKNOWN_TTL_SECONDS",
DEFAULT_UNKNOWN_CAPABILITY_TTL_SECONDS,
)
return generic
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,
)
@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,
) -> 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 "")
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 status == 1:
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,
)
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(
goods_items: list[dict[str, Any]],
*,
now: datetime | None = None,
) -> dict[str, GoodsAssessment]:
"""一次性归一完整商品列表,供选号、实时复核和展示共享。"""
assessments: dict[str, GoodsAssessment] = {}
for item in goods_items:
if not isinstance(item, dict):
continue
commodity_id = str(
item.get("commodityId") or item.get("commodity_id") or ""
).strip()
if not commodity_id:
continue
assessments[commodity_id] = classify_goods_item_assessment(item, now=now)
return assessments
def exchange_gate_for_availability(
availability: str | None,
*,
reason: str = "",
limited: bool = False,
allow_not_open: bool = False,
) -> tuple[str, str, str]:
"""把统一能力状态映射为履约兑换门槛,避免各入口重复维护状态表。"""
if limited:
return (
"limited",
"commodity_limit_reached",
reason or "该账号已达到此商品兑换上限",
)
if availability == AVAILABILITY_AVAILABLE:
return "", "", ""
if allow_not_open and availability == AVAILABILITY_NOT_OPEN:
return (
"waiting_release",
"commodity_not_open",
reason or "商品限时兑换尚未开始,可提前绑定角色",
)
issue_map = {
None: ("commodity_not_offered", "官方商品列表本次未返回该商品,可能已下架"),
AVAILABILITY_NOT_OPEN: ("commodity_not_open", "商品限时兑换尚未开始"),
AVAILABILITY_EXPIRED: ("commodity_expired", "商品限时兑换已经结束"),
AVAILABILITY_NO_STOCK: ("commodity_no_stock", "商品当前无库存"),
AVAILABILITY_NOT_OFFERED: ("commodity_not_offered", "商品当前未上架"),
AVAILABILITY_UNKNOWN: ("commodity_status_unknown", "商品资格状态未知"),
AVAILABILITY_LIMITED: (
"commodity_limit_reached",
"该账号已达到此商品兑换上限",
),
}
issue_code, fallback = issue_map.get(
availability,
("commodity_not_exchangeable", "商品当前不可兑换"),
)
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,
*,
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)
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
assessment = classify_goods_item_assessment(item, now=moment)
window = assessment.window
ttl_valid_until = moment + timedelta(
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.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
state.available_until = window.end
state.schedule_json = window.schedule or None
state.observed_at = moment
state.valid_until = (
min(ttl_valid_until, window.next_boundary)
if window.next_boundary is not None
else ttl_valid_until
)
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 = ""
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.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
state.available_from = None
state.available_until = None
state.schedule_json = None
state.observed_at = moment
state.valid_until = None
state.next_check_at = moment + timedelta(
seconds=capability_ttl_seconds(AVAILABILITY_NOT_OFFERED)
)
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,
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,
source: str = "live_check",
scope: str = "elite",
valid_for_seconds: int | None = None,
error_code: str = "",
) -> 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
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.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]
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.account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED
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.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,
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,
or_(
AccountCommodityState.available_from.is_(None),
AccountCommodityState.available_from <= moment,
),
or_(
AccountCommodityState.available_until.is_(None),
AccountCommodityState.available_until >= moment,
),
)
.scalar()
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",
"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",
"AVAILABILITY_NOT_OFFERED",
"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",
"invalidate_account_commodity_states",
"mark_commodity_exchanged",
"record_account_commodity_state",
"sync_account_goods_states",
]