PRINTFILM: AI short-video marketing and AI short-drama creation platform
refactor(billing): extract TaskRun freeze/settle into billing package
yie24c1f0b84a1
diff --git a/backend/app/api/billing.py b/backend/app/api/billing.pyindex 62645cb..7aa0971 100644--- a/backend/app/api/billing.py+++ b/backend/app/api/billing.py@@ -19,7 +19,13 @@ from app.config import get_settingsfrom app.database import get_dbfrom app.deps import get_current_userfrom app.models import Order, Project, UsageEvent, User+from app.models_tasks import TaskRunfrom app.services import billing, epay+from app.services.billing.http import http_exception_for_value_error+from app.services.billing.settlement import (+ billing_active,+ ensure_balance_for_task_batch,+)logger = logging.getLogger(__name__)router = APIRouter(prefix="/billing", tags=["billing"])@@ -54,6 +60,54 @@ async def list_skus() -> dict:}[email protected]("/preflight")+async def billing_preflight(+ domain: str = Query(..., min_length=1),+ task_type: str = Query(..., min_length=1),+ count: int = Query(1, ge=1, le=500),+ db: AsyncSession = Depends(get_db),+ user: User = Depends(get_current_user),+) -> dict:+ """入队前余额预检:返回单项估算与批量总需求。"""+ if not billing_active(user):+ return {+ "ok": True,+ "billing_enabled": False,+ "balance_fen": int(user.balance_fen or 0),+ "unit_estimate_fen": 0,+ "pending_commitment_fen": 0,+ "requested_total_fen": 0,+ "required_total_fen": 0,+ }+ probe = TaskRun(+ domain=domain.strip(),+ task_type=task_type.strip(),+ requested_by=user.id,+ payload={},+ )+ try:+ summary = await ensure_balance_for_task_batch(db, user, probe, count)+ except ValueError as exc:+ raise http_exception_for_value_error(exc) from exc+ return {+ "ok": True,+ "billing_enabled": True,+ "balance_fen": summary["balance_fen"],+ "balance_yuan": round(summary["balance_fen"] / 100, 2),+ "unit_estimate_fen": summary["unit_estimate_fen"],+ "unit_estimate_yuan": round(summary["unit_estimate_fen"] / 100, 2),+ "pending_commitment_fen": summary["pending_commitment_fen"],+ "pending_commitment_yuan": round(summary["pending_commitment_fen"] / 100, 2),+ "requested_total_fen": summary["requested_total_fen"],+ "requested_total_yuan": round(summary["requested_total_fen"] / 100, 2),+ "required_total_fen": summary["required_total_fen"],+ "required_total_yuan": round(summary["required_total_fen"] / 100, 2),+ "count": int(count),+ "domain": domain.strip(),+ "task_type": task_type.strip(),+ }++def _client_ip(request: Request) -> str:"""Prefer proxy headers, fall back to direct peer address."""forwarded = (request.headers.get("x-forwarded-for") or "").split(",")[0].strip()diff --git a/backend/app/api/tasks.py b/backend/app/api/tasks.pyindex b139638..9bb98f6 100644--- a/backend/app/api/tasks.py+++ b/backend/app/api/tasks.py@@ -11,6 +11,7 @@ from app.database import get_dbfrom app.deps import get_current_userfrom app.models import Userfrom app.schemas_tasks import MockDelayTaskRequest, TaskCreateRequest, TaskListOut, TaskRunOut+from app.services.billing.http import http_exception_for_value_errorfrom app.services.tasks.service import (cancel_task_for_user,count_active_tasks_for_user,@@ -59,7 +60,7 @@ async def create_mock_delay_task(),)except ValueError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc+ raise http_exception_for_value_error(exc) from excreturn TaskRunOut.model_validate(task)@@ -125,7 +126,7 @@ async def cancel_task_run(except LookupError as exc:raise HTTPException(status_code=404, detail="任务不存在") from excexcept ValueError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc+ raise http_exception_for_value_error(exc) from excreturn TaskRunOut.model_validate(task)diff --git a/backend/app/api/tools.py b/backend/app/api/tools.pyindex 588194e..d970a67 100644--- a/backend/app/api/tools.py+++ b/backend/app/api/tools.py@@ -12,6 +12,7 @@ from app.database import get_dbfrom app.deps import get_current_userfrom app.models import ToolRun, Userfrom app.schemas_tools import ToolRunListOut, ToolRunOut, ToolRunRecordOut, ToolTaskOut+from app.services.billing import run_billed_ephemeral_deferred, settle_deferred_video_pollfrom app.services.studio_tools import (enqueue_image_tool,get_tool_run,@@ -66,36 +67,54 @@ async def run_tool(raise ValueError("单个文件不能超过 40MB")saved.append(save_upload(user.id, raw, item.filename or "upload.bin"))if tid in IMAGE_TOOLS:- data = await enqueue_image_tool(- db,- user,- tool_id=tid,- prompt=prompt,- negative=negative,- ratio=ratio or None,- strength=strength or None,- mode=mode or None,- pack=pack or None,- files=saved,- params=tool_params,- )+ try:+ data = await enqueue_image_tool(+ db,+ user,+ tool_id=tid,+ prompt=prompt,+ negative=negative,+ ratio=ratio or None,+ strength=strength or None,+ mode=mode or None,+ pack=pack or None,+ files=saved,+ params=tool_params,+ )+ except ValueError as exc:+ raise HTTPException(status_code=402, detail=str(exc)) from excelif tid in VIDEO_TOOLS:- data = await start_video_tool(- db,- user,- tool_id=tid,- prompt=prompt,- ratio=ratio or None,- duration_raw=duration or None,- motion=motion or None,- files=saved,- )+ async def _exec_video() -> dict:+ return await start_video_tool(+ db,+ user,+ tool_id=tid,+ prompt=prompt,+ ratio=ratio or None,+ duration_raw=duration or None,+ motion=motion or None,+ files=saved,+ )++ try:+ billing_task, data = await run_billed_ephemeral_deferred(+ db,+ user,+ domain="studio",+ task_type="tool_video",+ executor=_exec_video,+ payload=tool_params,+ commit=False,+ )+ except ValueError as exc:+ raise HTTPException(status_code=402, detail=str(exc)) from exc+ data = {**data, "billing_task_id": billing_task.id}await persist_tool_run(db,user_id=user.id,tool_id=tid,prompt=prompt,- params=tool_params,+ params={**tool_params, "billing_task_id": billing_task.id},data=data,)else:@@ -123,10 +142,26 @@ async def get_tool_task(select(ToolRun).where(ToolRun.user_id == user.id, ToolRun.task_id == tid).limit(1))).scalar_one_or_none()+ billing_task_id: int | None = None+ if row and isinstance(row.params, dict):+ raw_bid = row.params.get("billing_task_id")+ if raw_bid is not None:+ try:+ billing_task_id = int(raw_bid)+ except (TypeError, ValueError):+ billing_task_id = Noneif row and row.kind == "image":data = await poll_image_tool_task(db, user, tid)else:data = await poll_video_task(user, tid)+ await settle_deferred_video_poll(+ db,+ user,+ provider_task_id=tid,+ poll_status=str(data.get("status") or ""),+ error=str(data.get("error") or "") or None,+ billing_task_id=billing_task_id,+ )await update_tool_run_task(db, user.id, tid, data)await db.commit()return ToolTaskOut.model_validate(data)diff --git a/backend/app/api/v1/generation.py b/backend/app/api/v1/generation.pyindex d4869eb..e935f4e 100644--- a/backend/app/api/v1/generation.py+++ b/backend/app/api/v1/generation.py@@ -15,7 +15,13 @@ from app.schemas_api import (V1SeedanceTaskRequest,V1VideoGenerateRequest,)-from app.services.billing import record_usage, settle_usage_charge+from app.services.ark import get_ark+from app.services.billing import (+ record_line,+ run_billed_ephemeral,+ run_billed_ephemeral_deferred,+ settle_deferred_video_poll,+)from app.services.studio_tools import poll_video_task, ratio_to_sizefrom app.services import storage@@ -42,44 +48,60 @@ async def generate_image(user: User = Depends(_resolve_api_user),) -> V1GenerationOut:"""文生图 / 图生图(Seedream)。"""- ark = get_ark()- refs: list[str] | None = None- prompt = body.prompt.strip()- if body.image_url:- refs = [body.image_url.strip()]- prompt = f"{prompt}。在保持主体可识别的前提下适度改变风格"- size = ratio_to_size(body.ratio)- try:- result = await ark.gen_image(- prompt,- body.negative,- refs,- project_id=0,- shot_no=user.id,- size=size,++ async def _exec() -> str:+ ark = get_ark()+ refs: list[str] | None = None+ prompt = body.prompt.strip()+ if body.image_url:+ refs = [body.image_url.strip()]+ prompt = f"{prompt}。在保持主体可识别的前提下适度改变风格"+ size = ratio_to_size(body.ratio)+ try:+ result = await ark.gen_image(+ prompt,+ body.negative,+ refs,+ project_id=0,+ shot_no=user.id,+ size=size,+ )+ except Exception as exc: # noqa: BLE001+ raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc++ await record_line(+ db,+ user_id=user.id,+ billing_key="seedream",+ model=get_settings().model_image,+ estimated=True,+ domain="api",+ raw={"source": "api_v1_image"},)- except Exception as exc: # noqa: BLE001- raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc+ url = result.local_url or result.remote_url or ""+ if url:+ url = storage.republish_url(url, sync=True) or url+ return url- ev = await record_usage(- db,- user_id=user.id,- project_id=None,- billing_key="seedream",- model=get_settings().model_image,- estimated=True,- raw={"source": "api_v1_image"},- )try:- await settle_usage_charge(db, user, int(ev.charge_fen or 0), ref_type="api", ref_id=f"img:{ev.id}")+ task, url = await run_billed_ephemeral(+ db,+ user,+ domain="api",+ task_type="v1_image",+ executor=_exec,+ payload={"prompt_len": len(body.prompt or "")},+ commit=True,+ )except ValueError as exc:raise HTTPException(status_code=402, detail=str(exc)) from exc- url = result.local_url or result.remote_url or ""- if url:- url = storage.republish_url(url, sync=True) or url- await db.commit()- return V1GenerationOut(status="succeeded", kind="image", urls=[url] if url else [])+ return V1GenerationOut(+ status="succeeded",+ kind="image",+ urls=[url] if url else [],+ task_id=str(task.id),+ )@router.post("/videos/generations", response_model=V1GenerationOut)@@ -89,37 +111,39 @@ async def generate_video(user: User = Depends(_resolve_api_user),) -> V1GenerationOut:"""首帧图 + 文案 → Seedance 图生视频,返回 task_id。"""- ark = get_ark()- try:- task_id = await ark.gen_video_i2v(- body.image_url.strip(),- body.prompt.strip(),- body.duration,- resolution=body.resolution,- generate_audio=body.generate_audio,- )- except Exception as exc: # noqa: BLE001- raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc- ev = await record_usage(- db,- user_id=user.id,- project_id=None,- billing_key="seedance2:video0",- model=get_settings().model_video,- estimated=True,- raw={"source": "api_v1_video", "duration": body.duration},- )+ async def _exec() -> str:+ ark = get_ark()+ try:+ upstream_id = await ark.gen_video_i2v(+ body.image_url.strip(),+ body.prompt.strip(),+ body.duration,+ resolution=body.resolution,+ generate_audio=body.generate_audio,+ )+ except Exception as exc: # noqa: BLE001+ raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc++ return upstream_id+try:- await settle_usage_charge(db, user, int(ev.charge_fen or 0), ref_type="api", ref_id=f"vid:{ev.id}")+ task, upstream_id = await run_billed_ephemeral_deferred(+ db,+ user,+ domain="api",+ task_type="v1_video",+ executor=_exec,+ payload={"duration": body.duration},+ commit=True,+ )except ValueError as exc:raise HTTPException(status_code=402, detail=str(exc)) from exc- await db.commit()return V1GenerationOut(status="queued",kind="video",- task_id=task_id,+ task_id=upstream_id,preview_url=body.image_url,urls=[],)@@ -148,28 +172,29 @@ async def forward_seedance(if body.ratio:payload["ratio"] = body.ratio- ark = get_ark()- try:- task_id = await ark.gen_video_seedance_body(payload, project_id=0)- except Exception as exc: # noqa: BLE001- raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc+ async def _exec() -> str:+ ark = get_ark()+ try:+ upstream_id = await ark.gen_video_seedance_body(payload, project_id=0)+ except Exception as exc: # noqa: BLE001+ raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc++ return upstream_id- ev = await record_usage(- db,- user_id=user.id,- project_id=None,- billing_key="seedance2:video0",- model=settings.model_video,- estimated=True,- raw={"source": "api_v1_seedance"},- )try:- await settle_usage_charge(db, user, int(ev.charge_fen or 0), ref_type="api", ref_id=f"sd:{ev.id}")+ task, upstream_id = await run_billed_ephemeral_deferred(+ db,+ user,+ domain="api",+ task_type="v1_seedance",+ executor=_exec,+ payload={"duration": body.duration},+ commit=True,+ )except ValueError as exc:raise HTTPException(status_code=402, detail=str(exc)) from exc- await db.commit()- return V1GenerationOut(status="queued", kind="video", task_id=task_id, urls=[])+ return V1GenerationOut(status="queued", kind="video", task_id=upstream_id, urls=[])@router.get("/tasks/{task_id}", response_model=V1GenerationOut)@@ -181,7 +206,15 @@ async def get_task("""查询 Seedance 视频任务状态。"""if not task_id.strip():raise HTTPException(status_code=400, detail="缺少 task_id")- data = await poll_video_task(user, task_id.strip())+ tid = task_id.strip()+ data = await poll_video_task(user, tid)+ await settle_deferred_video_poll(+ db,+ user,+ provider_task_id=tid,+ poll_status=str(data.get("status") or ""),+ error=str(data.get("error") or "") or None,+ )await db.commit()return V1GenerationOut(status=str(data.get("status") or "running"),diff --git a/backend/app/main.py b/backend/app/main.pyindex 61140af..c42d651 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -219,6 +219,12 @@ async def _migrate_sqlite() -> None:uecols = {row[0] for row in result.fetchall()}if "drama_project_id" not in uecols:await conn.execute(text("ALTER TABLE usage_events ADD COLUMN drama_project_id INTEGER"))+ if "task_run_id" not in uecols:+ await conn.execute(text("ALTER TABLE usage_events ADD COLUMN task_run_id INTEGER"))+ if "domain" not in uecols:+ await conn.execute(text("ALTER TABLE usage_events ADD COLUMN domain VARCHAR(32)"))+ if "capability" not in uecols:+ await conn.execute(text("ALTER TABLE usage_events ADD COLUMN capability VARCHAR(16)"))# Task platform additive columnsif is_sqlite:@@ -272,6 +278,14 @@ async def _migrate_sqlite() -> None:await conn.execute(text("ALTER TABLE task_runs ADD COLUMN lease_token VARCHAR(64)"))if "lease_until" not in trcols:await conn.execute(text("ALTER TABLE task_runs ADD COLUMN lease_until DATETIME"))+ if "billing_estimate_fen" not in trcols:+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN billing_estimate_fen INTEGER DEFAULT 0"))+ if "billing_charged_fen" not in trcols:+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN billing_charged_fen INTEGER DEFAULT 0"))+ if "billing_refunded_fen" not in trcols:+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN billing_refunded_fen INTEGER DEFAULT 0"))+ if "billing_status" not in trcols:+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN billing_status VARCHAR(16) DEFAULT 'none'"))# Drop leftover worker-era columns that block the new task platform.legacy_task_run_cols = (diff --git a/backend/app/models.py b/backend/app/models.pyindex a671457..1aeaa46 100644--- a/backend/app/models.py+++ b/backend/app/models.py@@ -187,6 +187,9 @@ class UsageEvent(Base):)# Drama module billing ref (mutually exclusive with kepu project_id when set)drama_project_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)+ task_run_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)+ domain: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True)+ capability: Mapped[str | None] = mapped_column(String(16), nullable=True, index=True)shot_id: Mapped[int | None] = mapped_column(Integer, nullable=True)provider: Mapped[str] = mapped_column(String(32), default="ark")billing_key: Mapped[str] = mapped_column(String(64), index=True)diff --git a/backend/app/models_tasks.py b/backend/app/models_tasks.pyindex d0fbd61..0dfe8f6 100644--- a/backend/app/models_tasks.py+++ b/backend/app/models_tasks.py@@ -59,6 +59,10 @@ class TaskRun(Base):)started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ billing_estimate_fen: Mapped[int] = mapped_column(Integer, default=0)+ billing_charged_fen: Mapped[int] = mapped_column(Integer, default=0)+ billing_refunded_fen: Mapped[int] = mapped_column(Integer, default=0)+ billing_status: Mapped[str] = mapped_column(String(16), default="none", index=True)targets: Mapped[list["TaskTarget"]] = relationship(back_populates="task", cascade="all, delete-orphan"diff --git a/backend/app/schemas_tasks.py b/backend/app/schemas_tasks.pyindex 1a99567..d1d11f3 100644--- a/backend/app/schemas_tasks.py+++ b/backend/app/schemas_tasks.py@@ -22,7 +22,7 @@ class TaskTargetBind(BaseModel):class TaskCreateRequest(BaseModel):"""Create a platform task run."""- domain: str = Field(default="drama", description="drama | kepu | tools")+ domain: str = Field(default="drama", description="drama | kepu | tools | api | studio")task_type: str = Field(min_length=1, max_length=64)priority: int = Field(default=100, ge=0, le=1000)client_request_id: str | None = Field(default=None, max_length=128)@@ -196,6 +196,10 @@ class TaskRunOut(BaseModel):updated_at: datetime | None = Nonestarted_at: datetime | None = Nonefinished_at: datetime | None = None+ billing_estimate_fen: int = 0+ billing_charged_fen: int = 0+ billing_refunded_fen: int = 0+ billing_status: str = "none"steps: list[TaskStepOut] = Field(default_factory=list)targets: list[TaskTargetOut] = Field(default_factory=list)events: list[TaskEventOut] = Field(default_factory=list)@@ -226,6 +230,50 @@ class AdminTaskRunOut(TaskRunOut):"""Admin task view with requester email."""user_email: str | None = None+ usage_lines: list["AdminUsageEventBriefOut"] = Field(default_factory=list)+++class AdminUsageEventBriefOut(BaseModel):+ """Compact usage line for task billing tab."""++ id: int+ billing_key: str+ capability: str | None = None+ model: str = ""+ total_tokens: int = 0+ charge_fen: int = 0+ estimated: bool = False+ created_at: datetime | None = None++ model_config = {"from_attributes": True}+++class AdminUsageEventOut(BaseModel):+ """Admin usage event list row."""++ id: int+ user_id: int+ user_email: str | None = None+ task_run_id: int | None = None+ domain: str | None = None+ capability: str | None = None+ billing_key: str+ model: str = ""+ total_tokens: int = 0+ charge_fen: int = 0+ cost_fen: int = 0+ estimated: bool = False+ created_at: datetime | None = None+ task_domain: str | None = None+ task_type: str | None = None+ task_status: str | None = None+++class AdminUsageEventListOut(BaseModel):+ """Paginated admin usage events."""++ items: list[AdminUsageEventOut] = Field(default_factory=list)+ meta: PageMetaclass AdminTaskListOut(BaseModel):diff --git a/backend/app/services/billing.py b/backend/app/services/billing.pydeleted file mode 100644index b24cb37..0000000--- a/backend/app/services/billing.py+++ /dev/null@@ -1,386 +0,0 @@-# -*- coding: utf-8 -*--"""Token-based billing: estimate, freeze, record usage, settle."""-from __future__ import annotations--import json-import logging-import math-from typing import Any--from sqlalchemy import select-from sqlalchemy.ext.asyncio import AsyncSession--from app.config import Settings, get_settings-from app.models import Project, UsageEvent, User, WalletLedger--logger = logging.getLogger(__name__)--SKUS: list[dict[str, Any]] = [- {"id": "topup_10", "name": "体验充值", "amount_fen": 10000, "credit_fen": 10000},- {"id": "topup_49", "name": "基础充值", "amount_fen": 49000, "credit_fen": 49000},- {"id": "topup_99", "name": "进阶充值", "amount_fen": 99000, "credit_fen": 104000, "recommended": True},- {"id": "topup_199", "name": "专业充值", "amount_fen": 199000, "credit_fen": 220000},-]---def provider_yuan_per_m(billing_key: str, settings: Settings | None = None) -> float:- s = settings or get_settings()- table = {- "seedance2:video0": s.billing_seedance_video0,- "seedance2:video1": s.billing_seedance_video1,- "llm_chat": s.billing_llm_per_m,- "seedream": s.billing_seedream_per_m,- "tts": s.billing_tts_per_m,- }- return float(table.get(billing_key, s.billing_llm_per_m))---def charge_fen_for_tokens(- tokens: int,- billing_key: str,- *,- settings: Settings | None = None,-) -> tuple[int, int]:- """Return (cost_fen, charge_fen) with markup."""- s = settings or get_settings()- t = max(0, int(tokens))- yuan_per_m = provider_yuan_per_m(billing_key, s)- cost = math.ceil(t / 1_000_000 * yuan_per_m * 100) if t else 0- charge = math.ceil(cost * float(s.billing_markup)) if cost else 0- if t > 0 and charge < 1:- charge = 1- cost = max(cost, 1)- return cost, charge---def parse_usage_dict(data: dict[str, Any] | None) -> dict[str, int]:- if not data:- return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}- usage = data.get("usage") if isinstance(data.get("usage"), dict) else data- if not isinstance(usage, dict):- return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}- prompt = int(usage.get("prompt_tokens") or usage.get("input_tokens") or 0)- completion = int(- usage.get("completion_tokens")- or usage.get("output_tokens")- or usage.get("generated_tokens")- or 0- )- total = int(usage.get("total_tokens") or (prompt + completion) or 0)- return {"prompt_tokens": prompt, "completion_tokens": completion, "total_tokens": total}---def billing_active(user: User | None = None, settings: Settings | None = None) -> bool:- s = settings or get_settings()- if not s.billing_enabled:- return False- if user is not None and getattr(user, "billing_unlimited", False):- return False- return True---def estimate_phase_fen(project: Project, phase: str, settings: Settings | None = None) -> int:- """phase: script | produce"""- s = settings or get_settings()- buf = float(s.billing_estimate_buffer or 1.2)- if phase == "script":- cost, charge = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)- return max(1, math.ceil(charge * buf))-- shots = list(project.shots or [])- n = max(len(shots), 1)- total = 0- # images + tts- for _ in range(n):- _, c_img = charge_fen_for_tokens(s.billing_est_seedream_tokens, "seedream", settings=s)- _, c_tts = charge_fen_for_tokens(s.billing_est_tts_tokens, "tts", settings=s)- total += c_img + c_tts- if (project.pipeline_mode or "full") != "image_text":- secs = sum(max(float(sh.duration or 4), 2.0) for sh in shots) or (n * 5.0)- tok = int(secs * s.billing_est_seedance_tokens_per_sec)- _, c_vid = charge_fen_for_tokens(tok, "seedance2:video0", settings=s)- total += c_vid- # compose negligible — 1 fen min bump- total = max(total, 1)- return math.ceil(total * buf)---async def _ledger(- db: AsyncSession,- user: User,- delta_fen: int,- kind: str,- *,- ref_type: str = "",- ref_id: str = "",- note: str = "",-) -> None:- user.balance_fen = int(user.balance_fen or 0) + int(delta_fen)- db.add(- WalletLedger(- user_id=user.id,- delta_fen=int(delta_fen),- balance_after=int(user.balance_fen),- kind=kind,- ref_type=ref_type,- ref_id=ref_id,- note=note[:255],- )- )---async def freeze_for_project(- db: AsyncSession,- user: User,- project: Project,- phase: str,-) -> int:- """Freeze estimate; raise ValueError if insufficient."""- if not billing_active(user):- return 0- need = estimate_phase_fen(project, phase)- available = int(user.balance_fen or 0)- if available < need:- raise ValueError(f"余额不足:需要 ¥{need/100:.2f},当前 ¥{available/100:.2f},请先充值")- user.balance_fen = available - need- user.frozen_fen = int(user.frozen_fen or 0) + need- db.add(- WalletLedger(- user_id=user.id,- delta_fen=-need,- balance_after=int(user.balance_fen),- kind="freeze",- ref_type="project",- ref_id=str(project.id),- note=f"freeze:{phase}",- )- )- await db.flush()- return need---async def record_usage(- db: AsyncSession,- *,- user_id: int,- project_id: int | None,- billing_key: str,- model: str = "",- tokens: int = 0,- prompt_tokens: int = 0,- completion_tokens: int = 0,- estimated: bool = False,- raw: dict | None = None,- shot_id: int | None = None,- provider: str = "ark",- drama_project_id: int | None = None,-) -> UsageEvent:- s = get_settings()- total = int(tokens) or (int(prompt_tokens) + int(completion_tokens))- if total <= 0:- # fallbacks by key- if billing_key == "llm_chat":- total = s.billing_est_llm_tokens- estimated = True- elif billing_key == "seedream":- total = s.billing_est_seedream_tokens- estimated = True- elif billing_key == "tts":- total = s.billing_est_tts_tokens- estimated = True- elif billing_key.startswith("seedance"):- total = s.billing_est_seedance_tokens_per_sec * 5- estimated = True- cost, charge = charge_fen_for_tokens(total, billing_key, settings=s)- ev = UsageEvent(- user_id=user_id,- project_id=project_id,- drama_project_id=drama_project_id,- shot_id=shot_id,- provider=provider,- billing_key=billing_key,- model=model or "",- prompt_tokens=int(prompt_tokens),- completion_tokens=int(completion_tokens),- total_tokens=total,- cost_fen=cost,- charge_fen=charge,- estimated=estimated,- settled=False,- raw_usage_json=json.dumps(raw, ensure_ascii=False)[:4000] if raw else None,- )- db.add(ev)- await db.flush()- return ev---async def settle_project(db: AsyncSession, project_id: int) -> dict[str, int]:- """Apply unsettled usage: consume freeze first, refund unused freeze."""- project = await db.get(Project, project_id)- if not project:- return {"charged": 0, "refunded": 0}- user = await db.get(User, project.user_id)- result = await db.execute(- select(UsageEvent).where(- UsageEvent.project_id == project_id,- UsageEvent.settled.is_(False),- )- )- events = list(result.scalars().all())- charged = sum(int(e.charge_fen or 0) for e in events)- for e in events:- e.settled = True-- if not user or not billing_active(user):- await db.flush()- return {"charged": 0, "refunded": 0}-- frozen_before = int(user.frozen_fen or 0)- from_freeze = min(frozen_before, charged)- extra = charged - from_freeze- refund = max(0, frozen_before - charged)- user.frozen_fen = 0-- if extra > 0:- logger.warning(- "settle overage user=%s project=%s extra_fen=%s balance=%s",- user.id,- project_id,- extra,- user.balance_fen,- )- await _ledger(- db,- user,- -extra,- "settle",- ref_type="project",- ref_id=str(project_id),- note="settle_overage",- )- if refund > 0:- await _ledger(- db,- user,- refund,- "unfreeze",- ref_type="project",- ref_id=str(project_id),- note="refund_unused_freeze",- )-- db.add(- WalletLedger(- user_id=user.id,- delta_fen=0,- balance_after=int(user.balance_fen or 0),- kind="settle",- ref_type="project",- ref_id=str(project_id),- note=f"charged={charged} freeze={from_freeze} refund={refund}",- )- )- await db.flush()- return {"charged": charged, "refunded": refund}---async def credit_topup(- db: AsyncSession,- user: User,- credit_fen: int,- *,- ref_type: str,- ref_id: str,- note: str = "",-) -> None:- await _ledger(db, user, int(credit_fen), "topup", ref_type=ref_type, ref_id=ref_id, note=note)- await db.flush()---def sku_by_id(sku_id: str) -> dict[str, Any] | None:- for s in SKUS:- if s["id"] == sku_id:- return s- return None---# 待支付订单有效期(秒),与前端扫码倒计时一致-ORDER_EXPIRE_SECONDS = 300---async def close_expired_pending_orders(- db: AsyncSession,- *,- user_id: int | None = None,- out_trade_no: str | None = None,-) -> int:- """将超时未支付的 pending 订单自动标为 closed,返回关闭条数。"""- from datetime import datetime, timedelta, timezone-- from app.models import Order-- now = datetime.now(timezone.utc)- stmt = select(Order).where(Order.status == "pending")- if user_id is not None:- stmt = stmt.where(Order.user_id == user_id)- if out_trade_no is not None:- stmt = stmt.where(Order.out_trade_no == out_trade_no)- rows = (await db.execute(stmt)).scalars().all()- closed = 0- for order in rows:- created = order.created_at- if created is None:- continue- if created.tzinfo is None:- created = created.replace(tzinfo=timezone.utc)- age = (now - created).total_seconds()- if age < ORDER_EXPIRE_SECONDS:- continue- order.status = "closed"- closed += 1- if closed:- await db.commit()- return closed---async def settle_usage_charge(- db: AsyncSession,- user: User,- charge_fen: int,- *,- ref_type: str = "api",- ref_id: str = "",-) -> None:- """API 等即时扣费:余额不足时抛 ValueError。"""- if not billing_active(user):- return- need = max(0, int(charge_fen))- if need <= 0:- return- available = int(user.balance_fen or 0)- if available < need:- raise ValueError(f"余额不足:需要 ¥{need / 100:.2f},当前 ¥{available / 100:.2f},请先充值")- await _ledger(- db,- user,- -need,- "settle",- ref_type=ref_type,- ref_id=ref_id,- note="api_usage",- )- await db.flush()---def billing_key_label(billing_key: str) -> str:- """把 billing_key 转成用户可读的能力名称。"""- key = (billing_key or "").strip().lower()- if key == "llm_chat":- return "LLM 对话"- if key == "seedream":- return "图片生成"- if key.startswith("seedance"):- return "视频生成"- if key == "tts":- return "语音合成"- return billing_key or "其他"diff --git a/backend/app/services/billing/__init__.py b/backend/app/services/billing/__init__.pynew file mode 100644index 0000000..c9f14d5--- /dev/null+++ b/backend/app/services/billing/__init__.py@@ -0,0 +1,74 @@+# -*- coding: utf-8 -*-+"""统一任务计费:预扣 → 记录用量 → 任务结束结算。"""+from __future__ import annotations++from app.services.billing.context import billing_scope, get_current_task_run_id, set_current_task_run_id+from app.services.billing.ephemeral import (+ create_ephemeral_task_row,+ run_billed_ephemeral,+ run_billed_ephemeral_deferred,+ run_with_registered_handler,+ settle_deferred_video_poll,+)+from app.services.billing.estimates import estimate_phase_fen, estimate_task_fen+from app.services.billing.pricing import (+ ORDER_EXPIRE_SECONDS,+ SKUS,+ billing_key_label,+ billing_key_to_capability,+ charge_fen_for_tokens,+ parse_usage_dict,+ provider_yuan_per_m,+ sku_by_id,+)+from app.services.billing.settlement import (+ billing_active,+ close_expired_pending_orders,+ credit_topup,+ ensure_balance_for_task,+ ensure_balance_for_task_batch,+ freeze_for_task,+ get_task_billing_summary,+ get_task_usage_lines,+ pending_task_commitment_fen,+ settle_project,+ settle_task,+ settle_usage_charge,+)+from app.services.billing.usage import record_line, record_llm_chat_line, record_usage++__all__ = [+ "ORDER_EXPIRE_SECONDS",+ "SKUS",+ "billing_active",+ "billing_key_label",+ "billing_key_to_capability",+ "billing_scope",+ "charge_fen_for_tokens",+ "close_expired_pending_orders",+ "create_ephemeral_task_row",+ "credit_topup",+ "estimate_phase_fen",+ "estimate_task_fen",+ "ensure_balance_for_task",+ "ensure_balance_for_task_batch",+ "freeze_for_task",+ "get_current_task_run_id",+ "get_task_billing_summary",+ "get_task_usage_lines",+ "parse_usage_dict",+ "pending_task_commitment_fen",+ "provider_yuan_per_m",+ "record_line",+ "record_llm_chat_line",+ "record_usage",+ "run_billed_ephemeral",+ "run_billed_ephemeral_deferred",+ "run_with_registered_handler",+ "settle_deferred_video_poll",+ "set_current_task_run_id",+ "settle_project",+ "settle_task",+ "settle_usage_charge",+ "sku_by_id",+]diff --git a/backend/app/services/billing/context.py b/backend/app/services/billing/context.pynew file mode 100644index 0000000..a125b94--- /dev/null+++ b/backend/app/services/billing/context.py@@ -0,0 +1,26 @@+# -*- coding: utf-8 -*-+"""任务计费上下文:当前 task_run_id。"""+from __future__ import annotations++from contextlib import asynccontextmanager+from contextvars import ContextVar+from typing import AsyncIterator++_current_task_run_id: ContextVar[int | None] = ContextVar("billing_task_run_id", default=None)+++def get_current_task_run_id() -> int | None:+ return _current_task_run_id.get()+++def set_current_task_run_id(task_run_id: int | None) -> None:+ _current_task_run_id.set(task_run_id)+++@asynccontextmanager+async def billing_scope(task_run_id: int | None) -> AsyncIterator[None]:+ token = _current_task_run_id.set(task_run_id)+ try:+ yield+ finally:+ _current_task_run_id.reset(token)diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.pynew file mode 100644index 0000000..a3eb043--- /dev/null+++ b/backend/app/services/billing/ephemeral.py@@ -0,0 +1,389 @@+# -*- coding: utf-8 -*-+"""轻量 TaskRun:同步执行并计费(聊天、API、工具)。"""+from __future__ import annotations++from collections.abc import Awaitable, Callable+from datetime import UTC, datetime+from typing import Any, TypeVar++from sqlalchemy.ext.asyncio import AsyncSession++from app.models import User+from app.models_tasks import TaskRun+from app.schemas_tasks import TaskCreateRequest, TaskEventCreate, TaskStepCreate+from sqlalchemy import select++from app.config import get_settings+from app.services.billing.context import billing_scope+from app.services.billing.settlement import freeze_for_task, settle_task+from app.services.billing.usage import record_line+from app.services.tasks.executor import execute_task_run+from app.services.tasks.handlers import get_task_handler+from app.services.tasks.service import append_task_event, build_task_event, build_task_step++T = TypeVar("T")+++async def create_ephemeral_task_row(+ db: AsyncSession,+ user: User,+ *,+ domain: str,+ task_type: str,+ payload: dict | None = None,+ project_id: int | None = None,+ drama_project_id: int | None = None,+ shot_id: int | None = None,+ fragment_id: int | None = None,+ asset_id: int | None = None,+ episode_id: int | None = None,+) -> TaskRun:+ """创建并立即执行的轻量任务行(不经过调度器排队)。"""+ handler = get_task_handler(domain, task_type)+ planned = handler.plan_steps(TaskCreateRequest(domain=domain, task_type=task_type)) if handler else []+ first = planned[0] if planned else None+ now = datetime.now(UTC)+ task = TaskRun(+ domain=domain,+ task_type=task_type,+ status="pending",+ priority=1,+ requested_by=user.id,+ cancelable=False,+ current_step_key=first.step_key if first else task_type,+ current_step_status="pending" if first else None,+ scheduled_at=now,+ next_action_at=now,+ payload=payload or {},+ project_id=project_id,+ drama_project_id=drama_project_id,+ shot_id=shot_id,+ fragment_id=fragment_id,+ asset_id=asset_id,+ episode_id=episode_id,+ )+ db.add(task)+ await db.flush()+ if first:+ db.add(build_task_step(task.id, first))+ db.add(+ build_task_event(+ task.id,+ TaskEventCreate(+ event_type="task.created",+ status=task.status,+ phase=task.current_step_key,+ message=f"轻量任务 {task_type}",+ payload={"ephemeral": True},+ ),+ )+ )+ await db.flush()+ return task+++async def run_billed_ephemeral(+ db: AsyncSession,+ user: User,+ *,+ domain: str,+ task_type: str,+ executor: Callable[[], Awaitable[T]],+ payload: dict | None = None,+ project_id: int | None = None,+ drama_project_id: int | None = None,+ shot_id: int | None = None,+ fragment_id: int | None = None,+ asset_id: int | None = None,+ episode_id: int | None = None,+ commit: bool = True,+) -> tuple[TaskRun, T]:+ """+ 创建轻量 TaskRun → 预扣 → 在 billing_scope 内执行 → 结算。+ 用于聊天、开放 API、工作室工具等同步调用。+ """+ task = await create_ephemeral_task_row(+ db,+ user,+ domain=domain,+ task_type=task_type,+ payload=payload,+ project_id=project_id,+ drama_project_id=drama_project_id,+ shot_id=shot_id,+ fragment_id=fragment_id,+ asset_id=asset_id,+ episode_id=episode_id,+ )+ try:+ await freeze_for_task(db, task)+ except ValueError:+ task.status = "failed"+ task.error_code = "insufficient_balance"+ task.error_message = "余额不足"+ # 未预扣成功,保持 none,勿标 skipped(skipped 表示无限额跳过扣费)+ task.billing_status = "none"+ await db.flush()+ raise++ now = datetime.now(UTC)+ task.status = "running"+ task.started_at = now+ await append_task_event(+ db,+ task.id,+ event_type="task.started",+ status=task.status,+ message="轻量任务开始",+ )+ await db.flush()++ result: T+ try:+ async with billing_scope(task.id):+ result = await executor()+ task.status = "succeeded"+ task.progress_percent = 100+ task.finished_at = datetime.now(UTC)+ task.result_payload = {"ok": True} if result is None else {"ok": True, "result": str(type(result))}+ await append_task_event(+ db,+ task.id,+ event_type="task.completed",+ status=task.status,+ message="轻量任务完成",+ )+ except Exception as exc:+ task.status = "failed"+ task.error_code = "ephemeral_failed"+ task.error_message = str(exc)[:500]+ task.finished_at = datetime.now(UTC)+ await append_task_event(+ db,+ task.id,+ event_type="task.failed",+ status=task.status,+ message=str(exc)[:200],+ )+ await settle_task(db, task.id)+ if commit:+ await db.commit()+ raise++ await settle_task(db, task.id)+ if commit:+ await db.commit()+ await db.refresh(task)+ return task, result+++def _extract_provider_task_id(result: Any) -> str:+ """从 executor 返回值解析上游 task_id。"""+ if isinstance(result, dict):+ raw = result.get("task_id") or result.get("provider_task_id") or ""+ return str(raw).strip()+ return str(result).strip()+++async def run_billed_ephemeral_deferred(+ db: AsyncSession,+ user: User,+ *,+ domain: str,+ task_type: str,+ executor: Callable[[], Awaitable[T]],+ payload: dict | None = None,+ project_id: int | None = None,+ drama_project_id: int | None = None,+ shot_id: int | None = None,+ fragment_id: int | None = None,+ asset_id: int | None = None,+ episode_id: int | None = None,+ commit: bool = True,+) -> tuple[TaskRun, T]:+ """+ 轻量 TaskRun:预扣 → 提交上游异步任务 → 保持 awaiting_poll,轮询终态后再结算。+ 用于开放 API / 工作室生视频,避免提交成功即扣费。+ """+ task = await create_ephemeral_task_row(+ db,+ user,+ domain=domain,+ task_type=task_type,+ payload=payload,+ project_id=project_id,+ drama_project_id=drama_project_id,+ shot_id=shot_id,+ fragment_id=fragment_id,+ asset_id=asset_id,+ episode_id=episode_id,+ )+ try:+ await freeze_for_task(db, task)+ except ValueError:+ task.status = "failed"+ task.error_code = "insufficient_balance"+ task.error_message = "余额不足"+ task.billing_status = "none"+ await db.flush()+ raise++ now = datetime.now(UTC)+ task.status = "running"+ task.started_at = now+ await append_task_event(+ db,+ task.id,+ event_type="task.started",+ status=task.status,+ message="轻量视频任务开始",+ )+ await db.flush()++ result: T+ try:+ async with billing_scope(task.id):+ result = await executor()+ provider_id = _extract_provider_task_id(result)+ if not provider_id:+ raise RuntimeError("上游未返回 task_id")+ task.status = "awaiting_poll"+ task.provider_task_id = provider_id+ task.progress_percent = 30+ task.next_action_at = now+ task.result_payload = {"awaiting_poll": True, "provider_task_id": provider_id}+ await append_task_event(+ db,+ task.id,+ event_type="task.submitted",+ status=task.status,+ message="已提交上游,等待轮询",+ payload={"provider_task_id": provider_id},+ )+ except Exception as exc:+ task.status = "failed"+ task.error_code = "ephemeral_failed"+ task.error_message = str(exc)[:500]+ task.finished_at = datetime.now(UTC)+ await append_task_event(+ db,+ task.id,+ event_type="task.failed",+ status=task.status,+ message=str(exc)[:200],+ )+ await settle_task(db, task.id)+ if commit:+ await db.commit()+ raise++ if commit:+ await db.commit()+ await db.refresh(task)+ return task, result+++async def settle_deferred_video_poll(+ db: AsyncSession,+ user: User,+ *,+ provider_task_id: str,+ poll_status: str,+ error: str | None = None,+ billing_task_id: int | None = None,+) -> None:+ """轮询终态后结算轻量视频任务:成功才记 seedance 用量。++ 用行锁 + billing_status==frozen 门闩,避免客户端轮询与后台 poller 并发双记用量。+ """+ from app.services.billing.settlement import _lock_task++ terminal = (poll_status or "").strip().lower()+ if terminal in {"", "running", "queued"}:+ return++ task_id: int | None = None+ if billing_task_id:+ probe = await db.get(TaskRun, billing_task_id)+ if probe and int(probe.requested_by) == int(user.id):+ task_id = int(probe.id)+ if task_id is None and provider_task_id.strip():+ stmt = (+ select(TaskRun.id)+ .where(+ TaskRun.requested_by == user.id,+ TaskRun.provider_task_id == provider_task_id.strip(),+ TaskRun.billing_status == "frozen",+ )+ .order_by(TaskRun.id.desc())+ .limit(1)+ )+ task_id = (await db.execute(stmt)).scalar_one_or_none()+ if task_id is None:+ return++ # 原子门闩:仅 frozen 任务可进入结算;并发第二次拿到 settled 后直接返回+ task = await _lock_task(db, task_id)+ if not task or task.billing_status != "frozen":+ return+ if int(task.requested_by) != int(user.id):+ return++ now = datetime.now(UTC)+ if terminal == "succeeded":+ payload = task.payload if isinstance(task.payload, dict) else {}+ async with billing_scope(task.id):+ await record_line(+ db,+ user_id=user.id,+ billing_key="seedance2:video0",+ model=get_settings().model_video,+ estimated=True,+ domain=task.domain,+ raw={+ "source": f"deferred_poll:{task.task_type}",+ "duration": payload.get("duration"),+ },+ )+ task.status = "succeeded"+ task.progress_percent = 100+ task.finished_at = now+ task.error_code = None+ task.error_message = None+ await append_task_event(+ db,+ task.id,+ event_type="task.completed",+ status=task.status,+ message="视频生成完成",+ )+ else:+ task.status = "failed"+ task.error_code = "upstream_failed"+ task.error_message = (error or "生成失败")[:500]+ task.finished_at = now+ await append_task_event(+ db,+ task.id,+ event_type="task.failed",+ status=task.status,+ message=task.error_message,+ )++ await settle_task(db, task.id)+++async def run_with_registered_handler(+ db: AsyncSession,+ user: User,+ body: TaskCreateRequest,+ *,+ commit: bool = True,+) -> TaskRun:+ """创建任务并同步执行已注册 handler(跳过后台调度器)。"""+ from app.services.tasks.service import create_task++ task = await create_task(db, user, body, commit=commit)+ await execute_task_run(task.id)+ refreshed = await db.get(TaskRun, task.id)+ return refreshed or taskdiff --git a/backend/app/services/billing/estimates.py b/backend/app/services/billing/estimates.pynew file mode 100644index 0000000..3a51524--- /dev/null+++ b/backend/app/services/billing/estimates.py@@ -0,0 +1,119 @@+# -*- coding: utf-8 -*-+"""按 TaskRun 估算预扣金额。"""+from __future__ import annotations++import math++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import selectinload++from app.config import Settings, get_settings+from app.models import Project+from app.models_tasks import TaskRun+from app.services.billing.pricing import charge_fen_for_tokens+++def estimate_phase_fen(project: Project, phase: str, settings: Settings | None = None) -> int:+ """科普 pipeline 阶段估算:script | produce。"""+ s = settings or get_settings()+ buf = float(s.billing_estimate_buffer or 1.2)+ if phase == "script":+ _, charge = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)+ return max(1, math.ceil(charge * buf))++ shots = list(project.shots or [])+ n = max(len(shots), 1)+ total = 0+ for _ in range(n):+ _, c_img = charge_fen_for_tokens(s.billing_est_seedream_tokens, "seedream", settings=s)+ _, c_tts = charge_fen_for_tokens(s.billing_est_tts_tokens, "tts", settings=s)+ total += c_img + c_tts+ if (project.pipeline_mode or "full") != "image_text":+ secs = sum(max(float(sh.duration or 4), 2.0) for sh in shots) or (n * 5.0)+ tok = int(secs * s.billing_est_seedance_tokens_per_sec)+ _, c_vid = charge_fen_for_tokens(tok, "seedance2:video0", settings=s)+ total += c_vid+ return max(math.ceil(total * buf), 1)+++async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings | None = None) -> int:+ """按 domain + task_type 估算单任务预扣(分)。"""+ s = settings or get_settings()+ buf = float(s.billing_estimate_buffer or 1.2)+ domain = (task.domain or "").strip()+ task_type = (task.task_type or "").strip()+ payload = task.payload if isinstance(task.payload, dict) else {}++ if domain == "kepu" and task_type == "project_pipeline":+ project_id = task.project_id or payload.get("project_id")+ if not project_id:+ _, charge = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)+ return max(1, math.ceil(charge * buf))+ result = await db.execute(+ select(Project).where(Project.id == int(project_id)).options(selectinload(Project.shots))+ )+ project = result.scalar_one_or_none()+ if not project:+ _, charge = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)+ return max(1, math.ceil(charge * buf))+ phase = str(payload.get("phase") or "script")+ return estimate_phase_fen(project, phase, settings=s)++ if domain == "kepu":+ if task_type in {"shot_regen_image"}:+ _, c = charge_fen_for_tokens(s.billing_est_seedream_tokens, "seedream", settings=s)+ return max(1, math.ceil(c * buf))+ if task_type in {"shot_regen_video"}:+ dur = float(payload.get("duration") or 5)+ tok = int(max(dur, 2.0) * s.billing_est_seedance_tokens_per_sec)+ _, c = charge_fen_for_tokens(tok, "seedance2:video0", settings=s)+ return max(1, math.ceil(c * buf))+ if task_type in {"shot_regen_audio", "project_regen_audio"}:+ _, c = charge_fen_for_tokens(s.billing_est_tts_tokens * 3, "tts", settings=s)+ return max(1, math.ceil(c * buf))+ if task_type == "project_compose_only":+ return 1++ if domain == "drama":+ if task_type in {"script_summary", "fragment_plan", "agent_chat"}:+ _, c = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)+ return max(1, math.ceil(c * buf))+ if task_type == "episode_script":+ total_eps = int(payload.get("total") or payload.get("episode_count") or 1)+ _, c = charge_fen_for_tokens(s.billing_est_llm_tokens * max(total_eps, 1), "llm_chat", settings=s)+ return max(1, math.ceil(c * buf))+ if task_type in {"asset_image", "seed_assets"}:+ if task_type == "seed_assets":+ _, c = charge_fen_for_tokens(s.billing_est_llm_tokens * 3, "llm_chat", settings=s)+ return max(1, math.ceil(c * buf))+ _, c = charge_fen_for_tokens(s.billing_est_seedream_tokens, "seedream", settings=s)+ return max(1, math.ceil(c * buf))+ if task_type in {"asset_video", "fragment_video"}:+ dur = float(payload.get("duration_sec") or payload.get("duration") or 8)+ tok = int(max(dur, 2.0) * s.billing_est_seedance_tokens_per_sec)+ _, c = charge_fen_for_tokens(tok, "seedance2:video0", settings=s)+ return max(1, math.ceil(c * buf))+ if task_type == "voice_synthesis":+ _, c = charge_fen_for_tokens(s.billing_est_tts_tokens, "tts", settings=s)+ return max(1, math.ceil(c * buf))+ if task_type in {"skill_optimize", "voice_prompt"}:+ _, c = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)+ return max(1, math.ceil(c * buf))++ if domain == "kepu" and task_type == "content_expand":+ _, c = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)+ return max(1, math.ceil(c * buf))++ if domain in {"api", "studio"}:+ if task_type in {"v1_image", "tool_image"}:+ _, c = charge_fen_for_tokens(s.billing_est_seedream_tokens, "seedream", settings=s)+ return max(1, math.ceil(c * buf))+ if task_type in {"v1_video", "v1_seedance", "tool_video"}:+ dur = float(payload.get("duration") or 5)+ tok = int(max(dur, 2.0) * s.billing_est_seedance_tokens_per_sec)+ _, c = charge_fen_for_tokens(tok, "seedance2:video0", settings=s)+ return max(1, math.ceil(c * buf))++ _, c = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)+ return max(1, math.ceil(c * buf))diff --git a/backend/app/services/billing/http.py b/backend/app/services/billing/http.pynew file mode 100644index 0000000..431a19f--- /dev/null+++ b/backend/app/services/billing/http.py@@ -0,0 +1,12 @@+# -*- coding: utf-8 -*-+"""计费相关 HTTP 异常映射。"""+from __future__ import annotations++from fastapi import HTTPException+++def http_exception_for_value_error(exc: ValueError) -> HTTPException:+ """余额不足 → 402,其余 ValueError → 400。"""+ detail = str(exc)+ status = 402 if detail.startswith("余额不足") else 400+ return HTTPException(status_code=status, detail=detail)diff --git a/backend/app/services/billing/pricing.py b/backend/app/services/billing/pricing.pynew file mode 100644index 0000000..fbafd54--- /dev/null+++ b/backend/app/services/billing/pricing.py@@ -0,0 +1,90 @@+# -*- coding: utf-8 -*-+"""Token 单价与费用换算。"""+from __future__ import annotations++import math+from typing import Any++from app.config import Settings, get_settings++SKUS: list[dict[str, Any]] = [+ {"id": "topup_10", "name": "体验充值", "amount_fen": 10000, "credit_fen": 10000},+ {"id": "topup_49", "name": "基础充值", "amount_fen": 49000, "credit_fen": 49000},+ {"id": "topup_99", "name": "进阶充值", "amount_fen": 99000, "credit_fen": 104000, "recommended": True},+ {"id": "topup_199", "name": "专业充值", "amount_fen": 199000, "credit_fen": 220000},+]++ORDER_EXPIRE_SECONDS = 300+++def provider_yuan_per_m(billing_key: str, settings: Settings | None = None) -> float:+ s = settings or get_settings()+ table = {+ "seedance2:video0": s.billing_seedance_video0,+ "seedance2:video1": s.billing_seedance_video1,+ "llm_chat": s.billing_llm_per_m,+ "seedream": s.billing_seedream_per_m,+ "tts": s.billing_tts_per_m,+ }+ return float(table.get(billing_key, s.billing_llm_per_m))+++def charge_fen_for_tokens(+ tokens: int,+ billing_key: str,+ *,+ settings: Settings | None = None,+) -> tuple[int, int]:+ """Return (cost_fen, charge_fen) with markup."""+ s = settings or get_settings()+ t = max(0, int(tokens))+ yuan_per_m = provider_yuan_per_m(billing_key, s)+ cost = math.ceil(t / 1_000_000 * yuan_per_m * 100) if t else 0+ charge = math.ceil(cost * float(s.billing_markup)) if cost else 0+ if t > 0 and charge < 1:+ charge = 1+ cost = max(cost, 1)+ return cost, charge+++def parse_usage_dict(data: dict[str, Any] | None) -> dict[str, int]:+ if not data:+ return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}+ usage = data.get("usage") if isinstance(data.get("usage"), dict) else data+ if not isinstance(usage, dict):+ return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}+ prompt = int(usage.get("prompt_tokens") or usage.get("input_tokens") or 0)+ completion = int(+ usage.get("completion_tokens")+ or usage.get("output_tokens")+ or usage.get("generated_tokens")+ or 0+ )+ total = int(usage.get("total_tokens") or (prompt + completion) or 0)+ return {"prompt_tokens": prompt, "completion_tokens": completion, "total_tokens": total}+++def billing_key_to_capability(billing_key: str) -> str:+ key = (billing_key or "").strip().lower()+ if key == "llm_chat":+ return "llm"+ if key == "seedream":+ return "image"+ if key.startswith("seedance"):+ return "video"+ if key == "tts":+ return "tts"+ return "other"+++def billing_key_label(billing_key: str) -> str:+ cap = billing_key_to_capability(billing_key)+ labels = {"llm": "LLM 对话", "image": "图片生成", "video": "视频生成", "tts": "语音合成"}+ return labels.get(cap, billing_key or "其他")+++def sku_by_id(sku_id: str) -> dict[str, Any] | None:+ for item in SKUS:+ if item["id"] == sku_id:+ return item+ return Nonediff --git a/backend/app/services/billing/settlement.py b/backend/app/services/billing/settlement.pynew file mode 100644index 0000000..fddc4af--- /dev/null+++ b/backend/app/services/billing/settlement.py@@ -0,0 +1,464 @@+# -*- coding: utf-8 -*-+"""任务级预扣与结算。"""+from __future__ import annotations++import logging+from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.config import Settings, get_settings+from app.models import UsageEvent, User, WalletLedger+from app.models_tasks import TaskRun+from app.services.billing.estimates import estimate_task_fen++logger = logging.getLogger(__name__)++# 仍占用余额承诺、尚未预扣冻结的进行中任务+_PENDING_BILLING_TASK_STATUSES = frozenset(+ {+ "pending",+ "leased",+ "running",+ "awaiting_poll",+ "awaiting_review",+ "cancel_requested",+ }+)+++def billing_active(user: User | None = None, settings: Settings | None = None) -> bool:+ s = settings or get_settings()+ if not s.billing_enabled:+ return False+ if user is not None and getattr(user, "billing_unlimited", False):+ return False+ return True+++async def _ledger(+ db: AsyncSession,+ user: User,+ delta_fen: int,+ kind: str,+ *,+ ref_type: str = "",+ ref_id: str = "",+ note: str = "",+) -> None:+ user.balance_fen = int(user.balance_fen or 0) + int(delta_fen)+ db.add(+ WalletLedger(+ user_id=user.id,+ delta_fen=int(delta_fen),+ balance_after=int(user.balance_fen),+ kind=kind,+ ref_type=ref_type,+ ref_id=ref_id,+ note=note[:255],+ )+ )+++async def _lock_user(db: AsyncSession, user_id: int) -> User | None:+ """行锁用户钱包,避免并发预扣/结算透支。"""+ return (+ await db.execute(select(User).where(User.id == int(user_id)).with_for_update())+ ).scalar_one_or_none()+++async def _lock_task(db: AsyncSession, task_id: int) -> TaskRun | None:+ """行锁 TaskRun,保证结算/预扣幂等。"""+ return (+ await db.execute(select(TaskRun).where(TaskRun.id == int(task_id)).with_for_update())+ ).scalar_one_or_none()+++async def pending_task_commitment_fen(+ db: AsyncSession,+ user_id: int,+ *,+ exclude_task_id: int | None = None,+) -> int:+ """汇总用户进行中、尚未预扣冻结的任务估算占用(分)。"""+ stmt = select(TaskRun).where(+ TaskRun.requested_by == int(user_id),+ TaskRun.billing_status == "none",+ TaskRun.status.in_(_PENDING_BILLING_TASK_STATUSES),+ )+ if exclude_task_id is not None:+ stmt = stmt.where(TaskRun.id != int(exclude_task_id))+ rows = list((await db.execute(stmt)).scalars().all())+ total = 0+ for row in rows:+ est = int(row.billing_estimate_fen or 0)+ if est <= 0:+ est = await estimate_task_fen(db, row)+ total += est+ return total+++async def ensure_balance_for_task(db: AsyncSession, user: User, task: TaskRun) -> int:+ """入队前同步校验余额(含排队中未冻结估算),不足抛 ValueError;返回本任务估算分。"""+ if not billing_active(user):+ return 0+ locked = await _lock_user(db, int(user.id))+ if locked is None:+ raise ValueError("用户不存在")+ # 同步调用方持有的 user 对象余额+ user.balance_fen = int(locked.balance_fen or 0)+ user.frozen_fen = int(locked.frozen_fen or 0)+ need = await estimate_task_fen(db, task)+ pending = await pending_task_commitment_fen(db, int(user.id))+ available = int(locked.balance_fen or 0)+ required = pending + need+ if available < required:+ if pending > 0:+ raise ValueError(+ f"余额不足:本次需要 ¥{need/100:.2f}(含排队中 ¥{pending/100:.2f}),"+ f"当前 ¥{available/100:.2f},请先充值"+ )+ raise ValueError(f"余额不足:需要 ¥{need/100:.2f},当前 ¥{available/100:.2f},请先充值")+ return need+++async def ensure_balance_for_task_batch(+ db: AsyncSession,+ user: User,+ task: TaskRun,+ count: int,+) -> dict[str, int]:+ """批量入队前校验:pending + unit*count。不足抛 ValueError。"""+ if not billing_active(user):+ return {"unit_estimate_fen": 0, "required_total_fen": 0}+ qty = max(1, int(count))+ locked = await _lock_user(db, int(user.id))+ if locked is None:+ raise ValueError("用户不存在")+ user.balance_fen = int(locked.balance_fen or 0)+ user.frozen_fen = int(locked.frozen_fen or 0)+ unit = await estimate_task_fen(db, task)+ pending = await pending_task_commitment_fen(db, int(user.id))+ additional = unit * qty+ required = pending + additional+ available = int(locked.balance_fen or 0)+ if available < required:+ raise ValueError(+ f"余额不足:批量生成 {qty} 项需 ¥{additional/100:.2f}"+ f"(含排队中 ¥{pending/100:.2f}),当前 ¥{available/100:.2f},请先充值"+ )+ return {+ "unit_estimate_fen": unit,+ "pending_commitment_fen": pending,+ "requested_total_fen": additional,+ "required_total_fen": required,+ "balance_fen": available,+ }+++async def freeze_for_task(db: AsyncSession, task: TaskRun) -> int:+ """任务开始前预扣估算;余额不足抛 ValueError。已 frozen 时幂等返回原估算。"""+ locked_task = await _lock_task(db, int(task.id))+ if not locked_task:+ return 0+ # 回写到调用方持有的 task 引用+ if locked_task is not task:+ task.billing_status = locked_task.billing_status+ task.billing_estimate_fen = locked_task.billing_estimate_fen+ if task.billing_status == "frozen":+ return int(task.billing_estimate_fen or 0)++ user = await _lock_user(db, int(task.requested_by))+ if not user or not billing_active(user):+ task.billing_status = "skipped"+ task.billing_estimate_fen = 0+ await db.flush()+ return 0+ need = await estimate_task_fen(db, task)+ available = int(user.balance_fen or 0)+ if available < need:+ raise ValueError(f"余额不足:需要 ¥{need/100:.2f},当前 ¥{available/100:.2f},请先充值")+ # 仅通过 _ledger 扣余额,避免双重扣款+ user.frozen_fen = int(user.frozen_fen or 0) + need+ task.billing_estimate_fen = need+ task.billing_status = "frozen"+ await _ledger(+ db,+ user,+ -need,+ "freeze",+ ref_type="task_run",+ ref_id=str(task.id),+ note=f"freeze:{task.domain}/{task.task_type}",+ )+ await db.flush()+ return need+++async def settle_task(db: AsyncSession, task_id: int) -> dict[str, int]:+ """任务结束时按 usage_events 结算,多退少补冻结额。"""+ task = await _lock_task(db, task_id)+ if not task:+ return {"charged": 0, "refunded": 0}+ if task.billing_status == "settled":+ return {+ "charged": int(task.billing_charged_fen or 0),+ "refunded": int(task.billing_refunded_fen or 0),+ }++ result = await db.execute(+ select(UsageEvent).where(+ UsageEvent.task_run_id == task_id,+ UsageEvent.settled.is_(False),+ )+ )+ events = list(result.scalars().all())+ if task.billing_status == "skipped" and not events:+ # 无限额且无用量:结算完成,统一标 settled 便于管理端展示+ task.billing_status = "settled"+ task.billing_charged_fen = int(task.billing_charged_fen or 0)+ await db.flush()+ return {+ "charged": int(task.billing_charged_fen or 0),+ "refunded": 0,+ }++ charged = sum(int(e.charge_fen or 0) for e in events)+ for e in events:+ e.settled = True++ # 无限额/跳过扣费:标记用量已结算,不动钱包,任务标 settled+ if task.billing_status == "skipped":+ task.billing_charged_fen = charged+ task.billing_status = "settled"+ await db.flush()+ return {"charged": charged, "refunded": 0}++ user = await _lock_user(db, int(task.requested_by)) if task.requested_by else None+ if not user or task.billing_status != "frozen":+ # 非 frozen(如 none)但已有用量:只落账用量,不碰钱包+ task.billing_charged_fen = charged+ if events:+ task.billing_status = "settled"+ await db.flush()+ return {"charged": charged, "refunded": 0}++ frozen_for_task = int(task.billing_estimate_fen or 0)+ user.frozen_fen = max(0, int(user.frozen_fen or 0) - frozen_for_task)+ extra = max(0, charged - frozen_for_task)+ refund = max(0, frozen_for_task - charged)++ if extra > 0:+ logger.warning(+ "settle overage user=%s task=%s extra_fen=%s balance=%s",+ user.id,+ task_id,+ extra,+ user.balance_fen,+ )+ await _ledger(+ db,+ user,+ -extra,+ "settle",+ ref_type="task_run",+ ref_id=str(task_id),+ note="settle_overage",+ )+ if refund > 0:+ await _ledger(+ db,+ user,+ refund,+ "unfreeze",+ ref_type="task_run",+ ref_id=str(task_id),+ note="refund_unused_freeze",+ )++ task.billing_charged_fen = charged+ task.billing_refunded_fen = refund+ task.billing_status = "settled"+ await _ledger(+ db,+ user,+ 0,+ "settle",+ ref_type="task_run",+ ref_id=str(task_id),+ note=f"charged={charged} freeze={frozen_for_task} refund={refund}",+ )+ await db.flush()+ return {"charged": charged, "refunded": refund}+++async def settle_project(db: AsyncSession, project_id: int) -> dict[str, int]:+ """兼容旧科普项目结算:按 project_id 汇总未结算 usage(无 task_run_id 的历史行)。"""+ from app.models import Project++ project = await db.get(Project, project_id)+ if not project:+ return {"charged": 0, "refunded": 0}+ user = await _lock_user(db, int(project.user_id))+ result = await db.execute(+ select(UsageEvent).where(+ UsageEvent.project_id == project_id,+ UsageEvent.settled.is_(False),+ )+ )+ events = list(result.scalars().all())+ charged = sum(int(e.charge_fen or 0) for e in events)+ for e in events:+ e.settled = True++ if not user or not billing_active(user):+ await db.flush()+ return {"charged": 0, "refunded": 0}++ frozen_before = int(user.frozen_fen or 0)+ extra = max(0, charged - frozen_before)+ refund = max(0, frozen_before - charged)+ user.frozen_fen = 0++ if extra > 0:+ await _ledger(+ db,+ user,+ -extra,+ "settle",+ ref_type="project",+ ref_id=str(project_id),+ note="settle_overage",+ )+ if refund > 0:+ await _ledger(+ db,+ user,+ refund,+ "unfreeze",+ ref_type="project",+ ref_id=str(project_id),+ note="refund_unused_freeze",+ )+ await _ledger(+ db,+ user,+ 0,+ "settle",+ ref_type="project",+ ref_id=str(project_id),+ note=f"charged={charged} refund={refund}",+ )+ await db.flush()+ return {"charged": charged, "refunded": refund}+++async def credit_topup(+ db: AsyncSession,+ user: User,+ credit_fen: int,+ *,+ ref_type: str,+ ref_id: str,+ note: str = "",+) -> None:+ locked = await _lock_user(db, int(user.id))+ target = locked or user+ await _ledger(db, target, int(credit_fen), "topup", ref_type=ref_type, ref_id=ref_id, note=note)+ if locked is not None and locked is not user:+ user.balance_fen = locked.balance_fen+ user.frozen_fen = locked.frozen_fen+ await db.flush()+++async def close_expired_pending_orders(+ db: AsyncSession,+ *,+ user_id: int | None = None,+ out_trade_no: str | None = None,+) -> int:+ from datetime import datetime, timezone++ from app.models import Order++ now = datetime.now(timezone.utc)+ stmt = select(Order).where(Order.status == "pending")+ if user_id is not None:+ stmt = stmt.where(Order.user_id == user_id)+ if out_trade_no is not None:+ stmt = stmt.where(Order.out_trade_no == out_trade_no)+ rows = (await db.execute(stmt)).scalars().all()+ closed = 0+ for order in rows:+ created = order.created_at+ if created is None:+ continue+ if created.tzinfo is None:+ created = created.replace(tzinfo=timezone.utc)+ if (now - created).total_seconds() < 300:+ continue+ order.status = "closed"+ closed += 1+ if closed:+ await db.commit()+ return closed+++async def settle_usage_charge(+ db: AsyncSession,+ user: User,+ charge_fen: int,+ *,+ ref_type: str = "api",+ ref_id: str = "",+) -> None:+ """即时扣费(已由 task 结算覆盖时仅作兼容)。"""+ if not billing_active(user):+ return+ need = max(0, int(charge_fen))+ if need <= 0:+ return+ locked = await _lock_user(db, int(user.id))+ target = locked or user+ available = int(target.balance_fen or 0)+ if available < need:+ raise ValueError(f"余额不足:需要 ¥{need / 100:.2f},当前 ¥{available / 100:.2f},请先充值")+ await _ledger(+ db,+ target,+ -need,+ "settle",+ ref_type=ref_type,+ ref_id=ref_id,+ note="api_usage",+ )+ if locked is not None and locked is not user:+ user.balance_fen = locked.balance_fen+ user.frozen_fen = locked.frozen_fen+ await db.flush()+++async def get_task_usage_lines(db: AsyncSession, task_id: int) -> list[UsageEvent]:+ result = await db.execute(+ select(UsageEvent)+ .where(UsageEvent.task_run_id == task_id)+ .order_by(UsageEvent.id.asc())+ )+ return list(result.scalars().all())+++async def get_task_billing_summary(db: AsyncSession, task_id: int) -> dict[str, Any]:+ task = await db.get(TaskRun, task_id)+ if not task:+ return {}+ lines = await get_task_usage_lines(db, task_id)+ return {+ "billing_status": task.billing_status,+ "billing_estimate_fen": int(task.billing_estimate_fen or 0),+ "billing_charged_fen": int(task.billing_charged_fen or 0),+ "billing_refunded_fen": int(task.billing_refunded_fen or 0),+ "usage_count": len(lines),+ "total_tokens": sum(int(l.total_tokens or 0) for l in lines),+ "lines": lines,+ }diff --git a/backend/app/services/billing/usage.py b/backend/app/services/billing/usage.pynew file mode 100644index 0000000..f9ab293--- /dev/null+++ b/backend/app/services/billing/usage.py@@ -0,0 +1,138 @@+# -*- coding: utf-8 -*-+"""用量行写入:唯一写 usage_events 的入口。"""+from __future__ import annotations++import json+from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.config import get_settings+from app.models import UsageEvent+from app.services.billing.context import get_current_task_run_id+from app.services.billing.pricing import billing_key_to_capability, charge_fen_for_tokens+++async def record_line(+ db: AsyncSession,+ *,+ user_id: int,+ billing_key: str,+ model: str = "",+ tokens: int = 0,+ prompt_tokens: int = 0,+ completion_tokens: int = 0,+ estimated: bool = False,+ raw: dict | None = None,+ project_id: int | None = None,+ drama_project_id: int | None = None,+ shot_id: int | None = None,+ provider: str = "ark",+ task_run_id: int | None = None,+ domain: str | None = None,+) -> UsageEvent:+ s = get_settings()+ tid = task_run_id if task_run_id is not None else get_current_task_run_id()+ total = int(tokens) or (int(prompt_tokens) + int(completion_tokens))+ if total <= 0:+ if billing_key == "llm_chat":+ total = s.billing_est_llm_tokens+ estimated = True+ elif billing_key == "seedream":+ total = s.billing_est_seedream_tokens+ estimated = True+ elif billing_key == "tts":+ total = s.billing_est_tts_tokens+ estimated = True+ elif billing_key.startswith("seedance"):+ total = s.billing_est_seedance_tokens_per_sec * 5+ estimated = True+ cost, charge = charge_fen_for_tokens(total, billing_key, settings=s)+ capability = billing_key_to_capability(billing_key)+ ev = UsageEvent(+ user_id=user_id,+ project_id=project_id,+ drama_project_id=drama_project_id,+ task_run_id=tid,+ domain=domain,+ capability=capability,+ shot_id=shot_id,+ provider=provider,+ billing_key=billing_key,+ model=model or "",+ prompt_tokens=int(prompt_tokens),+ completion_tokens=int(completion_tokens),+ total_tokens=total,+ cost_fen=cost,+ charge_fen=charge,+ estimated=estimated,+ settled=False,+ raw_usage_json=json.dumps(raw, ensure_ascii=False)[:4000] if raw else None,+ )+ db.add(ev)+ await db.flush()+ return ev+++async def record_llm_chat_line(+ db: AsyncSession,+ *,+ user_id: int,+ domain: str,+ drama_project_id: int | None = None,+ project_id: int | None = None,+ tokens: int | None = None,+) -> UsageEvent | None:+ """在 billing_scope 内记录一次 LLM 调用;无 scope 时跳过(由调用方聚合计费)。"""+ if get_current_task_run_id() is None:+ return None+ s = get_settings()+ return await record_line(+ db,+ user_id=user_id,+ billing_key="llm_chat",+ model=s.model_llm,+ tokens=int(tokens or 0),+ estimated=True,+ project_id=project_id,+ drama_project_id=drama_project_id,+ domain=domain,+ )+++# 兼容旧调用名+async def record_usage(+ db: AsyncSession,+ *,+ user_id: int,+ project_id: int | None,+ billing_key: str,+ model: str = "",+ tokens: int = 0,+ prompt_tokens: int = 0,+ completion_tokens: int = 0,+ estimated: bool = False,+ raw: dict | None = None,+ shot_id: int | None = None,+ provider: str = "ark",+ drama_project_id: int | None = None,+ domain: str | None = None,+ task_run_id: int | None = None,+) -> UsageEvent:+ return await record_line(+ db,+ user_id=user_id,+ billing_key=billing_key,+ model=model,+ tokens=tokens,+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens,+ estimated=estimated,+ raw=raw,+ project_id=project_id,+ drama_project_id=drama_project_id,+ shot_id=shot_id,+ provider=provider,+ domain=domain,+ task_run_id=task_run_id,+ )diff --git a/backend/app/services/drama/asset_video.py b/backend/app/services/drama/asset_video.pyindex b50d741..d012f17 100644--- a/backend/app/services/drama/asset_video.py+++ b/backend/app/services/drama/asset_video.py@@ -12,7 +12,7 @@ from app.config import get_settingsfrom app.models import Userfrom app.models_drama import DramaAsset, DramaProjectfrom app.services.ark import get_ark-from app.services.billing import record_usage+from app.services.billing import record_linefrom app.services.drama.billing_util import seedance_video_billing_tokensfrom app.services.drama.build_seedance_generate_body import (build_seedance_generate_body,@@ -148,7 +148,7 @@ async def generate_asset_video(}asset.params = params- await record_usage(+ await record_line(db,user_id=user.id,project_id=None,@@ -157,6 +157,7 @@ async def generate_asset_video(model=settings.model_video,tokens=seedance_video_billing_tokens(duration),estimated=True,+ domain="drama",)await db.commit()await db.refresh(asset)diff --git a/backend/app/services/drama/voice_synthesis.py b/backend/app/services/drama/voice_synthesis.pyindex d018a28..ffcdbb6 100644--- a/backend/app/services/drama/voice_synthesis.py+++ b/backend/app/services/drama/voice_synthesis.py@@ -8,7 +8,7 @@ from app.config import get_settingsfrom app.models import Userfrom app.models_drama import DramaAsset, DramaProjectfrom app.services.ark import get_ark-from app.services.billing import record_usage+from app.services.billing import record_linefrom app.services.drama.voice_design import (design_voice,parse_speaker_pool,@@ -214,7 +214,7 @@ async def synthesize_voice_asset(gen = params.get("generation") if isinstance(params.get("generation"), dict) else {}params["generation"] = {**gen, "status": "done", "url": audio_url}asset.params = params- await record_usage(+ await record_line(db,user_id=user.id,project_id=None,@@ -222,6 +222,7 @@ async def synthesize_voice_asset(billing_key="tts",model=settings.model_audio,estimated=True,+ domain="drama",)await db.commit()await db.refresh(asset)diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.pyindex 80027ca..9929336 100644--- a/backend/app/services/pipeline.py+++ b/backend/app/services/pipeline.py@@ -48,17 +48,6 @@ _running: dict[int, asyncio.Task] = {}_cancelled: set[int] = set()-async def _settle_billing(project_id: int) -> None:- try:- from app.services import billing as billing_svc-- async with AsyncSessionLocal() as db:- await billing_svc.settle_project(db, project_id)- await db.commit()- except Exception: # noqa: BLE001- logger.exception("billing settle failed project=%s", project_id)--async def _record_usage_est(project_id: int,billing_key: str,@@ -66,22 +55,25 @@ async def _record_usage_est(tokens: int = 0,model: str = "",estimated: bool = True,+ shot_id: int | None = None,) -> None:try:- from app.services import billing as billing_svc+ from app.services.billing import record_lineasync with AsyncSessionLocal() as db:project = await db.get(Project, project_id)if not project:return- await billing_svc.record_usage(+ await record_line(db,user_id=project.user_id,- project_id=project_id,billing_key=billing_key,model=model,tokens=tokens,estimated=estimated,+ project_id=project_id,+ shot_id=shot_id,+ domain="kepu",)await db.commit()except Exception: # noqa: BLE001@@ -416,8 +408,6 @@ async def run_pipeline(project_id: int) -> None:"message": "分镜已生成,请确认修改后手动继续",},)- await _settle_billing(project_id)- logger.info("pipeline paused after script project=%s", project_id)returnlogger.info(@@ -500,7 +490,6 @@ async def run_pipeline(project_id: int) -> None:project.status = ProjectStatus.CANCELLEDproject.error_msg = "用户取消"await db.commit()- await _settle_billing(project_id)await publish_progress(project_id,{@@ -520,7 +509,6 @@ async def run_pipeline(project_id: int) -> None:project.status = ProjectStatus.CANCELLEDproject.error_msg = "用户取消"await db.commit()- await _settle_billing(project_id)await publish_progress(project_id,{@@ -544,7 +532,6 @@ async def run_pipeline(project_id: int) -> None:project.status = ProjectStatus.FAILEDproject.error_msg = fail_msgawait db.commit()- await _settle_billing(project_id)await publish_progress(project_id,{@@ -1544,10 +1531,7 @@ async def _compose_stage(project_id: int) -> None:project.status = ProjectStatus.DONEproject.progress = 100await db.commit()- await _settle_billing(project_id)---# FFmpeg 合成:遇到 SIGTERM 自动重试,避免部署重启等打断直接落失败+# 遇到 SIGTERM 自动重试,避免部署重启等打断直接落失败async def _run_ffmpeg_compose_with_retry(project_id: int, work) -> None:last_exc: BaseException | None = Nonefor attempt in range(1, _COMPOSE_SIGTERM_MAX_ATTEMPTS + 1):@@ -1638,6 +1622,14 @@ async def regen_shot_image(project_id: int, shot_id: int) -> None:project.status = ProjectStatus.IMAGE_READYproject.final_video_url = Noneawait db.commit()+ s = get_settings()+ await _record_usage_est(+ project_id,+ "seedream",+ tokens=s.billing_est_seedream_tokens,+ model=s.model_image,+ shot_id=shot_id,+ )@storage.without_intermediate_oss@@ -1696,6 +1688,15 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:project.final_video_url = Noneproject.status = ProjectStatus.VIDEO_READYawait db.commit()+ billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"+ tok = int(max(float(dur), 2.0) * cfg.billing_est_seedance_tokens_per_sec)+ await _record_usage_est(+ project_id,+ billing_key,+ tokens=tok,+ model=cfg.model_video,+ shot_id=shot_id,+ )@storage.without_intermediate_ossdiff --git a/backend/app/services/studio_tools.py b/backend/app/services/studio_tools.pyindex b17da1b..2dfecf4 100644--- a/backend/app/services/studio_tools.py+++ b/backend/app/services/studio_tools.py@@ -14,8 +14,11 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.config import get_settingsfrom app.models import ToolRun, User+from app.models_tasks import TaskRunfrom app.services.ark import get_ark-from app.services.billing import record_usage+from app.services.billing import record_line, run_billed_ephemeral+from app.services.billing.estimates import estimate_task_fen+from app.services.billing.settlement import billing_activefrom app.services.ffmpeg_compose import extract_video_poster_framefrom app.services import storage@@ -193,13 +196,13 @@ async def run_image_tool(shot_no=user.id,size=size,)- await record_usage(+ await record_line(db,user_id=user.id,- project_id=None,billing_key="seedream",model=get_settings().model_image,estimated=True,+ domain="studio",raw={"tool_id": tool_id},)url = result.local_url or result.remote_url or ""@@ -216,6 +219,17 @@ def _dispatch_tool_image(run_id: int) -> str:return f"local-{run_id}"+# 入队前同步校验余额(与 run_billed_ephemeral 预扣估算一致)+async def _ensure_image_tool_balance(db: AsyncSession, user: User, tool_id: str) -> None:+ if not billing_active(user):+ return+ synthetic = TaskRun(domain="studio", task_type="tool_image", payload={"tool_id": tool_id})+ need = await estimate_task_fen(db, synthetic)+ available = int(user.balance_fen or 0)+ if available < need:+ raise ValueError(f"余额不足:需要 ¥{need/100:.2f},当前 ¥{available/100:.2f},请先充值")++# 提交生图任务:立即返回 task_id,实际生成在后台执行async def enqueue_image_tool(db: AsyncSession,@@ -231,6 +245,7 @@ async def enqueue_image_tool(files: list[Path],params: dict,) -> dict:+ await _ensure_image_tool_balance(db, user, tool_id)row = ToolRun(user_id=user.id,tool_id=tool_id,@@ -281,17 +296,28 @@ async def execute_image_tool_run(run_id: int) -> dict:await db.commit()try:- data = await run_image_tool(+ async def _exec() -> dict:+ return await run_image_tool(+ db,+ user,+ tool_id=row.tool_id,+ prompt=row.prompt or "",+ negative=str(stored.get("negative") or ""),+ ratio=stored.get("ratio") or None,+ strength=stored.get("strength") or None,+ mode=stored.get("mode") or None,+ pack=stored.get("pack") or None,+ files=file_paths,+ )++ billing_task, data = await run_billed_ephemeral(db,user,- tool_id=row.tool_id,- prompt=row.prompt or "",- negative=str(stored.get("negative") or ""),- ratio=stored.get("ratio") or None,- strength=stored.get("strength") or None,- mode=stored.get("mode") or None,- pack=stored.get("pack") or None,- files=file_paths,+ domain="studio",+ task_type="tool_image",+ executor=_exec,+ payload={"tool_id": row.tool_id, "run_id": run_id},+ commit=False,)urls = ensure_public_urls(list(data.get("urls") or []))row.kind = str(data.get("kind") or "image")@@ -299,8 +325,11 @@ async def execute_image_tool_run(run_id: int) -> dict:row.urls = urlsrow.preview_url = urls[0] if urls else row.preview_urlrow.error = None+ params = dict(row.params or {})+ params["billing_task_id"] = billing_task.id+ row.params = paramsawait db.commit()- return {"ok": True, "run_id": run_id, "urls": urls}+ return {"ok": True, "run_id": run_id, "urls": urls, "billing_task_id": billing_task.id}except Exception as exc: # noqa: BLE001row.status = "failed"row.error = str(exc)[:512]@@ -358,12 +387,12 @@ async def start_video_tool(shot_no=user.id,size=ratio_to_size(ratio or "9:16"),)- await record_usage(+ await record_line(db,user_id=user.id,- project_id=None,billing_key="seedream",estimated=True,+ domain="studio",raw={"tool_id": "t2v-still"},)preview_url = still.local_url or still.remote_url@@ -399,15 +428,6 @@ async def start_video_tool(resolution="480p",generate_audio=False,)- await record_usage(- db,- user_id=user.id,- project_id=None,- billing_key="seedance2:video0",- model=get_settings().model_video,- estimated=True,- raw={"tool_id": tool_id, "duration": duration},- )digest = hashlib.md5(f"{user.id}:{task_id}".encode()).hexdigest()[:8]logger.info("tool video queued user=%s tool=%s task=%s hash=%s", user.id, tool_id, task_id, digest)return {diff --git a/backend/app/services/tasks/executor.py b/backend/app/services/tasks/executor.pyindex 7be372a..8a45590 100644--- a/backend/app/services/tasks/executor.py+++ b/backend/app/services/tasks/executor.py@@ -2,12 +2,18 @@from __future__ import annotations+import asyncio+import loggingfrom datetime import UTC, datetimefrom app.database import AsyncSessionLocal+from app.services.billing.context import billing_scope+from app.services.billing.settlement import freeze_for_task, settle_taskfrom app.services.tasks.handlers import get_task_handlerfrom app.services.tasks.service import append_task_event, get_task_for_runtime, set_task_step_state+logger = logging.getLogger(__name__)+# 执行单个任务并回写平台状态。async def execute_task_run(task_id: int) -> None:@@ -24,6 +30,29 @@ async def execute_task_run(task_id: int) -> None:task.error_code = "handler_missing"task.error_message = f"未注册任务处理器: {task.domain}/{task.task_type}"task.finished_at = datetime.now(UTC)+ # 未进入预扣,保持 none+ task.billing_status = "none"+ await append_task_event(+ db,+ task.id,+ event_type="task.failed",+ status=task.status,+ phase=task.current_step_key,+ message=task.error_message,+ )+ await db.commit()+ return++ try:+ await freeze_for_task(db, task)+ except ValueError as exc:+ await _fail_drama_asset_generation_if_needed(db, task, str(exc))+ task.status = "failed"+ task.error_code = "insufficient_balance"+ task.error_message = str(exc)[:500]+ task.finished_at = datetime.now(UTC)+ # 未预扣成功,保持 none(skipped 仅表示无限额跳过扣费)+ task.billing_status = "none"await append_task_event(db,task.id,@@ -34,6 +63,7 @@ async def execute_task_run(task_id: int) -> None:)await db.commit()return+step = task.steps[0] if task.steps else Nonenow = datetime.now(UTC)task.status = "running"@@ -52,27 +82,30 @@ async def execute_task_run(task_id: int) -> None:await db.commit()try:- async with AsyncSessionLocal() as db:- task = await get_task_for_runtime(db, task_id)- if not task:- return- handler = get_task_handler(task.domain, task.task_type)- result = await handler.executor(task) if handler else {"ok": False, "error": "missing_handler"}- task = await get_task_for_runtime(db, task_id)- if not task:- return- # handler 在独立 session 提交后,本 session 可能仍缓存 running(expire_on_commit=False)- await db.refresh(task)- if isinstance(result, dict) and (result.get("deferred") or result.get("awaiting_poll")):- return- if task.status == "awaiting_poll":- return- if task.status == "pending" and isinstance(result, dict) and result.get("deferred"):- return- if isinstance(result, dict) and result.get("cancelled"):- await _mark_cancelled(db, task)- return- await _complete_task(db, task, result or {"ok": True})+ async with billing_scope(task_id):+ async with AsyncSessionLocal() as db:+ task = await get_task_for_runtime(db, task_id)+ if not task:+ return+ handler = get_task_handler(task.domain, task.task_type)+ result = await handler.executor(task) if handler else {"ok": False, "error": "missing_handler"}+ task = await get_task_for_runtime(db, task_id)+ if not task:+ return+ await db.refresh(task)+ if isinstance(result, dict) and (result.get("deferred") or result.get("awaiting_poll")):+ await db.commit()+ return+ if task.status == "awaiting_poll":+ await db.commit()+ return+ if task.status == "pending" and isinstance(result, dict) and result.get("deferred"):+ await db.commit()+ return+ if isinstance(result, dict) and result.get("cancelled"):+ await _mark_cancelled(db, task)+ return+ await _complete_task(db, task, result or {"ok": True})except asyncio.CancelledError:async with AsyncSessionLocal() as db:task = await get_task_for_runtime(db, task_id)@@ -89,9 +122,6 @@ async def execute_task_run(task_id: int) -> None:await _fail_task(db, task, exc)-import asyncio--# 把任务收敛到成功态。async def _complete_task(db, task, result: dict) -> None:now = datetime.now(UTC)@@ -112,6 +142,10 @@ async def _complete_task(db, task, result: dict) -> None:message="任务执行完成" if task.status == "succeeded" else "任务已取消",payload=result,)+ try:+ await settle_task(db, task.id)+ except Exception: # noqa: BLE001+ logger.exception("settle_task failed task_id=%s", task.id)await db.commit()@@ -143,7 +177,6 @@ async def _fail_task(db, task, exc: Exception) -> None:"error": task.error_message,}frag.params = params- # 科普拼接/流水线失败时同步项目态,避免卡在 COMPOSING 等 running 状态无法重试if task.domain == "kepu" and task.project_id:from app.models import Project, ProjectStatus@@ -170,6 +203,10 @@ async def _fail_task(db, task, exc: Exception) -> None:batch_index,"上一镜失败,无法衔接尾帧",)+ try:+ await settle_task(db, task.id)+ except Exception: # noqa: BLE001+ logger.exception("settle_task failed task_id=%s", task.id)await db.commit()@@ -190,9 +227,29 @@ async def _mark_cancelled(db, task) -> None:phase=task.current_step_key,message="任务已取消",)+ try:+ await settle_task(db, task.id)+ except Exception: # noqa: BLE001+ logger.exception("settle_task failed task_id=%s", task.id)await db.commit()+async def _fail_drama_asset_generation_if_needed(db, task, error: str) -> None:+ """任务未开始执行时失败,同步更新漫剧资产 generation 状态。"""+ if (task.domain or "") != "drama" or not task.asset_id:+ return+ if (task.task_type or "") not in {"asset_image", "asset_video"}:+ return+ from app.models_drama import DramaAsset++ asset = await db.get(DramaAsset, int(task.asset_id))+ if not asset:+ return+ params = dict(asset.params or {})+ params["generation"] = {"status": "failed", "error": error[:400]}+ asset.params = params++# 应用重启或热更新中断时,把任务重新放回待执行状态。async def _requeue_interrupted_task(db, task) -> None:now = datetime.now(UTC)diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.pyindex fc20697..90e070c 100644--- a/backend/app/services/tasks/handlers.py+++ b/backend/app/services/tasks/handlers.py@@ -57,21 +57,15 @@ async def _run_drama_fragment_plan(task: TaskRun) -> dict[str, Any] | None:)-# 执行漫剧分镜视频任务。+# 执行漫剧分镜视频任务(NIO + 任务平台计费;每 task 仅处理一个 fragment)。async def _run_drama_fragment_video(task: TaskRun) -> dict[str, Any] | None:- from app.services.drama.jobs import run_episode_generate_job, submit_fragment_video_task+ from app.services.drama.jobs import submit_fragment_video_taskpayload = task.payload or {}fragment_ids = payload.get("fragment_ids") or []- if not isinstance(fragment_ids, list):+ if fragment_ids and not isinstance(fragment_ids, list):raise ValueError("fragment_ids 必须为数组")- if task.fragment_id or len(fragment_ids) <= 1:- return await submit_fragment_video_task(task)- return await run_episode_generate_job(- _require_int(task.episode_id, "episode_id"),- int(task.requested_by),- [int(item) for item in fragment_ids],- )+ return await submit_fragment_video_task(task)# 执行漫剧资产生图任务。@@ -208,6 +202,11 @@ async def _run_tools_mock_delay(task: TaskRun) -> dict[str, Any] | None:}+# 轻量任务占位 handler(实际由 run_billed_ephemeral 内联执行)。+async def _noop_ephemeral(task: TaskRun) -> dict[str, Any] | None:+ return {"ok": True, "ephemeral": True}++# 确保关键主键字段存在。def _require_int(value: int | None, field_name: str) -> int:if isinstance(value, int) and value > 0:@@ -223,6 +222,16 @@ TASK_HANDLERS: dict[tuple[str, str], TaskHandler] = {("drama", "asset_image"): TaskHandler("drama", "asset_image", _run_drama_asset_image),("drama", "asset_video"): TaskHandler("drama", "asset_video", _run_drama_asset_video),("drama", "seed_assets"): TaskHandler("drama", "seed_assets", _run_drama_seed_assets),+ ("drama", "agent_chat"): TaskHandler("drama", "agent_chat", _noop_ephemeral),+ ("drama", "skill_optimize"): TaskHandler("drama", "skill_optimize", _noop_ephemeral),+ ("drama", "voice_prompt"): TaskHandler("drama", "voice_prompt", _noop_ephemeral),+ ("drama", "voice_synthesis"): TaskHandler("drama", "voice_synthesis", _noop_ephemeral),+ ("kepu", "content_expand"): TaskHandler("kepu", "content_expand", _noop_ephemeral),+ ("api", "v1_image"): TaskHandler("api", "v1_image", _noop_ephemeral),+ ("api", "v1_video"): TaskHandler("api", "v1_video", _noop_ephemeral),+ ("api", "v1_seedance"): TaskHandler("api", "v1_seedance", _noop_ephemeral),+ ("studio", "tool_image"): TaskHandler("studio", "tool_image", _noop_ephemeral),+ ("studio", "tool_video"): TaskHandler("studio", "tool_video", _noop_ephemeral),("kepu", "project_pipeline"): TaskHandler("kepu", "project_pipeline", _run_kepu_project_pipeline),("kepu", "shot_regen_image"): TaskHandler("kepu", "shot_regen_image", _run_kepu_shot_image),("kepu", "shot_regen_video"): TaskHandler("kepu", "shot_regen_video", _run_kepu_shot_video),diff --git a/backend/app/services/tasks/poller.py b/backend/app/services/tasks/poller.pyindex da0b552..8443480 100644--- a/backend/app/services/tasks/poller.py+++ b/backend/app/services/tasks/poller.py@@ -11,6 +11,7 @@ from sqlalchemy import selectfrom app.config import get_settingsfrom app.database import AsyncSessionLocalfrom app.models_tasks import TaskRun+from app.services.billing.settlement import settle_taskfrom app.services.tasks.service import append_task_eventlogger = logging.getLogger("app.tasks.poller")@@ -56,6 +57,7 @@ async def _poller_loop() -> None:while not _stop_event.is_set():try:await _select_and_poll_due()+ await _poll_ephemeral_deferred_tasks()except asyncio.CancelledError:raiseexcept Exception: # noqa: BLE001@@ -118,6 +120,10 @@ async def _poll_one_task(task_id: int) -> None:phase=task.current_step_key,message=task.error_message,)+ try:+ await settle_task(db, task.id)+ except Exception: # noqa: BLE001+ logger.exception("settle_task failed task_id=%s", task.id)await db.commit()return@@ -132,3 +138,80 @@ async def _poll_one_task(task_id: int) -> None:poll_interval = max(1.0, float(get_settings().ark_video_poll_interval or 8.0))task.next_action_at = datetime.now(UTC) + timedelta(seconds=poll_interval)await db.commit()+++# 后台轮询 api/studio 轻量视频任务:主动查上游终态,超时则失败并解冻。+async def _poll_ephemeral_deferred_tasks() -> None:+ from app.models import User+ from app.services.billing.ephemeral import settle_deferred_video_poll+ from app.services.studio_tools import poll_video_task++ now = datetime.now(UTC)+ timeout_sec = float(get_settings().ark_video_poll_timeout or 900.0)++ async with AsyncSessionLocal() as db:+ stmt = (+ select(TaskRun)+ .where(+ TaskRun.status == "awaiting_poll",+ TaskRun.domain.in_(["api", "studio"]),+ TaskRun.billing_status == "frozen",+ )+ .order_by(TaskRun.next_action_at.asc().nullsfirst(), TaskRun.id.asc())+ .limit(20)+ )+ rows = list((await db.execute(stmt)).scalars().all())++ for row in rows:+ task_id = int(row.id)+ async with AsyncSessionLocal() as db:+ task = await db.get(TaskRun, task_id)+ if not task or task.status != "awaiting_poll":+ continue++ started = task.started_at or task.created_at+ if started is not None and started.tzinfo is None:+ started = started.replace(tzinfo=UTC)+ if started and (now - started).total_seconds() > timeout_sec:+ task.status = "failed"+ task.error_code = "poll_timeout"+ task.error_message = "视频轮询超时,预扣已退回"+ task.finished_at = now+ await append_task_event(+ db,+ task.id,+ event_type="task.failed",+ status=task.status,+ phase=task.current_step_key,+ message=task.error_message,+ )+ try:+ await settle_task(db, task.id)+ except Exception: # noqa: BLE001+ logger.exception("settle_task failed task_id=%s", task.id)+ await db.commit()+ continue++ user = await db.get(User, task.requested_by)+ provider_id = (task.provider_task_id or "").strip()+ if not user or not provider_id:+ continue++ data = await poll_video_task(user, provider_id)+ status = str(data.get("status") or "").strip().lower()+ if status in {"", "running", "queued"}:+ task.next_action_at = now + timedelta(+ seconds=max(1.0, float(get_settings().ark_video_poll_interval or 8.0))+ )+ await db.commit()+ continue++ await settle_deferred_video_poll(+ db,+ user,+ provider_task_id=provider_id,+ poll_status=status,+ error=str(data.get("error") or "") or None,+ billing_task_id=task.id,+ )+ await db.commit()diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.pyindex e303bb9..7e050d6 100644--- a/backend/app/services/tasks/service.py+++ b/backend/app/services/tasks/service.py@@ -71,6 +71,21 @@ async def create_task(handler = get_task_handler(body.domain, body.task_type)if handler is None:raise ValueError("当前任务类型尚未接入任务平台")+ from app.services.billing.settlement import ensure_balance_for_task++ balance_probe = TaskRun(+ domain=body.domain,+ task_type=body.task_type,+ requested_by=user.id,+ payload=body.payload,+ project_id=body.project_id,+ drama_project_id=body.drama_project_id,+ episode_id=body.episode_id,+ fragment_id=body.fragment_id,+ asset_id=body.asset_id,+ shot_id=body.shot_id,+ )+ estimate_fen = await ensure_balance_for_task(db, user, balance_probe)planned_steps = handler.plan_steps(body)first_step = planned_steps[0] if planned_steps else Nonenow = datetime.now(UTC)@@ -99,6 +114,7 @@ async def create_task(fragment_id=body.fragment_id,asset_id=body.asset_id,shot_id=body.shot_id,+ billing_estimate_fen=int(estimate_fen or 0),)db.add(task)await db.flush()