Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

feat(admin-api): aggregate dashboard usage and project billing detail

yi76c13c566465
diff --git a/backend/app/api/admin/dashboard.py b/backend/app/api/admin/dashboard.py
index 480920f..b30755e 100644
--- a/backend/app/api/admin/dashboard.py
+++ b/backend/app/api/admin/dashboard.py
@@ -1,14 +1,17 @@
# Dashboard stats for admin console
-from datetime import datetime, timezone
-
from fastapi import APIRouter, Depends
-from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.deps import get_current_admin
-from app.models import Order, Project, User
-from app.schemas import AdminStatsOut
+from app.models import User
+from app.schemas import (
+ AdminDailyUsageOut,
+ AdminStatsOut,
+ AdminTopUserOut,
+ AdminUsageBucketOut,
+)
+from app.services.admin.stats import build_admin_dashboard_stats
router = APIRouter()
@@ -18,40 +21,25 @@ async def admin_stats(
_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
) -> AdminStatsOut:
- # Aggregate users, paid order amounts, project status histogram
- user_count = int((await db.execute(select(func.count()).select_from(User))).scalar_one() or 0)
-
- paid_total = int(
- (
- await db.execute(
- select(func.coalesce(func.sum(Order.amount_fen), 0)).where(Order.status == "paid")
- )
- ).scalar_one()
- or 0
- )
-
- today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
- paid_today = int(
- (
- await db.execute(
- select(func.coalesce(func.sum(Order.amount_fen), 0)).where(
- Order.status == "paid",
- Order.paid_at.is_not(None),
- Order.paid_at >= today_start,
- )
- )
- ).scalar_one()
- or 0
- )
-
- status_rows = (
- await db.execute(select(Project.status, func.count()).group_by(Project.status))
- ).all()
- project_status_counts = {str(status): int(cnt) for status, cnt in status_rows}
-
+ """用户/充值 + AI 调用量/费用/趋势/排行。"""
+ raw = await build_admin_dashboard_stats(db)
return AdminStatsOut(
- user_count=user_count,
- order_paid_total_fen=paid_total,
- order_paid_today_fen=paid_today,
- project_status_counts=project_status_counts,
+ user_count=raw["user_count"],
+ order_paid_total_fen=raw["order_paid_total_fen"],
+ order_paid_today_fen=raw["order_paid_today_fen"],
+ project_status_counts=raw["project_status_counts"],
+ drama_project_count=raw["drama_project_count"],
+ usage_calls_today=raw["usage_calls_today"],
+ usage_calls_month=raw["usage_calls_month"],
+ usage_calls_total=raw["usage_calls_total"],
+ usage_charge_today_fen=raw["usage_charge_today_fen"],
+ usage_charge_month_fen=raw["usage_charge_month_fen"],
+ usage_charge_total_fen=raw["usage_charge_total_fen"],
+ usage_cost_today_fen=raw["usage_cost_today_fen"],
+ usage_cost_month_fen=raw["usage_cost_month_fen"],
+ usage_cost_total_fen=raw["usage_cost_total_fen"],
+ usage_by_capability=[AdminUsageBucketOut(**x) for x in raw["usage_by_capability"]],
+ usage_by_domain=[AdminUsageBucketOut(**x) for x in raw["usage_by_domain"]],
+ daily_usage=[AdminDailyUsageOut(**x) for x in raw["daily_usage"]],
+ top_users_by_charge=[AdminTopUserOut(**x) for x in raw["top_users_by_charge"]],
)
diff --git a/backend/app/api/admin/drama_projects.py b/backend/app/api/admin/drama_projects.py
index e57b4e3..90b77de 100644
--- a/backend/app/api/admin/drama_projects.py
+++ b/backend/app/api/admin/drama_projects.py
@@ -1,22 +1,39 @@
-"""Admin drama project list with pagination and owner email."""
+"""Admin drama project list/detail with usage and production status."""
from __future__ import annotations
-from fastapi import APIRouter, Depends, Query
-from pydantic import BaseModel, ConfigDict
-from sqlalchemy import func, select
+from fastapi import APIRouter, Depends, HTTPException, Query
+from pydantic import BaseModel, ConfigDict, Field
+from sqlalchemy import func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
-from sqlalchemy.orm import aliased
+from sqlalchemy.orm import aliased, selectinload
from app.database import get_db
from app.deps import get_current_admin
from app.models import User
-from app.models_drama import DramaProject
-from app.schemas import PageMeta
+from app.models_drama import DramaAsset, DramaEpisode, DramaProject
+from app.models_tasks import TaskRun
+from app.schemas import AdminProjectUsageOut, AdminTaskBriefOut, PageMeta
+from app.services.admin.stats import aggregate_usage_summary
router = APIRouter()
+class AdminDramaEpisodeBriefOut(BaseModel):
+ id: int
+ name: str
+ fragment_count: int = 0
+ fragment_plan_status: str | None = None
+
+
+class AdminDramaAssetBriefOut(BaseModel):
+ id: int
+ type: str
+ name: str | None = None
+ has_cover: bool = False
+ generation_status: str | None = None
+
+
class AdminDramaProjectOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
@@ -27,6 +44,11 @@ class AdminDramaProjectOut(BaseModel):
description: str | None = None
created_at: object | None = None
updated_at: object | None = None
+ episode_count: int = 0
+ asset_count: int = 0
+ charge_fen: int = 0
+ summary_status: str | None = None
+ assets_seed_status: str | None = None
class AdminDramaProjectListOut(BaseModel):
@@ -34,18 +56,76 @@ class AdminDramaProjectListOut(BaseModel):
meta: PageMeta
+class AdminDramaProjectDetailOut(AdminDramaProjectOut):
+ fragment_count: int = 0
+ episode_content_status: str | None = None
+ usage: AdminProjectUsageOut = Field(default_factory=AdminProjectUsageOut)
+ episodes: list[AdminDramaEpisodeBriefOut] = Field(default_factory=list)
+ assets: list[AdminDramaAssetBriefOut] = Field(default_factory=list)
+ recent_tasks: list[AdminTaskBriefOut] = Field(default_factory=list)
+
+
+def _script_status(project: DramaProject, key: str) -> str | None:
+ script = project.script
+ if not script or not isinstance(script.params, dict):
+ return None
+ raw = script.params.get(key)
+ return str(raw) if raw else None
+
+
+def _project_param_status(project: DramaProject, key: str) -> str | None:
+ params = project.params if isinstance(project.params, dict) else {}
+ raw = params.get(key)
+ return str(raw) if raw else None
+
+
+def _asset_generation_status(asset: DramaAsset) -> str | None:
+ params = asset.params if isinstance(asset.params, dict) else {}
+ gen = params.get("generation")
+ if isinstance(gen, dict) and gen.get("status"):
+ return str(gen.get("status"))
+ return None
+
+
@router.get("/drama-projects", response_model=AdminDramaProjectListOut)
async def list_drama_projects(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
+ q: str | None = None,
+ user_id: int | None = None,
_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
) -> AdminDramaProjectListOut:
# Paginated drama projects joined with user email
owner = aliased(User)
- stmt = select(DramaProject, owner.email).outerjoin(owner, owner.id == DramaProject.user_id)
+ ep_count = (
+ select(func.count(DramaEpisode.id))
+ .where(DramaEpisode.project_id == DramaProject.id)
+ .correlate(DramaProject)
+ .scalar_subquery()
+ )
+ asset_count = (
+ select(func.count(DramaAsset.id))
+ .where(DramaAsset.project_id == DramaProject.id)
+ .correlate(DramaProject)
+ .scalar_subquery()
+ )
+ stmt = (
+ select(DramaProject, owner.email, ep_count, asset_count)
+ .outerjoin(owner, owner.id == DramaProject.user_id)
+ .options(selectinload(DramaProject.script))
+ )
count_stmt = select(func.count()).select_from(DramaProject)
+ if user_id is not None:
+ stmt = stmt.where(DramaProject.user_id == user_id)
+ count_stmt = count_stmt.where(DramaProject.user_id == user_id)
+ if q and q.strip():
+ like = f"%{q.strip()}%"
+ filt = or_(DramaProject.title.ilike(like), DramaProject.description.ilike(like))
+ stmt = stmt.where(filt)
+ count_stmt = count_stmt.where(filt)
+
total = int((await db.execute(count_stmt)).scalar_one() or 0)
rows = (
await db.execute(
@@ -53,12 +133,115 @@ async def list_drama_projects(
)
).all()
+ project_ids = [int(p.id) for p, _, _, _ in rows]
+ usage_map = await aggregate_usage_summary(db, drama_project_ids=project_ids)
+ assert isinstance(usage_map, dict)
+
items: list[AdminDramaProjectOut] = []
- for project, email in rows:
+ for project, email, ecount, acount in rows:
data = AdminDramaProjectOut.model_validate(project)
data.user_email = email
+ data.episode_count = int(ecount or 0)
+ data.asset_count = int(acount or 0)
+ data.charge_fen = int((usage_map.get(project.id) or {}).get("charge_fen") or 0)
+ data.summary_status = _script_status(project, "summary_status")
+ data.assets_seed_status = _project_param_status(project, "assets_seed_status")
items.append(data)
return AdminDramaProjectListOut(
items=items, meta=PageMeta(page=page, page_size=page_size, total=total)
)
+
+
[email protected]("/drama-projects/{project_id}", response_model=AdminDramaProjectDetailOut)
+async def get_drama_project(
+ project_id: int,
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminDramaProjectDetailOut:
+ owner = aliased(User)
+ row = (
+ await db.execute(
+ select(DramaProject, owner.email)
+ .outerjoin(owner, owner.id == DramaProject.user_id)
+ .where(DramaProject.id == project_id)
+ .options(
+ selectinload(DramaProject.script),
+ selectinload(DramaProject.episodes).selectinload(DramaEpisode.fragments),
+ selectinload(DramaProject.assets),
+ )
+ )
+ ).first()
+ if not row:
+ raise HTTPException(status_code=404, detail="漫剧项目不存在")
+ project, email = row
+
+ usage = await aggregate_usage_summary(db, drama_project_id=project_id)
+ assert isinstance(usage, dict)
+
+ episodes = sorted(project.episodes or [], key=lambda e: e.id)
+ assets = sorted(project.assets or [], key=lambda a: a.id)
+ fragment_count = sum(len(ep.fragments or []) for ep in episodes)
+
+ data = AdminDramaProjectDetailOut.model_validate(project)
+ data.user_email = email
+ data.episode_count = len(episodes)
+ data.asset_count = len(assets)
+ data.fragment_count = fragment_count
+ data.charge_fen = int(usage.get("charge_fen") or 0)
+ data.summary_status = _script_status(project, "summary_status")
+ data.episode_content_status = _script_status(project, "episode_content_status")
+ data.assets_seed_status = _project_param_status(project, "assets_seed_status")
+ data.usage = AdminProjectUsageOut(**usage)
+ data.episodes = [
+ AdminDramaEpisodeBriefOut(
+ id=ep.id,
+ name=ep.name or f"集 #{ep.id}",
+ fragment_count=len(ep.fragments or []),
+ fragment_plan_status=(
+ str((ep.params or {}).get("fragment_plan_status"))
+ if isinstance(ep.params, dict) and (ep.params or {}).get("fragment_plan_status")
+ else None
+ ),
+ )
+ for ep in episodes
+ ]
+ data.assets = [
+ AdminDramaAssetBriefOut(
+ id=a.id,
+ type=str(a.type or "none"),
+ name=a.name,
+ has_cover=bool(a.cover or a.url),
+ generation_status=_asset_generation_status(a),
+ )
+ for a in assets
+ ]
+
+ tasks = list(
+ (
+ await db.execute(
+ select(TaskRun)
+ .where(TaskRun.drama_project_id == project_id)
+ .order_by(TaskRun.id.desc())
+ .limit(20)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ data.recent_tasks = [
+ AdminTaskBriefOut(
+ id=t.id,
+ domain=str(t.domain or ""),
+ task_type=str(t.task_type or ""),
+ status=str(t.status or ""),
+ progress_percent=int(t.progress_percent or 0),
+ billing_charged_fen=int(t.billing_charged_fen or 0),
+ billing_estimate_fen=int(t.billing_estimate_fen or 0),
+ error_message=t.error_message,
+ created_at=t.created_at,
+ finished_at=t.finished_at,
+ )
+ for t in tasks
+ ]
+ return data
diff --git a/backend/app/api/admin/projects.py b/backend/app/api/admin/projects.py
index cb466e4..b8574e1 100644
--- a/backend/app/api/admin/projects.py
+++ b/backend/app/api/admin/projects.py
@@ -7,7 +7,17 @@ from sqlalchemy.orm import aliased
from app.database import get_db
from app.deps import get_current_admin
from app.models import Project, Shot, User
-from app.schemas import AdminProjectDetailOut, AdminProjectListOut, AdminProjectOut, PageMeta
+from app.models_tasks import TaskRun
+from app.schemas import (
+ AdminProjectDetailOut,
+ AdminProjectListOut,
+ AdminProjectOut,
+ AdminProjectUsageOut,
+ AdminShotBriefOut,
+ AdminTaskBriefOut,
+ PageMeta,
+)
+from app.services.admin.stats import aggregate_usage_summary
router = APIRouter()
@@ -49,11 +59,16 @@ async def list_projects(
)
).all()
+ project_ids = [int(project.id) for project, _, _ in rows]
+ usage_map = await aggregate_usage_summary(db, project_ids=project_ids)
+ assert isinstance(usage_map, dict)
+
items: list[AdminProjectOut] = []
for project, email, scount in rows:
data = AdminProjectOut.model_validate(project)
data.user_email = email
data.shot_count = int(scount or 0)
+ data.charge_fen = int((usage_map.get(project.id) or {}).get("charge_fen") or 0)
items.append(data)
return AdminProjectListOut(
@@ -85,4 +100,59 @@ async def get_project(
data = AdminProjectDetailOut.model_validate(project)
data.user_email = email
data.shot_count = int(scount or 0)
+
+ usage = await aggregate_usage_summary(db, project_id=project_id)
+ assert isinstance(usage, dict)
+ data.usage = AdminProjectUsageOut(**usage)
+ data.charge_fen = int(usage.get("charge_fen") or 0)
+
+ shots = list(
+ (
+ await db.execute(
+ select(Shot).where(Shot.project_id == project_id).order_by(Shot.shot_no.asc())
+ )
+ )
+ .scalars()
+ .all()
+ )
+ data.shots = [
+ AdminShotBriefOut(
+ id=s.id,
+ shot_no=int(s.shot_no or 0),
+ status=str(s.status or ""),
+ has_image=bool(s.image_url),
+ has_video=bool(s.video_url),
+ has_audio=bool(s.audio_url),
+ duration=float(s.duration or 0),
+ )
+ for s in shots
+ ]
+
+ tasks = list(
+ (
+ await db.execute(
+ select(TaskRun)
+ .where(TaskRun.project_id == project_id)
+ .order_by(TaskRun.id.desc())
+ .limit(20)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ data.recent_tasks = [
+ AdminTaskBriefOut(
+ id=t.id,
+ domain=str(t.domain or ""),
+ task_type=str(t.task_type or ""),
+ status=str(t.status or ""),
+ progress_percent=int(t.progress_percent or 0),
+ billing_charged_fen=int(t.billing_charged_fen or 0),
+ billing_estimate_fen=int(t.billing_estimate_fen or 0),
+ error_message=t.error_message,
+ created_at=t.created_at,
+ finished_at=t.finished_at,
+ )
+ for t in tasks
+ ]
return data
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index 828d855..99b69a9 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -266,11 +266,84 @@ class ProjectListOut(BaseModel):
stats: ProjectListStats
+class AdminUsageBucketOut(BaseModel):
+ """按 capability / domain 聚合桶。"""
+
+ key: str
+ calls: int = 0
+ charge_fen: int = 0
+
+
+class AdminDailyUsageOut(BaseModel):
+ date: str
+ calls: int = 0
+ charge_fen: int = 0
+
+
+class AdminTopUserOut(BaseModel):
+ user_id: int
+ email: str | None = None
+ calls: int = 0
+ charge_fen: int = 0
+
+
+class AdminProjectUsageOut(BaseModel):
+ """项目级用量摘要。"""
+
+ charge_fen: int = 0
+ cost_fen: int = 0
+ tokens: int = 0
+ calls: int = 0
+ image_gens: int = 0
+ video_gens: int = 0
+ llm_calls: int = 0
+ tts_gens: int = 0
+
+
+class AdminTaskBriefOut(BaseModel):
+ """关联任务简要行。"""
+
+ id: int
+ domain: str
+ task_type: str
+ status: str
+ progress_percent: int = 0
+ billing_charged_fen: int = 0
+ billing_estimate_fen: int = 0
+ error_message: str | None = None
+ created_at: datetime | None = None
+ finished_at: datetime | None = None
+
+
+class AdminShotBriefOut(BaseModel):
+ id: int
+ shot_no: int
+ status: str
+ has_image: bool = False
+ has_video: bool = False
+ has_audio: bool = False
+ duration: float = 0
+
+
class AdminStatsOut(BaseModel):
user_count: int
order_paid_total_fen: int
order_paid_today_fen: int
project_status_counts: dict[str, int]
+ drama_project_count: int = 0
+ usage_calls_today: int = 0
+ usage_calls_month: int = 0
+ usage_calls_total: int = 0
+ usage_charge_today_fen: int = 0
+ usage_charge_month_fen: int = 0
+ usage_charge_total_fen: int = 0
+ usage_cost_today_fen: int = 0
+ usage_cost_month_fen: int = 0
+ usage_cost_total_fen: int = 0
+ usage_by_capability: list[AdminUsageBucketOut] = Field(default_factory=list)
+ usage_by_domain: list[AdminUsageBucketOut] = Field(default_factory=list)
+ daily_usage: list[AdminDailyUsageOut] = Field(default_factory=list)
+ top_users_by_charge: list[AdminTopUserOut] = Field(default_factory=list)
class AdminQueueTaskOut(BaseModel):
@@ -399,6 +472,7 @@ class AdminProjectOut(BaseModel):
created_at: datetime
updated_at: datetime
shot_count: int = 0
+ charge_fen: int = 0
model_config = {"from_attributes": True}
@@ -414,6 +488,9 @@ class AdminProjectDetailOut(AdminProjectOut):
resolution_mode: str
output_ratio: str
voice_id: str
+ usage: AdminProjectUsageOut = Field(default_factory=AdminProjectUsageOut)
+ shots: list[AdminShotBriefOut] = Field(default_factory=list)
+ recent_tasks: list[AdminTaskBriefOut] = Field(default_factory=list)
class AdminWorkOut(BaseModel):
diff --git a/backend/app/services/admin/__init__.py b/backend/app/services/admin/__init__.py
new file mode 100644
index 0000000..0e9a5f1
--- /dev/null
+++ b/backend/app/services/admin/__init__.py
@@ -0,0 +1 @@
+"""管理端服务包。"""
diff --git a/backend/app/services/admin/stats.py b/backend/app/services/admin/stats.py
new file mode 100644
index 0000000..65f942a
--- /dev/null
+++ b/backend/app/services/admin/stats.py
@@ -0,0 +1,340 @@
+"""管理端统计聚合:仪表盘调用量/费用/排行。"""
+
+from __future__ import annotations
+
+from datetime import date, datetime, timedelta, timezone
+from typing import Any
+
+from sqlalchemy import Date, case, cast, func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import aliased
+
+from app.models import Order, Project, UsageEvent, User
+from app.models_drama import DramaProject
+
+
+def _utc_today_start() -> datetime:
+ return datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
+
+
+def _utc_month_start() -> datetime:
+ now = datetime.now(timezone.utc)
+ return now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+
+
+def _day_key(value: Any) -> str:
+ """把 DB 返回的 date/datetime/str 统一成 YYYY-MM-DD。"""
+ if isinstance(value, datetime):
+ return value.date().isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ text = str(value or "").strip()
+ return text[:10] if len(text) >= 10 else text
+
+
+async def _usage_day_expr(db: AsyncSession):
+ """
+ 按日历日分桶。
+ Postgres 用 CAST AS DATE;SQLite 用 date()(cast(Date) 会踩到结果处理器)。
+ """
+ conn = await db.connection()
+ if conn.dialect.name.startswith("postgres"):
+ return cast(UsageEvent.created_at, Date)
+ return func.date(UsageEvent.created_at)
+
+
+async def _usage_window_totals(
+ db: AsyncSession,
+ *,
+ since: datetime | None = None,
+) -> dict[str, int]:
+ """聚合 usage_events:calls / charge / cost。"""
+ filters = []
+ if since is not None:
+ filters.append(UsageEvent.created_at >= since)
+ stmt = select(
+ func.count(UsageEvent.id),
+ func.coalesce(func.sum(UsageEvent.charge_fen), 0),
+ func.coalesce(func.sum(UsageEvent.cost_fen), 0),
+ )
+ for clause in filters:
+ stmt = stmt.where(clause)
+ row = (await db.execute(stmt)).one()
+ return {
+ "calls": int(row[0] or 0),
+ "charge_fen": int(row[1] or 0),
+ "cost_fen": int(row[2] or 0),
+ }
+
+
+async def _group_usage(
+ db: AsyncSession,
+ *,
+ group_col,
+ since: datetime | None = None,
+ limit: int | None = None,
+) -> list[dict[str, Any]]:
+ """按某一列分组聚合 usage。"""
+ key = func.coalesce(group_col, "unknown")
+ stmt = (
+ select(
+ key.label("key"),
+ func.count(UsageEvent.id).label("calls"),
+ func.coalesce(func.sum(UsageEvent.charge_fen), 0).label("charge_fen"),
+ )
+ .group_by(key)
+ .order_by(func.coalesce(func.sum(UsageEvent.charge_fen), 0).desc())
+ )
+ if since is not None:
+ stmt = stmt.where(UsageEvent.created_at >= since)
+ if limit is not None:
+ stmt = stmt.limit(limit)
+ rows = (await db.execute(stmt)).all()
+ return [
+ {"key": str(r.key or "unknown"), "calls": int(r.calls or 0), "charge_fen": int(r.charge_fen or 0)}
+ for r in rows
+ ]
+
+
+async def build_admin_dashboard_stats(db: AsyncSession) -> dict[str, Any]:
+ """组装管理端仪表盘全部统计字段。"""
+ today = _utc_today_start()
+ month = _utc_month_start()
+ week_ago = today - timedelta(days=6)
+ month_ago = today - timedelta(days=29)
+
+ user_count = int((await db.execute(select(func.count()).select_from(User))).scalar_one() or 0)
+ drama_project_count = int(
+ (await db.execute(select(func.count()).select_from(DramaProject))).scalar_one() or 0
+ )
+
+ paid_total = int(
+ (
+ await db.execute(
+ select(func.coalesce(func.sum(Order.amount_fen), 0)).where(Order.status == "paid")
+ )
+ ).scalar_one()
+ or 0
+ )
+ paid_today = int(
+ (
+ await db.execute(
+ select(func.coalesce(func.sum(Order.amount_fen), 0)).where(
+ Order.status == "paid",
+ Order.paid_at.is_not(None),
+ Order.paid_at >= today,
+ )
+ )
+ ).scalar_one()
+ or 0
+ )
+
+ status_rows = (
+ await db.execute(select(Project.status, func.count()).group_by(Project.status))
+ ).all()
+ project_status_counts = {str(status): int(cnt) for status, cnt in status_rows}
+
+ total_u = await _usage_window_totals(db)
+ today_u = await _usage_window_totals(db, since=today)
+ month_u = await _usage_window_totals(db, since=month)
+
+ by_capability = await _group_usage(db, group_col=UsageEvent.capability, since=month)
+ by_domain = await _group_usage(db, group_col=UsageEvent.domain, since=month)
+
+ # 近 7 日按日趋势(方言安全的日分桶)
+ day_expr = await _usage_day_expr(db)
+ daily_rows = (
+ await db.execute(
+ select(
+ day_expr.label("day"),
+ func.count(UsageEvent.id).label("calls"),
+ func.coalesce(func.sum(UsageEvent.charge_fen), 0).label("charge_fen"),
+ )
+ .where(UsageEvent.created_at >= week_ago)
+ .group_by(day_expr)
+ .order_by(day_expr.asc())
+ )
+ ).all()
+ daily_map: dict[str, dict[str, int]] = {}
+ for r in daily_rows:
+ daily_map[_day_key(r.day)] = {
+ "calls": int(r.calls or 0),
+ "charge_fen": int(r.charge_fen or 0),
+ }
+ daily_usage: list[dict[str, Any]] = []
+ for i in range(7):
+ key = (week_ago + timedelta(days=i)).date().isoformat()
+ hit = daily_map.get(key) or {"calls": 0, "charge_fen": 0}
+ daily_usage.append({"date": key, "calls": hit["calls"], "charge_fen": hit["charge_fen"]})
+
+ # 近 30 日用户消费 Top10
+ owner = aliased(User)
+ top_rows = (
+ await db.execute(
+ select(
+ UsageEvent.user_id,
+ owner.email,
+ func.count(UsageEvent.id).label("calls"),
+ func.coalesce(func.sum(UsageEvent.charge_fen), 0).label("charge_fen"),
+ )
+ .outerjoin(owner, owner.id == UsageEvent.user_id)
+ .where(UsageEvent.created_at >= month_ago)
+ .group_by(UsageEvent.user_id, owner.email)
+ .order_by(func.coalesce(func.sum(UsageEvent.charge_fen), 0).desc())
+ .limit(10)
+ )
+ ).all()
+ top_users_by_charge = [
+ {
+ "user_id": int(r.user_id),
+ "email": r.email,
+ "calls": int(r.calls or 0),
+ "charge_fen": int(r.charge_fen or 0),
+ }
+ for r in top_rows
+ ]
+
+ return {
+ "user_count": user_count,
+ "order_paid_total_fen": paid_total,
+ "order_paid_today_fen": paid_today,
+ "project_status_counts": project_status_counts,
+ "drama_project_count": drama_project_count,
+ "usage_calls_today": today_u["calls"],
+ "usage_calls_month": month_u["calls"],
+ "usage_calls_total": total_u["calls"],
+ "usage_charge_today_fen": today_u["charge_fen"],
+ "usage_charge_month_fen": month_u["charge_fen"],
+ "usage_charge_total_fen": total_u["charge_fen"],
+ "usage_cost_today_fen": today_u["cost_fen"],
+ "usage_cost_month_fen": month_u["cost_fen"],
+ "usage_cost_total_fen": total_u["cost_fen"],
+ "usage_by_capability": by_capability,
+ "usage_by_domain": by_domain,
+ "daily_usage": daily_usage,
+ "top_users_by_charge": top_users_by_charge,
+ }
+
+
+def _usage_billing_cases():
+ """按 billing_key 拆分图/视/LLM/TTS 调用次数。"""
+ return (
+ case((UsageEvent.billing_key == "seedream", 1), else_=0),
+ case((UsageEvent.billing_key.like("seedance%"), 1), else_=0),
+ case((UsageEvent.billing_key == "llm_chat", 1), else_=0),
+ case((UsageEvent.billing_key == "tts", 1), else_=0),
+ )
+
+
+def _empty_usage_summary() -> dict[str, int]:
+ return {
+ "charge_fen": 0,
+ "cost_fen": 0,
+ "tokens": 0,
+ "calls": 0,
+ "image_gens": 0,
+ "video_gens": 0,
+ "llm_calls": 0,
+ "tts_gens": 0,
+ }
+
+
+def _row_to_usage_summary(row: Any) -> dict[str, int]:
+ return {
+ "charge_fen": int(row[0] or 0),
+ "cost_fen": int(row[1] or 0),
+ "tokens": int(row[2] or 0),
+ "calls": int(row[3] or 0),
+ "image_gens": int(row[4] or 0),
+ "video_gens": int(row[5] or 0),
+ "llm_calls": int(row[6] or 0),
+ "tts_gens": int(row[7] or 0),
+ }
+
+
+async def aggregate_usage_summary(
+ db: AsyncSession,
+ *,
+ project_id: int | None = None,
+ drama_project_id: int | None = None,
+ project_ids: list[int] | None = None,
+ drama_project_ids: list[int] | None = None,
+) -> dict[str, Any] | dict[int, dict[str, Any]]:
+ """
+ 项目级用量汇总。
+ - 单项目:传 project_id 或 drama_project_id,返回一条 dict
+ - 批量:传 project_ids 或 drama_project_ids,返回 {id: dict}
+ """
+ image_case, video_case, llm_case, tts_case = _usage_billing_cases()
+ empty = _empty_usage_summary()
+
+ if project_ids is not None:
+ if not project_ids:
+ return {}
+ result = await db.execute(
+ select(
+ UsageEvent.project_id,
+ func.coalesce(func.sum(UsageEvent.charge_fen), 0),
+ func.coalesce(func.sum(UsageEvent.cost_fen), 0),
+ func.coalesce(func.sum(UsageEvent.total_tokens), 0),
+ func.count(UsageEvent.id),
+ func.coalesce(func.sum(image_case), 0),
+ func.coalesce(func.sum(video_case), 0),
+ func.coalesce(func.sum(llm_case), 0),
+ func.coalesce(func.sum(tts_case), 0),
+ )
+ .where(UsageEvent.project_id.in_(project_ids))
+ .group_by(UsageEvent.project_id)
+ )
+ out: dict[int, dict[str, Any]] = {pid: dict(empty) for pid in project_ids}
+ for row in result.all():
+ pid = int(row[0])
+ out[pid] = _row_to_usage_summary(row[1:])
+ return out
+
+ if drama_project_ids is not None:
+ if not drama_project_ids:
+ return {}
+ result = await db.execute(
+ select(
+ UsageEvent.drama_project_id,
+ func.coalesce(func.sum(UsageEvent.charge_fen), 0),
+ func.coalesce(func.sum(UsageEvent.cost_fen), 0),
+ func.coalesce(func.sum(UsageEvent.total_tokens), 0),
+ func.count(UsageEvent.id),
+ func.coalesce(func.sum(image_case), 0),
+ func.coalesce(func.sum(video_case), 0),
+ func.coalesce(func.sum(llm_case), 0),
+ func.coalesce(func.sum(tts_case), 0),
+ )
+ .where(UsageEvent.drama_project_id.in_(drama_project_ids))
+ .group_by(UsageEvent.drama_project_id)
+ )
+ out_d: dict[int, dict[str, Any]] = {pid: dict(empty) for pid in drama_project_ids}
+ for row in result.all():
+ pid = int(row[0])
+ out_d[pid] = _row_to_usage_summary(row[1:])
+ return out_d
+
+ filters = []
+ if project_id is not None:
+ filters.append(UsageEvent.project_id == project_id)
+ elif drama_project_id is not None:
+ filters.append(UsageEvent.drama_project_id == drama_project_id)
+ else:
+ return dict(empty)
+
+ stmt = select(
+ func.coalesce(func.sum(UsageEvent.charge_fen), 0),
+ func.coalesce(func.sum(UsageEvent.cost_fen), 0),
+ func.coalesce(func.sum(UsageEvent.total_tokens), 0),
+ func.count(UsageEvent.id),
+ func.coalesce(func.sum(image_case), 0),
+ func.coalesce(func.sum(video_case), 0),
+ func.coalesce(func.sum(llm_case), 0),
+ func.coalesce(func.sum(tts_case), 0),
+ )
+ for clause in filters:
+ stmt = stmt.where(clause)
+ row = (await db.execute(stmt)).one()
+ return _row_to_usage_summary(row)
diff --git a/backend/tests/test_admin_stats.py b/backend/tests/test_admin_stats.py
new file mode 100644
index 0000000..e7e91a0
--- /dev/null
+++ b/backend/tests/test_admin_stats.py
@@ -0,0 +1,193 @@
+"""管理端仪表盘 / 项目用量聚合:日趋势、补零、Top10、能力分解。"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models import UsageEvent
+from app.services.admin.stats import aggregate_usage_summary, build_admin_dashboard_stats
+from tests.conftest import make_user
+
+
+def _utc_days_ago(days: int, *, hour: int = 12) -> datetime:
+ base = datetime.now(timezone.utc).replace(hour=hour, minute=0, second=0, microsecond=0)
+ return base - timedelta(days=days)
+
+
+async def _add_usage(
+ db: AsyncSession,
+ *,
+ user_id: int,
+ charge_fen: int,
+ cost_fen: int = 0,
+ created_at: datetime | None = None,
+ capability: str = "llm",
+ domain: str = "drama",
+ billing_key: str = "llm_chat",
+ project_id: int | None = None,
+ drama_project_id: int | None = None,
+ total_tokens: int = 100,
+) -> UsageEvent:
+ """写入一条用量事件。"""
+ ev = UsageEvent(
+ user_id=user_id,
+ project_id=project_id,
+ drama_project_id=drama_project_id,
+ domain=domain,
+ capability=capability,
+ billing_key=billing_key,
+ model="test-model",
+ prompt_tokens=total_tokens,
+ completion_tokens=0,
+ total_tokens=total_tokens,
+ charge_fen=charge_fen,
+ cost_fen=cost_fen,
+ estimated=False,
+ settled=True,
+ )
+ if created_at is not None:
+ ev.created_at = created_at
+ db.add(ev)
+ await db.flush()
+ return ev
+
+
+async def test_dashboard_daily_usage_pads_seven_days(db_session: AsyncSession) -> None:
+ """近 7 日趋势固定 7 行,无数据的日期补零。"""
+ user = await make_user(db_session)
+ await _add_usage(
+ db_session,
+ user_id=user.id,
+ charge_fen=50,
+ cost_fen=20,
+ created_at=_utc_days_ago(0),
+ capability="image",
+ billing_key="seedream",
+ )
+ await _add_usage(
+ db_session,
+ user_id=user.id,
+ charge_fen=30,
+ created_at=_utc_days_ago(2),
+ capability="video",
+ billing_key="seedance2:video0",
+ domain="kepu",
+ )
+ await db_session.commit()
+
+ stats = await build_admin_dashboard_stats(db_session)
+ daily = stats["daily_usage"]
+ assert len(daily) == 7
+ assert all("date" in d and "calls" in d and "charge_fen" in d for d in daily)
+ # 日期升序且连续
+ dates = [d["date"] for d in daily]
+ assert dates == sorted(dates)
+ today_key = _utc_days_ago(0).date().isoformat()
+ two_ago = _utc_days_ago(2).date().isoformat()
+ by_day = {d["date"]: d for d in daily}
+ assert by_day[today_key]["calls"] == 1
+ assert by_day[today_key]["charge_fen"] == 50
+ assert by_day[two_ago]["calls"] == 1
+ assert by_day[two_ago]["charge_fen"] == 30
+ empty_days = [d for d in daily if d["date"] not in {today_key, two_ago}]
+ assert all(d["calls"] == 0 and d["charge_fen"] == 0 for d in empty_days)
+
+ assert stats["usage_calls_total"] == 2
+ assert stats["usage_charge_total_fen"] == 80
+ assert stats["usage_cost_total_fen"] == 20
+ assert stats["usage_calls_today"] == 1
+ assert stats["usage_charge_today_fen"] == 50
+
+
+async def test_dashboard_top_users_by_charge(db_session: AsyncSession) -> None:
+ """近 30 日按扣费排序,最多 10 人。"""
+ high = await make_user(db_session)
+ low = await make_user(db_session)
+ await _add_usage(db_session, user_id=high.id, charge_fen=900, created_at=_utc_days_ago(1))
+ await _add_usage(db_session, user_id=high.id, charge_fen=100, created_at=_utc_days_ago(5))
+ await _add_usage(db_session, user_id=low.id, charge_fen=10, created_at=_utc_days_ago(1))
+ await db_session.commit()
+
+ stats = await build_admin_dashboard_stats(db_session)
+ top = stats["top_users_by_charge"]
+ assert len(top) >= 2
+ assert top[0]["user_id"] == high.id
+ assert top[0]["charge_fen"] == 1000
+ assert top[0]["calls"] == 2
+ assert top[0]["email"] == high.email
+ assert top[1]["user_id"] == low.id
+ assert top[1]["charge_fen"] == 10
+
+
+async def test_aggregate_usage_summary_breakdown(db_session: AsyncSession) -> None:
+ """单项目用量拆分图/视/LLM/TTS。"""
+ user = await make_user(db_session)
+ pid = 42
+ await _add_usage(
+ db_session, user_id=user.id, project_id=pid, charge_fen=10, billing_key="seedream", capability="image"
+ )
+ await _add_usage(
+ db_session,
+ user_id=user.id,
+ project_id=pid,
+ charge_fen=20,
+ billing_key="seedance2:video0",
+ capability="video",
+ )
+ await _add_usage(
+ db_session, user_id=user.id, project_id=pid, charge_fen=5, billing_key="llm_chat", capability="llm"
+ )
+ await _add_usage(
+ db_session, user_id=user.id, project_id=pid, charge_fen=3, billing_key="tts", capability="tts"
+ )
+ # 其他项目不应计入
+ await _add_usage(
+ db_session, user_id=user.id, project_id=99, charge_fen=999, billing_key="seedream", capability="image"
+ )
+ await db_session.commit()
+
+ summary = await aggregate_usage_summary(db_session, project_id=pid)
+ assert summary["calls"] == 4
+ assert summary["charge_fen"] == 38
+ assert summary["image_gens"] == 1
+ assert summary["video_gens"] == 1
+ assert summary["llm_calls"] == 1
+ assert summary["tts_gens"] == 1
+
+ batch = await aggregate_usage_summary(db_session, project_ids=[pid, 99, 7])
+ assert batch[pid]["tts_gens"] == 1
+ assert batch[99]["image_gens"] == 1
+ assert batch[99]["charge_fen"] == 999
+ assert batch[7]["calls"] == 0
+ assert batch[7]["tts_gens"] == 0
+
+
+async def test_aggregate_drama_project_usage(db_session: AsyncSession) -> None:
+ """漫剧项目按 drama_project_id 聚合。"""
+ user = await make_user(db_session)
+ did = 7
+ await _add_usage(
+ db_session,
+ user_id=user.id,
+ drama_project_id=did,
+ charge_fen=15,
+ cost_fen=8,
+ billing_key="tts",
+ capability="tts",
+ total_tokens=50,
+ )
+ await db_session.commit()
+
+ summary = await aggregate_usage_summary(db_session, drama_project_id=did)
+ assert summary["calls"] == 1
+ assert summary["charge_fen"] == 15
+ assert summary["cost_fen"] == 8
+ assert summary["tokens"] == 50
+ assert summary["tts_gens"] == 1