"""直播账号履约工作台的销售模式、开放状态和工作队列派生。""" from __future__ import annotations from datetime import UTC, datetime from typing import Any SALE_MODES = {"presale", "direct", "manual", "unknown"} AVAILABILITY_WAITING_RELEASE = "waiting_release" AVAILABILITY_AVAILABLE = "available" AVAILABILITY_SOLD_OUT = "sold_out" AVAILABILITY_ENDED = "ended" AVAILABILITY_UNKNOWN = "unknown" QUEUE_PENDING_MAPPING = "pending_mapping" QUEUE_PRESALE_WAITING = "presale_waiting" QUEUE_READY = "ready_for_fulfillment" QUEUE_NEEDS_ACTION = "needs_action" QUEUE_COMPLETED = "completed" QUEUE_CANCELLED = "cancelled" QUEUE_BUCKETS = { QUEUE_PENDING_MAPPING, QUEUE_PRESALE_WAITING, QUEUE_READY, QUEUE_NEEDS_ACTION, QUEUE_COMPLETED, QUEUE_CANCELLED, } def normalize_sale_mode(value: Any) -> str: mode = str(value or "").strip().lower() return mode if mode in SALE_MODES else "unknown" def availability_state( *, sale_mode: str, available_from: datetime | None, available_until: datetime | None, goods_status: str = "", now: datetime | None = None, ) -> str: """按报价窗口和最近商品状态派生,不回写销售模式。""" moment = now or datetime.now(UTC) if available_from is not None and moment < _aware(available_from): return AVAILABILITY_WAITING_RELEASE if available_until is not None and moment > _aware(available_until): return AVAILABILITY_ENDED status = str(goods_status or "").strip().lower() if status in {"sold_out", "out_of_stock"}: return AVAILABILITY_SOLD_OUT if sale_mode == "presale": return ( AVAILABILITY_AVAILABLE if available_from is not None else AVAILABILITY_WAITING_RELEASE ) if sale_mode in {"direct", "manual"}: return AVAILABILITY_AVAILABLE if available_from is not None or available_until is not None: return AVAILABILITY_AVAILABLE return AVAILABILITY_UNKNOWN def manual_reason(issue_code: str, exchange_status: str) -> str: issue = str(issue_code or "").strip() exchange = str(exchange_status or "").strip() if issue == "points_short" or exchange == "points_short": return "points_short" if issue == "elite_not_opened" or exchange == "not_opened": return "elite_not_opened" if issue == "commodity_limit_reached" or exchange == "limited": return "limit_reached" if issue in {"binding_failed", "account_role_cooldown", "customer_role_cooldown"}: return "binding_failed" if issue in {"lease_expired", "manual_required"}: return "account_cooldown" return "other_manual" def queue_bucket( *, execution_status: str, sale_mode: str, availability: str, ) -> str: status = str(execution_status or "") if status == "cancelled": return QUEUE_CANCELLED if status == "completed": return QUEUE_COMPLETED if status == "pending_mapping": return QUEUE_PENDING_MAPPING if sale_mode == "presale" and availability == AVAILABILITY_WAITING_RELEASE: return QUEUE_PRESALE_WAITING if status == "manual_required": return QUEUE_NEEDS_ACTION return QUEUE_READY def _aware(value: datetime) -> datetime: return value if value.tzinfo is not None else value.replace(tzinfo=UTC)