diff --git a/docs/斗鱼/账号评分与供给分层设计.md b/docs/斗鱼/账号评分与供给分层设计.md index 740fd69..4d819f6 100644 --- a/docs/斗鱼/账号评分与供给分层设计.md +++ b/docs/斗鱼/账号评分与供给分层设计.md @@ -283,3 +283,24 @@ capability_key = elite: - 不把租约账号算进供给池; - 不在未普查前给账号打最终质量分; - 不为了冗余无限养号,冗余按能力维度算。 + +## 10. 本轮实现(dev_11.24,P0) + +已实现,只读投影,不改变选号: + +| 内容 | 文件 | +| --- | --- | +| 投影表 `account_supply_profiles` | 模型 + migration `20261124_0128` | +| 画像计算 | `services/account_supply_profile_service.py` | +| 画像刷新作业 | `jobs/account_supply_profile_projection.py`,默认开启,10 分钟一批 | +| 账号列表展示 | “供给画像”列:角色/质量分/冗余/CK 剩余 | +| 测试 | 角色、评分、游标、作业持久化 | + +初始铺满 31k 账号需要约 7 批(batch=5000,10 分钟一批);铺满后再看角色分布,再进入 P1/P3 的行为改动。 + +下一步: + +1. 观察 3 天画像分布; +2. 做租约 CK 保护优先级(P1); +3. 做首次登录普查(P2,已有 `account_onboarding`); +4. 最后才把质量分/冗余接入选号(P3)。 diff --git a/tests/test_account_supply_profile.py b/tests/test_account_supply_profile.py new file mode 100644 index 0000000..1bf6c62 --- /dev/null +++ b/tests/test_account_supply_profile.py @@ -0,0 +1,161 @@ +"""账号供给画像投影:角色/质量分/冗余/游标刷新测试。""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +from web.backend.models import ( + Account, + AccountCommodityState, + AccountLease, + AccountSupplyProfile, + AutomationJob, + User, +) +from web.backend.services.account_supply_profile_service import ( + refresh_account_supply_profiles, +) +from web.backend.services.automation.jobs import ( + account_supply_profile_projection as job, +) + +NOW = datetime.now(UTC).replace(microsecond=0) + + +def _account(name: str, **overrides) -> Account: + values = { + "username": name, + "password": "p", + "email": f"{name}@example.com", + "email_password": "ep", + "status": "active", + "auto_managed": True, + "cookie": "acf_uid=1", + "ck_check_status": "valid", + "ck_checked_at": NOW, + "cookie_updated_at": NOW, + "value_tier": 3, + } + values.update(overrides) + return Account(**values) + + +def _state(account: Account, commodity_id: str = "C") -> AccountCommodityState: + return AccountCommodityState( + account_id=account.id, + platform="douyu", + scope="elite", + commodity_id=commodity_id, + account_eligibility="eligible", + offer_state="active", + stock_state="in_stock", + availability="available", + observed_at=NOW, + valid_until=NOW + timedelta(hours=1), + available_from=NOW - timedelta(hours=1), + available_until=NOW + timedelta(hours=1), + ) + + +def _user(db) -> User: + user = User( + username="profile-admin", + password_hash="h", + role="super_admin", + is_active=True, + ) + db.add(user) + db.commit() + return user + + +def test_profile_assigns_hard_roles_and_scores(db): + user = _user(db) + protected = _account( + "profile-protected", + value_tier=1, + high_value_bairimeng_status="available", + high_value_mengtu_status="available", + high_value_checked_at=NOW, + overview_queried_at=NOW, + ) + onboarding = _account("profile-onboarding", cookie="", ck_check_status="") + repair = _account("profile-repair", ck_check_status="invalid") + ordinary = _account("profile-ordinary", value_tier=3) + db.add_all([protected, onboarding, repair, ordinary]) + db.flush() + db.add_all( + [ + AccountLease( + account_id=protected.id, + holder_user_id=user.id, + scope="elite", + purpose="platform_fulfillment", + status="active", + ), + _state(protected, "C1"), + _state(ordinary, "C1"), + ] + ) + db.commit() + + result = refresh_account_supply_profiles(db, limit=100, now=NOW) + db.commit() + + profiles = { + int(row.account_id): row for row in db.query(AccountSupplyProfile).all() + } + assert result["processed"] == 4 + assert profiles[protected.id].supply_role == "fulfillment_protected" + assert profiles[protected.id].redundancy_class == "protected" + assert profiles[protected.id].quality_score > 0 + assert profiles[protected.id].ck_remaining_hours == 168 + assert profiles[onboarding.id].supply_role == "onboarding" + assert profiles[onboarding.id].lifecycle_state == "no_cookie" + assert profiles[onboarding.id].recoverable is True + assert profiles[repair.id].supply_role == "repair" + assert profiles[repair.id].recoverable is True + assert profiles[ordinary.id].supply_role == "supply_ordinary" + assert profiles[ordinary.id].capability_count == 1 + assert profiles[ordinary.id].onboarding_status == "partial" + + +def test_profile_cursor_moves_forward_and_wraps(db): + accounts = [_account(f"profile-cursor-{index}") for index in range(5)] + db.add_all(accounts) + db.commit() + + first = refresh_account_supply_profiles(db, limit=2, now=NOW) + db.commit() + second = refresh_account_supply_profiles( + db, limit=2, after_account_id=first["nextId"], now=NOW + ) + db.commit() + + assert first["processed"] == 2 + assert first["hasMore"] is True + assert second["nextId"] > first["nextId"] + + +def test_projection_job_persists_cursor(db): + _user(db) + accounts = [_account(f"profile-job-{index}") for index in range(3)] + db.add_all(accounts) + db.commit() + automation_job = AutomationJob( + key=job.JOB_KEY, + title="账号供给画像刷新", + enabled=True, + batch_size=2, + concurrency=1, + config={}, + ) + db.add(automation_job) + db.commit() + + result = job.run_account_supply_profile_projection(db, automation_job) + + assert result["scanned"] == 2 + assert result["detail"]["hasMore"] is True + assert automation_job.config["last_account_id"] == result["detail"]["nextId"] + assert db.query(AccountSupplyProfile).count() == 2 diff --git a/web/backend/migrations/versions/20261124_0128_account_supply_profiles.py b/web/backend/migrations/versions/20261124_0128_account_supply_profiles.py new file mode 100644 index 0000000..cc8ce0d --- /dev/null +++ b/web/backend/migrations/versions/20261124_0128_account_supply_profiles.py @@ -0,0 +1,55 @@ +"""add account supply profile projection. + +Revision ID: 20261124_0128 +Revises: 20261123_0127 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261124_0128" +down_revision: str | None = "20261123_0127" +branch_labels: str | None = None +depends_on: str | None = None + + +def upgrade() -> None: + op.create_table( + "account_supply_profiles", + sa.Column("account_id", sa.Integer(), nullable=False), + sa.Column("lifecycle_state", sa.String(length=16), nullable=False, server_default="unknown"), + sa.Column("supply_role", sa.String(length=24), nullable=False, server_default="cold"), + sa.Column("quality_score", sa.Integer(), nullable=False, server_default="0"), + sa.Column("score_version", sa.String(length=16), nullable=False, server_default="v1"), + sa.Column("ck_remaining_hours", sa.Integer(), nullable=True), + sa.Column("lease_purpose", sa.String(length=24), nullable=False, server_default=""), + sa.Column("lease_expires_at", sa.DateTime(), nullable=True), + sa.Column("value_tier", sa.Integer(), nullable=True), + sa.Column("capability_count", sa.Integer(), nullable=False, server_default="0"), + sa.Column("high_value_state", sa.String(length=24), nullable=False, server_default="unchecked"), + sa.Column("redundancy_class", sa.String(length=16), nullable=False, server_default="unknown"), + sa.Column("recoverable", sa.Boolean(), nullable=False, server_default=sa.text("0")), + sa.Column("onboarding_status", sa.String(length=16), nullable=False, server_default="unknown"), + sa.Column("risk_flags", sa.JSON(), nullable=True), + sa.Column("score_detail", sa.JSON(), nullable=True), + sa.Column("reason", sa.String(length=128), nullable=False, server_default=""), + sa.Column("computed_at", sa.DateTime(), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(["account_id"], ["accounts.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("account_id"), + ) + op.create_index("ix_account_supply_profile_role", "account_supply_profiles", ["supply_role"]) + op.create_index("ix_account_supply_profile_redundancy", "account_supply_profiles", ["redundancy_class"]) + op.create_index("ix_account_supply_profile_score", "account_supply_profiles", ["quality_score"]) + op.create_index("ix_account_supply_profile_computed", "account_supply_profiles", ["computed_at"]) + + +def downgrade() -> None: + op.drop_index("ix_account_supply_profile_computed", table_name="account_supply_profiles") + op.drop_index("ix_account_supply_profile_score", table_name="account_supply_profiles") + op.drop_index("ix_account_supply_profile_redundancy", table_name="account_supply_profiles") + op.drop_index("ix_account_supply_profile_role", table_name="account_supply_profiles") + op.drop_table("account_supply_profiles") diff --git a/web/backend/models.py b/web/backend/models.py index bf6acfb..b98d53f 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -2757,6 +2757,75 @@ class AccountWorkItem(Base): ) +class AccountSupplyProfile(Base): + """账号供给角色/质量分/冗余投影(只读派生表)。 + + 硬角色(租约/人工/生命周期)优先于质量分;质量分只在同角色内排序。 + 本表由 account_supply_profile_projection 作业刷新,不参与事实写入。 + """ + + __tablename__ = "account_supply_profiles" + + account_id: Mapped[int] = mapped_column( + ForeignKey("accounts.id", ondelete="CASCADE"), + primary_key=True, + ) + lifecycle_state: Mapped[str] = mapped_column( + String(16), nullable=False, default="unknown", server_default="unknown" + ) + supply_role: Mapped[str] = mapped_column( + String(24), nullable=False, default="cold", server_default="cold" + ) + quality_score: Mapped[int] = mapped_column( + Integer, nullable=False, default=0, server_default="0" + ) + score_version: Mapped[str] = mapped_column( + String(16), nullable=False, default="v1", server_default="v1" + ) + ck_remaining_hours: Mapped[int | None] = mapped_column(Integer, nullable=True) + lease_purpose: Mapped[str] = mapped_column( + String(24), nullable=False, default="", server_default="" + ) + lease_expires_at: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) + value_tier: Mapped[int | None] = mapped_column(Integer, nullable=True) + capability_count: Mapped[int] = mapped_column( + Integer, nullable=False, default=0, server_default="0" + ) + high_value_state: Mapped[str] = mapped_column( + String(24), nullable=False, default="unchecked", server_default="unchecked" + ) + redundancy_class: Mapped[str] = mapped_column( + String(16), nullable=False, default="unknown", server_default="unknown" + ) + recoverable: Mapped[bool] = mapped_column( + Boolean, nullable=False, default=False, server_default="0" + ) + onboarding_status: Mapped[str] = mapped_column( + String(16), nullable=False, default="unknown", server_default="unknown" + ) + risk_flags: Mapped[list | None] = mapped_column(JSON, nullable=True) + score_detail: Mapped[dict | None] = mapped_column(JSON, nullable=True) + reason: Mapped[str] = mapped_column( + String(128), nullable=False, default="", server_default="" + ) + computed_at: Mapped[datetime] = mapped_column( + UTCDateTime, nullable=False, default=_utcnow + ) + created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow) + updated_at: Mapped[datetime] = mapped_column( + UTCDateTime, default=_utcnow, onupdate=_utcnow + ) + + __table_args__ = ( + Index("ix_account_supply_profile_role", "supply_role"), + Index("ix_account_supply_profile_redundancy", "redundancy_class"), + Index("ix_account_supply_profile_score", "quality_score"), + Index("ix_account_supply_profile_computed", "computed_at"), + ) + + class AccountSupplyTarget(Base): """高价值、普通和商品维度的账号供给目标。""" diff --git a/web/backend/routers/accounts.py b/web/backend/routers/accounts.py index 07e0ce9..1e9567d 100644 --- a/web/backend/routers/accounts.py +++ b/web/backend/routers/accounts.py @@ -13,6 +13,7 @@ from ..models import ( Account, AccountCommodityState, AccountEvent, + AccountSupplyProfile, AuditLog, DouyuTask, User, @@ -616,6 +617,16 @@ def list_accounts( count, last_at, _ = exchange_stats[key] exchange_stats[key] = (count, last_at, str(title or "")) + profile_map = ( + { + int(row.account_id): row + for row in db.query(AccountSupplyProfile) + .filter(AccountSupplyProfile.account_id.in_(ids)) + .all() + } + if ids + else {} + ) result = [] for acc in accounts: eff_kind = acc.relogin_failure_kind or "" @@ -652,6 +663,18 @@ def list_accounts( # 只返回官方 storehome 的紧凑三态,不把整份快照带进列表。 high_value=high_value_payload(acc), overview_queried_at=acc.overview_queried_at, + supply_role=( + profile_map[acc.id].supply_role if acc.id in profile_map else "" + ), + quality_score=( + profile_map[acc.id].quality_score if acc.id in profile_map else None + ), + redundancy_class=( + profile_map[acc.id].redundancy_class if acc.id in profile_map else "" + ), + ck_remaining_hours=( + profile_map[acc.id].ck_remaining_hours if acc.id in profile_map else None + ), ) # 只有管理员可看完整字段(密码、邮箱等) if can_include_sensitive: diff --git a/web/backend/schemas.py b/web/backend/schemas.py index a4e82d8..2fc29fc 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -317,6 +317,10 @@ class AccountOut(BaseModel): # 外层 state 再给出 never/partial/stale/complete,避免“没查到”被当成“可兑换”。 high_value: dict[str, Any] = Field(default_factory=dict) overview_queried_at: datetime | None = None + supply_role: str = "" + quality_score: int | None = None + redundancy_class: str = "" + ck_remaining_hours: int | None = None model_config = ConfigDict(from_attributes=True) @@ -359,6 +363,10 @@ class AccountOut(BaseModel): "checked_at": _isoformat(self.high_value.get("checked_at")), }, "overview_queried_at": _isoformat(self.overview_queried_at), + "supply_role": self.supply_role, + "quality_score": self.quality_score, + "redundancy_class": self.redundancy_class, + "ck_remaining_hours": self.ck_remaining_hours, } diff --git a/web/backend/services/account_supply_profile_service.py b/web/backend/services/account_supply_profile_service.py new file mode 100644 index 0000000..4471ed1 --- /dev/null +++ b/web/backend/services/account_supply_profile_service.py @@ -0,0 +1,356 @@ +"""账号供给画像投影:角色、质量分、冗余级别。 + +只读派生计算,不改变账号事实;硬角色(租约/人工/生命周期)优先于质量分。 +""" + +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"] diff --git a/web/backend/services/automation/__init__.py b/web/backend/services/automation/__init__.py index 6cf0dd2..e06b612 100644 --- a/web/backend/services/automation/__init__.py +++ b/web/backend/services/automation/__init__.py @@ -18,6 +18,12 @@ from .jobs.account_onboarding import ( from .jobs.account_onboarding import ( run_account_onboarding, ) +from .jobs.account_supply_profile_projection import ( + JOB_KEY as ACCOUNT_SUPPLY_PROFILE_PROJECTION_KEY, +) +from .jobs.account_supply_profile_projection import ( + run_account_supply_profile_projection, +) from .jobs.account_supply_replenishment import ( JOB_KEY as ACCOUNT_SUPPLY_REPLENISHMENT_KEY, ) @@ -71,6 +77,7 @@ from .scheduler import ( __all__ = [ "ACCOUNT_CAPABILITY_REFRESH_KEY", "ACCOUNT_ONBOARDING_KEY", + "ACCOUNT_SUPPLY_PROFILE_PROJECTION_KEY", "ACCOUNT_SUPPLY_REPLENISHMENT_KEY", "ACCOUNT_SYNC_QUEUE_KEY", "ACCOUNT_VALUE_PROJECTION_KEY", @@ -88,6 +95,7 @@ __all__ = [ "reset_registry", "run_account_capability_refresh", "run_account_onboarding", + "run_account_supply_profile_projection", "run_account_supply_replenishment", "run_account_sync_queue_job", "run_account_value_projection", @@ -170,6 +178,19 @@ def register_default_jobs() -> None: default_enabled=False, ) ) + register_job( + JobSpec( + key=ACCOUNT_SUPPLY_PROFILE_PROJECTION_KEY, + title="账号供给画像刷新", + # 只写派生画像表,不改账号事实和选号;默认开启。 + interval_seconds=600, + run_interval_seconds=600, + batch_size=5000, + concurrency=1, + run=run_account_supply_profile_projection, + default_enabled=True, + ) + ) register_job( JobSpec( key=POINTS_EXPIRE_KEY, diff --git a/web/backend/services/automation/jobs/account_supply_profile_projection.py b/web/backend/services/automation/jobs/account_supply_profile_projection.py new file mode 100644 index 0000000..176abdb --- /dev/null +++ b/web/backend/services/automation/jobs/account_supply_profile_projection.py @@ -0,0 +1,51 @@ +"""账号供给画像投影刷新。""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any + +from sqlalchemy.orm import Session + +from ....models import AutomationJob +from ...account_supply_profile_service import refresh_account_supply_profiles + +JOB_KEY = "account_supply_profile_projection" + + +def run_account_supply_profile_projection( + db: Session, + job: AutomationJob, +) -> dict[str, Any]: + config = dict(job.config or {}) + cursor = int(config.get("last_account_id") or 0) + result = refresh_account_supply_profiles( + db, + limit=max(1, int(job.batch_size or 5000)), + after_account_id=cursor, + ) + if result["hasMore"]: + config["last_account_id"] = int(result["nextId"]) + else: + config["last_account_id"] = 0 + job.config = config + job.updated_at = datetime.now(UTC) + db.commit() + return { + "scanned": result["processed"], + "valid": 0, + "invalid": 0, + "skipped": 0, + "message": ( + f"刷新账号供给画像 {result['processed']} 条," + f"游标 {result['nextId']},{'继续下一批' if result['hasMore'] else '本轮已到末尾'}" + ), + "detail": { + "processed": result["processed"], + "nextId": result["nextId"], + "hasMore": result["hasMore"], + }, + } + + +__all__ = ["JOB_KEY", "run_account_supply_profile_projection"] diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index aec8b8c..ecafdf0 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -453,6 +453,10 @@ export interface AccountItem { high_value: HighValueStatus; /** 最近一次完整一键查询时间 */ overview_queried_at: string | null; + supply_role?: string; + quality_score?: number | null; + redundancy_class?: string; + ck_remaining_hours?: number | null; } export interface AssignmentsSummary { diff --git a/web/frontend/src/pages/AutomationPage.tsx b/web/frontend/src/pages/AutomationPage.tsx index a1377b3..6f78ce7 100644 --- a/web/frontend/src/pages/AutomationPage.tsx +++ b/web/frontend/src/pages/AutomationPage.tsx @@ -112,6 +112,12 @@ const JOB_UI: Record = { showRecheck: true, showConcurrency: true, }, + account_supply_profile_projection: { + description: "刷新账号供给角色、质量分、能力冗余和 CK 剩余;只写派生画像表,不改选号。", + core: true, + showRecheck: false, + showConcurrency: false, + }, account_onboarding: { description: "对没有 CK 的未登录账号执行首次真实登录;成功后写入 CK 并联动商品能力同步。默认关闭,建议先小批量。", core: true, diff --git a/web/frontend/src/pages/accounts/components/AccountColumns.tsx b/web/frontend/src/pages/accounts/components/AccountColumns.tsx index 0f8479f..6c49d64 100644 --- a/web/frontend/src/pages/accounts/components/AccountColumns.tsx +++ b/web/frontend/src/pages/accounts/components/AccountColumns.tsx @@ -14,6 +14,62 @@ import { const { Text } = Typography; +const SUPPLY_ROLE_LABELS: Record = { + fulfillment_protected: '履约保护', + collab_protected: '协作保护', + onboarding: '待首次登录', + repair: '待重登', + supply_high: '高价值供给', + supply_ordinary: '普通供给', + cold: '冷库存', + manual_hold: '人工', +}; + +const SUPPLY_ROLE_COLORS: Record = { + fulfillment_protected: 'blue', + collab_protected: 'cyan', + onboarding: 'gold', + repair: 'orange', + supply_high: 'green', + supply_ordinary: 'default', + cold: 'default', + manual_hold: 'red', +}; + +const REDUNDANCY_LABELS: Record = { + unique: '唯一', + rare: '稀有', + limited: '有限', + common: '常见', + protected: '保护中', + unknown: '未知', +}; + +function renderSupplyProfile(record: AccountItem) { + if (!record.supply_role) { + return 未生成; + } + return ( + + + + {SUPPLY_ROLE_LABELS[record.supply_role] || record.supply_role} + + + 分 {record.quality_score ?? '-'} · {REDUNDANCY_LABELS[record.redundancy_class || ''] || record.redundancy_class || '-'} + {record.ck_remaining_hours != null ? ` · CK ${record.ck_remaining_hours}h` : ''} + + + + ); +} + function BindChip({ scope, status }: { scope: string; status?: string }) { const tone = status === 'bound' @@ -235,6 +291,12 @@ export function buildAccountColumns({ ); }, }, + { + title: '供给画像', + key: 'supply_profile', + width: 190, + render: (_: unknown, record: AccountItem) => renderSupplyProfile(record), + }, { title: '绑定', dataIndex: 'role_bind_status',