perf(account-check): 优化账号检测首屏加载

This commit is contained in:
yml
2026-11-22 17:05:10 +08:00
parent 7233bdfa50
commit 22e106bf9b
9 changed files with 421 additions and 150 deletions
+16
View File
@@ -161,6 +161,22 @@ def test_protection_target_reports_ck_health_and_shortage(db):
} }
def test_protection_target_counts_missing_cookie_without_full_account_load(db):
account = _account("protection-no-cookie")
account.cookie = ""
db.add(account)
db.flush()
db.add(_presale_task(account))
db.add(_health_job())
db.commit()
rows = evaluate_protection_targets(db, now=NOW)
presale = next(row for row in rows if row["group_key"] == "presale_bound")
assert presale["bound_count"] == 1
assert presale["without_cookie"] == 1
def test_ck_health_probes_protected_account_at_its_shorter_interval_first(db): def test_ck_health_probes_protected_account_at_its_shorter_interval_first(db):
protected = _account( protected = _account(
"protection-due", "protection-due",
+27 -2
View File
@@ -19,9 +19,16 @@ from web.backend.models import (
LoginAttempt, LoginAttempt,
User, User,
) )
from web.backend.routers.douyu import create_supply_target, list_supply_targets from web.backend.routers.douyu import (
create_supply_target,
list_supply_target_configs,
list_supply_targets,
)
from web.backend.schemas import DouyuSupplyTargetUpsert from web.backend.schemas import DouyuSupplyTargetUpsert
from web.backend.services.account_observability import account_platform_status from web.backend.services.account_observability import (
account_platform_status,
account_platform_trends,
)
from web.backend.services.account_supply_service import ( from web.backend.services.account_supply_service import (
VALUE_HIGH, VALUE_HIGH,
_global_inventory_totals, _global_inventory_totals,
@@ -349,6 +356,9 @@ def test_supply_target_configuration_route_returns_inventory(db):
assert listed[0].id == created.id assert listed[0].id == created.id
assert listed[0].target_id == created.id assert listed[0].target_id == created.id
assert listed[0].needs_replenishment is True assert listed[0].needs_replenishment is True
configs = list_supply_target_configs(db=db, current=user)
assert configs[0].target_id == created.target_id
assert configs[0].target_covered == 10
def test_account_platform_status_aggregates_queue_sync_and_supply(db): def test_account_platform_status_aggregates_queue_sync_and_supply(db):
@@ -400,6 +410,21 @@ def test_account_platform_status_aggregates_queue_sync_and_supply(db):
} }
def test_account_platform_status_can_defer_trends(db):
account = _account("platform-no-trends", points=400)
db.add(account)
db.flush()
db.add(_state(account))
db.commit()
status = account_platform_status(db, now=NOW, include_trends=False)
trends = account_platform_trends(db, now=NOW)
assert status["trends"] is None
assert len(trends["trends"]["query"]) == 7
assert isinstance(trends["alerts"], list)
def test_account_platform_status_builds_seven_day_trends(db): def test_account_platform_status_builds_seven_day_trends(db):
account = _account("platform-trends", points=400) account = _account("platform-trends", points=400)
db.add(account) db.add(account)
+56 -2
View File
@@ -54,6 +54,7 @@ from ..schemas import (
DouyuConfigUpdate, DouyuConfigUpdate,
DouyuExchangeResultImageOut, DouyuExchangeResultImageOut,
DouyuGoodsOut, DouyuGoodsOut,
DouyuSupplyTargetConfigOut,
DouyuSupplyTargetOut, DouyuSupplyTargetOut,
DouyuSupplyTargetUpdate, DouyuSupplyTargetUpdate,
DouyuSupplyTargetUpsert, DouyuSupplyTargetUpsert,
@@ -64,7 +65,10 @@ from ..schemas import (
DouyuXpdGoodsOut, DouyuXpdGoodsOut,
) )
from ..services.account_binding import bind_payload from ..services.account_binding import bind_payload
from ..services.account_observability import account_platform_status from ..services.account_observability import (
account_platform_status,
account_platform_trends,
)
from ..services.account_protection_service import ( from ..services.account_protection_service import (
evaluate_protection_targets, evaluate_protection_targets,
update_protection_group, update_protection_group,
@@ -739,11 +743,21 @@ def task_types(current: User = Depends(require_permission("douyu:task"))):
@router.get("/account-platform-status") @router.get("/account-platform-status")
def get_account_platform_status( def get_account_platform_status(
include_trends: bool = Query(True),
db: Session = Depends(get_db), db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:task")), current: User = Depends(require_permission("douyu:task")),
): ):
"""账号同步、CK 周期、商品覆盖和供给缺口的统一观测快照。""" """账号同步、CK 周期、商品覆盖和供给缺口的统一观测快照。"""
return account_platform_status(db) return account_platform_status(db, include_trends=include_trends)
@router.get("/account-platform-trends")
def get_account_platform_trends(
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:task")),
):
"""延迟加载账号平台 7 天趋势,避免阻塞账号检测首屏。"""
return account_platform_trends(db)
@router.put( @router.put(
@@ -1071,6 +1085,46 @@ def list_supply_targets(
] ]
@router.get(
"/supply-targets/config",
response_model=list[DouyuSupplyTargetConfigOut],
)
def list_supply_target_configs(
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:config")),
):
"""只返回供给目标配置,库存由 account-platform-status 统一提供。"""
rows = (
db.query(AccountSupplyTarget)
.order_by(
AccountSupplyTarget.enabled.desc(),
AccountSupplyTarget.scope.asc(),
AccountSupplyTarget.value_class.asc(),
AccountSupplyTarget.commodity_id.asc(),
AccountSupplyTarget.id.asc(),
)
.all()
)
return [
DouyuSupplyTargetConfigOut(
id=int(row.id),
target_id=int(row.id),
platform=row.platform,
scope=row.scope,
commodity_id=row.commodity_id,
value_class=row.value_class,
target_covered=int(row.target_covered or 0),
target_available=int(row.target_available or 0),
target_allocatable=int(row.target_allocatable or 0),
safety_buffer=int(row.safety_buffer or 0),
enabled=bool(row.enabled),
updated_by=row.updated_by,
updated_at=row.updated_at,
)
for row in rows
]
@router.post("/supply-targets", response_model=DouyuSupplyTargetOut) @router.post("/supply-targets", response_model=DouyuSupplyTargetOut)
def create_supply_target( def create_supply_target(
req: DouyuSupplyTargetUpsert, req: DouyuSupplyTargetUpsert,
+16
View File
@@ -1630,6 +1630,22 @@ class DouyuSupplyTargetOut(BaseModel):
updated_at: datetime | None = None updated_at: datetime | None = None
class DouyuSupplyTargetConfigOut(BaseModel):
id: int
target_id: int
platform: str
scope: str
commodity_id: str
value_class: str
target_covered: int
target_available: int
target_allocatable: int
safety_buffer: int
enabled: bool
updated_by: int | None = None
updated_at: datetime | None = None
class DouyuAccountProtectionTargetUpdate(BaseModel): class DouyuAccountProtectionTargetUpdate(BaseModel):
enabled: bool = True enabled: bool = True
target_count: int = Field(0, ge=0, le=100_000) target_count: int = Field(0, ge=0, le=100_000)
+75 -59
View File
@@ -193,10 +193,79 @@ def _platform_trends(db: Session, moment: datetime) -> dict[str, Any]:
} }
def _trend_alerts(trends: dict[str, Any]) -> list[dict[str, Any]]:
alerts: list[dict[str, Any]] = []
query_sample = sum(
int(row["success"]) + int(row["failed"]) for row in trends["query"]
)
query_success = sum(int(row["success"]) for row in trends["query"])
query_rate = _rate(query_success, query_sample)
if query_sample >= 20 and query_rate < 80:
alerts.append(
{
"code": "query_success_rate_low",
"severity": "critical" if query_rate < 50 else "warning",
"count": query_sample,
"message": (
f"近 {TREND_DAYS} 天查询成功率 {query_rate:.1f}%"
f"({query_sample} 次已完成查询)"
),
}
)
login_sample = sum(
int(row["success"]) + int(row["failed"]) for row in trends["login"]
)
login_success = sum(int(row["success"]) for row in trends["login"])
login_rate = _rate(login_success, login_sample)
if login_sample >= 10 and login_rate < 60:
alerts.append(
{
"code": "login_success_rate_low",
"severity": "critical" if login_rate < 40 else "warning",
"count": login_sample,
"message": (
f"近 {TREND_DAYS} 天登录成功率 {login_rate:.1f}%"
f"({login_sample} 次已完成尝试)"
),
}
)
relogin_ok = sum(int(row["relogin_ok"]) for row in trends["lifecycle"])
relogin_failed = sum(int(row["relogin_failed"]) for row in trends["lifecycle"])
if relogin_failed >= 5 and relogin_failed > relogin_ok:
alerts.append(
{
"code": "relogin_failure_trend_high",
"severity": "warning",
"count": relogin_failed,
"message": (
f"近 {TREND_DAYS} 天重登失败 {relogin_failed} 次,"
f"成功 {relogin_ok} 次"
),
}
)
return alerts
def account_platform_trends(
db: Session,
*,
now: datetime | None = None,
) -> dict[str, Any]:
"""返回可延迟加载的趋势和趋势告警,避免阻塞账号检测首屏。"""
trends = _platform_trends(db, now or datetime.now(UTC))
return {
"trends": trends,
"alerts": _trend_alerts(trends),
}
def account_platform_status( def account_platform_status(
db: Session, db: Session,
*, *,
now: datetime | None = None, now: datetime | None = None,
include_trends: bool = True,
) -> dict[str, Any]: ) -> dict[str, Any]:
moment = now or datetime.now(UTC) moment = now or datetime.now(UTC)
in_24h = moment + timedelta(hours=24) in_24h = moment + timedelta(hours=24)
@@ -349,9 +418,8 @@ def account_platform_status(
) )
if not item.needs_replenishment: if not item.needs_replenishment:
continue continue
critical = ( critical = (item.target_available > 0 and item.available <= 0) or (
(item.target_available > 0 and item.available <= 0) item.target_allocatable > 0 and item.allocatable <= 0
or (item.target_allocatable > 0 and item.allocatable <= 0)
) )
alerts.append( alerts.append(
{ {
@@ -440,61 +508,9 @@ def account_platform_status(
} }
) )
trends = _platform_trends(db, moment) trends = _platform_trends(db, moment) if include_trends else None
query_sample = sum( if trends is not None:
int(row["success"]) + int(row["failed"]) alerts.extend(_trend_alerts(trends))
for row in trends["query"]
)
query_success = sum(int(row["success"]) for row in trends["query"])
query_rate = _rate(query_success, query_sample)
if query_sample >= 20 and query_rate < 80:
alerts.append(
{
"code": "query_success_rate_low",
"severity": "critical" if query_rate < 50 else "warning",
"count": query_sample,
"message": (
f"近 {TREND_DAYS} 天查询成功率 {query_rate:.1f}%"
f"({query_sample} 次已完成查询)"
),
}
)
login_sample = sum(
int(row["success"]) + int(row["failed"])
for row in trends["login"]
)
login_success = sum(int(row["success"]) for row in trends["login"])
login_rate = _rate(login_success, login_sample)
if login_sample >= 10 and login_rate < 60:
alerts.append(
{
"code": "login_success_rate_low",
"severity": "critical" if login_rate < 40 else "warning",
"count": login_sample,
"message": (
f"近 {TREND_DAYS} 天登录成功率 {login_rate:.1f}%"
f"({login_sample} 次已完成尝试)"
),
}
)
relogin_ok = sum(int(row["relogin_ok"]) for row in trends["lifecycle"])
relogin_failed = sum(
int(row["relogin_failed"]) for row in trends["lifecycle"]
)
if relogin_failed >= 5 and relogin_failed > relogin_ok:
alerts.append(
{
"code": "relogin_failure_trend_high",
"severity": "warning",
"count": relogin_failed,
"message": (
f"近 {TREND_DAYS} 天重登失败 {relogin_failed} 次,"
f"成功 {relogin_ok} 次"
),
}
)
return { return {
"checked_at": moment, "checked_at": moment,
@@ -523,4 +539,4 @@ def account_platform_status(
} }
__all__ = ["account_platform_status"] __all__ = ["account_platform_status", "account_platform_trends"]
@@ -14,9 +14,10 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from datetime import UTC, datetime from datetime import UTC, datetime, timedelta
from typing import Any from typing import Any
from sqlalchemy import and_, case, func, or_
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ..models import ( from ..models import (
@@ -97,9 +98,7 @@ def normalize_group_config(
MIN_PROBE_INTERVAL_MINUTES, MIN_PROBE_INTERVAL_MINUTES,
MAX_PROBE_INTERVAL_MINUTES, MAX_PROBE_INTERVAL_MINUTES,
), ),
"auto_relogin": bool( "auto_relogin": bool(value.get("auto_relogin", definition["auto_relogin"])),
value.get("auto_relogin", definition["auto_relogin"])
),
} }
@@ -124,9 +123,7 @@ def _presale_account_ids(db: Session) -> set[int]:
.filter( .filter(
PlatformFulfillmentTask.sale_mode == "presale", PlatformFulfillmentTask.sale_mode == "presale",
PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.account_id.isnot(None),
PlatformFulfillmentTask.execution_status.notin_( PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")),
("completed", "cancelled")
),
) )
.distinct() .distinct()
.all() .all()
@@ -246,59 +243,109 @@ def evaluate_protection_targets(
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
moment = now or datetime.now(UTC) moment = now or datetime.now(UTC)
snapshot = load_protection_snapshot(db, job_config=job_config) snapshot = load_protection_snapshot(db, job_config=job_config)
all_ids = {
account_id
for ids in snapshot.group_account_ids.values()
for account_id in ids
}
accounts = (
db.query(Account).filter(Account.id.in_(all_ids)).all() if all_ids else []
)
account_map = {int(account.id): account for account in accounts}
rows: list[dict[str, Any]] = [] rows: list[dict[str, Any]] = []
for key, group in snapshot.groups.items(): for key, group in snapshot.groups.items():
account_ids = snapshot.group_account_ids.get(key, frozenset()) account_ids = snapshot.group_account_ids.get(key, frozenset())
group_accounts = [ probe_cutoff = moment - timedelta(minutes=int(group["probe_interval_minutes"]))
account_map[account_id] if account_ids:
for account_id in account_ids # 只做数据库条件聚合,不加载 Account ORM。完整账号行包含加密密码、
if account_id in account_map # 邮箱/Cookie 和大型 JSON 快照,2174 行实测可占 2 秒以上。
] totals = (
db.query(
func.count(Account.id),
func.coalesce(
func.sum(
case((Account.ck_check_status == "valid", 1), else_=0)
),
0,
),
func.coalesce(
func.sum(
case((Account.ck_check_status == "invalid", 1), else_=0)
),
0,
),
func.coalesce(
func.sum(
case((Account.ck_check_status == "error", 1), else_=0)
),
0,
),
func.coalesce(
func.sum(
case(
(
func.coalesce(Account.ck_check_status, "").notin_(
("valid", "invalid", "error")
),
1,
),
else_=0,
)
),
0,
),
func.coalesce(
func.sum(
case(
(
or_(
Account.cookie.is_(None),
func.length(Account.cookie) == 0,
),
1,
),
else_=0,
)
),
0,
),
func.coalesce(
func.sum(
case(
(
or_(
Account.ck_checked_at.is_(None),
and_(
Account.ck_checked_at.isnot(None),
Account.ck_checked_at < probe_cutoff,
),
),
1,
),
else_=0,
)
),
0,
),
)
.filter(Account.id.in_(account_ids))
.one()
)
(
bound_count,
ck_valid,
ck_invalid,
ck_error,
ck_unchecked,
without_cookie,
probe_due_count,
) = (int(value or 0) for value in totals)
else:
bound_count = ck_valid = ck_invalid = ck_error = 0
ck_unchecked = without_cookie = probe_due_count = 0
status_counts = { status_counts = {
"ck_valid": 0, "ck_valid": ck_valid,
"ck_invalid": 0, "ck_invalid": ck_invalid,
"ck_error": 0, "ck_error": ck_error,
"ck_unchecked": 0, "ck_unchecked": ck_unchecked,
"without_cookie": 0, "without_cookie": without_cookie,
} }
for account in group_accounts:
status = str(account.ck_check_status or "")
if status == "valid":
status_counts["ck_valid"] += 1
elif status == "invalid":
status_counts["ck_invalid"] += 1
elif status == "error":
status_counts["ck_error"] += 1
else:
status_counts["ck_unchecked"] += 1
if not account.cookie:
status_counts["without_cookie"] += 1
target = int(group["target_count"]) target = int(group["target_count"])
shortage = max(target - status_counts["ck_valid"], 0) shortage = max(target - status_counts["ck_valid"], 0)
probe_seconds = int(group["probe_interval_minutes"]) * 60
due_at = moment.timestamp() - probe_seconds
due_count = sum(
1
for account in group_accounts
if account.ck_checked_at is None
or (
account.ck_checked_at.replace(tzinfo=UTC)
if account.ck_checked_at.tzinfo is None
else account.ck_checked_at
).timestamp()
<= due_at
)
needs_attention = bool( needs_attention = bool(
group["enabled"] group["enabled"]
and ( and (
@@ -317,10 +364,10 @@ def evaluate_protection_targets(
"target_count": target, "target_count": target,
"probe_interval_minutes": int(group["probe_interval_minutes"]), "probe_interval_minutes": int(group["probe_interval_minutes"]),
"auto_relogin": bool(group["auto_relogin"]), "auto_relogin": bool(group["auto_relogin"]),
"bound_count": len(group_accounts), "bound_count": bound_count,
**status_counts, **status_counts,
"target_shortage": shortage, "target_shortage": shortage,
"probe_due_count": due_count, "probe_due_count": probe_due_count,
"needs_attention": needs_attention, "needs_attention": needs_attention,
} }
) )
+10 -2
View File
@@ -3,11 +3,13 @@ import type {
DouyuAccountProtectionTarget, DouyuAccountProtectionTarget,
DouyuAccountProtectionTargetUpdate, DouyuAccountProtectionTargetUpdate,
DouyuAccountPlatformStatus, DouyuAccountPlatformStatus,
DouyuPlatformTrendsResponse,
DouyuConfig, DouyuConfig,
DouyuExchangeResultImage, DouyuExchangeResultImage,
DouyuGoodsItem, DouyuGoodsItem,
DouyuRechargeChannel, DouyuRechargeChannel,
DouyuSupplyTarget, DouyuSupplyTarget,
DouyuSupplyTargetConfig,
DouyuSupplyTargetUpdate, DouyuSupplyTargetUpdate,
DouyuSupplyTargetUpsert, DouyuSupplyTargetUpsert,
DouyuTaskAccountItem, DouyuTaskAccountItem,
@@ -22,8 +24,12 @@ import type {
export const douyuApi = { export const douyuApi = {
taskTypes: () => api.get<Record<string, string>, Record<string, string>>('/douyu/task-types'), taskTypes: () => api.get<Record<string, string>, Record<string, string>>('/douyu/task-types'),
getAccountPlatformStatus: () => getAccountPlatformStatus: (includeTrends = true) =>
api.get<DouyuAccountPlatformStatus, DouyuAccountPlatformStatus>('/douyu/account-platform-status'), api.get<DouyuAccountPlatformStatus, DouyuAccountPlatformStatus>('/douyu/account-platform-status', {
params: { include_trends: includeTrends },
}),
getAccountPlatformTrends: () =>
api.get<DouyuPlatformTrendsResponse, DouyuPlatformTrendsResponse>('/douyu/account-platform-trends'),
updateAccountProtectionTarget: ( updateAccountProtectionTarget: (
groupKey: DouyuAccountProtectionTarget['group_key'], groupKey: DouyuAccountProtectionTarget['group_key'],
data: DouyuAccountProtectionTargetUpdate, data: DouyuAccountProtectionTargetUpdate,
@@ -34,6 +40,8 @@ export const douyuApi = {
), ),
listSupplyTargets: () => listSupplyTargets: () =>
api.get<DouyuSupplyTarget[], DouyuSupplyTarget[]>('/douyu/supply-targets'), api.get<DouyuSupplyTarget[], DouyuSupplyTarget[]>('/douyu/supply-targets'),
listSupplyTargetConfigs: () =>
api.get<DouyuSupplyTargetConfig[], DouyuSupplyTargetConfig[]>('/douyu/supply-targets/config'),
createSupplyTarget: (data: DouyuSupplyTargetUpsert) => createSupplyTarget: (data: DouyuSupplyTargetUpsert) =>
api.post<DouyuSupplyTarget, DouyuSupplyTarget>('/douyu/supply-targets', data), api.post<DouyuSupplyTarget, DouyuSupplyTarget>('/douyu/supply-targets', data),
updateSupplyTarget: (targetId: number, data: DouyuSupplyTargetUpdate) => updateSupplyTarget: (targetId: number, data: DouyuSupplyTargetUpdate) =>
+22 -1
View File
@@ -745,6 +745,22 @@ export interface DouyuSupplyTargetStatus {
needs_replenishment: boolean; needs_replenishment: boolean;
} }
export interface DouyuSupplyTargetConfig {
id: number;
target_id: number;
platform: string;
scope: string;
commodity_id: string;
value_class: 'high_value' | 'ordinary';
target_covered: number;
target_available: number;
target_allocatable: number;
safety_buffer: number;
enabled: boolean;
updated_by: number | null;
updated_at: string | null;
}
export interface DouyuSupplyTarget extends DouyuSupplyTargetStatus { export interface DouyuSupplyTarget extends DouyuSupplyTargetStatus {
platform: string; platform: string;
enabled: boolean; enabled: boolean;
@@ -859,6 +875,11 @@ export interface DouyuPlatformTrends {
lifecycle: DouyuLifecycleTrendDay[]; lifecycle: DouyuLifecycleTrendDay[];
} }
export interface DouyuPlatformTrendsResponse {
trends: DouyuPlatformTrends;
alerts: DouyuPlatformAlert[];
}
export interface DouyuAccountPlatformStatus { export interface DouyuAccountPlatformStatus {
checked_at: string; checked_at: string;
accounts: { accounts: {
@@ -882,7 +903,7 @@ export interface DouyuAccountPlatformStatus {
protection_targets: DouyuAccountProtectionTarget[]; protection_targets: DouyuAccountProtectionTarget[];
supply_targets: DouyuSupplyTargetStatus[]; supply_targets: DouyuSupplyTargetStatus[];
alerts: DouyuPlatformAlert[]; alerts: DouyuPlatformAlert[];
trends: DouyuPlatformTrends; trends: DouyuPlatformTrends | null;
} }
export interface DouyuConfig { export interface DouyuConfig {
@@ -30,7 +30,10 @@ import {
douyuApi, douyuApi,
type DouyuAccountProtectionTarget, type DouyuAccountProtectionTarget,
type DouyuAccountPlatformStatus, type DouyuAccountPlatformStatus,
type DouyuPlatformAlert,
type DouyuPlatformTrends,
type DouyuSupplyTarget, type DouyuSupplyTarget,
type DouyuSupplyTargetConfig,
} from '../../api/modules'; } from '../../api/modules';
import { usePermissions } from '../../hooks/usePermissions'; import { usePermissions } from '../../hooks/usePermissions';
import { message } from '../../utils/antdMessage'; import { message } from '../../utils/antdMessage';
@@ -83,8 +86,11 @@ export default function AccountPlatformStatusPanel() {
const [form] = Form.useForm<TargetFormValues>(); const [form] = Form.useForm<TargetFormValues>();
const [protectionForm] = Form.useForm<ProtectionFormValues>(); const [protectionForm] = Form.useForm<ProtectionFormValues>();
const [status, setStatus] = useState<DouyuAccountPlatformStatus | null>(null); const [status, setStatus] = useState<DouyuAccountPlatformStatus | null>(null);
const [targets, setTargets] = useState<DouyuSupplyTarget[]>([]); const [targetConfigs, setTargetConfigs] = useState<DouyuSupplyTargetConfig[]>([]);
const [trends, setTrends] = useState<DouyuPlatformTrends | null>(null);
const [trendAlerts, setTrendAlerts] = useState<DouyuPlatformAlert[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [trendsLoading, setTrendsLoading] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -96,26 +102,43 @@ export default function AccountPlatformStatusPanel() {
const load = useCallback(async () => { const load = useCallback(async () => {
setLoading(true); setLoading(true);
setTrendsLoading(true);
setError(''); setError('');
try { const statusPromise = douyuApi
const platformStatus = await douyuApi.getAccountPlatformStatus(); .getAccountPlatformStatus(false)
if (canManage) { .then((platformStatus) => {
setTargets(await douyuApi.listSupplyTargets()); setStatus(platformStatus);
} else { })
setTargets(platformStatus.supply_targets.map((row) => ({ .catch((loadError: unknown) => {
...row, setError(getErrorMessage(loadError));
platform: 'douyu', })
enabled: true, .finally(() => {
updated_by: null, setLoading(false);
updated_at: null, });
}))); const targetsPromise = canManage
? douyuApi.listSupplyTargetConfigs()
.then(setTargetConfigs)
.catch((loadError: unknown) => {
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);
} }
setStatus(platformStatus); });
} catch (loadError: unknown) { await Promise.allSettled([statusPromise, targetsPromise, trendsPromise]);
setError(getErrorMessage(loadError));
} finally {
setLoading(false);
}
}, [canManage]); }, [canManage]);
useEffect(() => { useEffect(() => {
@@ -129,10 +152,48 @@ export default function AccountPlatformStatusPanel() {
), ),
[status?.work_queue], [status?.work_queue],
); );
const targets = useMemo<DouyuSupplyTarget[]>(() => {
const inventoryByTarget = new Map(
(status?.supply_targets || []).map((row) => [row.target_id, row]),
);
const statusConfigs: DouyuSupplyTargetConfig[] = (status?.supply_targets || []).map(
(row) => ({
id: row.target_id,
target_id: row.target_id,
platform: 'douyu',
scope: row.scope,
commodity_id: row.commodity_id,
value_class: row.value_class,
target_covered: row.target_covered,
target_available: row.target_available,
target_allocatable: row.target_allocatable,
safety_buffer: row.safety_buffer,
enabled: true,
updated_by: null,
updated_at: null,
}),
);
const sourceConfigs = canManage && targetConfigs.length > 0
? targetConfigs
: statusConfigs;
return sourceConfigs.map((config) => {
const inventory = inventoryByTarget.get(config.target_id);
return {
...config,
covered: inventory?.covered || 0,
available: inventory?.available || 0,
allocatable: inventory?.allocatable || 0,
covered_shortage: inventory?.covered_shortage || 0,
available_shortage: inventory?.available_shortage || 0,
allocatable_shortage: inventory?.allocatable_shortage || 0,
needs_replenishment: inventory?.needs_replenishment || false,
};
});
}, [canManage, status?.supply_targets, targetConfigs]);
const trendRows = useMemo(() => { const trendRows = useMemo(() => {
if (!status) return []; if (!trends) return [];
const rows = new Map<string, TrendRow>(); const rows = new Map<string, TrendRow>();
for (const item of status.trends.query) { for (const item of trends.query) {
rows.set(item.date, { rows.set(item.date, {
date: item.date, date: item.date,
queryTotal: item.total, queryTotal: item.total,
@@ -143,7 +204,7 @@ export default function AccountPlatformStatusPanel() {
reloginOk: 0, reloginOk: 0,
}); });
} }
for (const item of status.trends.login) { for (const item of trends.login) {
const row = rows.get(item.date) || { const row = rows.get(item.date) || {
date: item.date, date: item.date,
queryTotal: 0, queryTotal: 0,
@@ -157,7 +218,7 @@ export default function AccountPlatformStatusPanel() {
row.loginRate = item.success_rate; row.loginRate = item.success_rate;
rows.set(item.date, row); rows.set(item.date, row);
} }
for (const item of status.trends.lifecycle) { for (const item of trends.lifecycle) {
const row = rows.get(item.date) || { const row = rows.get(item.date) || {
date: item.date, date: item.date,
queryTotal: 0, queryTotal: 0,
@@ -172,7 +233,11 @@ export default function AccountPlatformStatusPanel() {
rows.set(item.date, row); rows.set(item.date, row);
} }
return [...rows.values()].sort((left, right) => left.date.localeCompare(right.date)); return [...rows.values()].sort((left, right) => left.date.localeCompare(right.date));
}, [status]); }, [trends]);
const visibleAlerts = useMemo(
() => [...(status?.alerts || []), ...trendAlerts],
[status?.alerts, trendAlerts],
);
const openCreate = () => { const openCreate = () => {
setEditing(null); setEditing(null);
@@ -480,15 +545,15 @@ export default function AccountPlatformStatusPanel() {
> >
{error ? <Alert type="error" showIcon message={error} style={{ marginBottom: 16 }} /> : null} {error ? <Alert type="error" showIcon message={error} style={{ marginBottom: 16 }} /> : null}
<Row gutter={[16, 16]}> <Row gutter={[16, 16]}>
<Col xs={12} md={6}><Statistic title="CK 有效" value={status?.accounts.ck_valid || 0} /></Col> <Col xs={12} md={6}><Statistic title="CK 有效" value={status ? status.accounts.ck_valid : '--'} /></Col>
<Col xs={12} md={6}><Statistic title="24h 预计到期" value={status?.accounts.ck_expiring_24h || 0} /></Col> <Col xs={12} md={6}><Statistic title="24h 预计到期" value={status ? status.accounts.ck_expiring_24h : '--'} /></Col>
<Col xs={12} md={6}><Statistic title="新鲜可兑换商品" value={status?.commodities.fresh_available || 0} /></Col> <Col xs={12} md={6}><Statistic title="新鲜可兑换商品" value={status ? status.commodities.fresh_available : '--'} /></Col>
<Col xs={12} md={6}><Statistic title="待处理账号工作" value={pendingWork} /></Col> <Col xs={12} md={6}><Statistic title="待处理账号工作" value={status ? pendingWork : '--'} /></Col>
</Row> </Row>
{status?.alerts.length ? ( {visibleAlerts.length ? (
<Space orientation="vertical" size={8} style={{ width: '100%', marginTop: 16 }}> <Space orientation="vertical" size={8} style={{ width: '100%', marginTop: 16 }}>
{status.alerts.map((alert) => ( {visibleAlerts.map((alert) => (
<Alert <Alert
key={`${alert.code}-${alert.scope || ''}-${alert.value_class || ''}-${alert.message}`} key={`${alert.code}-${alert.scope || ''}-${alert.value_class || ''}-${alert.message}`}
type={alert.severity === 'critical' ? 'error' : alert.severity === 'warning' ? 'warning' : 'info'} type={alert.severity === 'critical' ? 'error' : alert.severity === 'warning' ? 'warning' : 'info'}
@@ -511,6 +576,7 @@ export default function AccountPlatformStatusPanel() {
style={{ marginTop: 8 }} style={{ marginTop: 8 }}
columns={protectionColumns} columns={protectionColumns}
dataSource={status?.protection_targets || []} dataSource={status?.protection_targets || []}
loading={loading}
pagination={false} pagination={false}
scroll={{ x: 950 }} scroll={{ x: 950 }}
locale={{ locale={{
@@ -530,6 +596,7 @@ export default function AccountPlatformStatusPanel() {
style={{ marginTop: 8 }} style={{ marginTop: 8 }}
columns={columns} columns={columns}
dataSource={targets} dataSource={targets}
loading={loading}
pagination={false} pagination={false}
scroll={{ x: 750 }} scroll={{ x: 750 }}
locale={{ locale={{
@@ -540,12 +607,13 @@ export default function AccountPlatformStatusPanel() {
/> />
<Space orientation="vertical" size={8} style={{ width: '100%', marginTop: 20 }}> <Space orientation="vertical" size={8} style={{ width: '100%', marginTop: 20 }}>
<Text strong>{`近 ${status?.trends.days || 7} 天趋势`}</Text> <Text strong>{`近 ${trends?.days || 7} 天趋势`}</Text>
<Table <Table
rowKey="date" rowKey="date"
size="small" size="small"
columns={trendColumns} columns={trendColumns}
dataSource={trendRows} dataSource={trendRows}
loading={trendsLoading}
pagination={false} pagination={false}
scroll={{ x: 750 }} scroll={{ x: 750 }}
/> />