perf(douyu): 优化自动化中心运行总览加载
This commit is contained in:
@@ -28,6 +28,7 @@ from web.backend.schemas import DouyuSupplyTargetUpsert
|
||||
from web.backend.services.account_observability import (
|
||||
account_platform_status,
|
||||
account_platform_trends,
|
||||
account_supply_snapshot,
|
||||
)
|
||||
from web.backend.services.account_supply_service import (
|
||||
VALUE_HIGH,
|
||||
@@ -539,6 +540,70 @@ def test_account_platform_status_can_defer_trends(db):
|
||||
assert isinstance(trends["alerts"], list)
|
||||
|
||||
|
||||
def test_account_platform_status_compact_mode_defers_heavy_sections(db):
|
||||
account = _account("platform-compact", points=400)
|
||||
db.add(account)
|
||||
db.flush()
|
||||
db.add_all(
|
||||
[
|
||||
_state(account),
|
||||
AccountSupplyTarget(
|
||||
platform="douyu",
|
||||
scope="elite",
|
||||
commodity_id="C",
|
||||
value_class=VALUE_HIGH,
|
||||
target_covered=2,
|
||||
target_available=2,
|
||||
target_allocatable=1,
|
||||
),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
|
||||
status = account_platform_status(
|
||||
db,
|
||||
now=NOW,
|
||||
include_trends=False,
|
||||
include_supply=False,
|
||||
include_diagnostics=False,
|
||||
)
|
||||
|
||||
assert status["accounts"]["ck_valid"] == 1
|
||||
assert status["commodities"]["fresh_eligible"] == 1
|
||||
assert status["commodities"]["by_availability"] == {}
|
||||
assert status["sync_domains"] == {}
|
||||
assert status["supply_targets"] == []
|
||||
assert status["trends"] is None
|
||||
|
||||
|
||||
def test_account_supply_snapshot_loads_inventory_independently(db):
|
||||
account = _account("platform-supply-only", points=400)
|
||||
db.add(account)
|
||||
db.flush()
|
||||
db.add_all(
|
||||
[
|
||||
_state(account),
|
||||
AccountSupplyTarget(
|
||||
platform="douyu",
|
||||
scope="elite",
|
||||
commodity_id="C",
|
||||
value_class=VALUE_HIGH,
|
||||
target_covered=2,
|
||||
target_available=2,
|
||||
target_allocatable=1,
|
||||
),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
|
||||
snapshot = account_supply_snapshot(db, now=NOW)
|
||||
|
||||
assert snapshot["supply_targets"][0]["covered"] == 1
|
||||
assert snapshot["supply_targets"][0]["available"] == 1
|
||||
assert snapshot["supply_targets"][0]["target_available"] == 2
|
||||
assert {alert["code"] for alert in snapshot["alerts"]} == {"supply_shortage"}
|
||||
|
||||
|
||||
def test_account_platform_status_builds_seven_day_trends(db):
|
||||
account = _account("platform-trends", points=400)
|
||||
db.add(account)
|
||||
|
||||
@@ -42,7 +42,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261122_0117"
|
||||
HEAD_REVISION = "20261123_0118"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
|
||||
@@ -469,6 +469,10 @@
|
||||
"20261122_0117_retire_account_overview_refresh.py": {
|
||||
"revision": "20261122_0117",
|
||||
"sha256": "d49c6ddabdee24fc4013e765e2305f7cf9cb4750fae914303501c3d0a1b0723d"
|
||||
},
|
||||
"20261123_0118_account_platform_dashboard_indexes.py": {
|
||||
"revision": "20261123_0118",
|
||||
"sha256": "18af99f5be4afba9554c12a8fe0cef553948c4db07faf14c11a612dbd2290e42"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""add account platform dashboard aggregate indexes.
|
||||
|
||||
运行总览按平台聚合商品资格、同步新鲜度和全局供给库存。原索引都从
|
||||
scope/domain 等中低基数列开始,缺少 commodity_id 时会退化为大范围扫描。
|
||||
新增与总览查询同形的覆盖索引,降低首屏统计的扫描量。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261123_0118"
|
||||
down_revision: str | None = "20261122_0117"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
COMMODITY_TABLE = "account_commodity_states"
|
||||
SYNC_STATE_TABLE = "account_sync_states"
|
||||
|
||||
INDEXES: tuple[tuple[str, str, list[str]], ...] = (
|
||||
(
|
||||
"ix_account_commodity_global_eligible",
|
||||
COMMODITY_TABLE,
|
||||
[
|
||||
"platform",
|
||||
"scope",
|
||||
"account_eligibility",
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
],
|
||||
),
|
||||
(
|
||||
"ix_account_commodity_platform_availability",
|
||||
COMMODITY_TABLE,
|
||||
["platform", "availability", "valid_until"],
|
||||
),
|
||||
(
|
||||
"ix_account_commodity_platform_eligibility",
|
||||
COMMODITY_TABLE,
|
||||
["platform", "account_eligibility", "valid_until"],
|
||||
),
|
||||
(
|
||||
"ix_account_sync_state_platform_status_valid",
|
||||
SYNC_STATE_TABLE,
|
||||
["platform", "status", "valid_until", "domain"],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _indexes(table_name: str) -> set[str]:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
if not inspector.has_table(table_name):
|
||||
return set()
|
||||
names: set[str] = set()
|
||||
for item in inspector.get_indexes(table_name):
|
||||
name = item.get("name")
|
||||
if name:
|
||||
names.add(name)
|
||||
return names
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
for index_name, table_name, columns in INDEXES:
|
||||
if index_name in _indexes(table_name):
|
||||
continue
|
||||
op.create_index(index_name, table_name, columns, unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for index_name, table_name, _columns in reversed(INDEXES):
|
||||
if index_name in _indexes(table_name):
|
||||
op.drop_index(index_name, table_name=table_name)
|
||||
@@ -2010,6 +2010,27 @@ class AccountCommodityState(Base):
|
||||
"available_from",
|
||||
"available_until",
|
||||
),
|
||||
Index(
|
||||
"ix_account_commodity_global_eligible",
|
||||
"platform",
|
||||
"scope",
|
||||
"account_eligibility",
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
),
|
||||
Index(
|
||||
"ix_account_commodity_platform_availability",
|
||||
"platform",
|
||||
"availability",
|
||||
"valid_until",
|
||||
),
|
||||
Index(
|
||||
"ix_account_commodity_platform_eligibility",
|
||||
"platform",
|
||||
"account_eligibility",
|
||||
"valid_until",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -2457,6 +2478,13 @@ class AccountSyncState(Base):
|
||||
"last_success_at",
|
||||
"account_id",
|
||||
),
|
||||
Index(
|
||||
"ix_account_sync_state_platform_status_valid",
|
||||
"platform",
|
||||
"status",
|
||||
"valid_until",
|
||||
"domain",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ from ..services.account_binding import BIND_BOUND, bind_payload
|
||||
from ..services.account_observability import (
|
||||
account_platform_status,
|
||||
account_platform_trends,
|
||||
account_supply_snapshot,
|
||||
)
|
||||
from ..services.account_protection_service import (
|
||||
evaluate_protection_targets,
|
||||
@@ -766,11 +767,18 @@ def task_types(current: User = Depends(require_permission("douyu:task"))):
|
||||
@router.get("/account-platform-status")
|
||||
def get_account_platform_status(
|
||||
include_trends: bool = Query(True),
|
||||
include_supply: bool = Query(True),
|
||||
include_diagnostics: bool = Query(True),
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:task")),
|
||||
):
|
||||
"""账号同步、CK 周期、商品覆盖和供给缺口的统一观测快照。"""
|
||||
return account_platform_status(db, include_trends=include_trends)
|
||||
return account_platform_status(
|
||||
db,
|
||||
include_trends=include_trends,
|
||||
include_supply=include_supply,
|
||||
include_diagnostics=include_diagnostics,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/account-platform-trends")
|
||||
@@ -782,6 +790,15 @@ def get_account_platform_trends(
|
||||
return account_platform_trends(db)
|
||||
|
||||
|
||||
@router.get("/account-platform-supply")
|
||||
def get_account_platform_supply(
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:task")),
|
||||
):
|
||||
"""延迟加载账号供给库存,避免阻塞运行总览首屏。"""
|
||||
return account_supply_snapshot(db)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/account-protection-targets/{group_key}",
|
||||
response_model=DouyuAccountProtectionTargetOut,
|
||||
|
||||
@@ -261,21 +261,104 @@ def account_platform_trends(
|
||||
}
|
||||
|
||||
|
||||
def _supply_snapshot(
|
||||
db: Session,
|
||||
moment: datetime,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
inventories = evaluate_supply_targets(db, now=moment)
|
||||
supply_targets: list[dict[str, Any]] = []
|
||||
alerts: list[dict[str, Any]] = []
|
||||
for item in inventories:
|
||||
shortage = max(
|
||||
item.covered_shortage,
|
||||
item.available_shortage,
|
||||
item.allocatable_shortage,
|
||||
)
|
||||
supply_targets.append(
|
||||
{
|
||||
"target_id": item.target_id,
|
||||
"scope": item.scope,
|
||||
"commodity_id": item.commodity_id,
|
||||
"value_class": item.value_class,
|
||||
"target_covered": item.target_covered,
|
||||
"target_available": item.target_available,
|
||||
"target_allocatable": item.target_allocatable,
|
||||
"safety_buffer": item.safety_buffer,
|
||||
"covered": item.covered,
|
||||
"available": item.available,
|
||||
"allocatable": item.allocatable,
|
||||
"covered_shortage": item.covered_shortage,
|
||||
"available_shortage": item.available_shortage,
|
||||
"allocatable_shortage": item.allocatable_shortage,
|
||||
"needs_replenishment": item.needs_replenishment,
|
||||
}
|
||||
)
|
||||
if not item.needs_replenishment:
|
||||
continue
|
||||
critical = (item.target_available > 0 and item.available <= 0) or (
|
||||
item.target_allocatable > 0 and item.allocatable <= 0
|
||||
)
|
||||
alerts.append(
|
||||
{
|
||||
"code": "supply_shortage",
|
||||
"severity": "critical" if critical else "warning",
|
||||
"scope": item.scope,
|
||||
"commodity_id": item.commodity_id,
|
||||
"value_class": item.value_class,
|
||||
"shortage": shortage,
|
||||
"message": (
|
||||
f"{item.scope}/{item.commodity_id or 'all'}/"
|
||||
f"{item.value_class} 库存短缺 {shortage}"
|
||||
),
|
||||
}
|
||||
)
|
||||
if not inventories:
|
||||
alerts.append(
|
||||
{
|
||||
"code": "supply_targets_missing",
|
||||
"severity": "warning",
|
||||
"message": "尚未配置启用的账号供给目标",
|
||||
}
|
||||
)
|
||||
return supply_targets, alerts
|
||||
|
||||
|
||||
def account_supply_snapshot(
|
||||
db: Session,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""返回可延迟加载的账号供给库存,避免阻塞运行总览首屏。"""
|
||||
moment = now or datetime.now(UTC)
|
||||
supply_targets, alerts = _supply_snapshot(db, moment)
|
||||
return {
|
||||
"checked_at": moment,
|
||||
"supply_targets": supply_targets,
|
||||
"alerts": alerts,
|
||||
}
|
||||
|
||||
|
||||
def account_platform_status(
|
||||
db: Session,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
include_trends: bool = True,
|
||||
include_supply: bool = True,
|
||||
include_diagnostics: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
moment = now or datetime.now(UTC)
|
||||
in_24h = moment + timedelta(hours=24)
|
||||
in_72h = moment + timedelta(hours=72)
|
||||
|
||||
account_counts = dict(
|
||||
db.query(Account.ck_check_status, func.count(Account.id))
|
||||
account_counts: dict[str, int] = {
|
||||
str(status or ""): int(count or 0)
|
||||
for status, count in db.query(
|
||||
Account.ck_check_status,
|
||||
func.count(Account.id),
|
||||
)
|
||||
.group_by(Account.ck_check_status)
|
||||
.all()
|
||||
)
|
||||
}
|
||||
total_accounts = int(db.query(func.count(Account.id)).scalar() or 0)
|
||||
cookie_accounts = int(
|
||||
db.query(func.count(Account.id))
|
||||
@@ -334,129 +417,110 @@ def account_platform_status(
|
||||
if status == "pending":
|
||||
bucket["oldest_pending_due_at"] = oldest_due
|
||||
|
||||
sync_rows = (
|
||||
db.query(
|
||||
AccountSyncState.domain,
|
||||
AccountSyncState.status,
|
||||
func.count(AccountSyncState.id),
|
||||
)
|
||||
.group_by(AccountSyncState.domain, AccountSyncState.status)
|
||||
.all()
|
||||
)
|
||||
sync_domains: dict[str, dict[str, Any]] = {}
|
||||
for domain, status, count in sync_rows:
|
||||
bucket = sync_domains.setdefault(str(domain), {})
|
||||
bucket[str(status)] = int(count or 0)
|
||||
fresh_rows = (
|
||||
db.query(AccountSyncState.domain, func.count(AccountSyncState.id))
|
||||
.filter(
|
||||
AccountSyncState.status == "success",
|
||||
AccountSyncState.valid_until.isnot(None),
|
||||
AccountSyncState.valid_until > moment,
|
||||
if include_diagnostics:
|
||||
sync_rows = (
|
||||
db.query(
|
||||
AccountSyncState.domain,
|
||||
AccountSyncState.status,
|
||||
func.count(AccountSyncState.id),
|
||||
)
|
||||
.filter(AccountSyncState.platform == "douyu")
|
||||
.group_by(AccountSyncState.domain, AccountSyncState.status)
|
||||
.all()
|
||||
)
|
||||
.group_by(AccountSyncState.domain)
|
||||
.all()
|
||||
)
|
||||
for domain, count in fresh_rows:
|
||||
sync_domains.setdefault(str(domain), {})["fresh"] = int(count or 0)
|
||||
for domain, status, count in sync_rows:
|
||||
bucket = sync_domains.setdefault(str(domain), {})
|
||||
bucket[str(status)] = int(count or 0)
|
||||
fresh_rows = (
|
||||
db.query(AccountSyncState.domain, func.count(AccountSyncState.id))
|
||||
.filter(
|
||||
AccountSyncState.platform == "douyu",
|
||||
AccountSyncState.status == "success",
|
||||
AccountSyncState.valid_until.isnot(None),
|
||||
AccountSyncState.valid_until > moment,
|
||||
)
|
||||
.group_by(AccountSyncState.domain)
|
||||
.all()
|
||||
)
|
||||
for domain, count in fresh_rows:
|
||||
sync_domains.setdefault(str(domain), {})["fresh"] = int(count or 0)
|
||||
|
||||
commodity_rows = (
|
||||
db.query(
|
||||
AccountCommodityState.availability,
|
||||
func.count(AccountCommodityState.id),
|
||||
func.sum(
|
||||
case(
|
||||
(
|
||||
AccountCommodityState.valid_until > moment,
|
||||
1,
|
||||
),
|
||||
else_=0,
|
||||
)
|
||||
),
|
||||
commodities: dict[str, dict[str, int]] = {}
|
||||
eligibility: dict[str, dict[str, int]] = {}
|
||||
fresh_available = 0
|
||||
fresh_limited = 0
|
||||
if include_diagnostics:
|
||||
commodity_rows = (
|
||||
db.query(
|
||||
AccountCommodityState.availability,
|
||||
func.count(AccountCommodityState.id),
|
||||
func.sum(
|
||||
case(
|
||||
(
|
||||
AccountCommodityState.valid_until > moment,
|
||||
1,
|
||||
),
|
||||
else_=0,
|
||||
)
|
||||
),
|
||||
)
|
||||
.filter(AccountCommodityState.platform == "douyu")
|
||||
.group_by(AccountCommodityState.availability)
|
||||
.all()
|
||||
)
|
||||
.filter(AccountCommodityState.platform == "douyu")
|
||||
.group_by(AccountCommodityState.availability)
|
||||
.all()
|
||||
)
|
||||
commodities = {
|
||||
str(availability): {
|
||||
"total": int(total or 0),
|
||||
"fresh": int(fresh or 0),
|
||||
commodities = {
|
||||
str(availability): {
|
||||
"total": int(total or 0),
|
||||
"fresh": int(fresh or 0),
|
||||
}
|
||||
for availability, total, fresh in commodity_rows
|
||||
}
|
||||
for availability, total, fresh in commodity_rows
|
||||
}
|
||||
fresh_available = int(commodities.get(AVAILABILITY_AVAILABLE, {}).get("fresh", 0))
|
||||
fresh_limited = int(commodities.get(AVAILABILITY_LIMITED, {}).get("fresh", 0))
|
||||
eligibility_rows = (
|
||||
db.query(
|
||||
AccountCommodityState.account_eligibility,
|
||||
func.count(AccountCommodityState.id),
|
||||
func.sum(
|
||||
case(
|
||||
(AccountCommodityState.valid_until > moment, 1),
|
||||
else_=0,
|
||||
)
|
||||
),
|
||||
fresh_available = int(
|
||||
commodities.get(AVAILABILITY_AVAILABLE, {}).get("fresh", 0)
|
||||
)
|
||||
.filter(AccountCommodityState.platform == "douyu")
|
||||
.group_by(AccountCommodityState.account_eligibility)
|
||||
.all()
|
||||
)
|
||||
eligibility = {
|
||||
str(state): {
|
||||
"total": int(total or 0),
|
||||
"fresh": int(fresh or 0),
|
||||
fresh_limited = int(commodities.get(AVAILABILITY_LIMITED, {}).get("fresh", 0))
|
||||
eligibility_rows = (
|
||||
db.query(
|
||||
AccountCommodityState.account_eligibility,
|
||||
func.count(AccountCommodityState.id),
|
||||
func.sum(
|
||||
case(
|
||||
(AccountCommodityState.valid_until > moment, 1),
|
||||
else_=0,
|
||||
)
|
||||
),
|
||||
)
|
||||
.filter(AccountCommodityState.platform == "douyu")
|
||||
.group_by(AccountCommodityState.account_eligibility)
|
||||
.all()
|
||||
)
|
||||
eligibility = {
|
||||
str(state): {
|
||||
"total": int(total or 0),
|
||||
"fresh": int(fresh or 0),
|
||||
}
|
||||
for state, total, fresh in eligibility_rows
|
||||
}
|
||||
for state, total, fresh in eligibility_rows
|
||||
}
|
||||
fresh_eligible = int(eligibility.get("eligible", {}).get("fresh", 0))
|
||||
else:
|
||||
fresh_eligible = int(
|
||||
db.query(func.count(AccountCommodityState.id))
|
||||
.filter(
|
||||
AccountCommodityState.platform == "douyu",
|
||||
AccountCommodityState.account_eligibility == "eligible",
|
||||
AccountCommodityState.valid_until.isnot(None),
|
||||
AccountCommodityState.valid_until > moment,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
inventories = evaluate_supply_targets(db, now=moment)
|
||||
supply_targets: list[dict[str, Any]] = []
|
||||
alerts: list[dict[str, Any]] = []
|
||||
for item in inventories:
|
||||
shortage = max(
|
||||
item.covered_shortage,
|
||||
item.available_shortage,
|
||||
item.allocatable_shortage,
|
||||
)
|
||||
supply_targets.append(
|
||||
{
|
||||
"target_id": item.target_id,
|
||||
"scope": item.scope,
|
||||
"commodity_id": item.commodity_id,
|
||||
"value_class": item.value_class,
|
||||
"target_covered": item.target_covered,
|
||||
"target_available": item.target_available,
|
||||
"target_allocatable": item.target_allocatable,
|
||||
"safety_buffer": item.safety_buffer,
|
||||
"covered": item.covered,
|
||||
"available": item.available,
|
||||
"allocatable": item.allocatable,
|
||||
"covered_shortage": item.covered_shortage,
|
||||
"available_shortage": item.available_shortage,
|
||||
"allocatable_shortage": item.allocatable_shortage,
|
||||
"needs_replenishment": item.needs_replenishment,
|
||||
}
|
||||
)
|
||||
if not item.needs_replenishment:
|
||||
continue
|
||||
critical = (item.target_available > 0 and item.available <= 0) or (
|
||||
item.target_allocatable > 0 and item.allocatable <= 0
|
||||
)
|
||||
alerts.append(
|
||||
{
|
||||
"code": "supply_shortage",
|
||||
"severity": "critical" if critical else "warning",
|
||||
"scope": item.scope,
|
||||
"commodity_id": item.commodity_id,
|
||||
"value_class": item.value_class,
|
||||
"shortage": shortage,
|
||||
"message": (
|
||||
f"{item.scope}/{item.commodity_id or 'all'}/"
|
||||
f"{item.value_class} 库存短缺 {shortage}"
|
||||
),
|
||||
}
|
||||
)
|
||||
if include_supply:
|
||||
supply_targets, supply_alerts = _supply_snapshot(db, moment)
|
||||
alerts.extend(supply_alerts)
|
||||
|
||||
protection_targets = evaluate_protection_targets(db, now=moment)
|
||||
for item in protection_targets:
|
||||
@@ -494,14 +558,6 @@ def account_platform_status(
|
||||
}
|
||||
)
|
||||
|
||||
if not inventories:
|
||||
alerts.append(
|
||||
{
|
||||
"code": "supply_targets_missing",
|
||||
"severity": "warning",
|
||||
"message": "尚未配置启用的账号供给目标",
|
||||
}
|
||||
)
|
||||
if expiring_24h:
|
||||
alerts.append(
|
||||
{
|
||||
@@ -552,7 +608,7 @@ def account_platform_status(
|
||||
"commodities": {
|
||||
"by_availability": commodities,
|
||||
"by_account_eligibility": eligibility,
|
||||
"fresh_eligible": int(eligibility.get("eligible", {}).get("fresh", 0)),
|
||||
"fresh_eligible": fresh_eligible,
|
||||
"fresh_available": fresh_available,
|
||||
"fresh_limited": fresh_limited,
|
||||
},
|
||||
@@ -563,4 +619,8 @@ def account_platform_status(
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["account_platform_status", "account_platform_trends"]
|
||||
__all__ = [
|
||||
"account_platform_status",
|
||||
"account_platform_trends",
|
||||
"account_supply_snapshot",
|
||||
]
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
DouyuAccountProtectionTarget,
|
||||
DouyuAccountProtectionTargetUpdate,
|
||||
DouyuAccountPlatformStatus,
|
||||
DouyuAccountPlatformSupply,
|
||||
DouyuPlatformTrendsResponse,
|
||||
DouyuConfig,
|
||||
DouyuExchangeResultImage,
|
||||
@@ -24,10 +25,26 @@ import type {
|
||||
|
||||
export const douyuApi = {
|
||||
taskTypes: () => api.get<Record<string, string>, Record<string, string>>('/douyu/task-types'),
|
||||
getAccountPlatformStatus: (includeTrends = true) =>
|
||||
getAccountPlatformStatus: ({
|
||||
includeTrends = true,
|
||||
includeSupply = true,
|
||||
includeDiagnostics = true,
|
||||
}: {
|
||||
includeTrends?: boolean;
|
||||
includeSupply?: boolean;
|
||||
includeDiagnostics?: boolean;
|
||||
} = {}) =>
|
||||
api.get<DouyuAccountPlatformStatus, DouyuAccountPlatformStatus>('/douyu/account-platform-status', {
|
||||
params: { include_trends: includeTrends },
|
||||
params: {
|
||||
include_trends: includeTrends,
|
||||
include_supply: includeSupply,
|
||||
include_diagnostics: includeDiagnostics,
|
||||
},
|
||||
}),
|
||||
getAccountPlatformSupply: () =>
|
||||
api.get<DouyuAccountPlatformSupply, DouyuAccountPlatformSupply>(
|
||||
'/douyu/account-platform-supply',
|
||||
),
|
||||
getAccountPlatformTrends: () =>
|
||||
api.get<DouyuPlatformTrendsResponse, DouyuPlatformTrendsResponse>('/douyu/account-platform-trends'),
|
||||
updateAccountProtectionTarget: (
|
||||
|
||||
@@ -886,6 +886,12 @@ export interface DouyuPlatformTrendsResponse {
|
||||
alerts: DouyuPlatformAlert[];
|
||||
}
|
||||
|
||||
export interface DouyuAccountPlatformSupply {
|
||||
checked_at: string;
|
||||
supply_targets: DouyuSupplyTargetStatus[];
|
||||
alerts: DouyuPlatformAlert[];
|
||||
}
|
||||
|
||||
export interface DouyuAccountPlatformStatus {
|
||||
checked_at: string;
|
||||
accounts: {
|
||||
|
||||
@@ -198,7 +198,11 @@ export default function AutomationPage() {
|
||||
const [loginQuota, setLoginQuota] = useState<AutomationLoginQuota | null>(null);
|
||||
const [budgetRecommendation, setBudgetRecommendation] =
|
||||
useState<AutomationLoginQuotaRecommendation | null>(null);
|
||||
const [activeTab, setActiveTab] = useState("overview");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [budgetLoading, setBudgetLoading] = useState(false);
|
||||
const [historyLoading, setHistoryLoading] = useState(false);
|
||||
const [manualLoading, setManualLoading] = useState(false);
|
||||
const [applyingBudget, setApplyingBudget] = useState(false);
|
||||
const [savingBudget, setSavingBudget] = useState(false);
|
||||
const [savingKey, setSavingKey] = useState<string | null>(null);
|
||||
@@ -215,28 +219,14 @@ export default function AutomationPage() {
|
||||
[jobs],
|
||||
);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const loadJobs = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [data, recommendation, quota] = await Promise.all([
|
||||
automationApi.jobs(),
|
||||
automationApi.loginQuotaRecommendation(),
|
||||
automationApi.loginQuota(),
|
||||
]);
|
||||
const data = await automationApi.jobs();
|
||||
setJobs(data.jobs);
|
||||
setBudgetRecommendation(recommendation);
|
||||
setLoginQuota(quota);
|
||||
setPendingRelogin(data.pending_relogin ?? 0);
|
||||
setSchedulerEnabled(data.scheduler.enabled);
|
||||
setSchedulerRunning(data.scheduler.running);
|
||||
budgetForm.setFieldsValue(quota);
|
||||
const [history, manual] = await Promise.all([
|
||||
automationApi.runs({ limit: 80 }),
|
||||
automationApi.manualQueue(),
|
||||
]);
|
||||
setRuns(history.items);
|
||||
setManualGroups(manual.groups);
|
||||
setManualTotal(manual.total);
|
||||
jobForms.setFieldsValue(
|
||||
Object.fromEntries(
|
||||
data.jobs.map((job) => [
|
||||
@@ -259,11 +249,75 @@ export default function AutomationPage() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [budgetForm, jobForms]);
|
||||
}, [jobForms]);
|
||||
|
||||
const loadBudget = useCallback(async () => {
|
||||
setBudgetLoading(true);
|
||||
try {
|
||||
const [recommendation, quota] = await Promise.all([
|
||||
automationApi.loginQuotaRecommendation(),
|
||||
automationApi.loginQuota(),
|
||||
]);
|
||||
setBudgetRecommendation(recommendation);
|
||||
setLoginQuota(quota);
|
||||
budgetForm.setFieldsValue(quota);
|
||||
} catch (error: unknown) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setBudgetLoading(false);
|
||||
}
|
||||
}, [budgetForm]);
|
||||
|
||||
const loadHistory = useCallback(async () => {
|
||||
setHistoryLoading(true);
|
||||
try {
|
||||
const history = await automationApi.runs({ limit: 80 });
|
||||
setRuns(history.items);
|
||||
} catch (error: unknown) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setHistoryLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadManual = useCallback(async () => {
|
||||
setManualLoading(true);
|
||||
try {
|
||||
const manual = await automationApi.manualQueue();
|
||||
setManualGroups(manual.groups);
|
||||
setManualTotal(manual.total);
|
||||
} catch (error: unknown) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setManualLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
void loadJobs();
|
||||
}, [loadJobs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeTab === "budget") {
|
||||
void loadBudget();
|
||||
} else if (activeTab === "history") {
|
||||
void loadHistory();
|
||||
} else if (activeTab === "manual") {
|
||||
void loadManual();
|
||||
}
|
||||
}, [activeTab, loadBudget, loadHistory, loadManual]);
|
||||
|
||||
const refreshVisible = async () => {
|
||||
const jobsPromise = loadJobs();
|
||||
const tabPromise = activeTab === "budget"
|
||||
? loadBudget()
|
||||
: activeTab === "history"
|
||||
? loadHistory()
|
||||
: activeTab === "manual"
|
||||
? loadManual()
|
||||
: Promise.resolve();
|
||||
await Promise.allSettled([jobsPromise, tabPromise]);
|
||||
};
|
||||
|
||||
const saveJob = async (job: AutomationJobItem) => {
|
||||
const values = jobForms.getFieldValue(job.key) || {};
|
||||
@@ -283,7 +337,7 @@ export default function AutomationPage() {
|
||||
concurrency: values.concurrency,
|
||||
});
|
||||
message.success(`${job.title} 配置已保存`);
|
||||
await load();
|
||||
await loadJobs();
|
||||
} catch (error: unknown) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
@@ -298,7 +352,7 @@ export default function AutomationPage() {
|
||||
message.success(
|
||||
`${job.title}已执行:扫描 ${outcome.scanned},成功 ${outcome.valid},失败 ${outcome.invalid}`,
|
||||
);
|
||||
await load();
|
||||
await loadJobs();
|
||||
} catch (error: unknown) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
@@ -316,7 +370,7 @@ export default function AutomationPage() {
|
||||
enabled: Boolean(values.enabled),
|
||||
} as AutomationLoginQuota);
|
||||
message.success("登录预算已保存");
|
||||
await load();
|
||||
await loadBudget();
|
||||
} catch (error: unknown) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
@@ -333,7 +387,7 @@ export default function AutomationPage() {
|
||||
...budgetRecommendation.recommended,
|
||||
});
|
||||
message.success("已应用预算建议");
|
||||
await load();
|
||||
await loadBudget();
|
||||
} catch (error: unknown) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
@@ -588,7 +642,7 @@ export default function AutomationPage() {
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SaveOutlined />}
|
||||
loading={savingBudget}
|
||||
loading={savingBudget || budgetLoading}
|
||||
disabled={!canManage}
|
||||
onClick={() => void saveBudget()}
|
||||
>
|
||||
@@ -751,7 +805,7 @@ export default function AutomationPage() {
|
||||
<Table
|
||||
rowKey="id"
|
||||
size="small"
|
||||
loading={loading}
|
||||
loading={historyLoading}
|
||||
columns={runColumns}
|
||||
dataSource={filteredRuns}
|
||||
pagination={{ pageSize: 20, showSizeChanger: false }}
|
||||
@@ -786,14 +840,19 @@ export default function AutomationPage() {
|
||||
: "调度线程未运行"
|
||||
: "自动化总开关关闭"}
|
||||
</Tag>
|
||||
<Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>
|
||||
<Button
|
||||
icon={<ReloadOutlined />}
|
||||
loading={loading || budgetLoading || historyLoading || manualLoading}
|
||||
onClick={() => void refreshVisible()}
|
||||
>
|
||||
刷新配置
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<Tabs
|
||||
destroyOnHidden
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
items={[
|
||||
{
|
||||
key: "overview",
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
type DouyuPlatformTrends,
|
||||
type DouyuSupplyTarget,
|
||||
type DouyuSupplyTargetConfig,
|
||||
type DouyuSupplyTargetStatus,
|
||||
} from '../../api/modules';
|
||||
import { usePermissions } from '../../hooks/usePermissions';
|
||||
import { message } from '../../utils/antdMessage';
|
||||
@@ -158,9 +159,12 @@ export default function AccountPlatformStatusPanel() {
|
||||
const [protectionForm] = Form.useForm<ProtectionFormValues>();
|
||||
const [status, setStatus] = useState<DouyuAccountPlatformStatus | null>(null);
|
||||
const [targetConfigs, setTargetConfigs] = useState<DouyuSupplyTargetConfig[]>([]);
|
||||
const [supplyTargets, setSupplyTargets] = useState<DouyuSupplyTargetStatus[]>([]);
|
||||
const [supplyAlerts, setSupplyAlerts] = useState<DouyuPlatformAlert[]>([]);
|
||||
const [trends, setTrends] = useState<DouyuPlatformTrends | null>(null);
|
||||
const [trendAlerts, setTrendAlerts] = useState<DouyuPlatformAlert[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [statusLoading, setStatusLoading] = useState(false);
|
||||
const [supplyLoading, setSupplyLoading] = useState(false);
|
||||
const [trendsLoading, setTrendsLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
@@ -171,12 +175,15 @@ export default function AccountPlatformStatusPanel() {
|
||||
const [editingProtection, setEditingProtection] =
|
||||
useState<DouyuAccountProtectionTarget | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setTrendsLoading(true);
|
||||
const loadStatus = useCallback(async () => {
|
||||
setStatusLoading(true);
|
||||
setError('');
|
||||
const statusPromise = douyuApi
|
||||
.getAccountPlatformStatus(false)
|
||||
.getAccountPlatformStatus({
|
||||
includeTrends: false,
|
||||
includeSupply: false,
|
||||
includeDiagnostics: false,
|
||||
})
|
||||
.then((platformStatus) => {
|
||||
setStatus(platformStatus);
|
||||
})
|
||||
@@ -184,7 +191,7 @@ export default function AccountPlatformStatusPanel() {
|
||||
setError(getErrorMessage(loadError));
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false);
|
||||
setStatusLoading(false);
|
||||
});
|
||||
const targetsPromise = canManage
|
||||
? douyuApi.listSupplyTargetConfigs()
|
||||
@@ -193,25 +200,50 @@ export default function AccountPlatformStatusPanel() {
|
||||
setError((current) => current || getErrorMessage(loadError));
|
||||
})
|
||||
: Promise.resolve();
|
||||
// 主状态返回后再加载趋势,避免两条重查询同时争抢数据库和 CPU。
|
||||
const trendsPromise = statusPromise.then(async () => {
|
||||
try {
|
||||
const response = await douyuApi.getAccountPlatformTrends();
|
||||
setTrends(response.trends);
|
||||
setTrendAlerts(response.alerts);
|
||||
} catch (loadError: unknown) {
|
||||
setTrendAlerts([{
|
||||
code: 'account_trends_load_failed',
|
||||
severity: 'info',
|
||||
message: `趋势加载失败:${getErrorMessage(loadError)}`,
|
||||
}]);
|
||||
} finally {
|
||||
setTrendsLoading(false);
|
||||
}
|
||||
});
|
||||
await Promise.allSettled([statusPromise, targetsPromise, trendsPromise]);
|
||||
await Promise.allSettled([statusPromise, targetsPromise]);
|
||||
}, [canManage]);
|
||||
|
||||
const loadSupply = useCallback(async () => {
|
||||
setSupplyLoading(true);
|
||||
try {
|
||||
const response = await douyuApi.getAccountPlatformSupply();
|
||||
setSupplyTargets(response.supply_targets);
|
||||
setSupplyAlerts(response.alerts);
|
||||
} catch (loadError: unknown) {
|
||||
setSupplyAlerts([{
|
||||
code: 'account_supply_load_failed',
|
||||
severity: 'warning',
|
||||
message: `供给库存加载失败:${getErrorMessage(loadError)}`,
|
||||
}]);
|
||||
} finally {
|
||||
setSupplyLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadTrends = useCallback(async () => {
|
||||
setTrendsLoading(true);
|
||||
try {
|
||||
const response = await douyuApi.getAccountPlatformTrends();
|
||||
setTrends(response.trends);
|
||||
setTrendAlerts(response.alerts);
|
||||
} catch (loadError: unknown) {
|
||||
setTrendAlerts([{
|
||||
code: 'account_trends_load_failed',
|
||||
severity: 'info',
|
||||
message: `趋势加载失败:${getErrorMessage(loadError)}`,
|
||||
}]);
|
||||
} finally {
|
||||
setTrendsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
await loadStatus();
|
||||
// 首屏状态已经可交互;供给和趋势较重,按顺序加载,避免同时争抢数据库。
|
||||
await loadSupply();
|
||||
await loadTrends();
|
||||
}, [loadStatus, loadSupply, loadTrends]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
@@ -225,9 +257,9 @@ export default function AccountPlatformStatusPanel() {
|
||||
);
|
||||
const targets = useMemo<DouyuSupplyTarget[]>(() => {
|
||||
const inventoryByTarget = new Map(
|
||||
(status?.supply_targets || []).map((row) => [row.target_id, row]),
|
||||
supplyTargets.map((row) => [row.target_id, row]),
|
||||
);
|
||||
const statusConfigs: DouyuSupplyTargetConfig[] = (status?.supply_targets || []).map(
|
||||
const statusConfigs: DouyuSupplyTargetConfig[] = supplyTargets.map(
|
||||
(row) => ({
|
||||
id: row.target_id,
|
||||
target_id: row.target_id,
|
||||
@@ -260,7 +292,7 @@ export default function AccountPlatformStatusPanel() {
|
||||
needs_replenishment: inventory?.needs_replenishment || false,
|
||||
};
|
||||
});
|
||||
}, [canManage, status?.supply_targets, targetConfigs]);
|
||||
}, [canManage, supplyTargets, targetConfigs]);
|
||||
const trendRows = useMemo(() => {
|
||||
if (!trends) return [];
|
||||
const rows = new Map<string, TrendRow>();
|
||||
@@ -306,9 +338,10 @@ export default function AccountPlatformStatusPanel() {
|
||||
return [...rows.values()].sort((left, right) => left.date.localeCompare(right.date));
|
||||
}, [trends]);
|
||||
const visibleAlerts = useMemo(
|
||||
() => [...(status?.alerts || []), ...trendAlerts],
|
||||
[status?.alerts, trendAlerts],
|
||||
() => [...(status?.alerts || []), ...supplyAlerts, ...trendAlerts],
|
||||
[status?.alerts, supplyAlerts, trendAlerts],
|
||||
);
|
||||
const loading = statusLoading || supplyLoading || trendsLoading;
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
@@ -647,7 +680,7 @@ export default function AccountPlatformStatusPanel() {
|
||||
style={{ marginTop: 8 }}
|
||||
columns={protectionColumns}
|
||||
dataSource={status?.protection_targets || []}
|
||||
loading={loading}
|
||||
loading={statusLoading}
|
||||
pagination={false}
|
||||
scroll={{ x: 950 }}
|
||||
locale={{
|
||||
@@ -667,7 +700,7 @@ export default function AccountPlatformStatusPanel() {
|
||||
style={{ marginTop: 8 }}
|
||||
columns={columns}
|
||||
dataSource={targets}
|
||||
loading={loading}
|
||||
loading={supplyLoading}
|
||||
pagination={false}
|
||||
scroll={{ x: 750 }}
|
||||
locale={{
|
||||
|
||||
Reference in New Issue
Block a user