Skip to content

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

refactor: 去掉 Celery 残留,并收紧分镜对白覆盖与请求层拆分

yid4b11b1c45eb
diff --git a/CLAUDE.md b/CLAUDE.md
index 806e335..2bc773c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -43,7 +43,7 @@ pytest tests/test_x.py::test_name # 单测
### 统一任务平台(核心,易误判)
-代码里没有独立 worker 进程:Celery 仅是遗留依赖(`USE_CELERY` 代码已不读取,`workers/` 目录不存在)。实际运行时是 **随 FastAPI 启动的进程内三件套**(`app/services/tasks/`):
+代码里没有独立 worker 进程,也不依赖 Celery(`USE_CELERY` 等旧配置已移除,`workers/` 目录不存在)。实际运行时是 **随 FastAPI 启动的进程内三件套**(`app/services/tasks/`):
- `scheduler.py`:定时租约到期任务(pending→leased→running),受全站槽位 `TASK_RUNTIME_MAX_CONCURRENCY` 与单用户槽位 `TASK_USER_MAX_CONCURRENCY` 限制;含孤儿任务回收
- `executor.py`:执行 handler
diff --git a/admin/src/api/client.ts b/admin/src/api/client.ts
index 7e9b6a1..cfdc257 100644
--- a/admin/src/api/client.ts
+++ b/admin/src/api/client.ts
@@ -1,16 +1,10 @@
import { clearAuth, getToken, setCachedUser, setToken, type AdminUser } from "@/lib/auth";
-export type PageMeta = {
- page: number;
- page_size: number;
- total: number;
-};
-
type ApiError = {
detail?: string | { msg?: string }[];
};
-// Parse FastAPI error detail into a string
+// 将 FastAPI 的校验错误或业务错误转换为可读文案
function errorMessage(data: ApiError, status: number): string {
const detail = data?.detail;
if (typeof detail === "string") return detail;
@@ -18,7 +12,7 @@ function errorMessage(data: ApiError, status: number): string {
return `请求失败 (${status})`;
}
-// Authenticated JSON fetch against /api
+// 为管理接口附加会话信息,统一处理响应与登录失效
export async function api<T>(
path: string,
options: RequestInit = {},
@@ -48,7 +42,7 @@ export async function api<T>(
return data as T;
}
-// Login then verify admin role via /auth/me
+// 登录后读取用户资料并验证管理员权限
export async function loginAsAdmin(email: string, password: string): Promise<AdminUser> {
const tokenRes = await api<{ access_token: string }>("/api/auth/login", {
method: "POST",
@@ -64,657 +58,10 @@ export async function loginAsAdmin(email: string, password: string): Promise<Adm
return me;
}
-export type AdminUsageBucket = {
- key: string;
- calls: number;
- charge_fen: number;
- cost_fen?: number;
-};
-
-export type AdminDailyUsage = {
- date: string;
- calls: number;
- charge_fen: number;
- cost_fen?: number;
-};
-
-export type AdminTopUser = {
- user_id: number;
- email?: string | null;
- calls: number;
- charge_fen: number;
- cost_fen?: number;
-};
-
-export type AdminProjectUsage = {
- charge_fen: number;
- cost_fen: number;
- tokens: number;
- calls: number;
- image_gens: number;
- video_gens: number;
- llm_calls: number;
- tts_gens?: number;
-};
-
-export type AdminTaskBrief = {
- id: number;
- domain: string;
- task_type: string;
- status: string;
- progress_percent: number;
- billing_charged_fen: number;
- billing_estimate_fen: number;
- error_message?: string | null;
- created_at?: string | null;
- finished_at?: string | null;
-};
-
-export type AdminShotBrief = {
- id: number;
- shot_no: number;
- status: string;
- has_image: boolean;
- has_video: boolean;
- has_audio: boolean;
- duration: number;
-};
-
-export type AdminStats = {
- user_count: number;
- order_paid_total_fen: number;
- order_paid_today_fen: number;
- project_status_counts: Record<string, number>;
- drama_project_count?: number;
- usage_calls_today?: number;
- usage_calls_month?: number;
- usage_calls_total?: number;
- usage_charge_today_fen?: number;
- usage_charge_month_fen?: number;
- usage_charge_total_fen?: number;
- usage_cost_today_fen?: number;
- usage_cost_month_fen?: number;
- usage_cost_total_fen?: number;
- usage_by_capability?: AdminUsageBucket[];
- usage_by_domain?: AdminUsageBucket[];
- daily_usage?: AdminDailyUsage[];
- top_users_by_charge?: AdminTopUser[];
-};
-
-export type AdminUpstreamUsageDay = {
- date: string;
- local_cost_fen: number;
- local_tokens: number;
- official_tokens: number;
- official_cost_fen: number;
- delta_fen: number;
- delta_pct?: number | null;
-};
-
-export type AdminUpstreamUsage = {
- configured: boolean;
- days: number;
- last_sync_at?: string | null;
- series: AdminUpstreamUsageDay[];
-};
-
-export type AdminUpstreamUsageSync = {
- configured: boolean;
- synced: number;
- skipped: number;
- last_sync_at?: string | null;
-};
-
-export type AdminFinanceDailyRow = {
- date: string;
- charge_fen: number;
- cost_fen: number;
- tokens: number;
- actual_cost_fen: number;
- profit_fen: number;
- profit_pct?: number | null;
-};
-
-export type AdminFinanceDailyTotals = {
- charge_fen: number;
- cost_fen: number;
- tokens: number;
- actual_cost_fen: number;
- profit_fen: number;
- profit_pct?: number | null;
-};
-
-export type AdminFinanceDaily = {
- configured: boolean;
- days: number;
- last_sync_at?: string | null;
- totals: AdminFinanceDailyTotals;
- series: AdminFinanceDailyRow[];
-};
-
-export type AdminUserRow = {
- id: number;
- email: string;
- nickname: string;
- phone?: string;
- quota_left: number;
- balance_fen: number;
- frozen_fen: number;
- plan: string;
- role: string;
- created_at?: string | null;
-};
-
-/** @deprecated 遗留 Celery 队列快照,任务中心已改用 /api/admin/tasks */
-export type AdminOrder = {
- id: number;
- out_trade_no: string;
- user_id: number;
- user_email?: string | null;
- sku_id: string;
- amount_fen: number;
- credit_fen: number;
- pay_type: string;
- status: string;
- trade_no?: string | null;
- paid_at?: string | null;
- created_at: string;
-};
-
-export type AdminLedger = {
- id: number;
- user_id: number;
- user_email?: string | null;
- delta_fen: number;
- balance_after: number;
- kind: string;
- ref_type: string;
- ref_id: string;
- note: string;
- created_at: string;
- /** 手动调账操作人邮箱(ref_type=admin 时) */
- operator_email?: string | null;
-};
-
-export type AdminProject = {
- id: number;
- user_id: number;
- user_email?: string | null;
- template_id: string;
- title: string;
- status: string;
- progress: number;
- error_msg?: string | null;
- cover_url?: string | null;
- final_video_url?: string | null;
- pipeline_mode: string;
- created_at: string;
- updated_at: string;
- shot_count: number;
- charge_fen?: number;
- source_type?: string;
- source_text?: string;
- resolution_mode?: string;
- output_ratio?: string;
- voice_id?: string;
- usage?: AdminProjectUsage;
- shots?: AdminShotBrief[];
- recent_tasks?: AdminTaskBrief[];
-};
-
-export type AdminDramaProject = {
- id: number;
- user_id: number;
- user_email?: string | null;
- title: string;
- description?: string | null;
- created_at?: string | null;
- updated_at?: string | null;
- episode_count?: number;
- asset_count?: number;
- fragment_count?: number;
- charge_fen?: number;
- summary_status?: string | null;
- assets_seed_status?: string | null;
- episode_content_status?: string | null;
- usage?: AdminProjectUsage;
- episodes?: { id: number; name: string; fragment_count: number; fragment_plan_status?: string | null }[];
- assets?: {
- id: number;
- type: string;
- name?: string | null;
- has_cover: boolean;
- generation_status?: string | null;
- }[];
- recent_tasks?: AdminTaskBrief[];
-};
-
-export type AdminDramaAsset = {
- id: number;
- project_id: number;
- project_title?: string | null;
- user_id?: number | null;
- user_email?: string | null;
- type: string;
- asset_type: string;
- name?: string | null;
- cover?: string | null;
- url?: string | null;
- has_cover: boolean;
- generation_status?: string | null;
- derive_id?: string | null;
- created_at?: string | null;
- updated_at?: string | null;
- params?: Record<string, unknown> | null;
-};
-
-export type AdminDramaEpisode = {
- id: number;
- project_id: number;
- project_title?: string | null;
- user_id?: number | null;
- user_email?: string | null;
- name: string;
- fragment_count: number;
- fragment_plan_status?: string | null;
- created_at?: string | null;
- updated_at?: string | null;
- fragments?: {
- id: number;
- sort_order: number;
- content: string;
- cover: string;
- video: string;
- duration_sec?: number | null;
- generation_status?: string | null;
- asset_ref_count: number;
- }[];
-};
-
-export type AdminDramaFragment = {
- id: number;
- episode_id: number;
- episode_name?: string | null;
- project_id: number;
- project_title?: string | null;
- user_id?: number | null;
- user_email?: string | null;
- sort_order: number;
- content: string;
- cover: string;
- video: string;
- duration_sec?: number | null;
- generation_status?: string | null;
- asset_ref_count: number;
- created_at?: string | null;
- updated_at?: string | null;
- params?: Record<string, unknown> | null;
- asset_ids?: number[];
-};
-
-export type AdminWork = {
- id: number;
- project_id: number;
- user_id: number;
- user_email?: string | null;
- title: string;
- cover_url?: string | null;
- video_url: string;
- visibility: string;
- audit_status: string;
- published_at: string;
-};
-
-export type AdminQueueTask = {
- task_id: string;
- task_name: string;
- label: string;
- args_repr: string;
- queue: string;
- state: string;
- started_at?: number | null;
- ref_id?: number | null;
- position?: number | null;
-};
-
-export type AdminQueueSummary = {
- name: string;
- label: string;
- pending: number;
- sample: AdminQueueTask[];
-};
-
-/** @deprecated 遗留 Celery 队列快照,任务中心已改用 /api/admin/tasks */
-export type AdminQueuesSnapshot = {
- ok: boolean;
- redis_ok: boolean;
- unacked: number;
- total_pending: number;
- active_count: number;
- reserved_count: number;
- queues: AdminQueueSummary[];
- pending_tasks: AdminQueueTask[];
- active_tasks: AdminQueueTask[];
- reserved_tasks: AdminQueueTask[];
- runtime: Record<string, number | string>;
- fetched_at: string;
-};
-
-export type AdminTaskRow = {
- id: number;
- domain: string;
- task_type: string;
- status: string;
- priority: number;
- requested_by: number;
- user_email?: string | null;
- progress_percent: number;
- cancel_requested: boolean;
- cancelable: boolean;
- current_step_key?: string | null;
- current_step_status?: string | null;
- error_message?: string | null;
- project_id?: number | null;
- drama_project_id?: number | null;
- episode_id?: number | null;
- fragment_id?: number | null;
- asset_id?: number | null;
- script_id?: number | null;
- created_at?: string | null;
- started_at?: string | null;
- finished_at?: string | null;
- billing_estimate_fen?: number;
- billing_charged_fen?: number;
- billing_refunded_fen?: number;
- billing_status?: string;
- /** 提交参数(入队 payload) */
- payload?: Record<string, unknown> | null;
- /** 执行结果 */
- result_payload?: Record<string, unknown> | null;
-};
-
-export type AdminUsageEventBrief = {
- id: number;
- billing_key: string;
- capability?: string | null;
- model?: string;
- total_tokens?: number;
- charge_fen?: number;
- cost_fen?: number;
- estimated?: boolean;
- billing_basis?: string;
- billing_basis_label?: string;
- created_at?: string | null;
-};
-
-export type AdminUsageEvent = {
- id: number;
- user_id: number;
- user_email?: string | null;
- task_run_id?: number | null;
- domain?: string | null;
- capability?: string | null;
- billing_key: string;
- model?: string;
- total_tokens?: number;
- charge_fen?: number;
- cost_fen?: number;
- estimated?: boolean;
- billing_basis?: string;
- billing_basis_label?: string;
- created_at?: string | null;
- task_domain?: string | null;
- task_type?: string | null;
- task_status?: string | null;
- project_id?: number | null;
- drama_project_id?: number | null;
- provider?: string | null;
-};
-
-export type AdminUsageEventListRes = {
- items: AdminUsageEvent[];
- meta: PageMeta;
-};
-
-export type AdminTaskStep = {
- id: number;
- step_key: string;
- step_type: string;
- status: string;
- attempt_count: number;
- provider_name?: string | null;
- provider_task_id?: string | null;
- error_message?: string | null;
- started_at?: string | null;
- finished_at?: string | null;
-};
-
-export type AdminTaskEvent = {
- id: number;
- event_type: string;
- status?: string | null;
- phase?: string | null;
- message?: string | null;
- payload?: Record<string, unknown> | null;
- created_at?: string | null;
-};
-
-export type AdminTaskDetail = AdminTaskRow & {
- client_request_id?: string | null;
- dedupe_key?: string | null;
- batch_key?: string | null;
- provider_task_id?: string | null;
- scheduled_at?: string | null;
- next_action_at?: string | null;
- lease_until?: string | null;
- error_code?: string | null;
- payload?: Record<string, unknown> | null;
- result_payload?: Record<string, unknown> | null;
- script_id?: number | null;
- asset_id?: number | null;
- shot_id?: number | null;
- updated_at?: string | null;
- steps: AdminTaskStep[];
- events: AdminTaskEvent[];
- targets: Array<{ id: number; target_type: string; target_id: number }>;
- usage_lines?: AdminUsageEventBrief[];
- billing_estimate_fen?: number;
- billing_charged_fen?: number;
- billing_refunded_fen?: number;
- billing_status?: string;
-};
-
-export type AdminTaskStats = {
- pending_count: number;
- active_count: number;
- leased_count: number;
- running_count: number;
- awaiting_poll_count: number;
- cancel_requested_count: number;
- succeeded_count: number;
- failed_count: number;
- cancelled_count: number;
- scheduler_running_jobs: number;
- max_concurrency: number;
- domains: Array<{
- domain: string;
- pending: number;
- active: number;
- succeeded: number;
- failed: number;
- cancelled: number;
- }>;
- fetched_at?: string | null;
-};
-
-export type AdminTaskListRes = {
- items: AdminTaskRow[];
- meta: PageMeta;
-};
-
-export type ModelCapabilityReadiness = {
- capability: string;
- label: string;
- model: string;
- ready: boolean;
- message: string;
-};
-
-export type AdminModelSettings = {
- openai_api_key: string;
- openai_base_url: string;
- model_llm: string;
- has_openai_api_key: boolean;
- ark_api_key: string;
- ark_base_url: string;
- model_image: string;
- model_image_45: string;
- model_video: string;
- model_audio: string;
- has_ark_api_key: boolean;
- ark_image_size: string;
- ark_video_resolution: string;
- ark_video_ratio: string;
- seedance_duration_min: number;
- seedance_duration_max: number;
- ark_video_poll_interval: number;
- ark_video_poll_timeout: number;
- pipeline_image_concurrency: number;
- pipeline_video_concurrency: number;
- pipeline_audio_concurrency: number;
- task_runtime_max_concurrency: number;
- task_user_max_concurrency: number;
- task_poll_max_concurrency: number;
- drama_user_video_job_limit: number;
- drama_fragment_max_attempts: number;
- ark_mock: boolean;
- oss_enabled: boolean;
- oss_endpoint: string;
- oss_region: string;
- oss_bucket: string;
- oss_folder: string;
- oss_access_key_id: string;
- oss_access_key_secret: string;
- oss_public_base: string;
- oss_upload_async: boolean;
- oss_upload_queue: string;
- has_oss_access_key_id: boolean;
- has_oss_access_key_secret: boolean;
- tos_endpoint: string;
- tos_bucket: string;
- tos_access_key: string;
- tos_secret_key: string;
- has_tos_access_key: boolean;
- has_tos_secret_key: boolean;
- cdn_base: string;
- epay_api_url: string;
- epay_pid: string;
- epay_key: string;
- epay_notify_url: string;
- epay_return_url: string;
- has_epay_key: boolean;
- billing_enabled: boolean;
- billing_markup: number;
- billing_estimate_buffer: number;
- billing_seedance_video0: number;
- billing_seedance_video1: number;
- billing_llm_per_m: number;
- billing_seedream_per_m: number;
- billing_tts_per_m: number;
- billing_kie_fen_per_credit: number;
- billing_est_llm_tokens: number;
- billing_est_seedream_tokens: number;
- billing_est_tts_tokens: number;
- billing_est_seedance_tokens_per_sec: number;
- billing_signup_grant_fen: number;
- quota_enabled: boolean;
- new_user_quota: number;
- billing_user_alert_enabled: boolean;
- billing_user_alert_interval_fen: number;
- billing_admin_cost_alert_enabled: boolean;
- billing_admin_cost_alert_threshold_fen: number;
- billing_admin_cost_alert_emails: string;
- billing_admin_cost_alert_period: string;
- billing_admin_cost_alert_last_period_key: string;
- billing_admin_cost_alert_last_level: number;
- smtp_enabled: boolean;
- smtp_host: string;
- smtp_port: number;
- smtp_user: string;
- smtp_password: string;
- smtp_from: string;
- smtp_use_tls: boolean;
- has_smtp_password: boolean;
- public_base_url: string;
- ffmpeg_path: string;
- ffprobe_path: string;
- source: string;
- updated_at?: string | null;
- readiness: ModelCapabilityReadiness[];
-};
-
-export type AdminRoutingChannel = {
- id: string;
- name: string;
- base_url: string;
- api_key: string;
- has_api_key: boolean;
- api_format: "openai";
- protocol: "auto" | "openai";
- models: string[];
- enabled: boolean;
- sort_order: number;
-};
-
-export type AdminLogicalModelBinding = {
- id: string;
- channel_id: string;
- upstream_model: string;
- enabled: boolean;
- priority: number;
- weight?: number | null;
-};
-
-export type AdminLogicalModel = {
- id: string;
- name: string;
- capability: "text" | "image" | "video" | "audio";
- enabled: boolean;
- bindings: AdminLogicalModelBinding[];
-};
-
-export type AdminDefaultModels = {
- text_model: string;
- image_model: string;
- video_model: string;
- audio_model: string;
-};
-
-export type AdminRoutingSettings = {
- system_channels: AdminRoutingChannel[];
- logical_models: AdminLogicalModel[];
- default_models: AdminDefaultModels;
- validation_errors: string[];
- updated_at?: string | null;
-};
-
-export type AdminTemplate = {
- id: string;
- name: string;
- description: string;
- category: string[];
- preview_cover: string;
- style_prefix: string;
- negative_prompt: string;
- default_ratio: string;
- shot_duration_min: number;
- shot_duration_max: number;
- llm_system_addon: string;
- seedream_config: Record<string, unknown>;
- seedance_config: Record<string, unknown>;
- audio_config: Record<string, unknown>;
- subtitle_config: Record<string, unknown>;
- sort_order: number;
- is_active: boolean;
- is_premium: boolean;
-};
+// 保持既有导入路径兼容,新增接口类型按领域存放在 types/。
+export type * from "./types/common";
+export type * from "./types/analytics";
+export type * from "./types/finance";
+export type * from "./types/projects";
+export type * from "./types/tasks";
+export type * from "./types/settings";
diff --git a/admin/src/api/finance.ts b/admin/src/api/finance.ts
new file mode 100644
index 0000000..59bf71b
--- /dev/null
+++ b/admin/src/api/finance.ts
@@ -0,0 +1,65 @@
+import { api } from "./client";
+import type { PageResult } from "./types/common";
+import type { AdminLedger, AdminOrder, AdminUsageEventListRes } from "./types/finance";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
+
+/** 财务列表共享分页条件;嵌入用户详情时可使用更小的 pageSize。 */
+type ListFilters = { userId?: number | null; pageSize?: number };
+type OrderFilters = ListFilters & { status?: string; outTradeNo?: string };
+type LedgerFilters = ListFilters & { kind?: string; refType?: string; dateFrom?: string; dateTo?: string };
+type UsageFilters = ListFilters & {
+ taskRunId?: string;
+ domain?: string;
+ billingKey?: string;
+ capability?: string;
+ model?: string;
+ billingBasis?: string;
+ dateFrom?: string;
+ dateTo?: string;
+};
+
+/** 为财务列表构造服务端分页与用户条件。 */
+function listParams(page: number, filters: ListFilters): URLSearchParams {
+ const params = new URLSearchParams({
+ page: String(page),
+ page_size: String(filters.pageSize ?? DEFAULT_PAGE_SIZE),
+ });
+ if (filters.userId) params.set("user_id", String(filters.userId));
+ return params;
+}
+
+/** 按上海日历日设置时间边界,避免无时区时间被当成 UTC。 */
+function setDateRange(params: URLSearchParams, from?: string, to?: string): void {
+ if (from?.trim()) params.set("created_from", `${from.trim()}T00:00:00+08:00`);
+ if (to?.trim()) params.set("created_to", `${to.trim()}T23:59:59+08:00`);
+}
+
+/** 查询充值订单;商户单号筛选也供跨页深链定位使用。 */
+export function listAdminOrders(page = 1, filters: OrderFilters = {}): Promise<PageResult<AdminOrder>> {
+ const params = listParams(page, filters);
+ if (filters.status) params.set("status", filters.status);
+ if (filters.outTradeNo) params.set("out_trade_no", filters.outTradeNo);
+ return api(`/api/admin/orders?${params}`);
+}
+
+/** 查询钱包流水,支持调账记录与用户详情复用同一接口映射。 */
+export function listAdminLedger(page = 1, filters: LedgerFilters = {}): Promise<PageResult<AdminLedger>> {
+ const params = listParams(page, filters);
+ if (filters.kind) params.set("kind", filters.kind);
+ if (filters.refType) params.set("ref_type", filters.refType);
+ setDateRange(params, filters.dateFrom, filters.dateTo);
+ return api(`/api/admin/ledger?${params}`);
+}
+
+/** 查询 AI 用量明细,集中维护后端筛选参数与日期边界。 */
+export function listAdminUsageEvents(page = 1, filters: UsageFilters = {}): Promise<AdminUsageEventListRes> {
+ const params = listParams(page, filters);
+ if (filters.taskRunId) params.set("task_run_id", filters.taskRunId);
+ if (filters.domain) params.set("domain", filters.domain);
+ if (filters.billingKey) params.set("billing_key", filters.billingKey);
+ if (filters.capability) params.set("capability", filters.capability);
+ if (filters.model) params.set("model", filters.model);
+ if (filters.billingBasis) params.set("billing_basis", filters.billingBasis);
+ setDateRange(params, filters.dateFrom, filters.dateTo);
+ return api(`/api/admin/usage-events?${params}`);
+}
diff --git a/admin/src/api/types/analytics.ts b/admin/src/api/types/analytics.ts
new file mode 100644
index 0000000..5da3c78
--- /dev/null
+++ b/admin/src/api/types/analytics.ts
@@ -0,0 +1,94 @@
+/** 运营看板、官方用量对账与按日财务统计的接口契约。 */
+export type AdminUsageBucket = {
+ key: string;
+ calls: number;
+ charge_fen: number;
+ cost_fen?: number;
+};
+
+export type AdminDailyUsage = {
+ date: string;
+ calls: number;
+ charge_fen: number;
+ cost_fen?: number;
+};
+
+export type AdminTopUser = {
+ user_id: number;
+ email?: string | null;
+ calls: number;
+ charge_fen: number;
+ cost_fen?: number;
+};
+
+export type AdminStats = {
+ user_count: number;
+ order_paid_total_fen: number;
+ order_paid_today_fen: number;
+ project_status_counts: Record<string, number>;
+ drama_project_count?: number;
+ usage_calls_today?: number;
+ usage_calls_month?: number;
+ usage_calls_total?: number;
+ usage_charge_today_fen?: number;
+ usage_charge_month_fen?: number;
+ usage_charge_total_fen?: number;
+ usage_cost_today_fen?: number;
+ usage_cost_month_fen?: number;
+ usage_cost_total_fen?: number;
+ usage_by_capability?: AdminUsageBucket[];
+ usage_by_domain?: AdminUsageBucket[];
+ daily_usage?: AdminDailyUsage[];
+ top_users_by_charge?: AdminTopUser[];
+};
+
+export type AdminUpstreamUsageDay = {
+ date: string;
+ local_cost_fen: number;
+ local_tokens: number;
+ official_tokens: number;
+ official_cost_fen: number;
+ delta_fen: number;
+ delta_pct?: number | null;
+};
+
+export type AdminUpstreamUsage = {
+ configured: boolean;
+ days: number;
+ last_sync_at?: string | null;
+ series: AdminUpstreamUsageDay[];
+};
+
+export type AdminUpstreamUsageSync = {
+ configured: boolean;
+ synced: number;
+ skipped: number;
+ last_sync_at?: string | null;
+};
+
+export type AdminFinanceDailyRow = {
+ date: string;
+ charge_fen: number;
+ cost_fen: number;
+ tokens: number;
+ actual_cost_fen: number;
+ profit_fen: number;
+ profit_pct?: number | null;
+};
+
+export type AdminFinanceDailyTotals = {
+ charge_fen: number;
+ cost_fen: number;
+ tokens: number;
+ actual_cost_fen: number;
+ profit_fen: number;
+ profit_pct?: number | null;
+};
+
+export type AdminFinanceDaily = {
+ configured: boolean;
+ days: number;
+ last_sync_at?: string | null;
+ totals: AdminFinanceDailyTotals;
+ series: AdminFinanceDailyRow[];
+};
diff --git a/admin/src/api/types/common.ts b/admin/src/api/types/common.ts
new file mode 100644
index 0000000..fe83cff
--- /dev/null
+++ b/admin/src/api/types/common.ts
@@ -0,0 +1,9 @@
+/** 管理接口通用分页元信息;列表仍由服务端筛选和分页。 */
+export type PageMeta = {
+ page: number;
+ page_size: number;
+ total: number;
+};
+
+/** 服务端分页列表的统一响应结构。 */
+export type PageResult<T> = { items: T[]; meta: PageMeta };
diff --git a/admin/src/api/types/finance.ts b/admin/src/api/types/finance.ts
new file mode 100644
index 0000000..a275f0b
--- /dev/null
+++ b/admin/src/api/types/finance.ts
@@ -0,0 +1,75 @@
+import type { PageMeta } from "./common";
+
+/** 充值订单、钱包流水与用量明细的接口契约;金额单位均为分。 */
+export type AdminOrder = {
+ id: number;
+ out_trade_no: string;
+ user_id: number;
+ user_email?: string | null;
+ sku_id: string;
+ amount_fen: number;
+ credit_fen: number;
+ pay_type: string;
+ status: string;
+ trade_no?: string | null;
+ paid_at?: string | null;
+ created_at: string;
+};
+
+export type AdminLedger = {
+ id: number;
+ user_id: number;
+ user_email?: string | null;
+ delta_fen: number;
+ balance_after: number;
+ kind: string;
+ ref_type: string;
+ ref_id: string;
+ note: string;
+ created_at: string;
+ /** 手动调账操作人邮箱(ref_type=admin 时) */
+ operator_email?: string | null;
+};
+
+export type AdminUsageEventBrief = {
+ id: number;
+ billing_key: string;
+ capability?: string | null;
+ model?: string;
+ total_tokens?: number;
+ charge_fen?: number;
+ cost_fen?: number;
+ estimated?: boolean;
+ billing_basis?: string;
+ billing_basis_label?: string;
+ created_at?: string | null;
+};
+
+export type AdminUsageEvent = {
+ id: number;
+ user_id: number;
+ user_email?: string | null;
+ task_run_id?: number | null;
+ domain?: string | null;
+ capability?: string | null;
+ billing_key: string;
+ model?: string;
+ total_tokens?: number;
+ charge_fen?: number;
+ cost_fen?: number;
+ estimated?: boolean;
+ billing_basis?: string;
+ billing_basis_label?: string;
+ created_at?: string | null;
+ task_domain?: string | null;
+ task_type?: string | null;
+ task_status?: string | null;
+ project_id?: number | null;
+ drama_project_id?: number | null;
+ provider?: string | null;
+};
+
+export type AdminUsageEventListRes = {
+ items: AdminUsageEvent[];
+ meta: PageMeta;
+};
diff --git a/admin/src/api/types/projects.ts b/admin/src/api/types/projects.ts
new file mode 100644
index 0000000..57331f5
--- /dev/null
+++ b/admin/src/api/types/projects.ts
@@ -0,0 +1,197 @@
+/** 用户、科普项目、漫剧资产与模板的管理端接口契约。 */
+export type AdminProjectUsage = {
+ charge_fen: number;
+ cost_fen: number;
+ tokens: number;
+ calls: number;
+ image_gens: number;
+ video_gens: number;
+ llm_calls: number;
+ tts_gens?: number;
+};
+
+export type AdminTaskBrief = {
+ id: number;
+ domain: string;
+ task_type: string;
+ status: string;
+ progress_percent: number;
+ billing_charged_fen: number;
+ billing_estimate_fen: number;
+ error_message?: string | null;
+ created_at?: string | null;
+ finished_at?: string | null;
+};
+
+export type AdminShotBrief = {
+ id: number;
+ shot_no: number;
+ status: string;
+ has_image: boolean;
+ has_video: boolean;
+ has_audio: boolean;
+ duration: number;
+};
+
+export type AdminUserRow = {
+ id: number;
+ email: string;
+ nickname: string;
+ phone?: string;
+ quota_left: number;
+ balance_fen: number;
+ frozen_fen: number;
+ plan: string;
+ role: string;
+ created_at?: string | null;
+};
+
+export type AdminProject = {
+ id: number;
+ user_id: number;
+ user_email?: string | null;
+ template_id: string;
+ title: string;
+ status: string;
+ progress: number;
+ error_msg?: string | null;
+ cover_url?: string | null;
+ final_video_url?: string | null;
+ pipeline_mode: string;
+ created_at: string;
+ updated_at: string;
+ shot_count: number;
+ charge_fen?: number;
+ source_type?: string;
+ source_text?: string;
+ resolution_mode?: string;
+ output_ratio?: string;
+ voice_id?: string;
+ usage?: AdminProjectUsage;
+ shots?: AdminShotBrief[];
+ recent_tasks?: AdminTaskBrief[];
+};
+
+export type AdminDramaProject = {
+ id: number;
+ user_id: number;
+ user_email?: string | null;
+ title: string;
+ description?: string | null;
+ created_at?: string | null;
+ updated_at?: string | null;
+ episode_count?: number;
+ asset_count?: number;
+ fragment_count?: number;
+ charge_fen?: number;
+ summary_status?: string | null;
+ assets_seed_status?: string | null;
+ episode_content_status?: string | null;
+ usage?: AdminProjectUsage;
+ episodes?: { id: number; name: string; fragment_count: number; fragment_plan_status?: string | null }[];
+ assets?: {
+ id: number;
+ type: string;
+ name?: string | null;
+ has_cover: boolean;
+ generation_status?: string | null;
+ }[];
+ recent_tasks?: AdminTaskBrief[];
+};
+
+export type AdminDramaAsset = {
+ id: number;
+ project_id: number;
+ project_title?: string | null;
+ user_id?: number | null;
+ user_email?: string | null;
+ type: string;
+ asset_type: string;
+ name?: string | null;
+ cover?: string | null;
+ url?: string | null;
+ has_cover: boolean;
+ generation_status?: string | null;
+ derive_id?: string | null;
+ created_at?: string | null;
+ updated_at?: string | null;
+ params?: Record<string, unknown> | null;
+};
+
+export type AdminDramaEpisode = {
+ id: number;
+ project_id: number;
+ project_title?: string | null;
+ user_id?: number | null;
+ user_email?: string | null;
+ name: string;
+ fragment_count: number;
+ fragment_plan_status?: string | null;
+ created_at?: string | null;
+ updated_at?: string | null;
+ fragments?: {
+ id: number;
+ sort_order: number;
+ content: string;
+ cover: string;
+ video: string;
+ duration_sec?: number | null;
+ generation_status?: string | null;
+ asset_ref_count: number;
+ }[];
+};
+
+export type AdminDramaFragment = {
+ id: number;
+ episode_id: number;
+ episode_name?: string | null;
+ project_id: number;
+ project_title?: string | null;
+ user_id?: number | null;
+ user_email?: string | null;
+ sort_order: number;
+ content: string;
+ cover: string;
+ video: string;
+ duration_sec?: number | null;
+ generation_status?: string | null;
+ asset_ref_count: number;
+ created_at?: string | null;
+ updated_at?: string | null;
+ params?: Record<string, unknown> | null;
+ asset_ids?: number[];
+};
+
+export type AdminWork = {
+ id: number;
+ project_id: number;
+ user_id: number;
+ user_email?: string | null;
+ title: string;
+ cover_url?: string | null;
+ video_url: string;
+ visibility: string;
+ audit_status: string;
+ published_at: string;
+};
+
+export type AdminTemplate = {
+ id: string;
+ name: string;
+ description: string;
+ category: string[];
+ preview_cover: string;
+ style_prefix: string;
+ negative_prompt: string;
+ default_ratio: string;
+ shot_duration_min: number;
+ shot_duration_max: number;
+ llm_system_addon: string;
+ seedream_config: Record<string, unknown>;
+ seedance_config: Record<string, unknown>;
+ audio_config: Record<string, unknown>;
+ subtitle_config: Record<string, unknown>;
+ sort_order: number;
+ is_active: boolean;
+ is_premium: boolean;
+};
diff --git a/admin/src/api/types/settings.ts b/admin/src/api/types/settings.ts
new file mode 100644
index 0000000..928131a
--- /dev/null
+++ b/admin/src/api/types/settings.ts
@@ -0,0 +1,146 @@
+/** 模型路由、运行时、存储、支付与站点设置的接口契约。 */
+export type ModelCapabilityReadiness = {
+ capability: string;
+ label: string;
+ model: string;
+ ready: boolean;
+ message: string;
+};
+
+export type AdminModelSettings = {
+ openai_api_key: string;
+ openai_base_url: string;
+ model_llm: string;
+ has_openai_api_key: boolean;
+ ark_api_key: string;
+ ark_base_url: string;
+ model_image: string;
+ model_image_45: string;
+ model_video: string;
+ model_audio: string;
+ has_ark_api_key: boolean;
+ ark_image_size: string;
+ ark_video_resolution: string;
+ ark_video_ratio: string;
+ seedance_duration_min: number;
+ seedance_duration_max: number;
+ ark_video_poll_interval: number;
+ ark_video_poll_timeout: number;
+ pipeline_image_concurrency: number;
+ pipeline_video_concurrency: number;
+ pipeline_audio_concurrency: number;
+ task_runtime_max_concurrency: number;
+ task_user_max_concurrency: number;
+ task_poll_max_concurrency: number;
+ drama_user_video_job_limit: number;
+ drama_fragment_max_attempts: number;
+ ark_mock: boolean;
+ oss_enabled: boolean;
+ oss_endpoint: string;
+ oss_region: string;
+ oss_bucket: string;
+ oss_folder: string;
+ oss_access_key_id: string;
+ oss_access_key_secret: string;
+ oss_public_base: string;
+ oss_upload_async: boolean;
+ oss_upload_queue: string;
+ has_oss_access_key_id: boolean;
+ has_oss_access_key_secret: boolean;
+ tos_endpoint: string;
+ tos_bucket: string;
+ tos_access_key: string;
+ tos_secret_key: string;
+ has_tos_access_key: boolean;
+ has_tos_secret_key: boolean;
+ cdn_base: string;
+ epay_api_url: string;
+ epay_pid: string;
+ epay_key: string;
+ epay_notify_url: string;
+ epay_return_url: string;
+ has_epay_key: boolean;
+ billing_enabled: boolean;
+ billing_markup: number;
+ billing_estimate_buffer: number;
+ billing_seedance_video0: number;
+ billing_seedance_video1: number;
+ billing_llm_per_m: number;
+ billing_seedream_per_m: number;
+ billing_tts_per_m: number;
+ billing_kie_fen_per_credit: number;
+ billing_est_llm_tokens: number;
+ billing_est_seedream_tokens: number;
+ billing_est_tts_tokens: number;
+ billing_est_seedance_tokens_per_sec: number;
+ billing_signup_grant_fen: number;
+ quota_enabled: boolean;
+ new_user_quota: number;
+ billing_user_alert_enabled: boolean;
+ billing_user_alert_interval_fen: number;
+ billing_admin_cost_alert_enabled: boolean;
+ billing_admin_cost_alert_threshold_fen: number;
+ billing_admin_cost_alert_emails: string;
+ billing_admin_cost_alert_period: string;
+ billing_admin_cost_alert_last_period_key: string;
+ billing_admin_cost_alert_last_level: number;
+ smtp_enabled: boolean;
+ smtp_host: string;
+ smtp_port: number;
+ smtp_user: string;
+ smtp_password: string;
+ smtp_from: string;
+ smtp_use_tls: boolean;
+ has_smtp_password: boolean;
+ public_base_url: string;
+ ffmpeg_path: string;
+ ffprobe_path: string;
+ source: string;
+ updated_at?: string | null;
+ readiness: ModelCapabilityReadiness[];
+};
+
+export type AdminRoutingChannel = {
+ id: string;
+ name: string;
+ base_url: string;
+ api_key: string;
+ has_api_key: boolean;
+ api_format: "openai";
+ protocol: "auto" | "openai";
+ models: string[];
+ enabled: boolean;
+ sort_order: number;
+};
+
+export type AdminLogicalModelBinding = {
+ id: string;
+ channel_id: string;
+ upstream_model: string;
+ enabled: boolean;
+ priority: number;
+ weight?: number | null;
+};
+
+export type AdminLogicalModel = {
+ id: string;
+ name: string;
+ capability: "text" | "image" | "video" | "audio";
+ enabled: boolean;
+ bindings: AdminLogicalModelBinding[];
+};
+
+export type AdminDefaultModels = {
+ text_model: string;
+ image_model: string;
+ video_model: string;
+ audio_model: string;
+};
+
+export type AdminRoutingSettings = {
+ system_channels: AdminRoutingChannel[];
+ logical_models: AdminLogicalModel[];
+ default_models: AdminDefaultModels;
+ validation_errors: string[];
+ updated_at?: string | null;
+};
diff --git a/admin/src/api/types/tasks.ts b/admin/src/api/types/tasks.ts
new file mode 100644
index 0000000..4d78063
--- /dev/null
+++ b/admin/src/api/types/tasks.ts
@@ -0,0 +1,112 @@
+import type { PageMeta } from "./common";
+import type { AdminUsageEventBrief } from "./finance";
+
+/** 统一任务平台的任务、步骤、事件与运行统计接口契约。 */
+export type AdminTaskRow = {
+ id: number;
+ domain: string;
+ task_type: string;
+ status: string;
+ priority: number;
+ requested_by: number;
+ user_email?: string | null;
+ progress_percent: number;
+ cancel_requested: boolean;
+ cancelable: boolean;
+ current_step_key?: string | null;
+ current_step_status?: string | null;
+ error_message?: string | null;
+ project_id?: number | null;
+ drama_project_id?: number | null;
+ episode_id?: number | null;
+ fragment_id?: number | null;
+ asset_id?: number | null;
+ script_id?: number | null;
+ created_at?: string | null;
+ started_at?: string | null;
+ finished_at?: string | null;
+ billing_estimate_fen?: number;
+ billing_charged_fen?: number;
+ billing_refunded_fen?: number;
+ billing_status?: string;
+ /** 提交参数(入队 payload) */
+ payload?: Record<string, unknown> | null;
+ /** 执行结果 */
+ result_payload?: Record<string, unknown> | null;
+};
+
+export type AdminTaskStep = {
+ id: number;
+ step_key: string;
+ step_type: string;
+ status: string;
+ attempt_count: number;
+ provider_name?: string | null;
+ provider_task_id?: string | null;
+ error_message?: string | null;
+ started_at?: string | null;
+ finished_at?: string | null;
+};
+
+export type AdminTaskEvent = {
+ id: number;
+ event_type: string;
+ status?: string | null;
+ phase?: string | null;
+ message?: string | null;
+ payload?: Record<string, unknown> | null;
+ created_at?: string | null;
+};
+
+export type AdminTaskDetail = AdminTaskRow & {
+ client_request_id?: string | null;
+ dedupe_key?: string | null;
+ batch_key?: string | null;
+ provider_task_id?: string | null;
+ scheduled_at?: string | null;
+ next_action_at?: string | null;
+ lease_until?: string | null;
+ error_code?: string | null;
+ payload?: Record<string, unknown> | null;
+ result_payload?: Record<string, unknown> | null;
+ script_id?: number | null;
+ asset_id?: number | null;
+ shot_id?: number | null;
+ updated_at?: string | null;
+ steps: AdminTaskStep[];
+ events: AdminTaskEvent[];
+ targets: Array<{ id: number; target_type: string; target_id: number }>;
+ usage_lines?: AdminUsageEventBrief[];
+ billing_estimate_fen?: number;
+ billing_charged_fen?: number;
+ billing_refunded_fen?: number;
+ billing_status?: string;
+};
+
+export type AdminTaskStats = {
+ pending_count: number;
+ active_count: number;
+ leased_count: number;
+ running_count: number;
+ awaiting_poll_count: number;
+ cancel_requested_count: number;
+ succeeded_count: number;
+ failed_count: number;
+ cancelled_count: number;
+ scheduler_running_jobs: number;
+ max_concurrency: number;
+ domains: Array<{
+ domain: string;
+ pending: number;
+ active: number;
+ succeeded: number;
+ failed: number;
+ cancelled: number;
+ }>;
+ fetched_at?: string | null;
+};
+
+export type AdminTaskListRes = {
+ items: AdminTaskRow[];
+ meta: PageMeta;
+};
diff --git a/admin/src/assets/hero.png b/admin/src/assets/hero.png
deleted file mode 100644
index 02251f4..0000000
Binary files a/admin/src/assets/hero.png and /dev/null differ
diff --git a/admin/src/assets/react.svg b/admin/src/assets/react.svg
deleted file mode 100644
index 6c87de9..0000000
--- a/admin/src/assets/react.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
\ No newline at end of file
diff --git a/admin/src/assets/vite.svg b/admin/src/assets/vite.svg
deleted file mode 100644
index 5101b67..0000000
--- a/admin/src/assets/vite.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="g" width="74.749" height="58.852" x="29.961" y="-17.13" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="h" width="61.377" height="25.362" x="37.754" y="3.055" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="i" width="61.377" height="25.362" x="37.754" y="3.055" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="j" width="56.045" height="63.649" x="-13.43" y="-22.082" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="k" width="54.814" height="64.646" x="34.321" y="-37.644" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="l" width="33.541" height="35.313" x="38.847" y="-10.552" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="m" width="54.814" height="64.646" x="-15.081" y="6.78" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="n" width="54.814" height="64.646" x="-15.081" y="6.78" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="o" width="54.814" height="64.646" x="22.45" y="-1.645" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="p" width="39.409" height="43.623" x="32.919" y="11.36" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter></defs></svg>
diff --git a/admin/src/components/admin/UserDetailDrawer.tsx b/admin/src/components/admin/UserDetailDrawer.tsx
index 9250e03..028756a 100644
--- a/admin/src/components/admin/UserDetailDrawer.tsx
+++ b/admin/src/components/admin/UserDetailDrawer.tsx
@@ -6,8 +6,9 @@ import {
type AdminOrder,
type AdminUsageEvent,
type AdminUserRow,
- type PageMeta,
+ type PageResult,
} from "@/api/client";
+import { listAdminLedger, listAdminOrders, listAdminUsageEvents } from "@/api/finance";
import {
AdminDetailMeta,
AdminDetailSection,
@@ -20,7 +21,7 @@ import { formatAccountId } from "@/lib/admin-account";
import { fenToYuan } from "@/lib/utils";
import { ledgerKindLabel, orderStatusLabel } from "@/lib/statusLabels";
-type ListRes<T> = { items: T[]; meta: PageMeta };
+type ListRes<T> = PageResult<T>;
type UserDetailDrawerProps = {
userId: number | null;
@@ -46,9 +47,9 @@ export function UserDetailDrawer({ userId, open, onOpenChange, initialUser }: Us
initialUser?.id === userId
? Promise.resolve({ items: [initialUser], meta: { page: 1, page_size: 1, total: 1 } })
: api<ListRes<AdminUserRow>>(`/api/admin/users?page=1&page_size=1&q=${userId}`),
- api<ListRes<AdminOrder>>(`/api/admin/orders?page=1&page_size=8&user_id=${userId}`),
- api<ListRes<AdminLedger>>(`/api/admin/ledger?page=1&page_size=8&user_id=${userId}`),
- api<ListRes<AdminUsageEvent>>(`/api/admin/usage-events?page=1&page_size=20&user_id=${userId}`),
+ listAdminOrders(1, { pageSize: 8, userId }),
+ listAdminLedger(1, { pageSize: 8, userId }),
+ listAdminUsageEvents(1, { pageSize: 20, userId }),
]);
setUser(userRes.items[0] ?? initialUser ?? null);
setOrders(orderRes.items);
diff --git a/admin/src/components/finance/FinanceDetailDialogs.tsx b/admin/src/components/finance/FinanceDetailDialogs.tsx
new file mode 100644
index 0000000..316cb49
--- /dev/null
+++ b/admin/src/components/finance/FinanceDetailDialogs.tsx
@@ -0,0 +1,145 @@
+import { Link } from "react-router-dom";
+import { toast } from "sonner";
+import type { AdminLedger, AdminOrder } from "@/api/client";
+import { AdminDetailMeta, AdminDetailSection } from "@/components/admin/AdminDetailLayout";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminModal } from "@/components/admin/AdminModal";
+import { Button } from "@/components/ui/button";
+import { fenToYuan } from "@/lib/utils";
+import { ledgerKindLabel, orderStatusLabel, payTypeLabel } from "@/lib/statusLabels";
+
+/** 钱包关联对象链接:兼容数字订单 ID 与历史商户单号。 */
+export function LedgerRefLink({ row }: { row: AdminLedger }) {
+ if (row.ref_type === "order" && row.ref_id) {
+ const id = Number(row.ref_id);
+ if (Number.isFinite(id) && id > 0) {
+ return <AdminEntityLink kind="order" id={id} label={`订单#${id}`} />;
+ }
+ return (
+ <Link
+ to={`/orders?tab=orders&trade=${encodeURIComponent(row.ref_id)}`}
+ className="admin-link font-mono text-xs"
+ >
+ {row.ref_id}
+ </Link>
+ );
+ }
+ if (!row.ref_type && !row.ref_id) return "—";
+ return (
+ <span className="font-mono text-xs">
+ {row.ref_type}/{row.ref_id}
+ </span>
+ );
+}
+
+/** 展示充值订单详情,复制单号与关闭行为由弹层管理。 */
+export function OrderDetailDialog({
+ orderDetail,
+ open,
+ onClose,
+}: { orderDetail: AdminOrder | null; open: boolean; onClose: () => void }) {
+ // 将商户单号写入剪贴板,并反馈复制结果。
+ async function copyText(text: string) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast.success("已复制");
+ } catch {
+ toast.error("复制失败");
+ }
+ }
+
+ return (
+ <AdminModal
+ open={open && !!orderDetail}
+ onOpenChange={(nextOpen) => !nextOpen && onClose()}
+ size="md"
+ title={orderDetail ? `订单明细 #${orderDetail.id}` : "订单明细"}
+ subtitle={orderDetail?.out_trade_no}
+ footer={
+ orderDetail ? (
+ <Button size="sm" variant="outline" onClick={() => void copyText(orderDetail.out_trade_no)}>
+ 复制商户单号
+ </Button>
+ ) : undefined
+ }
+ >
+ {orderDetail ? (
+ <AdminDetailSection>
+ <AdminDetailMeta
+ items={[
+ {
+ label: "用户",
+ value: (
+ <AdminEntityLink
+ kind="user"
+ id={orderDetail.user_id}
+ label={orderDetail.user_email ?? undefined}
+ />
+ ),
+ },
+ { label: "SKU", value: orderDetail.sku_id },
+ { label: "金额", value: `¥${fenToYuan(orderDetail.amount_fen)}` },
+ { label: "入账", value: `¥${fenToYuan(orderDetail.credit_fen)}` },
+ { label: "支付方式", value: payTypeLabel(orderDetail.pay_type) },
+ { label: "状态", value: orderStatusLabel(orderDetail.status) },
+ { label: "渠道单号", value: orderDetail.trade_no || "—" },
+ {
+ label: "支付时间",
+ value: orderDetail.paid_at ? new Date(orderDetail.paid_at).toLocaleString() : "—",
+ },
+ {
+ label: "创建时间",
+ value: new Date(orderDetail.created_at).toLocaleString(),
+ full: true,
+ },
+ ]}
+ />
+ </AdminDetailSection>
+ ) : null}
+ </AdminModal>
+ );
+}
+
+/** 展示钱包流水详情,复用列表中的关联对象链接。 */
+export function LedgerDetailDialog({
+ ledgerDetail,
+ onClose,
+}: { ledgerDetail: AdminLedger | null; onClose: () => void }) {
+ return (
+ <AdminModal
+ open={!!ledgerDetail}
+ onOpenChange={(nextOpen) => !nextOpen && onClose()}
+ size="md"
+ title={ledgerDetail ? `流水明细 #${ledgerDetail.id}` : "流水明细"}
+ >
+ {ledgerDetail ? (
+ <AdminDetailSection>
+ <AdminDetailMeta
+ items={[
+ {
+ label: "用户",
+ value: (
+ <AdminEntityLink
+ kind="user"
+ id={ledgerDetail.user_id}
+ label={ledgerDetail.user_email ?? undefined}
+ />
+ ),
+ },
+ { label: "类型", value: ledgerKindLabel(ledgerDetail.kind) },
+ { label: "变动", value: `¥${fenToYuan(ledgerDetail.delta_fen)}` },
+ { label: "余额后", value: `¥${fenToYuan(ledgerDetail.balance_after)}` },
+ { label: "关联", value: <LedgerRefLink row={ledgerDetail} /> },
+ { label: "备注", value: ledgerDetail.note || "—" },
+ {
+ label: "时间",
+ value: new Date(ledgerDetail.created_at).toLocaleString(),
+ full: true,
+ },
+ ]}
+ />
+ </AdminDetailSection>
+ ) : null}
+ </AdminModal>
+ );
+}
diff --git a/admin/src/pages/AdjustRecordsPage.tsx b/admin/src/pages/AdjustRecordsPage.tsx
index 3bd5aba..19bb4b4 100644
--- a/admin/src/pages/AdjustRecordsPage.tsx
+++ b/admin/src/pages/AdjustRecordsPage.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
-import { api, type AdminLedger, type PageMeta } from "@/api/client";
+import type { AdminLedger, PageResult } from "@/api/client";
+import { listAdminLedger } from "@/api/finance";
import { AdminDateRangeFilter } from "@/components/admin/AdminDateRangeFilter";
import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
@@ -12,19 +13,12 @@ import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page";
import { Select } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
-import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { fenToYuan } from "@/lib/utils";
-type LedgerRes = { items: AdminLedger[]; meta: PageMeta };
+type LedgerRes = PageResult<AdminLedger>;
type DirectionFilter = "" | "credit" | "debit";
-/** 将 YYYY-MM-DD 转为东八区 ISO 边界(与订单用量筛选一致) */
-function toDayBoundary(date: string, endOfDay: boolean): string | null {
- if (!date.trim()) return null;
- return endOfDay ? `${date.trim()}T23:59:59+08:00` : `${date.trim()}T00:00:00+08:00`;
-}
-
/** 调账方向文案:正数为调增,负数为调减 */
function directionLabel(deltaFen: number): string {
return deltaFen >= 0 ? "调增" : "调减";
@@ -44,20 +38,14 @@ export function AdjustRecordsPage() {
async (nextPage = page) => {
setLoading(true);
try {
- const params = new URLSearchParams({
- page: String(nextPage),
- page_size: String(DEFAULT_PAGE_SIZE),
- ref_type: "admin",
- });
- if (userId) params.set("user_id", String(userId));
- // 后台写流水:调减 kind=adjust,调增 kind=grant
- if (direction === "credit") params.set("kind", "grant");
- if (direction === "debit") params.set("kind", "adjust");
- const fromIso = toDayBoundary(dateFrom, false);
- const toIso = toDayBoundary(dateTo, true);
- if (fromIso) params.set("created_from", fromIso);
- if (toIso) params.set("created_to", toIso);
- setData(await api<LedgerRes>(`/api/admin/ledger?${params}`));
+ // 后台写流水:调减 kind=adjust,调增 kind=grant。
+ setData(await listAdminLedger(nextPage, {
+ refType: "admin",
+ userId,
+ kind: direction === "credit" ? "grant" : direction === "debit" ? "adjust" : "",
+ dateFrom,
+ dateTo,
+ }));
} catch (err) {
setData(null);
toast.error(err instanceof Error ? err.message : "加载调账记录失败");
diff --git a/admin/src/pages/OrdersPage.tsx b/admin/src/pages/OrdersPage.tsx
index 0eb8b9a..7d75927 100644
--- a/admin/src/pages/OrdersPage.tsx
+++ b/admin/src/pages/OrdersPage.tsx
@@ -1,15 +1,14 @@
import { useEffect, useState } from "react";
-import { Link, useSearchParams } from "react-router-dom";
+import { useSearchParams } from "react-router-dom";
import { toast } from "sonner";
-import { api, type AdminLedger, type AdminOrder, type AdminUsageEventListRes, type PageMeta } from "@/api/client";
+import type { AdminLedger, AdminOrder, AdminUsageEventListRes, PageResult } from "@/api/client";
+import { listAdminLedger, listAdminOrders, listAdminUsageEvents } from "@/api/finance";
import { AdminDateRangeFilter } from "@/components/admin/AdminDateRangeFilter";
-import { AdminDetailMeta, AdminDetailSection } from "@/components/admin/AdminDetailLayout";
import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
-import { AdminModal } from "@/components/admin/AdminModal";
import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
+import { LedgerDetailDialog, LedgerRefLink, OrderDetailDialog } from "@/components/finance/FinanceDetailDialogs";
import { PaginationBar } from "@/components/PaginationBar";
-import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -21,40 +20,19 @@ import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";
import { fenToYuan } from "@/lib/utils";
import { ledgerKindLabel, orderStatusLabel, payTypeLabel, taskDomainLabel } from "@/lib/statusLabels";
-type OrderRes = { items: AdminOrder[]; meta: PageMeta };
-type LedgerRes = { items: AdminLedger[]; meta: PageMeta };
+type OrderRes = PageResult<AdminOrder>;
+type LedgerRes = PageResult<AdminLedger>;
const ORDER_TABS = new Set(["orders", "ledger", "usage"]);
+// 将 URL 中的 Tab 限定为已有的财务列表,兼容无参数入口。
function tabFromSearch(raw: string | null): string {
return raw && ORDER_TABS.has(raw) ? raw : "orders";
}
-function ledgerRefLink(row: AdminLedger) {
- if (row.ref_type === "order" && row.ref_id) {
- const id = Number(row.ref_id);
- if (Number.isFinite(id) && id > 0) {
- return <AdminEntityLink kind="order" id={id} label={`订单#${id}`} />;
- }
- return (
- <Link
- to={`/orders?tab=orders&trade=${encodeURIComponent(row.ref_id)}`}
- className="admin-link font-mono text-xs"
- >
- {row.ref_id}
- </Link>
- );
- }
- if (!row.ref_type && !row.ref_id) return "—";
- return (
- <span className="font-mono text-xs">
- {row.ref_type}/{row.ref_id}
- </span>
- );
-}
-
// 充值订单、钱包流水与用量明细
export function OrdersPage() {
+ // 列表筛选与分页分别保留,切换 Tab 不清空其他列表状态。
const [searchParams, setSearchParams] = useSearchParams();
const [tab, setTab] = useState(() => tabFromSearch(searchParams.get("tab")));
const [orderStatus, setOrderStatus] = useState("");
@@ -80,48 +58,41 @@ export function OrdersPage() {
const [ledgerDetail, setLedgerDetail] = useState<AdminLedger | null>(null);
const orderQuery = useAdminDetailQuery("order");
+ // 按当前筛选加载充值订单,分页仍由服务端完成。
async function loadOrders(page = orderPage) {
try {
- const params = new URLSearchParams({ page: String(page), page_size: String(DEFAULT_PAGE_SIZE) });
- if (orderStatus) params.set("status", orderStatus);
- if (orderUserId) params.set("user_id", String(orderUserId));
- setOrders(await api<OrderRes>(`/api/admin/orders?${params}`));
+ setOrders(await listAdminOrders(page, { status: orderStatus, userId: orderUserId }));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载订单失败");
}
}
+ // 加载钱包流水;与调账页、用户详情共享请求参数映射。
async function loadLedger(page = ledgerPage) {
try {
- const params = new URLSearchParams({ page: String(page), page_size: String(DEFAULT_PAGE_SIZE) });
- if (ledgerKind) params.set("kind", ledgerKind);
- if (ledgerUserId) params.set("user_id", String(ledgerUserId));
- setLedger(await api<LedgerRes>(`/api/admin/ledger?${params}`));
+ setLedger(await listAdminLedger(page, { kind: ledgerKind, userId: ledgerUserId }));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载流水失败");
}
}
+ // 支持快捷筛选覆盖尚未提交到 React state 的用量条件。
async function loadUsage(
page = usagePage,
overrides?: { billing_key?: string; capability?: string; model?: string },
) {
try {
- const params = new URLSearchParams({ page: String(page), page_size: String(DEFAULT_PAGE_SIZE) });
- if (usageUserId) params.set("user_id", String(usageUserId));
- if (usageTaskId.trim()) params.set("task_run_id", usageTaskId.trim());
- if (usageDomain) params.set("domain", usageDomain);
- const billingKey = overrides?.billing_key ?? usageBillingKey.trim();
- const capability = overrides?.capability ?? usageCapability.trim();
- const model = overrides?.model ?? usageModel.trim();
- if (billingKey) params.set("billing_key", billingKey);
- if (capability) params.set("capability", capability);
- if (model) params.set("model", model);
- if (usageBasis) params.set("billing_basis", usageBasis);
- // 按东八区日历日筛选,避免 naive 时间被当成 UTC 漏掉上午用量
- if (usageDateFrom) params.set("created_from", `${usageDateFrom}T00:00:00+08:00`);
- if (usageDateTo) params.set("created_to", `${usageDateTo}T23:59:59+08:00`);
- setUsage(await api<AdminUsageEventListRes>(`/api/admin/usage-events?${params}`));
+ setUsage(await listAdminUsageEvents(page, {
+ userId: usageUserId,
+ taskRunId: usageTaskId.trim(),
+ domain: usageDomain,
+ billingKey: overrides?.billing_key ?? usageBillingKey.trim(),
+ capability: overrides?.capability ?? usageCapability.trim(),
+ model: overrides?.model ?? usageModel.trim(),
+ billingBasis: usageBasis,
+ dateFrom: usageDateFrom,
+ dateTo: usageDateTo,
+ }));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载用量失败");
}
@@ -158,9 +129,7 @@ export function OrdersPage() {
if (!tradeNo) return;
void (async () => {
try {
- const res = await api<OrderRes>(
- `/api/admin/orders?page=1&page_size=1&out_trade_no=${encodeURIComponent(tradeNo)}`,
- );
+ const res = await listAdminOrders(1, { pageSize: 1, outTradeNo: tradeNo });
const hit = res.items[0];
if (hit) {
setOrderDetail(hit);
@@ -173,6 +142,7 @@ export function OrdersPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchParams]);
+ // 将激活列表同步到 URL,保证刷新和跨页深链保持一致。
function onTabChange(next: string) {
setTab(next);
const params = new URLSearchParams(searchParams);
@@ -181,15 +151,6 @@ export function OrdersPage() {
setSearchParams(params, { replace: true });
}
- async function copyText(text: string) {
- try {
- await navigator.clipboard.writeText(text);
- toast.success("已复制");
- } catch {
- toast.error("复制失败");
- }
- }
-
return (
<div className="admin-list-page">
<PageHeader description="查看充值单、钱包流水与 AI 用量明细" />
@@ -336,7 +297,7 @@ export function OrdersPage() {
<TableCell>
<Badge variant="secondary">{ledgerKindLabel(e.kind)}</Badge>
</TableCell>
- <TableCell>{ledgerRefLink(e)}</TableCell>
+ <TableCell><LedgerRefLink row={e} /></TableCell>
<TableCell className="max-w-[200px] truncate">{e.note}</TableCell>
<TableCell className="text-xs text-muted-foreground">
{new Date(e.created_at).toLocaleString()}
@@ -520,95 +481,15 @@ export function OrdersPage() {
</TabsContent>
</Tabs>
- <AdminModal
- open={orderQuery.isOpen && !!orderDetail}
- onOpenChange={(open) => {
- if (!open) {
- setOrderDetail(null);
- orderQuery.close();
- }
+ <OrderDetailDialog
+ orderDetail={orderDetail}
+ open={orderQuery.isOpen}
+ onClose={() => {
+ setOrderDetail(null);
+ orderQuery.close();
}}
- size="md"
- title={orderDetail ? `订单明细 #${orderDetail.id}` : "订单明细"}
- subtitle={orderDetail?.out_trade_no}
- footer={
- orderDetail ? (
- <Button size="sm" variant="outline" onClick={() => void copyText(orderDetail.out_trade_no)}>
- 复制商户单号
- </Button>
- ) : undefined
- }
- >
- {orderDetail ? (
- <AdminDetailSection>
- <AdminDetailMeta
- items={[
- {
- label: "用户",
- value: (
- <AdminEntityLink
- kind="user"
- id={orderDetail.user_id}
- label={orderDetail.user_email ?? undefined}
- />
- ),
- },
- { label: "SKU", value: orderDetail.sku_id },
- { label: "金额", value: `¥${fenToYuan(orderDetail.amount_fen)}` },
- { label: "入账", value: `¥${fenToYuan(orderDetail.credit_fen)}` },
- { label: "支付方式", value: payTypeLabel(orderDetail.pay_type) },
- { label: "状态", value: orderStatusLabel(orderDetail.status) },
- { label: "渠道单号", value: orderDetail.trade_no || "—" },
- {
- label: "支付时间",
- value: orderDetail.paid_at ? new Date(orderDetail.paid_at).toLocaleString() : "—",
- },
- {
- label: "创建时间",
- value: new Date(orderDetail.created_at).toLocaleString(),
- full: true,
- },
- ]}
- />
- </AdminDetailSection>
- ) : null}
- </AdminModal>
-
- <AdminModal
- open={!!ledgerDetail}
- onOpenChange={(open) => !open && setLedgerDetail(null)}
- size="md"
- title={ledgerDetail ? `流水明细 #${ledgerDetail.id}` : "流水明细"}
- >
- {ledgerDetail ? (
- <AdminDetailSection>
- <AdminDetailMeta
- items={[
- {
- label: "用户",
- value: (
- <AdminEntityLink
- kind="user"
- id={ledgerDetail.user_id}
- label={ledgerDetail.user_email ?? undefined}
- />
- ),
- },
- { label: "类型", value: ledgerKindLabel(ledgerDetail.kind) },
- { label: "变动", value: `¥${fenToYuan(ledgerDetail.delta_fen)}` },
- { label: "余额后", value: `¥${fenToYuan(ledgerDetail.balance_after)}` },
- { label: "关联", value: ledgerRefLink(ledgerDetail) },
- { label: "备注", value: ledgerDetail.note || "—" },
- {
- label: "时间",
- value: new Date(ledgerDetail.created_at).toLocaleString(),
- full: true,
- },
- ]}
- />
- </AdminDetailSection>
- ) : null}
- </AdminModal>
+ />
+ <LedgerDetailDialog ledgerDetail={ledgerDetail} onClose={() => setLedgerDetail(null)} />
</div>
);
}
diff --git a/backend/.env.example b/backend/.env.example
index fad4884..cb902dd 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -5,12 +5,10 @@ SECRET_KEY=dev-secret-change-me
# 仅支持 PostgreSQL(Docker 见 deploy/docker-compose.yml)
DATABASE_URL=postgresql+asyncpg://printfilm:[email protected]:15432/printfilm
DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:[email protected]:15432/printfilm
-# Postgres 生产建议:API uvicorn --workers 1;Celery 设 PRINTFILM_DB_ROLE=celery
+# Postgres 生产建议:API uvicorn --workers 1,任务调度与 API 共用进程内连接池
# 生产建议与任务并发对齐(杭州现网:100+20,PG max_connections≥250)
# DB_POOL_SIZE=100
# DB_MAX_OVERFLOW=20
-# DB_POOL_SIZE_CELERY=2
-# DB_MAX_OVERFLOW_CELERY=3
REDIS_URL=redis://127.0.0.1:16379/0
CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173,http://localhost:5174,http://127.0.0.1:5174
PUBLIC_BASE_URL=http://127.0.0.1:8000
@@ -25,7 +23,6 @@ OPENAI_API_KEY=replace-me
OPENAI_BASE_URL=https://www.tokenfree.com/v1
MODEL_LLM=
-USE_CELERY=false
QUOTA_ENABLED=false
# Token 计费(用户价 = TokenFree 官方成本,不再加价)
diff --git a/backend/.env.test.example b/backend/.env.test.example
new file mode 100644
index 0000000..e8d3fb2
--- /dev/null
+++ b/backend/.env.test.example
@@ -0,0 +1,24 @@
+# Local automated tests. Copy to .env.test; run python scripts/run_tests.py.
+SECRET_KEY=local-test-secret-not-for-production
+DEBUG=false
+SQL_ECHO=false
+DATABASE_URL=postgresql+asyncpg://printfilm:[email protected]:15432/printfilm_test
+DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:[email protected]:15432/printfilm_test
+REDIS_URL=redis://127.0.0.1:16379/15
+CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173,http://localhost:5174,http://127.0.0.1:5174
+PUBLIC_BASE_URL=http://127.0.0.1:8000
+ARK_MOCK=true
+ARK_API_KEY=
+OPENAI_API_KEY=
+OPENAI_BASE_URL=http://127.0.0.1:9/v1
+ARK_BASE_URL=http://127.0.0.1:9/v1
+QUOTA_ENABLED=false
+BILLING_ENABLED=false
+OSS_ENABLED=false
+OSS_ACCESS_KEY_ID=
+OSS_ACCESS_KEY_SECRET=
+SMTP_ENABLED=false
+SMTP_PASSWORD=
+EPAY_PID=
+EPAY_KEY=
+ADMIN_BOOTSTRAP_EMAILS=
diff --git a/backend/app/api/admin/drama_assets.py b/backend/app/api/admin/drama_assets.py
index abbbb3b..da555aa 100644
--- a/backend/app/api/admin/drama_assets.py
+++ b/backend/app/api/admin/drama_assets.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, ConfigDict
from sqlalchemy import func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased
diff --git a/backend/app/api/admin/works.py b/backend/app/api/admin/works.py
index c37fea7..f2c51bc 100644
--- a/backend/app/api/admin/works.py
+++ b/backend/app/api/admin/works.py
@@ -1,6 +1,6 @@
# Admin work audit (visibility / audit_status)
from fastapi import APIRouter, Depends, HTTPException, Query
-from sqlalchemy import func, or_, select
+from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased
diff --git a/backend/app/api/api_keys.py b/backend/app/api/api_keys.py
index 9986c3c..db9579f 100644
--- a/backend/app/api/api_keys.py
+++ b/backend/app/api/api_keys.py
@@ -1,4 +1,4 @@
-from fastapi import APIRouter, Depends, Header, HTTPException
+from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
diff --git a/backend/app/api/drama/agents.py b/backend/app/api/drama/agents.py
index 823b3fc..5417cae 100644
--- a/backend/app/api/drama/agents.py
+++ b/backend/app/api/drama/agents.py
@@ -214,6 +214,15 @@ async def episode_script(
if len(draft) < 20:
raise HTTPException(status_code=400, detail="剧本草稿至少 20 字")
elif mode in {"summary", "full"}:
+ cur = next(
+ (
+ x
+ for x in existing
+ if isinstance(x, dict) and int(x.get("episodeNumber") or 0) == episode_number
+ ),
+ None,
+ )
+ cur_summary = str((cur or {}).get("summary") or "").strip()
cur_creative = creative_in
if not cur_creative:
cur = next(
@@ -225,8 +234,8 @@ async def episode_script(
None,
)
cur_creative = str((cur or {}).get("creative") or "").strip()
- if len(cur_creative) < 20:
- raise HTTPException(status_code=400, detail="请先填写本集原始创意(至少 20 字)")
+ if len(cur_creative) < 20 and not (mode == "full" and len(cur_summary) >= 40):
+ raise HTTPException(status_code=400, detail="请先填写本集梗概(至少 40 字)或创作备注(至少 20 字)" if mode == "full" else "请先填写创作备注(至少 20 字)")
elif mode == "body":
# 与 run_episode_body_from_brief 门槛一致:创意≥10 或摘要≥40,否则任务必败
cur = next(
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.py
index 54945c7..3e5fc62 100644
--- a/backend/app/api/drama/episodes.py
+++ b/backend/app/api/drama/episodes.py
@@ -66,6 +66,7 @@ from app.services.drama.jobs import (
)
from app.config import get_settings
from app.services.drama.seed import (
+ _script_body_fingerprint,
require_confirmable_episode_body,
seed_assets_from_script,
seed_episodes_from_script,
@@ -103,12 +104,25 @@ def _fragment_out(frag: DramaEpisodeFragment) -> DramaFragmentOut:
)
-def _episode_out(ep: DramaEpisode) -> DramaEpisodeOut:
+def _episode_out(
+ ep: DramaEpisode,
+ *,
+ script_bodies: dict[int, str] | None = None,
+) -> DramaEpisodeOut:
+ """序列化分集;有当前正文时附加旧分镜标识,不修改数据库状态。"""
frags = sorted(ep.fragments or [], key=lambda f: f.sort_order)
+ params = dict(ep.params or {})
+ if script_bodies is not None:
+ number = int(params.get("episodeNumber") or 0)
+ stored_fp = str(params.get("fragment_source_fp") or "")
+ current_body = script_bodies.get(number, "")
+ params["fragment_script_changed"] = bool(
+ frags and stored_fp and stored_fp != _script_body_fingerprint(current_body)
+ )
return DramaEpisodeOut(
id=ep.id,
name=ep.name,
- params=ep.params,
+ params=params,
project_id=ep.project_id,
fragments=[_fragment_out(f) for f in frags],
active_tasks=list(getattr(ep, "active_tasks", []) or []),
@@ -198,7 +212,7 @@ async def list_episodes(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
) -> list[DramaEpisodeOut]:
- await get_owned_drama_project(db, project_id, user)
+ project = await get_owned_drama_project(db, project_id, user, with_script=True)
from app.services.drama.seed import merge_duplicate_episodes_by_number
# 打开分镜页时顺手合并同号重复行
@@ -228,7 +242,14 @@ async def list_episodes(
by_episode_id.setdefault(int(task.episode_id), []).append(task)
for ep in episodes:
ep.active_tasks = _expand_episode_task_items(by_episode_id.get(int(ep.id), []))
- return [_episode_out(ep) for ep in episodes]
+ content = project.script.episode_content if project.script else None
+ rows = content.get("episodes", []) if isinstance(content, dict) else content
+ script_bodies = {
+ int(row.get("episodeNumber") or 0): str(row.get("body") or row.get("content") or "")
+ for row in (rows or [])
+ if isinstance(row, dict)
+ }
+ return [_episode_out(ep, script_bodies=script_bodies) for ep in episodes]
@router.post("/episodes/seed_from_script", response_model=list[DramaEpisodeOut])
diff --git a/backend/app/api/drama/scripts.py b/backend/app/api/drama/scripts.py
index 8118e8b..504fb18 100644
--- a/backend/app/api/drama/scripts.py
+++ b/backend/app/api/drama/scripts.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
-from pydantic import BaseModel, Field
+from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
diff --git a/backend/app/api/projects.py b/backend/app/api/projects.py
index 5073805..49a6a3b 100644
--- a/backend/app/api/projects.py
+++ b/backend/app/api/projects.py
@@ -9,7 +9,7 @@ from pathlib import Path
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
from fastapi.responses import StreamingResponse
-from sqlalchemy import func, or_, select, update
+from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from sse_starlette.sse import EventSourceResponse
@@ -21,12 +21,9 @@ from app.models_tasks import TaskRun
from app.schemas import (
ContentExpandOut,
ContentExpandRequest,
- PageMeta,
ProjectCreate,
ProjectDownloadRequest,
- ProjectListItem,
ProjectListOut,
- ProjectListStats,
ProjectOut,
ProjectUpdate,
ShotOut,
@@ -51,6 +48,7 @@ from app.services.tasks.service import (
)
from app.services.voices import ensure_voice_preview, list_voices
from app.services.kepu_stages import resolve_kepu_billing_phase
+from app.services.kepu_projects import list_project_page, project_runtime_view
router = APIRouter(tags=["projects"])
@@ -157,7 +155,7 @@ async def _get_owned_project(db: AsyncSession, project_id: int, user: User) -> P
if not project:
raise HTTPException(status_code=404, detail="项目不存在")
project.active_tasks = await list_active_tasks_for_owner(db, user.id, project_id=project.id)
- runtime_status, runtime_progress, runtime_error = _project_runtime_view(project)
+ runtime_status, runtime_progress, runtime_error = project_runtime_view(project)
project.status = runtime_status
project.progress = runtime_progress
project.error_msg = runtime_error
@@ -212,58 +210,6 @@ async def _ensure_compose_allowed(db: AsyncSession, user: User, project: Project
# COMPOSING / FAILED / VIDEO_READY / DONE 等均可重试拼接(无 active task)
-# 用统一任务中心投影项目运行态,避免前端只依赖旧 Project.status。
-def _project_runtime_view(project: Project) -> tuple[str, int, str | None]:
- active_tasks = list(getattr(project, "active_tasks", []) or [])
- if not active_tasks:
- return str(project.status), int(project.progress or 0), project.error_msg
- task = active_tasks[0]
- task_type = str(getattr(task, "task_type", "") or "")
- status = str(getattr(task, "status", "") or "")
- progress = int(getattr(task, "progress_percent", 0) or 0)
- if task_type == "project_pipeline":
- # 勿一律标 SCRIPTING:续跑 videos/assets 时列表会误显示「拆分镜中」
- payload = getattr(task, "payload", None) or {}
- phase = str(payload.get("phase") or "").strip().lower() if isinstance(payload, dict) else ""
- phase_label = {
- "script": ProjectStatus.SCRIPTING,
- "assets": ProjectStatus.IMAGING,
- "videos": ProjectStatus.VIDEOING,
- "compose": ProjectStatus.COMPOSING,
- }.get(phase)
- proj_status = str(project.status or "")
- if phase_label:
- label = phase_label
- elif proj_status in {
- ProjectStatus.SCRIPTING,
- ProjectStatus.IMAGING,
- ProjectStatus.VIDEOING,
- ProjectStatus.AUDIOING,
- ProjectStatus.COMPOSING,
- ProjectStatus.AUDITING,
- }:
- label = proj_status
- else:
- label = ProjectStatus.SCRIPTING
- elif task_type == "shot_regen_image":
- label = ProjectStatus.IMAGING
- elif task_type == "shot_regen_video":
- label = ProjectStatus.VIDEOING
- elif task_type == "shot_regen_audio":
- label = ProjectStatus.AUDIOING
- elif task_type == "project_regen_audio":
- label = ProjectStatus.AUDIOING
- elif task_type == "project_compose_only":
- label = ProjectStatus.COMPOSING
- else:
- label = str(project.status)
- if status in {"failed", "cancelled"}:
- return status.upper(), progress, getattr(task, "error_message", None) or project.error_msg
- if status in {"pending", "leased", "running", "awaiting_poll", "cancel_requested"}:
- return label, max(progress, int(project.progress or 0)), getattr(task, "error_message", None)
- return str(project.status), int(project.progress or 0), project.error_msg
-
-
# 为科普项目/镜头创建统一任务,由平台调度器自动执行
async def _create_kepu_task(
db: AsyncSession,
@@ -297,22 +243,6 @@ async def _create_kepu_task(
return int(task.id)
-# 批量读取项目活动任务,避免列表页逐项查询。
-async def list_active_tasks_for_user_rows(
- db: AsyncSession,
- user_id: int,
- project_ids: list[int],
-) -> dict[int, list]:
- by_project_id: dict[int, list] = {}
- for project_id in project_ids:
- by_project_id[int(project_id)] = await list_active_tasks_for_owner(
- db,
- user_id,
- project_id=int(project_id),
- )
- return by_project_id
-
-
@router.post("/projects", response_model=ProjectOut)
async def create_project(
body: ProjectCreate,
@@ -352,16 +282,6 @@ async def create_project(
return result.scalar_one()
-_RUNNING_STATUSES = {
- ProjectStatus.SCRIPTING,
- ProjectStatus.IMAGING,
- ProjectStatus.VIDEOING,
- ProjectStatus.AUDIOING,
- ProjectStatus.COMPOSING,
- ProjectStatus.AUDITING,
-}
-
-
@router.get("/projects", response_model=ProjectListOut)
async def list_projects(
page: int = Query(1, ge=1),
@@ -378,122 +298,10 @@ async def list_projects(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
) -> ProjectListOut:
- """Paginated project list with status / published / type filters."""
- published_exists = (
- select(Work.id)
- .where(Work.project_id == Project.id, Work.user_id == user.id)
- .correlate(Project)
- .exists()
- )
-
- base = select(Project).where(Project.user_id == user.id)
- count_base = select(func.count()).select_from(Project).where(Project.user_id == user.id)
-
- mode = (pipeline_mode or "").strip().lower()
- if mode in {"full", "image_text"}:
- base = base.where(Project.pipeline_mode == mode)
- count_base = count_base.where(Project.pipeline_mode == mode)
-
- keyword = (q or "").strip()
- if keyword:
- like = f"%{keyword}%"
- filt = or_(Project.title.ilike(like), Project.error_msg.ilike(like))
- base = base.where(filt)
- count_base = count_base.where(filt)
-
- tab = (status or "all").strip().lower()
- if tab == "draft":
- base = base.where(Project.status == ProjectStatus.DRAFT)
- count_base = count_base.where(Project.status == ProjectStatus.DRAFT)
- elif tab == "running":
- base = base.where(Project.status.in_(_RUNNING_STATUSES))
- count_base = count_base.where(Project.status.in_(_RUNNING_STATUSES))
- elif tab == "done":
- base = base.where(Project.status == ProjectStatus.DONE)
- count_base = count_base.where(Project.status == ProjectStatus.DONE)
- elif tab == "published":
- base = base.where(published_exists)
- count_base = count_base.where(published_exists)
-
- total = int((await db.execute(count_base)).scalar_one() or 0)
- rows = list(
- (
- await db.execute(
- base.order_by(Project.id.desc())
- .offset((page - 1) * page_size)
- .limit(page_size)
- )
- )
- .scalars()
- .all()
- )
-
- published_ids: set[int] = set()
- if rows:
- pub_result = await db.execute(
- select(Work.project_id).where(
- Work.user_id == user.id,
- Work.project_id.in_([p.id for p in rows]),
- )
- )
- published_ids = {int(x) for x in pub_result.scalars().all()}
- active_tasks = await list_active_tasks_for_user_rows(db, user.id, [p.id for p in rows])
- for project in rows:
- project.active_tasks = active_tasks.get(int(project.id), [])
-
- items = [
- ProjectListItem(
- id=p.id,
- title=p.title,
- template_id=p.template_id,
- status=_project_runtime_view(p)[0],
- progress=_project_runtime_view(p)[1],
- cover_url=p.cover_url,
- final_video_url=p.final_video_url,
- error_msg=_project_runtime_view(p)[2],
- pipeline_mode=p.pipeline_mode or "full",
- output_ratio=p.output_ratio or "",
- published=p.id in published_ids,
- created_at=p.created_at,
- updated_at=p.updated_at,
- active_tasks=list(getattr(p, "active_tasks", []) or []),
- )
- for p in rows
- ]
-
- # Stats ignore status tab but keep type + search scope
- stats_filter = [Project.user_id == user.id]
- if mode in {"full", "image_text"}:
- stats_filter.append(Project.pipeline_mode == mode)
- if keyword:
- like = f"%{keyword}%"
- stats_filter.append(or_(Project.title.ilike(like), Project.error_msg.ilike(like)))
-
- async def _count(*extra):
- stmt = select(func.count()).select_from(Project).where(*stats_filter, *extra)
- return int((await db.execute(stmt)).scalar_one() or 0)
-
- stats_total = await _count()
- stats_generating = await _count(Project.status.in_(_RUNNING_STATUSES))
- stats_done = await _count(Project.status == ProjectStatus.DONE)
- pub_stmt = (
- select(func.count())
- .select_from(Work)
- .join(Project, Project.id == Work.project_id)
- .where(Work.user_id == user.id, *stats_filter)
- )
- stats_published = int((await db.execute(pub_stmt)).scalar_one() or 0)
- stats = ProjectListStats(
- total=stats_total,
- generating=stats_generating,
- done=stats_done,
- published=stats_published,
- )
-
- return ProjectListOut(
- items=items,
- meta=PageMeta(page=page, page_size=page_size, total=total),
- stats=stats,
+ """校验分页参数并返回当前用户的项目列表及统计。"""
+ return await list_project_page(
+ db, user.id, page=page, page_size=page_size,
+ status=status, q=q, pipeline_mode=pipeline_mode,
)
@@ -707,8 +515,6 @@ async def generate_project(
- Continue: one billing stage per click — assets → videos → compose(各自预扣)。
- restart=true: wipe shots/media and regenerate storyboard from scratch.
"""
- from app.services.kepu_stages import resolve_kepu_billing_phase
-
project = await _get_owned_project(db, project_id, user)
if project.status in {
ProjectStatus.SCRIPTING,
diff --git a/backend/app/api/templates.py b/backend/app/api/templates.py
index 190b8a7..05749aa 100644
--- a/backend/app/api/templates.py
+++ b/backend/app/api/templates.py
@@ -4,7 +4,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models import Template
-from app.schemas import TemplateDetailOut, TemplateOut
+from app.schemas import TemplateDetailOut
router = APIRouter(prefix="/templates", tags=["templates"])
diff --git a/backend/app/logging_setup.py b/backend/app/logging_setup.py
index 7d1cb07..3297972 100644
--- a/backend/app/logging_setup.py
+++ b/backend/app/logging_setup.py
@@ -43,11 +43,10 @@ def configure_logging(*, level: str = "INFO", sql_echo: bool = False) -> None:
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
# 其他噪音
- for name in ("uvicorn.access", "httpx", "httpcore", "celery", "asyncio", "multipart"):
+ for name in ("uvicorn.access", "httpx", "httpcore", "asyncio", "multipart"):
logging.getLogger(name).setLevel(
logging.INFO if name == "uvicorn.access" else logging.WARNING
)
- logging.getLogger("celery").setLevel(logging.INFO)
if not _configured:
logging.getLogger("app").info(
diff --git a/backend/app/models_drama.py b/backend/app/models_drama.py
index 649820b..1b961b1 100644
--- a/backend/app/models_drama.py
+++ b/backend/app/models_drama.py
@@ -3,7 +3,6 @@
from __future__ import annotations
from datetime import datetime
-from typing import Any
from sqlalchemy import JSON, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
diff --git a/backend/app/schemas_settings.py b/backend/app/schemas_settings.py
index a1f1eda..c1928d5 100644
--- a/backend/app/schemas_settings.py
+++ b/backend/app/schemas_settings.py
@@ -3,7 +3,6 @@
from __future__ import annotations
from datetime import datetime
-from typing import Any
from pydantic import BaseModel, Field
diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.py
index ed89ca1..5fa56dd 100644
--- a/backend/app/services/billing/ephemeral.py
+++ b/backend/app/services/billing/ephemeral.py
@@ -10,13 +10,12 @@ 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 app.schemas_tasks import TaskCreateRequest, TaskEventCreate
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.handlers import get_task_handler
from app.services.tasks.service import append_task_event, build_task_event, build_task_step
diff --git a/backend/app/services/billing/usage.py b/backend/app/services/billing/usage.py
index bfc1bc6..1a23ae4 100644
--- a/backend/app/services/billing/usage.py
+++ b/backend/app/services/billing/usage.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import json
from datetime import UTC, datetime
-from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
diff --git a/backend/app/services/drama/agents.py b/backend/app/services/drama/agents.py
index 6433771..b1e9eb6 100644
--- a/backend/app/services/drama/agents.py
+++ b/backend/app/services/drama/agents.py
@@ -136,6 +136,28 @@ EPISODE_BRIEF_FROM_BODY_SYSTEM = """你是专业的短剧/网剧编剧策划。
{"episodes":[{"episodeNumber":数字,"title":"集名","creative":"...","summary":"..."}]}"""
+# 所有正文入口共用:原始故事是事实依据,摘要与画面风格不得改变事件因果。
+_SCRIPT_ADAPTATION_RULES = """
+
+改编忠实度与可拍摄性(优先于通用戏剧化建议):
+1. 用户提供完整故事或剧本时,保留原文事件顺序、人物关系、关键行为、动机与结局;摘要若与原文事实矛盾,以原文为准,用户明确提出的改编要求除外。只补充实现已有情节必需的可见动作,不擅自增加危机、冲突、旁白或象征性支线。
+2. 单集故事须完整覆盖原文的开端、过程、结果,不能为尾钩省略结局。多集按规划分配情节。儿童/治愈/童话保持自然易懂、温暖的语气,不把好奇提问强改为质疑,不把正常储粮改为饥荒求生。
+3. 每段动作只写人物此刻做什么及可见结果;外观设定由角色资产承载,不反复描写虹膜、毛发比例、五官或材质。服装佩戴位置不得与设定冲突。不得使用“身份跃迁”“时间折叠”等无法直接拍摄的抽象句作动作。
+4. 景别、运镜适量;3D/CGI 是画面风格,不是往剧情里增加发光网络、地下特效的理由。时间/季节变化写明转场,前后动作与道具状态衔接。
+5. creative 是可选创作备注,不要再复述 summary;summary 是本集事件梗概,正文是唯一拍摄依据。二者冲突时以本集梗概的事件安排为准,同时遵守原文事实。
+"""
+EPISODE_BATCH_CONTENT_SYSTEM += _SCRIPT_ADAPTATION_RULES
+EPISODE_BODY_FROM_BRIEF_SYSTEM += _SCRIPT_ADAPTATION_RULES
+EPISODE_OPTIMIZE_SYSTEM += _SCRIPT_ADAPTATION_RULES
+
+
+def _require_generated_episode_bodies(rows: list[dict[str, Any]]) -> None:
+ """拒绝重试后仍不合格的短正文,避免继续自动分镜并显示成功。"""
+ for row in rows:
+ if _content_char_len(str(row.get("body") or "")) < MIN_EPISODE_CONTENT_CHARS:
+ raise ValueError(f"第 {row.get('episodeNumber')} 集正文仍过短,请重试或手动完善剧本")
+
+
def _format_neighbor_episode_briefs(episodes: list[dict[str, Any]], number: int, limit: int = 3) -> str:
"""邻集标题/创意/摘要,作正文节选的补充。"""
others = [
@@ -339,6 +361,7 @@ async def run_episode_body_from_brief(
row = normalized[0]
row["creative"] = brief or str(row.get("creative") or "")
row["summary"] = syn or str(row.get("summary") or "")
+ _require_generated_episode_bodies([row])
return [row]
@@ -351,17 +374,22 @@ async def run_episode_full_from_creative(
project_source: str = "",
title: str | None = None,
character_asset_names: list[str] | None = None,
+ summary: str = "",
) -> list[dict[str, Any]]:
- """创意 → 摘要 → 正文(一键整集)。"""
- summary_rows = await run_episode_summary_from_creative(
- project_summary,
- existing,
- number,
- creative,
- project_source=project_source,
- title=title,
- character_asset_names=character_asset_names,
- )
+ """优先按已确认梗概生成整集;无梗概时兼容旧创意→梗概→正文。"""
+ synopsis = (summary or "").strip()
+ if len(synopsis) >= 40:
+ summary_rows = [{"creative": creative, "summary": synopsis, "title": title}]
+ else:
+ summary_rows = await run_episode_summary_from_creative(
+ project_summary,
+ existing,
+ number,
+ creative,
+ project_source=project_source,
+ title=title,
+ character_asset_names=character_asset_names,
+ )
syn_row = summary_rows[0]
body_rows = await run_episode_body_from_brief(
project_summary,
@@ -884,6 +912,7 @@ async def run_episode_script_batch(
if not normalized:
raise ValueError(f"模型未返回第 {start}–{end} 集正文")
+ _require_generated_episode_bodies(normalized)
return normalized
@@ -962,6 +991,7 @@ async def run_episode_script_from_draft(
normalized = _normalize_batch_episodes(retry_eps, number, number, title_by_num)
if not normalized:
raise ValueError(f"模型未返回第 {number} 集正文")
+ _require_generated_episode_bodies(normalized)
origin_item = next(
(
item
diff --git a/backend/app/services/drama/fragment_dialogue.py b/backend/app/services/drama/fragment_dialogue.py
new file mode 100644
index 0000000..c35a859
--- /dev/null
+++ b/backend/app/services/drama/fragment_dialogue.py
@@ -0,0 +1,158 @@
+"""LLM 分镜的对白覆盖与口播估时;纯函数,不访问数据库或模型。"""
+
+from __future__ import annotations
+
+import math
+import re
+from collections import defaultdict
+from typing import Any
+
+from app.services.seedance_segments import (
+ SEGMENT_DURATION_MAX,
+ SEGMENT_DURATION_MIN,
+ SPEAKER_DIALOGUE_RE,
+ classify_voice_body,
+ is_generic_narrator_name,
+ is_production_meta_line,
+)
+
+_ASSET_REF_RE = re.compile(r"@asset:(\d+)")
+_VOICE_CUE_RE = re.compile(r"^(【(?:对白|旁白|内心独白)[^】]*】)\s*")
+_SPEECH_CHARS_PER_SECOND = 3
+_MIN_COVERAGE_LINE_CHARS = 6
+_SPEECH_BREAKS = frozenset("。!?!?;;,,、")
+
+
+def asset_names_by_id(assets: list[Any] | None) -> dict[int, str]:
+ """建立资产 ID 到名称的映射,用于还原角色称呼和台词中的引用。"""
+ return {
+ int(asset.id): str(asset.name or "")
+ for asset in assets or []
+ if getattr(asset, "id", None) is not None
+ }
+
+
+def _restore_assets(text: str, asset_names: dict[int, str]) -> str:
+ """将资产标记还原为实际名称,避免将标记字符计入口播。"""
+ return _ASSET_REF_RE.sub(lambda match: asset_names.get(int(match[1]), ""), text)
+
+
+def _spoken_parts(line: str) -> tuple[str, str, str] | None:
+ """提取生产前缀、说话人标注和台词,跳过画面、场头与舞台指示。"""
+ raw = (line or "").strip()
+ if not raw or is_production_meta_line(raw) or raw.startswith(("出场人物", "@duration:", "###")):
+ return None
+ cue = _VOICE_CUE_RE.match(raw)
+ if raw.startswith("【") and cue is None:
+ return None
+ prefix = cue[1] if cue else ""
+ body = raw[cue.end() :] if cue else raw
+ # 先屏蔽资产标记中的冒号,再识别真正分隔说话人与台词的冒号。
+ masked = _ASSET_REF_RE.sub(lambda match: f"@asset_{match[1]}", body)
+ if classify_voice_body(masked) not in {"dialogue", "narration", "inner"}:
+ return None
+ spoken = SPEAKER_DIALOGUE_RE.match(masked)
+ if not spoken:
+ return None
+ label = spoken["speaker"] + (spoken["paren"] or "")
+
+ def unmask(text: str) -> str:
+ """恢复解析前临时屏蔽的资产标记。"""
+ return re.sub(r"@asset_(\d+)", r"@asset:\1", text)
+
+ return prefix, unmask(label), unmask(spoken["text"])
+
+
+def _speech_char_count(text: str, asset_names: dict[int, str]) -> int:
+ """只统计实际读出的文字和数字,不计算标点、空白与生产标记。"""
+ return sum(char.isalnum() for char in _restore_assets(text, asset_names))
+
+
+def _split_spoken_text(text: str, asset_names: dict[int, str]) -> list[str]:
+ """保留全部台词,优先按句读拆成单段时长可容纳的口播。"""
+ max_chars = _SPEECH_CHARS_PER_SECOND * SEGMENT_DURATION_MAX
+ tokens = re.findall(r"@asset:\d+|[\s\S]", text)
+ chunks: list[str] = []
+ start = 0
+ while start < len(tokens):
+ end = start
+ count = 0
+ last_break: int | None = None
+ while end < len(tokens):
+ cost = _speech_char_count(tokens[end], asset_names)
+ if count + cost > max_chars and end > start:
+ break
+ count += cost
+ end += 1
+ if tokens[end - 1] in _SPEECH_BREAKS and count >= max_chars // 2:
+ last_break = end
+ if end < len(tokens) and last_break is not None:
+ end = last_break
+ chunks.append("".join(tokens[start:end]))
+ start = end
+ return chunks
+
+
+def timed_spoken_lines(
+ line: str, asset_names: dict[int, str]
+) -> list[tuple[int, str]] | None:
+ """按每秒约三字分配口播时长;过长台词拆段,画面行返回 None。"""
+ parts = _spoken_parts(line)
+ if parts is None:
+ return None
+ prefix, label, text = parts
+ result: list[tuple[int, str]] = []
+ for chunk in _split_spoken_text(text, asset_names):
+ seconds = max(
+ SEGMENT_DURATION_MIN,
+ math.ceil(_speech_char_count(chunk, asset_names) / _SPEECH_CHARS_PER_SECOND),
+ )
+ result.append((seconds, f"{prefix}{label}:{chunk}"))
+ return result
+
+
+def dialogue_coverage_insufficient(
+ episode_body: str,
+ drafts: list[dict[str, Any]],
+ *,
+ assets: list[Any] | None = None,
+) -> bool:
+ """检查源剧本主要台词是否按说话人保留,允许跨镜拆句与标点调整。"""
+ asset_names = asset_names_by_id(assets)
+ # 旧调用方未加载资产时,无法解析的引用不能成为自动重拆已有分镜的依据。
+ if assets is None and any(
+ int(match[1]) not in asset_names
+ for draft in drafts
+ for match in _ASSET_REF_RE.finditer(str(draft.get("content") or ""))
+ ):
+ return False
+
+ def spoken_rows(content: str) -> list[tuple[str, str]]:
+ """还原资产,去除情绪和标点,生成可逐句核对的口播文本。"""
+ rows: list[tuple[str, str]] = []
+ for line in content.splitlines():
+ parts = _spoken_parts(_restore_assets(line, asset_names))
+ if parts is None:
+ continue
+ _, label, text = parts
+ speaker = re.split(r"[((]", label, maxsplit=1)[0].strip().lower()
+ if is_generic_narrator_name(speaker):
+ speaker = "旁白"
+ normalized = "".join(char.lower() for char in text if char.isalnum())
+ if normalized:
+ rows.append((speaker, normalized))
+ return rows
+
+ target_by_speaker: dict[str, str] = defaultdict(str)
+ for draft in drafts:
+ for speaker, text in spoken_rows(str(draft.get("content") or "")):
+ target_by_speaker[speaker] += text
+ offsets: dict[str, int] = defaultdict(int)
+ for speaker, text in spoken_rows(episode_body):
+ if len(text) < _MIN_COVERAGE_LINE_CHARS:
+ continue
+ found = target_by_speaker[speaker].find(text, offsets[speaker])
+ if found < 0:
+ return True
+ offsets[speaker] = found + len(text)
+ return False
diff --git a/backend/app/services/drama/fragment_plan.py b/backend/app/services/drama/fragment_plan.py
index e56432a..136884d 100644
--- a/backend/app/services/drama/fragment_plan.py
+++ b/backend/app/services/drama/fragment_plan.py
@@ -37,6 +37,11 @@ from app.services.drama.fragment_asset_limit import (
)
from app.services.drama.fragment_budget import cap_llm_fragment_items, trim_episode_fragment_drafts
from app.services.drama.fragment_content_duration import sum_fragment_content_duration_seconds
+from app.services.drama.fragment_dialogue import (
+ asset_names_by_id,
+ dialogue_coverage_insufficient,
+ timed_spoken_lines,
+)
from app.services.drama.fragment_plan_prompt import (
FRAGMENT_PLAN_SYSTEM_PROMPT,
build_fragment_plan_user_prompt,
@@ -300,6 +305,7 @@ def normalize_llm_fragment_items(
if str(getattr(a, "type", "") or "") in {"prop", "material", "none"}
]
summary_lookup = build_summary_character_lookup(summary)
+ asset_names = asset_names_by_id(assets)
# introduced 本剧已介绍角色(含更早分集)
introduced: set[str] = set(already_introduced or ())
drafts: list[dict[str, Any]] = []
@@ -387,6 +393,7 @@ def normalize_llm_fragment_items(
used = 0
# timed_blocks 本 LLM 镜内各行 (时长, 文本行);超软/硬上限时拆成多条 Fragment
timed_blocks: list[tuple[int, list[str]]] = []
+ has_spoken_lines = False
inject_bindings = [*bindings, *prop_bindings]
for line in lines:
stripped = line.strip()
@@ -400,6 +407,14 @@ def normalize_llm_fragment_items(
formatted = _strip_subtitle_instruction(formatted)
if scene_asset_id and scene_name and scene_name in formatted and f"@asset:{scene_asset_id}" not in formatted:
formatted = formatted.replace(scene_name, f"@asset:{scene_asset_id} {scene_name}", 1)
+ spoken_blocks = timed_spoken_lines(formatted, asset_names)
+ if spoken_blocks is not None:
+ has_spoken_lines = True
+ timed_blocks.extend(
+ (duration, [f"@duration:{duration}", text])
+ for duration, text in spoken_blocks
+ )
+ continue
line_dur = _clamp_duration(_estimate_line_duration(formatted))
if line_dur <= 0:
continue
@@ -413,6 +428,7 @@ def normalize_llm_fragment_items(
# 仅在单镜可容纳范围内按 LLM 时长缩段;超硬上限仍走拆镜逻辑
if (
llm_target > 0
+ and not has_spoken_lines
and block_sum > llm_target
and block_sum <= FRAGMENT_TOTAL_MAX
):
@@ -563,10 +579,17 @@ def normalize_llm_fragment_items(
return drafts
-def llm_fragment_coverage_insufficient(episode_body: str, drafts: list[dict[str, Any]]) -> bool:
+def llm_fragment_coverage_insufficient(
+ episode_body: str,
+ drafts: list[dict[str, Any]],
+ *,
+ assets: list[Any] | None = None,
+ check_dialogue: bool = True,
+) -> bool:
"""
- 长正文/多场剧本若镜数盖不住场次,视为敷衍,应回退规则切分。
- 短正文单场允许 1 镜;多场至少每场一镜。不设整集镜数上限。
+ 校验场次数量与源剧本主要口播覆盖,不足时回退规则切分。
+ 短正文单场允许 1 镜;续拆时跳过已锁定口播的全量比对。
+ assets 用于还原台词中的引用;不设整集镜数上限。
"""
body = (episode_body or "").strip()
if not body:
@@ -577,6 +600,8 @@ def llm_fragment_coverage_insufficient(episode_body: str, drafts: list[dict[str,
# 多场:至少一场一镜
if len(scenes) >= 2 and n < len(scenes):
return True
+ if check_dialogue and dialogue_coverage_insufficient(body, drafts, assets=assets):
+ return True
if n >= 2:
return False
if len(scenes) >= 2:
@@ -671,9 +696,11 @@ async def plan_fragments_with_llm(
if not drafts:
raise RuntimeError("LLM 分镜规范化后为空")
drafts = trim_episode_fragment_drafts(drafts)
- if llm_fragment_coverage_insufficient(episode_body, drafts):
+ if llm_fragment_coverage_insufficient(
+ episode_body, drafts, assets=assets, check_dialogue=not bool(locked)
+ ):
raise RuntimeError(
- f"LLM 分镜过少({len(drafts)} 条),无法覆盖本集多场/长正文,将回退规则切分"
+ f"LLM 分镜覆盖不足({len(drafts)} 条):场次或主要对白缺失,将回退规则切分"
)
logger.info(
"LLM 分镜完成 episode=%s ep_no=%s fragments=%s introduced_before=%s locked=%s",
diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.py
index dd03b40..4e3e789 100644
--- a/backend/app/services/drama/generation.py
+++ b/backend/app/services/drama/generation.py
@@ -16,14 +16,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
from app.models import User
from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaFragmentAssetRef, DramaProject
-from app.services.ark import get_ark
+from app.services.ark import TaskResult, get_ark
from app.services.drama.billing_util import record_seedance_video_usage, record_seedream_image_usage, seedance_billing_key
from app.services.drama.output_settings import (
infer_aspect_ratio_from_pixels,
resolve_episode_video_output,
seedream_still_size_for_video_ratio,
)
-from app.services.billing import record_line
from app.services.drama.build_seedance_generate_body import (
ASSET_MENTION_TOKEN_PATTERN,
SEEDANCE_ATTACH_REFERENCE_AUDIO,
diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.py
index 6f32dc3..3708466 100644
--- a/backend/app/services/drama/jobs.py
+++ b/backend/app/services/drama/jobs.py
@@ -748,8 +748,8 @@ async def _run_single_episode_script_job(
character_asset_names=character_asset_names,
)
elif mode == "full":
- if len(ep_creative) < 20:
- raise ValueError("请先填写本集原始创意(至少 20 字)")
+ if len(ep_summary) < 40 and len(ep_creative) < 20:
+ raise ValueError("请先填写本集梗概(至少 40 字)或创作备注(至少 20 字)")
batch = await run_episode_full_from_creative(
summary,
existing,
@@ -758,6 +758,7 @@ async def _run_single_episode_script_job(
project_source=project_source,
title=ep_title,
character_asset_names=character_asset_names,
+ summary=ep_summary,
)
elif mode == "brief":
ep_body = str((current or {}).get("body") or (current or {}).get("content") or "").strip()
diff --git a/backend/app/services/drama/script_summary_prompt.py b/backend/app/services/drama/script_summary_prompt.py
index e8354b4..c213b86 100644
--- a/backend/app/services/drama/script_summary_prompt.py
+++ b/backend/app/services/drama/script_summary_prompt.py
@@ -24,7 +24,9 @@ SCRIPT_SUMMARY_SYSTEM_PROMPT = """你是专业的短剧/网剧剧本策划,负
10. synopsis 用一段完整中文叙述故事,从世界观、矛盾、结盟、高潮、结局到余韵,长度 200–400 字
11. 语言统一使用简体中文,偏影视策划文档风格,避免空泛形容词堆砌
12. 每人 visualImage 须 100–200 字:写清性别年龄、脸型五官、发型、体型、服饰材质与配色、气质神态、标志性道具或细节;只写外观本体,不要写「三视图 / 白底设定板」等构图指令(入库时由系统加结构前缀);禁止仅写「英俊」「美丽」等空泛词
-13. characters 建议 5–12 人;确有大量具名配角时宁可多列,也不要省略会反复出场的名字
+13. characters 数量由原文决定,只有 1–2 个角色就只列 1–2 个,禁止为凑人数添加角色。森林、松果、天气等非拟人的环境/道具不得列为人物;只有原文明示具有独立行动或对白的拟人角色才能作为人物
+14. 原文已是完整故事时,按改编整理处理:保留事件顺序、关键行为、人物动机与结局,不要凭空增加危机、反派、饥饿或焦虑,不要把友善提问改成质疑或对立。面向儿童时保持原文语气和可理解的因果,不强加成人化隐喻与追剧悬念
+15. 画面风格只影响 visualImage 和制作美学,不应改写剧情事实。人物外观写入 visualImage,synopsis 聚焦发生了什么,不堆砌毛发比例、材质、粒子特效等制作细节
必须输出严格 JSON 对象(不要 markdown、不要代码围栏),字段:
{
diff --git a/backend/app/services/drama/seed.py b/backend/app/services/drama/seed.py
index 561c3c7..d6dd8c4 100644
--- a/backend/app/services/drama/seed.py
+++ b/backend/app/services/drama/seed.py
@@ -37,6 +37,7 @@ from app.services.drama.seed_asset_params import (
build_named_image_params,
build_scene_params,
)
+from app.services.drama.summary_character_filter import partition_summary_characters
logger = logging.getLogger(__name__)
@@ -467,11 +468,12 @@ async def seed_assets_from_script(
len(existing),
)
+ summary_by_name, excluded_character_names = partition_summary_characters(summary)
+ excluded_seed_names = {_character_name_for_seed(name) for name in excluded_character_names}
+
# refresh:先把摘要人物/场景字段同步到已有资产
if refresh_prompts:
- for ch in summary.get("characters") or []:
- if not isinstance(ch, dict):
- continue
+ for ch in summary_by_name.values():
name = str(ch.get("name") or "").strip()
asset = existing_by_key.get(_asset_dedupe_key("character", name))
if asset:
@@ -482,21 +484,13 @@ async def seed_assets_from_script(
# Extract scene names from episode bodies
bodies = _episode_bodies(script.episode_content)
- # summary_by_name 摘要人物小传,优先用于建角色
- summary_by_name: dict[str, dict[str, Any]] = {}
- for ch in summary.get("characters") or []:
- if not isinstance(ch, dict):
- continue
- name = str(ch.get("name") or "").strip()
- if name:
- summary_by_name[name] = ch
# cast_names 分集「出场人物」全量名单(补摘要遗漏)
cast_names = _extract_cast_names_from_bodies(bodies)
# character_names 摘要 + 出场人物合并保序(跳过音色/声音标注名)
character_names: list[str] = []
for name in list(summary_by_name.keys()) + cast_names:
seed_name = _character_name_for_seed(name)
- if seed_name and seed_name not in character_names:
+ if seed_name and seed_name not in excluded_seed_names and seed_name not in character_names:
character_names.append(seed_name)
scene_names: list[str] = []
@@ -653,19 +647,14 @@ def collect_episode_seed_names(
body: str,
) -> tuple[list[str], list[str], dict[str, dict[str, Any]]]:
"""收集本集 seed 用角色名/场景名,及摘要人物小传索引。"""
- summary_by_name: dict[str, dict[str, Any]] = {}
- for ch in summary.get("characters") or []:
- if not isinstance(ch, dict):
- continue
- name = str(ch.get("name") or "").strip()
- if name:
- summary_by_name[name] = ch
+ summary_by_name, excluded_character_names = partition_summary_characters(summary)
+ excluded_seed_names = {_character_name_for_seed(name) for name in excluded_character_names}
cast_names = _extract_cast_names_from_bodies([body or ""])
character_names: list[str] = []
for name in list(summary_by_name.keys()) + cast_names:
seed_name = _character_name_for_seed(name)
- if seed_name and seed_name not in character_names:
+ if seed_name and seed_name not in excluded_seed_names and seed_name not in character_names:
character_names.append(seed_name)
scene_names = _extract_scene_names_from_bodies([body or ""])[:40]
diff --git a/backend/app/services/drama/summary_character_filter.py b/backend/app/services/drama/summary_character_filter.py
new file mode 100644
index 0000000..dcfad3b
--- /dev/null
+++ b/backend/app/services/drama/summary_character_filter.py
@@ -0,0 +1,87 @@
+"""Conservative category checks before summary entries become character assets."""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+
+_NON_CHARACTER_ROLES = frozenset(
+ {"场景", "场景角色", "环境", "环境角色", "氛围角色", "非人物", "非角色", "非拟人化道具", "道具"}
+)
+_NON_CHARACTER_DECLARATION_RE = re.compile(
+ r"^(?:非人物|非角色|非拟人化(?:角色|道具|物体)|无生命(?:物体|道具))(?=[,,。::;;\s]|$)"
+)
+_INANIMATE_IDENTITY_RE = re.compile(
+ r"植物种子|生态系统|生态环境|自然景观|无生命|非生物|道具|器物|建筑|场景|环境|"
+ r"(?:^|[,,。::;;\s])(?:植物|种子)(?=[,,。::;;\s]|$)"
+)
+_NEGATED_CHARACTER_IDENTITY_RE = re.compile(
+ r"非人物|非角色|非拟人化(?:角色|道具|物体)?|不拟人化|"
+ r"(?:无|没有|不具备|不具有)(?:人格|自主意识|意志)"
+)
+_CHARACTER_IDENTITY_RE = re.compile(
+ r"拟人|人格|自主意识|对话|人类|人形|男(?:人|孩|子|性)|女(?:人|孩|子|性)|"
+ r"树妖|树精|精灵|妖怪|机器人|群演|路人|村民|士兵|工作人员|道具师"
+)
+
+
+def _is_non_character_entry(character: dict[str, Any]) -> bool:
+ """Require an explicit category declaration and non-character identity evidence.
+
+ Animals and group characters remain valid. Ambiguous entries are retained;
+ this check only prevents clearly labelled scenery/objects from being seeded
+ with the character three-view and voice workflow.
+ """
+ role = str(character.get("roleType") or "").strip()
+ role_parts = {part.strip() for part in re.split(r"[//、,,+|]", role)}
+ visual = str(character.get("visualImage") or "").strip()
+ identity = str(character.get("identityBackground") or "").strip()
+ declared_non_character = bool(
+ role_parts & _NON_CHARACTER_ROLES
+ or _NON_CHARACTER_DECLARATION_RE.match(visual)
+ or _NON_CHARACTER_DECLARATION_RE.match(identity)
+ )
+ if not declared_non_character:
+ return False
+
+ # A mislabelled tree spirit, person or speaking robot still belongs to cast.
+ identity_text = " ".join(
+ str(character.get(key) or "")
+ for key in ("name", "title", "visualImage", "identityBackground")
+ )
+ identity_text = _NEGATED_CHARACTER_IDENTITY_RE.sub("", identity_text)
+ if _CHARACTER_IDENTITY_RE.search(identity_text):
+ return False
+
+ return bool(
+ role_parts & {"非人物", "非角色", "非拟人化道具"}
+ or re.match(r"^(?:非人物|非角色)", visual)
+ or re.match(r"^(?:非人物|非角色)", identity)
+ or _INANIMATE_IDENTITY_RE.search(identity)
+ or re.match(r"^(?:无生命|非生物)", visual)
+ )
+
+
+def partition_summary_characters(
+ summary: dict[str, Any],
+) -> tuple[dict[str, dict[str, Any]], set[str]]:
+ """Return usable biographies and explicitly excluded names without mutation.
+
+ Keeping excluded names lets seed ignore the same erroneous entry if a model
+ also repeated it in a screenplay cast line. A valid duplicate wins over an
+ excluded duplicate so an ambiguous name cannot suppress a genuine character.
+ """
+ accepted: dict[str, dict[str, Any]] = {}
+ excluded: set[str] = set()
+ for character in summary.get("characters") or []:
+ if not isinstance(character, dict):
+ continue
+ name = str(character.get("name") or "").strip()
+ if not name:
+ continue
+ if _is_non_character_entry(character):
+ excluded.add(name)
+ else:
+ accepted[name] = character
+ return accepted, excluded - accepted.keys()
diff --git a/backend/app/services/kepu_projects.py b/backend/app/services/kepu_projects.py
new file mode 100644
index 0000000..7d77140
--- /dev/null
+++ b/backend/app/services/kepu_projects.py
@@ -0,0 +1,172 @@
+"""科普项目列表:统一筛选范围、分页统计及任务运行态投影。"""
+
+from __future__ import annotations
+
+from sqlalchemy import func, or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models import Project, ProjectStatus, Work
+from app.schemas import PageMeta, ProjectListItem, ProjectListOut, ProjectListStats
+from app.services.tasks.service import list_active_tasks_for_projects
+
+# 列表“生成中”统计和无 phase 任务投影共用的项目状态集合。
+_RUNNING_STATUSES = {
+ ProjectStatus.SCRIPTING,
+ ProjectStatus.IMAGING,
+ ProjectStatus.VIDEOING,
+ ProjectStatus.AUDIOING,
+ ProjectStatus.COMPOSING,
+ ProjectStatus.AUDITING,
+}
+
+
+def project_runtime_view(project: Project) -> tuple[str, int, str | None]:
+ """从最新活动任务投影项目运行态,不修改项目持久化字段。"""
+ active_tasks = list(getattr(project, "active_tasks", []) or [])
+ if not active_tasks:
+ return str(project.status), int(project.progress or 0), project.error_msg
+ task = active_tasks[0]
+ task_type = str(getattr(task, "task_type", "") or "")
+ status = str(getattr(task, "status", "") or "")
+ progress = int(getattr(task, "progress_percent", 0) or 0)
+ if task_type == "project_pipeline":
+ # 勿一律标 SCRIPTING:续跑 videos/assets 时列表会误显示「拆分镜中」
+ payload = getattr(task, "payload", None) or {}
+ phase = str(payload.get("phase") or "").strip().lower() if isinstance(payload, dict) else ""
+ phase_label = {
+ "script": ProjectStatus.SCRIPTING,
+ "assets": ProjectStatus.IMAGING,
+ "videos": ProjectStatus.VIDEOING,
+ "compose": ProjectStatus.COMPOSING,
+ }.get(phase)
+ proj_status = str(project.status or "")
+ if phase_label:
+ label = phase_label
+ elif proj_status in _RUNNING_STATUSES:
+ label = proj_status
+ else:
+ label = ProjectStatus.SCRIPTING
+ elif task_type == "shot_regen_image":
+ label = ProjectStatus.IMAGING
+ elif task_type == "shot_regen_video":
+ label = ProjectStatus.VIDEOING
+ elif task_type == "shot_regen_audio":
+ label = ProjectStatus.AUDIOING
+ elif task_type == "project_regen_audio":
+ label = ProjectStatus.AUDIOING
+ elif task_type == "project_compose_only":
+ label = ProjectStatus.COMPOSING
+ else:
+ label = str(project.status)
+ if status in {"failed", "cancelled"}:
+ return status.upper(), progress, getattr(task, "error_message", None) or project.error_msg
+ if status in {"pending", "leased", "running", "awaiting_poll", "cancel_requested"}:
+ return label, max(progress, int(project.progress or 0)), getattr(task, "error_message", None)
+ return str(project.status), int(project.progress or 0), project.error_msg
+
+
+# 关键词和类型筛选同时用于列表、总数与统计,避免三个查询范围漂移。
+def _scope_filters(user_id: int, mode: str, keyword: str) -> list:
+ filters = [Project.user_id == user_id]
+ if mode in {"full", "image_text"}:
+ filters.append(Project.pipeline_mode == mode)
+ if keyword:
+ like = f"%{keyword}%"
+ filters.append(or_(Project.title.ilike(like), Project.error_msg.ilike(like)))
+ return filters
+
+
+# 每个项目仅计算一次运行态,再组装列表响应。
+def _list_item(project: Project, *, published: bool) -> ProjectListItem:
+ status, progress, error_msg = project_runtime_view(project)
+ return ProjectListItem(
+ id=project.id,
+ title=project.title,
+ template_id=project.template_id,
+ status=status,
+ progress=progress,
+ cover_url=project.cover_url,
+ final_video_url=project.final_video_url,
+ error_msg=error_msg,
+ pipeline_mode=project.pipeline_mode or "full",
+ output_ratio=project.output_ratio or "",
+ published=published,
+ created_at=project.created_at,
+ updated_at=project.updated_at,
+ active_tasks=list(getattr(project, "active_tasks", []) or []),
+ )
+
+
+async def list_project_page(
+ db: AsyncSession,
+ user_id: int,
+ *,
+ page: int,
+ page_size: int,
+ status: str | None = None,
+ q: str | None = None,
+ pipeline_mode: str | None = None,
+) -> ProjectListOut:
+ """分页读取用户项目,统计保留类型和关键词范围,但不受状态 Tab 限制。"""
+ # published_exists 复用列表与总数的发布状态条件;scope 是统计的完整范围。
+ published_exists = (
+ select(Work.id)
+ .where(Work.project_id == Project.id, Work.user_id == user_id)
+ .correlate(Project)
+ .exists()
+ )
+ mode = (pipeline_mode or "").strip().lower()
+ keyword = (q or "").strip()
+ scope = _scope_filters(user_id, mode, keyword)
+ filters = list(scope)
+ tab = (status or "all").strip().lower()
+ if tab == "draft":
+ filters.append(Project.status == ProjectStatus.DRAFT)
+ elif tab == "running":
+ filters.append(Project.status.in_(_RUNNING_STATUSES))
+ elif tab == "done":
+ filters.append(Project.status == ProjectStatus.DONE)
+ elif tab == "published":
+ filters.append(published_exists)
+
+ # 只为当前页批量读取发布标记和任务,避免随页大小增加逐项目查询。
+ count = select(func.count()).select_from(Project).where(*filters)
+ total = int((await db.execute(count)).scalar_one() or 0)
+ statement = (
+ select(Project).where(*filters).order_by(Project.id.desc())
+ .offset((page - 1) * page_size).limit(page_size)
+ )
+ rows = list((await db.execute(statement)).scalars().all())
+ published_ids: set[int] = set()
+ if rows:
+ project_ids = [project.id for project in rows]
+ published = await db.execute(
+ select(Work.project_id).where(Work.user_id == user_id, Work.project_id.in_(project_ids))
+ )
+ published_ids = {int(project_id) for project_id in published.scalars().all()}
+ active_tasks = await list_active_tasks_for_projects(db, user_id, project_ids)
+ for project in rows:
+ project.active_tasks = active_tasks[int(project.id)]
+ items = [_list_item(project, published=project.id in published_ids) for project in rows]
+
+ # 按共同范围统计各状态;单会话查询保持串行,避免并发使用 AsyncSession。
+ async def count_projects(*extra) -> int:
+ """对当前类型与关键词范围追加状态条件后计数。"""
+ statement = select(func.count()).select_from(Project).where(*scope, *extra)
+ return int((await db.execute(statement)).scalar_one() or 0)
+
+ stats_total = await count_projects()
+ stats_generating = await count_projects(Project.status.in_(_RUNNING_STATUSES))
+ stats_done = await count_projects(Project.status == ProjectStatus.DONE)
+ published_count = (
+ select(func.count()).select_from(Work).join(Project, Project.id == Work.project_id)
+ .where(Work.user_id == user_id, *scope)
+ )
+ stats_published = int((await db.execute(published_count)).scalar_one() or 0)
+ return ProjectListOut(
+ items=items,
+ meta=PageMeta(page=page, page_size=page_size, total=total),
+ stats=ProjectListStats(
+ total=stats_total, generating=stats_generating, done=stats_done, published=stats_published,
+ ),
+ )
diff --git a/backend/app/services/model_settings.py b/backend/app/services/model_settings.py
index 36b7343..2cef94e 100644
--- a/backend/app/services/model_settings.py
+++ b/backend/app/services/model_settings.py
@@ -239,7 +239,6 @@ def _bootstrap_logical_from_channels(channels: list[SystemModelChannel]) -> tupl
alias_models: list[LogicalModel] = []
def _bindings_for_upstream(upstream: str) -> list:
- from app.schemas_routing import LogicalModelBinding
from app.services.tokenfree_pricing import canonicalize_channel_model_id
wanted = {(upstream or "").strip(), canonicalize_channel_model_id(upstream)}
@@ -573,7 +572,7 @@ def _build_readiness(
"video": "video_model",
"audio": "audio_model",
}.items():
- cap = capability # type: LogicalModelCapability
+ cap: LogicalModelCapability = capability
model_id = getattr(defaults, attr) or ""
resolved = resolve_logical_model_config(logical_models, channels, cap, model_id) if model_id else None
items.append(
diff --git a/backend/app/services/oss.py b/backend/app/services/oss.py
index 2fa1b4b..dc3dc7d 100644
--- a/backend/app/services/oss.py
+++ b/backend/app/services/oss.py
@@ -104,7 +104,6 @@ def ensure_browser_cors() -> None:
if pub and pub not in origins:
origins.append(pub)
try:
- import oss2
from oss2.models import BucketCors, CorsRule
rule = CorsRule(
diff --git a/backend/app/services/oss_queue.py b/backend/app/services/oss_queue.py
index 991d00d..9144154 100644
--- a/backend/app/services/oss_queue.py
+++ b/backend/app/services/oss_queue.py
@@ -44,7 +44,6 @@ def enqueue_oss_upload(local_url: str) -> bool:
if not oss_svc.oss_enabled():
return False
- settings = get_settings()
key = _ENQUEUE_KEY.format(digest=_digest(url))
try:
r = _redis()
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index f646aa9..a190995 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -913,7 +913,6 @@ async def _parallel_image_and_audio(project_id: int) -> None:
negative = _project_image_negative(project)
voice = _project_voice(project)
image_model = (getattr(project, "image_model", None) or "").strip()
- video_model = (getattr(project, "video_model", None) or "").strip()
output_ratio = _project_output_ratio(project) or ""
if not shot_meta:
diff --git a/backend/app/services/studio_tools.py b/backend/app/services/studio_tools.py
index 4963061..fa4dc87 100644
--- a/backend/app/services/studio_tools.py
+++ b/backend/app/services/studio_tools.py
@@ -16,7 +16,7 @@ from app.config import get_settings
from app.models import ToolRun, User
from app.models_tasks import TaskRun
from app.services.ark import get_ark
-from app.services.billing import record_line, run_billed_ephemeral
+from app.services.billing import run_billed_ephemeral
from app.services.drama.billing_util import record_seedream_image_usage
from app.services.billing.estimates import estimate_task_fen
from app.services.billing.settlement import billing_active
diff --git a/backend/app/services/tasks/poller.py b/backend/app/services/tasks/poller.py
index c75b192..832c227 100644
--- a/backend/app/services/tasks/poller.py
+++ b/backend/app/services/tasks/poller.py
@@ -208,10 +208,6 @@ async def _poll_one_task(task_id: int) -> None:
# 后台轮询 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)
diff --git a/backend/app/services/tasks/runtime.py b/backend/app/services/tasks/runtime.py
index cafa70e..5de77b2 100644
--- a/backend/app/services/tasks/runtime.py
+++ b/backend/app/services/tasks/runtime.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import logging
+from contextlib import AsyncExitStack
from app.config import get_settings
from app.services.tasks.poller import (
@@ -33,16 +34,27 @@ _watchdog_intentionally_stopped: bool = True
# 启动统一任务平台运行时(Worker 调度 + Selector 轮询 + 看门狗)。
async def start_task_runtime() -> None:
- await start_scheduler()
- await start_poller()
- await start_watchdog()
+ # 逐个登记已启动组件;后续启动失败或取消时按依赖逆序清理。
+ async with AsyncExitStack() as startup:
+ await start_scheduler()
+ startup.push_async_callback(stop_scheduler)
+ await start_poller()
+ startup.push_async_callback(stop_poller)
+ await start_watchdog()
+ startup.push_async_callback(stop_watchdog)
+ startup.pop_all()
# 停止统一任务平台运行时。
async def stop_task_runtime() -> None:
- await stop_watchdog()
- await stop_poller()
- await stop_scheduler()
+ # 即使关闭某个组件失败,也必须继续释放其余后台协程。
+ try:
+ await stop_watchdog()
+ finally:
+ try:
+ await stop_poller()
+ finally:
+ await stop_scheduler()
# 启动看门狗:调度/轮询循环退出或心跳过期时自动拉起。
@@ -105,7 +117,13 @@ def runtime_summary() -> dict[str, int | str | float | bool]:
sched = scheduler_status()
poll = poller_status()
dog = watchdog_status()
- healthy = sched == "running" and poll == "running" and dog == "running"
+ healthy = (
+ sched == "running"
+ and poll == "running"
+ and dog == "running"
+ and not scheduler_tick_stale()
+ and not poller_tick_stale()
+ )
return {
"healthy": healthy,
"scheduler": sched,
diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.py
index a9fdbba..973a663 100644
--- a/backend/app/services/tasks/service.py
+++ b/backend/app/services/tasks/service.py
@@ -1014,6 +1014,20 @@ async def cancel_task_for_user(db: AsyncSession, user: User, task_id: int) -> Ta
return await get_task_for_user(db, user, task.id)
+# 共用用户隔离、活动态筛选和详情加载,保证单项目与列表查询语义一致。
+def _active_owner_tasks_statement(user_id: int, *scope_filters) -> Select:
+ return (
+ select(TaskRun)
+ .options(*task_detail_options())
+ .where(
+ TaskRun.requested_by == user_id,
+ TaskRun.status.in_(tuple(ACTIVE_TASK_STATUSES)),
+ or_(*scope_filters),
+ )
+ .order_by(TaskRun.created_at.desc())
+ )
+
+
async def list_active_tasks_for_owner(
db: AsyncSession,
user_id: int,
@@ -1021,6 +1035,7 @@ async def list_active_tasks_for_owner(
project_id: int | None = None,
drama_project_id: int | None = None,
) -> list[TaskRun]:
+ """读取用户在指定项目范围内的活动任务,按创建时间倒序返回。"""
scope_filters = []
if project_id is not None:
scope_filters.append(TaskRun.project_id == project_id)
@@ -1028,15 +1043,27 @@ async def list_active_tasks_for_owner(
scope_filters.append(TaskRun.drama_project_id == drama_project_id)
if not scope_filters:
return []
- filters = [
- TaskRun.requested_by == user_id,
- TaskRun.status.in_(tuple(ACTIVE_TASK_STATUSES)),
- or_(*scope_filters),
- ]
- stmt = select(TaskRun).options(*task_detail_options()).where(*filters).order_by(TaskRun.created_at.desc())
+ stmt = _active_owner_tasks_statement(user_id, *scope_filters)
return list((await db.execute(stmt)).scalars().unique().all())
+async def list_active_tasks_for_projects(
+ db: AsyncSession,
+ user_id: int,
+ project_ids: list[int],
+) -> dict[int, list[TaskRun]]:
+ """一次读取一页科普项目的活动任务,分组后仍保持各项目的新任务优先。"""
+ # 去重后的映射也为暂无活动任务的项目保留空列表;空页不访问数据库。
+ grouped: dict[int, list[TaskRun]] = {int(project_id): [] for project_id in project_ids}
+ if not grouped:
+ return grouped
+ stmt = _active_owner_tasks_statement(user_id, TaskRun.project_id.in_(list(grouped)))
+ tasks = (await db.execute(stmt)).scalars().unique().all()
+ for task in tasks:
+ grouped[task.project_id].append(task)
+ return grouped
+
+
async def cancel_tasks_for_scope(
db: AsyncSession,
user_id: int,
diff --git a/backend/app/services/tokenfree_image.py b/backend/app/services/tokenfree_image.py
index 37558c5..93390f3 100644
--- a/backend/app/services/tokenfree_image.py
+++ b/backend/app/services/tokenfree_image.py
@@ -9,7 +9,6 @@ import re
from collections.abc import Awaitable, Callable
from typing import Any
-from app.services.tokenfree_gateway import TOKENFREE_CHANNEL_ID
from app.services.tokenfree_video import uses_tokenfree_video
logger = logging.getLogger(__name__)
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 57edce5..c0db982 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -9,7 +9,6 @@ python-jose[cryptography]==3.4.0
passlib[bcrypt]==1.7.4
bcrypt==4.3.0
python-multipart==0.0.20
-celery==5.5.1
redis==5.2.1
httpx==0.28.1
sse-starlette==2.2.1
diff --git a/backend/scripts/run_tests.py b/backend/scripts/run_tests.py
new file mode 100644
index 0000000..50fd7e1
--- /dev/null
+++ b/backend/scripts/run_tests.py
@@ -0,0 +1,23 @@
+"""Run pytest using the isolated local test environment from any directory."""
+from pathlib import Path
+import os
+import sys
+
+from dotenv import load_dotenv
+
+
+def main() -> int:
+ backend = Path(__file__).resolve().parents[1]
+ env_file = backend / ".env.test"
+ if not env_file.is_file():
+ raise SystemExit("Copy backend/.env.test.example to backend/.env.test first.")
+ load_dotenv(env_file, override=True)
+ os.chdir(backend)
+ sys.path.insert(0, str(backend))
+ import pytest
+
+ return pytest.main(sys.argv[1:])
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/backend/tests/test_episode_authoring_quality.py b/backend/tests/test_episode_authoring_quality.py
new file mode 100644
index 0000000..797b8d5
--- /dev/null
+++ b/backend/tests/test_episode_authoring_quality.py
@@ -0,0 +1,58 @@
+"""分集梗概入口、生成失败和旧分镜标识的离线回归。"""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from app.api.drama.episodes import _episode_out
+from app.services.drama import agents
+from app.services.drama.seed import _script_body_fingerprint
+
+
+async def test_full_episode_uses_existing_synopsis_without_regenerating_it(monkeypatch):
+ """用户已确认梗概时,不强制补创意或让模型重写梗概。"""
+ synopsis = "小松鼠藏好松果,冬天找到部分存粮吃饱,春天发现遗忘的种子发芽。" * 3
+ body = "### 场1-1\n日 外 松树林\n出场人物:朵朵\n△ 朵朵埋好种子。\n" * 20
+ chat = AsyncMock(return_value={"episodes": [{"episodeNumber": 1, "title": "春芽", "content": body}]})
+ monkeypatch.setattr(agents, "drama_chat_json", chat)
+ rows = await agents.run_episode_full_from_creative(
+ {"episodeCount": 1}, [], 1, "", summary=synopsis, title="春芽",
+ )
+ assert rows[0]["summary"] == synopsis
+ assert rows[0]["creative"] == ""
+ assert rows[0]["body"] == body.strip()
+ assert chat.await_count == 1
+ assert synopsis in chat.call_args.args[1]
+
+
[email protected]("mode", ["body", "batch", "optimize"])
+async def test_generated_body_still_too_short_after_retry_fails(monkeypatch, mode):
+ """不能把连续失败的短稿作为成功结果传到自动分镜。"""
+ chat = AsyncMock(return_value={"episodes": [{"episodeNumber": 1, "content": "只有一句梗概。"}]})
+ monkeypatch.setattr(agents, "drama_chat_json", chat)
+ with pytest.raises(ValueError, match="正文仍过短"):
+ if mode == "body":
+ await agents.run_episode_body_from_brief({}, [], 1, creative="", summary="本集故事梗概。" * 12)
+ elif mode == "batch":
+ await agents.run_episode_script_batch({"episodeCount": 1}, [], total=1)
+ else:
+ await agents.run_episode_script_from_draft({}, [], 1, "用户的故事草稿。" * 10)
+ assert chat.await_count == 2
+
+
[email protected]("changed", [False, True])
+def test_episode_output_marks_stale_storyboard_without_mutating_params(changed):
+ """正文变更时只标注旧镜,保留镜头并且不写入 ORM params。"""
+ body = "### 场1-1\n日 外 森林\n△ 松鼠埋果。"
+ params = {"episodeNumber": 1, "fragment_source_fp": _script_body_fingerprint(body)}
+ frag = SimpleNamespace(
+ id=2, episode_id=1, sort_order=0, content="@duration:5\n空镜:森林。",
+ cover="", video="", duration_sec=5, params={}, asset_references=[],
+ )
+ episode = SimpleNamespace(id=1, name="春芽", project_id=1, params=params, fragments=[frag])
+ current_body = body + "\n△ 松鼠抬头。" if changed else body
+ out = _episode_out(episode, script_bodies={1: current_body})
+ assert out.params["fragment_script_changed"] is changed
+ assert "fragment_script_changed" not in params
+ assert len(out.fragments) == 1
diff --git a/backend/tests/test_fragment_plan.py b/backend/tests/test_fragment_plan.py
index 53ff01f..7005874 100644
--- a/backend/tests/test_fragment_plan.py
+++ b/backend/tests/test_fragment_plan.py
@@ -200,3 +200,79 @@ def test_normalize_llm_splits_when_durations_exceed_hard_max():
total = sum(int(m) for m in re.findall(r"@duration:(\d+)", draft["content"]))
assert total <= 15
assert draft["duration_sec"] == total
+
+
+def test_llm_short_duration_cannot_squeeze_long_dialogue():
+ import re
+
+ # 99 spoken characters need at least 33 seconds at the documented slow pace.
+ speech = "藏" * 99
+ drafts = normalize_llm_fragment_items(
+ [{"duration_sec": 4, "lines": [f"朵朵:{speech}"]}],
+ [],
+ allow_opening=False,
+ )
+ spoken_parts = []
+ durations = []
+ for draft in drafts:
+ assert draft["duration_sec"] <= 15
+ durations.extend(int(value) for value in re.findall(r"@duration:(\d+)", draft["content"]))
+ spoken_parts.extend(re.findall(r"朵朵:([^\n]+)", draft["content"]))
+ assert "".join(spoken_parts) == speech
+ assert sum(durations) >= 33
+ assert all(3 <= duration <= 12 for duration in durations)
+ assert len(drafts) >= 3
+
+
+def test_short_llm_duration_keeps_dialogue_and_visual_time():
+ drafts = normalize_llm_fragment_items(
+ [{"duration_sec": 4, "lines": ["近景:朵朵捧起一颗松果。", "朵朵:现在藏好松果,冬天就不会饿肚子了。"]}],
+ [],
+ allow_opening=False,
+ )
+ assert sum(draft["duration_sec"] for draft in drafts) >= 8
+ joined = "\n".join(draft["content"] for draft in drafts)
+ assert "朵朵捧起一颗松果" in joined
+ assert "现在藏好松果,冬天就不会饿肚子了。" in joined
+
+
+def test_long_narration_preserves_clauses_when_split_into_timed_beats():
+ import re
+
+ speech = "秋天到了,朵朵每天认真收集松果,把松果藏在不同的树下。冬天来了,它终于明白提前准备的重要,也愿意把找到的松果分给森林里的朋友。"
+ drafts = normalize_llm_fragment_items(
+ [{"duration_sec": 5, "lines": [f"旁白(VO):{speech}"]}],
+ [],
+ allow_opening=False,
+ )
+ pieces = [
+ piece
+ for draft in drafts
+ for piece in re.findall(r"旁白(VO):([^\n]+)", draft["content"])
+ ]
+ assert "".join(pieces) == speech
+ assert len(pieces) >= 2
+ assert sum(draft["duration_sec"] for draft in drafts) >= 19
+
+
+def test_asset_tokens_are_not_counted_as_spoken_markup():
+ assets = [SimpleNamespace(id=123456, type="character", name="朵朵", params={})]
+ drafts = normalize_llm_fragment_items(
+ [{"duration_sec": 4, "character_names": ["朵朵"], "lines": ["朵朵:朵朵最喜欢松果了。"]}],
+ assets,
+ allow_opening=False,
+ )
+ assert len(drafts) == 1
+ assert drafts[0]["duration_sec"] == 3
+ assert "@asset:123456" in drafts[0]["content"]
+
+
+def test_visual_shot_label_is_not_timed_as_a_speaking_character():
+ drafts = normalize_llm_fragment_items(
+ [{"duration_sec": 4, "lines": ["空镜:森林中松树层层叠叠,阳光穿过针叶照亮泥土,风吹叶动。"]}],
+ [],
+ allow_opening=False,
+ )
+ assert len(drafts) == 1
+ assert drafts[0]["duration_sec"] <= 4
+ assert "【画面·无配音仅环境音】空镜:" in drafts[0]["content"]
diff --git a/backend/tests/test_kepu_project_listing.py b/backend/tests/test_kepu_project_listing.py
new file mode 100644
index 0000000..157d98d
--- /dev/null
+++ b/backend/tests/test_kepu_project_listing.py
@@ -0,0 +1,72 @@
+"""科普列表编排回归:筛选、分页、任务运行态与统计共用明确的数据范围。"""
+
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+from sqlalchemy.dialects import postgresql
+
+from app.models import ProjectStatus
+from app.services import kepu_projects
+
+
+# 包装固定的计数或 ORM 行,供离线服务测试模拟数据库返回。
+def _result(value):
+ return SimpleNamespace(scalar_one=lambda: value, scalars=lambda: SimpleNamespace(all=lambda: value))
+
+
+# 构造带完整列表字段的项目,避免测试依赖业务数据库。
+def _project(project_id):
+ return SimpleNamespace(
+ id=project_id, title=f"项目 {project_id}", template_id="test", status=ProjectStatus.DONE,
+ progress=30, cover_url=None, final_video_url=None, error_msg="旧错误", pipeline_mode="full",
+ output_ratio="16:9", created_at=datetime(2026, 10, 20, tzinfo=UTC), updated_at=None,
+ )
+
+
+async def test_listing_batches_tasks_and_projects_runtime_once(monkeypatch):
+ """列表一次获取整页任务,运行态与已发布标记保持原响应语义。"""
+ rows = [_project(12), _project(20)]
+ task = SimpleNamespace(
+ id=99, domain="kepu", task_type="project_pipeline", status="running",
+ progress_percent=60, error_message=None, payload={"phase": "videos"},
+ )
+ batch = AsyncMock(return_value={12: [task], 20: []})
+ monkeypatch.setattr(kepu_projects, "list_active_tasks_for_projects", batch)
+ # 列表总数、当前页、发布 ID、全部/生成中/完成/已发布统计。
+ db = SimpleNamespace(execute=AsyncMock(side_effect=[_result(value) for value in [9, rows, [20], 10, 2, 5, 1]]))
+
+ page = await kepu_projects.list_project_page(
+ db, 7, page=2, page_size=2, status="done", q="测试", pipeline_mode="full",
+ )
+
+ batch.assert_awaited_once_with(db, 7, [12, 20])
+ assert page.meta.model_dump() == {"page": 2, "page_size": 2, "total": 9}
+ assert page.stats.model_dump() == {"total": 10, "generating": 2, "done": 5, "published": 1}
+ assert (page.items[0].status, page.items[0].progress, page.items[0].error_msg) == (ProjectStatus.VIDEOING, 60, None)
+ assert [item.published for item in page.items] == [False, True]
+ assert page.items[1].error_msg == "旧错误"
+
+ compiled = [call.args[0].compile(dialect=postgresql.dialect()) for call in db.execute.await_args_list]
+ # 统计与当前页都保持用户/关键词/类型范围;Tab 仅约束当前页与其总数。
+ for index in [0, 1, 3, 4, 5, 6]:
+ assert "projects.user_id =" in str(compiled[index])
+ assert "%测试%" in compiled[index].params.values()
+ assert "full" in compiled[index].params.values()
+ assert "projects.status =" in str(compiled[0])
+ assert "projects.status =" not in str(compiled[3])
+ assert 2 in compiled[1].params.values() # 分页大小与第二页偏移均为 2。
+
+
+async def test_empty_page_skips_task_and_publish_queries(monkeypatch):
+ """超出末页时仍返回统计,不为不存在的项目查询发布或活动任务。"""
+ batch = AsyncMock()
+ monkeypatch.setattr(kepu_projects, "list_active_tasks_for_projects", batch)
+ db = SimpleNamespace(execute=AsyncMock(side_effect=[_result(value) for value in [0, [], 0, 0, 0, 0]]))
+
+ page = await kepu_projects.list_project_page(db, 7, page=1, page_size=8)
+
+ assert page.items == []
+ assert page.stats.total == 0
+ batch.assert_not_awaited()
+ assert db.execute.await_count == 6
diff --git a/backend/tests/test_llm_fragment_coverage.py b/backend/tests/test_llm_fragment_coverage.py
index ca89785..e83259a 100644
--- a/backend/tests/test_llm_fragment_coverage.py
+++ b/backend/tests/test_llm_fragment_coverage.py
@@ -1,5 +1,7 @@
"""LLM 分镜过少(长正文/多场只 1 镜)应判定不足并回退。"""
+from types import SimpleNamespace
+
from app.services.drama.fragment_plan import llm_fragment_coverage_insufficient
@@ -70,3 +72,78 @@ def test_many_drafts_never_capped_as_insufficient():
body = "### 场1-1\n日内 A\n### 场1-2\n夜外 B\n" + ("旁白。" * 80)
drafts = [{"content": f"@duration:8\n镜{i}", "duration_sec": 8} for i in range(12)]
assert llm_fragment_coverage_insufficient(body, drafts) is False
+
+
+def test_enough_unrelated_drafts_cannot_replace_source_dialogue():
+ body = "\n".join(
+ [
+ "### 场1-1\n日外 林地\n出场人物:朵朵、蹦蹦",
+ "朵朵:现在把松果藏好,冬天就不会饿肚子。",
+ "### 场1-2\n夜外 雪林\n出场人物:朵朵",
+ "朵朵:我记得松果就藏在这棵树下。",
+ "### 场1-3\n日外 松林\n出场人物:蹦蹦",
+ "蹦蹦:你藏的松果都变成新松树啦!",
+ ]
+ )
+ drafts = [{"content": "空镜:云朵飘过天空。", "duration_sec": 8} for _ in range(6)]
+ assert llm_fragment_coverage_insufficient(body, drafts) is True
+
+
+def test_dialogue_coverage_restores_assets_and_ignores_emotion_and_punctuation():
+ body = "朵朵(开心):蹦蹦,你看!我藏的松果变成小树了。"
+ drafts = [
+ {
+ "content": (
+ "@duration:5\n【对白·慢速清晰·同步字幕】@asset:1:@asset:2你看,\n"
+ "@duration:7\n【对白·慢速清晰·同步字幕】@asset:1:我藏的松果变成小树了!"
+ ),
+ "duration_sec": 12,
+ }
+ ]
+ assets = [SimpleNamespace(id=1, name="朵朵"), SimpleNamespace(id=2, name="蹦蹦")]
+ assert llm_fragment_coverage_insufficient(body, drafts, assets=assets) is False
+
+
+def test_dialogue_in_visual_description_does_not_count_as_spoken_coverage():
+ body = "朵朵:现在把松果藏好,冬天就不会饿肚子。"
+ drafts = [{"content": f"【画面·无配音仅环境音】特写:{body}", "duration_sec": 8}]
+ assert llm_fragment_coverage_insufficient(body, drafts) is True
+
+
+def test_dialogue_assigned_to_wrong_character_is_incomplete():
+ body = "朵朵:现在把松果藏好,冬天就不会饿肚子。"
+ drafts = [{"content": "蹦蹦:现在把松果藏好,冬天就不会饿肚子。", "duration_sec": 8}]
+ assert llm_fragment_coverage_insufficient(body, drafts) is True
+
+
+def test_missing_one_main_line_is_incomplete_even_when_other_dialogue_survives():
+ body = "朵朵:现在把松果藏好,冬天就不会饿肚子。\n朵朵:这些被忘记的松果,原来都长成新松树了。"
+ drafts = [
+ {"content": "朵朵:现在把松果藏好,冬天就不会饿肚子。", "duration_sec": 8},
+ {"content": "空镜:金色阳光洒进森林。", "duration_sec": 6},
+ ]
+ assert llm_fragment_coverage_insufficient(body, drafts) is True
+
+
+def test_visual_only_story_can_be_reframed_without_dialogue_false_positive():
+ body = "### 场1-1\n日外 林地\n出场人物:朵朵\n△ 松鼠埋好松果,压平泥土。"
+ drafts = [{"content": "【画面·无配音仅环境音】特写:小爪把泥土轻轻拍实。", "duration_sec": 6}]
+ assert llm_fragment_coverage_insufficient(body, drafts) is False
+
+
+def test_legacy_unknown_assets_do_not_trigger_automatic_dialogue_replan():
+ body = "朵朵:现在把松果藏好,冬天就不会饿肚子。"
+ drafts = [{"content": "【对白·慢速清晰】@asset:42:现在把松果藏好,冬天就不会饿肚子。"}]
+ assert llm_fragment_coverage_insufficient(body, drafts) is False
+
+
+def test_unknown_reference_cannot_bypass_check_when_catalog_is_available():
+ body = "朵朵:现在把松果藏好,冬天就不会饿肚子。"
+ drafts = [{"content": "【对白·慢速清晰】@asset:42:这是一段与原剧本无关的话。"}]
+ assert llm_fragment_coverage_insufficient(body, drafts, assets=[]) is True
+
+
+def test_continuation_does_not_need_to_repeat_locked_dialogue():
+ body = "朵朵:现在把松果藏好,冬天就不会饿肚子。\n蹦蹦:那我们现在就去森林里收集松果吧。"
+ drafts = [{"content": "蹦蹦:那我们现在就去森林里收集松果吧。", "duration_sec": 10}]
+ assert llm_fragment_coverage_insufficient(body, drafts, check_dialogue=False) is False
diff --git a/backend/tests/test_project_runtime_view.py b/backend/tests/test_project_runtime_view.py
index 42da9dc..47faa56 100644
--- a/backend/tests/test_project_runtime_view.py
+++ b/backend/tests/test_project_runtime_view.py
@@ -2,8 +2,10 @@
from types import SimpleNamespace
-from app.api.projects import _project_runtime_view
+import pytest
+
from app.models import ProjectStatus
+from app.services.kepu_projects import project_runtime_view as _project_runtime_view
def _proj(**kwargs):
@@ -49,3 +51,44 @@ def test_no_active_task_keeps_project_status():
status, progress, _ = _project_runtime_view(p)
assert status == ProjectStatus.VIDEOING
assert progress == 81
+
+
+ ("task_type", "expected"),
+ [
+ ("shot_regen_image", ProjectStatus.IMAGING),
+ ("shot_regen_video", ProjectStatus.VIDEOING),
+ ("shot_regen_audio", ProjectStatus.AUDIOING),
+ ("project_regen_audio", ProjectStatus.AUDIOING),
+ ("project_compose_only", ProjectStatus.COMPOSING),
+ ("unknown", ProjectStatus.DONE),
+ ],
+)
+def test_side_tasks_keep_status_projection(task_type, expected):
+ """各任务类型沿用原列表展示状态,未知类型保留项目状态。"""
+ project = _proj(status=ProjectStatus.DONE, active_tasks=[_task(task_type=task_type, progress=90)])
+ assert _project_runtime_view(project) == (expected, 90, None)
+
+
[email protected]("task_status", ["failed", "cancelled"])
+def test_terminal_task_keeps_its_error_and_progress(task_status):
+ """终态任务按任务自身进度展示,错误为空时回退项目错误。"""
+ task = _task(status=task_status, progress=20)
+ project = _proj(progress=81, error_msg="原项目错误", active_tasks=[task])
+ assert _project_runtime_view(project) == (task_status.upper(), 20, "原项目错误")
+ task.error_message = "任务错误"
+ assert _project_runtime_view(project)[2] == "任务错误"
+
+
+def test_pipeline_unknown_phase_keeps_running_stage_or_defaults_to_scripting():
+ """旧任务缺少 phase 时优先沿用进行中阶段,否则显示拆分镜。"""
+ project = _proj(status=ProjectStatus.AUDIOING, active_tasks=[_task(phase="")])
+ assert _project_runtime_view(project)[0] == ProjectStatus.AUDIOING
+ project.status = ProjectStatus.DRAFT
+ assert _project_runtime_view(project)[0] == ProjectStatus.SCRIPTING
+
+
+def test_completed_task_does_not_override_persisted_project_view():
+ """终态成功记录混入活动列表时,仍使用项目持久化进度和错误。"""
+ project = _proj(error_msg="项目错误", active_tasks=[_task(status="succeeded", progress=100)])
+ assert _project_runtime_view(project) == (ProjectStatus.VIDEOING, 81, "项目错误")
diff --git a/backend/tests/test_project_task_batch.py b/backend/tests/test_project_task_batch.py
new file mode 100644
index 0000000..6ae7989
--- /dev/null
+++ b/backend/tests/test_project_task_batch.py
@@ -0,0 +1,71 @@
+"""项目列表活动任务必须批量读取,并保持用户隔离和新任务优先。"""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+from sqlalchemy.dialects import postgresql
+
+from app.services.tasks.service import (
+ ACTIVE_TASK_STATUSES,
+ list_active_tasks_for_owner,
+ list_active_tasks_for_projects,
+)
+
+
+# 模拟 SQLAlchemy 结果链;保留任务顺序供批量分组断言。
+def _result(tasks):
+ rows = SimpleNamespace(all=lambda: tasks)
+ rows.unique = lambda: rows
+ return SimpleNamespace(scalars=lambda: rows)
+
+
+async def test_empty_projects_skip_database():
+ """空列表无需发出 IN 查询。"""
+ db = SimpleNamespace(execute=AsyncMock())
+ assert await list_active_tasks_for_projects(db, 7, []) == {}
+ db.execute.assert_not_awaited()
+
+
+async def test_projects_use_one_scoped_query_and_keep_task_order():
+ """一页项目只查一次任务,且无任务的项目仍返回空列表。"""
+ newest = SimpleNamespace(project_id=12, id=3)
+ older = SimpleNamespace(project_id=12, id=1)
+ other = SimpleNamespace(project_id=20, id=2)
+ db = SimpleNamespace(execute=AsyncMock(return_value=_result([newest, other, older])))
+
+ grouped = await list_active_tasks_for_projects(db, 7, [12, 20, 30, 12])
+
+ assert grouped == {12: [newest, older], 20: [other], 30: []}
+ db.execute.assert_awaited_once()
+ statement = db.execute.await_args.args[0].compile(dialect=postgresql.dialect())
+ sql = str(statement)
+ assert "task_runs.requested_by =" in sql
+ assert "task_runs.project_id IN" in sql
+ assert "task_runs.status IN" in sql
+ assert "ORDER BY task_runs.created_at DESC" in sql
+ assert 7 in statement.params.values()
+ assert [12, 20, 30] in statement.params.values()
+ assert any(set(value) == ACTIVE_TASK_STATUSES for value in statement.params.values() if isinstance(value, (list, tuple)))
+
+
+async def test_projects_without_tasks_return_empty_groups():
+ """整页都没有任务时,仍保留所有项目供列表直接索引。"""
+ db = SimpleNamespace(execute=AsyncMock(return_value=_result([])))
+ assert await list_active_tasks_for_projects(db, 7, [12, 20]) == {12: [], 20: []}
+ db.execute.assert_awaited_once()
+
+
+async def test_owner_without_scope_skips_database():
+ """原单项目查询未传范围时不扩大到用户全部任务。"""
+ db = SimpleNamespace(execute=AsyncMock())
+ assert await list_active_tasks_for_owner(db, 7) == []
+ db.execute.assert_not_awaited()
+
+
+async def test_owner_keeps_project_and_drama_union_scope():
+ """共享查询构造后仍兼容两个项目范围的或条件。"""
+ db = SimpleNamespace(execute=AsyncMock(return_value=_result([])))
+ assert await list_active_tasks_for_owner(db, 7, project_id=12, drama_project_id=20) == []
+ statement = db.execute.await_args.args[0].compile(dialect=postgresql.dialect())
+ assert "(task_runs.project_id =" in str(statement)
+ assert " OR task_runs.drama_project_id =" in str(statement)
diff --git a/backend/tests/test_summary_character_seed_filter.py b/backend/tests/test_summary_character_seed_filter.py
new file mode 100644
index 0000000..de238fd
--- /dev/null
+++ b/backend/tests/test_summary_character_seed_filter.py
@@ -0,0 +1,125 @@
+"""角色 seed 的类别纠错:纯函数回归,不连接数据库或调用模型。"""
+
+from copy import deepcopy
+
+import pytest
+
+from app.services.drama.seed import collect_episode_seed_names
+from app.services.drama.summary_character_filter import partition_summary_characters
+
+
+def test_rejects_explicit_environment_and_non_anthropomorphic_seed_objects():
+ summary = {
+ "characters": [
+ {"name": "朵朵", "roleType": "主角", "visualImage": "幼年小松鼠"},
+ {"name": "蹦蹦", "roleType": "配角", "visualImage": "幼年灰兔"},
+ {
+ "name": "松果们",
+ "roleType": "特殊群体角色",
+ "visualImage": "非拟人化角色,以CGI精细呈现:成熟松果棕褐鳞片层叠。",
+ "identityBackground": "森林原生植物种子,承担食物与繁殖双重功能",
+ },
+ {
+ "name": "森林",
+ "roleType": "场景/氛围角色",
+ "visualImage": "非人物,以环境拟态呈现:秋季树冠如金红云团。",
+ "identityBackground": "温带针阔混交林生态系统,无意志但有规律",
+ },
+ ]
+ }
+ original = deepcopy(summary)
+
+ accepted, excluded = partition_summary_characters(summary)
+
+ assert list(accepted) == ["朵朵", "蹦蹦"]
+ assert excluded == {"松果们", "森林"}
+ assert summary == original
+
+
+ "character",
+ [
+ {"name": "村民们", "roleType": "特殊群体角色", "visualImage": "一群村民"},
+ {"name": "树妖", "roleType": "场景/氛围角色", "identityBackground": "有自主意识的古树"},
+ {"name": "小铁", "roleType": "道具", "visualImage": "拟人化机器人,能够和主人对话"},
+ {"name": "松果精灵", "roleType": "特殊群体角色", "identityBackground": "由植物种子化成的精灵"},
+ {"name": "朵朵", "roleType": "主角", "visualImage": "非拟人化角色,以真实松鼠形态行动"},
+ {
+ "name": "朵朵",
+ "roleType": "主角",
+ "visualImage": "非拟人化角色,一只叼着植物种子的松鼠",
+ "identityBackground": "在林间寻找种子的小松鼠",
+ },
+ {"name": "森林", "roleType": "配角", "title": "森林守护者", "visualImage": "一名年轻女孩"},
+ {"name": "道具师", "roleType": "道具", "identityBackground": "负责舞台道具的工作人员"},
+ {"name": "木匣", "roleType": "配角", "identityBackground": "普通木制道具"},
+ ],
+)
+def test_keeps_real_characters_and_ambiguous_entries(character):
+ accepted, excluded = partition_summary_characters({"characters": [character]})
+ assert accepted == {character["name"]: character}
+ assert excluded == set()
+
+
+ "role_type, visual, identity",
+ [
+ ("道具", "普通木制匣子", "无生命器物"),
+ ("非拟人化道具", "普通木制匣子", "存放信件的道具"),
+ ("场景", "无人居住的旧宅", "一座建筑"),
+ ("氛围角色", "非人物,四季变化的环境", ""),
+ ("非人物", "无生命的石头", ""),
+ ],
+)
+def test_rejects_clearly_declared_non_character_assets(role_type, visual, identity):
+ accepted, excluded = partition_summary_characters(
+ {"characters": [{"name": "测试项", "roleType": role_type, "visualImage": visual, "identityBackground": identity}]}
+ )
+ assert accepted == {}
+ assert excluded == {"测试项"}
+
+
+def test_invalid_entries_and_valid_duplicate_do_not_block_real_cast():
+ real = {"name": "森林", "roleType": "主角", "visualImage": "一名人类探险家"}
+ summary = {
+ "characters": [
+ None,
+ "bad",
+ {},
+ {"name": "森林", "roleType": "场景", "visualImage": "非人物,生态环境"},
+ real,
+ ]
+ }
+ accepted, excluded = partition_summary_characters(summary)
+ assert accepted == {"森林": real}
+ assert excluded == set()
+
+
+def test_cast_cannot_reintroduce_summary_entries_identified_as_non_characters():
+ summary = {
+ "characters": [
+ {"name": "朵朵", "roleType": "主角"},
+ {"name": "森林", "roleType": "场景/氛围角色", "visualImage": "非人物,生态环境"},
+ {
+ "name": "松果们",
+ "roleType": "特殊群体角色",
+ "visualImage": "非拟人化角色,成熟的松果",
+ "identityBackground": "森林原生植物种子",
+ },
+ ]
+ }
+ body = "### 场1-1\n日 外 林间\n出场人物:朵朵、森林、松果们、蹦蹦\n△ 朵朵埋下松果。"
+
+ characters, scenes, by_name = collect_episode_seed_names(summary, body)
+
+ assert characters == ["朵朵", "蹦蹦"]
+ assert scenes == ["林间"]
+ assert list(by_name) == ["朵朵"]
+
+
+def test_undeclared_cast_names_still_seed_normally():
+ names, _, _ = collect_episode_seed_names(
+ {"characters": []},
+ "### 场1-1\n日 外 林间\n出场人物:树妖、机器人、村民们\n△ 大家相遇。",
+ )
+ assert names == ["树妖", "机器人", "村民们"]
diff --git a/backend/tests/test_task_runtime_lifecycle.py b/backend/tests/test_task_runtime_lifecycle.py
new file mode 100644
index 0000000..976c9ff
--- /dev/null
+++ b/backend/tests/test_task_runtime_lifecycle.py
@@ -0,0 +1,81 @@
+"""任务平台启动回滚、关闭清理与健康摘要的回归测试。"""
+
+import asyncio
+from unittest.mock import AsyncMock
+
+import pytest
+
+from app.services.tasks import runtime
+
+
+def components(monkeypatch):
+ """替换组件生命周期,避免测试连接数据库或启动后台任务。"""
+ mocks = {}
+ for name in ("scheduler", "poller", "watchdog"):
+ for action in ("start", "stop"):
+ key = f"{action}_{name}"
+ mocks[key] = AsyncMock()
+ monkeypatch.setattr(runtime, key, mocks[key])
+ return mocks
+
+
+async def test_successful_start_keeps_components_running(components):
+ """启动成功后不应触发回滚。"""
+ await runtime.start_task_runtime()
+ for name in ("scheduler", "poller", "watchdog"):
+ components[f"start_{name}"].assert_awaited_once()
+ components[f"stop_{name}"].assert_not_awaited()
+
+
[email protected]("failure", [RuntimeError("启动失败"), asyncio.CancelledError()])
[email protected]("failed_component", ["scheduler", "poller", "watchdog"])
+async def test_start_failure_rolls_back_started_components(components, failure, failed_component):
+ """启动异常或取消时,仅清理此前成功启动的组件。"""
+ names = ("scheduler", "poller", "watchdog")
+ components[f"start_{failed_component}"].side_effect = failure
+ with pytest.raises(type(failure)):
+ await runtime.start_task_runtime()
+ for index, name in enumerate(names):
+ if index < names.index(failed_component):
+ components[f"stop_{name}"].assert_awaited_once()
+ else:
+ components[f"stop_{name}"].assert_not_awaited()
+ if index > names.index(failed_component):
+ components[f"start_{name}"].assert_not_awaited()
+
+
[email protected]("failed_component", ["watchdog", "poller", "scheduler"])
[email protected]("failure", [RuntimeError("关闭失败"), asyncio.CancelledError()])
+async def test_stop_failure_still_cleans_up_remaining_components(components, failed_component, failure):
+ """关闭报错或取消不能跳过其余组件的清理。"""
+ components[f"stop_{failed_component}"].side_effect = failure
+ with pytest.raises(type(failure)):
+ await runtime.stop_task_runtime()
+ for name in ("watchdog", "poller", "scheduler"):
+ components[f"stop_{name}"].assert_awaited_once()
+
+
[email protected]("scheduler_running", [True, False])
[email protected]("poller_running", [True, False])
[email protected]("watchdog_running", [True, False])
[email protected]("scheduler_stale,poller_stale", [(False, False), (True, False), (False, True), (True, True)])
+def test_health_requires_live_components_and_fresh_heartbeats(
+ monkeypatch, scheduler_running, poller_running, watchdog_running, scheduler_stale, poller_stale,
+):
+ """运行状态与心跳都正常时,健康摘要才能报告 healthy。"""
+ for name, running in (("scheduler", scheduler_running), ("poller", poller_running), ("watchdog", watchdog_running)):
+ monkeypatch.setattr(runtime, f"{name}_status", lambda running=running: "running" if running else "stopped")
+ monkeypatch.setattr(runtime, "scheduler_tick_stale", lambda: scheduler_stale)
+ monkeypatch.setattr(runtime, "poller_tick_stale", lambda: poller_stale)
+ monkeypatch.setattr(runtime, "scheduler_tick_age_sec", lambda: 120.0 if scheduler_stale else 1.0)
+ monkeypatch.setattr(runtime, "poller_tick_age_sec", lambda: 120.0 if poller_stale else 1.0)
+ monkeypatch.setattr(runtime, "running_count", lambda: 2)
+ summary = runtime.runtime_summary()
+ assert summary["healthy"] is (
+ scheduler_running and poller_running and watchdog_running and not scheduler_stale and not poller_stale
+ )
+ assert summary["scheduler_running_jobs"] == 2
diff --git a/deploy/.env.prod.example b/deploy/.env.prod.example
index 7d26a8f..5a490f2 100644
--- a/deploy/.env.prod.example
+++ b/deploy/.env.prod.example
@@ -8,11 +8,9 @@ REDIS_PORT=16379
SECRET_KEY=change-me-to-a-long-random-string
DATABASE_URL=postgresql+asyncpg://printfilm:[email protected]:15432/printfilm
DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:[email protected]:15432/printfilm
-# API 连接池(uvicorn 建议 --workers 1);Worker unit 设 PRINTFILM_DB_ROLE=celery
+# API 与进程内任务平台共用连接池(uvicorn 建议 --workers 1)
DB_POOL_SIZE=5
DB_MAX_OVERFLOW=5
-DB_POOL_SIZE_CELERY=2
-DB_MAX_OVERFLOW_CELERY=3
REDIS_URL=redis://127.0.0.1:16379/0
PUBLIC_BASE_URL=https://your-site.example.com
@@ -28,7 +26,6 @@ OPENAI_API_KEY=your-tokenfree-api-key
OPENAI_BASE_URL=https://www.tokenfree.com/v1
MODEL_LLM=kimi-k2.6
-USE_CELERY=true
QUOTA_ENABLED=false
BILLING_ENABLED=true
@@ -41,6 +38,6 @@ EPAY_KEY=
EPAY_NOTIFY_URL=https://www.printfilm.com/epay/notify
EPAY_RETURN_URL=https://www.printfilm.com/pricing?paid=1
-CELERY_AUTOSCALE_MIN=1
-CELERY_AUTOSCALE_MAX=3
-CELERY_WORKER_QUEUES=drama,oss,video,pipeline
+# 统一任务平台:全站与单用户执行槽位
+TASK_RUNTIME_MAX_CONCURRENCY=4
+TASK_USER_MAX_CONCURRENCY=4
diff --git a/deploy/README.md b/deploy/README.md
index a580e32..a26718d 100644
--- a/deploy/README.md
+++ b/deploy/README.md
@@ -10,7 +10,7 @@
|------|----------|
| PostgreSQL | Docker |
| Redis | Docker |
-| FastAPI / Celery worker | 宿主机 Python 进程 |
+| FastAPI / 进程内任务平台 | 同一个宿主机 Python 进程 |
| 前端 / 管理后台 | 宿主机 `npm run build` + nginx 静态托管 |
## 1. 启动中间件(独立目录,不复用其它项目的库)
@@ -35,7 +35,8 @@ Postgres / Redis 端口均映射为 `0.0.0.0`(便于本机直连调试)。
DATABASE_URL=postgresql+asyncpg://printfilm:<密码>@127.0.0.1:5432/printfilm
DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:<密码>@127.0.0.1:5432/printfilm
REDIS_URL=redis://127.0.0.1:6379/0
-USE_CELERY=true
+TASK_RUNTIME_MAX_CONCURRENCY=4
+TASK_USER_MAX_CONCURRENCY=4
```
需本机已安装:Python 3.12、FFmpeg(PATH)、Node.js。
@@ -50,7 +51,7 @@ sudo apt-get install -y fonts-wqy-zenhei fonts-wqy-microhei fontconfig
缺字体时字幕会显示为「方框」(□),需装字体后**重新合成**该项目成片。
-## 3. 启动 API + Worker
+## 3. 启动 API 与任务平台
```bash
cd backend
@@ -62,6 +63,8 @@ pip install -r requirements.txt
uvicorn app.main:app --host 0.0.0.0 --port 8000
```
+调度器、执行器、轮询器与看门狗随 API 启动,无需单独的 Celery worker。OSS 上传在后台协程执行。
+
## 4. 前端
```bash
diff --git a/deploy/scripts/migrate_media_to_oss.py b/deploy/scripts/migrate_media_to_oss.py
index 1aa6ac8..466d76e 100644
--- a/deploy/scripts/migrate_media_to_oss.py
+++ b/deploy/scripts/migrate_media_to_oss.py
@@ -104,7 +104,7 @@ def main() -> None:
parser.add_argument(
"--enqueue",
action="store_true",
- help="Enqueue Celery oss uploads instead of sync upload+DB write",
+ help="Queue background OSS uploads instead of synchronous upload and DB update",
)
args = parser.parse_args()
asyncio.run(run(dry_run=args.dry_run, enqueue=args.enqueue))
diff --git a/docs/STANDARDS.md b/docs/STANDARDS.md
index 671960f..748fc34 100644
--- a/docs/STANDARDS.md
+++ b/docs/STANDARDS.md
@@ -71,7 +71,7 @@ backend/app/
services/ 业务逻辑、流水线、方舟/OSS/计费
models*.py ORM
schemas*.py Pydantic 入出参
- workers/ Celery / autoscale
+ services/tasks/ 进程内调度、执行、轮询与看门狗
frontend/src/
pages/ 路由页(studio / drama / …)
components/ 可复用 UI
@@ -104,6 +104,7 @@ docs/ 产品与工程文档(本规范所在处)
- 样式以 **`styles/printfilm.css` + 语义化 class(`pf-*`)** 为主,与现有视觉体系统一。
- 路由与壳:`AppShell` / `SiteNav`;漫剧页 `active="drama"`。
- 请求统一走 `src/api.ts` / `src/api/*`;错误用可读中文抛给 UI。
+- `api/http.ts` 只负责可独立测试的 HTTP 传输与响应解析,`api/client.ts` 绑定浏览器地址、登录态和错误展示;业务模块复用它们,不再各自维护 `fetch` 包装器。
- 列表筛选、分页:**服务端分页**(见历史页 `/api/projects`);禁止只在前端 slice 全量列表当长期方案。
- 组件内临时 UI 状态用 `useState`;跨页共享若出现,优先评估提升到明确模块,避免隐式全局变量。
@@ -112,6 +113,8 @@ docs/ 产品与工程文档(本规范所在处)
- **Tailwind + shadcn/ui**;用 `cn()` 合并 class。
- 复杂运营台布局可用 `admin-*.css` / `index.css` 中的语义 class(与用户端 `pf-*` 分离)。
- 分页组件复用 `PaginationBar`;列表接口带 `page` / `page_size` / `meta`。
+- `api/client.ts` 维护请求与登录能力,接口类型按领域放在 `api/types/`;旧路径保留类型导出,避免页面随内部拆分批量改动。
+- 财务列表统一调用 `api/finance.ts`,订单与流水详情放在 `components/finance/`,页面只编排筛选、分页和交互状态。
### 4.3 交互与可访问性
@@ -129,11 +132,14 @@ docs/ 产品与工程文档(本规范所在处)
- 鉴权:用户接口 `get_current_user`;管理 `get_current_admin`。
- 入参用 Pydantic;出参明确 `response_model`。
- 列表默认:**分页**(`page`、`page_size`、`meta.total`),并支持必要筛选参数。
+- 项目列表的筛选、统计和运行态投影放在 `services/kepu_projects.py`;关联活动任务按整页项目批量读取,复用任务服务的用户隔离与加载规则。
- 错误:业务用 `HTTPException`,对外 `detail` 为中文短句;勿把堆栈直接回给前端。
### 5.2 异步与任务
-- 长任务走 Celery(`pipeline` / `oss` 队列);`USE_CELERY=true` 时本地也要起 worker。
+- 长任务走 `services/tasks/` 统一任务平台,由 FastAPI 进程内的调度器、执行器和轮询器处理;不需要单独启动 Celery worker。
+- 运行时按调度器、轮询器、看门狗的顺序启动,启动失败时逆序清理已启动组件;关闭某个组件失败也必须继续清理其余组件。
+- 健康摘要同时检查组件存活和心跳是否过期;轮询下载期间沿用轮询器自身的心跳宽限规则。
- 启动 `seed_*` 不得阻塞过久:已有 OSS URL 勿重复同步上传。
- 多 worker 下注意 `create_all` / 迁移竞态;生产 API 建议单 worker 或显式迁移策略。
diff --git a/frontend/README.md b/frontend/README.md
index d6af7e3..62a258d 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -1,32 +1,40 @@
-# React + TypeScript + Vite
+# PRINTFILM 用户端
-This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
+React 19、TypeScript 与 Vite 用户端。管理后台位于仓库的 `admin/`,两端分别构建。
-Currently, two official plugins are available:
+## 本地开发与检查
-- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
-- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
+使用 Node.js 22.21 或更高版本,在本目录执行:
-## React Compiler
+```bash
+npm ci
+npm run dev
+npm test
+npm run lint
+npm run build
+```
-The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
+`npm test` 使用 Node 内建测试运行器及 TypeScript 类型擦除,无需额外测试框架。目前覆盖 API 地址解析、动态登录态、请求头覆盖、文件上传、下载及错误处理;不需要后端服务。
-## Expanding the Oxlint configuration
+## 目录职责
-If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
+| 目录 / 文件 | 职责 |
+|---|---|
+| `src/pages/` | 路由页面与交互编排 |
+| `src/components/` | 通用 UI 及按业务分组的组件 |
+| `src/hooks/` | 可复用的 React 状态与订阅 |
+| `src/lib/` | 纯函数与业务工具,新增逻辑前先查找已有实现 |
+| `src/api/http.ts` | 可独立测试的 HTTP 传输、请求头合并与错误文案解析 |
+| `src/api/client.ts` | 浏览器配置、登录态、计费错误提示及通用上传的统一入口 |
+| `src/api.ts`、`src/api/*.ts` | 各业务接口及类型;通过共享客户端发送请求 |
+| `src/styles/printfilm.css` | `pf-*` 语义样式,保持现有视觉体系 |
-```json
-{
- "$schema": "./node_modules/oxlint/configuration_schema.json",
- "plugins": ["react", "typescript", "oxc"],
- "options": {
- "typeAware": true
- },
- "rules": {
- "react/rules-of-hooks": "error",
- "react/only-export-components": ["warn", { "allowConstantExport": true }]
- }
-}
-```
+业务模块通过 `createJsonRequester` 复用请求实现,并保留自身错误提示;单文件上传使用 `uploadFile`,非 JSON 下载使用 `requestResponse`。不要在页面重新拼鉴权头或复制 `fetch` 包装器。
+
+## API 地址
+
+- 未设置 `VITE_API_BASE`:使用当前主机的 `8000` 端口。
+- 显式设为空字符串:请求同源 `/api`,供生产 Nginx 反向代理。
+- 设为完整地址:请求指定 API 服务。
-See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
+Vite 未配置开发 API 代理。详细工程规范见仓库的 `docs/STANDARDS.md`。
diff --git a/frontend/package.json b/frontend/package.json
index b0f4e1b..072c82e 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -7,6 +7,7 @@
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint",
+ "test": "node --experimental-strip-types --test tests/*.test.mjs",
"preview": "vite preview"
},
"dependencies": {
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index 93cb857..f5f5fbe 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -1,37 +1,8 @@
-import { throwApiError } from './lib/apiError'
+import { API_BASE, createJsonRequester, requestResponse, uploadFile } from './api/client'
+import { apiErrorMessage } from './api/http'
-function defaultApiBase() {
- if (typeof window !== 'undefined' && window.location?.hostname) {
- const { protocol, hostname } = window.location
- // Same host as Vite; API listens on 8000 for LAN + local
- return `${protocol}//${hostname}:8000`
- }
- return 'http://127.0.0.1:8000'
-}
-
-// Empty string = same-origin (nginx proxies /api). Undefined = LAN default :8000.
-const _viteApiBase = import.meta.env.VITE_API_BASE
-const API_BASE =
- _viteApiBase === undefined || _viteApiBase === null ? defaultApiBase() : String(_viteApiBase)
-
-function authHeaders(): HeadersInit {
- const token = localStorage.getItem('token')
- return token
- ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }
- : { 'Content-Type': 'application/json' }
-}
-
-async function request<T>(path: string, init?: RequestInit): Promise<T> {
- const res = await fetch(`${API_BASE}${path}`, {
- ...init,
- headers: { ...authHeaders(), ...(init?.headers || {}) },
- })
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- throwApiError(res.status, err.detail, res.statusText)
- }
- return res.json()
-}
+/** 科普、账号和计费 API 共用 JSON 传输层。 */
+const request = createJsonRequester()
export type PipelineMode = 'full' | 'image_text'
@@ -356,27 +327,11 @@ export const api = {
body: JSON.stringify(body),
})
},
- async uploadAvatar(file: File) {
- const token = localStorage.getItem('token')
- const form = new FormData()
- form.append('file', file)
- const res = await fetch(`${API_BASE}/api/auth/avatar`, {
- method: 'POST',
- headers: token ? { Authorization: `Bearer ${token}` } : {},
- body: form,
+ /** 上传用户头像并返回更新后的用户资料。 */
+ uploadAvatar(file: File) {
+ return uploadFile<User>('/api/auth/avatar', file, (response, detail) => {
+ throw new Error(apiErrorMessage(detail, response.statusText) || '头像上传失败')
})
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- const detail = err.detail
- const message =
- typeof detail === 'string'
- ? detail
- : Array.isArray(detail)
- ? detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
- : res.statusText
- throw new Error(message || '头像上传失败')
- }
- return res.json() as Promise<User>
},
templates() {
return request<Template[]>('/api/templates')
@@ -425,27 +380,11 @@ export const api = {
mediaModels() {
return request<MediaModelsCatalog>('/api/media-models')
},
- async uploadCover(id: number, file: File) {
- const token = localStorage.getItem('token')
- const form = new FormData()
- form.append('file', file)
- const res = await fetch(`${API_BASE}/api/projects/${id}/cover`, {
- method: 'POST',
- headers: token ? { Authorization: `Bearer ${token}` } : {},
- body: form,
+ /** 上传科普项目封面并返回项目。 */
+ uploadCover(id: number, file: File) {
+ return uploadFile<Project>(`/api/projects/${id}/cover`, file, (response, detail) => {
+ throw new Error(apiErrorMessage(detail, response.statusText) || '封面上传失败')
})
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- const detail = err.detail
- const message =
- typeof detail === 'string'
- ? detail
- : Array.isArray(detail)
- ? detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
- : res.statusText
- throw new Error(message || '封面上传失败')
- }
- return res.json() as Promise<Project>
},
voices() {
return request<VoicePreset[]>('/api/voices')
@@ -491,23 +430,14 @@ export const api = {
stats: { total: number; generating: number; done: number; published: number }
}>(`/api/projects${qs ? `?${qs}` : ''}`)
},
+ /** 打包下载选中项目的视频,保留服务端文件名。 */
async downloadZip(ids: number[]) {
- const res = await fetch(`${API_BASE}/api/projects/download-zip`, {
+ const res = await requestResponse('/api/projects/download-zip', {
method: 'POST',
- headers: authHeaders(),
body: JSON.stringify({ ids }),
+ }, (response, detail) => {
+ throw new Error(apiErrorMessage(detail, response.statusText) || '打包下载失败')
})
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- const detail = err.detail
- const message =
- typeof detail === 'string'
- ? detail
- : Array.isArray(detail)
- ? detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
- : res.statusText
- throw new Error(message || '打包下载失败')
- }
const blob = await res.blob()
const cd = res.headers.get('Content-Disposition') || ''
const m = cd.match(/filename="?([^"]+)"?/)
@@ -542,21 +472,11 @@ export const api = {
body: JSON.stringify({ shot_ids: shotIds }),
})
},
- async uploadShotImage(projectId: number, shotId: number, file: File) {
- const token = localStorage.getItem('token')
- const form = new FormData()
- form.append('file', file)
- const res = await fetch(`${API_BASE}/api/projects/${projectId}/shots/${shotId}/image`, {
- method: 'POST',
- headers: token ? { Authorization: `Bearer ${token}` } : {},
- body: form,
- })
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- const detail = err.detail
+ /** 上传分镜图片,保留当前项目响应结构。 */
+ uploadShotImage(projectId: number, shotId: number, file: File) {
+ return uploadFile<Project>(`/api/projects/${projectId}/shots/${shotId}/image`, file, (_response, detail) => {
throw new Error(typeof detail === 'string' ? detail : '画面上传失败')
- }
- return res.json() as Promise<Project>
+ })
},
regenImage(projectId: number, shotId: number) {
return request<Project>(`/api/projects/${projectId}/shots/${shotId}/regen-image`, {
diff --git a/frontend/src/api/agentSkills.ts b/frontend/src/api/agentSkills.ts
index a0fc1aa..101d798 100644
--- a/frontend/src/api/agentSkills.ts
+++ b/frontend/src/api/agentSkills.ts
@@ -1,29 +1,11 @@
/** Agent Skill API:列表 / 上传 / 启用 / 删除 */
-import { getDramaApiBase } from './drama'
+import { createJsonRequester, uploadFile } from './client'
-/** 组装请求头;FormData 时不要强行 JSON */
-function authHeaders(json = true): HeadersInit {
- const token = localStorage.getItem('token')
- const headers: Record<string, string> = {}
- if (token) headers.Authorization = `Bearer ${token}`
- if (json) headers['Content-Type'] = 'application/json'
- return headers
-}
-
-/** 带登录态请求 Agent Skill API */
-async function request<T>(path: string, init?: RequestInit): Promise<T> {
- const res = await fetch(`${getDramaApiBase()}${path}`, {
- ...init,
- headers: { ...authHeaders(init?.body instanceof FormData ? false : true), ...(init?.headers || {}) },
- })
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- const detail = err.detail
- throw new Error(typeof detail === 'string' ? detail : '请求失败')
- }
- return res.json()
-}
+/** Skill API 保留本模块的错误文案,避免依赖漫剧客户端。 */
+const request = createJsonRequester((_response, detail) => {
+ throw new Error(typeof detail === 'string' ? detail : '请求失败')
+})
export type AgentSkill = {
id: number
@@ -53,20 +35,10 @@ export function uploadAgentSkillMarkdown(markdown: string) {
}
/** 上传 .md 文件 */
-export async function uploadAgentSkillFile(file: File) {
- const token = localStorage.getItem('token')
- const body = new FormData()
- body.append('file', file)
- const res = await fetch(`${getDramaApiBase()}/api/drama/skills/upload`, {
- method: 'POST',
- headers: token ? { Authorization: `Bearer ${token}` } : undefined,
- body,
+export function uploadAgentSkillFile(file: File) {
+ return uploadFile<AgentSkill>('/api/drama/skills/upload', file, (_response, detail) => {
+ throw new Error(typeof detail === 'string' ? detail : '上传失败')
})
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- throw new Error(typeof err.detail === 'string' ? err.detail : '上传失败')
- }
- return res.json() as Promise<AgentSkill>
}
/** 启用/停用或改正文 */
diff --git a/frontend/src/api/apiKeys.ts b/frontend/src/api/apiKeys.ts
index 6414a18..f815e53 100644
--- a/frontend/src/api/apiKeys.ts
+++ b/frontend/src/api/apiKeys.ts
@@ -1,17 +1,12 @@
/** API Key 管理客户端(/api/user/api-keys) */
-function defaultApiBase() {
- if (typeof window !== 'undefined' && window.location?.hostname) {
- const { protocol, hostname } = window.location
- return `${protocol}//${hostname}:8000`
- }
- return 'http://127.0.0.1:8000'
-}
+import { API_BASE, createJsonRequester } from './client'
+import { apiErrorMessage } from './http'
-const API_BASE =
- import.meta.env.VITE_API_BASE === undefined || import.meta.env.VITE_API_BASE === null
- ? defaultApiBase()
- : String(import.meta.env.VITE_API_BASE)
+/** API Key 错误仅交由当前页面展示,不触发计费弹窗。 */
+const request = createJsonRequester((response, detail) => {
+ throw new Error(apiErrorMessage(detail, response.statusText) || '请求失败')
+})
export type ApiKeyItem = {
id: number
@@ -25,30 +20,7 @@ export type ApiKeyCreated = ApiKeyItem & {
secret: string
}
-async function request<T>(path: string, init?: RequestInit): Promise<T> {
- const token = localStorage.getItem('token')
- const res = await fetch(`${API_BASE}${path}`, {
- ...init,
- headers: {
- 'Content-Type': 'application/json',
- ...(token ? { Authorization: `Bearer ${token}` } : {}),
- ...(init?.headers || {}),
- },
- })
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- const detail = err.detail
- const message =
- typeof detail === 'string'
- ? detail
- : Array.isArray(detail)
- ? detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
- : res.statusText
- throw new Error(message || '请求失败')
- }
- return res.json() as Promise<T>
-}
-
+/** 返回开放 API 调用示例使用的服务根地址。 */
export function getPublicApiBase() {
return API_BASE
}
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
new file mode 100644
index 0000000..fd4358c
--- /dev/null
+++ b/frontend/src/api/client.ts
@@ -0,0 +1,32 @@
+import { throwApiError } from '../lib/apiError'
+import { createHttpTransport, resolveApiBase } from './http'
+import type { ApiErrorHandler } from './http'
+
+/** 用户端统一 API 地址;空值为生产同源,未设置时使用开发端口 8000。 */
+export const API_BASE = resolveApiBase(
+ import.meta.env.VITE_API_BASE,
+ typeof window === 'undefined' ? undefined : window.location,
+)
+
+/** 默认保留全局计费提示,上传和工具请求可以显式传入原有错误处理。 */
+const transport = createHttpTransport({
+ baseUrl: API_BASE,
+ getToken: () => localStorage.getItem('token'),
+ onError: (response, detail) => throwApiError(response.status, detail, response.statusText),
+})
+
+/** 共用鉴权与错误解析,返回原始响应以支持文件下载。 */
+export const requestResponse = transport.response
+
+/** 为业务模块绑定固定错误策略,同时复用 JSON 请求实现。 */
+export function createJsonRequester(onError?: ApiErrorHandler) {
+ // 对外保留泛型返回值,避免每个业务模块重复实现 fetch 包装器。
+ return <T>(path: string, init?: RequestInit): Promise<T> => transport.json<T>(path, init, onError)
+}
+
+/** 统一单文件上传字段与 multipart 请求,业务模块只提供路径和错误策略。 */
+export function uploadFile<T>(path: string, file: File, onError?: ApiErrorHandler): Promise<T> {
+ const body = new FormData()
+ body.append('file', file)
+ return transport.json<T>(path, { method: 'POST', body }, onError)
+}
diff --git a/frontend/src/api/drama.ts b/frontend/src/api/drama.ts
index c287148..3cc5b76 100644
--- a/frontend/src/api/drama.ts
+++ b/frontend/src/api/drama.ts
@@ -1,16 +1,11 @@
import { throwApiError } from '../lib/apiError'
+import { API_BASE, createJsonRequester, uploadFile } from './client'
+import { apiErrorMessage } from './http'
-function defaultApiBase() {
- if (typeof window !== 'undefined' && window.location?.hostname) {
- const { protocol, hostname } = window.location
- return `${protocol}//${hostname}:8000`
- }
- return 'http://127.0.0.1:8000'
-}
-
-const _viteApiBase = import.meta.env.VITE_API_BASE
-const API_BASE =
- _viteApiBase === undefined || _viteApiBase === null ? defaultApiBase() : String(_viteApiBase)
+/** 漫剧 API 沿用原有错误提示,并共用登录态与 JSON 解析。 */
+const request = createJsonRequester((response, detail) =>
+ throwApiError(response.status, detail, '请求失败'),
+)
/** 导出 API 根地址,供静态资源 URL 拼接 */
export function getDramaApiBase() {
@@ -45,25 +40,6 @@ export function resolveDramaAssetPreviewUrl(asset: {
return resolveDramaMediaUrl(raw, bust || null)
}
-function authHeaders(): HeadersInit {
- const token = localStorage.getItem('token')
- return token
- ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }
- : { 'Content-Type': 'application/json' }
-}
-
-async function request<T>(path: string, init?: RequestInit): Promise<T> {
- const res = await fetch(`${API_BASE}${path}`, {
- ...init,
- headers: { ...authHeaders(), ...(init?.headers || {}) },
- })
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- throwApiError(res.status, err.detail, '请求失败')
- }
- return res.json()
-}
-
export type DramaScript = {
id: number
name: string
@@ -335,28 +311,11 @@ export const dramaApi = {
request<DramaAsset>('/api/drama/assets', { method: 'POST', body: JSON.stringify(body) }),
updateAsset: (id: number, body: Partial<DramaAsset>) =>
request<DramaAsset>(`/api/drama/assets/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),
- uploadAssetMedia: async (assetId: number, file: File) => {
- const token = localStorage.getItem('token')
- const form = new FormData()
- form.append('file', file)
- const res = await fetch(`${API_BASE}/api/drama/assets/${assetId}/upload`, {
- method: 'POST',
- headers: token ? { Authorization: `Bearer ${token}` } : {},
- body: form,
- })
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- const detail = err.detail
- const message =
- typeof detail === 'string'
- ? detail
- : Array.isArray(detail)
- ? detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
- : res.statusText
- throw new Error(message || '上传失败')
- }
- return res.json() as Promise<DramaAsset>
- },
+ /** 上传资产媒体并返回更新后的资产。 */
+ uploadAssetMedia: (assetId: number, file: File) =>
+ uploadFile<DramaAsset>(`/api/drama/assets/${assetId}/upload`, file, (response, detail) => {
+ throw new Error(apiErrorMessage(detail, response.statusText) || '上传失败')
+ }),
activateAssetImageVersion: (assetId: number, versionId: string) =>
request<DramaAsset>(`/api/drama/assets/${assetId}/activate_image_version`, {
method: 'POST',
diff --git a/frontend/src/api/http.ts b/frontend/src/api/http.ts
new file mode 100644
index 0000000..e444148
--- /dev/null
+++ b/frontend/src/api/http.ts
@@ -0,0 +1,68 @@
+/** HTTP 基础能力:地址、登录态和响应解析;不依赖浏览器全局配置或业务模块。 */
+
+/** 将 FastAPI 的字符串或校验错误数组转换为可展示文案。 */
+export function apiErrorMessage(detail: unknown, fallback: string): string {
+ if (typeof detail === 'string') return detail || fallback
+ if (Array.isArray(detail)) {
+ const message = detail.map((item) => {
+ if (item && typeof item === 'object' && 'msg' in item) {
+ return String(item.msg || JSON.stringify(item))
+ }
+ return JSON.stringify(item)
+ }).join('; ')
+ return message || fallback
+ }
+ return fallback
+}
+
+/** 未配置时使用当前主机的开发 API;显式空字符串保留同源代理语义。 */
+export function resolveApiBase(
+ configuredBase: unknown,
+ location?: { protocol: string; hostname: string },
+): string {
+ if (configuredBase !== undefined && configuredBase !== null) return String(configuredBase)
+ return location?.hostname
+ ? `${location.protocol}//${location.hostname}:8000`
+ : 'http://127.0.0.1:8000'
+}
+
+/** 不同业务沿用原有错误文案和计费提示,由调用方决定错误展示策略。 */
+export type ApiErrorHandler = (response: Response, detail: unknown) => never
+
+/** 创建可注入登录态的 HTTP 客户端,JSON 与文件上传共用同一请求路径。 */
+export function createHttpTransport(options: {
+ baseUrl: string
+ getToken: () => string | null
+ onError: ApiErrorHandler
+}) {
+ /** 保留 Headers 的全部合法输入形式,FormData 的 boundary 交给浏览器生成。 */
+ async function response(
+ path: string,
+ init?: RequestInit,
+ onError: ApiErrorHandler = options.onError,
+ ): Promise<Response> {
+ /* 每次请求重新读取 token,登录、登出后无需重建客户端。 */
+ const headers = new Headers()
+ const token = options.getToken()
+ if (token) headers.set('Authorization', `Bearer ${token}`)
+ if (!(init?.body instanceof FormData)) headers.set('Content-Type', 'application/json')
+ new Headers(init?.headers).forEach((value, key) => headers.set(key, value))
+ const result = await fetch(`${options.baseUrl}${path}`, { ...init, headers })
+ if (!result.ok) {
+ const error = await result.json().catch(() => ({ detail: result.statusText }))
+ onError(result, error?.detail)
+ }
+ return result
+ }
+
+ /** 解析成功的 JSON 响应;下载等非 JSON 请求直接使用 response。 */
+ async function json<T>(
+ path: string,
+ init?: RequestInit,
+ onError?: ApiErrorHandler,
+ ): Promise<T> {
+ return (await response(path, init, onError)).json() as Promise<T>
+ }
+
+ return { response, json }
+}
diff --git a/frontend/src/api/tasks.ts b/frontend/src/api/tasks.ts
index 3337c60..c429402 100644
--- a/frontend/src/api/tasks.ts
+++ b/frontend/src/api/tasks.ts
@@ -1,35 +1,10 @@
import { throwApiError } from '../lib/apiError'
+import { createJsonRequester } from './client'
-function defaultApiBase() {
- if (typeof window !== 'undefined' && window.location?.hostname) {
- const { protocol, hostname } = window.location
- return `${protocol}//${hostname}:8000`
- }
- return 'http://127.0.0.1:8000'
-}
-
-const _viteApiBase = import.meta.env.VITE_API_BASE
-const API_BASE =
- _viteApiBase === undefined || _viteApiBase === null ? defaultApiBase() : String(_viteApiBase)
-
-function authHeaders(): HeadersInit {
- const token = localStorage.getItem('token')
- return token
- ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }
- : { 'Content-Type': 'application/json' }
-}
-
-async function request<T>(path: string, init?: RequestInit): Promise<T> {
- const res = await fetch(`${API_BASE}${path}`, {
- ...init,
- headers: { ...authHeaders(), ...(init?.headers || {}) },
- })
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- throwApiError(res.status, err.detail, `HTTP ${res.status}`)
- }
- return res.json() as Promise<T>
-}
+/** 任务 API 沿用 HTTP 状态回退文案,共用统一传输层。 */
+const request = createJsonRequester((response, detail) =>
+ throwApiError(response.status, detail, `HTTP ${response.status}`),
+)
export type TaskEventOut = {
id: number
diff --git a/frontend/src/api/tools.ts b/frontend/src/api/tools.ts
index 5eac739..8fb4372 100644
--- a/frontend/src/api/tools.ts
+++ b/frontend/src/api/tools.ts
@@ -1,19 +1,23 @@
/** 独立创作工具 API:/api/tools/* */
import { throwApiError } from '../lib/apiError'
+import { API_BASE, createJsonRequester } from './client'
+import { apiErrorMessage } from './http'
-function defaultApiBase() {
- if (typeof window !== 'undefined' && window.location?.hostname) {
- const { protocol, hostname } = window.location
- return `${protocol}//${hostname}:8000`
- }
- return 'http://127.0.0.1:8000'
+/** 工具请求统一处理登录失效;仅生成入口沿用全局计费提示。 */
+function requestToolJson<T>(
+ path: string,
+ fallback: string,
+ init?: RequestInit,
+ notifyBilling = false,
+): Promise<T> {
+ return createJsonRequester((response, detail) => {
+ if (response.status === 401) throw new Error('未登录')
+ if (notifyBilling) throwApiError(response.status, detail, fallback)
+ throw new Error(apiErrorMessage(detail, fallback))
+ })<T>(path, init)
}
-const _viteApiBase = import.meta.env.VITE_API_BASE
-const API_BASE =
- _viteApiBase === undefined || _viteApiBase === null ? defaultApiBase() : String(_viteApiBase)
-
export type ToolRunResult = {
kind: string
urls: string[]
@@ -61,15 +65,6 @@ export function resolveToolMediaUrl(url?: string | null): string {
return url
}
-// 解析 FastAPI 错误详情
-function errorMessage(detail: unknown, fallback: string): string {
- if (typeof detail === 'string') return detail
- if (Array.isArray(detail)) {
- return detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
- }
- return fallback
-}
-
export type ToolRunPayload = {
toolId: string
prompt?: string
@@ -85,7 +80,6 @@ export type ToolRunPayload = {
// 提交工具生成(multipart)
export async function runStudioTool(payload: ToolRunPayload): Promise<ToolRunResult> {
- const token = localStorage.getItem('token')
const body = new FormData()
body.append('tool_id', payload.toolId)
body.append('prompt', payload.prompt || '')
@@ -99,58 +93,21 @@ export async function runStudioTool(payload: ToolRunPayload): Promise<ToolRunRes
for (const file of payload.files || []) {
body.append('files', file)
}
- const res = await fetch(`${API_BASE}/api/tools/run`, {
- method: 'POST',
- headers: token ? { Authorization: `Bearer ${token}` } : undefined,
- body,
- })
- if (res.status === 401) throw new Error('未登录')
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- throwApiError(res.status, err.detail, '生成失败')
- }
- return res.json()
+ return requestToolJson('/api/tools/run', '生成失败', { method: 'POST', body }, true)
}
// 查询视频任务状态
export async function pollStudioToolTask(taskId: string): Promise<ToolTaskResult> {
- const token = localStorage.getItem('token')
- const res = await fetch(`${API_BASE}/api/tools/tasks/${encodeURIComponent(taskId)}`, {
- headers: token ? { Authorization: `Bearer ${token}` } : undefined,
- })
- if (res.status === 401) throw new Error('未登录')
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- throw new Error(errorMessage(err.detail, '查询失败'))
- }
- return res.json()
+ return requestToolJson(`/api/tools/tasks/${encodeURIComponent(taskId)}`, '查询失败')
}
// 个人中心:分页拉取工具创作记录
export async function listToolRuns(page = 1, pageSize = 8): Promise<ToolRunList> {
- const token = localStorage.getItem('token')
const qs = new URLSearchParams({ page: String(page), page_size: String(pageSize) })
- const res = await fetch(`${API_BASE}/api/tools/runs?${qs}`, {
- headers: token ? { Authorization: `Bearer ${token}` } : undefined,
- })
- if (res.status === 401) throw new Error('未登录')
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- throw new Error(errorMessage(err.detail, '加载失败'))
- }
- return res.json()
+ return requestToolJson(`/api/tools/runs?${qs}`, '加载失败')
}
// 个人中心:单条创作详情(含 OSS 结果地址)
export async function getToolRun(runId: number): Promise<ToolRunRecord> {
- const token = localStorage.getItem('token')
- const res = await fetch(`${API_BASE}/api/tools/runs/${runId}`, {
- headers: token ? { Authorization: `Bearer ${token}` } : undefined,
- })
- if (res.status === 401) throw new Error('未登录')
- if (!res.ok) {
- const err = await res.json().catch(() => ({ detail: res.statusText }))
- throw new Error(errorMessage(err.detail, '加载失败'))
- }
- return res.json()
+ return requestToolJson(`/api/tools/runs/${runId}`, '加载失败')
}
diff --git a/frontend/src/assets/react.svg b/frontend/src/assets/react.svg
deleted file mode 100644
index 6c87de9..0000000
--- a/frontend/src/assets/react.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
\ No newline at end of file
diff --git a/frontend/src/assets/vite.svg b/frontend/src/assets/vite.svg
deleted file mode 100644
index 5101b67..0000000
--- a/frontend/src/assets/vite.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="g" width="74.749" height="58.852" x="29.961" y="-17.13" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="h" width="61.377" height="25.362" x="37.754" y="3.055" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="i" width="61.377" height="25.362" x="37.754" y="3.055" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="j" width="56.045" height="63.649" x="-13.43" y="-22.082" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="k" width="54.814" height="64.646" x="34.321" y="-37.644" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="l" width="33.541" height="35.313" x="38.847" y="-10.552" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="m" width="54.814" height="64.646" x="-15.081" y="6.78" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="n" width="54.814" height="64.646" x="-15.081" y="6.78" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="o" width="54.814" height="64.646" x="22.45" y="-1.645" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="p" width="39.409" height="43.623" x="32.919" y="11.36" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter></defs></svg>
diff --git a/frontend/src/components/billing/PaymentModal.tsx b/frontend/src/components/billing/PaymentModal.tsx
index a3c779a..32efd8d 100644
--- a/frontend/src/components/billing/PaymentModal.tsx
+++ b/frontend/src/components/billing/PaymentModal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useEffectEvent, useState } from 'react'
+import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import QRCode from 'qrcode'
import Modal from '../ui/Modal'
import PaymentBrandIcon from './PaymentBrandIcon'
@@ -26,10 +26,12 @@ type Props = {
onPaid: () => void
}
+/** 将分转换为支付弹窗显示的两位小数金额。 */
function yuan(fen: number) {
return (fen / 100).toFixed(2)
}
+/** 将剩余秒数格式化为分秒倒计时。 */
function formatRemain(sec: number) {
const m = Math.floor(sec / 60)
const s = sec % 60
@@ -50,9 +52,11 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
const [checking, setChecking] = useState(false)
const [error, setError] = useState('')
- const handlePaid = useEffectEvent(() => {
- onPaid()
- })
+ // 轮询和手动确认都读取最近一次提交的回调,父组件重渲染不会重启订单计时。
+ const onPaidRef = useRef(onPaid)
+ useLayoutEffect(() => {
+ onPaidRef.current = onPaid
+ }, [onPaid])
/** 取消支付:关闭弹窗,并尽量把待支付订单置为 closed */
async function handleCancel() {
@@ -96,6 +100,7 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
const payload = checkout.qr_payload || checkout.img || ''
let cancelled = false
+ /** 按网关返回值展示二维码图片、编码二维码或打开收银台。 */
async function paintQr() {
if (isRedirect) {
// 无原生二维码:直接新开易支付站点,弹窗仅等待到账
@@ -148,7 +153,7 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
setStatus('paid')
window.clearInterval(poll)
window.clearInterval(tick)
- handlePaid()
+ onPaidRef.current()
} else if (order.status === 'closed') {
setStatus('expired')
window.clearInterval(poll)
@@ -166,6 +171,7 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
}
}, [open, checkout])
+ /** 主动查询订单到账状态,与后台轮询共用最新支付成功回调。 */
async function confirmPaid() {
if (!checkout) return
setChecking(true)
@@ -174,7 +180,7 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
const order = await api.getBillingOrder(checkout.out_trade_no)
if (order.status === 'paid') {
setStatus('paid')
- handlePaid()
+ onPaidRef.current()
} else {
setError(
checkout.pay_mode === 'redirect'
diff --git a/frontend/src/lib/apiError.ts b/frontend/src/lib/apiError.ts
index 1b2e2d0..2c58778 100644
--- a/frontend/src/lib/apiError.ts
+++ b/frontend/src/lib/apiError.ts
@@ -1,14 +1,9 @@
import { notifyBillingErrorIfNeeded } from './billingError'
+import { apiErrorMessage } from '../api/http'
/** 解析 FastAPI detail 并抛出;402 / 余额不足时弹出充值引导 */
export function throwApiError(status: number, detail: unknown, fallback = '请求失败'): never {
- const message =
- typeof detail === 'string'
- ? detail
- : Array.isArray(detail)
- ? detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
- : fallback
- const finalMessage = message || fallback
+ const finalMessage = apiErrorMessage(detail, fallback)
notifyBillingErrorIfNeeded(status, finalMessage)
throw new Error(finalMessage)
}
diff --git a/frontend/src/pages/drama/OutlineEpisodePanel.tsx b/frontend/src/pages/drama/OutlineEpisodePanel.tsx
index 9a0ec68..4957511 100644
--- a/frontend/src/pages/drama/OutlineEpisodePanel.tsx
+++ b/frontend/src/pages/drama/OutlineEpisodePanel.tsx
@@ -1,4 +1,4 @@
-/** 剧情大纲:左栏分集目录 + 右栏本集创意/摘要/剧本(对齐截图样式) */
+/** 剧情大纲:左栏分集目录 + 右栏本集梗概/剧本与可选创作备注 */
import { useEffect, useMemo, useState, type ReactNode } from 'react'
import { useNavigate } from 'react-router-dom'
import {
@@ -83,7 +83,7 @@ type SectionCardProps = {
onCancel: () => void
onSave: () => void
onDraftChange: (v: string) => void
- onRegenerate: () => void
+ onRegenerate?: () => void
onCopy: () => void
/** 剧本区:解析预览 + 分段编辑 */
scriptPreview?: ReactNode
@@ -130,10 +130,12 @@ function SectionCard({
<Pencil size={14} strokeWidth={2} />
编辑
</button>
- <button type="button" className="drama-outline-text-btn" disabled={genBusy} onClick={onRegenerate}>
- <RefreshCw size={14} strokeWidth={2} />
- {regenerateLabel}
- </button>
+ {onRegenerate ? (
+ <button type="button" className="drama-outline-text-btn" disabled={genBusy} onClick={onRegenerate}>
+ <RefreshCw size={14} strokeWidth={2} />
+ {regenerateLabel}
+ </button>
+ ) : null}
<button type="button" className="drama-outline-text-btn" onClick={onCopy}>
<Copy size={14} strokeWidth={2} />
复制
@@ -186,7 +188,7 @@ function SectionCard({
</article>
)
}
-// 分集目录 + 本集三卡片
+// 分集目录 + 本集梗概、拍摄剧本、可选备注
export function OutlineEpisodePanel({
projectId,
script,
@@ -207,7 +209,7 @@ export function OutlineEpisodePanel({
const navigate = useNavigate()
const [activeEpisodeNumber, setActiveEpisodeNumber] = useState(1)
const [openSections, setOpenSections] = useState<Set<SectionKey>>(
- () => new Set(['creative', 'summary', 'body']),
+ () => new Set(['summary', 'body']),
)
const [editingSection, setEditingSection] = useState<SectionKey | null>(null)
const [sectionDraft, setSectionDraft] = useState('')
@@ -221,9 +223,10 @@ export function OutlineEpisodePanel({
const [localError, setLocalError] = useState('')
const [localNotice, setLocalNotice] = useState('')
const [scriptModalOpen, setScriptModalOpen] = useState(false)
+ const [sceneEditing, setSceneEditing] = useState(false)
const [episodeCovers, setEpisodeCovers] = useState<Record<number, string>>({})
const [episodeShotStats, setEpisodeShotStats] = useState<
- Record<number, { fragmentCount: number; totalSec: number; planStatus: string }>
+ Record<number, { fragmentCount: number; totalSec: number; planStatus: string; scriptChanged: boolean }>
>({})
const episodeBodies = parseEpisodeBodies(script)
@@ -246,8 +249,13 @@ export function OutlineEpisodePanel({
setLocalError('')
setLocalNotice('')
setScriptModalOpen(false)
+ setSceneEditing(false)
}, [selected?.episodeNumber])
+ useEffect(() => {
+ if (!editingSection) setTitleDraft(selected?.title || '')
+ }, [selected?.title, editingSection])
+
// 读取分集 AI 分镜状态(含自动入队)
function readPlanStatus(ep: DramaEpisode): string {
const active = (ep.active_tasks || []).find((task) => task.task_type === 'fragment_plan')
@@ -265,7 +273,7 @@ export function OutlineEpisodePanel({
// 从分集列表刷新封面 / 镜数 / 分镜状态
function applyEpisodeRows(rows: DramaEpisode[]) {
const map: Record<number, string> = {}
- const shotMap: Record<number, { fragmentCount: number; totalSec: number; planStatus: string }> =
+ const shotMap: Record<number, { fragmentCount: number; totalSec: number; planStatus: string; scriptChanged: boolean }> =
{}
for (const ep of rows) {
const epNo = Number(ep.params?.episodeNumber) || 0
@@ -286,6 +294,7 @@ export function OutlineEpisodePanel({
fragmentCount: frags.length,
totalSec,
planStatus,
+ scriptChanged: ep.params?.fragment_script_changed === true,
}
const first = frags.find((f) => (f.cover || '').trim() || (f.video || '').trim())
if (!first) continue
@@ -326,7 +335,7 @@ export function OutlineEpisodePanel({
cancelled = true
if (timer) window.clearTimeout(timer)
}
- }, [projectId, script?.id, episodeCount, episodeGenerating, generatingMode])
+ }, [projectId, script?.id, script?.episode_content, episodeCount, episodeGenerating, generatingMode])
const selectedGenerating =
Boolean(generatingMode) && generatingEpisodeNumber === (selected?.episodeNumber ?? null)
@@ -337,6 +346,8 @@ export function OutlineEpisodePanel({
editingSection === 'summary' ? sectionDraft : selected?.summary || ''
const canGenerateBody =
episodeBodyCharLen(effectiveCreative) >= 10 || episodeBodyCharLen(effectiveSummary) >= 40
+ const canRegenerateEpisode =
+ isSubstantialEpisodeCreative(effectiveCreative) || episodeBodyCharLen(effectiveSummary) >= 40
const canAdd =
summaryReady &&
!episodeGenerating &&
@@ -348,6 +359,9 @@ export function OutlineEpisodePanel({
// 整剧批量生成时:已写完正文的集可编辑 / 进分镜 / 重生成;未完成集仍锁生成
// 单集手动生成全局串行,故 anyEpisodeGenerating 时禁止再点生成
const selectedBodyReady = isSubstantialEpisodeBody(selected?.body)
+ const summaryGenerateMode = selectedBodyReady
+ ? 'brief'
+ : isSubstantialEpisodeCreative(selected?.creative) ? 'summary' : null
const batchLocksThisEpisode = episodeGenerating && !selectedBodyReady
const busy = selectedGenerating || confirming || saving || adding
const generateBusy =
@@ -396,8 +410,9 @@ export function OutlineEpisodePanel({
const p = await dramaApi.getProject(projectId)
onProjectChange(p)
setActiveEpisodeNumber(res.episode_number)
- setEditingSection('creative')
+ setEditingSection('summary')
setSectionDraft('')
+ setOpenSections((prev) => new Set(prev).add('summary'))
onOpenEpisodes()
} catch (err) {
const msg = err instanceof Error ? err.message : '加集失败'
@@ -433,26 +448,34 @@ export function OutlineEpisodePanel({
async function handleGenerate(mode: 'summary' | 'body' | 'full' | 'brief') {
if (!selected?.episodeNumber) return
- const creative = editingSection === 'creative' ? sectionDraft : selected.creative || ''
- const summary = editingSection === 'summary' ? sectionDraft : selected.summary || ''
- if ((mode === 'summary' || mode === 'full') && !isSubstantialEpisodeCreative(creative)) {
- setLocalError(`本集原始创意至少 ${MIN_EPISODE_CREATIVE_CHARS} 字`)
+ if (editingSection || sceneEditing) {
+ setLocalError('请先保存或取消正在编辑的内容,再生成。')
+ return
+ }
+ const creative = selected.creative || ''
+ const summary = selected.summary || ''
+ if (mode === 'summary' && !isSubstantialEpisodeCreative(creative)) {
+ setLocalError(`用于生成梗概的创作备注至少 ${MIN_EPISODE_CREATIVE_CHARS} 字`)
+ return
+ }
+ if (mode === 'full' && !isSubstantialEpisodeCreative(creative) && episodeBodyCharLen(summary) < 40) {
+ setLocalError(`请填写至少 40 字的本集梗概,或至少 ${MIN_EPISODE_CREATIVE_CHARS} 字的创作备注`)
return
}
// 与后端 run_episode_body_from_brief 一致:创意≥10 或摘要≥40
if (mode === 'body' && episodeBodyCharLen(creative) < 10 && episodeBodyCharLen(summary) < 40) {
- setLocalError('请先填写本集创意或摘要,再生成剧本正文')
+ setLocalError('请先填写本集梗概,再生成拍摄剧本')
return
}
if (mode === 'brief' && !isSubstantialEpisodeBody(selected.body)) {
- setLocalError(`剧本内容需满 ${MIN_EPISODE_BODY_CHARS} 字后再补齐创意与摘要`)
+ setLocalError(`拍摄剧本需满 ${MIN_EPISODE_BODY_CHARS} 字后再提取本集梗概`)
return
}
if (mode === 'full') {
const ok = await dialog.confirm({
title: '重新生成整集',
message:
- '将按本集创意重写摘要与剧本正文。若本集已进入分镜,之后重新分镜会覆盖并清空已生成镜头。是否继续?',
+ '将优先按本集梗概重写拍摄剧本;没有梗概时使用创作备注。若本集已进入分镜,之后重新分镜会覆盖并清空已生成镜头。是否继续?',
confirmText: '重新生成',
tone: 'danger',
})
@@ -464,31 +487,12 @@ export function OutlineEpisodePanel({
setLocalError('')
setLocalNotice('')
try {
- // 生成前落盘创意/摘要/标题草稿,避免 body 模式只读库内空字段
- if (
- editingSection === 'creative' ||
- editingSection === 'summary' ||
- titleDraft !== selected.title
- ) {
- const next = displayEpisodes.map((ep) =>
- ep.episodeNumber === targetEpisode
- ? {
- ...ep,
- creative: editingSection === 'creative' ? sectionDraft : ep.creative,
- summary: editingSection === 'summary' ? sectionDraft : ep.summary,
- title: titleDraft || ep.title,
- }
- : ep,
- )
- await saveBodies(next)
- setEditingSection(null)
- }
await dramaApi.episodeScript({
project_id: projectId,
episode_number: targetEpisode,
generate_mode: mode,
creative: creative || undefined,
- title: titleDraft || selected.title,
+ title: selected.title,
})
const cur = await pollOptimize(targetEpisode)
const created = Number((cur.params || {}).episode_optimize_assets_created || 0)
@@ -507,6 +511,10 @@ export function OutlineEpisodePanel({
async function handleConfirmEnter() {
if (!selected?.episodeNumber) return
+ if (editingSection || sceneEditing) {
+ setLocalError('请先保存或取消正在编辑的内容,再进入分镜。')
+ return
+ }
if (!isSubstantialEpisodeBody(selected.body)) {
setLocalError(`剧本内容需满 ${MIN_EPISODE_BODY_CHARS} 字后再进入分镜`)
return
@@ -606,6 +614,10 @@ export function OutlineEpisodePanel({
function startEdit(section: SectionKey) {
if (!selected) return
+ if (sceneEditing) {
+ setLocalError('请先保存或取消正在编辑的场次。')
+ return
+ }
setEditingSection(section)
setSectionDraft(
section === 'creative'
@@ -634,10 +646,10 @@ export function OutlineEpisodePanel({
}, [storyType, selected])
const bodyReady = selectedBodyReady
+ const selectedShot = episodeShotStats[selected?.episodeNumber || 0]
const charHint = selected
? [
- selected.creative ? `创意 ${episodeBodyCharLen(selected.creative)} 字` : null,
- selected.summary ? `摘要 ${episodeBodyCharLen(selected.summary)} 字` : null,
+ selected.summary ? `梗概 ${episodeBodyCharLen(selected.summary)} 字` : null,
selected.body ? `剧本 ${episodeBodyCharLen(selected.body)} 字` : null,
]
.filter(Boolean)
@@ -677,21 +689,23 @@ export function OutlineEpisodePanel({
? 'AI 分镜中…'
: shot?.planStatus === 'failed'
? '分镜失败'
- : shot?.planStatus === 'completed' &&
+ : shot?.scriptChanged && shot.fragmentCount > 0
+ ? `${shot.fragmentCount} 镜 · ${formatOutlineShotDuration(shot.totalSec)}(旧稿)`
+ : shot?.planStatus === 'completed' &&
shot.fragmentCount > 0 &&
shot.totalSec > 0
? shot.fragmentCount <= 1 && ready
? `1 镜 · ${formatOutlineShotDuration(shot.totalSec)}(偏少)`
: `${shot.fragmentCount} 镜 · ${formatOutlineShotDuration(shot.totalSec)}`
- : episodeGenerating && !ready && !body?.creative
+ : episodeGenerating && !ready && !body?.summary && !body?.creative
? episodeProgress.total > 0
? `整剧进度 ${episodeProgress.done}/${episodeProgress.total}`
: '等待生成剧本…'
: ready
? '待 AI 分镜'
- : body?.creative
+ : body?.summary || body?.creative
? '待生成剧本'
- : '待填写创意'
+ : '待填写梗概'
return (
<li key={ep.episodeNumber}>
<button
@@ -782,26 +796,30 @@ export function OutlineEpisodePanel({
</div>
</div>
<div className="drama-outline-detail-actions">
- <span className={`drama-outline-saved${bodyReady ? ' is-ready' : ''}`}>
+ <span className={`drama-outline-saved${bodyReady && !editingSection && !sceneEditing && !selectedShot?.scriptChanged ? ' is-ready' : ''}`}>
<Check size={14} strokeWidth={2.5} />
- {bodyReady ? '可进分镜' : saving ? '保存中' : '已同步'}
+ {editingSection || sceneEditing
+ ? '编辑未保存'
+ : selectedShot?.scriptChanged
+ ? '分镜待更新'
+ : bodyReady
+ ? '可进分镜'
+ : saving ? '保存中' : '已同步'}
</span>
- {bodyReady &&
- (!isSubstantialEpisodeCreative(selected.creative) ||
- episodeBodyCharLen(selected.summary) < 40) ? (
+ {bodyReady && episodeBodyCharLen(selected.summary) < 40 ? (
<button
type="button"
className="drama-btn-ghost"
disabled={generateBusy}
onClick={() => void handleGenerate('brief')}
>
- {selectedGenerating && generatingMode === 'brief' ? '补齐中…' : '补齐创意与摘要'}
+ {selectedGenerating && generatingMode === 'brief' ? '提取中…' : '提取本集梗概'}
</button>
) : null}
<button
type="button"
className="drama-outline-regen-btn"
- disabled={generateBusy || !isSubstantialEpisodeCreative(selected.creative)}
+ disabled={generateBusy || !canRegenerateEpisode}
onClick={() => void handleGenerate('full')}
title={
batchLocksThisEpisode
@@ -828,6 +846,9 @@ export function OutlineEpisodePanel({
{localError ? <p className="drama-error">{localError}</p> : null}
{localNotice ? <p className="drama-outline-notice">{localNotice}</p> : null}
+ {selectedShot?.scriptChanged ? (
+ <p className="drama-outline-notice">剧本已修改,当前分镜仍为旧稿;进入后请重新分镜。</p>
+ ) : null}
{summaryGenerating ? (
<p className="drama-loader">全剧摘要生成中…完成后抽取资产,再生成各集剧本</p>
) : null}
@@ -860,76 +881,39 @@ export function OutlineEpisodePanel({
) : null}
<div className="drama-outline-sections">
- <SectionCard
- sectionKey="creative"
- icon={<Lightbulb size={18} strokeWidth={1.9} />}
- title="原始创意"
- subtitle="本集故事起点与核心冲突"
- text={selected.creative || ''}
- editing={editingSection === 'creative'}
- draft={sectionDraft}
- open={openSections.has('creative')}
- busy={busy}
- generateBusy={generateBusy}
- placeholder={`填写本集创意(至少 ${MIN_EPISODE_CREATIVE_CHARS} 字)`}
- regenerateLabel={
- selectedGenerating && generatingMode === 'brief'
- ? '补齐中…'
- : selectedGenerating && generatingMode === 'summary'
- ? '生成中…'
- : isSubstantialEpisodeCreative(selected.creative)
- ? '生成摘要'
- : '补齐创意与摘要'
- }
- onToggle={() => toggleSection('creative')}
- onEdit={() => startEdit('creative')}
- onCancel={() => setEditingSection(null)}
- onSave={() => void handleSaveSection('creative')}
- onDraftChange={setSectionDraft}
- onRegenerate={() =>
- void handleGenerate(
- isSubstantialEpisodeCreative(selected.creative) ? 'summary' : 'brief',
- )
- }
- onCopy={() => void copyText(selected.creative || '')}
- />
<SectionCard
sectionKey="summary"
icon={<BookOpen size={18} strokeWidth={1.9} />}
- title="剧情摘要"
- subtitle="人物、冲突、转折与结尾钩子"
+ title="本集梗概"
+ subtitle="本集人物、冲突、转折与结局;生成拍摄剧本的主要依据"
text={selected.summary || ''}
editing={editingSection === 'summary'}
draft={sectionDraft}
open={openSections.has('summary')}
busy={busy}
generateBusy={generateBusy}
- placeholder="本集剧情摘要"
+ placeholder="填写本集梗概(至少 40 字),再生成拍摄剧本"
regenerateLabel={
selectedGenerating && generatingMode === 'brief'
- ? '补齐中…'
+ ? '提取中…'
: selectedGenerating && generatingMode === 'summary'
? '生成中…'
- : isSubstantialEpisodeCreative(selected.creative)
- ? '重新生成'
- : '补齐创意与摘要'
+ : summaryGenerateMode === 'brief'
+ ? '从剧本提取'
+ : '从备注生成'
}
onToggle={() => toggleSection('summary')}
onEdit={() => startEdit('summary')}
onCancel={() => setEditingSection(null)}
onSave={() => void handleSaveSection('summary')}
onDraftChange={setSectionDraft}
- onRegenerate={() =>
- void handleGenerate(
- isSubstantialEpisodeCreative(selected.creative) ? 'summary' : 'brief',
- )
- }
+ onRegenerate={summaryGenerateMode ? () => void handleGenerate(summaryGenerateMode) : undefined}
onCopy={() => void copyText(selected.summary || '')}
/>
<SectionCard
sectionKey="body"
icon={<FileText size={18} strokeWidth={1.9} />}
- title="剧本内容"
+ title="拍摄剧本"
subtitle="含对白与画面描述的拍摄正文(按场次解析,可分段编辑)"
text={selected.body || ''}
editing={editingSection === 'body'}
@@ -948,14 +932,35 @@ export function OutlineEpisodePanel({
onCopy={() => void copyText(selected.body || '')}
scriptPreview={
<OutlineScriptPreview
+ key={selected.episodeNumber}
text={selected.body || ''}
empty={`拍摄剧本正文(进入分镜需满 ${MIN_EPISODE_BODY_CHARS} 字)`}
busy={busy}
shotStats={episodeShotStats[selected.episodeNumber || 0] || null}
onSaveScenes={handleSaveScenes}
+ onEditingChange={setSceneEditing}
/>
}
/>
+ <SectionCard
+ sectionKey="creative"
+ icon={<Lightbulb size={18} strokeWidth={1.9} />}
+ title="创作备注(可选)"
+ subtitle="补充创作方向或保留早期创意;已有梗概时无需填写"
+ text={selected.creative || ''}
+ editing={editingSection === 'creative'}
+ draft={sectionDraft}
+ open={openSections.has('creative')}
+ busy={busy}
+ placeholder="可选:补充人物动机、创作方向或特别要求"
+ regenerateLabel="生成梗概"
+ onToggle={() => toggleSection('creative')}
+ onEdit={() => startEdit('creative')}
+ onCancel={() => setEditingSection(null)}
+ onSave={() => void handleSaveSection('creative')}
+ onDraftChange={setSectionDraft}
+ onCopy={() => void copyText(selected.creative || '')}
+ />
</div>
<OutlineScriptParseModal
open={scriptModalOpen}
diff --git a/frontend/src/pages/drama/outlineScriptPreview.tsx b/frontend/src/pages/drama/outlineScriptPreview.tsx
index c21e9d0..ebf526b 100644
--- a/frontend/src/pages/drama/outlineScriptPreview.tsx
+++ b/frontend/src/pages/drama/outlineScriptPreview.tsx
@@ -1,5 +1,5 @@
/** 大纲页:剧本按场次解析展示 / 分段编辑 / 弹窗预览 */
-import { useMemo, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { Pencil } from 'lucide-react'
import Modal from '../../components/ui/Modal'
@@ -34,6 +34,7 @@ export type OutlineSceneStats = {
export type OutlineShotDurationStats = {
fragmentCount: number
totalSec: number
+ scriptChanged?: boolean
}
const SPEAKER_COLORS = ['#059669', '#dc2626', '#ea580c', '#2563eb', '#7c3aed', '#db2777']
@@ -285,6 +286,7 @@ type OutlineScriptPreviewProps = {
shotStats?: OutlineShotDurationStats | null
/** 分段保存:返回更新后的完整 body */
onSaveScenes?: (nextBody: string) => Promise<void> | void
+ onEditingChange?: (editing: boolean) => void
}
// 场次卡片列表 + 分段编辑
@@ -294,6 +296,7 @@ export function OutlineScriptPreview({
busy,
shotStats,
onSaveScenes,
+ onEditingChange,
}: OutlineScriptPreviewProps) {
const blocks = useMemo(() => parseOutlineSceneBlocks(text), [text])
const blockStats = useMemo(
@@ -304,12 +307,19 @@ export function OutlineScriptPreview({
() => blockStats.reduce((sum, s) => sum + (s.estimatedSec || 0), 0),
[blockStats],
)
- const hasShotDuration = Boolean(shotStats && shotStats.fragmentCount > 0 && shotStats.totalSec > 0)
+ const hasShotDuration = Boolean(
+ shotStats && !shotStats.scriptChanged && shotStats.fragmentCount > 0 && shotStats.totalSec > 0,
+ )
const displayTotalSec = hasShotDuration ? shotStats!.totalSec : estimateTotalSec
const [editingIndex, setEditingIndex] = useState<number | null>(null)
const [draft, setDraft] = useState('')
const [saving, setSaving] = useState(false)
+ useEffect(() => {
+ onEditingChange?.(editingIndex != null)
+ return () => onEditingChange?.(false)
+ }, [editingIndex, onEditingChange])
+
function startEdit(index: number) {
setEditingIndex(index)
setDraft(blocks[index]?.raw || '')
@@ -347,7 +357,9 @@ export function OutlineScriptPreview({
<span className="drama-outline-script-summary-hint">
{hasShotDuration
? '时长取自已切分镜头'
- : '时长为解析估算,进分镜后以镜头为准'}
+ : shotStats?.scriptChanged
+ ? '时长为当前剧本估算;已有分镜仍为旧稿'
+ : '时长为解析估算,进分镜后以镜头为准'}
</span>
</div>
) : null
diff --git a/frontend/tests/http.test.mjs b/frontend/tests/http.test.mjs
new file mode 100644
index 0000000..0e585cd
--- /dev/null
+++ b/frontend/tests/http.test.mjs
@@ -0,0 +1,103 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { apiErrorMessage, createHttpTransport, resolveApiBase } from '../src/api/http.ts'
+
+/** 创建带可观察 token 的客户端;错误策略不依赖浏览器弹窗。 */
+function testTransport(getToken = () => 'first-token') {
+ return createHttpTransport({
+ baseUrl: 'http://api.test',
+ getToken,
+ onError: (response, detail) => {
+ throw new Error(apiErrorMessage(detail, response.statusText || '请求失败'))
+ },
+ })
+}
+
+test('API 地址保留显式同源、配置值和 LAN 开发默认值', () => {
+ const location = { protocol: 'https:', hostname: 'studio.test' }
+ assert.equal(resolveApiBase('', location), '')
+ assert.equal(resolveApiBase('https://backend.test', location), 'https://backend.test')
+ assert.equal(resolveApiBase(undefined, location), 'https://studio.test:8000')
+ assert.equal(resolveApiBase(null), 'http://127.0.0.1:8000')
+})
+
+test('JSON 请求保留方法和正文,并在登录变化后重新读取 token', async (t) => {
+ const calls = []
+ let token = 'first-token'
+ t.mock.method(globalThis, 'fetch', async (url, init) => {
+ calls.push({ url, init })
+ return Response.json({ ok: true })
+ })
+ const client = testTransport(() => token)
+ assert.deepEqual(await client.json('/api/projects', { method: 'POST', body: '{"title":"测试"}' }), { ok: true })
+ token = null
+ await client.json('/api/auth/me')
+ assert.equal(calls[0].url, 'http://api.test/api/projects')
+ assert.equal(calls[0].init.method, 'POST')
+ assert.equal(calls[0].init.body, '{"title":"测试"}')
+ assert.equal(calls[0].init.headers.get('Authorization'), 'Bearer first-token')
+ assert.equal(calls[0].init.headers.get('Content-Type'), 'application/json')
+ assert.equal(calls[1].init.headers.has('Authorization'), false)
+})
+
+test('调用方的 Headers 和键值数组均可覆盖默认请求头', async (t) => {
+ const calls = []
+ t.mock.method(globalThis, 'fetch', async (_url, init) => {
+ calls.push(init.headers)
+ return Response.json({})
+ })
+ const client = testTransport()
+ await client.json('/headers', { headers: new Headers({ authorization: 'Custom token', 'X-Trace': 'trace' }) })
+ await client.json('/tuples', { headers: [['Content-Type', 'application/custom']] })
+ assert.equal(calls[0].get('Authorization'), 'Custom token')
+ assert.equal(calls[0].get('X-Trace'), 'trace')
+ assert.equal(calls[1].get('Content-Type'), 'application/custom')
+})
+
+test('上传保留 FormData 并由平台生成 multipart boundary', async (t) => {
+ const body = new FormData()
+ body.append('file', new Blob(['test']), 'asset.txt')
+ t.mock.method(globalThis, 'fetch', async (url, init) => {
+ assert.equal(init.body, body)
+ assert.equal(init.headers.has('Content-Type'), false)
+ const actualRequest = new Request(url, init)
+ assert.match(actualRequest.headers.get('Content-Type'), /^multipart\/form-data; boundary=/)
+ assert.equal(actualRequest.headers.get('Authorization'), 'Bearer first-token')
+ return Response.json({ uploaded: true })
+ })
+ assert.deepEqual(await testTransport().json('/upload', { method: 'POST', body }), { uploaded: true })
+})
+
+test('非 JSON 下载返回可读取的原始响应', async (t) => {
+ t.mock.method(globalThis, 'fetch', async () => new Response('zip-bytes', {
+ headers: { 'Content-Disposition': 'attachment; filename="project.zip"' },
+ }))
+ const response = await testTransport().response('/download')
+ assert.equal(response.headers.get('Content-Disposition'), 'attachment; filename="project.zip"')
+ assert.equal(await response.text(), 'zip-bytes')
+})
+
+test('FastAPI 校验数组及空错误详情生成可读回退文案', () => {
+ assert.equal(apiErrorMessage([{ msg: '字段缺失' }, { msg: '格式错误' }], '请求失败'), '字段缺失; 格式错误')
+ assert.equal(apiErrorMessage([null, { type: 'unknown' }], '请求失败'), 'null; {"type":"unknown"}')
+ for (const detail of ['', [], null, undefined, {}]) {
+ assert.equal(apiErrorMessage(detail, '请求失败'), '请求失败')
+ }
+})
+
+test('请求失败交给业务错误策略,并保留状态和 detail', async (t) => {
+ t.mock.method(globalThis, 'fetch', async () => Response.json({ detail: '余额不足' }, { status: 402 }))
+ await assert.rejects(testTransport().json('/generate', undefined, (response, detail) => {
+ assert.equal(response.status, 402)
+ assert.equal(detail, '余额不足')
+ throw new Error('业务计费处理')
+ }), /业务计费处理/)
+})
+
+test('网关返回非 JSON、null 或空 detail 时错误处理仍可运行', async (t) => {
+ for (const body of ['upstream failed', 'null', '{}']) {
+ t.mock.method(globalThis, 'fetch', async () => new Response(body, { status: 502, statusText: 'Bad Gateway' }))
+ await assert.rejects(testTransport().json('/failed'), /Bad Gateway/)
+ t.mock.restoreAll()
+ }
+})