"""账号供给画像投影:角色、质量分、冗余级别。 只读派生计算,不改变账号事实;硬角色(租约/人工/生命周期)优先于质量分。 """ from __future__ import annotations from datetime import UTC, datetime, timedelta from typing import Any from sqlalchemy import func, or_ from sqlalchemy.orm import Session from ..models import ( Account, AccountCommodityState, AccountLease, AccountSupplyProfile, ) from .account_lifecycle import MANUAL_KINDS, STATUS_MANUAL from .high_value_service import ( HIGH_VALUE_STATUS_AVAILABLE, HIGH_VALUE_STATUS_OWNED, ) SCORE_VERSION = "v1" CK_LIFETIME = timedelta(days=7) LEASE_LABELS = { "platform_fulfillment": "fulfillment_protected", "douyu_collab": "collab_protected", } VALUE_SCORE = {1: 30, 2: 24, 3: 12, 4: 6, 5: 0} def _lifecycle(account: Account) -> str: if str(account.status or "") in {"disabled", "archived"}: return "disabled" if str(account.status or "") == STATUS_MANUAL: return "manual" if str(account.relogin_failure_kind or "") in MANUAL_KINDS: return "manual" if not account.cookie: return "no_cookie" if str(account.ck_check_status or "") == "invalid": return "invalid" if str(account.ck_check_status or "") == "valid": return "valid" return "unknown" def _high_value_state(account: Account) -> str: b = str(account.high_value_bairimeng_status or "") m = str(account.high_value_mengtu_status or "") if b == HIGH_VALUE_STATUS_AVAILABLE and m == HIGH_VALUE_STATUS_AVAILABLE: return "both_available" if b == HIGH_VALUE_STATUS_AVAILABLE or m == HIGH_VALUE_STATUS_AVAILABLE: return "one_available" if b == HIGH_VALUE_STATUS_OWNED or m == HIGH_VALUE_STATUS_OWNED: return "owned" if account.high_value_checked_at is not None: return "unknown" return "unchecked" def _ck_remaining_hours(account: Account, lifecycle: str, now: datetime) -> int | None: if lifecycle != "valid": return None base = account.cookie_updated_at or account.ck_checked_at if base is None: return None if base.tzinfo is None: base = base.replace(tzinfo=UTC) remaining = (base + CK_LIFETIME - now).total_seconds() / 3600 return max(0, min(168, int(remaining))) def _lease_map(db: Session, account_ids: list[int]) -> dict[int, AccountLease]: if not account_ids: return {} priority = {"platform_fulfillment": 0, "douyu_collab": 1} rows = ( db.query(AccountLease) .filter( AccountLease.account_id.in_(account_ids), AccountLease.status == "active", ) .all() ) result: dict[int, AccountLease] = {} for lease in rows: current = result.get(int(lease.account_id)) if current is None: result[int(lease.account_id)] = lease continue if priority.get(str(lease.purpose), 9) < priority.get(str(current.purpose), 9): result[int(lease.account_id)] = lease return result def _capability_counts(db: Session, account_ids: list[int]) -> dict[int, int]: if not account_ids: return {} return { int(account_id): int(count or 0) for account_id, count in ( db.query(AccountCommodityState.account_id, func.count(AccountCommodityState.id)) .filter( AccountCommodityState.account_id.in_(account_ids), AccountCommodityState.platform == "douyu", AccountCommodityState.scope == "elite", AccountCommodityState.observed_at.isnot(None), ) .group_by(AccountCommodityState.account_id) .all() ) } def _role( lifecycle: str, lease: AccountLease | None, value_tier: int, ) -> str: if lease is not None: return LEASE_LABELS.get(str(lease.purpose), "protected") if lifecycle in {"manual", "disabled"}: return "manual_hold" if lifecycle == "no_cookie": return "onboarding" if lifecycle == "invalid": return "repair" if lifecycle == "valid": if value_tier <= 2: return "supply_high" if value_tier <= 4: return "supply_ordinary" return "cold" def _redundancy_class( *, role: str, high_value_state: str, capability_count: int, both_available_count: int, one_available_count: int, ) -> str: if role in {"fulfillment_protected", "collab_protected", "protected"}: return "protected" if capability_count <= 0 and high_value_state in {"unchecked", "unknown"}: return "unknown" if high_value_state == "both_available": if both_available_count <= 10: return "unique" if both_available_count <= 200: return "rare" if both_available_count <= 2000: return "limited" return "common" if high_value_state == "one_available": if one_available_count <= 50: return "rare" if one_available_count <= 1000: return "limited" return "common" if capability_count <= 5: return "rare" if capability_count <= 20: return "limited" return "common" def _quality_score( *, account: Account, lifecycle: str, value_tier: int, high_value_state: str, capability_count: int, ck_remaining_hours: int | None, ) -> tuple[int, dict[str, int]]: ck_component = 0 if lifecycle == "valid": ck_component = round(30 * (min(ck_remaining_hours or 0, 168) / 168)) value_component = VALUE_SCORE.get(value_tier, 0) capability_component = { "both_available": 20, "one_available": 14, "owned": 6, "unknown": 6, "unchecked": 4, }.get(high_value_state, 4) reliability = 0 if lifecycle not in {"manual", "disabled"} and account.auto_managed: reliability = 10 if str(account.relogin_failure_kind or ""): reliability = max(0, reliability - 4) survey = 2 if account.overview_queried_at is not None and account.high_value_checked_at is not None: survey = 10 elif account.overview_queried_at is not None or account.high_value_checked_at is not None: survey = 6 if capability_count <= 0: capability_component = min(capability_component, 4) components = { "ck": ck_component, "value": value_component, "capability": capability_component, "reliability": reliability, "survey": survey, } return max(0, min(100, sum(components.values()))), components def _onboarding_status(account: Account, capability_count: int) -> str: if ( account.overview_queried_at is not None and account.high_value_checked_at is not None and capability_count > 0 ): return "surveyed" if ( account.overview_queried_at is not None or account.high_value_checked_at is not None or capability_count > 0 ): return "partial" return "unknown" def refresh_account_supply_profiles( db: Session, *, limit: int = 5000, after_account_id: int = 0, now: datetime | None = None, ) -> dict[str, Any]: """按 account_id 游标刷新一批画像;返回下一游标。""" moment = now or datetime.now(UTC) batch = max(1, min(int(limit), 20000)) accounts = ( db.query(Account) .filter(Account.id > int(after_account_id or 0)) .order_by(Account.id.asc()) .limit(batch) .all() ) if not accounts: return {"processed": 0, "nextId": 0, "hasMore": False} account_ids = [int(account.id) for account in accounts] lease_map = _lease_map(db, account_ids) capability_map = _capability_counts(db, account_ids) both_available_count = int( db.query(func.count(Account.id)) .filter( Account.high_value_bairimeng_status == HIGH_VALUE_STATUS_AVAILABLE, Account.high_value_mengtu_status == HIGH_VALUE_STATUS_AVAILABLE, ) .scalar() or 0 ) one_available_count = int( db.query(func.count(Account.id)) .filter( or_( Account.high_value_bairimeng_status == HIGH_VALUE_STATUS_AVAILABLE, Account.high_value_mengtu_status == HIGH_VALUE_STATUS_AVAILABLE, ) ) .scalar() or 0 ) existing = { int(row.account_id): row for row in db.query(AccountSupplyProfile) .filter(AccountSupplyProfile.account_id.in_(account_ids)) .all() } for account in accounts: lifecycle = _lifecycle(account) lease = lease_map.get(int(account.id)) value_tier = int(account.value_tier or 5) role = _role(lifecycle, lease, value_tier) high_value_state = _high_value_state(account) capability_count = capability_map.get(int(account.id), 0) ck_remaining = _ck_remaining_hours(account, lifecycle, moment) quality, components = _quality_score( account=account, lifecycle=lifecycle, value_tier=value_tier, high_value_state=high_value_state, capability_count=capability_count, ck_remaining_hours=ck_remaining, ) redundancy = _redundancy_class( role=role, high_value_state=high_value_state, capability_count=capability_count, both_available_count=both_available_count, one_available_count=one_available_count, ) recoverable = bool( account.auto_managed and lifecycle not in {"manual", "disabled"} and (lifecycle in {"valid", "no_cookie", "invalid"}) ) risk_flags: list[str] = [] if lifecycle == "manual": risk_flags.append("manual") if str(account.relogin_failure_kind or ""): risk_flags.append(str(account.relogin_failure_kind)) if lease is not None: risk_flags.append("leased") reason = ( f"lease:{lease.purpose}" if lease is not None else f"{lifecycle}:tier{value_tier}" ) profile = existing.get(int(account.id)) if profile is None: profile = AccountSupplyProfile(account_id=int(account.id)) db.add(profile) profile.lifecycle_state = lifecycle profile.supply_role = role profile.quality_score = quality profile.score_version = SCORE_VERSION profile.ck_remaining_hours = ck_remaining profile.lease_purpose = str(lease.purpose or "") if lease is not None else "" profile.lease_expires_at = lease.expires_at if lease is not None else None profile.value_tier = value_tier profile.capability_count = capability_count profile.high_value_state = high_value_state profile.redundancy_class = redundancy profile.recoverable = recoverable profile.onboarding_status = _onboarding_status(account, capability_count) profile.risk_flags = risk_flags profile.score_detail = { **components, "bothAvailableCount": both_available_count, "oneAvailableCount": one_available_count, "capabilityCount": capability_count, } profile.reason = reason[:128] profile.computed_at = moment profile.updated_at = moment if profile.created_at is None: profile.created_at = moment db.flush() return { "processed": len(accounts), "nextId": int(accounts[-1].id), "hasMore": len(accounts) == batch, } __all__ = ["SCORE_VERSION", "refresh_account_supply_profiles"]