"""直播账号履约:按商品统计当前可分配账号库存。""" from __future__ import annotations from datetime import datetime, timedelta from typing import Any from sqlalchemy import and_, case, func, or_, select from sqlalchemy.orm import Session from ...models import Account, AccountCommodityState, AccountEvent from ..account_query_filters import ( active_collab_order_exists, active_lease_exists, assigned_to_pool_filter, automatable_account_filter, cookie_present_filter, fresh_eligible_state_filter, role_change_ready_filter, valid_ck_filter, ) from .account_selector import ( EXCHANGE_COOLDOWN_DAYS, _co_commodity_eligible_exists, ) from .common import SCOPE_ELITE, TARGET_PLATFORM, _jsonable, _now from .policy import bundle_requirements_for_commodity, normalize_allocation_policy from .runtime import get_settings def _clean_commodity_ids(values: list[str] | tuple[str, ...]) -> tuple[str, ...]: cleaned: list[str] = [] for value in values: commodity_id = str(value or "").strip()[:64] if commodity_id and commodity_id not in cleaned: cleaned.append(commodity_id) return tuple(cleaned[:100]) def _allocatable_pool_filter(now: datetime): return and_( cookie_present_filter(), valid_ck_filter(), automatable_account_filter(), assigned_to_pool_filter(), role_change_ready_filter(now), ~active_lease_exists(), ~active_collab_order_exists(), ) def _recent_exchange_exists( *, since: datetime, commodity_ids: tuple[str, ...], ): return ( select(AccountEvent.id) .where( AccountEvent.account_id == Account.id, AccountEvent.event_type == "exchange", AccountEvent.subject_key.in_(commodity_ids), AccountEvent.occurred_at >= since, ) .exists() ) def _recent_exchange_for_joined_state_exists(*, since: datetime): return ( select(AccountEvent.id) .where( AccountEvent.account_id == Account.id, AccountEvent.event_type == "exchange", AccountEvent.subject_key == AccountCommodityState.commodity_id, AccountEvent.occurred_at >= since, ) .exists() ) def _bundle_group( policy: dict[str, Any], commodity_id: str, ) -> tuple[str, ...]: required, preferred = bundle_requirements_for_commodity(policy, commodity_id) return tuple(dict.fromkeys((commodity_id, *required, *preferred))) def _full_bundle_allocatable_count( db: Session, *, group: tuple[str, ...], scope: str, now: datetime, ) -> int: commodity_id = group[0] since = now - timedelta(days=EXCHANGE_COOLDOWN_DAYS) query = ( db.query(func.count(func.distinct(Account.id))) .join( AccountCommodityState, AccountCommodityState.account_id == Account.id, ) .filter( AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.scope == scope, AccountCommodityState.commodity_id == commodity_id, fresh_eligible_state_filter(now, allow_before_open=True), or_( AccountCommodityState.last_exchange_at.is_(None), AccountCommodityState.last_exchange_at < since, ), _allocatable_pool_filter(now), ~_recent_exchange_exists(since=since, commodity_ids=group), ) ) for peer_id in group[1:]: query = query.filter( _co_commodity_eligible_exists( peer_id, scope=scope, moment=now, since=since, ) ) return int(query.scalar() or 0) def get_account_availability( db: Session, *, commodity_ids: list[str] | tuple[str, ...], scope: str = SCOPE_ELITE, now: datetime | None = None, ) -> dict[str, Any]: """返回当前页商品的可分配库存,并按账号去重汇总。""" ids = _clean_commodity_ids(commodity_ids) moment = now or _now() if not ids: return { "items": {}, "uniqueAllocatable": 0, "updatedAt": _jsonable(moment), } since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS) allocatable_filter = _allocatable_pool_filter(moment) rows = ( db.query( AccountCommodityState.commodity_id.label("commodity_id"), func.count(func.distinct(Account.id)).label("eligible"), func.count( func.distinct( case((role_change_ready_filter(moment), Account.id)) ) ).label("role_ready"), func.count( func.distinct( case((active_lease_exists(), Account.id)) ) ).label("leased"), func.count( func.distinct( case((active_collab_order_exists(), Account.id)) ) ).label("active_collab"), func.count( func.distinct( case( ( and_( allocatable_filter, ~_recent_exchange_for_joined_state_exists( since=since ), ), Account.id, ) ) ) ).label("allocatable"), ) .join(Account, Account.id == AccountCommodityState.account_id) .filter( AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.scope == scope, AccountCommodityState.commodity_id.in_(ids), fresh_eligible_state_filter(moment, allow_before_open=True), or_( AccountCommodityState.last_exchange_at.is_(None), AccountCommodityState.last_exchange_at < since, ), ) .group_by(AccountCommodityState.commodity_id) .all() ) counts = {str(row.commodity_id): row for row in rows} policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy")) bundle_groups: dict[str, tuple[str, ...]] = {} bundle_counts: dict[tuple[str, ...], int] = {} for commodity_id in ids: group = _bundle_group(policy, commodity_id) bundle_groups[commodity_id] = group if len(group) > 1 and group not in bundle_counts: bundle_counts[group] = _full_bundle_allocatable_count( db, group=group, scope=scope, now=moment, ) items: dict[str, dict[str, int]] = {} for commodity_id in ids: row = counts.get(commodity_id) eligible = int(getattr(row, "eligible", 0) or 0) role_ready = int(getattr(row, "role_ready", 0) or 0) allocatable = int(getattr(row, "allocatable", 0) or 0) group = bundle_groups[commodity_id] items[commodity_id] = { "allocatable": allocatable, "fullBundleAllocatable": ( bundle_counts.get(group, 0) if len(group) > 1 else allocatable ), "bundleCommodityCount": len(group), "roleCooldown": max(0, eligible - role_ready), "leased": int(getattr(row, "leased", 0) or 0), "activeCollab": int(getattr(row, "active_collab", 0) or 0), } unique_allocatable = int( db.query(func.count(func.distinct(Account.id))) .join( AccountCommodityState, AccountCommodityState.account_id == Account.id, ) .filter( AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.scope == scope, AccountCommodityState.commodity_id.in_(ids), fresh_eligible_state_filter(moment, allow_before_open=True), or_( AccountCommodityState.last_exchange_at.is_(None), AccountCommodityState.last_exchange_at < since, ), allocatable_filter, ~_recent_exchange_exists(since=since, commodity_ids=ids), ) .scalar() or 0 ) return { "items": items, "uniqueAllocatable": unique_allocatable, "updatedAt": _jsonable(moment), } __all__ = ["get_account_availability"]