"""共享常量、快照解析与订单匹配基础函数。""" from __future__ import annotations import os from datetime import UTC, datetime from typing import Any from sqlalchemy.orm import Session from ...models import ( PlatformCommodityMapping, PlatformFulfillmentSetting, PlatformFulfillmentTask, ) from ..account_capability_service import ( AVAILABILITY_AVAILABLE, exchange_gate_for_availability, ) from ..douyu_account_state import DouyuLiveAccountState TARGET_PLATFORM = "douyu" SCOPE_ELITE = "elite" BINDING_COOLDOWN_ISSUES = frozenset({"account_role_cooldown", "customer_role_cooldown"}) ACTIVE_STATUSES = { "ready", "allocated", "waiting_bind", "role_ready", "binding_confirming", "bound", "manual_required", } BINDING_QR_TTL_SECONDS = int(os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "1260")) AUTO_SYNC_INTERVAL_SECONDS = 900.0 DEFAULT_CAPABILITY_CANDIDATE_LIMIT = 20 LOCAL_STOCK_RETRY_SECONDS = 5 * 60 LOCAL_CACHE_MISS_RETRY_SECONDS = 2 * 60 LOCAL_LEASE_CONFLICT_RETRY_SECONDS = 5 DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES = 120 def binding_failed_lease_ttl_minutes() -> int: """扫码超时任务的账号保留时间;过期后允许重新进入选号池。""" try: value = int( os.getenv( "PLATFORM_BINDING_FAILED_LEASE_TTL_MINUTES", str(DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES), ) ) except ValueError: return DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES return max(1, value) def _exchange_gate( state: DouyuLiveAccountState, commodity_id: str, *, allow_not_open: bool = False, ) -> tuple[str, str, str]: """把实时商品资格映射为履约可展示的硬门槛。""" limited = commodity_id in state.limited_ids if not state.commodity_availability: return ( exchange_gate_for_availability( AVAILABILITY_AVAILABLE, limited=limited, ) if limited else ("", "", "") ) availability = state.commodity_availability.get(commodity_id) reason = state.commodity_blocking_reasons.get(commodity_id, "") return exchange_gate_for_availability( availability, reason=reason, limited=limited, allow_not_open=allow_not_open, ) def _now() -> datetime: return datetime.now(UTC) def _jsonable(value: Any) -> Any: if isinstance(value, datetime): return value.isoformat() if isinstance(value, dict): return {str(key): _jsonable(item) for key, item in value.items()} if isinstance(value, (list, tuple)): return [_jsonable(item) for item in value] if isinstance(value, (str, int, float, bool)) or value is None: return value return str(value) def _mapping_for_sku( db: Session, internal_sku_key: str ) -> PlatformCommodityMapping | None: return ( db.query(PlatformCommodityMapping) .filter( PlatformCommodityMapping.target_platform == TARGET_PLATFORM, PlatformCommodityMapping.internal_sku_key == internal_sku_key, PlatformCommodityMapping.enabled.is_(True), PlatformCommodityMapping.archived_at.is_(None), ) .order_by(PlatformCommodityMapping.updated_at.desc()) .first() ) def _parse_snapshot_datetime(value: Any) -> datetime | None: if isinstance(value, datetime): return value if value.tzinfo is not None else value.replace(tzinfo=UTC) text = str(value or "").strip() if not text: return None try: parsed = datetime.fromisoformat(text) except ValueError: return None return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC) def _snapshot_value(data: dict[str, Any], *names: str, default: Any = "") -> Any: for name in names: if name in data and data[name] is not None: return data[name] return default def _order_snapshot_from_event(payload: dict[str, Any]) -> dict[str, Any]: data = payload.get("data") return data if isinstance(data, dict) else payload def _order_match_started_at(db: Session) -> datetime | None: row = ( db.query(PlatformFulfillmentSetting) .filter(PlatformFulfillmentSetting.id == 1) .first() ) return row.order_match_started_at if row is not None else None def _apply_order_match_cutoff( query, match_started_at: datetime | None, ): if match_started_at is None: return query return query.filter(PlatformFulfillmentTask.paid_at >= match_started_at)