Compare commits
59 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9e87781a85 | |||
| 57545ab694 | |||
| 51694cbd0c | |||
| fca943428b | |||
| 3eb2fcf3ec | |||
| 50b413a6fa | |||
| 410487fef5 | |||
| fc99b5a080 | |||
| 300f4b2abd | |||
| bb47e89a47 | |||
| 6155b4d21e | |||
| 41cd9cdc56 | |||
| 799a7f7367 | |||
| 13c302c037 | |||
| 1e8ab91984 | |||
| 3f27d199f5 | |||
| 67b270bce2 | |||
| 0432629aef | |||
| 3ad48335f6 | |||
| 1bf0e73fd2 | |||
| 7d2fbfa49f | |||
| 7564b50f7e | |||
| 7bf135789e | |||
| f8c8d4320e | |||
| b73cd1f22d | |||
| 0918d347cf | |||
| ba7e056232 | |||
| c455e33110 | |||
| d706a76205 | |||
| 8b69a6e18b | |||
| 3c41115b31 | |||
| 7715b789a8 | |||
| 29cdd32203 | |||
| 00045131f6 | |||
| de56a67457 | |||
| 371be8034d | |||
| d0af26116c | |||
| ab90a5ec9f | |||
| d0125a1da2 | |||
| f30fe14ff8 | |||
| 509b8db3a3 | |||
| dc0a5834f1 | |||
| 59fbbd8e26 | |||
| 81180d16e5 | |||
| b64d384b91 | |||
| 6a4913a3b9 | |||
| bc85c79f39 | |||
| 19eeb1b475 | |||
| 0e5127df05 | |||
| 08cad1f1ee | |||
| 0c59f83a7f | |||
| 53fb25efcf | |||
| 29a127c7f1 | |||
| 352221f199 | |||
| a25aa7baed | |||
| 493d175e87 | |||
| c2997a11c2 | |||
| 90cc0026b1 | |||
| 2b12c055dc |
+1
-1
@@ -1,2 +1,2 @@
|
||||
CI trigger file - safe to delete
|
||||
updated!
|
||||
retrigger at 2026-09-15 20:31:24 UTC
|
||||
|
||||
@@ -196,3 +196,10 @@ DOUBAO_MODEL=doubao-seed-1-6-250615
|
||||
DOUBAO_BASE_URL=https://ark.cn-beijing.volces.com/api/v3
|
||||
DOUBAO_TIMEOUT=30
|
||||
DOUBAO_MAX_RETRIES=2
|
||||
|
||||
# ==================== 积分/会员系统 (#1895) ====================
|
||||
# 积分扣点总开关:默认 false(对现有用户零影响)。
|
||||
# P2 阶段各业务路由逐个接入 @points_gate 时,用
|
||||
# `if settings.points_enabled: ...`
|
||||
# 包裹扣点逻辑;所有路由接入完成并验证通过后再在 staging/prod 打开。
|
||||
POINTS_ENABLED=false
|
||||
|
||||
+465
-464
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,133 @@
|
||||
"""add membership & points system
|
||||
|
||||
Revision ID: 076_membership_points
|
||||
Revises: 075_add_sentence_timings
|
||||
Create Date: 2026-09-15
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "076_membership_points"
|
||||
down_revision = "075_add_sentence_timings"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# 1. users 表新增字段
|
||||
with op.batch_alter_table("users") as batch:
|
||||
batch.add_column(
|
||||
sa.Column("is_member", sa.Boolean(), nullable=False, server_default=sa.text("false")),
|
||||
)
|
||||
batch.add_column(
|
||||
sa.Column("member_type", sa.String(20), nullable=True),
|
||||
)
|
||||
batch.add_column(
|
||||
sa.Column("member_expires_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
batch.add_column(
|
||||
sa.Column("points_balance", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||
)
|
||||
|
||||
# 2. points_accounts 积分账户表
|
||||
op.create_table(
|
||||
"points_accounts",
|
||||
sa.Column("id", sa.String(36), primary_key=True),
|
||||
sa.Column("user_id", sa.String(36), nullable=False, unique=True, index=True),
|
||||
sa.Column("balance", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||
sa.Column("total_earned", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||
sa.Column("total_spent", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(),
|
||||
nullable=False,
|
||||
server_default=sa.text("NOW()"),
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.DateTime(),
|
||||
nullable=False,
|
||||
server_default=sa.text("NOW()"),
|
||||
),
|
||||
)
|
||||
|
||||
# 3. points_transactions 积分流水表
|
||||
op.create_table(
|
||||
"points_transactions",
|
||||
sa.Column("id", sa.String(36), primary_key=True),
|
||||
sa.Column("user_id", sa.String(36), nullable=False, index=True),
|
||||
sa.Column("account_id", sa.String(36), nullable=False, index=True),
|
||||
sa.Column("type", sa.String(20), nullable=False, index=True),
|
||||
sa.Column("source", sa.String(50), nullable=False, index=True),
|
||||
sa.Column("amount", sa.Integer(), nullable=False),
|
||||
sa.Column("balance_after", sa.Integer(), nullable=False),
|
||||
sa.Column("description", sa.String(255), nullable=False, server_default=""),
|
||||
sa.Column("ref_id", sa.String(100), nullable=False, server_default=""),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(),
|
||||
nullable=False,
|
||||
server_default=sa.text("NOW()"),
|
||||
),
|
||||
)
|
||||
|
||||
# 4. points_orders 积分/会员订单表
|
||||
op.create_table(
|
||||
"points_orders",
|
||||
sa.Column("id", sa.String(36), primary_key=True),
|
||||
sa.Column("user_id", sa.String(36), nullable=False, index=True),
|
||||
sa.Column("order_type", sa.String(20), nullable=False),
|
||||
sa.Column("product_code", sa.String(50), nullable=False),
|
||||
sa.Column("amount_cents", sa.Integer(), nullable=False),
|
||||
sa.Column("original_amount_cents", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||
sa.Column("discount", sa.Float(), nullable=False, server_default=sa.text("1.0")),
|
||||
sa.Column("points_amount", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||
sa.Column("status", sa.String(20), nullable=False, server_default="pending", index=True),
|
||||
sa.Column("payment_method", sa.String(50), nullable=True),
|
||||
sa.Column("payment_id", sa.String(100), nullable=True),
|
||||
sa.Column("paid_at", sa.DateTime(), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(),
|
||||
nullable=False,
|
||||
server_default=sa.text("NOW()"),
|
||||
),
|
||||
)
|
||||
|
||||
# 5. daily_usage_records 每日使用记录表
|
||||
op.create_table(
|
||||
"daily_usage_records",
|
||||
sa.Column("id", sa.String(36), primary_key=True),
|
||||
sa.Column("user_id", sa.String(36), nullable=False, index=True),
|
||||
sa.Column("usage_date", sa.DateTime(), nullable=False),
|
||||
sa.Column("usage_type", sa.String(50), nullable=False, server_default="free_clip"),
|
||||
sa.Column("count", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.DateTime(),
|
||||
nullable=False,
|
||||
server_default=sa.text("NOW()"),
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
"user_id",
|
||||
"usage_date",
|
||||
"usage_type",
|
||||
name="uq_daily_usage_user_date_type",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("daily_usage_records")
|
||||
op.drop_table("points_orders")
|
||||
op.drop_table("points_transactions")
|
||||
op.drop_table("points_accounts")
|
||||
|
||||
with op.batch_alter_table("users") as batch:
|
||||
batch.drop_column("points_balance")
|
||||
batch.drop_column("member_expires_at")
|
||||
batch.drop_column("member_type")
|
||||
batch.drop_column("is_member")
|
||||
@@ -0,0 +1,67 @@
|
||||
"""#1894: merge title_libraries into scripts — add title_text/title_category/title_config
|
||||
|
||||
Revision ID: 077_merge_title_libs
|
||||
Revises: 076_membership_points
|
||||
Create Date: 2026-09-15
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import context, op
|
||||
|
||||
revision = "077_merge_title_libs"
|
||||
down_revision = "076_membership_points"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("scripts") as batch:
|
||||
batch.add_column(
|
||||
sa.Column("title_text", sa.String(500), nullable=False, server_default=""),
|
||||
)
|
||||
batch.add_column(
|
||||
sa.Column("title_category", sa.String(50), nullable=False, server_default=""),
|
||||
)
|
||||
batch.add_column(
|
||||
sa.Column("title_config", sa.JSON, nullable=False, server_default="{}"),
|
||||
)
|
||||
|
||||
if context.get_context().dialect.name == "postgresql":
|
||||
conn = op.get_bind()
|
||||
result = conn.execute(sa.text("SELECT to_regclass('public.title_libraries')"))
|
||||
if result.scalar() is not None:
|
||||
conn.execute(sa.text("""
|
||||
INSERT INTO scripts
|
||||
(id, user_id, title, content, segments, tags,
|
||||
title_text, title_category, title_config,
|
||||
created_at, updated_at)
|
||||
SELECT
|
||||
gen_random_uuid()::TEXT,
|
||||
tl.user_id,
|
||||
COALESCE(tl.name, '迁移标题'),
|
||||
COALESCE(tl.text, ''),
|
||||
'[]'::JSONB,
|
||||
COALESCE(tl.tags, '[]'::JSONB),
|
||||
COALESCE(tl.text, ''),
|
||||
COALESCE(tl.category, ''),
|
||||
COALESCE(tl."metadata", '{}'::JSONB),
|
||||
tl.created_at,
|
||||
tl.updated_at
|
||||
FROM title_libraries tl
|
||||
WHERE tl.is_active = true
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM scripts s
|
||||
WHERE s.user_id = tl.user_id
|
||||
AND s.title_text = COALESCE(tl.text, '')
|
||||
AND s.title_category = COALESCE(tl.category, '')
|
||||
AND s.created_at = tl.created_at
|
||||
)
|
||||
"""))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("scripts") as batch:
|
||||
batch.drop_column("title_config")
|
||||
batch.drop_column("title_category")
|
||||
batch.drop_column("title_text")
|
||||
@@ -6,6 +6,7 @@ from app.api.routes.assets import router as assets_router
|
||||
from app.api.routes.auth import router as auth_router
|
||||
from app.api.routes.chunked_upload import router as chunked_upload_router
|
||||
from app.api.routes.classification_jobs import router as classification_jobs_router
|
||||
from app.api.routes.clips_standalone import router as clips_standalone_router
|
||||
from app.api.routes.cover_templates import router as cover_templates_router
|
||||
from app.api.routes.duplication import router as duplication_router
|
||||
from app.api.routes.feature_flags import router as feature_flags_router
|
||||
@@ -17,8 +18,10 @@ from app.api.routes.health import router as health_check_router
|
||||
from app.api.routes.ingest_jobs import router as ingest_jobs_router
|
||||
from app.api.routes.internal_render import router as internal_render_router
|
||||
from app.api.routes.lipsync import router as lipsync_router
|
||||
from app.api.routes.points import points_router, usage_router
|
||||
from app.api.routes.projects import router as projects_router
|
||||
from app.api.routes.scripts import router as scripts_router
|
||||
from app.api.routes.scripts_ai import router as scripts_ai_router
|
||||
from app.api.routes.share import router as share_router
|
||||
from app.api.routes.subscription import router as subscription_router
|
||||
from app.api.routes.tags import router as tags_router
|
||||
@@ -156,6 +159,10 @@ api_router.include_router(
|
||||
prefix="/templates",
|
||||
tags=["Template"],
|
||||
)
|
||||
api_router.include_router(
|
||||
clips_standalone_router,
|
||||
tags=["Clips"],
|
||||
)
|
||||
api_router.include_router(
|
||||
templates_editor_router,
|
||||
prefix="/templates/{template_id}/editor",
|
||||
@@ -184,8 +191,23 @@ api_router.include_router(
|
||||
prefix="/scripts",
|
||||
tags=["ScriptLibrary"],
|
||||
)
|
||||
api_router.include_router(
|
||||
scripts_ai_router,
|
||||
prefix="/scripts",
|
||||
tags=["ScriptLibrary AI"],
|
||||
)
|
||||
api_router.include_router(
|
||||
ai_avatar_render_router,
|
||||
prefix="/ai-avatar/render",
|
||||
tags=["AI Avatar Render"],
|
||||
)
|
||||
api_router.include_router(
|
||||
points_router,
|
||||
prefix="/points",
|
||||
tags=["Points"],
|
||||
)
|
||||
api_router.include_router(
|
||||
usage_router,
|
||||
prefix="/usage",
|
||||
tags=["Usage"],
|
||||
)
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""默认模板兜底共享逻辑(P0 #1922).
|
||||
|
||||
提供 get_or_create_default_template_id(db, user_id) 共享函数,
|
||||
供 templates.py 列表查询、clips_standalone.py 独立端点、dependencies.py
|
||||
resolve_draft_plan_id 三处复用,避免三处各写一套兜底逻辑产生分叉。
|
||||
|
||||
根因:PR#1918 清理模板管理 API 时误删了 GET /templates 自动创建默认模板
|
||||
兜底,前端 PR#1913 去掉空 tid 拦截后首次进入生成页拼出
|
||||
/templates//editor/clips/from-assets(双斜杠)→ FastAPI 404,阻断新用户首次
|
||||
生成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_or_create_default_template_id(db: Session, user_id: str) -> Optional[str]:
|
||||
"""获取或自动创建默认配音模板的 id。
|
||||
|
||||
判定逻辑(不做异常降级,只有确实创建失败时才回滚重查):
|
||||
1. 查用户名下 is_active=True 且有 TemplateClipConfig 的模板 → 返回其 id;
|
||||
2. 无则调用 CreateTemplateUseCase 创建一条默认 voice_over 模板;
|
||||
3. 创建异常时 rollback 再重查一次(防并发唯一键冲突),重查仍无返回 None。
|
||||
"""
|
||||
from packages.adapters.sqlalchemy_impl.models import (
|
||||
TemplateClipConfigModel,
|
||||
TemplateModel,
|
||||
)
|
||||
from packages.adapters.sqlalchemy_impl.template_repository import (
|
||||
SQLAlchemyTemplateRepository,
|
||||
)
|
||||
from packages.application.template.commands import (
|
||||
CreateTemplateCommand,
|
||||
SegmentCommand,
|
||||
)
|
||||
from packages.application.template.use_cases import CreateTemplateUseCase
|
||||
|
||||
existing = (
|
||||
db.query(TemplateModel)
|
||||
.filter(TemplateModel.user_id == user_id, TemplateModel.is_active.is_(True))
|
||||
.order_by(TemplateModel.created_at.asc())
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
has_seg = (
|
||||
db.query(TemplateClipConfigModel.id).filter(TemplateClipConfigModel.template_id == existing.id).first()
|
||||
)
|
||||
if has_seg:
|
||||
return existing.id
|
||||
|
||||
try:
|
||||
repo = SQLAlchemyTemplateRepository(db)
|
||||
cmd = CreateTemplateCommand(
|
||||
user_id=user_id,
|
||||
name="默认配音模板",
|
||||
mode="voice_over",
|
||||
category="default",
|
||||
tags=[],
|
||||
title_config={},
|
||||
subtitle_config={},
|
||||
bgm_config={},
|
||||
estimated_duration=0.0,
|
||||
segments=[SegmentCommand(segment_order=0, duration_min=1.0, duration_max=30.0)],
|
||||
)
|
||||
tpl = CreateTemplateUseCase(repo).execute(cmd)
|
||||
db.commit()
|
||||
logger.info("auto-created default voice_over template: id=%s user=%s", tpl.id, user_id)
|
||||
return tpl.id
|
||||
except Exception:
|
||||
db.rollback()
|
||||
# 重查:可能并发请求已建好
|
||||
existing = (
|
||||
db.query(TemplateModel)
|
||||
.filter(TemplateModel.user_id == user_id, TemplateModel.is_active.is_(True))
|
||||
.order_by(TemplateModel.created_at.asc())
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
has_seg = (
|
||||
db.query(TemplateClipConfigModel.id).filter(TemplateClipConfigModel.template_id == existing.id).first()
|
||||
)
|
||||
if has_seg:
|
||||
return existing.id
|
||||
logger.exception("failed to auto-create default template user=%s", user_id)
|
||||
return None
|
||||
@@ -1,6 +1,6 @@
|
||||
"""路由层共享辅助函数 — 消除跨文件重复定义。"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
@@ -138,4 +138,4 @@ def format_utc_datetime(dt: datetime | None) -> str:
|
||||
return dt
|
||||
if dt.tzinfo is None:
|
||||
return dt.isoformat() + "Z"
|
||||
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
return dt.astimezone(UTC).isoformat().replace("+00:00", "Z")
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List, Literal
|
||||
from typing import Literal
|
||||
|
||||
from app.services.ai_service import TITLE_STYLES, generate_smart_titles, semantic_match_assets
|
||||
from fastapi import APIRouter
|
||||
@@ -31,7 +31,7 @@ class GenerateTitlesRequest(BaseModel):
|
||||
class GenerateTitlesResponse(BaseModel):
|
||||
"""智能标题生成响应."""
|
||||
|
||||
titles: List[str] = Field(..., description="生成的标题列表")
|
||||
titles: list[str] = Field(..., description="生成的标题列表")
|
||||
style: str = Field(..., description="实际使用的风格")
|
||||
source: str = Field(..., description="来源:doubao 或 fallback")
|
||||
description: str = Field(..., description="原始描述")
|
||||
@@ -53,7 +53,7 @@ class AssetMatchItem(BaseModel):
|
||||
|
||||
id: str = Field(..., description="素材ID")
|
||||
name: str = Field(default="", description="素材名称")
|
||||
tags: List[str] = Field(default_factory=list, description="标签列表")
|
||||
tags: list[str] = Field(default_factory=list, description="标签列表")
|
||||
description: str = Field(default="", description="素材描述")
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ class SemanticMatchRequest(BaseModel):
|
||||
"""语义匹配请求."""
|
||||
|
||||
description: str = Field(..., min_length=1, max_length=500, description="目标视频内容描述")
|
||||
assets: List[AssetMatchItem] = Field(..., min_length=1, max_length=100, description="待匹配素材列表")
|
||||
assets: list[AssetMatchItem] = Field(..., min_length=1, max_length=100, description="待匹配素材列表")
|
||||
top_k: int = Field(default=0, ge=0, le=100, description="返回前K个,0返回全部")
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ class SemanticMatchResultItem(AssetMatchItem):
|
||||
class SemanticMatchResponse(BaseModel):
|
||||
"""语义匹配响应."""
|
||||
|
||||
matches: List[SemanticMatchResultItem] = Field(..., description="按匹配度降序排列的素材列表")
|
||||
matches: list[SemanticMatchResultItem] = Field(..., description="按匹配度降序排列的素材列表")
|
||||
source: str = Field(..., description="来源:doubao / fallback")
|
||||
description: str = Field(..., description="原始描述")
|
||||
total: int = Field(..., description="输入素材总数")
|
||||
@@ -99,7 +99,7 @@ def generate_titles(request: GenerateTitlesRequest):
|
||||
return GenerateTitlesResponse(**result)
|
||||
|
||||
|
||||
@router.get("/titles/styles", response_model=List[TitleStyleInfo])
|
||||
@router.get("/titles/styles", response_model=list[TitleStyleInfo])
|
||||
def list_title_styles():
|
||||
"""获取支持的标题风格列表."""
|
||||
return [
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import get_db_session
|
||||
@@ -29,6 +29,8 @@ from app.services.ai_avatar_render_service import (
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.middleware.points_gate import points_gate
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
@@ -42,10 +44,12 @@ def _get_service(db: Session = Depends(get_db_session)) -> AiAvatarRenderService
|
||||
|
||||
|
||||
@router.post("", response_model=AiAvatarRenderJobResponse, status_code=201)
|
||||
@points_gate("ai_digital_human", per_unit=15)
|
||||
def create_render_job(
|
||||
body: CreateAiAvatarRenderRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
svc: AiAvatarRenderService = Depends(_get_service),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""提交 AI 数字人渲染任务.
|
||||
|
||||
@@ -82,7 +86,7 @@ def create_render_job(
|
||||
logger.exception("Celery 任务投递失败(创建): job_id=%s err=%s", job.id, exc)
|
||||
job.status = "failed"
|
||||
job.error_message = f"任务提交失败:{exc}"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
svc.db.commit()
|
||||
svc.db.refresh(job)
|
||||
return AiAvatarRenderJobResponse.model_validate(job)
|
||||
@@ -183,7 +187,7 @@ def retry_render_job(
|
||||
logger.exception("Celery 任务投递失败(重试): job_id=%s err=%s", job.id, exc)
|
||||
job.status = "failed"
|
||||
job.error_message = f"任务提交失败:{exc}"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
svc.db.commit()
|
||||
svc.db.refresh(job)
|
||||
return AiAvatarRenderJobResponse.model_validate(job)
|
||||
@@ -246,7 +250,7 @@ def generate_render_smart_cover(
|
||||
"url": cover_url,
|
||||
}
|
||||
job.output_cover_url = cover_url
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
except Exception as exc:
|
||||
logger.warning("更新 render_job 封面字段失败(不影响返回): job_id=%s err=%s", job_id, exc)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Any, List, Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.api.routes._helpers import check_project_access, format_utc_datetime
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
@@ -390,7 +390,7 @@ def update_asset_review_status(
|
||||
return _to_asset_response(updated)
|
||||
|
||||
|
||||
@router.post("/batch", response_model=List[AssetResponse])
|
||||
@router.post("/batch", response_model=list[AssetResponse])
|
||||
def batch_get_assets(
|
||||
request: BatchGetRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import Optional
|
||||
import jwt
|
||||
from app.auth import AuthenticatedUser, blacklist_token, get_current_user
|
||||
from app.config import settings
|
||||
from app.dependencies import get_auth_email_service, get_auth_session_store, get_user_repository
|
||||
from app.dependencies import get_auth_email_service, get_auth_session_store, get_db_session, get_user_repository
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from pydantic import BaseModel, EmailStr, field_validator
|
||||
@@ -126,6 +126,7 @@ async def register(
|
||||
request: RegisterRequest,
|
||||
user_repository: UserRepository = Depends(get_user_repository),
|
||||
email_service=Depends(get_auth_email_service),
|
||||
db=Depends(get_db_session),
|
||||
) -> RegisterResponse:
|
||||
use_case = RegisterUserUseCase(
|
||||
user_repository=user_repository,
|
||||
@@ -143,6 +144,22 @@ async def register(
|
||||
if error or response is None:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=_translate_auth_error(error))
|
||||
|
||||
# 新用户注册赠送 50 积分(失败不影响注册)
|
||||
if settings.points_enabled:
|
||||
try:
|
||||
from packages.domain.points_service import PointsService
|
||||
_svc = PointsService()
|
||||
_svc.add_points(
|
||||
user_id=response.user_id,
|
||||
amount=50,
|
||||
source="task_reward",
|
||||
db=db,
|
||||
description="新用户注册赠送",
|
||||
)
|
||||
except Exception as _bonus_err:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("注册送积分失败: user_id=%s err=%s", response.user_id, _bonus_err)
|
||||
|
||||
return RegisterResponse(
|
||||
user_id=response.user_id,
|
||||
email=response.email,
|
||||
|
||||
@@ -8,7 +8,7 @@ import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -156,7 +156,7 @@ def _cleanup_expired_uploads() -> int:
|
||||
if not CHUNK_STORAGE_ROOT.exists():
|
||||
return 0
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.now(UTC)
|
||||
cleaned = 0
|
||||
|
||||
for meta_file in CHUNK_STORAGE_ROOT.glob("*.meta.json"):
|
||||
@@ -166,7 +166,7 @@ def _cleanup_expired_uploads() -> int:
|
||||
|
||||
expires_at = datetime.fromisoformat(meta["expires_at"])
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
||||
expires_at = expires_at.replace(tzinfo=UTC)
|
||||
|
||||
# Only cleanup uploads that are not actively being uploaded
|
||||
if expires_at < now and meta.get("status") != "uploading":
|
||||
@@ -226,7 +226,7 @@ async def init_chunked_upload(
|
||||
|
||||
# Generate upload ID
|
||||
upload_id = uuid4().hex
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.now(UTC)
|
||||
expires_at = now + timedelta(hours=CHUNK_EXPIRY_HOURS)
|
||||
|
||||
# Create chunk directory
|
||||
@@ -421,9 +421,9 @@ async def upload_chunk(
|
||||
# Check expiry
|
||||
expires_at = datetime.fromisoformat(meta["expires_at"])
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
||||
expires_at = expires_at.replace(tzinfo=UTC)
|
||||
|
||||
if expires_at < datetime.now(timezone.utc):
|
||||
if expires_at < datetime.now(UTC):
|
||||
raise HTTPException(status_code=status.HTTP_410_GONE, detail="Upload has expired")
|
||||
|
||||
# Validate chunk index
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""独立的从素材创建片段端点(不依赖 template_id 路径参数).
|
||||
|
||||
POST /api/v1/clips/from-assets
|
||||
- 与 /api/v1/templates/{template_id}/editor/clips/from-assets 功能一致
|
||||
- 区别:template_id 从 body 传入(可选),为空时后端自动创建/查找默认模板
|
||||
- 解决前端首次加载时 templateId 为空导致双斜杠 404 的问题(P0 #1922)
|
||||
- 内部复用 resolve_draft_plan_id 和 create_clips_from_assets_editor 的核心逻辑
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import get_asset_repository, get_db_session
|
||||
from app.services.edit_plan_service import EditPlanService
|
||||
from app.services.edit_template_service import EditTemplateService
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.adapters.sqlalchemy_impl.asset_repository import SQLAlchemyAssetRepository
|
||||
|
||||
from ._default_template import get_or_create_default_template_id
|
||||
from .templates_editor.clips import create_clips_from_assets_editor
|
||||
from .templates_editor.dependencies import resolve_draft_plan_id
|
||||
from .templates_editor.schemas import ClipsFromAssetsRequest, ClipsFromAssetsResponse
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(tags=["Clips"])
|
||||
|
||||
|
||||
class StandaloneClipsRequest(ClipsFromAssetsRequest):
|
||||
"""扩展请求:template_id 可选(不传则后端自动兜底默认模板)。"""
|
||||
|
||||
template_id: str | None = None
|
||||
|
||||
|
||||
def _get_editor_services_direct(db: Session) -> tuple[EditTemplateService, EditPlanService]:
|
||||
"""直接构造服务实例(非 Depends 版本,供独立端点内部调用)。"""
|
||||
return EditTemplateService(db), EditPlanService(db)
|
||||
|
||||
|
||||
@router.post("/clips/from-assets", response_model=ClipsFromAssetsResponse)
|
||||
def create_clips_from_assets(
|
||||
body: StandaloneClipsRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
db: Session = Depends(get_db_session),
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
asset_repo: SQLAlchemyAssetRepository = Depends(get_asset_repository),
|
||||
) -> ClipsFromAssetsResponse:
|
||||
"""从素材批量创建片段(template_id 可选,为空自动兜底)。"""
|
||||
user_id = str(current_user.user.id)
|
||||
services = _get_editor_services_direct(db)
|
||||
|
||||
# 1. 解析/兜底 template_id,拿到 plan_id
|
||||
template_id = (body.template_id or "").strip()
|
||||
if not template_id:
|
||||
template_id = get_or_create_default_template_id(db, user_id)
|
||||
if not template_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="无法自动创建默认模板,请刷新页面重试",
|
||||
)
|
||||
plan_id = resolve_draft_plan_id(
|
||||
template_id=template_id,
|
||||
services=services,
|
||||
current_user=current_user,
|
||||
db=db,
|
||||
auto_create_default=False, # 上面已兜底过
|
||||
)
|
||||
|
||||
# 2. 构造标准化请求(去除独立端扩展字段),复用原端点核心逻辑
|
||||
core_body = ClipsFromAssetsRequest(
|
||||
asset_ids=body.asset_ids,
|
||||
clip_type=body.clip_type,
|
||||
clip_count=body.clip_count,
|
||||
required_clips_count=body.required_clips_count,
|
||||
)
|
||||
|
||||
# 3. 直接调用原端点函数(此时所有 Depends 依赖已手动传入)
|
||||
return create_clips_from_assets_editor(
|
||||
template_id=template_id,
|
||||
body=core_body,
|
||||
background_tasks=background_tasks,
|
||||
plan_id=plan_id,
|
||||
services=services,
|
||||
asset_repo=asset_repo,
|
||||
db=db,
|
||||
current_user=current_user,
|
||||
)
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, List, Optional
|
||||
from typing import Any, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
@@ -27,6 +27,7 @@ from packages.adapters.sqlalchemy_impl.generation_task_repository import (
|
||||
)
|
||||
from packages.application import ListGeneratedVideosByTaskUseCase
|
||||
from packages.domain.config_schemas import normalize_plan_config
|
||||
from packages.middleware.points_gate import points_gate
|
||||
from packages.shared.storage import get_shared_storage_service
|
||||
|
||||
from .templates_editor.dependencies import get_draft_plan_id, get_editor_services
|
||||
@@ -41,7 +42,7 @@ router = APIRouter(tags=["Generation"])
|
||||
class GenerateCoverRequest(BaseModel):
|
||||
"""AI 封面生成请求体"""
|
||||
|
||||
asset_ids: List[str] = Field(default_factory=list, description="素材 ID 列表(确定视频来源)")
|
||||
asset_ids: list[str] = Field(default_factory=list, description="素材 ID 列表(确定视频来源)")
|
||||
cover_type: str = Field(
|
||||
default="ai_frame",
|
||||
description="封面类型: ai_frame / manual / upload / ai_regenerate",
|
||||
@@ -331,6 +332,7 @@ def _is_trusted_media_url(url: str) -> bool:
|
||||
|
||||
|
||||
@router.post("/generate-cover", response_model=GenerateCoverResponse)
|
||||
@points_gate("ai_cover")
|
||||
def generate_cover(
|
||||
body: GenerateCoverRequest,
|
||||
template_id: str = Query(..., description="模板 ID"),
|
||||
|
||||
@@ -43,6 +43,7 @@ from packages.application import (
|
||||
GetGenerationTaskUseCase,
|
||||
ListGeneratedVideosByTaskUseCase,
|
||||
)
|
||||
from packages.middleware.points_gate import points_gate
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -271,6 +272,7 @@ def _variant_value(values: list[str], index: int, fallback: str = "") -> str:
|
||||
|
||||
|
||||
@router.post("/preview", response_model=BatchPreviewGenerationTaskResponse, status_code=201)
|
||||
@points_gate("ai_video", quantity_field="preview_count")
|
||||
def create_preview_generation_task(
|
||||
request: CreatePreviewGenerationTaskRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
|
||||
@@ -42,6 +42,7 @@ from packages.application import (
|
||||
ListGeneratedVideosByTaskUseCase,
|
||||
)
|
||||
from packages.domain.smart_match import smart_select_assets
|
||||
from packages.middleware.points_gate import points_gate
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -211,6 +212,7 @@ def _resolve_project_and_library(
|
||||
|
||||
|
||||
@router.post("/tasks", response_model=BatchGenerationTaskResponse)
|
||||
@points_gate("ai_video", quantity_field="count")
|
||||
def create_generation_task(
|
||||
request: CreateGenerationTaskRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import psycopg
|
||||
import redis
|
||||
@@ -13,7 +13,7 @@ router = APIRouter(tags=["Health"])
|
||||
async def health_check():
|
||||
return {
|
||||
"status": "healthy",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"version": settings.APP_VERSION,
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ async def startup_check():
|
||||
all_ready = all(check["status"] == "healthy" for check in checks.values())
|
||||
response = {
|
||||
"status": "started" if all_ready else "starting",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"checks": checks,
|
||||
}
|
||||
if not all_ready:
|
||||
|
||||
@@ -12,8 +12,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
from datetime import UTC
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.config import settings
|
||||
from app.dependencies import (
|
||||
get_db_session,
|
||||
get_voice_clone_profile_repository,
|
||||
@@ -29,6 +32,9 @@ from app.services.mediakit_client import MediaKitError
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
from packages.domain.points_service import PointsService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
@@ -52,8 +58,40 @@ def _get_service(
|
||||
def create_lipsync_job(
|
||||
body: CreateLipsyncJobRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
svc: LipsyncService = Depends(_get_service),
|
||||
):
|
||||
user_id = current_user.user.id
|
||||
|
||||
# ── 积分扣点(#1895 P2) ──
|
||||
_points_deducted = 0
|
||||
_points_scene = "ai_digital_human"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
if _points_svc is not None:
|
||||
# 口型同步:TTS 模式按 script_text 估时长(240字/分钟);音频直传按 audio_duration(秒→分钟)
|
||||
if body.audio_url and body.audio_duration and body.audio_duration > 0:
|
||||
est_minutes = max(1.0, math.ceil(body.audio_duration / 60.0))
|
||||
elif body.script_text:
|
||||
est_minutes = max(1.0, math.ceil(len(body.script_text) / 240))
|
||||
else:
|
||||
est_minutes = 1.0
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(current_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(current_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
"""提交对口型任务.
|
||||
|
||||
三种模式:
|
||||
@@ -65,7 +103,7 @@ def create_lipsync_job(
|
||||
"""
|
||||
try:
|
||||
job = svc.create_job(
|
||||
user_id=current_user.user.id,
|
||||
user_id=user_id,
|
||||
video_url=body.video_url,
|
||||
audio_url=body.audio_url,
|
||||
audio_duration=body.audio_duration,
|
||||
@@ -78,8 +116,18 @@ def create_lipsync_job(
|
||||
project_id=body.project_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"对口型 ValueError 退积分异常: err={refund_err}")
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except MediaKitError as exc:
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"对口型 MediaKitError 退积分异常: err={refund_err}")
|
||||
status_code = 502
|
||||
if exc.code in ("VoiceForbidden",):
|
||||
status_code = 403
|
||||
@@ -95,11 +143,24 @@ def create_lipsync_job(
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
logger.error("创建对口型任务异常: %s", exc, exc_info=True)
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"对口型异常退积分异常: err={refund_err}")
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"创建对口型任务失败: {exc}",
|
||||
) from exc
|
||||
|
||||
# 创建成功但状态为 failed(同步路径失败已抛异常到上面 except;此处处理 Celery 调度失败等)
|
||||
# 若任务已创建且状态为 failed,退费
|
||||
if _points_deducted > 0 and _points_svc is not None and getattr(job, "status", None) == "failed":
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db, ref_id=job.id)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"对口型任务失败退积分异常: job_id={job.id}, err={refund_err}")
|
||||
|
||||
return job
|
||||
|
||||
|
||||
@@ -110,8 +171,34 @@ def create_lipsync_job(
|
||||
def preview_tts(
|
||||
body: AiAvatarTtsPreviewRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
svc: LipsyncService = Depends(_get_service),
|
||||
):
|
||||
user_id = current_user.user.id
|
||||
|
||||
# ── 积分扣点(#1895 P2) ──
|
||||
_points_deducted = 0
|
||||
_points_scene = "ai_digital_human"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
if _points_svc is not None:
|
||||
est_minutes = max(1.0, math.ceil(len(body.script_text or "") / 240)) if body.script_text else 1.0
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(current_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(current_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
"""步骤1「生成配音」同步 TTS 预合成.
|
||||
|
||||
同步执行 TTS 合成 → 下载音频 → ffprobe 时长 → 句子时间戳计算,
|
||||
@@ -120,13 +207,18 @@ def preview_tts(
|
||||
"""
|
||||
try:
|
||||
result = svc.preview_tts(
|
||||
user_id=current_user.user.id,
|
||||
user_id=user_id,
|
||||
voice_id=body.voice_id,
|
||||
script_text=body.script_text,
|
||||
speed=body.speed,
|
||||
emotion=body.emotion,
|
||||
)
|
||||
except MediaKitError as exc:
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"TTS 预合成 MediaKitError 退积分异常: err={refund_err}")
|
||||
status_code = 400
|
||||
if exc.code in ("VoiceForbidden",):
|
||||
status_code = 403
|
||||
@@ -141,6 +233,11 @@ def preview_tts(
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
logger.error("TTS 预合成异常: %s", exc, exc_info=True)
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"TTS 预合成异常退积分异常: err={refund_err}")
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"TTS 合成失败: {exc}",
|
||||
@@ -196,9 +293,8 @@ def get_lipsync_job(
|
||||
# 三层防御 ①:如果距上次更新超过 30 秒,同步刷新一次(避免 background task
|
||||
# 静默失败导致前端永远看到 running);否则挂后台异步刷新(避免阻塞轮询)。
|
||||
from datetime import datetime as _dt
|
||||
from datetime import timezone as _tz
|
||||
|
||||
_now = _dt.now(_tz.utc)
|
||||
_now = _dt.now(UTC)
|
||||
_stale = job.updated_at is None or (_now - job.updated_at).total_seconds() > 30
|
||||
if _stale:
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
"""积分 & 会员 API 路由 (#1895)
|
||||
|
||||
导出两个 router:
|
||||
- points_router: 积分相关路由,前缀 /points
|
||||
- usage_router: 每日额度路由,前缀 /usage
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import get_db_session
|
||||
from app.schemas.points import (
|
||||
DailyUsageResponse,
|
||||
MembershipStatusResponse,
|
||||
PointRuleItem,
|
||||
PointsBalanceResponse,
|
||||
PointsCheckRequest,
|
||||
PointsCheckResponse,
|
||||
PointsDeductRequest,
|
||||
PointsOrderResponse,
|
||||
PointsPackageItem,
|
||||
PointsPackagesResponse,
|
||||
PointsRechargeRequest,
|
||||
PointsRefundRequest,
|
||||
PointsRulesResponse,
|
||||
PointsTransactionsResponse,
|
||||
SimpleMessageResponse,
|
||||
)
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.domain.points_rules import (
|
||||
FREE_USER_MULTIPLIER,
|
||||
MEMBER_DISCOUNT,
|
||||
POINTS_PACKAGES,
|
||||
POINTS_SCENES,
|
||||
calculate_points_cost,
|
||||
)
|
||||
from packages.domain.points_service import PointsService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── 两个 router ──
|
||||
points_router = APIRouter()
|
||||
usage_router = APIRouter()
|
||||
|
||||
|
||||
def _get_service() -> PointsService:
|
||||
return PointsService()
|
||||
|
||||
|
||||
def _is_member(user: AuthenticatedUser) -> bool:
|
||||
"""判断用户是否为付费会员。"""
|
||||
return getattr(user.user, "is_member", False)
|
||||
|
||||
|
||||
def _member_type(user: AuthenticatedUser) -> str | None:
|
||||
return getattr(user.user, "member_type", None)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
# 积分相关路由 (prefix=/points)
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
@points_router.get("/balance", response_model=PointsBalanceResponse)
|
||||
def get_balance(
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""查询当前用户积分余额 + 会员状态。"""
|
||||
svc = _get_service()
|
||||
account = svc.get_or_create_account(current_user.user.id, db)
|
||||
return PointsBalanceResponse(
|
||||
balance=account["balance"],
|
||||
total_earned=account["total_earned"],
|
||||
total_spent=account["total_spent"],
|
||||
is_member=_is_member(current_user),
|
||||
member_type=_member_type(current_user),
|
||||
member_expires_at=getattr(current_user.user, "member_expires_at", None),
|
||||
)
|
||||
|
||||
|
||||
@points_router.get("/transactions", response_model=PointsTransactionsResponse)
|
||||
def get_transactions(
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=100),
|
||||
type: Optional[str] = Query(None, description="筛选类型: add/deduct"),
|
||||
source: Optional[str] = Query(None, description="筛选来源场景"),
|
||||
start_date: Optional[datetime] = Query(None),
|
||||
end_date: Optional[datetime] = Query(None),
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""查询积分流水(分页+筛选)。"""
|
||||
svc = _get_service()
|
||||
result = svc.get_transactions(
|
||||
user_id=current_user.user.id,
|
||||
db=db,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
type_filter=type,
|
||||
source_filter=source,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
)
|
||||
return PointsTransactionsResponse(**result)
|
||||
|
||||
|
||||
@points_router.get("/rules", response_model=PointsRulesResponse)
|
||||
def get_rules(
|
||||
_current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
):
|
||||
"""查询所有积分消耗规则。"""
|
||||
rules = []
|
||||
for scene_key, scene_data in POINTS_SCENES.items():
|
||||
rules.append(
|
||||
PointRuleItem(
|
||||
scene_key=scene_key,
|
||||
name=scene_data["name"],
|
||||
base_points=scene_data["base_points"],
|
||||
unit=scene_data["unit"],
|
||||
extra_per_30s=scene_data.get("extra_per_30s"),
|
||||
description=scene_data.get("description", ""),
|
||||
)
|
||||
)
|
||||
return PointsRulesResponse(
|
||||
rules=rules,
|
||||
free_user_multiplier=FREE_USER_MULTIPLIER,
|
||||
)
|
||||
|
||||
|
||||
@points_router.get("/packages", response_model=PointsPackagesResponse)
|
||||
def get_packages(
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
):
|
||||
"""查询可购买的积分包列表。"""
|
||||
packages = []
|
||||
for code, pkg in POINTS_PACKAGES.items():
|
||||
unit_price = f"¥{pkg['price_cents'] / 100 / pkg['points']:.3f}/积分"
|
||||
packages.append(
|
||||
PointsPackageItem(
|
||||
code=code,
|
||||
name=pkg["name"],
|
||||
points=pkg["points"],
|
||||
price_cents=pkg["price_cents"],
|
||||
unit_price=unit_price,
|
||||
)
|
||||
)
|
||||
mt = _member_type(current_user)
|
||||
discount = MEMBER_DISCOUNT.get(mt) if mt else None
|
||||
return PointsPackagesResponse(packages=packages, user_discount=discount)
|
||||
|
||||
|
||||
@points_router.post("/check", response_model=PointsCheckResponse)
|
||||
def check_points(
|
||||
body: PointsCheckRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""消费前检查余额是否足够。未知 scene_key 返回 400(而非 500)。"""
|
||||
if body.scene_key not in POINTS_SCENES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "UNKNOWN_SCENE",
|
||||
"message": f"未知场景: {body.scene_key}",
|
||||
"valid_scenes": sorted(POINTS_SCENES.keys()),
|
||||
},
|
||||
)
|
||||
is_mem = _is_member(current_user)
|
||||
mt = _member_type(current_user)
|
||||
|
||||
# 混剪场景先检查免费额度
|
||||
is_free_quota = False
|
||||
if body.scene_key == "ai_video" and not is_mem:
|
||||
svc = _get_service()
|
||||
if svc.check_daily_free_clip(current_user.user.id, db):
|
||||
is_free_quota = True
|
||||
|
||||
required = calculate_points_cost(
|
||||
body.scene_key,
|
||||
is_mem,
|
||||
quantity=body.quantity or 1,
|
||||
duration_minutes=body.duration_minutes or 0,
|
||||
member_type=mt,
|
||||
)
|
||||
|
||||
svc = _get_service()
|
||||
account = svc.get_or_create_account(current_user.user.id, db)
|
||||
balance = account["balance"]
|
||||
|
||||
return PointsCheckResponse(
|
||||
allowed=is_free_quota or balance >= required,
|
||||
required_points=required,
|
||||
current_balance=balance,
|
||||
remaining_after=balance - required,
|
||||
is_free_quota=is_free_quota,
|
||||
)
|
||||
|
||||
|
||||
@points_router.post("/deduct", response_model=SimpleMessageResponse)
|
||||
def deduct_points(
|
||||
body: PointsDeductRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""积分扣减(内部服务调用)。"""
|
||||
svc = _get_service()
|
||||
result = svc.deduct_points(
|
||||
user_id=current_user.user.id,
|
||||
amount=body.amount,
|
||||
source=body.scene_key,
|
||||
db=db,
|
||||
description=body.description or "",
|
||||
ref_id=body.ref_id or "",
|
||||
)
|
||||
if not result["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {body.amount},余额 {result['balance']}",
|
||||
},
|
||||
)
|
||||
return SimpleMessageResponse(
|
||||
success=True,
|
||||
message=f"扣减 {body.amount} 积分成功",
|
||||
data={"transaction_id": result["transaction_id"], "balance": result["balance"]},
|
||||
)
|
||||
|
||||
|
||||
@points_router.post("/refund", response_model=SimpleMessageResponse)
|
||||
def refund_points(
|
||||
body: PointsRefundRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""积分退还(内部服务调用)。"""
|
||||
from packages.adapters.sqlalchemy_impl.models import PointsTransactionModel
|
||||
|
||||
txn = (
|
||||
db.query(PointsTransactionModel)
|
||||
.filter(PointsTransactionModel.id == body.transaction_id)
|
||||
.first()
|
||||
)
|
||||
if txn is None:
|
||||
raise HTTPException(status_code=404, detail="交易记录不存在")
|
||||
if txn.user_id != current_user.user.id:
|
||||
raise HTTPException(status_code=403, detail="无权退还他人积分")
|
||||
|
||||
svc = _get_service()
|
||||
result = svc.refund_points(
|
||||
user_id=current_user.user.id,
|
||||
amount=txn.amount,
|
||||
source=txn.source,
|
||||
db=db,
|
||||
ref_id=body.transaction_id,
|
||||
description=body.reason or f"退还: {txn.description}",
|
||||
)
|
||||
if not result["success"]:
|
||||
raise HTTPException(status_code=500, detail="退还失败")
|
||||
return SimpleMessageResponse(
|
||||
success=True,
|
||||
message=f"退还 {txn.amount} 积分成功",
|
||||
data={"transaction_id": result["transaction_id"], "balance": result["balance"]},
|
||||
)
|
||||
|
||||
|
||||
@points_router.post("/recharge", response_model=PointsOrderResponse)
|
||||
def create_recharge_order(
|
||||
body: PointsRechargeRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""创建积分充值订单。pay_params 在支付通道接入后填入 prepay_id/payment_url;当前为空 dict。"""
|
||||
svc = _get_service()
|
||||
try:
|
||||
order = svc.create_order(
|
||||
user_id=current_user.user.id,
|
||||
order_type="points",
|
||||
product_code=body.package_id,
|
||||
db=db,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from None
|
||||
|
||||
package = POINTS_PACKAGES.get(body.package_id, {})
|
||||
now = datetime.now(timezone.utc)
|
||||
expire_at = now + timedelta(hours=48)
|
||||
# TODO: 接入微信/支付宝后填充真实 prepay_id / payment_url
|
||||
order["points_amount"] = package.get("points", 0)
|
||||
order["pay_params"] = {}
|
||||
order["expire_at"] = expire_at.isoformat()
|
||||
return PointsOrderResponse(**order)
|
||||
|
||||
|
||||
@points_router.get("/subscription/membership", response_model=MembershipStatusResponse)
|
||||
def get_membership_status(
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""获取当前用户会员状态(聚合信息)。"""
|
||||
svc = _get_service()
|
||||
account = svc.get_or_create_account(current_user.user.id, db)
|
||||
is_mem = _is_member(current_user)
|
||||
max_resolution = "1080p" if is_mem else "720p"
|
||||
|
||||
return MembershipStatusResponse(
|
||||
is_member=is_mem,
|
||||
member_type=_member_type(current_user),
|
||||
member_expires_at=getattr(current_user.user, "member_expires_at", None),
|
||||
points_balance=account["balance"],
|
||||
max_resolution=max_resolution,
|
||||
)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
# 每日额度路由 (prefix=/usage)
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
@usage_router.get("/daily", response_model=DailyUsageResponse)
|
||||
def get_daily_usage(
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""查询今日免费混剪额度使用情况。"""
|
||||
svc = _get_service()
|
||||
result = svc.get_daily_usage(current_user.user.id, db)
|
||||
return DailyUsageResponse(**result)
|
||||
|
||||
|
||||
# 为了向后兼容,也导出一个不带后缀的 router(方便旧引用)
|
||||
router = points_router
|
||||
@@ -36,6 +36,9 @@ def _to_response(script) -> ScriptResponse:
|
||||
for s in segments
|
||||
],
|
||||
tags=script.tags or [],
|
||||
title_text=getattr(script, "title_text", "") or "",
|
||||
title_category=getattr(script, "title_category", "") or "",
|
||||
title_config=getattr(script, "title_config", None) or {},
|
||||
created_at=script.created_at,
|
||||
updated_at=script.updated_at,
|
||||
)
|
||||
@@ -70,6 +73,9 @@ def create_script(
|
||||
content=request.content,
|
||||
segments=[s.model_dump() for s in request.segments],
|
||||
tags=request.tags,
|
||||
title_text=request.title_text or "",
|
||||
title_category=request.title_category or "",
|
||||
title_config=request.title_config or {},
|
||||
)
|
||||
return _to_response(script)
|
||||
|
||||
@@ -104,6 +110,9 @@ def update_script(
|
||||
content=request.content,
|
||||
segments=[s.model_dump() for s in request.segments] if request.segments is not None else None,
|
||||
tags=request.tags,
|
||||
title_text=request.title_text,
|
||||
title_category=request.title_category,
|
||||
title_config=request.title_config,
|
||||
)
|
||||
except ScriptNotFoundError as exc:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Script not found") from exc
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
"""Scripts AI 能力路由 — Issue #1893.
|
||||
|
||||
三个 AI 工具接口(均挂载在 /api/v1/scripts 前缀下):
|
||||
- POST /extract-from-douyin 从抖音视频提取文案(yt-dlp 下载 + ASR 转写)
|
||||
- POST /ai-rewrite AI 文案改写(复用豆包 LLM)
|
||||
- POST /ai-generate-titles AI 标题生成(复用 generate_smart_titles)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import get_db_session
|
||||
from app.schemas.scripts_ai import (
|
||||
AiGenerateTitlesRequest,
|
||||
AiGenerateTitlesResponse,
|
||||
AiRewriteRequest,
|
||||
AiRewriteResponse,
|
||||
ExtractFromDouyinRequest,
|
||||
ExtractFromDouyinResponse,
|
||||
)
|
||||
from app.services.script_asr_service import (
|
||||
ASRNotConfiguredError,
|
||||
ASRTranscriptionError,
|
||||
transcribe_to_text,
|
||||
)
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.middleware.points_gate import points_gate
|
||||
from packages.shared.ai_client import get_doubao_client
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# 抖音 URL 校验:支持短链 v.douyin.com 和长链 www.douyin.com/video/
|
||||
_DOUYIN_URL_RE = re.compile(
|
||||
r"^(https?://)?(v\.douyin\.com/\S+|www\.douyin\.com/video/\S+)$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _validate_douyin_url(url: str) -> None:
|
||||
"""校验抖音 URL 格式,不合法时抛 HTTPException(400)."""
|
||||
if not url or not url.strip():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="链接不能为空",
|
||||
)
|
||||
if not _DOUYIN_URL_RE.match(url.strip()):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="无效的抖音链接,仅支持 v.douyin.com 短链或 www.douyin.com/video/ 长链",
|
||||
)
|
||||
|
||||
|
||||
# ── 1. 从抖音视频提取文案 ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.post(
|
||||
"/extract-from-douyin",
|
||||
response_model=ExtractFromDouyinResponse,
|
||||
)
|
||||
@points_gate("douyin_extract")
|
||||
def extract_from_douyin(
|
||||
request: ExtractFromDouyinRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
) -> ExtractFromDouyinResponse:
|
||||
"""从抖音视频下载无水印视频并通过 ASR 提取文案."""
|
||||
source_url = request.url.strip()
|
||||
_validate_douyin_url(source_url)
|
||||
|
||||
# 确保 URL 有 scheme(yt-dlp 需要完整 URL)
|
||||
url_for_download = source_url
|
||||
if not re.match(r"^https?://", url_for_download, re.IGNORECASE):
|
||||
url_for_download = "https://" + url_for_download
|
||||
|
||||
text: str = ""
|
||||
duration: float = 0.0
|
||||
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="douyin_extract_") as temp_dir:
|
||||
# 延迟导入 yt-dlp,避免模块缺失时影响其他路由启动
|
||||
try:
|
||||
import yt_dlp
|
||||
except ImportError as exc:
|
||||
logger.error("yt-dlp 未安装,抖音提取功能不可用: %s", exc)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="抖音提取功能暂不可用(缺少依赖 yt-dlp)",
|
||||
) from exc
|
||||
|
||||
ydl_opts = {
|
||||
"format": "best[ext=mp4]/best",
|
||||
"outtmpl": f"{temp_dir}/%(id)s.%(ext)s",
|
||||
"quiet": True,
|
||||
"no_warnings": True,
|
||||
"noplaylist": True,
|
||||
}
|
||||
|
||||
try:
|
||||
ydl = yt_dlp.YoutubeDL(ydl_opts)
|
||||
info = ydl.extract_info(url_for_download, download=True)
|
||||
except yt_dlp.utils.DownloadError as exc:
|
||||
# yt-dlp 官方异常类型:HTTP 错误、短链失效、视频下架等
|
||||
msg = str(exc)
|
||||
logger.warning("抖音下载失败: url=%s error=%s", source_url, msg)
|
||||
# 404/视频不存在/不可下载 → 400;网络问题/上游异常 → 502
|
||||
is_bad_url = any(
|
||||
kw in msg.lower() for kw in ("404", "not found", "unable to download webpage", "unsupported url", "no video formats")
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST if is_bad_url else status.HTTP_502_BAD_GATEWAY,
|
||||
detail=("无法解析该抖音链接,请确认链接有效且视频未被下架" if is_bad_url else f"视频下载失败: {msg[:200]}"),
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
logger.exception("抖音视频下载异常: url=%s", source_url)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"视频下载失败: {str(exc)[:200]}",
|
||||
) from exc
|
||||
|
||||
if info is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="无法解析该抖音链接",
|
||||
)
|
||||
|
||||
video_path = ydl.prepare_filename(info)
|
||||
try:
|
||||
duration = float(info.get("duration") or 0)
|
||||
except (TypeError, ValueError):
|
||||
duration = 0.0
|
||||
|
||||
# 校验下载的文件是否真的存在(某些 yt-dlp 版本可能 info 成功但未下载到文件)
|
||||
if not os.path.isfile(video_path) or os.path.getsize(video_path) == 0:
|
||||
logger.error("yt-dlp 未产生有效视频文件: path=%s", video_path)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="视频下载异常:未获取到有效文件",
|
||||
)
|
||||
|
||||
# ASR 转写(兜底捕获所有异常,避免 500)
|
||||
try:
|
||||
text = transcribe_to_text(video_path)
|
||||
except ASRNotConfiguredError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
except ASRTranscriptionError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
logger.exception("ASR 转写异常: path=%s", video_path)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"语音识别失败: {str(exc)[:200]}",
|
||||
) from exc
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
# 最后兜底:任何未捕获异常都转成 502/400,不允许冒泡成 500
|
||||
logger.exception("抖音文案提取未预期异常: url=%s", source_url)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"抖音文案提取失败: {str(exc)[:200]}",
|
||||
) from exc
|
||||
|
||||
return ExtractFromDouyinResponse(
|
||||
text=text,
|
||||
duration_seconds=duration,
|
||||
source_url=source_url,
|
||||
)
|
||||
|
||||
|
||||
# ── 2. AI 文案改写 ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.post(
|
||||
"/ai-rewrite",
|
||||
response_model=AiRewriteResponse,
|
||||
)
|
||||
@points_gate("ai_rewrite")
|
||||
def ai_rewrite(
|
||||
request: AiRewriteRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
) -> AiRewriteResponse:
|
||||
"""使用豆包大模型改写文案."""
|
||||
content = (request.content or "").strip()
|
||||
if not content:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="文案内容不能为空",
|
||||
)
|
||||
|
||||
style = request.style or "口语化"
|
||||
|
||||
client = get_doubao_client()
|
||||
if not client.is_available:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="AI 服务不可用,请联系管理员配置豆包大模型 API Key",
|
||||
)
|
||||
|
||||
system_prompt = (
|
||||
"你是一个专业的短视频文案改写专家。请对以下文案进行改写,"
|
||||
"要求:保留原意、口语化、适合短视频口播、调整语序避免查重。"
|
||||
)
|
||||
if style:
|
||||
system_prompt += f"\n风格要求:{style}"
|
||||
|
||||
user_prompt = f"请改写以下文案:\n\n{content}"
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
]
|
||||
|
||||
try:
|
||||
rewritten = client.chat_completion(
|
||||
messages=messages,
|
||||
temperature=0.8,
|
||||
max_tokens=2048,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("AI 改写调用失败: %s", exc)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"AI 改写失败: {exc}",
|
||||
) from exc
|
||||
|
||||
if not rewritten:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="AI 改写未返回有效结果",
|
||||
)
|
||||
|
||||
return AiRewriteResponse(
|
||||
original=content,
|
||||
rewritten=rewritten.strip(),
|
||||
style=style,
|
||||
)
|
||||
|
||||
|
||||
# ── 3. AI 标题生成 ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.post(
|
||||
"/ai-generate-titles",
|
||||
response_model=AiGenerateTitlesResponse,
|
||||
)
|
||||
@points_gate("ai_title")
|
||||
def ai_generate_titles(
|
||||
request: AiGenerateTitlesRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
) -> AiGenerateTitlesResponse:
|
||||
"""使用现有 generate_smart_titles 生成标题."""
|
||||
content = (request.content or "").strip()
|
||||
if not content:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="文案内容不能为空",
|
||||
)
|
||||
|
||||
# count 限制在 1-5(Pydantic ge=1 le=5 已校验),但为兼容直接调用场景截断
|
||||
count = max(1, min(5, request.count))
|
||||
|
||||
from app.services.ai_service import generate_smart_titles
|
||||
|
||||
result = generate_smart_titles(
|
||||
description=content,
|
||||
style="viral",
|
||||
count=count,
|
||||
)
|
||||
|
||||
titles = result.get("titles", [])[:count]
|
||||
|
||||
return AiGenerateTitlesResponse(titles=titles)
|
||||
@@ -4,8 +4,8 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timezone
|
||||
from typing import List
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import get_user_repository
|
||||
@@ -67,7 +67,7 @@ def _get_plan_price(plan_id: str, billing_cycle: str) -> float:
|
||||
|
||||
def _build_subscription_info(user: AuthenticatedUser) -> SubscriptionInfo:
|
||||
"""构建订阅信息响应"""
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.now(UTC)
|
||||
if user.user.subscription_expires_at:
|
||||
period_end = user.user.subscription_expires_at.isoformat()
|
||||
period_start = now.isoformat()
|
||||
@@ -100,10 +100,43 @@ async def get_current_subscription(
|
||||
return _build_subscription_info(current_user)
|
||||
|
||||
|
||||
@router.get("/billing-records", response_model=List[BillingRecord])
|
||||
@router.get("/plans")
|
||||
def list_membership_plans(
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
"""查询所有会员档位(供前端会员购买页展示)。
|
||||
|
||||
返回 points 积分体系下的会员档位(月卡/季卡/年卡),含价格、时长、积分折扣等信息。
|
||||
"""
|
||||
from packages.domain.points_rules import MEMBER_DISCOUNT, MEMBERSHIP_PRICES
|
||||
|
||||
plans: list[dict[str, Any]] = []
|
||||
for plan_id, info in MEMBERSHIP_PRICES.items():
|
||||
days = info["duration_days"]
|
||||
monthly_cents = round(info["price_cents"] * 30 / days)
|
||||
features: dict[str, Any] = {"max_resolution": "1080p"}
|
||||
if plan_id == "monthly":
|
||||
features.update({"free_clips_daily": 2})
|
||||
elif plan_id == "quarterly":
|
||||
features.update({"free_clips_daily": 5})
|
||||
elif plan_id == "yearly":
|
||||
features.update({"free_clips_daily": "unlimited"})
|
||||
plans.append({
|
||||
"plan_id": plan_id,
|
||||
"name": info["name"],
|
||||
"price_cents": info["price_cents"],
|
||||
"monthly_price_cents": monthly_cents,
|
||||
"duration_days": days,
|
||||
"points_discount": MEMBER_DISCOUNT.get(plan_id, 1.0),
|
||||
"features": features,
|
||||
})
|
||||
return {"plans": plans}
|
||||
|
||||
|
||||
@router.get("/billing-records", response_model=list[BillingRecord])
|
||||
async def get_billing_records(
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
) -> List[BillingRecord]:
|
||||
) -> list[BillingRecord]:
|
||||
"""获取账单记录列表"""
|
||||
from packages.adapters.sqlalchemy_impl.billing_repository import SQLAlchemyBillingRepository
|
||||
from packages.adapters.sqlalchemy_impl.session import SessionLocal
|
||||
@@ -251,7 +284,7 @@ async def payment_callback(
|
||||
|
||||
# 计算到期时间
|
||||
days = 365 if billing_cycle == "yearly" else 30
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(days=days)
|
||||
expires_at = datetime.now(UTC) + timedelta(days=days)
|
||||
repo.update_subscription_on_payment(user_id, plan, expires_at)
|
||||
|
||||
return {"success": True, "message": "支付成功", "record_id": record_id}
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
保留:
|
||||
- GET /templates:列表查询(生成页使用)
|
||||
- 默认模板自动创建兜底逻辑(``_get_or_create_default_template_id`` 位于
|
||||
generation_variant_plans.py)继续通过 service 层 CreateTemplateUseCase 工作,
|
||||
但不再暴露模板 CRUD / 分类 / 标签 / 收藏 / 复制 / 校验 / 使用统计等 HTTP 端点
|
||||
(前端 PR#1911 已删除 my-templates / editing-planner / templates 管理页面)。
|
||||
- 默认模板自动创建兜底逻辑(复用 _default_template.get_or_create_default_template_id)
|
||||
|
||||
其他模板 CRUD / 分类 / 标签 / 收藏 / 复制 / 校验 / 使用统计等 HTTP 端点
|
||||
已在 PR#1918 中删除(前端 PR#1911 已删除 my-templates / editing-planner /
|
||||
templates 管理页面)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,6 +28,8 @@ from packages.adapters.sqlalchemy_impl.template_repository import SQLAlchemyTemp
|
||||
from packages.application.template.commands import ListTemplatesFilter
|
||||
from packages.application.template.use_cases import CountTemplatesUseCase, ListTemplatesUseCase
|
||||
|
||||
from ._default_template import get_or_create_default_template_id
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@@ -43,9 +46,13 @@ def list_templates(
|
||||
page_size: int = Query(20, ge=1, le=100, description="每页条数,默认 20"),
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
repo: SQLAlchemyTemplateRepository = Depends(_get_template_repository),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""获取用户可用的模板列表(仅返回 active 状态)。"""
|
||||
user_id = str(current_user.user.id)
|
||||
# P0 兜底:无有效模板时自动创建默认配音模板(解决新用户首次进入生成页 404)
|
||||
get_or_create_default_template_id(db, user_id)
|
||||
|
||||
list_uc = ListTemplatesUseCase(repo)
|
||||
count_uc = CountTemplatesUseCase(repo)
|
||||
filters = ListTemplatesFilter(
|
||||
|
||||
@@ -28,7 +28,7 @@ from .adjustments import router as adjustments_router
|
||||
from .ai_features import router as ai_features_router
|
||||
from .bgm import router as bgm_router
|
||||
from .clips import router as clips_router
|
||||
from .dependencies import get_draft_plan_id, get_editor_services # noqa: F401
|
||||
from .dependencies import get_draft_plan_id, get_editor_services, resolve_draft_plan_id # noqa: F401
|
||||
from .draft import router as draft_router
|
||||
from .effects import router as effects_router
|
||||
from .export import router as export_router
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
核心依赖:
|
||||
- get_editor_services: 获取模板+计划服务
|
||||
- get_draft_plan_id: 根据 template_id 获取或创建草稿,返回 plan_id
|
||||
- get_draft_plan_id: Depends 形式的路径依赖(template_id 路径参数必填)
|
||||
- resolve_draft_plan_id: 纯函数版本,供 clips_standalone 等非路径参数场景复用
|
||||
(支持空 tid 时自动兜底创建默认模板)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from app.api.routes._default_template import get_or_create_default_template_id
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import get_db_session
|
||||
from app.services.edit_plan_service import EditPlanService
|
||||
@@ -30,50 +33,61 @@ def get_editor_services(
|
||||
return EditTemplateService(db), EditPlanService(db)
|
||||
|
||||
|
||||
def get_draft_plan_id(
|
||||
def resolve_draft_plan_id(
|
||||
template_id: str,
|
||||
services: tuple[EditTemplateService, EditPlanService] = Depends(get_editor_services),
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
services: tuple[EditTemplateService, EditPlanService],
|
||||
current_user: AuthenticatedUser,
|
||||
db: Session,
|
||||
auto_create_default: bool = True,
|
||||
) -> str:
|
||||
"""路径依赖:根据 template_id 获取或创建草稿,返回 plan_id.
|
||||
"""根据 template_id 获取或创建草稿,返回 plan_id(纯函数,不带 Depends)。
|
||||
|
||||
这是模板编辑器路由的核心依赖——所有编辑器端点都先经过这里,
|
||||
确保 template_id → plan_id 的映射始终存在。
|
||||
|
||||
模板读取遵循单一数据源、显式判定(不使用异常降级):
|
||||
- 用户自建模板在旧表 ``templates``(归属 user_id,is_active=True);
|
||||
- 全局模板在新表 ``edit_templates``(无 user_id,全局可读)。
|
||||
模板不存在、已删除或不归属于当前用户时,一律返回 404。
|
||||
当 auto_create_default=True 且 template_id 为空时,自动调用
|
||||
get_or_create_default_template_id 创建默认模板(用于 clips_standalone
|
||||
等非路径参数场景)。
|
||||
"""
|
||||
tpl_svc, plan_svc = services
|
||||
user_id = str(current_user.user.id)
|
||||
|
||||
# 0. 门禁:校验模板存在且可访问(即使草稿已缓存命中也要校验,
|
||||
# 避免模板被删除/无权访问后仍可通过既有草稿 plan 继续操作)。
|
||||
# 0. 空 tid 兜底
|
||||
if not template_id:
|
||||
if auto_create_default:
|
||||
tid = get_or_create_default_template_id(db, user_id)
|
||||
if not tid:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="无法自动创建默认模板,请刷新页面重试",
|
||||
)
|
||||
template_id = tid
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="template_id 不能为空",
|
||||
)
|
||||
|
||||
# 1. 门禁:校验模板存在且可访问
|
||||
old_repo = SQLAlchemyTemplateRepository(db)
|
||||
old_template = old_repo.get_active(template_id, user_id)
|
||||
is_global_template = tpl_svc.get_template(template_id) is not None
|
||||
if old_template is None and not is_global_template:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="模板不存在")
|
||||
|
||||
# 1. 草稿已存在 → 直接返回
|
||||
# 2. 草稿已存在 → 直接返回
|
||||
draft = tpl_svc.get_template_draft(template_id)
|
||||
if draft is not None:
|
||||
return draft.id
|
||||
|
||||
# 2. 全局模板(新系统)→ 用新服务创建草稿
|
||||
# 3. 全局模板(新系统)→ 用新服务创建草稿
|
||||
if is_global_template:
|
||||
draft = tpl_svc.create_template_draft(template_id, user_id=user_id)
|
||||
return draft.id
|
||||
|
||||
# 3. 旧模板(templates 表)→ 基于旧模板创建草稿计划
|
||||
# 4. 旧模板(templates 表)→ 基于旧模板创建草稿计划
|
||||
from app.services.plan_generator_service import PlanGeneratorService
|
||||
|
||||
from packages.domain.edit_template import EditTemplate, EditTemplateStatus
|
||||
from packages.domain.template_clip_config import ClipType, TemplateClipConfig
|
||||
|
||||
# 构造伪 EditTemplate 对象(只填 generate_from_template 需要的字段)
|
||||
pseudo_template = EditTemplate(
|
||||
id=old_template.id,
|
||||
name=old_template.name,
|
||||
@@ -81,7 +95,6 @@ def get_draft_plan_id(
|
||||
status=EditTemplateStatus.ACTIVE,
|
||||
)
|
||||
|
||||
# 将旧模板 segments 转换为 clip_configs
|
||||
clip_configs: list[TemplateClipConfig] = []
|
||||
for seg in old_template.segments or []:
|
||||
clip_configs.append(
|
||||
@@ -105,7 +118,6 @@ def get_draft_plan_id(
|
||||
)
|
||||
plan = result["plan"]
|
||||
|
||||
# 标记为模板草稿(后续可复用 tpl_svc.get_template_draft 的查找逻辑)
|
||||
plan_svc.update_plan_config(plan.id, {"is_template_draft": True})
|
||||
|
||||
logger.info(
|
||||
@@ -115,3 +127,23 @@ def get_draft_plan_id(
|
||||
user_id,
|
||||
)
|
||||
return plan.id
|
||||
|
||||
|
||||
def get_draft_plan_id(
|
||||
template_id: str,
|
||||
services: tuple[EditTemplateService, EditPlanService] = Depends(get_editor_services),
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
) -> str:
|
||||
"""路径依赖:根据 template_id 获取或创建草稿,返回 plan_id.
|
||||
|
||||
Depends 版本:路径参数 template_id 由 FastAPI 保证非空,不自动兜底。
|
||||
兜底逻辑走 resolve_draft_plan_id(auto_create_default=False)。
|
||||
"""
|
||||
return resolve_draft_plan_id(
|
||||
template_id=template_id,
|
||||
services=services,
|
||||
current_user=current_user,
|
||||
db=db,
|
||||
auto_create_default=False,
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re as _re
|
||||
from typing import Any, List, Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator, validator
|
||||
|
||||
@@ -21,7 +21,7 @@ _EXPORT_VALID_FORMATS = {"mp4", "mov"}
|
||||
class AIRecommendRequest(BaseModel):
|
||||
"""AI 推荐片段方案请求体"""
|
||||
|
||||
asset_ids: List[str] = Field(default_factory=list, description="素材 ID 列表")
|
||||
asset_ids: list[str] = Field(default_factory=list, description="素材 ID 列表")
|
||||
editing_mode: str = Field(default="one_take", description="剪辑模式: one_take / pip / voice_over / voice_pip")
|
||||
target_duration: float = Field(default=30.0, ge=1.0, le=600.0, description="目标时长(秒)")
|
||||
|
||||
@@ -44,7 +44,7 @@ class AIRecommendResponse(BaseModel):
|
||||
"""AI 推荐片段方案响应体"""
|
||||
|
||||
plan_id: str = Field(..., description="剪辑计划 ID")
|
||||
clips: List[AIRecommendClipItem] = Field(..., description="推荐的片段列表")
|
||||
clips: list[AIRecommendClipItem] = Field(..., description="推荐的片段列表")
|
||||
config: dict[str, Any] = Field(..., description="推荐的 plan config(cover/title/subtitle/bgm)")
|
||||
total_duration: float = Field(..., ge=0.0, description="推荐方案总时长(秒)")
|
||||
confidence: float = Field(..., ge=0.0, le=1.0, description="AI 推荐置信度 (0~1)")
|
||||
@@ -137,7 +137,7 @@ class ClipReorderItem(BaseModel):
|
||||
class ClipReorderRequest(BaseModel):
|
||||
"""片段重排序请求"""
|
||||
|
||||
items: List[ClipReorderItem] = Field(..., min_length=1, max_length=500, description="重排序条目列表")
|
||||
items: list[ClipReorderItem] = Field(..., min_length=1, max_length=500, description="重排序条目列表")
|
||||
|
||||
|
||||
class ClipReorderResponse(BaseModel):
|
||||
@@ -151,7 +151,7 @@ class ClipReorderResponse(BaseModel):
|
||||
class ClipBatchDeleteRequest(BaseModel):
|
||||
"""批量删除片段请求"""
|
||||
|
||||
clip_ids: List[str] = Field(..., min_length=1, max_length=500, description="要删除的片段ID列表")
|
||||
clip_ids: list[str] = Field(..., min_length=1, max_length=500, description="要删除的片段ID列表")
|
||||
|
||||
|
||||
class ClipBatchDeleteResponse(BaseModel):
|
||||
@@ -169,7 +169,7 @@ _UNSET = object()
|
||||
class ClipsFromAssetsRequest(BaseModel):
|
||||
"""从素材批量创建片段请求"""
|
||||
|
||||
asset_ids: List[str] = Field(..., min_length=1, max_length=200, description="素材 ID 列表,按顺序追加到时间线末尾")
|
||||
asset_ids: list[str] = Field(..., min_length=1, max_length=200, description="素材 ID 列表,按顺序追加到时间线末尾")
|
||||
clip_type: str = Field(default="main", description="片段类型,默认 main")
|
||||
clip_count: Optional[int] = Field(
|
||||
default=None,
|
||||
@@ -218,7 +218,7 @@ class ClipsFromAssetsResponse(BaseModel):
|
||||
created_count: int
|
||||
plan_id: str = ""
|
||||
message: str = ""
|
||||
clip_ids: List[str] = Field(default_factory=list, description="创建的片段ID列表")
|
||||
clip_ids: list[str] = Field(default_factory=list, description="创建的片段ID列表")
|
||||
duplicate_warning: Optional[str] = Field(default=None, description="查重率超标警告")
|
||||
exhaustion_warning: Optional[str] = Field(default=None, description="素材耗尽警告")
|
||||
|
||||
@@ -302,7 +302,7 @@ class ExportPresetItem(BaseModel):
|
||||
class ExportPresetListResponse(BaseModel):
|
||||
"""导出预设列表响应"""
|
||||
|
||||
items: List[ExportPresetItem]
|
||||
items: list[ExportPresetItem]
|
||||
total: int
|
||||
|
||||
|
||||
@@ -316,7 +316,7 @@ class FilterPresetResponse(BaseModel):
|
||||
name: str
|
||||
category: str
|
||||
description: str
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class FilterConfigResponse(BaseModel):
|
||||
@@ -346,7 +346,7 @@ class FilterUpdateRequest(BaseModel):
|
||||
class FilterPresetListResponse(BaseModel):
|
||||
"""滤镜预设列表响应"""
|
||||
|
||||
items: List[FilterPresetResponse]
|
||||
items: list[FilterPresetResponse]
|
||||
total: int
|
||||
|
||||
|
||||
@@ -360,7 +360,7 @@ class TransitionPresetResponse(BaseModel):
|
||||
name: str
|
||||
category: str
|
||||
description: str
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
default_duration: float
|
||||
min_duration: float
|
||||
max_duration: float
|
||||
@@ -402,7 +402,7 @@ class BatchTransitionResponse(BaseModel):
|
||||
class TransitionPresetListResponse(BaseModel):
|
||||
"""转场预设列表响应"""
|
||||
|
||||
items: List[TransitionPresetResponse]
|
||||
items: list[TransitionPresetResponse]
|
||||
total: int
|
||||
|
||||
|
||||
@@ -458,7 +458,7 @@ class EditorClipResponse(BaseModel):
|
||||
class EditorClipListResponse(BaseModel):
|
||||
"""片段列表响应"""
|
||||
|
||||
items: List[EditorClipResponse]
|
||||
items: list[EditorClipResponse]
|
||||
total: int
|
||||
|
||||
|
||||
@@ -496,7 +496,7 @@ class EditorClipBatchItem(BaseModel):
|
||||
class EditorClipBatchUpdateRequest(BaseModel):
|
||||
"""批量替换clips请求(全量覆盖)"""
|
||||
|
||||
clips: List[EditorClipBatchItem] = Field(default_factory=list)
|
||||
clips: list[EditorClipBatchItem] = Field(default_factory=list)
|
||||
|
||||
|
||||
class EditorClipBatchUpdateResponse(BaseModel):
|
||||
@@ -584,4 +584,4 @@ class EditorTimelineResponse(BaseModel):
|
||||
|
||||
plan_id: str
|
||||
total_duration: float
|
||||
scenes: List[EditorTimelineSceneResponse]
|
||||
scenes: list[EditorTimelineSceneResponse]
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
"""Title library CRUD routes."""
|
||||
"""Title library CRUD routes.
|
||||
|
||||
.. deprecated::
|
||||
标题库 API 已废弃(#1894),标题配置已整合到 scripts 模型。
|
||||
所有接口保留向后兼容,但返回 Warning header 并记录日志。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from app.api.routes._helpers import get_user_plan
|
||||
@@ -35,6 +41,21 @@ from packages.application.title_library.use_cases import (
|
||||
from packages.ports.user_repository import UserRepository
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DEPRECATION_WARNING = (
|
||||
'299 - "Title library API is deprecated; migrate to scripts.title_text/'
|
||||
'title_category/title_config (issue #1894)"'
|
||||
)
|
||||
|
||||
|
||||
def _deprecation_headers() -> dict:
|
||||
"""返回 deprecation Warning header (ASCII-only, RFC 7234 §5.5)."""
|
||||
return {"Warning": _DEPRECATION_WARNING, "Deprecation": "true"}
|
||||
|
||||
|
||||
def _log_deprecation(endpoint: str) -> None:
|
||||
logger.warning("[Deprecated] title_library API 调用: %s — %s", endpoint, _DEPRECATION_WARNING)
|
||||
|
||||
|
||||
def _get_title_repository(session: Session = Depends(get_db_session)) -> SQLAlchemyTitleLibraryRepository:
|
||||
@@ -59,12 +80,17 @@ def _to_response(item) -> TitleLibraryItemResponse:
|
||||
|
||||
@router.get("", response_model=ListTitleLibraryResponse)
|
||||
def list_titles(
|
||||
response: Response,
|
||||
category: Optional[str] = Query(None),
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
title_repository: SQLAlchemyTitleLibraryRepository = Depends(_get_title_repository),
|
||||
) -> ListTitleLibraryResponse:
|
||||
"""[Deprecated] 请使用 scripts API 的 title_text/title_category 字段替代."""
|
||||
_log_deprecation("list_titles")
|
||||
for k, v in _deprecation_headers().items():
|
||||
response.headers[k] = v
|
||||
user_id = authenticated_user.user.id
|
||||
use_case = ListTitleLibraryUseCase(title_repository)
|
||||
items = use_case.execute(user_id, category=category, skip=skip, limit=limit)
|
||||
@@ -77,6 +103,7 @@ def list_titles(
|
||||
|
||||
@router.post("/pick", response_model=TitleLibraryItemResponse)
|
||||
def pick_title(
|
||||
response: Response,
|
||||
category: Optional[str] = Query(None, description="按分类筛选,不填则从全部标题中选"),
|
||||
exclude_ids: Optional[str] = Query(
|
||||
None,
|
||||
@@ -85,10 +112,15 @@ def pick_title(
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
title_repository: SQLAlchemyTitleLibraryRepository = Depends(_get_title_repository),
|
||||
) -> TitleLibraryItemResponse:
|
||||
"""智能选择一个标题。
|
||||
"""[Deprecated] 请使用 scripts API 的 title_text/title_category 字段替代.
|
||||
|
||||
智能选择一个标题。
|
||||
|
||||
策略:优先使用次数少的,从最少的前5个中随机选一个,兼顾公平和多样性。
|
||||
"""
|
||||
_log_deprecation("pick_title")
|
||||
for k, v in _deprecation_headers().items():
|
||||
response.headers[k] = v
|
||||
user_id = authenticated_user.user.id
|
||||
exclude_list: list[str] = []
|
||||
if exclude_ids:
|
||||
@@ -113,9 +145,14 @@ def pick_title(
|
||||
@router.get("/{title_id}", response_model=TitleLibraryItemResponse)
|
||||
def get_title(
|
||||
title_id: str,
|
||||
response: Response,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
title_repository: SQLAlchemyTitleLibraryRepository = Depends(_get_title_repository),
|
||||
) -> TitleLibraryItemResponse:
|
||||
"""[Deprecated] 请使用 scripts API 的 title_text/title_category 字段替代."""
|
||||
_log_deprecation("get_title")
|
||||
for k, v in _deprecation_headers().items():
|
||||
response.headers[k] = v
|
||||
user_id = authenticated_user.user.id
|
||||
use_case = GetTitleLibraryUseCase(title_repository)
|
||||
item = use_case.execute(title_id, user_id)
|
||||
@@ -126,11 +163,16 @@ def get_title(
|
||||
|
||||
@router.post("", response_model=TitleLibraryItemResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_title(
|
||||
response: Response,
|
||||
request: CreateTitleLibraryRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
title_repository: SQLAlchemyTitleLibraryRepository = Depends(_get_title_repository),
|
||||
user_repository: UserRepository = Depends(get_user_repository),
|
||||
) -> TitleLibraryItemResponse:
|
||||
"""[Deprecated] 请使用 scripts API 的 title_text/title_category 字段替代."""
|
||||
_log_deprecation("create_title")
|
||||
for k, v in _deprecation_headers().items():
|
||||
response.headers[k] = v
|
||||
user_id = authenticated_user.user.id
|
||||
plan_name = get_user_plan(user_id, user_repository)
|
||||
command = CreateTitleLibraryCommand(
|
||||
@@ -155,10 +197,15 @@ def create_title(
|
||||
@router.put("/{title_id}", response_model=TitleLibraryItemResponse)
|
||||
def update_title(
|
||||
title_id: str,
|
||||
response: Response,
|
||||
request: UpdateTitleLibraryRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
title_repository: SQLAlchemyTitleLibraryRepository = Depends(_get_title_repository),
|
||||
) -> TitleLibraryItemResponse:
|
||||
"""[Deprecated] 请使用 scripts API 的 title_text/title_category 字段替代."""
|
||||
_log_deprecation("update_title")
|
||||
for k, v in _deprecation_headers().items():
|
||||
response.headers[k] = v
|
||||
user_id = authenticated_user.user.id
|
||||
command = UpdateTitleLibraryCommand(
|
||||
title_id=title_id,
|
||||
@@ -180,9 +227,14 @@ def update_title(
|
||||
@router.delete("/{title_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None, response_class=Response)
|
||||
def delete_title(
|
||||
title_id: str,
|
||||
response: Response,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
title_repository: SQLAlchemyTitleLibraryRepository = Depends(_get_title_repository),
|
||||
) -> Response:
|
||||
"""[Deprecated] 请使用 scripts API 的 title_text/title_category 字段替代."""
|
||||
_log_deprecation("delete_title")
|
||||
for k, v in _deprecation_headers().items():
|
||||
response.headers[k] = v
|
||||
user_id = authenticated_user.user.id
|
||||
use_case = DeleteTitleLibraryUseCase(title_repository)
|
||||
deleted = use_case.execute(title_id, user_id)
|
||||
|
||||
@@ -4,12 +4,14 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.config import settings
|
||||
from app.core.celery_app import celery_app
|
||||
from app.core.storage import get_storage_service
|
||||
from app.dependencies import (
|
||||
@@ -51,6 +53,8 @@ from packages.application.tts_job.use_cases import (
|
||||
)
|
||||
from packages.application.tts_job.workflow import TTSWorkflowService
|
||||
from packages.domain import Asset, AssetLibrary, AssetLibraryKind, AssetStatus, ClassificationStatus
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
from packages.domain.points_service import PointsService
|
||||
from packages.domain.voice_presets import list_voices
|
||||
from packages.ports.asset_library_repository import AssetLibraryRepository
|
||||
from packages.ports.asset_repository import AssetRepository
|
||||
@@ -128,6 +132,7 @@ def _to_response(job, sign_url=None) -> TTSJobResponse:
|
||||
def synthesize(
|
||||
request: TTSSynthesizeRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
repository: SQLAlchemyTTSJobRepository = Depends(_get_repository),
|
||||
cosyvoice_service: CosyVoiceService = Depends(get_cosyvoice_service),
|
||||
voice_clone_repo=Depends(get_voice_clone_profile_repository),
|
||||
@@ -139,6 +144,31 @@ def synthesize(
|
||||
"""
|
||||
user_id = authenticated_user.user.id
|
||||
|
||||
# ── 积分扣点(#1895 P2) ──
|
||||
_points_deducted = 0
|
||||
_points_scene = "ai_voice"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
if _points_svc is not None:
|
||||
# 中文按 ~240 字/分钟粗估时长,至少按 1 分钟扣 1 分
|
||||
est_minutes = max(1.0, math.ceil(len(request.text) / 240))
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(authenticated_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(authenticated_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
|
||||
# 解析 voice_id:前端可能传克隆音色 profile UUID(而非 CosyVoice voice_id),
|
||||
# 与 /tts/preview 保持一致:命中 profile → 校验归属 → 取 CosyVoice voice_id
|
||||
actual_voice_id = request.voice_id
|
||||
@@ -198,6 +228,7 @@ def synthesize(
|
||||
cosyvoice_service=cosyvoice_service,
|
||||
)
|
||||
|
||||
synthesis_error: Exception | None = None
|
||||
try:
|
||||
job = workflow.start_synthesis(job.id)
|
||||
except Exception as e:
|
||||
@@ -205,10 +236,17 @@ def synthesize(
|
||||
# 但 DB 异常、网络异常等意外错误可能逃逸。
|
||||
# 与音色克隆接口保持一致:标记 failed,返回 201,不抛 500。
|
||||
logger.error(f"TTS 合成异常: job_id={job.id}, error={e}", exc_info=True)
|
||||
synthesis_error = e
|
||||
try:
|
||||
job = workflow.process_synthesis_failure(job.id, str(e))
|
||||
except Exception as inner_e:
|
||||
logger.error(f"标记 TTS job 失败时出错: job_id={job.id}, error={inner_e}")
|
||||
# 合成失败且已扣积分 → 退费
|
||||
if synthesis_error is not None and _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db, ref_id=job.id)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"TTS 合失败退积分异常: job_id={job.id}, err={refund_err}")
|
||||
|
||||
# 若任务处于 processing 状态(异步模式),触发 Celery 后台轮询
|
||||
if job.status.value == "processing":
|
||||
@@ -223,10 +261,17 @@ def synthesize(
|
||||
celery_app.send_task("worker.process_tts_synthesis", args=[job.id])
|
||||
except Exception as e:
|
||||
# Celery 调度失败,标记 job 为 failed
|
||||
# e used below for refund context
|
||||
try:
|
||||
workflow.process_synthesis_failure(job.id, f"Celery 任务调度失败: {e}")
|
||||
except Exception as inner_e:
|
||||
logger.error(f"Celery 调度后标记失败时出错: job_id={job.id}, error={inner_e}")
|
||||
# 调度失败退费
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db, ref_id=job.id)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"Celery 调度失败退积分异常: job_id={job.id}, err={refund_err}")
|
||||
|
||||
return TTSSynthesizeResponse(
|
||||
job_id=job.id,
|
||||
@@ -553,6 +598,7 @@ def save_tts_job_to_library(
|
||||
def preview_tts(
|
||||
request: TTSPreviewRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
cosyvoice_service: CosyVoiceService = Depends(get_cosyvoice_service),
|
||||
voice_clone_repo=Depends(get_voice_clone_profile_repository),
|
||||
) -> TTSPreviewResponse:
|
||||
@@ -561,6 +607,31 @@ def preview_tts(
|
||||
用于前端预览配音效果,限制文本长度 200 字以内。
|
||||
支持预设音色和克隆音色:克隆音色传的是 profile UUID,需解析为 CosyVoice voice_id。
|
||||
"""
|
||||
user_id = authenticated_user.user.id
|
||||
# ── 积分扣点(#1895 P2) ──
|
||||
_points_deducted = 0
|
||||
_points_scene = "ai_voice"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
if _points_svc is not None:
|
||||
est_minutes = max(1.0, math.ceil(len(request.text) / 240))
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(authenticated_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(authenticated_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
|
||||
# 解析 voice_id:前端可能传 VoiceCloneProfile UUID 或预设音色 ID
|
||||
actual_voice_id = request.voice_id
|
||||
profile = voice_clone_repo.get(request.voice_id)
|
||||
@@ -586,16 +657,16 @@ def preview_tts(
|
||||
emotion=request.emotion,
|
||||
language=getattr(request, "language", "zh-CN"),
|
||||
)
|
||||
except CosyVoiceError as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"TTS 合成失败: {e}",
|
||||
) from e
|
||||
except ValueError as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=str(e),
|
||||
) from e
|
||||
except (CosyVoiceError, ValueError) as e:
|
||||
# 合成失败退费
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"TTS 预览失败退积分异常: {refund_err}")
|
||||
if isinstance(e, CosyVoiceError):
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"TTS 合成失败: {e}") from e
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e
|
||||
|
||||
return TTSPreviewResponse(
|
||||
audio_url=result.audio_url,
|
||||
|
||||
@@ -3,14 +3,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
from typing import Optional
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.config import settings
|
||||
from app.core.celery_app import celery_app
|
||||
from app.core.storage import get_storage_service
|
||||
from app.dependencies import (
|
||||
get_asset_repository,
|
||||
get_cosyvoice_service,
|
||||
get_db_session,
|
||||
get_project_repository,
|
||||
get_voice_clone_profile_repository,
|
||||
)
|
||||
@@ -22,6 +25,7 @@ from app.schemas.voice_clone import (
|
||||
VoiceCloneStatusResponse,
|
||||
)
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.adapters.sqlalchemy_impl.voice_clone_profile_repository import (
|
||||
SQLAlchemyVoiceCloneProfileRepository,
|
||||
@@ -38,6 +42,11 @@ from packages.application.voice_clone.use_cases import (
|
||||
from packages.application.voice_clone.workflow import (
|
||||
VoiceCloneWorkflowService,
|
||||
)
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
from packages.domain.points_service import PointsService
|
||||
|
||||
# remove duplicate
|
||||
_DUMMY_DELETED = ()
|
||||
from packages.ports.asset_repository import AssetRepository
|
||||
from packages.ports.project_repository import ProjectRepository
|
||||
from packages.shared.storage import SharedStorageService
|
||||
@@ -287,7 +296,46 @@ def retry_voice_clone(
|
||||
return _to_response(profile)
|
||||
|
||||
|
||||
_ALLOWED_PREVIEW_EMOTIONS = {"", "natural", "excited", "calm", "friendly"}
|
||||
_ALLOWED_PREVIEW_EMOTIONS = {
|
||||
"",
|
||||
# 7 种标准英文枚举(CosyVoice v3 官方值)
|
||||
"neutral",
|
||||
"happy",
|
||||
"sad",
|
||||
"angry",
|
||||
"surprised",
|
||||
"fearful",
|
||||
"disgusted",
|
||||
# 前端中文 7 标签
|
||||
"中立",
|
||||
"开心",
|
||||
"难过",
|
||||
"生气",
|
||||
"惊讶",
|
||||
"恐惧",
|
||||
"厌恶",
|
||||
# 旧英文 4 枚举 + 常见中文别名兼容
|
||||
"natural",
|
||||
"excited",
|
||||
"calm",
|
||||
"friendly",
|
||||
"自然",
|
||||
"愉快",
|
||||
"高兴",
|
||||
"快乐",
|
||||
"兴奋",
|
||||
"悲伤",
|
||||
"愤怒",
|
||||
"惊奇",
|
||||
"吃惊",
|
||||
"害怕",
|
||||
"讨厌",
|
||||
# 灵应 P1 指定别名
|
||||
"中性",
|
||||
"伤心",
|
||||
"沉稳",
|
||||
"亲切",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{clone_id}/preview", response_model=VoiceClonePreviewResponse)
|
||||
@@ -295,8 +343,12 @@ def get_voice_clone_preview(
|
||||
clone_id: str,
|
||||
text: str = Query("", description="自定义试听文本,为空则使用默认示例"),
|
||||
speed: float = Query(1.0, ge=0.5, le=2.0, description="语速,0.5-2.0,默认 1.0"),
|
||||
emotion: str = Query("", description="情绪:natural/excited/calm/friendly,空字符串为默认自然"),
|
||||
emotion: str = Query(
|
||||
"",
|
||||
description="情绪:neutral/happy/sad/angry/surprised/fearful/disgusted,兼容旧值 natural/excited/calm/friendly,空为默认自然",
|
||||
),
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
repository: SQLAlchemyVoiceCloneProfileRepository = Depends(get_voice_clone_profile_repository),
|
||||
cosyvoice: CosyVoiceService = Depends(get_cosyvoice_service),
|
||||
) -> VoiceClonePreviewResponse:
|
||||
@@ -308,10 +360,35 @@ def get_voice_clone_preview(
|
||||
"""
|
||||
import time
|
||||
|
||||
user_id = authenticated_user.user.id
|
||||
_points_deducted = 0
|
||||
_points_scene = "voice_clone_synth"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
_preview_text_for_points = text.strip() or CLONE_PREVIEW_TEMPLATE
|
||||
if _points_svc is not None:
|
||||
est_minutes = max(1.0, math.ceil(len(_preview_text_for_points) / 240))
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(authenticated_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(authenticated_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
|
||||
if emotion not in _ALLOWED_PREVIEW_EMOTIONS:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"不支持的 emotion 值: {emotion},可选: natural/excited/calm/friendly 或留空",
|
||||
detail=f"不支持的 emotion 值: {emotion},可选: neutral/happy/sad/angry/surprised/fearful/disgusted 或中文 中立/中性/开心/难过/伤心/生气/愤怒/惊讶/吃惊/恐惧/害怕/厌恶/讨厌 或留空",
|
||||
)
|
||||
|
||||
use_case = GetVoiceCloneUseCase(repository)
|
||||
@@ -351,9 +428,14 @@ def get_voice_clone_preview(
|
||||
speed=speed,
|
||||
emotion=emotion,
|
||||
)
|
||||
except CosyVoiceError as e:
|
||||
raise HTTPException(status_code=502, detail=f"TTS 合成失败: {e}") from e
|
||||
except ValueError as e:
|
||||
except (CosyVoiceError, ValueError) as e:
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"克隆音色试听失败退积分异常: clone_id={clone_id}, err={refund_err}")
|
||||
if isinstance(e, CosyVoiceError):
|
||||
raise HTTPException(status_code=502, detail=f"TTS 合成失败: {e}") from e
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e
|
||||
|
||||
# 缓存(仅默认参数组合)
|
||||
|
||||
@@ -6,7 +6,7 @@ ensuring proper lifecycle management and testability.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Generator
|
||||
from collections.abc import Generator
|
||||
|
||||
import redis
|
||||
from app.config import settings
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Callable
|
||||
from collections.abc import Callable
|
||||
|
||||
from fastapi import Request
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
@@ -10,7 +10,7 @@ Exposes:
|
||||
|
||||
import re
|
||||
import time
|
||||
from typing import Callable
|
||||
from collections.abc import Callable
|
||||
|
||||
from fastapi import Request, Response
|
||||
from prometheus_client import (
|
||||
|
||||
@@ -67,7 +67,10 @@ class CreateLipsyncJobRequest(BaseModel):
|
||||
voice_id: str = Field("", description="音色 ID(预置音色或克隆音色 profile UUID)")
|
||||
script_text: str = Field("", description="要合成的文案(直生模式必填,最长 5000 字符)")
|
||||
speed: float = Field(1.0, ge=0.5, le=2.0, description="语速(0.5-2.0),默认 1.0")
|
||||
emotion: str = Field("", description="情绪(中文/英文:自然/兴奋/沉稳/亲切/开心/悲伤/愤怒/惊讶/恐惧/厌恶 等)")
|
||||
emotion: str = Field(
|
||||
"",
|
||||
description="情绪(英文枚举 neutral/happy/sad/angry/surprised/fearful/disgusted,或中文 中立/开心/难过/生气/惊讶/恐惧/厌恶;空为默认自然)",
|
||||
)
|
||||
|
||||
enable_video_loop: bool = Field(
|
||||
True, description="音频长于视频时是否循环画面(AI数字人默认开启,防止音频长于视频被截断)"
|
||||
@@ -120,7 +123,11 @@ class AiAvatarTtsPreviewRequest(BaseModel):
|
||||
voice_id: str = Field(..., min_length=1, max_length=128, description="音色 ID")
|
||||
script_text: str = Field(..., min_length=1, max_length=5000, description="要合成的文案")
|
||||
speed: float = Field(1.0, ge=0.5, le=2.0, description="语速(0.5-2.0),默认 1.0")
|
||||
emotion: str = Field("natural", max_length=32, description="情绪")
|
||||
emotion: str = Field(
|
||||
"neutral",
|
||||
max_length=32,
|
||||
description="情绪(英文枚举 neutral/happy/sad/angry/surprised/fearful/disgusted,或中文 中立/开心/难过/生气/惊讶/恐惧/厌恶;默认 neutral)",
|
||||
)
|
||||
|
||||
|
||||
class AiAvatarTtsPreviewResponse(BaseModel):
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""积分 & 会员相关 Pydantic Schema (#1895)"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# ============ 余额 & 账户 ============
|
||||
|
||||
|
||||
class PointsBalanceResponse(BaseModel):
|
||||
"""积分余额 + 会员状态"""
|
||||
|
||||
balance: int = Field(..., description="当前积分余额")
|
||||
total_earned: int = Field(..., description="累计获得积分")
|
||||
total_spent: int = Field(..., description="累计消耗积分")
|
||||
is_member: bool = Field(default=False, description="是否付费会员")
|
||||
member_type: Optional[str] = Field(None, description="会员类型: monthly/quarterly/yearly")
|
||||
member_expires_at: Optional[datetime] = Field(None, description="会员到期时间")
|
||||
|
||||
|
||||
# ============ 流水 ============
|
||||
|
||||
|
||||
class PointsTransactionItem(BaseModel):
|
||||
"""单条积分流水"""
|
||||
|
||||
id: str
|
||||
type: str = Field(..., description="类型: add/deduct")
|
||||
source: str = Field(..., description="来源场景")
|
||||
amount: int
|
||||
balance_after: int
|
||||
description: str = ""
|
||||
ref_id: str = ""
|
||||
created_at: Optional[str] = None
|
||||
|
||||
|
||||
class PointsTransactionsResponse(BaseModel):
|
||||
"""积分流水分页响应"""
|
||||
|
||||
items: list[PointsTransactionItem]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
# ============ 规则 & 积分包 ============
|
||||
|
||||
|
||||
class PointRuleItem(BaseModel):
|
||||
"""单条积分规则"""
|
||||
|
||||
scene_key: str
|
||||
name: str
|
||||
base_points: int
|
||||
unit: str
|
||||
extra_per_30s: Optional[int] = None
|
||||
description: str = Field(default="", description="规则中文说明,例如 AI 配音每分钟消耗 X 积分")
|
||||
|
||||
|
||||
class PointsRulesResponse(BaseModel):
|
||||
"""所有积分消耗规则"""
|
||||
|
||||
rules: list[PointRuleItem]
|
||||
free_user_multiplier: float = Field(..., description="免费用户积分上浮系数")
|
||||
|
||||
|
||||
class PointsPackageItem(BaseModel):
|
||||
"""积分包信息"""
|
||||
|
||||
code: str
|
||||
name: str
|
||||
points: int
|
||||
price_cents: int
|
||||
unit_price: str = Field("", description="单价描述,如 ¥0.099/积分")
|
||||
|
||||
|
||||
class PointsPackagesResponse(BaseModel):
|
||||
"""可购买的积分包列表"""
|
||||
|
||||
packages: list[PointsPackageItem]
|
||||
user_discount: Optional[float] = Field(None, description="当前用户折扣(会员)")
|
||||
|
||||
|
||||
# ============ 消费前检查 ============
|
||||
|
||||
|
||||
class PointsCheckRequest(BaseModel):
|
||||
"""消费前余额检查请求"""
|
||||
|
||||
scene_key: str
|
||||
duration_minutes: Optional[float] = None
|
||||
quantity: Optional[int] = 1
|
||||
|
||||
|
||||
class PointsCheckResponse(BaseModel):
|
||||
"""消费前余额检查响应"""
|
||||
|
||||
allowed: bool
|
||||
required_points: int
|
||||
current_balance: int
|
||||
remaining_after: int
|
||||
is_free_quota: bool = False
|
||||
|
||||
|
||||
# ============ 手动扣减 / 退还(内部接口) ============
|
||||
|
||||
|
||||
class PointsDeductRequest(BaseModel):
|
||||
"""积分扣减请求"""
|
||||
|
||||
scene_key: str
|
||||
amount: int
|
||||
description: Optional[str] = ""
|
||||
ref_id: Optional[str] = ""
|
||||
|
||||
|
||||
class PointsRefundRequest(BaseModel):
|
||||
"""积分退还请求"""
|
||||
|
||||
transaction_id: str
|
||||
reason: Optional[str] = ""
|
||||
|
||||
|
||||
class PointsRechargeRequest(BaseModel):
|
||||
"""积分充值请求"""
|
||||
|
||||
package_id: str = Field(..., description="积分包 code,如 starter_pack")
|
||||
|
||||
|
||||
# ============ 订单 ============
|
||||
|
||||
|
||||
class PointsOrderResponse(BaseModel):
|
||||
"""订单信息"""
|
||||
|
||||
id: str
|
||||
order_type: str
|
||||
product_code: str
|
||||
amount_cents: int
|
||||
points_amount: int = Field(0, description="本次充值/购买可获得的积分(仅 points 类型订单有意义)")
|
||||
status: str
|
||||
pay_params: dict[str, Any] = Field(
|
||||
default_factory=dict, description="拉起支付所需参数(payment_url/prepay_id 等),支付通道接入后填充"
|
||||
)
|
||||
expire_at: Optional[str] = Field(None, description="订单过期时间(ISO 8601),默认创建后 48 小时")
|
||||
created_at: Optional[str] = None
|
||||
|
||||
|
||||
# ============ 每日额度 ============
|
||||
|
||||
|
||||
class DailyUsageResponse(BaseModel):
|
||||
"""今日免费额度使用情况"""
|
||||
|
||||
free_clips_used: int
|
||||
free_clips_limit: int
|
||||
free_clips_remaining: int
|
||||
reset_at: str
|
||||
|
||||
|
||||
# ============ 会员状态(聚合) ============
|
||||
|
||||
|
||||
class MembershipStatusResponse(BaseModel):
|
||||
"""当前用户会员状态(聚合信息)"""
|
||||
|
||||
is_member: bool
|
||||
member_type: Optional[str] = None
|
||||
member_expires_at: Optional[datetime] = None
|
||||
points_balance: int
|
||||
max_resolution: str = Field(
|
||||
default="1080p",
|
||||
description="可用最高分辨率: 720p(free) / 1080p(paid)",
|
||||
)
|
||||
|
||||
|
||||
# ============ 订阅档位 ============
|
||||
|
||||
|
||||
class MembershipPlanItem(BaseModel):
|
||||
"""单个会员档位"""
|
||||
|
||||
plan_id: str = Field(..., description="档位标识: monthly/quarterly/yearly")
|
||||
name: str = Field(..., description="档位名称,例如 月卡")
|
||||
monthly_price_cents: int = Field(..., description="折算月价(分)")
|
||||
price_cents: int = Field(..., description="该档位总价(分)")
|
||||
duration_days: int = Field(..., description="时长(天)")
|
||||
points_discount: float = Field(..., description="该档位积分折扣,如 0.9 表示 9 折")
|
||||
features: dict[str, Any] = Field(default_factory=dict, description="档位权益(max_resolution 等)")
|
||||
|
||||
|
||||
class MembershipPlansResponse(BaseModel):
|
||||
"""所有会员档位列表"""
|
||||
|
||||
plans: list[MembershipPlanItem]
|
||||
|
||||
|
||||
# ============ 通用响应 ============
|
||||
|
||||
|
||||
class SimpleMessageResponse(BaseModel):
|
||||
"""简单消息响应"""
|
||||
|
||||
success: bool
|
||||
message: str
|
||||
data: Optional[dict[str, Any]] = None
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -20,8 +20,11 @@ class ScriptResponse(BaseModel):
|
||||
user_id: str
|
||||
title: str
|
||||
content: str
|
||||
segments: List[ScriptSegment] = Field(default_factory=list)
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
segments: list[ScriptSegment] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
title_text: str = ""
|
||||
title_category: str = ""
|
||||
title_config: Dict[str, Any] = Field(default_factory=dict)
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@@ -34,12 +37,18 @@ class ScriptListResponse(BaseModel):
|
||||
class CreateScriptRequest(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=255)
|
||||
content: str = ""
|
||||
segments: List[ScriptSegment] = Field(default_factory=list)
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
segments: list[ScriptSegment] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
title_text: str = ""
|
||||
title_category: str = ""
|
||||
title_config: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class UpdateScriptRequest(BaseModel):
|
||||
title: Optional[str] = Field(None, min_length=1, max_length=255)
|
||||
content: Optional[str] = None
|
||||
segments: Optional[List[ScriptSegment]] = None
|
||||
tags: Optional[List[str]] = None
|
||||
segments: Optional[list[ScriptSegment]] = None
|
||||
tags: Optional[list[str]] = None
|
||||
title_text: Optional[str] = None
|
||||
title_category: Optional[str] = None
|
||||
title_config: Optional[Dict[str, Any]] = None
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Scripts AI 能力 Pydantic schemas — Issue #1893.
|
||||
|
||||
抖音文案提取、AI 改写、AI 标题生成的请求/响应模型。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# ── 抖音文案提取 ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class ExtractFromDouyinRequest(BaseModel):
|
||||
"""从抖音视频提取文案请求."""
|
||||
|
||||
url: str = Field(..., description="抖音视频链接(短链或长链)")
|
||||
|
||||
|
||||
class ExtractFromDouyinResponse(BaseModel):
|
||||
"""从抖音视频提取文案响应."""
|
||||
|
||||
text: str = Field(..., description="ASR 识别出的文案文本")
|
||||
duration_seconds: float = Field(..., description="视频时长(秒)")
|
||||
source_url: str = Field(..., description="原始视频链接")
|
||||
|
||||
|
||||
# ── AI 改写 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class AiRewriteRequest(BaseModel):
|
||||
"""AI 文案改写请求."""
|
||||
|
||||
content: str = Field(..., description="原文内容")
|
||||
style: Optional[str] = Field("口语化", description="改写风格,如 口语化/正式/活泼")
|
||||
|
||||
|
||||
class AiRewriteResponse(BaseModel):
|
||||
"""AI 文案改写响应."""
|
||||
|
||||
original: str = Field(..., description="原文")
|
||||
rewritten: str = Field(..., description="改写后的文案")
|
||||
style: str = Field(..., description="使用的改写风格")
|
||||
|
||||
|
||||
# ── AI 标题生成 ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class AiGenerateTitlesRequest(BaseModel):
|
||||
"""AI 标题生成请求."""
|
||||
|
||||
content: str = Field(..., description="文案内容")
|
||||
count: int = Field(3, ge=1, le=5, description="生成标题数量(1-5,默认3)")
|
||||
|
||||
|
||||
class AiGenerateTitlesResponse(BaseModel):
|
||||
"""AI 标题生成响应."""
|
||||
|
||||
titles: List[str] = Field(..., description="生成的标题列表")
|
||||
@@ -8,7 +8,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -42,12 +42,12 @@ class TemplateResponse(BaseModel):
|
||||
name: str
|
||||
mode: str
|
||||
category: str = ""
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
title_config: Dict[str, Any] = Field(default_factory=dict)
|
||||
subtitle_config: Dict[str, Any] = Field(default_factory=dict)
|
||||
bgm_config: Dict[str, Any] = Field(default_factory=dict)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
title_config: dict[str, Any] = Field(default_factory=dict)
|
||||
subtitle_config: dict[str, Any] = Field(default_factory=dict)
|
||||
bgm_config: dict[str, Any] = Field(default_factory=dict)
|
||||
estimated_duration: float = 0.0
|
||||
segments: List[SegmentResponse] = Field(default_factory=list)
|
||||
segments: list[SegmentResponse] = Field(default_factory=list)
|
||||
is_active: bool = True
|
||||
is_favorite: bool = False
|
||||
usage_count: int = 0
|
||||
@@ -56,7 +56,7 @@ class TemplateResponse(BaseModel):
|
||||
|
||||
|
||||
class ListTemplatesResponse(BaseModel):
|
||||
items: List[TemplateResponse]
|
||||
items: list[TemplateResponse]
|
||||
total: int = 0
|
||||
|
||||
|
||||
@@ -67,12 +67,12 @@ class CreateTemplateRequest(BaseModel):
|
||||
name: str
|
||||
mode: str
|
||||
category: str = ""
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
title_config: Dict[str, Any] = Field(default_factory=dict)
|
||||
subtitle_config: Dict[str, Any] = Field(default_factory=dict)
|
||||
bgm_config: Dict[str, Any] = Field(default_factory=dict)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
title_config: dict[str, Any] = Field(default_factory=dict)
|
||||
subtitle_config: dict[str, Any] = Field(default_factory=dict)
|
||||
bgm_config: dict[str, Any] = Field(default_factory=dict)
|
||||
estimated_duration: float = 0.0
|
||||
segments: List[SegmentRequest] = Field(default_factory=list)
|
||||
segments: list[SegmentRequest] = Field(default_factory=list)
|
||||
|
||||
|
||||
class GenerateWarningResponse(BaseModel):
|
||||
@@ -80,4 +80,4 @@ class GenerateWarningResponse(BaseModel):
|
||||
|
||||
code: str
|
||||
message: str
|
||||
details: Dict[str, Any] = Field(default_factory=dict)
|
||||
details: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -15,7 +15,7 @@ class TitleLibraryItemResponse(BaseModel):
|
||||
text: str
|
||||
category: str = "default"
|
||||
description: str = ""
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
usage_count: int = 0
|
||||
is_active: bool = True
|
||||
created_at: datetime
|
||||
@@ -32,7 +32,7 @@ class CreateTitleLibraryRequest(BaseModel):
|
||||
text: str = Field(..., min_length=1, max_length=500)
|
||||
category: str = "default"
|
||||
description: str = ""
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class UpdateTitleLibraryRequest(BaseModel):
|
||||
@@ -40,4 +40,4 @@ class UpdateTitleLibraryRequest(BaseModel):
|
||||
text: Optional[str] = Field(None, min_length=1, max_length=500)
|
||||
category: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
tags: Optional[List[str]] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -23,7 +23,7 @@ class TTSSynthesizeRequest(BaseModel):
|
||||
voice_model: str = Field("", description="语音模型名称")
|
||||
voice_clone_profile_id: str = Field("", description="关联的音色克隆档案 ID")
|
||||
format: str = Field("mp3", description="输出格式(mp3/wav/pcm)")
|
||||
metadata_: Optional[Dict[str, Any]] = Field(default=None, alias="metadata", description="额外元数据")
|
||||
metadata_: Optional[dict[str, Any]] = Field(default=None, alias="metadata", description="额外元数据")
|
||||
|
||||
class Config:
|
||||
populate_by_name = True
|
||||
@@ -49,7 +49,7 @@ class TTSJobResponse(BaseModel):
|
||||
error_message: str = ""
|
||||
retry_count: int = 0
|
||||
max_retries: int = 3
|
||||
metadata_: Optional[Dict[str, Any]] = Field(default=None, alias="metadata", description="额外元数据")
|
||||
metadata_: Optional[dict[str, Any]] = Field(default=None, alias="metadata", description="额外元数据")
|
||||
started_at: Optional[datetime] = None
|
||||
completed_at: Optional[datetime] = None
|
||||
created_at: datetime
|
||||
@@ -83,7 +83,7 @@ class TTSSynthesizeResponse(BaseModel):
|
||||
class ListTTSJobResponse(BaseModel):
|
||||
"""TTS 任务列表响应。"""
|
||||
|
||||
items: List[TTSJobResponse]
|
||||
items: list[TTSJobResponse]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -61,7 +61,7 @@ class ShareResponse(BaseModel):
|
||||
class ShareListResponse(BaseModel):
|
||||
"""分享列表响应."""
|
||||
|
||||
items: List[ShareResponse]
|
||||
items: list[ShareResponse]
|
||||
total: int = 0
|
||||
skip: int = 0
|
||||
limit: int = 20
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Literal, Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -56,7 +56,7 @@ class UnifiedVoiceItemResponse(BaseModel):
|
||||
status: str = "completed"
|
||||
"""状态"""
|
||||
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
"""标签列表"""
|
||||
|
||||
# 克隆音色特有字段
|
||||
@@ -113,7 +113,7 @@ class PresetVoiceItemResponse(BaseModel):
|
||||
preview_url: str = ""
|
||||
"""预览音频 URL"""
|
||||
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
"""标签列表"""
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -19,7 +19,7 @@ class CreateVoiceCloneRequest(BaseModel):
|
||||
language: str = Field("zh-CN", description="语言")
|
||||
gender: str = Field("unknown", description="性别")
|
||||
max_retries: int = Field(3, ge=1, le=10, description="最大重试次数")
|
||||
metadata_: Optional[Dict[str, Any]] = Field(default=None, alias="metadata", description="额外元数据")
|
||||
metadata_: Optional[dict[str, Any]] = Field(default=None, alias="metadata", description="额外元数据")
|
||||
|
||||
class Config:
|
||||
populate_by_name = True
|
||||
@@ -41,7 +41,7 @@ class VoiceCloneProfileResponse(BaseModel):
|
||||
error_message: str = ""
|
||||
retry_count: int = 0
|
||||
max_retries: int = 3
|
||||
metadata_: Optional[Dict[str, Any]] = Field(default=None, alias="metadata", description="额外元数据")
|
||||
metadata_: Optional[dict[str, Any]] = Field(default=None, alias="metadata", description="额外元数据")
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@@ -62,7 +62,7 @@ class VoiceCloneStatusResponse(BaseModel):
|
||||
class ListVoiceCloneResponse(BaseModel):
|
||||
"""音色克隆列表响应。"""
|
||||
|
||||
items: List[VoiceCloneProfileResponse]
|
||||
items: list[VoiceCloneProfileResponse]
|
||||
total: int
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -21,7 +21,7 @@ class VoiceLibraryItemResponse(BaseModel):
|
||||
file_size: int = 0
|
||||
status: str = "completed"
|
||||
project_id: Optional[str] = None
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@@ -42,7 +42,7 @@ class CreateVoiceLibraryRequest(BaseModel):
|
||||
file_size: int = 0
|
||||
status: str = "completed"
|
||||
project_id: Optional[str] = None
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class UpdateVoiceLibraryRequest(BaseModel):
|
||||
@@ -55,4 +55,4 @@ class UpdateVoiceLibraryRequest(BaseModel):
|
||||
duration: Optional[float] = None
|
||||
file_size: Optional[int] = None
|
||||
status: Optional[str] = None
|
||||
tags: Optional[List[str]] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
@@ -16,7 +16,7 @@ import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -117,7 +117,7 @@ class AiAvatarRenderService:
|
||||
self.db.add(job)
|
||||
self.db.flush()
|
||||
|
||||
job.submitted_at = datetime.now(timezone.utc)
|
||||
job.submitted_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
self.db.refresh(job)
|
||||
return job
|
||||
@@ -164,7 +164,7 @@ class AiAvatarRenderService:
|
||||
return None
|
||||
if job.status in ("pending", "submitted"):
|
||||
job.status = "cancelled"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
self.db.refresh(job)
|
||||
return job
|
||||
@@ -186,7 +186,7 @@ class AiAvatarRenderService:
|
||||
job.output_duration = 0.0
|
||||
job.started_at = None
|
||||
job.completed_at = None
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
self.db.refresh(job)
|
||||
return job
|
||||
@@ -215,9 +215,9 @@ class AiAvatarRenderService:
|
||||
try:
|
||||
# 更新状态为 processing
|
||||
job.status = "processing"
|
||||
job.started_at = datetime.now(timezone.utc)
|
||||
job.started_at = datetime.now(UTC)
|
||||
job.progress = 5
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
|
||||
# 获取对口型任务信息
|
||||
@@ -394,8 +394,8 @@ class AiAvatarRenderService:
|
||||
# 6. 完成
|
||||
job.status = "completed"
|
||||
job.progress = 100
|
||||
job.completed_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.completed_at = datetime.now(UTC)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
logger.info("渲染任务完成: %s", job_id)
|
||||
|
||||
@@ -406,14 +406,14 @@ class AiAvatarRenderService:
|
||||
except AiAvatarRenderError as exc:
|
||||
job.status = "failed"
|
||||
job.error_message = str(exc)
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
logger.error("渲染任务失败 [%s]: %s", job_id, exc)
|
||||
raise
|
||||
except Exception as exc:
|
||||
job.status = "failed"
|
||||
job.error_message = f"渲染异常: {str(exc)}"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
logger.exception("渲染任务异常 [%s]", job_id)
|
||||
raise
|
||||
@@ -494,7 +494,7 @@ class AiAvatarRenderService:
|
||||
# 同步更新 cover_config,保持 smart-cover 路径一致
|
||||
if isinstance(job.cover_config, dict):
|
||||
job.cover_config = {**job.cover_config, "mode": "auto_frame", "url": cover_url.strip()}
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
|
||||
return self._persist_to_library(job, cover_url=cover_url)
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
from packages.domain.ai_parsing import generate_titles_fallback as _generate_titles_fallback_base
|
||||
from packages.domain.ai_parsing import keyword_match_fallback as _semantic_match_fallback_base
|
||||
@@ -64,7 +64,7 @@ def _generate_titles_fallback(
|
||||
description: str,
|
||||
style: str = "viral",
|
||||
count: int = 5,
|
||||
) -> List[str]:
|
||||
) -> list[str]:
|
||||
"""本地降级:基于模板规则生成标题(薄包装,转发到 ai_parsing 模块)."""
|
||||
style_info = TITLE_STYLES.get(style, TITLE_STYLES["viral"])
|
||||
return _generate_titles_fallback_base(description, style_info, count)
|
||||
@@ -74,7 +74,7 @@ def generate_smart_titles(
|
||||
description: str,
|
||||
style: str = "viral",
|
||||
count: int = 5,
|
||||
) -> Dict[str, Any]:
|
||||
) -> dict[str, Any]:
|
||||
"""生成智能标题.
|
||||
|
||||
Args:
|
||||
@@ -164,16 +164,16 @@ def generate_smart_titles(
|
||||
|
||||
def _semantic_match_fallback(
|
||||
description: str,
|
||||
assets: List[Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
assets: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""本地降级:基于关键词的简单匹配(薄包装,转发到 ai_parsing 模块)."""
|
||||
return _semantic_match_fallback_base(description, assets)
|
||||
|
||||
|
||||
def _parse_semantic_match_response(
|
||||
content: str,
|
||||
asset_ids: List[str],
|
||||
) -> Optional[Dict[str, float]]:
|
||||
asset_ids: list[str],
|
||||
) -> Optional[dict[str, float]]:
|
||||
"""从模型返回中解析素材匹配度(薄包装,转发到 ai_parsing 模块)."""
|
||||
result = _parse_semantic_match_base(content, asset_ids)
|
||||
if result is None:
|
||||
@@ -183,9 +183,9 @@ def _parse_semantic_match_response(
|
||||
|
||||
def semantic_match_assets(
|
||||
description: str,
|
||||
assets: List[Dict[str, Any]],
|
||||
assets: list[dict[str, Any]],
|
||||
top_k: int = 0,
|
||||
) -> Dict[str, Any]:
|
||||
) -> dict[str, Any]:
|
||||
"""智能素材语义匹配.
|
||||
|
||||
根据用户描述,评估每个素材的语义匹配度并排序。
|
||||
@@ -336,13 +336,13 @@ class AIService:
|
||||
description: str,
|
||||
style: str = "viral",
|
||||
count: int = 5,
|
||||
) -> Dict[str, Any]:
|
||||
) -> dict[str, Any]:
|
||||
return generate_smart_titles(description, style, count)
|
||||
|
||||
def semantic_match(
|
||||
self,
|
||||
description: str,
|
||||
assets: List[Dict[str, Any]],
|
||||
assets: list[dict[str, Any]],
|
||||
top_k: int = 0,
|
||||
) -> Dict[str, Any]:
|
||||
) -> dict[str, Any]:
|
||||
return semantic_match_assets(description, assets, top_k)
|
||||
|
||||
@@ -28,8 +28,8 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Callable
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -57,7 +57,7 @@ _REUSE_OVERLAP_RATIO = 0.6
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
return datetime.now(UTC).isoformat()
|
||||
|
||||
|
||||
def _read_meta(model) -> dict:
|
||||
@@ -156,7 +156,7 @@ def record_used_segments(
|
||||
r["plan_id"] = plan_id
|
||||
meta[USED_RANGES_KEY] = ranges
|
||||
model.classification_result = json.dumps(meta, ensure_ascii=False)
|
||||
model.updated_at = datetime.now(timezone.utc)
|
||||
model.updated_at = datetime.now(UTC)
|
||||
return
|
||||
|
||||
ranges.append(
|
||||
@@ -171,7 +171,7 @@ def record_used_segments(
|
||||
)
|
||||
meta[USED_RANGES_KEY] = ranges
|
||||
model.classification_result = json.dumps(meta, ensure_ascii=False)
|
||||
model.updated_at = datetime.now(timezone.utc)
|
||||
model.updated_at = datetime.now(UTC)
|
||||
|
||||
|
||||
def remove_used_segment(
|
||||
@@ -215,7 +215,7 @@ def remove_used_segment(
|
||||
if removed:
|
||||
meta[USED_RANGES_KEY] = remaining
|
||||
model.classification_result = json.dumps(meta, ensure_ascii=False)
|
||||
model.updated_at = datetime.now(timezone.utc)
|
||||
model.updated_at = datetime.now(UTC)
|
||||
return removed
|
||||
|
||||
|
||||
@@ -231,7 +231,7 @@ def reset_used_segments(db: Session, asset_id: str) -> None:
|
||||
if meta.get(USED_RANGES_KEY):
|
||||
meta[USED_RANGES_KEY] = []
|
||||
model.classification_result = json.dumps(meta, ensure_ascii=False)
|
||||
model.updated_at = datetime.now(timezone.utc)
|
||||
model.updated_at = datetime.now(UTC)
|
||||
logger.info("[片段追踪] 素材区间记录手动清空: asset_id=%s", asset_id)
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.services.asset_segment_tracker import (
|
||||
REUSE_RATIO_LIMIT,
|
||||
@@ -206,7 +206,7 @@ class EditPlanService:
|
||||
status: Optional[EditPlanClipStatus] = None,
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
) -> List[EditPlanClip]:
|
||||
) -> list[EditPlanClip]:
|
||||
"""列出计划的片段"""
|
||||
# 确保计划存在
|
||||
self.get_plan_or_raise(plan_id)
|
||||
@@ -503,7 +503,7 @@ class EditPlanService:
|
||||
source = self.get_plan_or_raise(source_plan_id)
|
||||
|
||||
# 分页读取源 plan 全部片段
|
||||
clips: List[EditPlanClip] = []
|
||||
clips: list[EditPlanClip] = []
|
||||
skip, page = 0, 500
|
||||
while True:
|
||||
batch = self._clip_repo.list_by_plan(source_plan_id, skip=skip, limit=page)
|
||||
@@ -665,7 +665,7 @@ class EditPlanService:
|
||||
source = self.get_plan_or_raise(source_plan_id)
|
||||
|
||||
# 分页读取源 plan 全部片段
|
||||
clips: List[EditPlanClip] = []
|
||||
clips: list[EditPlanClip] = []
|
||||
skip, page = 0, 500
|
||||
while True:
|
||||
batch = self._clip_repo.list_by_plan(source_plan_id, skip=skip, limit=page)
|
||||
@@ -797,7 +797,7 @@ class EditPlanService:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
clips: List[EditPlanClip] = []
|
||||
clips: list[EditPlanClip] = []
|
||||
skip, page = 0, 500
|
||||
while True:
|
||||
batch = self._clip_repo.list_by_plan(plan_id, skip=skip, limit=page)
|
||||
@@ -1063,7 +1063,7 @@ class EditPlanService:
|
||||
|
||||
# ── 片段分割与合并 ──────────────────────────────────────────────────────
|
||||
|
||||
def split_clip(self, clip_id: str, split_time: float) -> Dict[str, Any]:
|
||||
def split_clip(self, clip_id: str, split_time: float) -> dict[str, Any]:
|
||||
"""将一个片段从指定位置分割为两个片段
|
||||
|
||||
Args:
|
||||
@@ -1151,7 +1151,7 @@ class EditPlanService:
|
||||
"right_clip": created_right,
|
||||
}
|
||||
|
||||
def merge_clips(self, clip_ids: List[str]) -> EditPlanClip:
|
||||
def merge_clips(self, clip_ids: list[str]) -> EditPlanClip:
|
||||
"""合并多个连续片段为一个片段
|
||||
|
||||
Args:
|
||||
@@ -1217,7 +1217,7 @@ class EditPlanService:
|
||||
|
||||
# ── 渲染生成流程 ────────────────────────────────────────────────────────
|
||||
|
||||
def get_generation_status(self, plan_id: str) -> Dict[str, Any]:
|
||||
def get_generation_status(self, plan_id: str) -> dict[str, Any]:
|
||||
"""获取渲染进度状态
|
||||
|
||||
Returns:
|
||||
@@ -1364,7 +1364,7 @@ class EditPlanService:
|
||||
)
|
||||
return count
|
||||
|
||||
def update_plan_config(self, plan_id: str, config_updates: Dict[str, Any]) -> EditPlan:
|
||||
def update_plan_config(self, plan_id: str, config_updates: dict[str, Any]) -> EditPlan:
|
||||
"""更新计划配置(合并更新)
|
||||
|
||||
Args:
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, List, Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -76,7 +76,7 @@ class EditTemplateService:
|
||||
active_only: bool = False,
|
||||
skip: int = 0,
|
||||
limit: int = 50,
|
||||
) -> List[EditTemplate]:
|
||||
) -> list[EditTemplate]:
|
||||
"""列出模板
|
||||
|
||||
Args:
|
||||
@@ -227,7 +227,7 @@ class EditTemplateService:
|
||||
clip_type: Optional[ClipType] = None,
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
) -> List[TemplateClipConfig]:
|
||||
) -> list[TemplateClipConfig]:
|
||||
"""列出模板的片段配置
|
||||
|
||||
注意:本方法要求模板存在于新表 ``edit_templates``(全局模板库),
|
||||
@@ -253,7 +253,7 @@ class EditTemplateService:
|
||||
clip_type: Optional[ClipType] = None,
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
) -> List[TemplateClipConfig]:
|
||||
) -> list[TemplateClipConfig]:
|
||||
"""编辑器读取模板片段配置的单一数据源入口.
|
||||
|
||||
片段配置主表是 ``template_clip_configs``(直接读取,不抛异常、不降级)。
|
||||
@@ -404,8 +404,8 @@ class EditTemplateService:
|
||||
def reorder_clip_configs(
|
||||
self,
|
||||
template_id: str,
|
||||
config_ids: List[str],
|
||||
) -> List[TemplateClipConfig]:
|
||||
config_ids: list[str],
|
||||
) -> list[TemplateClipConfig]:
|
||||
"""重新排序片段配置
|
||||
|
||||
Args:
|
||||
@@ -560,7 +560,7 @@ class EditTemplateService:
|
||||
)
|
||||
|
||||
# 5. 转换每个片段为模板片段配置
|
||||
created_configs: List[TemplateClipConfig] = []
|
||||
created_configs: list[TemplateClipConfig] = []
|
||||
for clip_config_obj in clips_to_template_clip_configs(created_template.id, clips):
|
||||
created = self._clip_config_repo.create(clip_config_obj)
|
||||
created_configs.append(created)
|
||||
|
||||
@@ -17,7 +17,7 @@ from __future__ import annotations
|
||||
import io
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from typing import Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
@@ -229,7 +229,7 @@ class LipsyncService:
|
||||
)
|
||||
job.mediakit_task_id = result["task_id"]
|
||||
job.status = "submitted"
|
||||
job.submitted_at = datetime.now(timezone.utc)
|
||||
job.submitted_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
logger.info(
|
||||
"[lipsync] 直传音频已提交 MediaKit: job_id=%s task_id=%s",
|
||||
@@ -338,7 +338,7 @@ class LipsyncService:
|
||||
job.status = "failed"
|
||||
job.error_message = f"Celery 任务投递失败: {exc}"
|
||||
job.error_code = "AsyncDispatchFailed"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
else:
|
||||
# 2b/2c. 直接音频 / 预合成音频:同步路径
|
||||
@@ -360,7 +360,7 @@ class LipsyncService:
|
||||
voice_id: str,
|
||||
script_text: str,
|
||||
speed: float = 1.0,
|
||||
emotion: str = "natural",
|
||||
emotion: str = "neutral",
|
||||
) -> dict:
|
||||
"""同步做 TTS 合成 + 下载 + ffprobe + 句子时间戳计算.
|
||||
|
||||
@@ -498,8 +498,8 @@ class LipsyncService:
|
||||
temp_url = result.get("video_url", "")
|
||||
job.output_video_url = temp_url
|
||||
job.output_duration = result.get("duration", 0.0)
|
||||
job.completed_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.completed_at = datetime.now(UTC)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
# 异步转存自家 OSS
|
||||
try:
|
||||
@@ -517,12 +517,12 @@ class LipsyncService:
|
||||
job.status = "failed"
|
||||
job.error_message = error.get("message", "任务执行失败")
|
||||
job.error_code = error.get("code", "TaskFailed")
|
||||
job.completed_at = datetime.now(timezone.utc)
|
||||
job.completed_at = datetime.now(UTC)
|
||||
else:
|
||||
# 中间状态(running/processing/queued 等)同步到 DB,避免前端永远卡在 submitted
|
||||
if isinstance(mk_status, str) and mk_status:
|
||||
job.status = mk_status
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
except Exception as exc: # noqa: BLE001 - DB 提交失败必须记录日志并重试,否则后台任务静默失败
|
||||
logger.error(
|
||||
@@ -589,7 +589,7 @@ class LipsyncService:
|
||||
|
||||
if job.status in ("pending", "tts_processing", "submitted"):
|
||||
job.status = "cancelled"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
self.db.refresh(job)
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import random
|
||||
from typing import Any, List
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -62,8 +62,8 @@ class PlanGeneratorService:
|
||||
def generate_from_template(
|
||||
self,
|
||||
template: EditTemplate,
|
||||
clip_configs: List[TemplateClipConfig],
|
||||
asset_ids: List[str],
|
||||
clip_configs: list[TemplateClipConfig],
|
||||
asset_ids: list[str],
|
||||
*,
|
||||
project_id: str = "",
|
||||
created_by_user_id: str = "",
|
||||
@@ -135,7 +135,7 @@ class PlanGeneratorService:
|
||||
)
|
||||
|
||||
# 5. 持久化所有 clips 并计算总时长
|
||||
created_clips: List[EditPlanClip] = []
|
||||
created_clips: list[EditPlanClip] = []
|
||||
total_duration = 0.0
|
||||
for clip in clips:
|
||||
saved = self._clip_repo.create(clip)
|
||||
@@ -184,15 +184,15 @@ class PlanGeneratorService:
|
||||
def _create_clips_from_configs(
|
||||
self,
|
||||
plan_id: str,
|
||||
clip_configs: List[TemplateClipConfig],
|
||||
) -> List[EditPlanClip]:
|
||||
clip_configs: list[TemplateClipConfig],
|
||||
) -> list[EditPlanClip]:
|
||||
"""从 TemplateClipConfig 列表创建 EditPlanClip 列表(未持久化).
|
||||
|
||||
委托给 plan_generator_utils.create_clips_from_configs 纯函数。
|
||||
"""
|
||||
return create_clips_from_configs(plan_id, clip_configs)
|
||||
|
||||
def _map_clip_types_for_mode(self, clips: List[EditPlanClip], editing_mode: str) -> None:
|
||||
def _map_clip_types_for_mode(self, clips: list[EditPlanClip], editing_mode: str) -> None:
|
||||
"""将 MAIN 类型片段按 editing_mode 映射为对应角色类型.
|
||||
|
||||
委托给 plan_generator_utils.map_clip_types_for_mode 纯函数。
|
||||
@@ -204,7 +204,7 @@ class PlanGeneratorService:
|
||||
plan_id: str,
|
||||
editing_mode: str,
|
||||
asset_count: int,
|
||||
) -> List[EditPlanClip]:
|
||||
) -> list[EditPlanClip]:
|
||||
"""无 clip_configs 时,根据 editing_mode 生成默认 clip 结构.
|
||||
|
||||
委托给 plan_generator_utils.generate_default_clips 纯函数。
|
||||
@@ -213,8 +213,8 @@ class PlanGeneratorService:
|
||||
|
||||
def _distribute_assets(
|
||||
self,
|
||||
clips: List[EditPlanClip],
|
||||
asset_ids: List[str],
|
||||
clips: list[EditPlanClip],
|
||||
asset_ids: list[str],
|
||||
editing_mode: str,
|
||||
*,
|
||||
random_selection: bool = False,
|
||||
@@ -259,7 +259,7 @@ class PlanGeneratorService:
|
||||
external_used_segments=external_used_segments,
|
||||
)
|
||||
|
||||
def _fetch_asset_scene_points(self, asset_ids: List[str]) -> dict[str, list[float]]:
|
||||
def _fetch_asset_scene_points(self, asset_ids: list[str]) -> dict[str, list[float]]:
|
||||
"""从素材 metadata 读取场景切换点缓存(无缓存的素材不包含在结果中)。"""
|
||||
points_map: dict[str, list[float]] = {}
|
||||
if not self._asset_repo:
|
||||
@@ -272,7 +272,7 @@ class PlanGeneratorService:
|
||||
points_map[asset_id] = points
|
||||
return points_map
|
||||
|
||||
def _sort_assets_by_smart_score(self, asset_ids: List[str]) -> List[str]:
|
||||
def _sort_assets_by_smart_score(self, asset_ids: list[str]) -> list[str]:
|
||||
"""按 smart_match 综合评分降序排列素材 ID(注入随机噪声)。
|
||||
|
||||
评分高的素材(质量好、时长合适、新鲜、使用次数少)倾向排在前面;
|
||||
@@ -295,7 +295,7 @@ class PlanGeneratorService:
|
||||
)
|
||||
return [aid for aid, _ in scored]
|
||||
|
||||
def _fetch_asset_durations(self, asset_ids: List[str]) -> dict[str, float]:
|
||||
def _fetch_asset_durations(self, asset_ids: list[str]) -> dict[str, float]:
|
||||
"""从数据库获取素材时长信息.
|
||||
|
||||
Args:
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""文案提取 ASR 服务封装 — Issue #1893.
|
||||
|
||||
将已有的 ASR 服务工厂封装为面向文案提取场景的简单接口:
|
||||
- transcribe_to_text(video_path) -> str:将视频/音频转写为纯文本
|
||||
- 未配置 ASR 时抛 ASRNotConfiguredError(路由层映射为 503)
|
||||
- ASR 调用失败时抛 ASRTranscriptionError(路由层映射为 502)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from packages.ports.asr_service import ASRServiceError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ASRNotConfiguredError(Exception):
|
||||
"""ASR 服务未配置."""
|
||||
|
||||
|
||||
class ASRTranscriptionError(Exception):
|
||||
"""ASR 转写失败."""
|
||||
|
||||
|
||||
def transcribe_to_text(media_path: str | Path) -> str:
|
||||
"""将视频/音频文件转写为纯文本.
|
||||
|
||||
Args:
|
||||
media_path: 媒体文件路径
|
||||
|
||||
Returns:
|
||||
转写出的文本
|
||||
|
||||
Raises:
|
||||
ASRNotConfiguredError: ASR 服务未配置
|
||||
ASRTranscriptionError: ASR 调用失败
|
||||
"""
|
||||
# 延迟导入,避免循环依赖和启动时副作用
|
||||
from apps.worker.services.asr_service_factory import get_asr_service
|
||||
|
||||
asr = get_asr_service()
|
||||
if asr is None:
|
||||
raise ASRNotConfiguredError("ASR 服务未配置,请联系管理员配置火山 MediaKit 或阿里云 ASR 密钥")
|
||||
|
||||
try:
|
||||
timeline = asr.transcribe(Path(media_path))
|
||||
# 拼接所有分段的文本
|
||||
text = "".join(seg.text for seg in timeline.segments)
|
||||
return text.strip()
|
||||
except ASRNotConfiguredError:
|
||||
raise
|
||||
except ASRServiceError as exc:
|
||||
logger.error("ASR 转写失败: %s", exc)
|
||||
raise ASRTranscriptionError(f"语音识别失败: {exc}") from exc
|
||||
except Exception as exc:
|
||||
logger.error("ASR 转写异常: %s", exc)
|
||||
raise ASRTranscriptionError(f"语音识别失败: {exc}") from exc
|
||||
@@ -6,7 +6,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -51,6 +51,9 @@ class ScriptService:
|
||||
content: str = "",
|
||||
segments: list | None = None,
|
||||
tags: list | None = None,
|
||||
title_text: str = "",
|
||||
title_category: str = "",
|
||||
title_config: dict | None = None,
|
||||
) -> ScriptModel:
|
||||
script = ScriptModel(
|
||||
id=str(uuid.uuid4()),
|
||||
@@ -59,6 +62,9 @@ class ScriptService:
|
||||
content=content,
|
||||
segments=segments if segments is not None else [],
|
||||
tags=tags if tags is not None else [],
|
||||
title_text=title_text or "",
|
||||
title_category=title_category or "",
|
||||
title_config=title_config if title_config is not None else {},
|
||||
)
|
||||
self.db.add(script)
|
||||
self.db.commit()
|
||||
@@ -83,6 +89,9 @@ class ScriptService:
|
||||
content: Optional[str] = None,
|
||||
segments: Optional[list] = None,
|
||||
tags: Optional[list] = None,
|
||||
title_text: Optional[str] = None,
|
||||
title_category: Optional[str] = None,
|
||||
title_config: Optional[dict] = None,
|
||||
) -> ScriptModel:
|
||||
script = self.get_script(script_id, user_id)
|
||||
if title is not None:
|
||||
@@ -93,11 +102,27 @@ class ScriptService:
|
||||
script.segments = segments
|
||||
if tags is not None:
|
||||
script.tags = tags
|
||||
script.updated_at = datetime.now(timezone.utc)
|
||||
if title_text is not None:
|
||||
script.title_text = title_text
|
||||
if title_category is not None:
|
||||
script.title_category = title_category
|
||||
if title_config is not None:
|
||||
script.title_config = title_config
|
||||
script.updated_at = datetime.now(UTC)
|
||||
self.db.commit()
|
||||
self.db.refresh(script)
|
||||
return script
|
||||
|
||||
# ── title config ─────────────────────────────────────────────────────
|
||||
|
||||
def get_title_config_for_script(self, script_id: str, user_id: str) -> dict:
|
||||
"""从 script 读取标题配置,返回可直接用于渲染的 title_config dict."""
|
||||
script = self.get_script(script_id, user_id)
|
||||
config = dict(script.title_config or {})
|
||||
if not config.get("text") and script.title_text:
|
||||
config["text"] = script.title_text
|
||||
return config
|
||||
|
||||
# ── delete ────────────────────────────────────────────────────────────
|
||||
|
||||
def delete_script(self, script_id: str, user_id: str) -> bool:
|
||||
|
||||
@@ -20,7 +20,7 @@ _estimate_sentence_timings_by_chars 等内部函数已复用共享实现,避
|
||||
|
||||
import io
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from celery import shared_task
|
||||
@@ -167,7 +167,7 @@ def tts_synthesize_and_submit(
|
||||
job.status = "failed"
|
||||
job.error_message = f"TTS 合成失败: {exc}"
|
||||
job.error_code = "TTSSynthesisFailed"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
return
|
||||
except ValueError as exc:
|
||||
@@ -175,7 +175,7 @@ def tts_synthesize_and_submit(
|
||||
job.status = "failed"
|
||||
job.error_message = f"TTS 参数错误: {exc}"
|
||||
job.error_code = "TTSInvalidParam"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
return
|
||||
|
||||
@@ -185,7 +185,7 @@ def tts_synthesize_and_submit(
|
||||
job.status = "failed"
|
||||
job.error_message = "TTS 未返回音频 URL"
|
||||
job.error_code = "TTSNoAudio"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
return
|
||||
|
||||
@@ -271,7 +271,7 @@ def tts_synthesize_and_submit(
|
||||
)
|
||||
job.mediakit_task_id = mk_result["task_id"]
|
||||
job.status = "submitted"
|
||||
job.submitted_at = datetime.now(timezone.utc)
|
||||
job.submitted_at = datetime.now(UTC)
|
||||
logger.info(
|
||||
"[lipsync_tts] 已提交 MediaKit: job_id=%s task_id=%s",
|
||||
job_id,
|
||||
@@ -305,7 +305,7 @@ def tts_synthesize_and_submit(
|
||||
job.status = "failed"
|
||||
job.error_message = "TTS 异步任务执行异常"
|
||||
job.error_code = "AsyncTaskError"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
except Exception:
|
||||
logger.exception("[lipsync_tts] 回写失败状态时异常: job_id=%s", job_id)
|
||||
@@ -374,8 +374,8 @@ def poll_mediakit_status(self, job_id: str, user_id: str):
|
||||
logger.warning("[lipsync_poll] 转存 OSS 失败,保留临时 URL: job_id=%s err=%s", job_id, exc)
|
||||
job.output_video_url = output_url
|
||||
job.output_duration = result.get("duration", 0.0)
|
||||
job.completed_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.completed_at = datetime.now(UTC)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
logger.info("[lipsync_poll] 任务完成: job_id=%s", job_id)
|
||||
elif mk_status in ("failed", "error", _SF):
|
||||
@@ -383,13 +383,13 @@ def poll_mediakit_status(self, job_id: str, user_id: str):
|
||||
job.status = "failed"
|
||||
job.error_message = error.get("message", "任务执行失败")
|
||||
job.error_code = error.get("code", "TaskFailed")
|
||||
job.completed_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.completed_at = datetime.now(UTC)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
logger.info("[lipsync_poll] 任务失败: job_id=%s err=%s", job_id, job.error_message)
|
||||
else:
|
||||
# 中间状态,更新时间戳,继续重试
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
if isinstance(mk_status, str) and mk_status:
|
||||
job.status = mk_status
|
||||
db.commit()
|
||||
@@ -446,7 +446,7 @@ def persist_output_video_task(job_id: str, user_id: str, temp_url: str):
|
||||
permanent_url = storage.upload_file(io.BytesIO(data), storage_key, content_type="video/mp4")
|
||||
final_url = _sign_media_url(permanent_url) if permanent_url else temp_url
|
||||
job.output_video_url = final_url
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
job.updated_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
logger.info("[lipsync_tts.persist] 输出视频已转存 OSS: job_id=%s key=%s", job_id, storage_key)
|
||||
except Exception as exc:
|
||||
|
||||
@@ -40,7 +40,6 @@ async function loginWithRetry(
|
||||
|
||||
type ProjectResponse = { id: string }
|
||||
type LibraryResponse = { id: string }
|
||||
type TemplateResponse = { id: string }
|
||||
type AssetListResponse = {
|
||||
items: Array<{
|
||||
id: string
|
||||
@@ -50,10 +49,10 @@ type AssetListResponse = {
|
||||
}
|
||||
|
||||
test.describe("Core generation flow", () => {
|
||||
test.describe.configure({ timeout: 360_000 })
|
||||
test.describe.configure({ timeout: 600_000 })
|
||||
|
||||
test("walks through 6-step wizard and starts generation", async ({ page, request }) => {
|
||||
test.setTimeout(360_000)
|
||||
test("walks through wizard with count modal and starts generation", async ({ page, request }) => {
|
||||
test.setTimeout(600_000)
|
||||
|
||||
await routeBrowserApiToTestApi(page)
|
||||
const suffix = Date.now().toString(36)
|
||||
@@ -126,28 +125,17 @@ test.describe("Core generation flow", () => {
|
||||
)
|
||||
.toBe("ready")
|
||||
|
||||
// Create an editing template so the generate page has at least one template
|
||||
// (templates are now loaded from API; new users have none by default)
|
||||
const template = await request.post(`${apiBase}/templates`, {
|
||||
headers,
|
||||
data: {
|
||||
name: `E2E 测试模板 ${suffix}`,
|
||||
mode: "pip",
|
||||
estimated_duration: 30,
|
||||
segments: [
|
||||
{
|
||||
segment_order: 1,
|
||||
duration_min: 5,
|
||||
duration_max: 30,
|
||||
material_type: "video",
|
||||
},
|
||||
],
|
||||
tags: ["e2e"],
|
||||
},
|
||||
})
|
||||
expect(template.status(), await template.text()).toBe(201)
|
||||
const templateData = (await template.json()) as TemplateResponse
|
||||
expect(templateData.id).toBeTruthy()
|
||||
// #1926 P0 fix: POST /templates CRUD endpoint removed; GET /templates
|
||||
// now auto-creates a default template for new users. Use the first one.
|
||||
const templatesResp = await request.get(`${apiBase}/templates`, { headers })
|
||||
expect(templatesResp.status(), await templatesResp.text()).toBe(200)
|
||||
const templatesData = (await templatesResp.json()) as {
|
||||
items: Array<{ id: string }>
|
||||
}
|
||||
expect(Array.isArray(templatesData.items)).toBe(true)
|
||||
expect(templatesData.items.length).toBeGreaterThan(0)
|
||||
const templateId = templatesData.items[0].id
|
||||
expect(templateId).toBeTruthy()
|
||||
|
||||
// Set auth in localStorage
|
||||
await page.addInitScript(
|
||||
@@ -181,18 +169,9 @@ test.describe("Core generation flow", () => {
|
||||
timeout: 20_000,
|
||||
})
|
||||
|
||||
// Step 1: template - default selected, click next
|
||||
await expect(page.locator(".xx-choice-item.selected")).toBeVisible()
|
||||
await page.getByRole("button", { name: "下一步" }).click()
|
||||
|
||||
// Step1 下一步弹出数量选择弹窗(Issue #1677 固定6步:模板→素材→配音→标题→确认生成→封面)
|
||||
// 单视频流程:默认 1 个,点击「生成 1 个视频」进入步骤2
|
||||
await expect(page.getByRole("heading", { name: "要生成几个视频?" })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
})
|
||||
await page.getByRole("button", { name: "生成 1 个视频" }).click()
|
||||
|
||||
// Step 2: select material (card grid UI)
|
||||
// 5步向导:素材→数量弹窗→配音→标题→确认生成→封面(#1911 删除选模板步骤,后端自动使用默认模板;
|
||||
// #1677 批量生成在选完素材后弹「要生成几个视频?」数量弹窗,默认1,回车确认)
|
||||
// Step 1: select material (card grid UI)
|
||||
await expect(page.getByRole("heading", { name: /选择素材/ })).toBeVisible()
|
||||
const librarySelect = page.locator("select").first()
|
||||
await librarySelect.selectOption({ label: libraryName })
|
||||
@@ -205,11 +184,17 @@ test.describe("Core generation flow", () => {
|
||||
await expect(materialCard.getByTestId("material-card-check")).toBeVisible({ timeout: 5_000 })
|
||||
await page.getByRole("button", { name: "下一步" }).click()
|
||||
|
||||
// Step 3: voice (可选步骤,新注册用户无配音素材,直接跳过)
|
||||
// #1677 数量弹窗:默认值1,点击「生成 1 个视频」确认(新用户单视频冒烟路径)
|
||||
await expect(page.getByRole("heading", { name: "要生成几个视频?" })).toBeVisible({
|
||||
timeout: 5_000,
|
||||
})
|
||||
await page.getByRole("button", { name: "生成 1 个视频" }).click()
|
||||
|
||||
// Step 2: voice(新注册用户无配音素材时展示空状态 h3「🎙️ 选择配音」,仍可点「下一步」跳过)
|
||||
await expect(page.getByRole("heading", { name: /选择配音/ })).toBeVisible({ timeout: 15000 })
|
||||
await page.getByRole("button", { name: "下一步" }).click()
|
||||
|
||||
// Step 4: title(新顺序:标题在预览之前)
|
||||
// Step 3: title(新顺序:标题在预览之前)
|
||||
await expect(page.getByRole("heading", { name: /选择标题/ })).toBeVisible({ timeout: 15000 })
|
||||
// 等待组件完全渲染
|
||||
await page.waitForTimeout(2000)
|
||||
@@ -222,7 +207,14 @@ test.describe("Core generation flow", () => {
|
||||
const titleText = `E2E Test ${suffix}`
|
||||
await titleInput.fill(titleText)
|
||||
|
||||
// Step 4(标题+实时预览):确认生成按钮已移到标题页,点击直接创建最终渲染任务
|
||||
// 步骤3(标题页)底部操作栏按钮是「下一步 →」,点击后进入步骤4
|
||||
// 步骤4底部才是「✨ 确认生成视频」按钮
|
||||
const nextBtn = page.locator(".xx-step-actions .xx-btn-primary").filter({ hasText: "下一步" })
|
||||
await expect(nextBtn).toBeVisible({ timeout: 15_000 })
|
||||
await nextBtn.click()
|
||||
|
||||
// Step 4:「确认生成」页面——此处底部是「✨ 确认生成视频」按钮
|
||||
// 注意:Step4 主内容区是实时预览画布,没有 h3 「🎬 确认生成」标题,标题由顶部步骤条展示
|
||||
// 等待前端实时预览就绪:未就绪时右侧 FrontendPreviewPlayer 显示「准备预览素材...」占位,
|
||||
// 就绪(previewReady:素材已解析 + 模板已选中)后占位消失;否则按钮会被校验拦截弹 warning
|
||||
await page
|
||||
@@ -230,19 +222,25 @@ test.describe("Core generation flow", () => {
|
||||
.waitFor({ state: "detached", timeout: 30_000 })
|
||||
.catch(() => {})
|
||||
|
||||
// Wait for generation API to be called
|
||||
// 前端直接创建生成任务:POST /generation/tasks
|
||||
// 定位底部操作栏的「✨ 确认生成视频」按钮
|
||||
// 使用底部操作栏 xx-step-actions 作用域,避免命中其他 primary 按钮
|
||||
const confirmBtn = page
|
||||
.locator(".xx-step-actions .xx-btn-primary")
|
||||
.filter({ hasText: "确认生成" })
|
||||
await expect(confirmBtn).toBeVisible({ timeout: 30_000 })
|
||||
await expect(confirmBtn).toBeEnabled({ timeout: 30_000 })
|
||||
|
||||
// Wait for generation API to be called — 先挂监听再点击,避免竞态
|
||||
const generatePromise = page.waitForResponse(
|
||||
(response) => {
|
||||
const url = response.url()
|
||||
const path = new URL(url).pathname
|
||||
return response.request().method() === "POST" && path.endsWith("/generation/tasks")
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
{ timeout: 60_000 },
|
||||
)
|
||||
|
||||
// 点击「确认生成视频」
|
||||
await page.locator(".xx-btn-primary").filter({ hasText: "确认生成视频" }).first().click()
|
||||
await confirmBtn.click()
|
||||
|
||||
// Verify generation was triggered
|
||||
const genResp = await generatePromise
|
||||
@@ -262,19 +260,26 @@ test.describe("Core generation flow", () => {
|
||||
expect(genData.items.length).toBeGreaterThan(0)
|
||||
expect(genData.items[0].id).toBeTruthy()
|
||||
|
||||
// 单视频(N=1):点击「确认生成视频」后跳 Step 5「确认生成」,展示实时渲染进度
|
||||
await expect(page.getByRole("heading", { name: "🎬 确认生成" })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
})
|
||||
// 单视频(N=1):点击「确认生成视频」后跳步骤 5「确认生成」进度页,展示进度卡
|
||||
// 注意:进度页底部按钮变为 disabled 的「⏳ 视频渲染中…」
|
||||
await expect(page.getByText("视频渲染中")).toBeVisible({ timeout: 30_000 })
|
||||
|
||||
// 等待渲染完成:进度卡变为「视频生成完成」(最长等待 3 分钟)
|
||||
await expect(page.getByText("视频生成完成")).toBeVisible({ timeout: 180_000 })
|
||||
// 等待渲染完成:单视频成片播放器渲染(带「⬇️ 下载」按钮),最长等待 3 分钟
|
||||
// 注意:message.success「视频生成完成」toast 3秒后自动消失,不能作为稳定断言点
|
||||
await expect(page.getByRole("button", { name: "⬇️ 下载" })).toBeVisible({ timeout: 420_000 })
|
||||
|
||||
// 全部完成后「下一步:选择封面」解锁,点击进入 Step 6
|
||||
await page.getByRole("button", { name: /下一步:选择封面/ }).click()
|
||||
await expect(page.getByRole("heading", { name: /选择封面/ })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
})
|
||||
// #1954 修复:生成完成后步骤4底部应显示「下一步:选择封面」按钮
|
||||
// 等待底部主按钮从「⏳/确认生成」切换为「下一步:选择封面」
|
||||
const nextCoverBtn = page
|
||||
.locator(".xx-step-actions > .xx-btn-primary")
|
||||
.filter({ hasText: "选择封面" })
|
||||
await expect(nextCoverBtn).toBeVisible({ timeout: 15_000 })
|
||||
await nextCoverBtn.click()
|
||||
|
||||
// 断言进入步骤5封面页:主内容出现「选择封面」标题
|
||||
await expect(page.getByText("🖼️ 选择封面")).toBeVisible({ timeout: 10_000 })
|
||||
// 底部操作栏主按钮应消失(封面是最后一步,只剩「← 上一步」)
|
||||
await expect(page.locator(".xx-step-actions > .xx-btn-primary")).toHaveCount(0)
|
||||
} else {
|
||||
console.log(`[E2E] Generate API returned ${genResp.status()}, wizard flow test still passes`)
|
||||
// 创建失败时停留在标题页并展示错误提示
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
/**
|
||||
* 积分系统 API 封装
|
||||
* 对齐后端 staging 实测最终契约(2026-09-16)
|
||||
*
|
||||
* 当前 POINTS_API_MOCK=true:使用 MOCK_* 常量 + setTimeout 模拟延迟,
|
||||
* 等后端 P0(支付通道接入、change-plan 校验)稳定后切 false 联调。
|
||||
*
|
||||
* 会员/订阅 API 在 @/api/subscription 中定义,避免重复封装。
|
||||
*/
|
||||
import apiClient from "../client"
|
||||
import type {
|
||||
PointsBalance,
|
||||
PointsRulesResponse,
|
||||
PointsPackagesResponse,
|
||||
PointsTransaction,
|
||||
PointsTransactionsResponse,
|
||||
PointsCheckRequest,
|
||||
PointsCheckResponse,
|
||||
CreateRechargeOrderRequest,
|
||||
CreateRechargeOrderResponse,
|
||||
DailyUsage,
|
||||
MembershipResponse,
|
||||
} from "./types"
|
||||
|
||||
/** 模拟网络延迟(ms) */
|
||||
const MOCK_DELAY = 500
|
||||
|
||||
/* ================================================================
|
||||
* Mock 数据
|
||||
* ================================================================ */
|
||||
|
||||
/** mock 余额(无 free_clips_* 字段,已拆分到 dailyUsage) */
|
||||
const MOCK_BALANCE: PointsBalance = {
|
||||
balance: 258,
|
||||
total_earned: 500,
|
||||
total_spent: 242,
|
||||
is_member: false,
|
||||
member_type: null,
|
||||
member_expires_at: null,
|
||||
}
|
||||
|
||||
const MOCK_RULES: PointsRulesResponse = {
|
||||
rules: [
|
||||
{
|
||||
scene_key: "ai_voice",
|
||||
name: "AI 配音",
|
||||
base_points: 2,
|
||||
unit: "次",
|
||||
description: "单次配音消耗 2 积分,超 30 秒每 30 秒 +1 积分",
|
||||
extra_per_30s: 1,
|
||||
},
|
||||
{
|
||||
scene_key: "ai_video",
|
||||
name: "AI 视频生成",
|
||||
base_points: 8,
|
||||
unit: "条",
|
||||
description: "单条视频 8 积分起,按视频时长加收",
|
||||
extra_per_30s: 3,
|
||||
},
|
||||
{
|
||||
scene_key: "ai_digital_human",
|
||||
name: "AI 数字人",
|
||||
base_points: 15,
|
||||
unit: "次",
|
||||
description: "数字人生成 15 积分起",
|
||||
extra_per_30s: 5,
|
||||
},
|
||||
{
|
||||
scene_key: "voice_clone_train",
|
||||
name: "声音克隆训练",
|
||||
base_points: 20,
|
||||
unit: "次",
|
||||
description: "声音模型训练一次性消耗 20 积分",
|
||||
},
|
||||
{
|
||||
scene_key: "voice_clone_synth",
|
||||
name: "声音克隆合成",
|
||||
base_points: 3,
|
||||
unit: "次",
|
||||
description: "使用克隆声音合成音频每次 3 积分",
|
||||
},
|
||||
{
|
||||
scene_key: "douyin_extract",
|
||||
name: "抖音文案提取",
|
||||
base_points: 1,
|
||||
unit: "次",
|
||||
description: "提取抖音视频文案每次 1 积分",
|
||||
},
|
||||
{
|
||||
scene_key: "ai_rewrite",
|
||||
name: "AI 文案改写",
|
||||
base_points: 2,
|
||||
unit: "次",
|
||||
description: "AI 改写文案每次 2 积分",
|
||||
},
|
||||
{
|
||||
scene_key: "ai_title",
|
||||
name: "AI 标题生成",
|
||||
base_points: 1,
|
||||
unit: "次",
|
||||
description: "AI 生成标题每次 1 积分,一次生成多条",
|
||||
},
|
||||
{
|
||||
scene_key: "ai_cover",
|
||||
name: "AI 封面生成",
|
||||
base_points: 3,
|
||||
unit: "次",
|
||||
description: "AI 生成封面每次 3 积分",
|
||||
},
|
||||
],
|
||||
free_user_multiplier: 1.15,
|
||||
}
|
||||
|
||||
const MOCK_PACKAGES: PointsPackagesResponse = {
|
||||
packages: [
|
||||
{ code: "points_100", name: "100 积分", points: 100, price_cents: 990, unit_price: 0.099 },
|
||||
{ code: "points_500", name: "500 积分", points: 500, price_cents: 4490, unit_price: 0.0898 },
|
||||
{ code: "points_1000", name: "1000 积分", points: 1000, price_cents: 7990, unit_price: 0.0799 },
|
||||
{
|
||||
code: "points_3000",
|
||||
name: "3000 积分",
|
||||
points: 3000,
|
||||
price_cents: 19900,
|
||||
unit_price: 0.0663,
|
||||
},
|
||||
],
|
||||
user_discount: null,
|
||||
}
|
||||
|
||||
const MOCK_TRANSACTIONS: PointsTransaction[] = [
|
||||
{
|
||||
id: 1,
|
||||
type: "deduct",
|
||||
source: "ai_video",
|
||||
amount: 10,
|
||||
balance_after: 248,
|
||||
description: "AI 视频生成 ×1(非会员倍率)",
|
||||
ref_id: "task_abc123",
|
||||
created_at: "2026-09-16T08:30:00Z",
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
type: "add",
|
||||
source: "recharge",
|
||||
amount: 100,
|
||||
balance_after: 258,
|
||||
description: "充值 100 积分",
|
||||
ref_id: "order_xyz789",
|
||||
created_at: "2026-09-15T14:20:00Z",
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
type: "deduct",
|
||||
source: "ai_voice",
|
||||
amount: 3,
|
||||
balance_after: 158,
|
||||
description: "AI 配音 ×1(45s 加收)",
|
||||
ref_id: "",
|
||||
created_at: "2026-09-15T10:15:00Z",
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
type: "add",
|
||||
source: "sign_up",
|
||||
amount: 60,
|
||||
balance_after: 161,
|
||||
description: "新用户注册赠送",
|
||||
ref_id: "",
|
||||
created_at: "2026-09-10T09:00:00Z",
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
type: "deduct",
|
||||
source: "ai_title",
|
||||
amount: 1,
|
||||
balance_after: 101,
|
||||
description: "AI 标题生成 ×1",
|
||||
ref_id: "",
|
||||
created_at: "2026-09-14T16:45:00Z",
|
||||
},
|
||||
]
|
||||
|
||||
const MOCK_DAILY_USAGE: DailyUsage = {
|
||||
free_clips_used: 1,
|
||||
free_clips_limit: 3,
|
||||
free_clips_remaining: 2,
|
||||
reset_at: new Date(Date.now() + 8 * 3600_000).toISOString(),
|
||||
}
|
||||
|
||||
const MOCK_MEMBERSHIP: MembershipResponse = {
|
||||
is_member: false,
|
||||
member_type: null,
|
||||
member_expires_at: null,
|
||||
points_balance: 258,
|
||||
max_resolution: "720p",
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 积分 API
|
||||
* ================================================================ */
|
||||
|
||||
/** 获取积分余额 */
|
||||
export async function getPointsBalance(): Promise<PointsBalance> {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { ...MOCK_BALANCE }
|
||||
}
|
||||
const { data } = await apiClient.get(`/points/balance`)
|
||||
return data
|
||||
}
|
||||
|
||||
/** 获取积分消耗规则 */
|
||||
export async function getPointsRules(): Promise<PointsRulesResponse> {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { rules: [...MOCK_RULES.rules], free_user_multiplier: MOCK_RULES.free_user_multiplier }
|
||||
}
|
||||
const { data } = await apiClient.get(`/points/rules`)
|
||||
return data
|
||||
}
|
||||
|
||||
/** 获取充值包列表 */
|
||||
export async function getPointsPackages(): Promise<PointsPackagesResponse> {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { packages: MOCK_PACKAGES.packages.map((p) => ({ ...p })), user_discount: null }
|
||||
}
|
||||
const { data } = await apiClient.get(`/points/packages`)
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取积分流水(分页)
|
||||
*/
|
||||
export async function getPointsTransactions(
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
): Promise<PointsTransactionsResponse> {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
const start = (page - 1) * pageSize
|
||||
const items = MOCK_TRANSACTIONS.slice(start, start + pageSize)
|
||||
return {
|
||||
items: items.map((t) => ({ ...t })),
|
||||
total: MOCK_TRANSACTIONS.length,
|
||||
page,
|
||||
page_size: pageSize,
|
||||
}
|
||||
}
|
||||
const { data } = await apiClient.get(`/points/transactions`, {
|
||||
params: { page, page_size: pageSize },
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建充值订单
|
||||
* 注意:当前 pay_params 返回空对象 {}(支付通道未接入),
|
||||
* 前端可以完成订单创建 UI,但无法发起真实支付,待后续支付通道接入后联调。
|
||||
*/
|
||||
export async function createPointsOrder(
|
||||
data: CreateRechargeOrderRequest,
|
||||
): Promise<CreateRechargeOrderResponse> {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY * 2))
|
||||
const pkg = MOCK_PACKAGES.packages.find((p) => p.code === data.package_id)
|
||||
if (!pkg) throw new Error("充值包不存在")
|
||||
return {
|
||||
id: `mock_order_${Date.now()}`,
|
||||
order_type: "points_recharge",
|
||||
product_code: pkg.code,
|
||||
amount_cents: pkg.price_cents,
|
||||
points_amount: pkg.points,
|
||||
status: "pending",
|
||||
pay_params: {},
|
||||
expire_at: new Date(Date.now() + 30 * 60_000).toISOString(),
|
||||
created_at: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
const { data: d } = await apiClient.post(`/points/recharge`, data)
|
||||
return d
|
||||
}
|
||||
|
||||
/**
|
||||
* 积分预检查(消耗前调用)
|
||||
*/
|
||||
export async function checkPoints(data: PointsCheckRequest): Promise<PointsCheckResponse> {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
const rule = MOCK_RULES.rules.find((r) => r.scene_key === data.scene_key)
|
||||
if (!rule) {
|
||||
throw {
|
||||
error: {
|
||||
code: 400,
|
||||
message: `未知场景:${data.scene_key}`,
|
||||
valid_scenes: MOCK_RULES.rules.map((r) => r.scene_key),
|
||||
},
|
||||
}
|
||||
}
|
||||
const durationExtra =
|
||||
data.duration_minutes && data.duration_minutes > 0.5 && rule.extra_per_30s
|
||||
? Math.ceil((data.duration_minutes * 60 - 30) / 30) * rule.extra_per_30s
|
||||
: 0
|
||||
const base = (rule.base_points + durationExtra) * data.quantity
|
||||
const balance = MOCK_BALANCE.balance
|
||||
const multiplier = MOCK_BALANCE.is_member ? 1 : MOCK_RULES.free_user_multiplier
|
||||
const required = Math.ceil(base * multiplier)
|
||||
// 免费额度抵扣
|
||||
const isFreeQuota = !MOCK_BALANCE.is_member && MOCK_DAILY_USAGE.free_clips_remaining > 0
|
||||
const finalRequired = isFreeQuota ? 0 : required
|
||||
return {
|
||||
allowed: balance >= finalRequired,
|
||||
required_points: finalRequired,
|
||||
current_balance: balance,
|
||||
remaining_after: balance - finalRequired,
|
||||
is_free_quota: isFreeQuota,
|
||||
}
|
||||
}
|
||||
const { data: d2 } = await apiClient.post(`/points/check`, data)
|
||||
return d2
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 每日免费额度 + 会员聚合信息(新接口)
|
||||
* ================================================================ */
|
||||
|
||||
/** 获取每日免费额度使用情况 */
|
||||
export async function getDailyUsage(): Promise<DailyUsage> {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { ...MOCK_DAILY_USAGE }
|
||||
}
|
||||
const { data } = await apiClient.get(`/usage/daily`)
|
||||
return data
|
||||
}
|
||||
|
||||
/** 获取会员聚合信息(创作页可用来判断 max_resolution) */
|
||||
export async function getMembership(): Promise<MembershipResponse> {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { ...MOCK_MEMBERSHIP }
|
||||
}
|
||||
const { data } = await apiClient.get(`/points/subscription/membership`)
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* 积分系统类型定义
|
||||
* 对齐后端 staging 实测最终契约(2026-09-16)
|
||||
*
|
||||
* Base path: /api/v1/
|
||||
* 会员/订阅相关类型请从 @/api/subscription/types 引入,本文件仅保留积分核心类型。
|
||||
*/
|
||||
|
||||
/* ================================================================
|
||||
* 场景键
|
||||
* ================================================================ */
|
||||
/**
|
||||
* 积分消耗场景键(9 个)
|
||||
* - ai_script 已拆分为 douyin_extract / ai_rewrite / ai_title,前端禁止再传 ai_script
|
||||
*/
|
||||
export type PointsSource =
|
||||
| "ai_voice" // AI 配音
|
||||
| "ai_video" // AI 视频生成
|
||||
| "ai_digital_human" // AI 数字人
|
||||
| "voice_clone_train" // 声音克隆训练
|
||||
| "voice_clone_synth" // 声音克隆合成
|
||||
| "douyin_extract" // 抖音提取文案
|
||||
| "ai_rewrite" // AI 文案改写
|
||||
| "ai_title" // AI 标题生成
|
||||
| "ai_cover" // AI 封面生成
|
||||
|
||||
/** 非消耗场景 source 前缀(用于流水 source 字段) */
|
||||
export type PointsSourceExtra =
|
||||
PointsSource | `refund:${string}` | "recharge" | "sign_up" | "bind_phone" | "gift" | "admin"
|
||||
|
||||
/* ================================================================
|
||||
* 通用
|
||||
* ================================================================ */
|
||||
/** ISO 8601 时间字符串 */
|
||||
export type ISODate = string
|
||||
|
||||
/* ================================================================
|
||||
* 积分余额(GET /points/balance)
|
||||
* ================================================================ */
|
||||
export interface PointsBalance {
|
||||
/** 当前可用积分 */
|
||||
balance: number
|
||||
/** 累计获得积分 */
|
||||
total_earned: number
|
||||
/** 累计消耗积分 */
|
||||
total_spent: number
|
||||
/** 是否为付费会员 */
|
||||
is_member: boolean
|
||||
/** 会员类型(monthly/quarterly/yearly,非会员 null)。推荐使用 /subscription/current 的 plan_id+billing_cycle 做判断 */
|
||||
member_type: "monthly" | "quarterly" | "yearly" | null
|
||||
/** 会员到期时间 */
|
||||
member_expires_at: ISODate | null
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 积分规则(GET /points/rules)
|
||||
* ================================================================ */
|
||||
export interface PointsRule {
|
||||
scene_key: PointsSource
|
||||
/** 场景中文名 */
|
||||
name: string
|
||||
/** 基准消耗积分(points_per_use 改名) */
|
||||
base_points: number
|
||||
/** 单位描述,如「次」「分钟」「个」 */
|
||||
unit: string
|
||||
/** 超过30秒后每30秒额外积分(视频/语音类) */
|
||||
extra_per_30s?: number
|
||||
/** 场景说明(后端已补回) */
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface PointsRulesResponse {
|
||||
rules: PointsRule[]
|
||||
/** 非会员消耗倍率(如 1.15) */
|
||||
free_user_multiplier: number
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 充值包(GET /points/packages)
|
||||
* ================================================================ */
|
||||
export interface PointsPackage {
|
||||
/** 包编码(id 改名) */
|
||||
code: string
|
||||
name: string
|
||||
points: number
|
||||
/** 原价,单位分 */
|
||||
price_cents: number
|
||||
/** 每积分单价(元),展示用 */
|
||||
unit_price: number
|
||||
}
|
||||
|
||||
export interface PointsPackagesResponse {
|
||||
packages: PointsPackage[]
|
||||
/** 当前用户折扣(会员折扣或活动折扣),null 表示无折扣 */
|
||||
user_discount: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 充值包前端展示辅助:折后价(分)
|
||||
* 后端废弃 4 档 discounted_price_for_*,前端按 price_cents * (user_discount ?? 1) 计算。
|
||||
*/
|
||||
export function getDiscountPriceCents(pkg: PointsPackage, userDiscount: number | null): number {
|
||||
return Math.round(pkg.price_cents * (userDiscount ?? 1))
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 积分流水(GET /points/transactions)
|
||||
* ================================================================ */
|
||||
export type PointsTxType = "add" | "deduct"
|
||||
|
||||
export interface PointsTransaction {
|
||||
id: number
|
||||
/** 流水类型:add=获得/退款,deduct=消耗 */
|
||||
type: PointsTxType
|
||||
/**
|
||||
* 消耗/获得来源:
|
||||
* - 消耗场景直接用 PointsSource 值
|
||||
* - 充值/退款/赠送使用 recharge / refund:<source> / sign_up / bind_phone / gift / admin
|
||||
*/
|
||||
source: string
|
||||
/** 变动数量(绝对值,正负由 type 决定) */
|
||||
amount: number
|
||||
/** 变动后余额 */
|
||||
balance_after: number
|
||||
/** 中文描述 */
|
||||
description: string
|
||||
/** 关联订单/任务 ID,空字符串 "" 表示无关联(不是 null) */
|
||||
ref_id: string
|
||||
created_at: ISODate
|
||||
}
|
||||
|
||||
export interface PointsTransactionsResponse {
|
||||
items: PointsTransaction[]
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 创建充值订单(POST /points/recharge)
|
||||
* ================================================================ */
|
||||
export interface CreateRechargeOrderRequest {
|
||||
/** 充值包 code(字段名保留 package_id 与后端一致) */
|
||||
package_id: string
|
||||
}
|
||||
|
||||
export interface CreateRechargeOrderResponse {
|
||||
id: string
|
||||
order_type: string
|
||||
product_code: string
|
||||
/** 订单金额(分) */
|
||||
amount_cents: number
|
||||
/** 充值积分数量 */
|
||||
points_amount: number
|
||||
status: string
|
||||
/**
|
||||
* 支付参数(支付通道未接入时返回空对象 {},前端可透传)
|
||||
*/
|
||||
pay_params: Record<string, unknown>
|
||||
/** 订单过期时间 */
|
||||
expire_at: ISODate
|
||||
created_at: ISODate
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 积分预检查(POST /points/check)
|
||||
* ================================================================ */
|
||||
export interface PointsCheckRequest {
|
||||
scene_key: PointsSource
|
||||
/** 数量(units 改名) */
|
||||
quantity: number
|
||||
/** 预计时长(分钟),可选 */
|
||||
duration_minutes?: number
|
||||
}
|
||||
|
||||
export interface PointsCheckResponse {
|
||||
/** 是否可以执行 */
|
||||
allowed: boolean
|
||||
/** 需要消耗积分 */
|
||||
required_points: number
|
||||
/** 当前余额 */
|
||||
current_balance: number
|
||||
/** 扣除后剩余 */
|
||||
remaining_after: number
|
||||
/** 是否走免费额度 */
|
||||
is_free_quota: boolean
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 每日使用情况(GET /usage/daily,新接口)
|
||||
* ================================================================ */
|
||||
export interface DailyUsage {
|
||||
/** 今日已用免费次数 */
|
||||
free_clips_used: number
|
||||
/** 每日免费次数上限 */
|
||||
free_clips_limit: number
|
||||
/** 今日剩余免费次数 */
|
||||
free_clips_remaining: number
|
||||
/** 额度重置时间 */
|
||||
reset_at: ISODate
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 会员聚合信息(GET /points/subscription/membership,新接口)
|
||||
* ================================================================ */
|
||||
export interface MembershipResponse {
|
||||
is_member: boolean
|
||||
/** 会员类型(monthly/quarterly/yearly,非会员 null) */
|
||||
member_type: "monthly" | "quarterly" | "yearly" | null
|
||||
member_expires_at: ISODate | null
|
||||
/** 当前积分余额(冗余,可与 balance 互校) */
|
||||
points_balance: number
|
||||
/** 最大分辨率,如 "720p" / "1080p" / "4k" */
|
||||
max_resolution: string
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 错误响应(统一格式 {error:{code,message}})
|
||||
* ================================================================ */
|
||||
export interface ApiError {
|
||||
error: {
|
||||
code: number
|
||||
message: string
|
||||
/** 部分场景会返回,如 unknown scene_key */
|
||||
valid_scenes?: PointsSource[]
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "./scripts"
|
||||
export * from "./types"
|
||||
export * from "./scripts-ai"
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* 文案库 AI 能力 API(#1893)
|
||||
* 三个端点均走真实后端,不参与 SCRIPTS_API_MOCK 开关。
|
||||
*/
|
||||
import apiClient from "../client"
|
||||
|
||||
/** ── 1. 从抖音视频提取文案(下载 + ASR) */
|
||||
export interface ExtractFromDouyinRequest {
|
||||
url: string
|
||||
}
|
||||
export interface ExtractFromDouyinResponse {
|
||||
text: string
|
||||
duration_seconds?: number
|
||||
source_url?: string
|
||||
}
|
||||
|
||||
export async function extractScriptFromDouyin(
|
||||
body: ExtractFromDouyinRequest,
|
||||
opts?: { signal?: AbortSignal },
|
||||
): Promise<ExtractFromDouyinResponse> {
|
||||
const res = await apiClient.post<ExtractFromDouyinResponse>(
|
||||
"/scripts/extract-from-douyin",
|
||||
body,
|
||||
{
|
||||
// ASR 可能较慢,给足超时
|
||||
timeout: 60_000,
|
||||
signal: opts?.signal,
|
||||
},
|
||||
)
|
||||
return res.data
|
||||
}
|
||||
|
||||
/** ── 2. AI 改写文案 */
|
||||
export type RewriteStyle = "口语化" | "正式" | "活泼" | "治愈" | "励志"
|
||||
|
||||
export const REWRITE_STYLE_OPTIONS: { value: RewriteStyle; label: string }[] = [
|
||||
{ value: "口语化", label: "口语化" },
|
||||
{ value: "正式", label: "正式" },
|
||||
{ value: "活泼", label: "活泼" },
|
||||
{ value: "治愈", label: "治愈" },
|
||||
{ value: "励志", label: "励志" },
|
||||
]
|
||||
|
||||
export interface AiRewriteRequest {
|
||||
content: string
|
||||
style?: RewriteStyle
|
||||
}
|
||||
export interface AiRewriteResponse {
|
||||
original: string
|
||||
rewritten: string
|
||||
style: RewriteStyle
|
||||
}
|
||||
|
||||
export async function aiRewriteScript(
|
||||
body: AiRewriteRequest,
|
||||
opts?: { signal?: AbortSignal },
|
||||
): Promise<AiRewriteResponse> {
|
||||
const res = await apiClient.post<AiRewriteResponse>("/scripts/ai-rewrite", body, {
|
||||
timeout: 60_000,
|
||||
signal: opts?.signal,
|
||||
})
|
||||
return res.data
|
||||
}
|
||||
|
||||
/** ── 3. AI 生成标题 */
|
||||
export interface AiGenerateTitlesRequest {
|
||||
content: string
|
||||
count?: number
|
||||
}
|
||||
export interface AiGenerateTitlesResponse {
|
||||
titles: string[]
|
||||
}
|
||||
|
||||
export async function aiGenerateTitles(
|
||||
body: AiGenerateTitlesRequest,
|
||||
opts?: { signal?: AbortSignal },
|
||||
): Promise<AiGenerateTitlesResponse> {
|
||||
const res = await apiClient.post<AiGenerateTitlesResponse>(
|
||||
"/scripts/ai-generate-titles",
|
||||
{ content: body.content, count: body.count ?? 3 },
|
||||
{
|
||||
timeout: 30_000,
|
||||
signal: opts?.signal,
|
||||
},
|
||||
)
|
||||
return res.data
|
||||
}
|
||||
@@ -1,37 +1,195 @@
|
||||
/**
|
||||
* 文案库 API
|
||||
* 对接后端 /api/v1/scripts(CRUD + 列表解包)
|
||||
* 文案库 API(#1811 v2)
|
||||
* CRUD + 搜索/分类/分页;后端未就绪时使用 mock 数据(SCRIPTS_API_MOCK=true)
|
||||
*/
|
||||
import apiClient from "../client"
|
||||
import type {
|
||||
ScriptItem,
|
||||
ScriptListParams,
|
||||
ScriptListResponse,
|
||||
CreateScriptRequest,
|
||||
UpdateScriptRequest,
|
||||
ScriptUpsertRequest,
|
||||
ScriptCategory,
|
||||
} from "./types"
|
||||
|
||||
/** 获取文案列表 — 必须解包 items(后端返回 {items,total})*/
|
||||
export const getScripts = async (): Promise<ScriptItem[]> => {
|
||||
const response = await apiClient.get<ScriptListResponse | ScriptItem[]>("/scripts")
|
||||
const data = response.data as unknown
|
||||
if (Array.isArray(data)) return data
|
||||
const items = (data as { items?: ScriptItem[] })?.items
|
||||
return Array.isArray(items) ? items : []
|
||||
/** 是否启用 mock(后端合入后改为 false) */
|
||||
export const SCRIPTS_API_MOCK = true
|
||||
|
||||
// ==================== Mock 数据 ====================
|
||||
|
||||
const MOCK_CATEGORIES: ScriptCategory[] = [
|
||||
"promo",
|
||||
"vlog",
|
||||
"knowledge",
|
||||
"story",
|
||||
"emotion",
|
||||
"other",
|
||||
]
|
||||
|
||||
const SAMPLE_TITLES: Record<ScriptCategory, string[]> = {
|
||||
promo: ["新品上市限时特惠", "618大促开场", "品牌故事宣传片"],
|
||||
vlog: ["周末citywalk记录", "打工人的一天", "探店vlog"],
|
||||
knowledge: ["3分钟学会XX", "冷知识科普", "行业深度解读"],
|
||||
story: ["励志小故事", "情感故事一则", "反转剧情"],
|
||||
emotion: ["深夜emo时刻", "治愈系文案", "朋友圈金句"],
|
||||
other: ["通用开场白", "节日祝福", "万能结尾"],
|
||||
}
|
||||
|
||||
const SAMPLE_TAGS = ["热门", "新品", "节日", "情感", "干货", "搞笑", "治愈", "励志"]
|
||||
|
||||
function genMockScripts(): ScriptItem[] {
|
||||
const items: ScriptItem[] = []
|
||||
const now = Date.now()
|
||||
let idx = 0
|
||||
for (const cat of MOCK_CATEGORIES) {
|
||||
const titles = SAMPLE_TITLES[cat]
|
||||
for (let i = 0; i < titles.length; i++) {
|
||||
idx++
|
||||
const title = titles[i]
|
||||
const content = `这是一条【${cat}】分类下的示例文案,标题为「${title}」。\n\n正文可以包含多段落,每段对应一个片段(segments)。\n\n此为 mock 数据,后端接口就绪后会自动切换为真实数据。`
|
||||
const segments = content.split(/\n\n+/).filter(Boolean)
|
||||
const tagCount = 1 + (idx % 3)
|
||||
const tags: string[] = []
|
||||
for (let t = 0; t < tagCount; t++) {
|
||||
tags.push(SAMPLE_TAGS[(idx + t) % SAMPLE_TAGS.length])
|
||||
}
|
||||
items.push({
|
||||
id: `mock_${idx}`,
|
||||
title,
|
||||
content,
|
||||
segments,
|
||||
tags,
|
||||
title_text: title,
|
||||
title_category: cat,
|
||||
title_config: {
|
||||
font: "default",
|
||||
color: "#ffffff",
|
||||
stroke: "#000000",
|
||||
position: (["top", "center", "bottom"] as const)[idx % 3],
|
||||
size: 48,
|
||||
bold: idx % 2 === 0,
|
||||
italic: false,
|
||||
},
|
||||
char_count: content.length,
|
||||
use_count: Math.floor(Math.random() * 50),
|
||||
created_at: new Date(now - idx * 86400_000 * 2).toISOString(),
|
||||
updated_at: new Date(now - idx * 86400_000).toISOString(),
|
||||
})
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
const MOCK_SCRIPTS = genMockScripts()
|
||||
|
||||
// ==================== 真实 API ====================
|
||||
|
||||
/** 获取文案列表(支持分页/搜索/分类) */
|
||||
export async function getScripts(params: ScriptListParams = {}): Promise<ScriptListResponse> {
|
||||
if (SCRIPTS_API_MOCK) {
|
||||
const page = params.page ?? 1
|
||||
const pageSize = params.page_size ?? 20
|
||||
let items = [...MOCK_SCRIPTS]
|
||||
if (params.keyword) {
|
||||
const kw = params.keyword.toLowerCase()
|
||||
items = items.filter(
|
||||
(s) => s.title.toLowerCase().includes(kw) || s.content.toLowerCase().includes(kw),
|
||||
)
|
||||
}
|
||||
if (params.category && params.category !== "all") {
|
||||
items = items.filter((s) => s.title_category === params.category)
|
||||
}
|
||||
if (params.tag) {
|
||||
items = items.filter((s) => s.tags?.includes(params.tag as string))
|
||||
}
|
||||
const total = items.length
|
||||
const start = (page - 1) * pageSize
|
||||
const pageItems = items.slice(start, start + pageSize)
|
||||
return new Promise((r) =>
|
||||
setTimeout(() => r({ items: pageItems, total, page, page_size: pageSize }), 200),
|
||||
)
|
||||
}
|
||||
const res = await apiClient.get<ScriptListResponse>("/scripts", { params })
|
||||
return res.data
|
||||
}
|
||||
|
||||
/** 获取单条文案详情 */
|
||||
export async function getScript(id: string): Promise<ScriptItem> {
|
||||
if (SCRIPTS_API_MOCK) {
|
||||
const item = MOCK_SCRIPTS.find((s) => s.id === id)
|
||||
return new Promise((r) => setTimeout(() => r(item ?? MOCK_SCRIPTS[0]), 120))
|
||||
}
|
||||
const res = await apiClient.get<ScriptItem>(`/scripts/${id}`)
|
||||
return res.data
|
||||
}
|
||||
|
||||
/** 新建文案 */
|
||||
export const createScript = async (data: CreateScriptRequest): Promise<ScriptItem> => {
|
||||
const response = await apiClient.post<ScriptItem>("/scripts", data)
|
||||
return response.data
|
||||
export async function createScript(data: ScriptUpsertRequest): Promise<ScriptItem> {
|
||||
if (SCRIPTS_API_MOCK) {
|
||||
const segments =
|
||||
data.segments && data.segments.length > 0
|
||||
? data.segments
|
||||
: data.content.split(/\n\n+/).filter(Boolean)
|
||||
const item: ScriptItem = {
|
||||
id: `mock_${Date.now()}`,
|
||||
...data,
|
||||
segments,
|
||||
char_count: data.content.length,
|
||||
use_count: 0,
|
||||
tags: data.tags ?? [],
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
}
|
||||
MOCK_SCRIPTS.unshift(item)
|
||||
return new Promise((r) => setTimeout(() => r(item), 200))
|
||||
}
|
||||
const res = await apiClient.post<ScriptItem>("/scripts", data)
|
||||
return res.data
|
||||
}
|
||||
|
||||
/** 更新文案 */
|
||||
export const updateScript = async (id: string, data: UpdateScriptRequest): Promise<ScriptItem> => {
|
||||
const response = await apiClient.put<ScriptItem>(`/scripts/${id}`, data)
|
||||
return response.data
|
||||
export async function updateScript(id: string, data: ScriptUpsertRequest): Promise<ScriptItem> {
|
||||
if (SCRIPTS_API_MOCK) {
|
||||
const idx = MOCK_SCRIPTS.findIndex((s) => s.id === id)
|
||||
const segments =
|
||||
data.segments && data.segments.length > 0
|
||||
? data.segments
|
||||
: data.content.split(/\n\n+/).filter(Boolean)
|
||||
const updated: ScriptItem = {
|
||||
...MOCK_SCRIPTS[idx],
|
||||
...data,
|
||||
segments,
|
||||
char_count: data.content.length,
|
||||
tags: data.tags ?? MOCK_SCRIPTS[idx]?.tags ?? [],
|
||||
updated_at: new Date().toISOString(),
|
||||
}
|
||||
if (idx >= 0) MOCK_SCRIPTS[idx] = updated
|
||||
return new Promise((r) => setTimeout(() => r(updated), 200))
|
||||
}
|
||||
const res = await apiClient.put<ScriptItem>(`/scripts/${id}`, data)
|
||||
return res.data
|
||||
}
|
||||
|
||||
/** 删除文案 */
|
||||
export const deleteScript = async (id: string): Promise<void> => {
|
||||
export async function deleteScript(id: string): Promise<void> {
|
||||
if (SCRIPTS_API_MOCK) {
|
||||
const idx = MOCK_SCRIPTS.findIndex((s) => s.id === id)
|
||||
if (idx >= 0) MOCK_SCRIPTS.splice(idx, 1)
|
||||
return new Promise((r) => setTimeout(r, 150))
|
||||
}
|
||||
await apiClient.delete(`/scripts/${id}`)
|
||||
}
|
||||
|
||||
/** 复制文案(返回新副本) */
|
||||
export async function duplicateScript(id: string): Promise<ScriptItem> {
|
||||
const orig = await getScript(id)
|
||||
const copy = await createScript({
|
||||
title: `${orig.title}(副本)`,
|
||||
content: orig.content,
|
||||
segments: orig.segments,
|
||||
tags: orig.tags,
|
||||
title_text: orig.title_text,
|
||||
title_category: orig.title_category,
|
||||
title_config: orig.title_config,
|
||||
})
|
||||
return copy
|
||||
}
|
||||
|
||||
@@ -1,24 +1,97 @@
|
||||
/**
|
||||
* 文案库 API — 类型定义
|
||||
* 对接后端 /api/v1/scripts
|
||||
* 文案库 API — 类型定义(#1811 v2 完整字段版)
|
||||
* 字段对齐后端契约:title / content / segments / tags / title_text / title_category / title_config
|
||||
* 同时保留 char_count / use_count / timestamps 等展示字段
|
||||
*/
|
||||
|
||||
/** 标题配置(字体、颜色、位置、字号) */
|
||||
export interface ScriptTitleConfig {
|
||||
/** 字体预设 key,如 "default" / "bold" / "handwritten" */
|
||||
font?: string
|
||||
/** 文字颜色(CSS color) */
|
||||
color?: string
|
||||
/** 描边色 */
|
||||
stroke?: string
|
||||
/** 位置:top / center / bottom */
|
||||
position?: "top" | "center" | "bottom"
|
||||
/** 字号(px) */
|
||||
size?: number
|
||||
/** 是否加粗 */
|
||||
bold?: boolean
|
||||
/** 是否斜体 */
|
||||
italic?: boolean
|
||||
}
|
||||
|
||||
/** 文案分类(可枚举,也支持自定义) */
|
||||
export type ScriptCategory =
|
||||
| "promo" // 营销推广
|
||||
| "vlog" // Vlog/日常
|
||||
| "knowledge" // 知识科普
|
||||
| "story" // 故事剧情
|
||||
| "emotion" // 情感语录
|
||||
| "other" // 其他
|
||||
|
||||
export const SCRIPT_CATEGORY_LABEL: Record<ScriptCategory, string> = {
|
||||
promo: "营销推广",
|
||||
vlog: "Vlog 日常",
|
||||
knowledge: "知识科普",
|
||||
story: "故事剧情",
|
||||
emotion: "情感语录",
|
||||
other: "其他",
|
||||
}
|
||||
|
||||
/** 文案条目 */
|
||||
export interface ScriptItem {
|
||||
id: string
|
||||
/** 名称(标题) */
|
||||
title: string
|
||||
/** 正文 */
|
||||
content: string
|
||||
char_count: number
|
||||
/** 分段(按段落切分,供后端/生成步骤逐段使用) */
|
||||
segments?: string[]
|
||||
/** 标签(逗号分隔或数组,列表展示用 Tag) */
|
||||
tags?: string[]
|
||||
/** 配套标题文本(选填,"使用"跳创作页时会预填到标题) */
|
||||
title_text?: string
|
||||
/** 分类 */
|
||||
title_category?: ScriptCategory
|
||||
/** 标题样式配置(字体/颜色/位置/字号) */
|
||||
title_config?: ScriptTitleConfig
|
||||
/** 正文字符数(后端返回,前端用于展示) */
|
||||
char_count?: number
|
||||
/** 使用次数(后端返回) */
|
||||
use_count?: number
|
||||
created_at: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
/** 列表查询参数(支持搜索/分类/分页) */
|
||||
export interface ScriptListParams {
|
||||
page?: number
|
||||
page_size?: number
|
||||
/** 标题/正文模糊搜索 */
|
||||
keyword?: string
|
||||
/** 分类筛选 */
|
||||
category?: ScriptCategory | "all"
|
||||
/** 标签筛选 */
|
||||
tag?: string
|
||||
}
|
||||
|
||||
/** 列表响应 */
|
||||
export interface ScriptListResponse {
|
||||
items: ScriptItem[]
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
}
|
||||
|
||||
export interface CreateScriptRequest {
|
||||
/** 创建/编辑请求 */
|
||||
export interface ScriptUpsertRequest {
|
||||
title: string
|
||||
content: string
|
||||
segments?: string[]
|
||||
tags?: string[]
|
||||
title_text?: string
|
||||
title_category?: ScriptCategory
|
||||
title_config?: ScriptTitleConfig
|
||||
}
|
||||
|
||||
export type UpdateScriptRequest = Partial<CreateScriptRequest>
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
/**
|
||||
* 订阅 API — 目录化入口
|
||||
* 保持与原 subscription.ts 相同导出,向后兼容
|
||||
* 对齐后端 staging 最终契约(2026-09-16)
|
||||
*/
|
||||
|
||||
// 类型
|
||||
export type {
|
||||
PlanId,
|
||||
PlanType,
|
||||
SubscriptionStatus,
|
||||
BillingStatus,
|
||||
BillingCycle,
|
||||
Plan,
|
||||
SubscriptionInfo,
|
||||
SubscriptionPlan,
|
||||
SubscriptionPlansResponse,
|
||||
BillingRecord,
|
||||
ChangePlanRequest,
|
||||
ChangePlanResponse,
|
||||
ToggleAutoRenewRequest,
|
||||
} from "./types"
|
||||
|
||||
export { PLAN_LABEL, BILLING_CYCLE_LABEL } from "./types"
|
||||
|
||||
// API 函数
|
||||
export {
|
||||
getCurrentSubscription,
|
||||
getSubscriptionPlans,
|
||||
getBillingRecords,
|
||||
changePlan,
|
||||
cancelSubscription,
|
||||
|
||||
@@ -1,47 +1,154 @@
|
||||
/**
|
||||
* 订阅相关 API 函数
|
||||
* 订阅/会员 API 封装
|
||||
* 对齐后端 staging 实测最终契约(2026-09-16)
|
||||
*
|
||||
* Base path: /api/v1/
|
||||
* 所有请求走 apiClient(已配置 baseURL=/api/v1 和 token 拦截器)。
|
||||
*/
|
||||
import apiClient from "../client"
|
||||
import type {
|
||||
SubscriptionInfo,
|
||||
SubscriptionPlan,
|
||||
SubscriptionPlansResponse,
|
||||
BillingRecord,
|
||||
ChangePlanRequest,
|
||||
ChangePlanResponse,
|
||||
SubscriptionInfo,
|
||||
ToggleAutoRenewRequest,
|
||||
} from "./types"
|
||||
|
||||
/** 获取当前订阅信息 */
|
||||
export const getCurrentSubscription = async (): Promise<SubscriptionInfo> => {
|
||||
const response = await apiClient.get("/subscription/current")
|
||||
return response.data
|
||||
const MOCK_DELAY = 500
|
||||
|
||||
const MOCK_SUBSCRIPTION: SubscriptionInfo = {
|
||||
id: "sub_mock_001",
|
||||
plan_id: "free",
|
||||
plan_name: "免费版",
|
||||
status: "active",
|
||||
billing_cycle: "monthly",
|
||||
current_period_start: new Date(Date.now() - 30 * 86400_000).toISOString(),
|
||||
current_period_end: new Date(Date.now() + 30 * 86400_000).toISOString(),
|
||||
amount: 0,
|
||||
auto_renew: false,
|
||||
created_at: new Date(Date.now() - 30 * 86400_000).toISOString(),
|
||||
}
|
||||
|
||||
/** 获取账单记录列表 */
|
||||
const MOCK_PLANS: SubscriptionPlan[] = [
|
||||
{
|
||||
plan_id: "free",
|
||||
name: "免费版",
|
||||
price_cents: 0,
|
||||
monthly_price_cents: 0,
|
||||
duration_days: 0,
|
||||
points_discount: 1,
|
||||
features: { max_resolution: "720p", free_clips_daily: 3 },
|
||||
},
|
||||
{
|
||||
plan_id: "monthly",
|
||||
name: "月度会员",
|
||||
price_cents: 1990,
|
||||
monthly_price_cents: 1990,
|
||||
duration_days: 30,
|
||||
points_discount: 0.9,
|
||||
features: { max_resolution: "1080p", free_clips_daily: 10 },
|
||||
},
|
||||
{
|
||||
plan_id: "quarterly",
|
||||
name: "季度会员",
|
||||
price_cents: 3990,
|
||||
monthly_price_cents: 1330,
|
||||
duration_days: 90,
|
||||
points_discount: 0.85,
|
||||
features: { max_resolution: "1080p", free_clips_daily: 15 },
|
||||
},
|
||||
{
|
||||
plan_id: "yearly",
|
||||
name: "年度会员",
|
||||
price_cents: 15900,
|
||||
monthly_price_cents: 1325,
|
||||
duration_days: 365,
|
||||
points_discount: 0.8,
|
||||
features: { max_resolution: "4k", free_clips_daily: 30 },
|
||||
},
|
||||
]
|
||||
|
||||
const MOCK_BILLING: BillingRecord[] = []
|
||||
|
||||
const isMock = () => (process.env.POINTS_API_MOCK as string | undefined) === "true"
|
||||
|
||||
/** 获取当前订阅 */
|
||||
export const getCurrentSubscription = async (): Promise<SubscriptionInfo> => {
|
||||
if (isMock()) {
|
||||
await new Promise((r) => setTimeout(r, MOCK_DELAY))
|
||||
return { ...MOCK_SUBSCRIPTION }
|
||||
}
|
||||
const { data } = await apiClient.get("/subscription/current")
|
||||
return data
|
||||
}
|
||||
|
||||
/** 获取所有订阅档位 */
|
||||
export const getSubscriptionPlans = async (): Promise<SubscriptionPlansResponse> => {
|
||||
if (isMock()) {
|
||||
await new Promise((r) => setTimeout(r, MOCK_DELAY))
|
||||
return { plans: MOCK_PLANS.map((p) => ({ ...p, features: { ...p.features } })) }
|
||||
}
|
||||
const { data } = await apiClient.get("/subscription/plans")
|
||||
return data
|
||||
}
|
||||
|
||||
/** 获取账单记录 */
|
||||
export const getBillingRecords = async (): Promise<BillingRecord[]> => {
|
||||
const response = await apiClient.get("/subscription/billing-records")
|
||||
return response.data
|
||||
if (isMock()) {
|
||||
await new Promise((r) => setTimeout(r, MOCK_DELAY))
|
||||
return MOCK_BILLING.map((r) => ({ ...r }))
|
||||
}
|
||||
const { data } = await apiClient.get("/subscription/billing-records")
|
||||
return data
|
||||
}
|
||||
|
||||
/** 升级/降级套餐 */
|
||||
export const changePlan = async (request: ChangePlanRequest): Promise<ChangePlanResponse> => {
|
||||
const response = await apiClient.post("/subscription/change-plan", request)
|
||||
return response.data
|
||||
if (isMock()) {
|
||||
await new Promise((r) => setTimeout(r, MOCK_DELAY * 2))
|
||||
const plan = MOCK_PLANS.find((p) => p.plan_id === request.target_plan_id)
|
||||
if (!plan) return { success: false, message: "套餐不存在" }
|
||||
const newSub: SubscriptionInfo = {
|
||||
...MOCK_SUBSCRIPTION,
|
||||
plan_id: plan.plan_id,
|
||||
plan_name: plan.name,
|
||||
billing_cycle: request.billing_cycle,
|
||||
amount: plan.price_cents,
|
||||
status: "pending",
|
||||
current_period_start: new Date().toISOString(),
|
||||
current_period_end: new Date(Date.now() + plan.duration_days * 86400_000).toISOString(),
|
||||
auto_renew: true,
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
message: "订阅变更成功(mock,支付通道待接入)",
|
||||
new_subscription: newSub,
|
||||
}
|
||||
}
|
||||
const { data } = await apiClient.post("/subscription/change-plan", request)
|
||||
return data
|
||||
}
|
||||
|
||||
/** 取消订阅 */
|
||||
export const cancelSubscription = async (): Promise<{
|
||||
success: boolean
|
||||
message: string
|
||||
}> => {
|
||||
const response = await apiClient.post("/subscription/cancel")
|
||||
return response.data
|
||||
/** 取消订阅(到期后失效) */
|
||||
export const cancelSubscription = async (): Promise<{ success: boolean; message: string }> => {
|
||||
if (isMock()) {
|
||||
await new Promise((r) => setTimeout(r, MOCK_DELAY))
|
||||
return { success: true, message: "已取消订阅,到期后将不再续费" }
|
||||
}
|
||||
const { data } = await apiClient.post("/subscription/cancel")
|
||||
return data
|
||||
}
|
||||
|
||||
/** 切换自动续费 */
|
||||
export const toggleAutoRenew = async (
|
||||
enabled: boolean,
|
||||
req: ToggleAutoRenewRequest,
|
||||
): Promise<{ success: boolean; message: string }> => {
|
||||
const response = await apiClient.post("/subscription/toggle-auto-renew", {
|
||||
enabled,
|
||||
})
|
||||
return response.data
|
||||
if (isMock()) {
|
||||
await new Promise((r) => setTimeout(r, MOCK_DELAY))
|
||||
return { success: true, message: req.enabled ? "已开启自动续费" : "已关闭自动续费" }
|
||||
}
|
||||
const { data } = await apiClient.post("/subscription/toggle-auto-renew", req)
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -1,65 +1,115 @@
|
||||
/**
|
||||
* 订阅相关类型定义
|
||||
* 订阅/会员类型定义
|
||||
* 对齐后端 staging 实测最终契约(2026-09-16)
|
||||
*
|
||||
* Base path: /api/v1/
|
||||
*/
|
||||
|
||||
/** 套餐类型 */
|
||||
export type PlanType = "free" | "standard" | "pro" | "enterprise"
|
||||
|
||||
/** 订阅状态 */
|
||||
export type SubscriptionStatus = "active" | "expired" | "cancelled" | "trial"
|
||||
|
||||
/** 账单状态 */
|
||||
export type BillingStatus = "paid" | "pending" | "failed" | "refunded"
|
||||
/** 订阅计划 ID */
|
||||
export type PlanId = "free" | "monthly" | "quarterly" | "yearly"
|
||||
|
||||
/** 计费周期 */
|
||||
export type BillingCycle = "monthly" | "yearly"
|
||||
|
||||
/** 套餐信息 */
|
||||
export interface Plan {
|
||||
id: PlanType
|
||||
name: string
|
||||
price: number | null
|
||||
yearly_price?: number | null
|
||||
description: string
|
||||
recommended: boolean
|
||||
features: string[]
|
||||
}
|
||||
/** 订阅状态 */
|
||||
export type SubscriptionStatus = "active" | "expired" | "cancelled" | "pending"
|
||||
|
||||
/** 当前订阅信息 */
|
||||
/** 账单状态 */
|
||||
export type BillingStatus = "paid" | "pending" | "failed" | "refunded"
|
||||
|
||||
/* ================================================================
|
||||
* 当前订阅(GET /subscription/current)
|
||||
* ================================================================ */
|
||||
export interface SubscriptionInfo {
|
||||
id: string
|
||||
plan_id: PlanType
|
||||
plan_id: PlanId
|
||||
plan_name: string
|
||||
status: SubscriptionStatus
|
||||
/** 当前计费周期:monthly 对月卡/季卡按自然月续费;yearly 对年卡 */
|
||||
billing_cycle: BillingCycle
|
||||
current_period_start: string
|
||||
current_period_end: string
|
||||
/** 本期金额(分) */
|
||||
amount: number
|
||||
auto_renew: boolean
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/** 账单记录 */
|
||||
/* ================================================================
|
||||
* 订阅计划(GET /subscription/plans)
|
||||
* ================================================================ */
|
||||
export interface SubscriptionPlan {
|
||||
plan_id: PlanId
|
||||
/** 中文名 */
|
||||
name: string
|
||||
/** 价格(分),年卡/季卡为总价 */
|
||||
price_cents: number
|
||||
/** 折算月价(分),对比用 */
|
||||
monthly_price_cents: number
|
||||
/** 时长(天) */
|
||||
duration_days: number
|
||||
/** 积分折扣(0.9 = 9折,1 = 无折扣) */
|
||||
points_discount: number
|
||||
features: {
|
||||
max_resolution: string
|
||||
free_clips_daily: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
}
|
||||
|
||||
export interface SubscriptionPlansResponse {
|
||||
plans: SubscriptionPlan[]
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 账单(GET /subscription/billing-records)
|
||||
* ================================================================ */
|
||||
export interface BillingRecord {
|
||||
id: string
|
||||
plan_name: string
|
||||
amount: number
|
||||
billing_cycle: BillingCycle
|
||||
/** 订单类型:subscribe/renew/upgrade/refund */
|
||||
order_type: string
|
||||
plan_id: PlanId
|
||||
/** 金额(分) */
|
||||
amount_cents: number
|
||||
status: BillingStatus
|
||||
payment_method: string
|
||||
created_at: string
|
||||
invoice_url?: string
|
||||
paid_at?: string
|
||||
}
|
||||
|
||||
/** 升级/降级请求 */
|
||||
/* ================================================================
|
||||
* 变更/取消/开关自动续费
|
||||
* ================================================================ */
|
||||
export interface ChangePlanRequest {
|
||||
target_plan_id: PlanType
|
||||
target_plan_id: PlanId
|
||||
billing_cycle: BillingCycle
|
||||
}
|
||||
|
||||
/** 升级/降级响应 */
|
||||
export interface ChangePlanResponse {
|
||||
success: boolean
|
||||
message: string
|
||||
new_subscription?: SubscriptionInfo
|
||||
}
|
||||
|
||||
export interface ToggleAutoRenewRequest {
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
* 中文标签映射
|
||||
* ================================================================ */
|
||||
export const PLAN_LABEL: Record<PlanId, string> = {
|
||||
free: "免费版",
|
||||
monthly: "月度会员",
|
||||
quarterly: "季度会员",
|
||||
yearly: "年度会员",
|
||||
}
|
||||
|
||||
export const BILLING_CYCLE_LABEL: Record<BillingCycle, string> = {
|
||||
monthly: "月付",
|
||||
yearly: "年付",
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated 旧命名保留别名,新代码请直接用 PlanId
|
||||
*/
|
||||
export type PlanType = PlanId
|
||||
|
||||
@@ -85,9 +85,13 @@ export async function batchDeleteEditPlanClips(
|
||||
return response.data
|
||||
}
|
||||
|
||||
/** 从素材批量创建片段(追加到时间线末尾) */
|
||||
/**
|
||||
* 从素材批量创建片段(追加到时间线末尾)。
|
||||
* #1921 修复:templateId 为空时调用新端点 POST /clips/from-assets,避免拼出双斜杠
|
||||
* `/templates//editor/clips/from-assets` 导致 404;有 templateId 时保持原路径向后兼容。
|
||||
*/
|
||||
export async function createClipsFromAssets(
|
||||
templateId: string,
|
||||
templateId: string | undefined | null,
|
||||
assetIds: string[],
|
||||
clipType = "main",
|
||||
requiredClipsCount?: number,
|
||||
@@ -100,16 +104,15 @@ export async function createClipsFromAssets(
|
||||
if (requiredClipsCount !== undefined) {
|
||||
body.required_clips_count = requiredClipsCount
|
||||
}
|
||||
// 新端点(#1921):templateId 为空时,body 不传 template_id,由后端兜底创建默认模板
|
||||
const hasTid = !!templateId
|
||||
const url = hasTid ? `/templates/${templateId}/editor/clips/from-assets` : "/clips/from-assets"
|
||||
// from-assets 后端会调用 MediaKit 智能选片(最长 60s),单独延长超时
|
||||
const response = await apiClient.post<ClipsFromAssetsResponse>(
|
||||
`/templates/${templateId}/editor/clips/from-assets`,
|
||||
body,
|
||||
{
|
||||
timeout: 60000,
|
||||
signal: opts?.signal,
|
||||
// _silentErrorToast 由 api/client.ts 响应拦截器读取(抑制全局错误 toast,#1777)
|
||||
...(opts?.silentErrorToast ? ({ _silentErrorToast: true } as Record<string, unknown>) : {}),
|
||||
},
|
||||
)
|
||||
const response = await apiClient.post<ClipsFromAssetsResponse>(url, body, {
|
||||
timeout: 60000,
|
||||
signal: opts?.signal,
|
||||
// _silentErrorToast 由 api/client.ts 响应拦截器读取(抑制全局错误 toast,#1777)
|
||||
...(opts?.silentErrorToast ? ({ _silentErrorToast: true } as Record<string, unknown>) : {}),
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
/* Header 积分徽章 & Popover 样式 */
|
||||
.xx-points-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 12px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border-color, #e5e7eb);
|
||||
background: var(--bg-tertiary, #fafafa);
|
||||
color: var(--text-secondary, #6b7280);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
line-height: 1;
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
.xx-points-badge:hover {
|
||||
border-color: var(--primary-color, #6366f1);
|
||||
color: var(--primary-color, #6366f1);
|
||||
background: var(--primary-soft, #eef2ff);
|
||||
}
|
||||
|
||||
.xx-points-badge.zero {
|
||||
color: #faad14;
|
||||
border-color: #ffe58f;
|
||||
background: #fffbe6;
|
||||
}
|
||||
|
||||
.xx-points-badge.low {
|
||||
color: #fa8c16;
|
||||
border-color: #ffd591;
|
||||
background: #fff7e6;
|
||||
}
|
||||
|
||||
.xx-points-badge-icon {
|
||||
font-size: 14px;
|
||||
color: #8b5cf6;
|
||||
}
|
||||
|
||||
.xx-points-badge.zero .xx-points-badge-icon,
|
||||
.xx-points-badge.low .xx-points-badge-icon {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.xx-points-badge-val {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* Popover */
|
||||
.xx-points-popover {
|
||||
width: 260px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.xx-points-popover-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.xx-points-popover-balance {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.xx-points-icon {
|
||||
color: #8b5cf6;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.xx-points-value {
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
color: var(--text-primary, #111827);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.xx-points-unit {
|
||||
color: var(--text-secondary, #6b7280);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.xx-points-warn {
|
||||
margin: 0 !important;
|
||||
padding: 8px 10px;
|
||||
background: #fffbe6;
|
||||
border-radius: var(--radius-sm, 6px);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.xx-points-expire {
|
||||
font-size: 12px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.xx-points-popover-stats {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
padding: 10px;
|
||||
background: var(--bg-tertiary, #fafafa);
|
||||
border-radius: var(--radius-sm, 6px);
|
||||
}
|
||||
|
||||
.xx-points-stat-val {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary, #111827);
|
||||
margin-top: 2px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Header 右上角积分徽章
|
||||
* - 余额 <10 时橙色告警
|
||||
* - 点击弹出 Popover:余额、会员信息、充值入口、积分明细入口
|
||||
*
|
||||
* 字段对齐新契约:
|
||||
* - balance.is_member / balance.member_type 保留但降级;推荐用 membership.member_type
|
||||
* - 免费额度、会员 max_resolution 在 popover 展示
|
||||
*/
|
||||
import React, { useEffect } from "react"
|
||||
import { Popover, Button, Tag, Space, Typography, Badge } from "antd"
|
||||
import {
|
||||
ThunderboltOutlined,
|
||||
CrownOutlined,
|
||||
RightOutlined,
|
||||
WarningOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { usePointsStore } from "@/store/pointsStore"
|
||||
import "./PointsBadge.css"
|
||||
|
||||
const { Text, Paragraph } = Typography
|
||||
|
||||
const MEMBER_LABEL: Record<string, string> = {
|
||||
monthly: "月卡会员",
|
||||
quarterly: "季卡会员",
|
||||
yearly: "年卡会员",
|
||||
}
|
||||
|
||||
const PointsBadge: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const { balance, membership, subscription, dailyUsage, init, loading } = usePointsStore()
|
||||
|
||||
useEffect(() => {
|
||||
if (!balance) init()
|
||||
}, [balance, init])
|
||||
|
||||
// 余额:优先用 membership.points_balance(冗余字段),降级 balance.balance
|
||||
const bal = membership?.points_balance ?? balance?.balance ?? 0
|
||||
const lowBalance = bal > 0 && bal < 10
|
||||
const zero = bal === 0
|
||||
const isMember = membership?.is_member ?? balance?.is_member ?? false
|
||||
const memberKey =
|
||||
membership?.member_type ??
|
||||
(subscription?.plan_id && subscription.plan_id !== "free" ? subscription.plan_id : null)
|
||||
const memberLabel = memberKey ? MEMBER_LABEL[memberKey] || "付费会员" : "免费会员"
|
||||
const maxRes = membership?.max_resolution
|
||||
|
||||
const freeRemain = dailyUsage?.free_clips_remaining ?? 0
|
||||
|
||||
const popContent = (
|
||||
<div className="xx-points-popover">
|
||||
<div className="xx-points-popover-top">
|
||||
<div className="xx-points-popover-balance">
|
||||
<ThunderboltOutlined className="xx-points-icon" />
|
||||
<span className="xx-points-value">{loading ? "…" : bal}</span>
|
||||
<span className="xx-points-unit">积分</span>
|
||||
</div>
|
||||
<Tag color={isMember ? "gold" : "default"} icon={<CrownOutlined />}>
|
||||
{memberLabel}
|
||||
</Tag>
|
||||
</div>
|
||||
|
||||
{(zero || lowBalance) && (
|
||||
<Paragraph type="warning" className="xx-points-warn">
|
||||
<WarningOutlined /> 积分不足,充值后可继续使用 AI 功能
|
||||
</Paragraph>
|
||||
)}
|
||||
|
||||
{!isMember && dailyUsage && freeRemain > 0 && (
|
||||
<Text type="secondary" className="xx-points-expire">
|
||||
今日剩余免费次数:{freeRemain}/{dailyUsage.free_clips_limit}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{balance?.member_expires_at && isMember && (
|
||||
<Text type="secondary" className="xx-points-expire">
|
||||
会员到期:{new Date(balance.member_expires_at).toLocaleDateString("zh-CN")}
|
||||
{maxRes ? ` · ${maxRes}` : ""}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<div className="xx-points-popover-stats">
|
||||
<div>
|
||||
<Text type="secondary">累计获得</Text>
|
||||
<div className="xx-points-stat-val">+{balance?.total_earned ?? 0}</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text type="secondary">累计消耗</Text>
|
||||
<div className="xx-points-stat-val">-{balance?.total_spent ?? 0}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Space direction="vertical" style={{ width: "100%" }} size={8}>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<ThunderboltOutlined />}
|
||||
block
|
||||
onClick={() => navigate("/points/recharge")}
|
||||
>
|
||||
充值积分
|
||||
</Button>
|
||||
<Button block onClick={() => navigate("/points/transactions")}>
|
||||
积分明细
|
||||
<RightOutlined />
|
||||
</Button>
|
||||
{!isMember && (
|
||||
<Button block type="link" onClick={() => navigate("/subscription")}>
|
||||
<CrownOutlined /> 升级会员享折扣
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<Popover content={popContent} placement="bottomRight" trigger="click" arrow={false}>
|
||||
<button
|
||||
type="button"
|
||||
className={`xx-points-badge ${zero ? "zero" : lowBalance ? "low" : ""}`}
|
||||
>
|
||||
<Badge dot={zero} color={zero ? "#faad14" : undefined}>
|
||||
<ThunderboltOutlined className="xx-points-badge-icon" />
|
||||
</Badge>
|
||||
<span className="xx-points-badge-val">{loading ? "…" : bal}</span>
|
||||
</button>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
export default PointsBadge
|
||||
@@ -0,0 +1,67 @@
|
||||
/* 功能按钮旁的积分消耗提示 */
|
||||
.xx-points-cost {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary, #6b7280);
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.xx-points-cost.free,
|
||||
.xx-points-cost.free-quota {
|
||||
color: #10b981;
|
||||
}
|
||||
|
||||
.xx-points-cost.insufficient {
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.xx-points-gem {
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.xx-points-num {
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.xx-points-unit-label {
|
||||
color: var(--text-tertiary, #9ca3af);
|
||||
}
|
||||
|
||||
.xx-points-tag-free {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
background: #d1fae5;
|
||||
color: #059669;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.xx-points-free-user-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
background: #fef3c7;
|
||||
color: #d97706;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.xx-points-desc {
|
||||
color: var(--text-tertiary, #9ca3af);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.xx-points-warn-icon {
|
||||
color: #ef4444;
|
||||
margin-left: 2px;
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* 功能操作按钮旁的"消耗积分"提示
|
||||
* 例:[生成配音] 💎 -1 积分
|
||||
* - 根据 scene_key 自动读取规则(来自 store.rules)
|
||||
* - 免费用户自动计算 ×free_user_multiplier 向上取整
|
||||
* - 会员 floor(base × points_discount)
|
||||
* - 余额不足时显示红色告警 + 充值提示
|
||||
*
|
||||
* 字段对齐新契约:
|
||||
* - rule.points_per_use → base_points
|
||||
* - balance.free_clips_remaining → dailyUsage.free_clips_remaining
|
||||
* - props.units → 保留兼容,新代码优先用 quantity
|
||||
*/
|
||||
import React, { useMemo } from "react"
|
||||
import { Tooltip } from "antd"
|
||||
import { WarningOutlined } from "@ant-design/icons"
|
||||
import { usePointsStore } from "@/store/pointsStore"
|
||||
import type { PointsSource } from "@/api/points/types"
|
||||
import "./PointsCost.css"
|
||||
|
||||
interface Props {
|
||||
/** 消耗场景 key */
|
||||
scene: PointsSource
|
||||
/** 数量(新字段),默认 1 */
|
||||
quantity?: number
|
||||
/** 预计时长(分钟),可选 */
|
||||
durationMinutes?: number
|
||||
/** 是否显示为紧凑模式(仅图标+数字,不显示单位文字) */
|
||||
compact?: boolean
|
||||
/** 余额不足时,是否显示充值提示 */
|
||||
showRechargeHint?: boolean
|
||||
/** 自定义 class */
|
||||
className?: string
|
||||
/**
|
||||
* @deprecated 旧字段保留兼容,内部映射为 quantity
|
||||
*/
|
||||
units?: number
|
||||
}
|
||||
|
||||
/** 单位中文 */
|
||||
const UNIT_LABEL: Record<string, string> = {
|
||||
分钟: "分钟",
|
||||
条: "条",
|
||||
次: "次",
|
||||
张: "张",
|
||||
}
|
||||
|
||||
const PointsCost: React.FC<Props> = ({
|
||||
scene,
|
||||
quantity,
|
||||
units,
|
||||
durationMinutes,
|
||||
compact = false,
|
||||
showRechargeHint = true,
|
||||
className = "",
|
||||
}) => {
|
||||
const { balance, dailyUsage, rules, membership } = usePointsStore()
|
||||
const qty = quantity ?? units ?? 1
|
||||
|
||||
const { cost, isFreeQuota, rule, isFreeUser, insufficient, freeRemain } = useMemo(() => {
|
||||
const isMem = membership?.is_member ?? balance?.is_member ?? false
|
||||
if (!rules || !balance) {
|
||||
return {
|
||||
cost: 0,
|
||||
isFreeQuota: false,
|
||||
rule: null,
|
||||
isFreeUser: !isMem,
|
||||
insufficient: false,
|
||||
freeRemain: 0,
|
||||
}
|
||||
}
|
||||
const rule = rules.rules.find((r) => r.scene_key === scene)
|
||||
if (!rule)
|
||||
return {
|
||||
cost: 0,
|
||||
isFreeQuota: false,
|
||||
rule: null,
|
||||
isFreeUser: !isMem,
|
||||
insufficient: false,
|
||||
freeRemain: 0,
|
||||
}
|
||||
// 免费训练不扣费
|
||||
if (rule.base_points === 0) {
|
||||
return {
|
||||
cost: 0,
|
||||
isFreeQuota: false,
|
||||
rule,
|
||||
isFreeUser: !isMem,
|
||||
insufficient: false,
|
||||
freeRemain: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// 计算 base
|
||||
let baseCost: number
|
||||
if (scene === "ai_video" && rule.extra_per_30s) {
|
||||
const minutes = durationMinutes ?? qty
|
||||
const segments = Math.max(1, Math.ceil(minutes * 2))
|
||||
baseCost = rule.base_points + rule.extra_per_30s * (segments - 1)
|
||||
} else {
|
||||
baseCost = rule.base_points * Math.max(1, qty)
|
||||
}
|
||||
|
||||
// 非会员 + 今日免费额度 → 免费
|
||||
const freeRemain = dailyUsage?.free_clips_remaining ?? 0
|
||||
const isFree = scene === "ai_video" && !isMem && freeRemain > 0
|
||||
|
||||
const multiplier = rules.free_user_multiplier ?? 1.15
|
||||
const cost = isFree ? 0 : isMem ? Math.floor(baseCost) : Math.ceil(baseCost * multiplier)
|
||||
const insufficient = !isFree && balance.balance < cost
|
||||
return {
|
||||
cost,
|
||||
isFreeQuota: isFree,
|
||||
rule,
|
||||
isFreeUser: !isMem,
|
||||
insufficient,
|
||||
freeRemain,
|
||||
}
|
||||
}, [rules, balance, dailyUsage, membership, scene, qty, durationMinutes])
|
||||
|
||||
if (!rule || !balance) {
|
||||
return <span className={`xx-points-cost ${className}`} />
|
||||
}
|
||||
|
||||
if (rule.base_points === 0) {
|
||||
return (
|
||||
<span className={`xx-points-cost free ${className}`}>
|
||||
<span className="xx-points-tag-free">免费</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
if (isFreeQuota) {
|
||||
return (
|
||||
<Tooltip title={`今日免费额度剩余 ${freeRemain} 条,不扣积分`}>
|
||||
<span className={`xx-points-cost free-quota ${className}`}>
|
||||
<span className="xx-points-tag-free">免费</span>
|
||||
{!compact && <span className="xx-points-desc">(今日剩余 {freeRemain} 条)</span>}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
const unitLabel = compact
|
||||
? ""
|
||||
: `/${qty > 1 ? `${qty}${UNIT_LABEL[rule.unit] ?? rule.unit}` : rule.unit}`
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`xx-points-cost ${insufficient ? "insufficient" : ""} ${isFreeUser ? "free-user" : ""} ${className}`}
|
||||
>
|
||||
<span className="xx-points-gem">💎</span>
|
||||
<span className="xx-points-num">-{cost}</span>
|
||||
{unitLabel && <span className="xx-points-unit-label">积分{unitLabel}</span>}
|
||||
{isFreeUser && !compact && (
|
||||
<Tooltip title={`免费用户消耗 ×${rules?.free_user_multiplier ?? 1.15},开通会员享标准价`}>
|
||||
<span className="xx-points-free-user-tag">非会员</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{insufficient && showRechargeHint && (
|
||||
<Tooltip title={`积分不足,需 ${cost} 积分,当前余额 ${balance.balance}`}>
|
||||
<WarningOutlined className="xx-points-warn-icon" />
|
||||
</Tooltip>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export default PointsCost
|
||||
@@ -1,4 +1,5 @@
|
||||
/* Phase 1 Header 样式 + 手机端适配 */
|
||||
/* Phase 1 Header 样式 + 手机端适配
|
||||
v2: 增加积分徽章、升级按钮、会员金冠 */
|
||||
.xx-top-nav {
|
||||
height: 68px;
|
||||
position: sticky;
|
||||
@@ -77,10 +78,40 @@
|
||||
.xx-right-section {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
gap: 10px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* v2: 顶部积分徽章 */
|
||||
.xx-header-points {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* v2: 升级会员按钮 */
|
||||
.xx-upgrade-btn {
|
||||
background: linear-gradient(135deg, #f59e0b, #ef4444);
|
||||
border: none;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3);
|
||||
}
|
||||
|
||||
.xx-upgrade-btn:hover {
|
||||
background: linear-gradient(135deg, #d97706, #dc2626) !important;
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
/* v2: 会员金冠按钮 */
|
||||
.xx-crown-btn {
|
||||
font-weight: 700;
|
||||
color: #d97706;
|
||||
padding: 2px 8px;
|
||||
}
|
||||
|
||||
.xx-crown-btn:hover {
|
||||
background: rgba(245, 158, 11, 0.1) !important;
|
||||
color: #b45309 !important;
|
||||
}
|
||||
|
||||
.xx-user-menu {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -115,6 +146,29 @@
|
||||
gap: var(--space-xs);
|
||||
}
|
||||
|
||||
/* v2: 手机端积分/会员行 */
|
||||
.xx-mobile-points-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 8px 4px 16px;
|
||||
margin-bottom: 12px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.xx-mobile-member-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: #d97706;
|
||||
background: #fef3c7;
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.xx-mobile-nav-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -157,6 +211,7 @@
|
||||
|
||||
.xx-top-nav-inner {
|
||||
padding: 0 12px;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.xx-brand-text {
|
||||
@@ -177,6 +232,19 @@
|
||||
.xx-username {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* 手机端:缩小升级按钮文字 */
|
||||
.xx-upgrade-btn {
|
||||
padding: 0 8px !important;
|
||||
font-size: 12px !important;
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
.xx-crown-btn {
|
||||
padding: 0 4px !important;
|
||||
font-size: 12px !important;
|
||||
height: 28px;
|
||||
}
|
||||
}
|
||||
|
||||
/* 小屏幕平板:导航文字缩小 */
|
||||
@@ -188,4 +256,14 @@
|
||||
.xx-nav-links button {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.xx-header-points {
|
||||
transform: scale(0.9);
|
||||
transform-origin: center;
|
||||
}
|
||||
|
||||
.xx-upgrade-btn {
|
||||
font-size: 12px !important;
|
||||
padding: 0 10px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
/**
|
||||
* Phase 1 Header 重构
|
||||
* 扁平化导航菜单 + 手机端汉堡菜单
|
||||
* v2: 增加积分徽章、升级会员入口、我的积分入口
|
||||
*/
|
||||
import React, { useState } from "react"
|
||||
import { Avatar, Dropdown, Drawer, Space } from "antd"
|
||||
import { LogoutOutlined, SettingOutlined, UserOutlined, MenuOutlined } from "@ant-design/icons"
|
||||
import React, { useEffect, useState } from "react"
|
||||
import { Avatar, Badge, Button, Dropdown, Drawer, Space, Tooltip } from "antd"
|
||||
import {
|
||||
LogoutOutlined,
|
||||
SettingOutlined,
|
||||
UserOutlined,
|
||||
MenuOutlined,
|
||||
CrownFilled,
|
||||
ThunderboltOutlined,
|
||||
HistoryOutlined,
|
||||
WalletOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import { useLocation, useNavigate } from "react-router-dom"
|
||||
import { useAuthStore } from "@/store/authStore"
|
||||
import { useLogout } from "@/hooks/useAuth"
|
||||
import type { MenuProps } from "antd"
|
||||
import { NAV_ITEMS } from "@/config/navigation"
|
||||
import PointsBadge from "@/components/common/PointsBadge"
|
||||
import { usePointsStore } from "@/store/pointsStore"
|
||||
import "./Header.css"
|
||||
|
||||
const Header: React.FC = () => {
|
||||
@@ -19,6 +31,18 @@ const Header: React.FC = () => {
|
||||
const logoutMutation = useLogout()
|
||||
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
|
||||
|
||||
// 积分与会员状态
|
||||
const { balance, init } = usePointsStore()
|
||||
useEffect(() => {
|
||||
init()
|
||||
// 每 60s 刷新一次(余额可能变化)
|
||||
const t = setInterval(() => init(), 60_000)
|
||||
return () => clearInterval(t)
|
||||
}, [init])
|
||||
|
||||
const isMember = !!balance?.is_member
|
||||
const memberType = balance?.member_type ?? null
|
||||
|
||||
/** 用户下拉菜单 */
|
||||
const menuItems: MenuProps["items"] = [
|
||||
{
|
||||
@@ -33,6 +57,30 @@ const Header: React.FC = () => {
|
||||
label: "订阅管理",
|
||||
onClick: () => navigate("/app/subscription"),
|
||||
},
|
||||
// v2: 我的积分入口
|
||||
{
|
||||
key: "points-center",
|
||||
icon: <ThunderboltOutlined />,
|
||||
label: (
|
||||
<Space>
|
||||
我的积分
|
||||
{balance && <span style={{ color: "#8b5cf6", fontWeight: 700 }}>{balance.balance}</span>}
|
||||
</Space>
|
||||
),
|
||||
onClick: () => navigate("/app/points"),
|
||||
},
|
||||
{
|
||||
key: "points-history",
|
||||
icon: <HistoryOutlined />,
|
||||
label: "积分明细",
|
||||
onClick: () => navigate("/app/points/transactions"),
|
||||
},
|
||||
{
|
||||
key: "recharge",
|
||||
icon: <WalletOutlined />,
|
||||
label: "充值积分",
|
||||
onClick: () => navigate("/app/points/recharge"),
|
||||
},
|
||||
{ type: "divider" },
|
||||
{
|
||||
key: "logout",
|
||||
@@ -44,7 +92,6 @@ const Header: React.FC = () => {
|
||||
|
||||
/** 判断导航项是否激活 */
|
||||
const isActive = (path: string) => {
|
||||
// 首页特殊处理:/ 和 /app/dashboard 都算激活
|
||||
if (path === "/app/dashboard") {
|
||||
return (
|
||||
location.pathname === "/" ||
|
||||
@@ -78,6 +125,47 @@ const Header: React.FC = () => {
|
||||
</nav>
|
||||
|
||||
<div className="xx-right-section">
|
||||
{/* v2: 积分徽章(顶部显示) */}
|
||||
<PointsBadge />
|
||||
|
||||
{/* v2: 升级会员入口(仅免费用户显示) */}
|
||||
{!isMember && (
|
||||
<Tooltip title="升级会员解锁无限混剪、批量导出,积分 8 折起">
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<CrownFilled />}
|
||||
className="xx-upgrade-btn"
|
||||
onClick={() => navigate("/app/subscription")}
|
||||
>
|
||||
升级会员
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{/* v2: 付费会员显示金冠标识 */}
|
||||
{isMember && (
|
||||
<Tooltip
|
||||
title={`${memberType === "yearly" ? "年卡" : memberType === "quarterly" ? "季卡" : "月卡"}会员${
|
||||
balance?.member_expires_at
|
||||
? ` · 到期 ${new Date(balance.member_expires_at).toLocaleDateString("zh-CN")}`
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
<Badge dot color="gold">
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<CrownFilled style={{ color: "#f59e0b" }} />}
|
||||
className="xx-crown-btn"
|
||||
onClick={() => navigate("/app/subscription")}
|
||||
>
|
||||
{memberType === "yearly" ? "年卡" : memberType === "quarterly" ? "季卡" : "会员"}
|
||||
</Button>
|
||||
</Badge>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{/* 手机端汉堡菜单按钮 */}
|
||||
<button className="xx-hamburger" type="button" onClick={() => setMobileMenuOpen(true)}>
|
||||
<MenuOutlined />
|
||||
@@ -103,6 +191,31 @@ const Header: React.FC = () => {
|
||||
width={260}
|
||||
className="xx-mobile-drawer"
|
||||
>
|
||||
{/* 手机端积分/会员入口 */}
|
||||
{balance && (
|
||||
<div className="xx-mobile-points-row">
|
||||
<PointsBadge />
|
||||
{!isMember ? (
|
||||
<Button
|
||||
size="small"
|
||||
type="primary"
|
||||
icon={<CrownFilled />}
|
||||
onClick={() => {
|
||||
navigate("/app/subscription")
|
||||
setMobileMenuOpen(false)
|
||||
}}
|
||||
>
|
||||
升级
|
||||
</Button>
|
||||
) : (
|
||||
<span className="xx-mobile-member-tag">
|
||||
<CrownFilled style={{ color: "#f59e0b" }} />{" "}
|
||||
{memberType === "yearly" ? "年卡" : memberType === "quarterly" ? "季卡" : "月卡"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="xx-mobile-nav">
|
||||
{NAV_ITEMS.map((item) => (
|
||||
<button
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
ScanOutlined,
|
||||
ControlOutlined,
|
||||
CrownOutlined,
|
||||
ThunderboltOutlined,
|
||||
UnorderedListOutlined,
|
||||
UserOutlined,
|
||||
} from "@ant-design/icons"
|
||||
@@ -105,6 +106,18 @@ export const NAV_ITEMS: NavItem[] = [
|
||||
path: "/app/tasks",
|
||||
icon: React.createElement(UnorderedListOutlined),
|
||||
},
|
||||
{
|
||||
key: "subscription",
|
||||
label: "会员订阅",
|
||||
path: "/app/subscription",
|
||||
icon: React.createElement(CrownOutlined),
|
||||
},
|
||||
{
|
||||
key: "points",
|
||||
label: "积分中心",
|
||||
path: "/app/points",
|
||||
icon: React.createElement(ThunderboltOutlined),
|
||||
},
|
||||
]
|
||||
|
||||
/** 侧边栏导航分组(Sidebar 分组列表使用) */
|
||||
@@ -196,10 +209,16 @@ export const NAV_GROUPS: NavGroup[] = [
|
||||
},
|
||||
{
|
||||
key: "subscription",
|
||||
label: "订阅管理",
|
||||
label: "会员订阅",
|
||||
path: "/app/subscription",
|
||||
icon: React.createElement(CrownOutlined),
|
||||
},
|
||||
{
|
||||
key: "points",
|
||||
label: "积分中心",
|
||||
path: "/app/points",
|
||||
icon: React.createElement(ThunderboltOutlined),
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
@@ -28,13 +28,21 @@ import { useVariantVoicePreview } from "./hooks/useVariantVoicePreview"
|
||||
import { useTitleStyleUpdaters } from "./hooks/useStep4Title/useTitleStyleUpdaters"
|
||||
import { getAssetsByKind } from "@/api/assets"
|
||||
import { previewTts } from "@/api/tts"
|
||||
import { usePointsStore } from "@/store/pointsStore"
|
||||
import { hasEnoughPoints } from "./hooks/pointsCost"
|
||||
import "./generate.css"
|
||||
import "./generate-points.css"
|
||||
|
||||
const GeneratePage: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
|
||||
/* ── 表单状态 ── */
|
||||
const formState = useGenerateFormState()
|
||||
/* ── 积分状态 ── */
|
||||
const { balance, dailyUsage, rules, init: initPoints } = usePointsStore()
|
||||
useEffect(() => {
|
||||
initPoints()
|
||||
}, [initPoints])
|
||||
const {
|
||||
currentStep,
|
||||
setCurrentStep,
|
||||
@@ -348,6 +356,20 @@ const GeneratePage: React.FC = () => {
|
||||
|
||||
/* ── 步骤3「确认生成视频」:校验通过 → 创建正式生成任务 → 跳步骤4看实时进展 ── */
|
||||
const handleConfirmGenerate = useCallback(async () => {
|
||||
// 积分预检查
|
||||
const units = isBatch ? Math.max(selectedVariantIds.length, 1) : 1
|
||||
const check = hasEnoughPoints(
|
||||
balance ?? null,
|
||||
units,
|
||||
dailyUsage ?? null,
|
||||
[],
|
||||
"free",
|
||||
rules?.free_user_multiplier ?? 1.15,
|
||||
)
|
||||
if (!check.sufficient) {
|
||||
message.error(check.reason ?? "积分不足,请充值")
|
||||
return
|
||||
}
|
||||
if (isBatch) {
|
||||
if (selectedVariantIds.length === 0) {
|
||||
message.warning("请至少勾选一个视频")
|
||||
@@ -381,6 +403,9 @@ const GeneratePage: React.FC = () => {
|
||||
previewReady,
|
||||
handleGenerate,
|
||||
setCurrentStep,
|
||||
balance,
|
||||
dailyUsage,
|
||||
rules,
|
||||
])
|
||||
|
||||
/* ── 步骤导航 ── */
|
||||
@@ -404,6 +429,22 @@ const GeneratePage: React.FC = () => {
|
||||
return "xx-generate-layout full-width"
|
||||
}, [currentStep])
|
||||
|
||||
/* ── 积分消耗估算(步骤3确认生成展示用) ── */
|
||||
const unitsForCost = isBatch ? Math.max(selectedVariantIds.length, 1) : 1
|
||||
const pointsEstimate = useMemo(
|
||||
() =>
|
||||
hasEnoughPoints(
|
||||
balance ?? null,
|
||||
unitsForCost,
|
||||
dailyUsage ?? null,
|
||||
[],
|
||||
"free",
|
||||
rules?.free_user_multiplier ?? 1.15,
|
||||
),
|
||||
[unitsForCost, balance, dailyUsage, rules],
|
||||
)
|
||||
const insufficientPoints = !pointsEstimate.sufficient
|
||||
|
||||
/* ================================================================
|
||||
渲染
|
||||
================================================================ */
|
||||
@@ -607,6 +648,11 @@ const GeneratePage: React.FC = () => {
|
||||
generated={generated}
|
||||
generateError={generateError}
|
||||
selectedCount={isBatch ? selectedVariantIds.length : 1}
|
||||
estimatedCost={pointsEstimate.cost}
|
||||
freeClipsUsedThisTime={pointsEstimate.freeClipsUsed ?? 0}
|
||||
pointsInsufficient={insufficientPoints}
|
||||
insufficientReason={pointsEstimate.reason}
|
||||
onRecharge={() => navigate("/app/points/recharge")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
/**
|
||||
* 第5步「确认生成」— 批量渲染进度网格(Issue #1677)
|
||||
* 第5步「确认生成」— 批量渲染进度网格(Issue #1677 / #1800 布局修复)
|
||||
*
|
||||
* N 个正式生成任务各自独立卡片:进度条 / 成功成片播放 / 失败原因 + 单独重试。
|
||||
* 数据来自 useGenerateVideo 的 batchTasks(useGenerationPolling 实时回传)。
|
||||
*
|
||||
* #1800 修复点:
|
||||
* - 不再用 inline style 硬编码 grid 列宽 / 卡片 maxWidth,改由 CSS 统一控制
|
||||
* (便于响应式 + 避免 inline 覆盖类规则)。
|
||||
* - 标题图标 + 文本拆分为独立 span,文本 span 加 flex:1/min-width:0/ellipsis,
|
||||
* 防止长标题在窄列里溢出导致与相邻卡片进度条视觉重叠。
|
||||
*/
|
||||
import React from "react"
|
||||
import { LoadingOutlined, CheckCircleFilled, CloseCircleOutlined } from "@ant-design/icons"
|
||||
@@ -34,36 +40,34 @@ const BatchGenerationGrid: React.FC<BatchGenerationGridProps> = ({
|
||||
完成 {tasks.filter((t) => t.status === "completed").length} / {tasks.length}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className="xx-batch-gen-grid"
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fill, minmax(280px, 320px))",
|
||||
justifyContent: "center",
|
||||
justifyItems: "center",
|
||||
gap: 14,
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
{/* #1800: grid 列宽 / gap / justify 全部交由 .xx-batch-gen-grid CSS 控制 */}
|
||||
<div className="xx-batch-gen-grid">
|
||||
{sorted.map((task) => {
|
||||
const title = titles[task.variantIndex] || `视频 ${task.variantIndex + 1}`
|
||||
const video = (task.videos?.[0] || null) as GeneratedVideo | null
|
||||
return (
|
||||
<div
|
||||
key={task.taskId}
|
||||
className={`xx-batch-gen-card status-${task.status}`}
|
||||
style={{ maxWidth: 320 }}
|
||||
>
|
||||
<div key={task.taskId} className={`xx-batch-gen-card status-${task.status}`}>
|
||||
<div className="xx-batch-gen-card-head">
|
||||
<span className="xx-batch-gen-card-title" title={title}>
|
||||
{task.status === "completed" ? (
|
||||
<CheckCircleFilled style={{ color: "#52c41a", marginRight: 6 }} />
|
||||
<CheckCircleFilled
|
||||
className="xx-batch-gen-card-icon"
|
||||
style={{ color: "#52c41a" }}
|
||||
/>
|
||||
) : task.status === "failed" ? (
|
||||
<CloseCircleOutlined style={{ color: "#ef4444", marginRight: 6 }} />
|
||||
<CloseCircleOutlined
|
||||
className="xx-batch-gen-card-icon"
|
||||
style={{ color: "#ef4444" }}
|
||||
/>
|
||||
) : (
|
||||
<LoadingOutlined style={{ color: "#1677ff", marginRight: 6 }} />
|
||||
<LoadingOutlined
|
||||
className="xx-batch-gen-card-icon"
|
||||
style={{ color: "#1677ff" }}
|
||||
/>
|
||||
)}
|
||||
视频 {task.variantIndex + 1}:{title}
|
||||
<span className="xx-batch-gen-card-title-text">
|
||||
视频 {task.variantIndex + 1}:{title}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,24 +1,37 @@
|
||||
/**
|
||||
* GeneratePage 步骤底部操作按钮(#1899 简化为 5 步)
|
||||
* GeneratePage 步骤底部操作按钮(5 步向导:素材→配音→标题→确认生成→封面)
|
||||
* v3: 修复 #1954 off-by-one —— 步骤4 单视频/批量生成完成后正确显示「下一步:选择封面」
|
||||
*
|
||||
* 步骤 1~2:上一步 / 下一步
|
||||
* 步骤 3(选择标题):「✨ 确认生成视频 / 确认生成 N 个视频」→ 创建正式生成任务,成功后跳步骤4
|
||||
* 步骤 4(确认生成):渲染进度页,全部完成后「下一步:选择封面」;仅上一步
|
||||
* 步骤 5(选择封面):仅上一步
|
||||
* 步骤 1~3:上一步 / 下一步
|
||||
* 步骤 4(确认生成/进度):未开始 →「✨ 确认生成视频」;生成中 →「⏳ 视频渲染中…」;
|
||||
* 失败 →「🔄 重新生成」;全部完成 →「下一步:选择封面 →」
|
||||
* 步骤 5(选择封面):仅上一步,无主按钮
|
||||
*/
|
||||
import React from "react"
|
||||
import { Tooltip } from "antd"
|
||||
import { ThunderboltOutlined, ExclamationCircleOutlined } from "@ant-design/icons"
|
||||
|
||||
export interface GenerateStepActionsProps {
|
||||
currentStep: number
|
||||
onPrev: () => void
|
||||
onNext: () => void
|
||||
/** 步骤3:确认生成视频(校验 + 创建渲染任务) */
|
||||
/** 步骤4:确认生成视频(校验 + 创建渲染任务) */
|
||||
onConfirmGenerate: () => void | Promise<void>
|
||||
generating: boolean
|
||||
generated: boolean
|
||||
generateError: string | null
|
||||
/** 批量模式下勾选的视频数量(N=1 时为1) */
|
||||
selectedCount?: number
|
||||
/** 本次预估消耗积分 */
|
||||
estimatedCost?: number
|
||||
/** 是否积分不足 */
|
||||
pointsInsufficient?: boolean
|
||||
/** 积分不足原因 */
|
||||
insufficientReason?: string
|
||||
/** 本次使用的免费混剪次数 */
|
||||
freeClipsUsedThisTime?: number
|
||||
/** 前往充值 */
|
||||
onRecharge?: () => void
|
||||
}
|
||||
|
||||
const GenerateStepActions: React.FC<GenerateStepActionsProps> = ({
|
||||
@@ -30,10 +43,15 @@ const GenerateStepActions: React.FC<GenerateStepActionsProps> = ({
|
||||
generated,
|
||||
generateError,
|
||||
selectedCount = 1,
|
||||
estimatedCost,
|
||||
pointsInsufficient,
|
||||
insufficientReason,
|
||||
freeClipsUsedThisTime,
|
||||
onRecharge,
|
||||
}) => {
|
||||
const renderPrimaryButton = () => {
|
||||
/* 步骤 1~2:上一步 / 下一步 */
|
||||
if (currentStep < 3) {
|
||||
/* 步骤 1~3:上一步 / 下一步 */
|
||||
if (currentStep < 4) {
|
||||
return (
|
||||
<button className="xx-btn xx-btn-primary" onClick={onNext}>
|
||||
下一步 →
|
||||
@@ -41,8 +59,29 @@ const GenerateStepActions: React.FC<GenerateStepActionsProps> = ({
|
||||
)
|
||||
}
|
||||
|
||||
/* 步骤 3:选择标题 — 确认生成 */
|
||||
if (currentStep === 3) {
|
||||
/* 步骤 4:确认生成 / 进度 / 完成进封面 */
|
||||
if (currentStep === 4) {
|
||||
// #1954 修复:单视频/批量 全部生成完成后显示「下一步:选择封面」
|
||||
if (generated && !generating && !generateError) {
|
||||
return (
|
||||
<button className="xx-btn xx-btn-primary" onClick={onNext}>
|
||||
下一步:选择封面 →
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
const costTag =
|
||||
typeof estimatedCost === "number" && estimatedCost > 0 ? (
|
||||
<span className="xx-step-cost-tag">
|
||||
<ThunderboltOutlined />
|
||||
{estimatedCost}
|
||||
</span>
|
||||
) : typeof estimatedCost === "number" &&
|
||||
estimatedCost === 0 &&
|
||||
typeof freeClipsUsedThisTime === "number" ? (
|
||||
<span className="xx-step-cost-tag free">使用 {freeClipsUsedThisTime} 次免费额度</span>
|
||||
) : null
|
||||
|
||||
if (generating) {
|
||||
return (
|
||||
<button className="xx-btn xx-btn-primary" disabled>
|
||||
@@ -54,28 +93,35 @@ const GenerateStepActions: React.FC<GenerateStepActionsProps> = ({
|
||||
return (
|
||||
<button className="xx-btn xx-btn-primary" onClick={onConfirmGenerate}>
|
||||
🔄 重新生成
|
||||
{costTag}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
if (pointsInsufficient) {
|
||||
return (
|
||||
<Tooltip title={insufficientReason ?? "积分不足,请充值"}>
|
||||
<span>
|
||||
<button className="xx-btn xx-btn-primary" disabled>
|
||||
<ExclamationCircleOutlined /> 积分不足
|
||||
{costTag}
|
||||
</button>
|
||||
{onRecharge && (
|
||||
<button
|
||||
className="xx-btn xx-btn-ghost"
|
||||
style={{ marginLeft: 8, color: "#7c3aed", borderColor: "#c4b5fd" }}
|
||||
onClick={onRecharge}
|
||||
>
|
||||
去充值 →
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<button className="xx-btn xx-btn-primary" onClick={onConfirmGenerate}>
|
||||
{selectedCount > 1 ? `✨ 确认生成 ${selectedCount} 个视频` : "✨ 确认生成视频"}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/* 步骤 4:确认生成进度页 — 全部完成后下一步进封面 */
|
||||
if (currentStep === 4) {
|
||||
if (generated) {
|
||||
return (
|
||||
<button className="xx-btn xx-btn-primary" onClick={onNext}>
|
||||
下一步:选择封面 →
|
||||
</button>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<button className="xx-btn xx-btn-primary" disabled>
|
||||
⏳ 视频渲染中…
|
||||
{costTag}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/* Points cost badge inside step actions button */
|
||||
.xx-step-cost-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: 8px;
|
||||
padding: 2px 8px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.xx-step-cost-tag.free {
|
||||
background: rgba(16, 185, 129, 0.2);
|
||||
color: #d1fae5;
|
||||
}
|
||||
|
||||
.xx-step-cost-warning {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 10px 14px;
|
||||
background: #fef3c7;
|
||||
border: 1px solid #fde68a;
|
||||
border-radius: 10px;
|
||||
color: #92400e;
|
||||
font-size: 13px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
@@ -3376,14 +3376,18 @@
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
第5步确认生成:批量渲染进度网格(Issue #1677)
|
||||
第5步确认生成:批量渲染进度网格(Issue #1677 / #1800 布局修复)
|
||||
- 列宽从 minmax(160,180) 放宽到 minmax(300,360),避免进度条/标题挤压
|
||||
- 卡片 width:100% 撑满列宽,避免 inline maxWidth 硬编码
|
||||
- 标题图标/文本拆分 flex 布局,文本 ellipsis 长标题不溢出
|
||||
============================================================ */
|
||||
.xx-batch-gen-grid {
|
||||
justify-items: center;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 180px));
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 360px));
|
||||
justify-content: center;
|
||||
justify-items: stretch;
|
||||
gap: 14px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card {
|
||||
@@ -3394,7 +3398,9 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card.status-completed {
|
||||
@@ -3410,14 +3416,30 @@
|
||||
.xx-batch-gen-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary, #1a1a1a);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card-icon {
|
||||
flex-shrink: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card-title-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
@@ -3427,6 +3449,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card-pct {
|
||||
@@ -3455,10 +3478,10 @@
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* ── 响应式:窄屏批量网格回退单列(.xx-canvas-grid 的窄屏限宽见网格定义处 #1741) ── */
|
||||
/* ── 响应式:窄屏批量网格回退单列 ── */
|
||||
@media (max-width: 960px) {
|
||||
.xx-batch-gen-grid {
|
||||
justify-items: center;
|
||||
grid-template-columns: minmax(0, 320px);
|
||||
grid-template-columns: minmax(0, 360px);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* 生成前积分消耗估算与余额校验
|
||||
* 用于步骤「确认生成」按钮前展示本次消耗,积分不足时禁用并提示充值
|
||||
*
|
||||
* 契约对齐(2026-09-16 最终版):
|
||||
* - balance 不再包含 free_clips_* 字段,免费额度通过 dailyUsage 传入
|
||||
* - 乘数逻辑:非会员 ceil(base × free_user_multiplier),会员 floor(base × points_discount)
|
||||
* - points_discount 从 subscription.plans.points_discount 获取(mock 阶段用 1 占位)
|
||||
*/
|
||||
import type { PointsBalance, DailyUsage } from "@/api/points/types"
|
||||
import type { SubscriptionPlan } from "@/api/subscription/types"
|
||||
|
||||
/** 生成单条视频基准积分(ai_video base_points=8,但向导默认使用短片段,先保守按 3 估算) */
|
||||
export const BASE_VIDEO_POINTS = 3
|
||||
|
||||
/** 默认免费用户倍率(后端 free_user_multiplier,mock 默认 1.15) */
|
||||
const DEFAULT_FREE_MULTIPLIER = 1.15
|
||||
|
||||
export interface HasEnoughPointsResult {
|
||||
sufficient: boolean
|
||||
cost: number
|
||||
reason?: string
|
||||
freeClipsUsed?: number
|
||||
freeClipsRemaining?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断积分是否充足(含每日免费额度)
|
||||
* @param balance 积分余额
|
||||
* @param videoCount 视频条数(批量模式下为 variant 数)
|
||||
* @param dailyUsage 每日免费额度(可选;不传视为 0)
|
||||
* @param plans 当前可用订阅计划列表(用于计算会员积分折扣;mock 传 [])
|
||||
* @param currentPlanId 当前用户 plan_id(free/monthly/quarterly/yearly)
|
||||
* @param freeMultiplier 免费用户倍率,默认 1.15
|
||||
*/
|
||||
export function hasEnoughPoints(
|
||||
balance: PointsBalance | null,
|
||||
videoCount: number,
|
||||
dailyUsage?: DailyUsage | null,
|
||||
plans: SubscriptionPlan[] = [],
|
||||
currentPlanId: string = "free",
|
||||
freeMultiplier: number = DEFAULT_FREE_MULTIPLIER,
|
||||
): HasEnoughPointsResult {
|
||||
if (!balance) {
|
||||
return { sufficient: true, cost: estimateGenerateCost(videoCount, 1) }
|
||||
}
|
||||
|
||||
const isMember = balance.is_member && currentPlanId !== "free"
|
||||
const plan = plans.find((p) => p.plan_id === currentPlanId)
|
||||
const multiplier = isMember ? (plan?.points_discount ?? 1) : freeMultiplier
|
||||
const raw = BASE_VIDEO_POINTS * videoCount * multiplier
|
||||
const cost = isMember ? Math.floor(raw) : Math.ceil(raw)
|
||||
|
||||
const freeRemain = dailyUsage?.free_clips_remaining ?? 0
|
||||
|
||||
// 非会员优先用每日免费额度
|
||||
if (!isMember && freeRemain > 0) {
|
||||
const freeUsed = Math.min(freeRemain, videoCount)
|
||||
const afterFree = videoCount - freeUsed
|
||||
const paidCost =
|
||||
afterFree === 0
|
||||
? 0
|
||||
: isMember
|
||||
? Math.floor(BASE_VIDEO_POINTS * afterFree * multiplier)
|
||||
: Math.ceil(BASE_VIDEO_POINTS * afterFree * multiplier)
|
||||
if (paidCost === 0) {
|
||||
return {
|
||||
sufficient: true,
|
||||
cost: 0,
|
||||
freeClipsUsed: freeUsed,
|
||||
freeClipsRemaining: freeRemain - freeUsed,
|
||||
}
|
||||
}
|
||||
if (balance.balance >= paidCost) {
|
||||
return {
|
||||
sufficient: true,
|
||||
cost: paidCost,
|
||||
freeClipsUsed: freeUsed,
|
||||
freeClipsRemaining: freeRemain - freeUsed,
|
||||
}
|
||||
}
|
||||
return {
|
||||
sufficient: false,
|
||||
cost: paidCost,
|
||||
reason: `积分不足:本次需 ${paidCost} 积分(已用 ${freeUsed} 次免费额度),当前余额 ${balance.balance},还差 ${paidCost - balance.balance} 积分`,
|
||||
freeClipsUsed: freeUsed,
|
||||
}
|
||||
}
|
||||
|
||||
if (balance.balance >= cost) return { sufficient: true, cost }
|
||||
return {
|
||||
sufficient: false,
|
||||
cost,
|
||||
reason: `积分不足:本次需 ${cost} 积分,当前余额 ${balance.balance},还差 ${cost - balance.balance} 积分`,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 估算生成任务的积分消耗(导出给 UI 直接使用)
|
||||
*/
|
||||
export function estimateGenerateCost(videoCount: number, multiplier = 1): number {
|
||||
return Math.ceil(BASE_VIDEO_POINTS * videoCount * multiplier)
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
/**
|
||||
* 积分中心主页(/points 或 /app/points)
|
||||
* 展示余额、会员信息、免费额度、快捷入口、最近流水
|
||||
*
|
||||
* 字段对齐新契约(2026-09-16):
|
||||
* - balance 不含 free_clips_*,从 dailyUsage 取
|
||||
* - subscription.member_type → plan_id(free/monthly/quarterly/yearly)
|
||||
* - subscription.member_type_name → 前端 PLAN_LABEL 映射
|
||||
*/
|
||||
import React, { useEffect } from "react"
|
||||
import {
|
||||
Card,
|
||||
Col,
|
||||
Row,
|
||||
Statistic,
|
||||
Button,
|
||||
Space,
|
||||
Tag,
|
||||
Typography,
|
||||
Progress,
|
||||
List,
|
||||
Avatar,
|
||||
Empty,
|
||||
} from "antd"
|
||||
import {
|
||||
ThunderboltOutlined,
|
||||
CrownFilled,
|
||||
ArrowUpOutlined,
|
||||
ArrowDownOutlined,
|
||||
HistoryOutlined,
|
||||
WalletOutlined,
|
||||
FileTextOutlined,
|
||||
InfoCircleOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import { usePointsStore } from "@/store/pointsStore"
|
||||
import { PLAN_LABEL } from "@/api/subscription/types"
|
||||
import "./Points.css"
|
||||
|
||||
const { Text } = Typography
|
||||
|
||||
const SOURCE_NAME: Record<string, string> = {
|
||||
recharge: "充值",
|
||||
task_reward: "任务奖励",
|
||||
ai_voice: "AI 配音",
|
||||
ai_digital_human: "AI 数字人",
|
||||
ai_video: "智能混剪",
|
||||
voice_clone_train: "声音克隆训练",
|
||||
voice_clone_synth: "声音克隆合成",
|
||||
douyin_extract: "抖音提取",
|
||||
ai_rewrite: "AI 改写",
|
||||
ai_title: "AI 标题",
|
||||
ai_cover: "AI 封面",
|
||||
sign_up: "注册赠送",
|
||||
bind_phone: "绑定手机",
|
||||
gift: "活动赠送",
|
||||
admin: "管理员调整",
|
||||
}
|
||||
|
||||
const sourceLabel = (src: string): string => {
|
||||
if (src.startsWith("refund:")) return `${SOURCE_NAME[src.slice(7)] || src.slice(7)}退款`
|
||||
return SOURCE_NAME[src] || src
|
||||
}
|
||||
|
||||
/** 会员标签:优先取 membership.member_type,降级 subscription.plan_id */
|
||||
const memberKey = (
|
||||
membership: { member_type: string | null } | null,
|
||||
subscription: { plan_id: string } | null,
|
||||
): string | null =>
|
||||
membership?.member_type ??
|
||||
(subscription?.plan_id && subscription.plan_id !== "free" ? subscription.plan_id : null)
|
||||
|
||||
const memberLabel = (
|
||||
membership: { member_type: string | null } | null,
|
||||
subscription: { plan_id: string; plan_name?: string } | null,
|
||||
): string => {
|
||||
const key = memberKey(membership, subscription)
|
||||
if (!key) return "免费会员"
|
||||
return PLAN_LABEL[key as keyof typeof PLAN_LABEL] || subscription?.plan_name || "付费会员"
|
||||
}
|
||||
|
||||
const PointsCenter: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const { balance, dailyUsage, membership, subscription, rules, init, loading } = usePointsStore()
|
||||
|
||||
useEffect(() => {
|
||||
init()
|
||||
}, [init])
|
||||
|
||||
const bal = membership?.points_balance ?? balance?.balance ?? 0
|
||||
const earned = balance?.total_earned ?? 0
|
||||
const spent = balance?.total_spent ?? 0
|
||||
const isMember = membership?.is_member ?? balance?.is_member ?? false
|
||||
|
||||
// 免费额度从 dailyUsage 取
|
||||
const freeUsed = dailyUsage?.free_clips_used ?? 0
|
||||
const freeLimit = dailyUsage?.free_clips_limit ?? (isMember ? 0 : 3)
|
||||
const freeRemain = dailyUsage?.free_clips_remaining ?? 0
|
||||
|
||||
// 最近流水 mock(后续可改为调用 getPointsTransactions(1,5))
|
||||
const recentTx = [
|
||||
{ type: "deduct" as const, source: "ai_voice", amount: 1, time: "今天 10:30" },
|
||||
{ type: "deduct" as const, source: "ai_video", amount: 3, time: "今天 09:15" },
|
||||
{ type: "add" as const, source: "recharge", amount: 100, time: "昨天" },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="xx-points-page">
|
||||
<PageHead
|
||||
title="积分中心"
|
||||
description="管理积分余额、查看流水、充值使用"
|
||||
actions={
|
||||
<Space>
|
||||
<Button icon={<FileTextOutlined />} onClick={() => navigate("/points/rules")}>
|
||||
积分规则
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<WalletOutlined />}
|
||||
onClick={() => navigate("/points/recharge")}
|
||||
>
|
||||
充值积分
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 顶部大卡 */}
|
||||
<Card className="xx-points-hero" bordered={false}>
|
||||
<Row gutter={24} align="middle">
|
||||
<Col xs={24} md={14}>
|
||||
<Space direction="vertical" size={8} style={{ width: "100%" }}>
|
||||
<Text type="secondary" style={{ color: "rgba(255,255,255,0.8)" }}>
|
||||
当前可用积分
|
||||
</Text>
|
||||
<div className="xx-points-hero-balance">
|
||||
<ThunderboltOutlined />
|
||||
<span>{loading ? "…" : bal.toLocaleString()}</span>
|
||||
</div>
|
||||
<Space size={8} wrap>
|
||||
{isMember ? (
|
||||
<Tag color="gold" icon={<CrownFilled />} style={{ padding: "4px 10px" }}>
|
||||
{memberLabel(membership, subscription)}
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag
|
||||
style={{
|
||||
padding: "4px 10px",
|
||||
background: "rgba(255,255,255,0.2)",
|
||||
color: "#fff",
|
||||
border: "none",
|
||||
}}
|
||||
>
|
||||
免费会员
|
||||
</Tag>
|
||||
)}
|
||||
{balance?.member_expires_at && isMember && (
|
||||
<Text style={{ color: "rgba(255,255,255,0.85)", fontSize: 12 }}>
|
||||
到期 {new Date(balance.member_expires_at).toLocaleDateString("zh-CN")}
|
||||
</Text>
|
||||
)}
|
||||
{membership?.max_resolution && isMember && (
|
||||
<Text style={{ color: "rgba(255,255,255,0.85)", fontSize: 12 }}>
|
||||
· {membership.max_resolution}
|
||||
</Text>
|
||||
)}
|
||||
{!isMember && (
|
||||
<Button
|
||||
size="small"
|
||||
type="primary"
|
||||
onClick={() => navigate("/subscription")}
|
||||
style={{ background: "#fff", color: "#7c3aed", borderColor: "#fff" }}
|
||||
>
|
||||
<CrownFilled /> 升级会员享折扣
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
</Space>
|
||||
</Col>
|
||||
<Col xs={24} md={10}>
|
||||
{/* 今日免费额度 */}
|
||||
{!isMember && freeLimit > 0 && (
|
||||
<div className="xx-points-free-quota">
|
||||
<div className="xx-points-free-title">
|
||||
<InfoCircleOutlined /> 今日免费混剪
|
||||
</div>
|
||||
<Progress
|
||||
percent={freeLimit > 0 ? Math.round((freeUsed / freeLimit) * 100) : 0}
|
||||
strokeColor={{ "0%": "#f59e0b", "100%": "#ef4444" }}
|
||||
format={() => `${freeUsed}/${freeLimit} 条`}
|
||||
/>
|
||||
<Text style={{ color: "rgba(255,255,255,0.8)", fontSize: 12 }}>
|
||||
剩余 {freeRemain} 条免费混剪,超出部分消耗积分
|
||||
{rules?.free_user_multiplier ? `(×${rules.free_user_multiplier} 倍率)` : ""}
|
||||
{dailyUsage?.reset_at && (
|
||||
<span>
|
||||
{" "}
|
||||
·{" "}
|
||||
{new Date(dailyUsage.reset_at).toLocaleTimeString("zh-CN", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
重置
|
||||
</span>
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
{/* 统计 */}
|
||||
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
|
||||
<Col xs={12} md={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="累计获得"
|
||||
value={earned}
|
||||
prefix={<ArrowUpOutlined style={{ color: "#10b981" }} />}
|
||||
valueStyle={{ color: "#10b981" }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="累计消耗"
|
||||
value={spent}
|
||||
prefix={<ArrowDownOutlined style={{ color: "#ef4444" }} />}
|
||||
valueStyle={{ color: "#ef4444" }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="可用积分"
|
||||
value={bal}
|
||||
prefix={<ThunderboltOutlined style={{ color: "#8b5cf6" }} />}
|
||||
valueStyle={{ color: "#8b5cf6" }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title={isMember ? "会员等级" : "今日免费剩余"}
|
||||
value={isMember ? memberLabel(membership, subscription) : `${freeRemain} 条`}
|
||||
prefix={<CrownFilled style={{ color: "#f59e0b" }} />}
|
||||
valueStyle={{ color: "#f59e0b" }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 快捷入口 & 最近流水 */}
|
||||
<Row gutter={[16, 16]} style={{ marginTop: 8 }}>
|
||||
<Col xs={24} md={14}>
|
||||
<Card
|
||||
title={
|
||||
<Space>
|
||||
<HistoryOutlined />
|
||||
最近流水
|
||||
</Space>
|
||||
}
|
||||
extra={<a onClick={() => navigate("/points/transactions")}>查看全部 →</a>}
|
||||
>
|
||||
{recentTx.length === 0 ? (
|
||||
<Empty description="暂无积分流水" />
|
||||
) : (
|
||||
<List
|
||||
dataSource={recentTx}
|
||||
renderItem={(item) => (
|
||||
<List.Item>
|
||||
<List.Item.Meta
|
||||
avatar={
|
||||
<Avatar
|
||||
size="small"
|
||||
style={{
|
||||
background: item.type === "add" ? "#d1fae5" : "#fee2e2",
|
||||
color: item.type === "add" ? "#059669" : "#dc2626",
|
||||
}}
|
||||
icon={item.type === "add" ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
|
||||
/>
|
||||
}
|
||||
title={sourceLabel(item.source)}
|
||||
description={item.time}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
color: item.type === "add" ? "#10b981" : "#ef4444",
|
||||
fontWeight: 700,
|
||||
}}
|
||||
>
|
||||
{item.type === "add" ? "+" : "-"}
|
||||
{item.amount}
|
||||
</div>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} md={10}>
|
||||
<Card title="快捷操作">
|
||||
<Space direction="vertical" style={{ width: "100%" }} size={10}>
|
||||
<Button
|
||||
block
|
||||
size="large"
|
||||
type="primary"
|
||||
icon={<WalletOutlined />}
|
||||
onClick={() => navigate("/points/recharge")}
|
||||
>
|
||||
充值积分
|
||||
</Button>
|
||||
<Button
|
||||
block
|
||||
size="large"
|
||||
icon={<HistoryOutlined />}
|
||||
onClick={() => navigate("/points/transactions")}
|
||||
>
|
||||
积分明细
|
||||
</Button>
|
||||
<Button
|
||||
block
|
||||
size="large"
|
||||
icon={<CrownFilled />}
|
||||
onClick={() => navigate("/subscription")}
|
||||
>
|
||||
{isMember ? "续费/升级会员" : "升级付费会员"}
|
||||
</Button>
|
||||
<Button
|
||||
block
|
||||
size="large"
|
||||
icon={<FileTextOutlined />}
|
||||
onClick={() => navigate("/points/rules")}
|
||||
>
|
||||
积分消耗规则
|
||||
</Button>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PointsCenter
|
||||
export const Component = PointsCenter
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* 积分充值页(/points/recharge)
|
||||
* 单独展示积分包,供入口直接跳转使用
|
||||
*
|
||||
* 字段对齐新契约(2026-09-16):
|
||||
* - package 用 code 做唯一键(替代 id)
|
||||
* - 价格单位为 cents,折后价 = price_cents × (user_discount ?? 1)
|
||||
* - 下单接口返回 pay_params(当前为 {},支付通道未接入)
|
||||
* - 余额优先取 membership.points_balance,降级 balance.balance
|
||||
*/
|
||||
import React, { useEffect, useState } from "react"
|
||||
import {
|
||||
Card,
|
||||
Col,
|
||||
Row,
|
||||
Button,
|
||||
Tag,
|
||||
Typography,
|
||||
Space,
|
||||
Modal,
|
||||
message,
|
||||
Tooltip,
|
||||
Alert,
|
||||
} from "antd"
|
||||
import { ThunderboltOutlined, SafetyCertificateOutlined, CrownFilled } from "@ant-design/icons"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import { usePointsStore } from "@/store/pointsStore"
|
||||
import { createPointsOrder, getPointsPackages } from "@/api/points"
|
||||
import type { PointsPackage, PointsPackagesResponse } from "@/api/points/types"
|
||||
import { getDiscountPriceCents } from "@/api/points/types"
|
||||
import "./Points.css"
|
||||
|
||||
const { Title, Text, Paragraph } = Typography
|
||||
|
||||
const PointsRecharge: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const { balance, membership, init } = usePointsStore()
|
||||
const [packagesResp, setPackagesResp] = useState<PointsPackagesResponse | null>(null)
|
||||
const [buying, setBuying] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
init()
|
||||
getPointsPackages()
|
||||
.then((r) => setPackagesResp(r))
|
||||
.catch(() => {})
|
||||
}, [init])
|
||||
|
||||
const packages = packagesResp?.packages ?? []
|
||||
const userDiscount = packagesResp?.user_discount ?? null
|
||||
const isMember = membership?.is_member ?? balance?.is_member ?? false
|
||||
const currentBalance = membership?.points_balance ?? balance?.balance ?? 0
|
||||
|
||||
const handleBuy = async (pkg: PointsPackage) => {
|
||||
try {
|
||||
setBuying(pkg.code)
|
||||
const order = await createPointsOrder({ package_id: pkg.code })
|
||||
Modal.info({
|
||||
title: "支付功能开发中",
|
||||
icon: <SafetyCertificateOutlined />,
|
||||
content: (
|
||||
<div>
|
||||
<Paragraph>
|
||||
订单已创建({order.id.slice(0, 16)}…),购买 {pkg.points} 积分,金额{" "}
|
||||
<b>¥{(order.amount_cents / 100).toFixed(2).replace(/\.00$/, "")}</b>。
|
||||
{order.points_amount !== undefined && ` 到账 ${order.points_amount} 积分。`}
|
||||
{order.expire_at && (
|
||||
<span> 有效期至 {new Date(order.expire_at).toLocaleDateString("zh-CN")}。</span>
|
||||
)}
|
||||
微信/支付宝支付正在接入中。
|
||||
</Paragraph>
|
||||
<Paragraph type="secondary" style={{ marginBottom: 0 }}>
|
||||
现阶段所有功能免费体验,积分仅为演示数据。
|
||||
</Paragraph>
|
||||
</div>
|
||||
),
|
||||
okText: "知道了",
|
||||
})
|
||||
} catch (e) {
|
||||
const err = e as { response?: { data?: { error?: { message?: string } } }; message?: string }
|
||||
const msg = err?.response?.data?.error?.message || err?.message || "下单失败"
|
||||
message.error(msg)
|
||||
} finally {
|
||||
setBuying(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="xx-points-page">
|
||||
<PageHead
|
||||
title="积分充值"
|
||||
description="积分永久有效,可用于全部 AI 功能;付费会员享折扣"
|
||||
actions={
|
||||
<Space>
|
||||
{!isMember && (
|
||||
<Button icon={<CrownFilled />} onClick={() => navigate("/subscription")}>
|
||||
升级会员享折扣
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => navigate("/points/transactions")}>积分明细</Button>
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
|
||||
<Card
|
||||
bordered={false}
|
||||
style={{ marginBottom: 16, background: "linear-gradient(135deg,#ede9fe,#fce7f3)" }}
|
||||
>
|
||||
<Space size="large">
|
||||
<div>
|
||||
<Text type="secondary">当前可用积分</Text>
|
||||
<div style={{ fontSize: 28, fontWeight: 800, color: "#7c3aed" }}>
|
||||
<ThunderboltOutlined /> {currentBalance.toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
{userDiscount !== null && userDiscount < 1 && (
|
||||
<Alert
|
||||
type="success"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message={`您当前享 ${Math.round(userDiscount * 100) / 10} 折优惠`}
|
||||
description="会员/优惠已自动应用到下方价格"
|
||||
/>
|
||||
)}
|
||||
|
||||
<Title level={4}>选择积分包</Title>
|
||||
<Row gutter={[20, 20]}>
|
||||
{packages.map((pkg) => {
|
||||
const priceCents = getDiscountPriceCents(pkg, userDiscount)
|
||||
const originalCents = pkg.price_cents
|
||||
const discount =
|
||||
priceCents < originalCents ? Math.round((1 - priceCents / originalCents) * 100) : 0
|
||||
const unit = priceCents / 100 / pkg.points
|
||||
const isHot = pkg.unit_price < 0.1 // 单价低于 0.1 元/分视为热门
|
||||
return (
|
||||
<Col xs={24} sm={12} md={8} key={pkg.code}>
|
||||
<Card
|
||||
className={`xx-pkg-card ${isHot ? "recommended" : ""} ${discount > 0 ? "has-discount" : ""}`}
|
||||
hoverable
|
||||
>
|
||||
{isHot && <div className="xx-pkg-badge">热门</div>}
|
||||
{discount > 0 && (
|
||||
<Tag color="gold" className="xx-pkg-discount">
|
||||
{Math.round((priceCents / originalCents) * 10) / 1}折
|
||||
</Tag>
|
||||
)}
|
||||
<div className="xx-pkg-name">{pkg.name}</div>
|
||||
<div className="xx-pkg-points">
|
||||
<ThunderboltOutlined /> {pkg.points.toLocaleString()} 积分
|
||||
</div>
|
||||
<div className="xx-pkg-price">
|
||||
<span className="currency">¥</span>
|
||||
<span className="amount">
|
||||
{(priceCents / 100).toFixed(priceCents % 100 === 0 ? 0 : 1).replace(/\.0$/, "")}
|
||||
</span>
|
||||
{discount > 0 && (
|
||||
<span className="xx-pkg-origin">¥{(originalCents / 100).toFixed(0)}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="xx-pkg-unit">≈¥{unit.toFixed(3)}/积分 · 永久有效</div>
|
||||
<Button
|
||||
block
|
||||
type={isHot ? "primary" : "default"}
|
||||
loading={buying === pkg.code}
|
||||
onClick={() => handleBuy(pkg)}
|
||||
size="large"
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
立即购买
|
||||
</Button>
|
||||
</Card>
|
||||
</Col>
|
||||
)
|
||||
})}
|
||||
</Row>
|
||||
|
||||
<Card style={{ marginTop: 24 }}>
|
||||
<Title level={5}>积分消耗说明</Title>
|
||||
<ul style={{ paddingLeft: 20, color: "var(--text-secondary)", lineHeight: 2 }}>
|
||||
<li>智能混剪:基础积分/条(≤30s),每加 30s 额外消耗</li>
|
||||
<li>AI 配音 / 声音克隆合成:按分钟消耗积分</li>
|
||||
<li>AI 数字人:按分钟消耗积分</li>
|
||||
<li>抖音链接提取 / AI 改写 / AI 标题 / AI 封面:按次消耗</li>
|
||||
<li>声音克隆训练:免费</li>
|
||||
<li>免费用户每日若干条免费混剪,其余 AI 功能按会员价 ×1.15 消耗</li>
|
||||
<li>会员享积分折扣(具体档位见会员中心)</li>
|
||||
</ul>
|
||||
<Tooltip title="具体规则以系统实际计算为准">
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
<SafetyCertificateOutlined /> 所有规则以页面实际显示为准
|
||||
</Text>
|
||||
</Tooltip>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PointsRecharge
|
||||
export const Component = PointsRecharge
|
||||
@@ -0,0 +1,88 @@
|
||||
/* 积分中心 & 明细 & 规则页通用样式 */
|
||||
.xx-points-page {
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
padding: 24px 0;
|
||||
}
|
||||
|
||||
/* Hero 渐变卡 */
|
||||
.xx-points-hero {
|
||||
background: linear-gradient(135deg, #7c3aed 0%, #ec4899 50%, #f59e0b 100%);
|
||||
border-radius: 16px;
|
||||
color: #fff;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.xx-points-hero::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
right: -60px;
|
||||
top: -60px;
|
||||
width: 220px;
|
||||
height: 220px;
|
||||
background: radial-gradient(circle, rgba(255, 255, 255, 0.15) 0%, transparent 70%);
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.xx-points-hero .ant-card-body {
|
||||
padding: 28px 32px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.xx-points-hero-balance {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
font-size: 52px;
|
||||
font-weight: 800;
|
||||
color: #fff;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.xx-points-hero-balance .anticon {
|
||||
font-size: 32px;
|
||||
}
|
||||
|
||||
.xx-points-free-quota {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-radius: 12px;
|
||||
padding: 14px 16px;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.xx-points-free-title {
|
||||
font-size: 13px;
|
||||
margin-bottom: 8px;
|
||||
color: rgba(255, 255, 255, 0.95);
|
||||
}
|
||||
|
||||
.xx-points-free-quota .ant-progress-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
/* 列表筛选 */
|
||||
.xx-points-filters {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.xx-tx-earn {
|
||||
color: #10b981;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.xx-tx-spend {
|
||||
color: #ef4444;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.xx-tx-refund {
|
||||
color: #3b82f6;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* 规则页 */
|
||||
.xx-rules-table .ant-descriptions-item-label {
|
||||
width: 160px;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* 积分规则页(/app/points/rules)
|
||||
* 静态展示积分获得、消耗、会员折扣等规则
|
||||
*/
|
||||
import React from "react"
|
||||
import { Card, Descriptions, Table, Tag, Typography, Divider, Space } from "antd"
|
||||
import { InfoCircleOutlined, CrownFilled, ThunderboltOutlined } from "@ant-design/icons"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import "./Points.css"
|
||||
|
||||
const { Title, Text, Paragraph } = Typography
|
||||
|
||||
const costData = [
|
||||
{ key: "ai_video", scene: "智能混剪", unit: "条(≤30s)", cost: 3, remark: "每加 30s +1" },
|
||||
{ key: "ai_voice", scene: "AI 配音(含克隆合成)", unit: "分钟", cost: 1, remark: "" },
|
||||
{ key: "ai_digital_human", scene: "AI 数字人", unit: "分钟", cost: 15, remark: "" },
|
||||
{ key: "douyin_extract", scene: "抖音文案提取", unit: "次", cost: 1, remark: "" },
|
||||
{ key: "ai_rewrite", scene: "AI 文案改写", unit: "次", cost: 1, remark: "" },
|
||||
{ key: "ai_title", scene: "AI 标题生成", unit: "次", cost: 1, remark: "" },
|
||||
{ key: "ai_cover", scene: "AI 封面生成", unit: "次", cost: 2, remark: "" },
|
||||
{ key: "voice_clone_train", scene: "声音克隆训练", unit: "次", cost: 0, remark: "免费" },
|
||||
]
|
||||
|
||||
const earnData = [
|
||||
{ key: "new_user", channel: "注册奖励", points: "50~100", remark: "新人专享" },
|
||||
{ key: "recharge", channel: "充值购买", points: "100~2000/次", remark: "永久有效" },
|
||||
{ key: "subscribe", channel: "开通会员赠送", points: "见会员方案", remark: "季/年卡赠送更多" },
|
||||
{ key: "task", channel: "任务/活动奖励", points: "不定额", remark: "运营活动发放" },
|
||||
]
|
||||
|
||||
const PointsRules: React.FC = () => {
|
||||
return (
|
||||
<div className="xx-points-page">
|
||||
<PageHead title="积分规则" description="了解如何获得、使用与管理积分" />
|
||||
|
||||
<Card>
|
||||
<Title level={5}>
|
||||
<InfoCircleOutlined style={{ color: "#3b82f6" }} /> 什么是积分?
|
||||
</Title>
|
||||
<Paragraph>
|
||||
积分是小虾 SaaS 用于结算 AI 能力的虚拟货币。每次使用智能混剪、AI 配音、AI 数字人、AI
|
||||
改写等功能时,
|
||||
会根据使用量扣除相应积分。积分永久有效,可通过充值、任务奖励、注册礼包等方式获取。
|
||||
</Paragraph>
|
||||
|
||||
<Divider />
|
||||
|
||||
<Title level={5}>
|
||||
<ThunderboltOutlined style={{ color: "#8b5cf6" }} /> 积分消耗规则
|
||||
</Title>
|
||||
<Table
|
||||
className="xx-rules-table"
|
||||
dataSource={costData}
|
||||
pagination={false}
|
||||
columns={[
|
||||
{ title: "功能场景", dataIndex: "scene", width: 200 },
|
||||
{ title: "计费单位", dataIndex: "unit", width: 140 },
|
||||
{
|
||||
title: "消耗积分",
|
||||
dataIndex: "cost",
|
||||
width: 110,
|
||||
render: (v: number) =>
|
||||
v === 0 ? (
|
||||
<Tag color="green">免费</Tag>
|
||||
) : (
|
||||
<Text strong style={{ color: "#ef4444" }}>
|
||||
{v}
|
||||
</Text>
|
||||
),
|
||||
},
|
||||
{ title: "备注", dataIndex: "remark" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<Paragraph type="secondary" style={{ marginTop: 12, fontSize: 12 }}>
|
||||
免费用户每日享有 2 条免费混剪额度,超出后按上述标准 ×1.15 扣除积分;
|
||||
付费会员按上述标准原价扣除积分。
|
||||
</Paragraph>
|
||||
|
||||
<Divider />
|
||||
|
||||
<Title level={5} style={{ color: "#10b981" }}>
|
||||
↑ 积分获得方式
|
||||
</Title>
|
||||
<Table
|
||||
className="xx-rules-table"
|
||||
dataSource={earnData}
|
||||
pagination={false}
|
||||
columns={[
|
||||
{ title: "渠道", dataIndex: "channel", width: 200 },
|
||||
{ title: "积分数量", dataIndex: "points", width: 180 },
|
||||
{ title: "备注", dataIndex: "remark" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<Divider />
|
||||
|
||||
<Title level={5}>
|
||||
<CrownFilled style={{ color: "#f59e0b" }} /> 会员折扣
|
||||
</Title>
|
||||
<Descriptions bordered column={1} size="small">
|
||||
<Descriptions.Item label="免费用户">
|
||||
所有 AI 功能按标准价 ×1.15 消耗积分;每日 2 条免费混剪
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="付费会员(月/季/年卡)">
|
||||
所有 AI 功能按标准价消耗;积分购买享 8~9 折;解锁批量导出、多平台发布等高级功能
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="年卡会员">
|
||||
积分购买最低 8 折;开通即赠送 2000 积分
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="季卡会员">
|
||||
积分购买 8.5 折;开通即赠送 400 积分
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
|
||||
<Divider />
|
||||
|
||||
<Title level={5}>退款与有效期</Title>
|
||||
<ul style={{ paddingLeft: 20, lineHeight: 2 }}>
|
||||
<li>充值积分永久有效,不会过期</li>
|
||||
<li>AI 生成失败或服务异常时,已扣除的积分将自动退还</li>
|
||||
<li>会员为虚拟商品,一经开通不支持退款;到期后会员权益自动失效,积分余额不受影响</li>
|
||||
<li>如需发票请联系客服</li>
|
||||
</ul>
|
||||
|
||||
<Space style={{ marginTop: 16 }}>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
规则更新时间:2026-09-15
|
||||
</Text>
|
||||
</Space>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PointsRules
|
||||
export const Component = PointsRules
|
||||
@@ -0,0 +1,271 @@
|
||||
/**
|
||||
* 积分明细页(/points/transactions)
|
||||
* 分页展示积分流水,支持按类型/来源筛选
|
||||
*
|
||||
* 字段对齐新契约(2026-09-16):
|
||||
* - 分页接口返回 {items, total, page, page_size}
|
||||
* - type 仅 add/deduct;refund 通过 source=refund:xxx 前缀体现
|
||||
* - source_name 字段已移除,中文名在前端 SOURCE_LABEL 映射
|
||||
* - signed_amount 字段已移除,根据 type 显示 +/-
|
||||
* - ref_id 在新契约中为 string(不再是 number)
|
||||
*/
|
||||
import React, { useEffect, useState, useCallback } from "react"
|
||||
import {
|
||||
Card,
|
||||
Table,
|
||||
Tag,
|
||||
Select,
|
||||
DatePicker,
|
||||
Space,
|
||||
Typography,
|
||||
Empty,
|
||||
Input,
|
||||
Spin,
|
||||
Button,
|
||||
} from "antd"
|
||||
import { SearchOutlined, ReloadOutlined } from "@ant-design/icons"
|
||||
import type { ColumnsType } from "antd/es/table"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import dayjs from "dayjs"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import { getPointsTransactions } from "@/api/points"
|
||||
import type { PointsTransaction, PointsTxType } from "@/api/points/types"
|
||||
import "./Points.css"
|
||||
|
||||
const { Text } = Typography
|
||||
const { RangePicker } = DatePicker
|
||||
|
||||
const TYPE_LABEL: Record<PointsTxType, { text: string; color: string }> = {
|
||||
add: { text: "获得", color: "green" },
|
||||
deduct: { text: "消耗", color: "red" },
|
||||
}
|
||||
|
||||
const SOURCE_LABEL: Record<string, string> = {
|
||||
recharge: "充值",
|
||||
ai_voice: "AI 配音",
|
||||
ai_digital_human: "AI 数字人",
|
||||
ai_video: "智能混剪",
|
||||
voice_clone_train: "声音克隆训练",
|
||||
voice_clone_synth: "克隆合成",
|
||||
douyin_extract: "抖音链接提取",
|
||||
ai_rewrite: "AI 文案改写",
|
||||
ai_title: "AI 标题生成",
|
||||
ai_cover: "AI 封面生成",
|
||||
sign_up: "注册赠送",
|
||||
bind_phone: "绑定手机",
|
||||
gift: "活动赠送",
|
||||
admin: "管理员调整",
|
||||
}
|
||||
|
||||
const sourceLabel = (s: string): { label: string; isRefund: boolean } => {
|
||||
if (s.startsWith("refund:")) {
|
||||
const inner = s.slice(7)
|
||||
return { label: `${SOURCE_LABEL[inner] || inner}(退款)`, isRefund: true }
|
||||
}
|
||||
return { label: SOURCE_LABEL[s] || s, isRefund: false }
|
||||
}
|
||||
|
||||
const PointsTransactions: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [data, setData] = useState<PointsTransaction[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
const [type, setType] = useState<PointsTxType | "all">("all")
|
||||
const [source, setSource] = useState<string>("all")
|
||||
const [dateRange, setDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null)
|
||||
const [keyword, setKeyword] = useState("")
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
// 新契约后端暂不支持 type/source/date/keyword 过滤参数,先前端过滤
|
||||
const res = await getPointsTransactions(page, pageSize)
|
||||
let items = res.items
|
||||
if (type !== "all") {
|
||||
items = items.filter((it) => it.type === type)
|
||||
}
|
||||
if (source !== "all") {
|
||||
items = items.filter((it) => it.source === source || it.source === `refund:${source}`)
|
||||
}
|
||||
if (dateRange && dateRange[0] && dateRange[1]) {
|
||||
const start = dateRange[0].startOf("day")
|
||||
const end = dateRange[1].endOf("day")
|
||||
items = items.filter((it) => {
|
||||
const t = dayjs(it.created_at)
|
||||
return t.isAfter(start) && t.isBefore(end)
|
||||
})
|
||||
}
|
||||
if (keyword) {
|
||||
const k = keyword.toLowerCase()
|
||||
items = items.filter((it) => {
|
||||
const sl = sourceLabel(it.source).label
|
||||
return (it.description || "").toLowerCase().includes(k) || sl.toLowerCase().includes(k)
|
||||
})
|
||||
}
|
||||
setData(items)
|
||||
setTotal(res.total)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [page, pageSize, type, source, dateRange, keyword])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
const columns: ColumnsType<PointsTransaction> = [
|
||||
{
|
||||
title: "时间",
|
||||
dataIndex: "created_at",
|
||||
width: 180,
|
||||
render: (v: string) => dayjs(v).format("YYYY-MM-DD HH:mm"),
|
||||
},
|
||||
{
|
||||
title: "类型",
|
||||
dataIndex: "type",
|
||||
width: 90,
|
||||
render: (t: PointsTxType, r: PointsTransaction) => {
|
||||
if (r.source.startsWith("refund:")) {
|
||||
return <Tag color="blue">退还</Tag>
|
||||
}
|
||||
const cfg = TYPE_LABEL[t]
|
||||
return <Tag color={cfg?.color || "default"}>{cfg?.text || t}</Tag>
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "来源/场景",
|
||||
dataIndex: "source",
|
||||
width: 180,
|
||||
render: (s: string) => <Text>{sourceLabel(s).label}</Text>,
|
||||
},
|
||||
{
|
||||
title: "说明",
|
||||
dataIndex: "description",
|
||||
ellipsis: true,
|
||||
render: (v: string) => v || "-",
|
||||
},
|
||||
{
|
||||
title: "变动",
|
||||
dataIndex: "amount",
|
||||
width: 110,
|
||||
align: "right",
|
||||
render: (v: number, r: PointsTransaction) => {
|
||||
const isRefund = r.source.startsWith("refund:")
|
||||
const positive = r.type === "add" || isRefund
|
||||
return (
|
||||
<span className={positive ? "xx-tx-earn" : "xx-tx-spend"}>
|
||||
{positive ? "+" : "-"}
|
||||
{v}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "余额",
|
||||
dataIndex: "balance_after",
|
||||
width: 110,
|
||||
align: "right",
|
||||
render: (v: number) => (
|
||||
<Text strong style={{ fontVariantNumeric: "tabular-nums" }}>
|
||||
{v}
|
||||
</Text>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="xx-points-page">
|
||||
<PageHead
|
||||
title="积分明细"
|
||||
description="查看积分收入、消耗与退还记录"
|
||||
actions={
|
||||
<Space>
|
||||
<Button icon={<ReloadOutlined />} onClick={load}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button type="primary" onClick={() => navigate("/points/recharge")}>
|
||||
充值积分
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<div className="xx-points-filters">
|
||||
<Space wrap size={12}>
|
||||
<Select
|
||||
value={type}
|
||||
onChange={(v) => {
|
||||
setType(v)
|
||||
setPage(1)
|
||||
}}
|
||||
style={{ width: 120 }}
|
||||
options={[
|
||||
{ value: "all", label: "全部类型" },
|
||||
{ value: "add", label: "获得" },
|
||||
{ value: "deduct", label: "消耗" },
|
||||
]}
|
||||
/>
|
||||
<Select
|
||||
value={source}
|
||||
onChange={(v) => {
|
||||
setSource(v)
|
||||
setPage(1)
|
||||
}}
|
||||
style={{ width: 160 }}
|
||||
showSearch
|
||||
options={[
|
||||
{ value: "all", label: "全部来源" },
|
||||
...Object.entries(SOURCE_LABEL).map(([k, v]) => ({ value: k, label: v })),
|
||||
]}
|
||||
/>
|
||||
<RangePicker
|
||||
value={dateRange ?? undefined}
|
||||
onChange={(dates) => {
|
||||
setDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null] | null)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
placeholder="搜索说明"
|
||||
prefix={<SearchOutlined />}
|
||||
allowClear
|
||||
style={{ width: 200 }}
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
onPressEnter={() => {
|
||||
setPage(1)
|
||||
load()
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<Spin spinning={loading}>
|
||||
<Table<PointsTransaction>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
locale={{ emptyText: <Empty description="暂无积分流水,快去使用 AI 功能吧" /> }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total,
|
||||
showSizeChanger: true,
|
||||
showTotal: (t) => `共 ${t} 条记录`,
|
||||
onChange: (p, ps) => {
|
||||
setPage(p)
|
||||
setPageSize(ps)
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Spin>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PointsTransactions
|
||||
export const Component = PointsTransactions
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,137 +1,260 @@
|
||||
/**
|
||||
* 文案库页面 - V21 设计系统样式
|
||||
* 单列卡片列表,风格对齐标题库(xx-titles-page)
|
||||
* 文案库页面样式(#1811 v2)
|
||||
* 风格对齐标题库,新增卡片 hover 阴影、标签/meta 行、筛选栏样式
|
||||
*/
|
||||
@import "../../styles/global.css";
|
||||
|
||||
/* ============================================================
|
||||
页面容器
|
||||
============================================================ */
|
||||
.xx-scripts-page {
|
||||
min-height: 100%;
|
||||
padding: var(--space-xl);
|
||||
padding: 24px;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.xx-scripts-layout {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-lg);
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
顶部筛选栏
|
||||
============================================================ */
|
||||
/* ── 筛选栏 ── */
|
||||
.xx-scripts-filters {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-md);
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
padding: 12px 16px;
|
||||
background: var(--bg-card, #fff);
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--border-color, #f0f0f0);
|
||||
}
|
||||
|
||||
.xx-scripts-filters-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.xx-scripts-filters-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
列表
|
||||
============================================================ */
|
||||
/* ── 列表 ── */
|
||||
.xx-scripts-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-sm);
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.xx-scripts-loading {
|
||||
text-align: center;
|
||||
color: var(--text-secondary);
|
||||
padding: var(--space-xl);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
文案卡片(对齐标题卡片风格,单列)
|
||||
============================================================ */
|
||||
.xx-script-card {
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-primary);
|
||||
border-radius: var(--radius-md);
|
||||
padding: var(--space-md);
|
||||
transition: var(--transition-all);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
transition:
|
||||
box-shadow 0.2s,
|
||||
transform 0.2s;
|
||||
}
|
||||
|
||||
.xx-script-card:hover {
|
||||
border-color: var(--primary-color);
|
||||
background: var(--bg-secondary);
|
||||
box-shadow: var(--shadow-sm);
|
||||
box-shadow: 0 4px 16px rgba(124, 58, 237, 0.1);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
.xx-script-card .ant-card-body {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.xx-script-card-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-md);
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.xx-script-title {
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.5;
|
||||
word-break: break-word;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.xx-script-actions {
|
||||
.xx-script-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-xxs);
|
||||
flex-shrink: 0;
|
||||
opacity: 0;
|
||||
transition: var(--transition-opacity, opacity 0.2s);
|
||||
gap: 8px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.xx-script-card:hover .xx-script-actions {
|
||||
opacity: 1;
|
||||
.xx-script-title {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary, #1f1f1f);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.xx-script-actions {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.xx-script-actions .ant-btn {
|
||||
padding: 0 6px;
|
||||
}
|
||||
|
||||
.xx-script-preview {
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary, #666);
|
||||
line-height: 1.6;
|
||||
word-break: break-word;
|
||||
margin-bottom: 8px;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.xx-script-title-text {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary, #999);
|
||||
margin-bottom: 6px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.xx-script-label {
|
||||
color: var(--text-tertiary, #999);
|
||||
}
|
||||
|
||||
.xx-script-tags {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.xx-script-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-xs);
|
||||
font-size: var(--font-size-xs, 12px);
|
||||
color: var(--text-tertiary);
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary, #999);
|
||||
}
|
||||
.xx-script-meta-sep {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
弹窗表单
|
||||
============================================================ */
|
||||
.xx-script-form {
|
||||
/* ── 分页 ── */
|
||||
.xx-scripts-pagination {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-md);
|
||||
justify-content: center;
|
||||
padding: 16px 0;
|
||||
}
|
||||
|
||||
.xx-script-form textarea.ant-input {
|
||||
resize: vertical;
|
||||
.xx-scripts-loading {
|
||||
padding: 48px;
|
||||
text-align: center;
|
||||
color: var(--text-tertiary, #999);
|
||||
}
|
||||
|
||||
/* ── 弹窗表单 ── */
|
||||
.xx-script-form .ant-form-item {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
/* ── 响应式 ── */
|
||||
@media (max-width: 768px) {
|
||||
.xx-scripts-page {
|
||||
padding: 16px 12px;
|
||||
}
|
||||
.xx-scripts-list {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.xx-scripts-filters {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
.xx-scripts-filters-left {
|
||||
width: 100%;
|
||||
}
|
||||
.xx-scripts-filters-left .ant-input,
|
||||
.xx-scripts-filters-left .ant-select {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── #1893 AI 能力样式 ── */
|
||||
|
||||
/* 抖音提取 / AI 按钮与主按钮间距 */
|
||||
.xx-scripts-filters-right .ant-btn + .ant-btn {
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
/* AI 改写工具条(贴在正文 TextArea 下方) */
|
||||
.xx-ai-rewrite-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-top: -8px;
|
||||
margin-bottom: 16px;
|
||||
padding: 8px 12px;
|
||||
background: linear-gradient(90deg, #f7f5ff 0%, #fff 100%);
|
||||
border: 1px dashed #d3c6ff;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
/* AI 生成标题候选 */
|
||||
.xx-ai-title-candidates {
|
||||
margin-top: -8px;
|
||||
margin-bottom: 12px;
|
||||
padding: 10px 12px;
|
||||
background: #fafaff;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #eee6ff;
|
||||
}
|
||||
.xx-ai-title-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.xx-ai-title-tag {
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
padding: 4px 12px;
|
||||
border-radius: 16px;
|
||||
transition: transform 0.15s;
|
||||
margin: 0;
|
||||
}
|
||||
.xx-ai-title-tag:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 8px rgba(114, 46, 209, 0.18);
|
||||
}
|
||||
|
||||
/* loading 提示文本 */
|
||||
.xx-ai-loading-hint {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-top: 12px;
|
||||
padding: 10px 12px;
|
||||
color: var(--text-secondary, #666);
|
||||
font-size: 13px;
|
||||
background: #fafafa;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
/* AI 改写对比块 */
|
||||
.xx-ai-rewrite-item {
|
||||
border-bottom: 1px solid var(--border-color, #f0f0f0) !important;
|
||||
padding: 12px 0 !important;
|
||||
}
|
||||
.xx-ai-rewrite-item:last-child {
|
||||
border-bottom: none !important;
|
||||
}
|
||||
.xx-ai-rewrite-block {
|
||||
width: 100%;
|
||||
}
|
||||
.xx-ai-rewrite-label {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.xx-ai-rewrite-text {
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
color: var(--text-primary, #1f1f1f);
|
||||
padding: 8px 12px;
|
||||
background: #fafafa;
|
||||
border-radius: 6px;
|
||||
max-height: 180px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.xx-ai-rewrite-item:first-child .xx-ai-rewrite-text {
|
||||
color: var(--text-secondary, #666);
|
||||
background: #f7f7f7;
|
||||
}
|
||||
.xx-ai-rewrite-item:last-child .xx-ai-rewrite-text {
|
||||
background: linear-gradient(180deg, #faf5ff 0%, #ffffff 100%);
|
||||
border: 1px solid #eee6ff;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
/**
|
||||
* 账单管理页面
|
||||
* 展示当前订阅信息 + 自动续费开关
|
||||
* P1-3: antd Switch→自定义ToggleSwitch, antd Spin→自定义Spinner
|
||||
* 展示当前订阅信息 + 自动续费开关 + 账单历史
|
||||
*
|
||||
* 字段对齐新契约(2026-09-16):
|
||||
* - toggleAutoRenew 参数改为 {enabled} 对象
|
||||
* - billing_cycle 仅 monthly/yearly(季卡走 monthly 周期 + 3 个月时长)
|
||||
* - 新增账单历史表格:order_type / amount_cents / status / created_at
|
||||
*/
|
||||
import React, { useState, useEffect } from "react"
|
||||
import { message } from "antd"
|
||||
import { getCurrentSubscription, toggleAutoRenew } from "@/api/subscription"
|
||||
import type { SubscriptionInfo } from "@/api/subscription"
|
||||
import { message, Table, Tag, Card, Space, Button, Modal, Typography } from "antd"
|
||||
import type { ColumnsType } from "antd/es/table"
|
||||
import {
|
||||
getCurrentSubscription,
|
||||
toggleAutoRenew,
|
||||
cancelSubscription,
|
||||
getBillingRecords,
|
||||
} from "@/api/subscription"
|
||||
import type { SubscriptionInfo, BillingRecord } from "@/api/subscription/types"
|
||||
import { PLAN_LABEL, BILLING_CYCLE_LABEL } from "@/api/subscription/types"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import "./Billing.css"
|
||||
|
||||
const { Text } = Typography
|
||||
|
||||
const formatDate = (iso: string): string => {
|
||||
const d = new Date(iso)
|
||||
return d.toLocaleDateString("zh-CN", {
|
||||
@@ -51,21 +64,40 @@ const Spinner: React.FC<{ size?: "small" | "large" }> = ({ size = "large" }) =>
|
||||
</div>
|
||||
)
|
||||
|
||||
const ORDER_TYPE_LABEL: Record<string, string> = {
|
||||
subscribe: "新购",
|
||||
renew: "续费",
|
||||
upgrade: "升级",
|
||||
downgrade: "降级",
|
||||
refund: "退款",
|
||||
}
|
||||
|
||||
const BILLING_STATUS_TAG: Record<string, { color: string; text: string }> = {
|
||||
paid: { color: "green", text: "已支付" },
|
||||
pending: { color: "orange", text: "待支付" },
|
||||
failed: { color: "red", text: "支付失败" },
|
||||
refunded: { color: "blue", text: "已退款" },
|
||||
cancelled: { color: "default", text: "已取消" },
|
||||
}
|
||||
|
||||
const Billing: React.FC = () => {
|
||||
const [subscription, setSubscription] = useState<SubscriptionInfo | null>(null)
|
||||
const [billingRecords, setBillingRecords] = useState<BillingRecord[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [recordsLoading, setRecordsLoading] = useState(false)
|
||||
const [autoRenewChecked, setAutoRenewChecked] = useState(false)
|
||||
const [autoRenewLoading, setAutoRenewLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
loadData()
|
||||
loadRecords()
|
||||
}, [])
|
||||
|
||||
const loadData = async () => {
|
||||
try {
|
||||
const data = await getCurrentSubscription()
|
||||
setSubscription(data)
|
||||
setAutoRenewChecked(data.auto_renew)
|
||||
setAutoRenewChecked(!!data.auto_renew)
|
||||
} catch (err: unknown) {
|
||||
if (!(err as { __msgShown?: boolean })?.__msgShown) message.error("加载订阅数据失败")
|
||||
} finally {
|
||||
@@ -73,22 +105,106 @@ const Billing: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const loadRecords = async () => {
|
||||
try {
|
||||
setRecordsLoading(true)
|
||||
const list = await getBillingRecords()
|
||||
setBillingRecords(Array.isArray(list) ? list : [])
|
||||
} catch {
|
||||
// 账单加载失败不阻塞主流程
|
||||
setBillingRecords([])
|
||||
} finally {
|
||||
setRecordsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleAutoRenew = async (checked: boolean) => {
|
||||
setAutoRenewLoading(true)
|
||||
try {
|
||||
const res = await toggleAutoRenew(checked)
|
||||
message.success(res.message)
|
||||
const res = await toggleAutoRenew({ enabled: checked })
|
||||
message.success(res?.message ?? (checked ? "已开启自动续费" : "已关闭自动续费"))
|
||||
setAutoRenewChecked(checked)
|
||||
if (subscription) {
|
||||
setSubscription({ ...subscription, auto_renew: checked })
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if (!(err as { __msgShown?: boolean })?.__msgShown) message.error("操作失败")
|
||||
const e = err as { response?: { data?: { error?: { message?: string } } }; message?: string }
|
||||
message.error(e?.response?.data?.error?.message || e?.message || "操作失败")
|
||||
} finally {
|
||||
setAutoRenewLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancelSubscription = () => {
|
||||
Modal.confirm({
|
||||
title: "确认取消订阅?",
|
||||
content: "取消后,当前周期结束时将不再自动续费。您仍可使用当前会员权益至到期日。",
|
||||
okText: "确认取消",
|
||||
okType: "danger",
|
||||
cancelText: "我再想想",
|
||||
onOk: async () => {
|
||||
try {
|
||||
await cancelSubscription()
|
||||
message.success("已取消订阅,到期后不再续费")
|
||||
await loadData()
|
||||
} catch (err: unknown) {
|
||||
const e = err as {
|
||||
response?: { data?: { error?: { message?: string } } }
|
||||
message?: string
|
||||
}
|
||||
message.error(e?.response?.data?.error?.message || e?.message || "取消失败")
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const columns: ColumnsType<BillingRecord> = [
|
||||
{
|
||||
title: "时间",
|
||||
dataIndex: "created_at",
|
||||
width: 170,
|
||||
render: (v: string) => formatDate(v),
|
||||
},
|
||||
{
|
||||
title: "类型",
|
||||
dataIndex: "order_type",
|
||||
width: 100,
|
||||
render: (v: string) => ORDER_TYPE_LABEL[v] || v || "-",
|
||||
},
|
||||
{
|
||||
title: "套餐",
|
||||
dataIndex: "plan_id",
|
||||
width: 120,
|
||||
render: (v: string) => (v ? PLAN_LABEL[v as keyof typeof PLAN_LABEL] || v : "-"),
|
||||
},
|
||||
{
|
||||
title: "金额",
|
||||
dataIndex: "amount_cents",
|
||||
width: 110,
|
||||
align: "right",
|
||||
render: (v: number) => (
|
||||
<Text strong style={{ fontVariantNumeric: "tabular-nums" }}>
|
||||
¥{((v ?? 0) / 100).toFixed(2)}
|
||||
</Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "status",
|
||||
width: 100,
|
||||
render: (v: string) => {
|
||||
const cfg = BILLING_STATUS_TAG[v]
|
||||
return <Tag color={cfg?.color || "default"}>{cfg?.text || v || "-"}</Tag>
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "支付时间",
|
||||
dataIndex: "paid_at",
|
||||
width: 170,
|
||||
render: (v?: string) => (v ? formatDate(v) : <Text type="secondary">—</Text>),
|
||||
},
|
||||
]
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="xx-billing-page">
|
||||
@@ -109,19 +225,42 @@ const Billing: React.FC = () => {
|
||||
<div className="xx-overview-details">
|
||||
<div className="xx-overview-item">
|
||||
<span className="xx-label">套餐</span>
|
||||
<span className="xx-value">{subscription.plan_name}</span>
|
||||
<span className="xx-value">
|
||||
{subscription.plan_name ||
|
||||
PLAN_LABEL[subscription.plan_id as keyof typeof PLAN_LABEL] ||
|
||||
"-"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="xx-overview-item">
|
||||
<span className="xx-label">计费周期</span>
|
||||
<span className="xx-value">
|
||||
{subscription.billing_cycle === "monthly" ? "月付" : "年付"}
|
||||
{BILLING_CYCLE_LABEL[
|
||||
subscription.billing_cycle as keyof typeof BILLING_CYCLE_LABEL
|
||||
] ||
|
||||
subscription.billing_cycle ||
|
||||
"-"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="xx-overview-item">
|
||||
<span className="xx-label">下次扣费</span>
|
||||
<span className="xx-label">本期金额</span>
|
||||
<span className="xx-value">¥{((subscription.amount ?? 0) / 100).toFixed(2)}</span>
|
||||
</div>
|
||||
<div className="xx-overview-item">
|
||||
<span className="xx-label">周期开始</span>
|
||||
<span className="xx-value">{formatDate(subscription.current_period_start)}</span>
|
||||
</div>
|
||||
<div className="xx-overview-item">
|
||||
<span className="xx-label">下次扣费/到期</span>
|
||||
<span className="xx-value">{formatDate(subscription.current_period_end)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{subscription.plan_id !== "free" && (
|
||||
<Space style={{ marginTop: 16 }}>
|
||||
<Button danger onClick={handleCancelSubscription}>
|
||||
取消订阅
|
||||
</Button>
|
||||
</Space>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 自动续费 */}
|
||||
@@ -145,6 +284,26 @@ const Billing: React.FC = () => {
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 账单历史 */}
|
||||
<Card
|
||||
title="账单历史"
|
||||
style={{ marginTop: 16 }}
|
||||
extra={
|
||||
<Button size="small" onClick={loadRecords} loading={recordsLoading}>
|
||||
刷新
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Table<BillingRecord>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={billingRecords}
|
||||
loading={recordsLoading}
|
||||
pagination={{ pageSize: 10, showSizeChanger: false }}
|
||||
locale={{ emptyText: "暂无账单记录" }}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,233 +1,286 @@
|
||||
/* V21 定价页面 - CSS变量体系 */
|
||||
@import "../../styles/global.css";
|
||||
|
||||
/* 会员订阅 & 积分充值页样式 v2 */
|
||||
.xx-plans-page {
|
||||
max-width: 1200px;
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
padding: var(--space-3xl) var(--space-lg);
|
||||
padding: 24px 0;
|
||||
}
|
||||
|
||||
/* 页面头部 */
|
||||
.xx-page-head {
|
||||
text-align: center;
|
||||
margin-bottom: var(--space-3xl);
|
||||
/* 当前状态卡片 */
|
||||
.xx-current-status {
|
||||
background: linear-gradient(135deg, #ede9fe 0%, #fce7f3 100%);
|
||||
border-radius: 14px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.xx-page-head h2 {
|
||||
font-size: var(--font-size-5xl);
|
||||
font-weight: var(--font-weight-extrabold);
|
||||
color: var(--text-primary);
|
||||
margin: 0 0 var(--space-md);
|
||||
letter-spacing: var(--letter-spacing-tight);
|
||||
.xx-current-status .ant-card-body {
|
||||
padding: 20px 24px;
|
||||
}
|
||||
|
||||
.xx-page-head p {
|
||||
font-size: var(--font-size-lg);
|
||||
color: var(--text-secondary);
|
||||
margin: 0;
|
||||
max-width: 560px;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
/* 定价卡片网格 - 4列 */
|
||||
.xx-plans-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: var(--space-lg);
|
||||
margin-top: var(--space-xl);
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.xx-plans-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.xx-plans-grid {
|
||||
grid-template-columns: 1fr;
|
||||
max-width: 400px;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
}
|
||||
|
||||
/* V21 定价卡片 */
|
||||
.xx-plan-card {
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-xl);
|
||||
box-shadow: var(--shadow-card);
|
||||
padding: var(--space-xl) var(--space-lg);
|
||||
position: relative;
|
||||
transition: var(--transition-base);
|
||||
.xx-current-balance {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 20px;
|
||||
font-weight: 800;
|
||||
color: var(--text-primary, #111827);
|
||||
}
|
||||
|
||||
.xx-plan-card:hover {
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: 0 32px 90px color-mix(in srgb, var(--primary-color) 15%, transparent);
|
||||
transform: translateY(-4px);
|
||||
.xx-current-balance-val {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 计费周期切换 */
|
||||
.xx-billing-switch {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 12px;
|
||||
margin-top: 12px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.xx-billing-btn {
|
||||
position: relative;
|
||||
border: 2px solid var(--border-color, #e5e7eb);
|
||||
background: var(--bg-primary, #fff);
|
||||
border-radius: 12px;
|
||||
padding: 16px 12px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.xx-billing-btn:hover {
|
||||
border-color: var(--primary-soft, #c4b5fd);
|
||||
}
|
||||
|
||||
.xx-billing-btn.active {
|
||||
border-color: #7c3aed;
|
||||
background: #f5f3ff;
|
||||
box-shadow: 0 4px 12px rgba(124, 58, 237, 0.15);
|
||||
}
|
||||
|
||||
.xx-billing-name {
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
color: var(--text-primary, #111827);
|
||||
}
|
||||
|
||||
.xx-billing-price {
|
||||
margin: 6px 0;
|
||||
}
|
||||
|
||||
.xx-billing-yuan {
|
||||
font-size: 14px;
|
||||
color: var(--text-secondary, #6b7280);
|
||||
}
|
||||
|
||||
.xx-billing-amount {
|
||||
font-size: 28px;
|
||||
font-weight: 800;
|
||||
color: var(--text-primary, #111827);
|
||||
margin: 0 2px;
|
||||
}
|
||||
|
||||
.xx-billing-sub {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary, #9ca3af);
|
||||
}
|
||||
|
||||
.xx-billing-save {
|
||||
display: inline-block;
|
||||
margin-left: 6px;
|
||||
background: #fef3c7;
|
||||
color: #d97706;
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* 方案卡片 */
|
||||
.xx-plan-card {
|
||||
border-radius: 14px;
|
||||
position: relative;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.xx-plan-card.featured {
|
||||
border: 2px solid var(--primary-color);
|
||||
box-shadow:
|
||||
0 0 0 4px color-mix(in srgb, var(--primary-color) 10%, transparent),
|
||||
0 32px 90px color-mix(in srgb, var(--primary-color) 15%, transparent);
|
||||
transform: scale(1.02);
|
||||
border: 2px solid #7c3aed;
|
||||
box-shadow: 0 8px 24px rgba(124, 58, 237, 0.12);
|
||||
}
|
||||
|
||||
.xx-plan-card.featured:hover {
|
||||
transform: scale(1.02) translateY(-4px);
|
||||
}
|
||||
|
||||
/* 推荐标签 */
|
||||
.xx-badge {
|
||||
.xx-plan-recommend-badge {
|
||||
position: absolute;
|
||||
top: -12px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: var(--gradient-primary);
|
||||
color: var(--text-inverse);
|
||||
padding: 6px 16px;
|
||||
border-radius: var(--radius-full);
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-extrabold);
|
||||
white-space: nowrap;
|
||||
right: 20px;
|
||||
background: linear-gradient(135deg, #f59e0b, #ef4444);
|
||||
color: #fff;
|
||||
padding: 4px 12px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
|
||||
/* 企业版定制标签 */
|
||||
.xx-badge.enterprise {
|
||||
background: linear-gradient(135deg, var(--accent-color), var(--accent-dark));
|
||||
}
|
||||
|
||||
/* 套餐名称 */
|
||||
.xx-plan-card h3 {
|
||||
font-size: var(--font-size-2xl);
|
||||
font-weight: var(--font-weight-extrabold);
|
||||
color: var(--text-primary);
|
||||
margin: 0 0 var(--space-lg);
|
||||
.xx-plan-head {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 价格 */
|
||||
.xx-plan-price {
|
||||
text-align: center;
|
||||
margin-bottom: 12px;
|
||||
margin: 12px 0 6px;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.xx-plan-price .currency {
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
color: var(--text-secondary);
|
||||
vertical-align: top;
|
||||
font-size: 18px;
|
||||
color: var(--text-secondary, #6b7280);
|
||||
}
|
||||
|
||||
.xx-plan-price .amount {
|
||||
font-size: var(--font-size-5xl);
|
||||
font-weight: var(--font-weight-extrabold);
|
||||
color: var(--primary-color);
|
||||
font-size: 44px;
|
||||
font-weight: 800;
|
||||
color: var(--text-primary, #111827);
|
||||
line-height: 1;
|
||||
margin: 0 4px;
|
||||
}
|
||||
|
||||
.xx-plan-card.featured .xx-plan-price .amount {
|
||||
color: #7c3aed;
|
||||
}
|
||||
|
||||
.xx-plan-price .period {
|
||||
font-size: var(--font-size-md);
|
||||
color: var(--text-secondary);
|
||||
font-weight: var(--font-weight-medium);
|
||||
color: var(--text-secondary, #6b7280);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* 企业版价格 */
|
||||
.xx-plan-price.custom .amount {
|
||||
font-size: var(--font-size-3xl);
|
||||
.xx-feature-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0 0 20px 0;
|
||||
}
|
||||
|
||||
/* 描述 */
|
||||
.xx-plan-description {
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--font-size-base);
|
||||
text-align: center;
|
||||
margin-bottom: var(--space-lg);
|
||||
padding-bottom: var(--space-lg);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
/* 功能列表 */
|
||||
.xx-features {
|
||||
margin-top: var(--space-sm);
|
||||
padding-top: var(--space-lg);
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.xx-feature {
|
||||
.xx-feature-list li {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--font-size-base);
|
||||
margin-bottom: var(--space-md);
|
||||
line-height: var(--line-height-base);
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 7px 0;
|
||||
font-size: 14px;
|
||||
color: var(--text-primary, #111827);
|
||||
}
|
||||
|
||||
.xx-feature span:first-child {
|
||||
color: var(--secondary-color);
|
||||
font-weight: var(--font-weight-extrabold);
|
||||
flex-shrink: 0;
|
||||
.xx-feature-list li.disabled {
|
||||
color: var(--text-tertiary, #9ca3af);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
/* 订阅按钮 */
|
||||
.xx-subscribe-btn {
|
||||
width: 100%;
|
||||
margin-top: var(--space-lg);
|
||||
padding: var(--space-md) var(--space-lg) !important;
|
||||
font-size: var(--font-size-base) !important;
|
||||
font-weight: var(--font-weight-extrabold) !important;
|
||||
border-radius: var(--radius-md) !important;
|
||||
transition: var(--transition-fast) !important;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
.xx-feature-no {
|
||||
width: 16px;
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
color: var(--text-tertiary, #d1d5db);
|
||||
}
|
||||
|
||||
.xx-subscribe-btn.primary {
|
||||
background: var(--gradient-primary) !important;
|
||||
color: var(--text-inverse) !important;
|
||||
border: none !important;
|
||||
box-shadow: var(--shadow-primary) !important;
|
||||
.xx-plan-tip {
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary, #9ca3af);
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.xx-subscribe-btn.primary:hover {
|
||||
box-shadow: var(--shadow-hover) !important;
|
||||
transform: translateY(-1px);
|
||||
/* 积分包卡片 */
|
||||
.xx-pkg-card {
|
||||
position: relative;
|
||||
border-radius: 14px;
|
||||
text-align: center;
|
||||
transition: all 0.2s;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.xx-subscribe-btn.ghost {
|
||||
background: var(--bg-primary) !important;
|
||||
border: 1px solid var(--border-color) !important;
|
||||
color: var(--text-primary) !important;
|
||||
.xx-pkg-card:hover {
|
||||
transform: translateY(-4px);
|
||||
box-shadow: 0 12px 28px rgba(139, 92, 246, 0.18);
|
||||
}
|
||||
|
||||
.xx-subscribe-btn.ghost:hover {
|
||||
border-color: var(--primary-color) !important;
|
||||
color: var(--primary-color) !important;
|
||||
.xx-pkg-card.recommended {
|
||||
border: 2px solid #8b5cf6;
|
||||
}
|
||||
|
||||
/* 企业版按钮 */
|
||||
.xx-subscribe-btn.enterprise {
|
||||
background: linear-gradient(135deg, var(--accent-color), var(--accent-dark)) !important;
|
||||
color: var(--text-inverse) !important;
|
||||
border: none !important;
|
||||
box-shadow: 0 14px 26px color-mix(in srgb, var(--accent-color) 22%, transparent) !important;
|
||||
.xx-pkg-badge {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
left: 12px;
|
||||
background: linear-gradient(135deg, #8b5cf6, #ec4899);
|
||||
color: #fff;
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.xx-plans-grid {
|
||||
.xx-pkg-discount {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.xx-pkg-name {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary, #111827);
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.xx-pkg-points {
|
||||
font-size: 16px;
|
||||
color: #8b5cf6;
|
||||
font-weight: 600;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.xx-pkg-price {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.xx-pkg-price .currency {
|
||||
font-size: 16px;
|
||||
color: var(--text-secondary, #6b7280);
|
||||
}
|
||||
|
||||
.xx-pkg-price .amount {
|
||||
font-size: 32px;
|
||||
font-weight: 800;
|
||||
color: var(--text-primary, #111827);
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.xx-pkg-card.recommended .xx-pkg-price .amount {
|
||||
color: #8b5cf6;
|
||||
}
|
||||
|
||||
.xx-pkg-origin {
|
||||
color: var(--text-tertiary, #9ca3af);
|
||||
text-decoration: line-through;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.xx-pkg-unit {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary, #9ca3af);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.xx-billing-switch {
|
||||
grid-template-columns: 1fr;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
|
||||
.xx-plan-card {
|
||||
padding: var(--space-lg);
|
||||
.xx-plan-price .amount {
|
||||
font-size: 36px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,107 +1,529 @@
|
||||
/**
|
||||
* 定价页面 - V21 UI 四级定价
|
||||
* 会员订阅 & 积分充值页
|
||||
* v3: 对齐后端最终契约(2026-09-16)
|
||||
* - 订阅计划走 GET /subscription/plans(4 档:free/monthly/quarterly/yearly)
|
||||
* - 积分包走 GET /points/packages,折后价 = price_cents × (user_discount ?? 1)
|
||||
* - 当前身份/余额优先从 membership + dailyUsage 取,降级 balance
|
||||
* - 暂保留 SUBSCRIPTION_PLANS_FALLBACK 常量,API 失败时降级
|
||||
*/
|
||||
import React, { useState } from "react"
|
||||
import { message } from "antd"
|
||||
import React, { useEffect, useMemo, useState } from "react"
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Row,
|
||||
Tag,
|
||||
Divider,
|
||||
Space,
|
||||
Typography,
|
||||
Modal,
|
||||
message,
|
||||
Tooltip,
|
||||
Badge,
|
||||
} from "antd"
|
||||
import {
|
||||
CheckCircleFilled,
|
||||
CrownFilled,
|
||||
ThunderboltOutlined,
|
||||
SafetyCertificateOutlined,
|
||||
VideoCameraOutlined,
|
||||
StarFilled,
|
||||
} from "@ant-design/icons"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import { usePointsStore } from "@/store/pointsStore"
|
||||
import { createPointsOrder, getPointsPackages } from "@/api/points"
|
||||
import { getSubscriptionPlans, changePlan } from "@/api/subscription"
|
||||
import type { PointsPackage, PointsPackagesResponse } from "@/api/points/types"
|
||||
import { getDiscountPriceCents } from "@/api/points/types"
|
||||
import type { SubscriptionPlan } from "@/api/subscription/types"
|
||||
import { PLAN_LABEL, BILLING_CYCLE_LABEL } from "@/api/subscription/types"
|
||||
import "./Plans.css"
|
||||
|
||||
const PLANS = [
|
||||
const { Title, Text, Paragraph } = Typography
|
||||
|
||||
/** 免费会员权益(根据后端 features 动态展示,这里保留兜底) */
|
||||
const FREE_FEATURES = [
|
||||
{ include: true, text: "每日免费混剪额度" },
|
||||
{ include: true, text: "720p 导出分辨率" },
|
||||
{ include: true, text: "AI 配音(×1.15 积分)" },
|
||||
{ include: true, text: "AI 数字人(×1.15 积分)" },
|
||||
{ include: true, text: "声音克隆训练免费" },
|
||||
{ include: false, text: "批量导出" },
|
||||
{ include: false, text: "多平台一键发布" },
|
||||
{ include: false, text: "去重检测报告" },
|
||||
]
|
||||
|
||||
/** 付费会员权益(兜底) */
|
||||
const PAID_FEATURES = [
|
||||
{ include: true, text: "智能混剪按会员折扣积分" },
|
||||
{ include: true, text: "最高 1080p 导出" },
|
||||
{ include: true, text: "全部 AI 功能(会员折扣积分)" },
|
||||
{ include: true, text: "声音克隆训练免费" },
|
||||
{ include: true, text: "积分购买最低折扣" },
|
||||
{ include: true, text: "批量导出" },
|
||||
{ include: true, text: "多平台一键发布" },
|
||||
{ include: true, text: "去重检测报告" },
|
||||
]
|
||||
|
||||
/** 旧 SUBSCRIPTION_PLANS 兜底(API 不可用时) */
|
||||
const SUBSCRIPTION_PLANS_FALLBACK = [
|
||||
{
|
||||
id: "free",
|
||||
name: "体验版",
|
||||
price: 0,
|
||||
description: "适合个人体验",
|
||||
id: "monthly" as const,
|
||||
name: "月卡",
|
||||
price_cents: 1990,
|
||||
per_month_yuan: "19.9",
|
||||
savings_percent: 0,
|
||||
recommended: false,
|
||||
features: ["3个视频成片", "基础标题模板", "基础配音音色", "720p导出"],
|
||||
billing_label: "/月",
|
||||
billing_cycle: "monthly" as const,
|
||||
},
|
||||
{
|
||||
id: "standard",
|
||||
name: "标准版",
|
||||
price: 99,
|
||||
description: "适合内容创作者",
|
||||
recommended: false,
|
||||
features: ["无限视频成片", "高级标题模板", "全部配音音色", "1080p导出", "API接口"],
|
||||
},
|
||||
{
|
||||
id: "pro",
|
||||
name: "专业版",
|
||||
price: 299,
|
||||
description: "适合专业团队",
|
||||
id: "quarterly" as const,
|
||||
name: "季卡",
|
||||
price_cents: 3990,
|
||||
per_month_yuan: "13.3",
|
||||
savings_percent: 33,
|
||||
recommended: true,
|
||||
features: ["无限视频成片", "自定义标题", "全部配音音色", "4K导出", "优先渲染队列", "专属客服"],
|
||||
billing_label: "/季",
|
||||
billing_cycle: "monthly" as const,
|
||||
},
|
||||
{
|
||||
id: "enterprise",
|
||||
name: "企业版",
|
||||
price: null,
|
||||
description: "适合企业用户",
|
||||
id: "yearly" as const,
|
||||
name: "年卡",
|
||||
price_cents: 15900,
|
||||
per_month_yuan: "13.25",
|
||||
savings_percent: 34,
|
||||
recommended: false,
|
||||
features: ["私有化部署", "自定义品牌形象", " SLA服务保障", "技术支持", "团队协作", "数据报表"],
|
||||
billing_label: "/年",
|
||||
billing_cycle: "yearly" as const,
|
||||
},
|
||||
]
|
||||
|
||||
const Plans: React.FC = () => {
|
||||
const [subscribing, setSubscribing] = useState(false)
|
||||
const formatYuan = (cents: number) =>
|
||||
`¥${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 1).replace(/\.0$/, "")}`
|
||||
|
||||
const handleSubscribe = async (_planId: string) => {
|
||||
const Plans: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const { balance, dailyUsage, membership, subscription, init } = usePointsStore()
|
||||
const [plans, setPlans] = useState<SubscriptionPlan[]>([])
|
||||
const [packagesResp, setPackagesResp] = useState<PointsPackagesResponse | null>(null)
|
||||
const [subscribing, setSubscribing] = useState(false)
|
||||
const [buying, setBuying] = useState<string | null>(null)
|
||||
const [selectedBilling, setSelectedBilling] = useState<"monthly" | "quarterly" | "yearly">(
|
||||
"quarterly",
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
init()
|
||||
// 拉取订阅计划
|
||||
getSubscriptionPlans()
|
||||
.then((r) => {
|
||||
const paid = r.plans.filter((p) => p.plan_id !== "free")
|
||||
setPlans(paid)
|
||||
// 默认选季卡,没有就选第一个
|
||||
const hasQuarterly = paid.some((p) => p.plan_id === "quarterly")
|
||||
if (!hasQuarterly && paid.length > 0) setSelectedBilling(paid[0].plan_id as "monthly")
|
||||
})
|
||||
.catch(() => {
|
||||
// 降级
|
||||
})
|
||||
getPointsPackages()
|
||||
.then((r) => setPackagesResp(r))
|
||||
.catch(() => {})
|
||||
}, [init])
|
||||
|
||||
const packages = packagesResp?.packages ?? []
|
||||
const userDiscount = packagesResp?.user_discount ?? null
|
||||
|
||||
const isMember = membership?.is_member ?? balance?.is_member ?? false
|
||||
// 当前会员档位:优先 membership.member_type,降级 subscription.plan_id
|
||||
const memberPlanId =
|
||||
membership?.member_type ??
|
||||
(subscription?.plan_id && subscription.plan_id !== "free" ? subscription.plan_id : null)
|
||||
|
||||
const bal = membership?.points_balance ?? balance?.balance ?? 0
|
||||
const freeUsed = dailyUsage?.free_clips_used ?? 0
|
||||
const freeLimit = dailyUsage?.free_clips_limit ?? (isMember ? 0 : 3)
|
||||
const freeRemain = dailyUsage?.free_clips_remaining ?? (isMember ? 0 : freeLimit - freeUsed)
|
||||
|
||||
/** 统一的可选付费档位(API 返回 + 兜底) */
|
||||
const billingOptions = useMemo(() => {
|
||||
if (plans.length > 0) {
|
||||
return plans.map((p) => {
|
||||
const id = p.plan_id as "monthly" | "quarterly" | "yearly"
|
||||
const perMonth =
|
||||
p.duration_days > 0
|
||||
? (p.price_cents / 100 / (p.duration_days / 30)).toFixed(1)
|
||||
: (p.monthly_price_cents / 100).toFixed(1)
|
||||
const monthlyCents = p.monthly_price_cents || p.price_cents
|
||||
const savings =
|
||||
p.price_cents > 0 && monthlyCents > 0
|
||||
? Math.max(
|
||||
0,
|
||||
Math.round((1 - p.price_cents / (monthlyCents * (p.duration_days / 30))) * 100),
|
||||
)
|
||||
: 0
|
||||
return {
|
||||
id,
|
||||
name: p.name,
|
||||
price_cents: p.price_cents,
|
||||
per_month_yuan: perMonth,
|
||||
savings_percent: savings,
|
||||
recommended: id === "quarterly",
|
||||
billing_label: id === "yearly" ? "/年" : id === "quarterly" ? "/季" : "/月",
|
||||
billing_cycle: (id === "yearly" ? "yearly" : "monthly") as "monthly" | "yearly",
|
||||
}
|
||||
})
|
||||
}
|
||||
return SUBSCRIPTION_PLANS_FALLBACK
|
||||
}, [plans])
|
||||
|
||||
const selectedPlan = useMemo(
|
||||
() => billingOptions.find((p) => p.id === selectedBilling) ?? billingOptions[0],
|
||||
[billingOptions, selectedBilling],
|
||||
)
|
||||
|
||||
const handleSubscribe = async () => {
|
||||
if (!selectedPlan) return
|
||||
try {
|
||||
setSubscribing(true)
|
||||
message.success("订阅成功")
|
||||
} catch (error: unknown) {
|
||||
message.error("订阅失败")
|
||||
await changePlan({
|
||||
target_plan_id: selectedPlan.id,
|
||||
billing_cycle: selectedPlan.billing_cycle,
|
||||
})
|
||||
Modal.success({
|
||||
title: "订阅已提交",
|
||||
icon: <SafetyCertificateOutlined />,
|
||||
content: `已为您切换到 ${selectedPlan.name},${BILLING_CYCLE_LABEL[selectedPlan.billing_cycle]} ${formatYuan(selectedPlan.price_cents)}。支付通道接入中,正式上线后会自动扣费。`,
|
||||
okText: "知道了",
|
||||
})
|
||||
} catch (e) {
|
||||
const err = e as { response?: { data?: { error?: { message?: string } } }; message?: string }
|
||||
// 支付未接入阶段,保持演示体验
|
||||
Modal.confirm({
|
||||
title: "支付功能开发中",
|
||||
icon: <SafetyCertificateOutlined />,
|
||||
content:
|
||||
err?.response?.data?.error?.message ||
|
||||
"微信/支付宝支付正在接入中,完成后会第一时间通知。是否返回首页继续使用免费功能?",
|
||||
okText: "返回首页",
|
||||
cancelText: "留在此页",
|
||||
onOk: () => navigate("/app/dashboard"),
|
||||
})
|
||||
} finally {
|
||||
setSubscribing(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleBuyPoints = async (pkg: PointsPackage) => {
|
||||
try {
|
||||
setBuying(pkg.code)
|
||||
const order = await createPointsOrder({ package_id: pkg.code })
|
||||
Modal.info({
|
||||
title: "支付功能开发中",
|
||||
icon: <ThunderboltOutlined />,
|
||||
content: (
|
||||
<div>
|
||||
<Paragraph>
|
||||
订单 <Text code>{order.id.slice(0, 16)}…</Text> 已创建,购买 {pkg.points} 积分,金额{" "}
|
||||
<b>{formatYuan(order.amount_cents)}</b>,
|
||||
{order.points_amount !== undefined && `到账 ${order.points_amount} 积分。`}
|
||||
微信/支付宝支付正在接入中,正式上线后可直接付款。
|
||||
</Paragraph>
|
||||
<Paragraph type="secondary" style={{ marginBottom: 0 }}>
|
||||
现阶段所有功能均处于免费体验阶段,积分仅为演示数据。
|
||||
</Paragraph>
|
||||
</div>
|
||||
),
|
||||
okText: "知道了",
|
||||
})
|
||||
} catch (e) {
|
||||
const err = e as { response?: { data?: { error?: { message?: string } } }; message?: string }
|
||||
message.error(err?.response?.data?.error?.message || err?.message || "创建订单失败")
|
||||
} finally {
|
||||
setBuying(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="xx-plans-page">
|
||||
<PageHead title="选择适合您的方案" description="灵活定价,满足不同规模的创作需求" />
|
||||
|
||||
<div className="xx-plans-grid">
|
||||
{PLANS.map((plan) => (
|
||||
<div key={plan.id} className={`xx-plan-card ${plan.recommended ? "featured" : ""}`}>
|
||||
{plan.recommended && <div className="xx-badge">推荐</div>}
|
||||
{plan.id === "enterprise" && <div className="xx-badge enterprise">定制</div>}
|
||||
|
||||
<h3>{plan.name}</h3>
|
||||
|
||||
<div className={`xx-plan-price ${plan.price === null ? "custom" : ""}`}>
|
||||
{plan.price !== null ? (
|
||||
<>
|
||||
<span className="currency">¥</span>
|
||||
<span className="amount">{plan.price}</span>
|
||||
<span className="period">/月</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="amount">联系我们</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="xx-plan-description">{plan.description}</p>
|
||||
|
||||
<div className="xx-features">
|
||||
{plan.features.map((feature, idx) => (
|
||||
<div key={idx} className="xx-feature">
|
||||
<span>✓</span>
|
||||
<span>{feature}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button
|
||||
className={`xx-subscribe-btn ${
|
||||
plan.id === "enterprise" ? "enterprise" : plan.recommended ? "primary" : "ghost"
|
||||
}`}
|
||||
onClick={() => handleSubscribe(plan.id)}
|
||||
disabled={subscribing}
|
||||
<PageHead
|
||||
title="会员与积分"
|
||||
description="开通会员解锁全部功能,按需充值积分灵活使用 AI 能力"
|
||||
actions={
|
||||
<Space>
|
||||
<Button
|
||||
icon={<ThunderboltOutlined />}
|
||||
onClick={() => navigate("/app/points/transactions")}
|
||||
>
|
||||
{subscribing ? "处理中..." : plan.price === null ? "联系我们" : "立即订阅"}
|
||||
</button>
|
||||
</div>
|
||||
积分明细
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 当前状态卡片 */}
|
||||
<Card className="xx-current-status" bordered={false}>
|
||||
<Row align="middle" gutter={24}>
|
||||
<Col flex="auto">
|
||||
<Space size="large" wrap>
|
||||
<div>
|
||||
<Text type="secondary">当前身份</Text>
|
||||
<div>
|
||||
{isMember ? (
|
||||
<Tag
|
||||
color="gold"
|
||||
icon={<CrownFilled />}
|
||||
style={{ marginTop: 4, fontSize: 14, padding: "4px 10px" }}
|
||||
>
|
||||
{memberPlanId
|
||||
? PLAN_LABEL[memberPlanId as keyof typeof PLAN_LABEL] || "付费会员"
|
||||
: "付费会员"}
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag style={{ marginTop: 4, fontSize: 14, padding: "4px 10px" }}>免费会员</Tag>
|
||||
)}
|
||||
{balance?.member_expires_at && isMember && (
|
||||
<Text type="secondary" style={{ marginLeft: 8 }}>
|
||||
到期 {new Date(balance.member_expires_at).toLocaleDateString("zh-CN")}
|
||||
</Text>
|
||||
)}
|
||||
{membership?.max_resolution && (
|
||||
<Text type="secondary" style={{ marginLeft: 8 }}>
|
||||
· 最高 {membership.max_resolution}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text type="secondary">可用积分</Text>
|
||||
<div className="xx-current-balance">
|
||||
<ThunderboltOutlined style={{ color: "#8b5cf6" }} />
|
||||
<span className="xx-current-balance-val">{bal}</span>
|
||||
</div>
|
||||
</div>
|
||||
{!isMember && freeLimit > 0 && (
|
||||
<div>
|
||||
<Text type="secondary">今日免费混剪</Text>
|
||||
<div>
|
||||
<Text strong>{freeUsed}</Text>
|
||||
<Text type="secondary"> / {freeLimit} 条</Text>
|
||||
{!isMember && (
|
||||
<Tag color="blue" style={{ marginLeft: 8 }}>
|
||||
剩余 {freeRemain} 条
|
||||
</Tag>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
</Col>
|
||||
<Col>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<ThunderboltOutlined />}
|
||||
onClick={() => {
|
||||
const el = document.getElementById("points-packages")
|
||||
el?.scrollIntoView({ behavior: "smooth" })
|
||||
}}
|
||||
>
|
||||
充值积分
|
||||
</Button>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
{/* 两档会员对比 */}
|
||||
<Title level={4} style={{ marginTop: 24 }}>
|
||||
<CrownFilled style={{ color: "#f59e0b", marginRight: 8 }} />
|
||||
选择适合您的方案
|
||||
</Title>
|
||||
|
||||
{/* 计费周期切换 */}
|
||||
<div className="xx-billing-switch">
|
||||
{billingOptions.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
className={`xx-billing-btn ${selectedBilling === p.id ? "active" : ""}`}
|
||||
onClick={() => setSelectedBilling(p.id)}
|
||||
>
|
||||
{p.recommended && (
|
||||
<Badge.Ribbon text="推荐" color="gold" style={{ top: -14, right: -22 }} />
|
||||
)}
|
||||
<div className="xx-billing-name">{p.name}</div>
|
||||
<div className="xx-billing-price">
|
||||
<span className="xx-billing-yuan">¥</span>
|
||||
<span className="xx-billing-amount">
|
||||
{(p.price_cents / 100)
|
||||
.toFixed(p.price_cents % 100 === 0 ? 0 : 1)
|
||||
.replace(/\.0$/, "")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="xx-billing-sub">
|
||||
≈¥{p.per_month_yuan}/月
|
||||
{p.savings_percent ? (
|
||||
<span className="xx-billing-save">省{p.savings_percent}%</span>
|
||||
) : null}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Row gutter={[20, 20]} style={{ marginTop: 16 }}>
|
||||
{/* 免费会员 */}
|
||||
<Col xs={24} md={12}>
|
||||
<Card className="xx-plan-card" bordered>
|
||||
<div className="xx-plan-head">
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
免费会员
|
||||
</Title>
|
||||
<div className="xx-plan-price">
|
||||
<span className="currency">¥</span>
|
||||
<span className="amount">0</span>
|
||||
<span className="period">/永久</span>
|
||||
</div>
|
||||
<Text type="secondary">体验 AI 剪辑的基础能力</Text>
|
||||
</div>
|
||||
<Divider style={{ margin: "16px 0" }} />
|
||||
<ul className="xx-feature-list">
|
||||
{FREE_FEATURES.map((f, i) => (
|
||||
<li key={i} className={f.include ? "" : "disabled"}>
|
||||
{f.include ? (
|
||||
<CheckCircleFilled style={{ color: "#10b981" }} />
|
||||
) : (
|
||||
<span className="xx-feature-no">—</span>
|
||||
)}
|
||||
<span>{f.text}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Button block size="large" disabled={!isMember ? false : true}>
|
||||
{!isMember ? "当前方案" : "免费方案"}
|
||||
</Button>
|
||||
</Card>
|
||||
</Col>
|
||||
|
||||
{/* 付费会员 */}
|
||||
<Col xs={24} md={12}>
|
||||
<Card className="xx-plan-card featured" bordered>
|
||||
<div className="xx-plan-recommend-badge">
|
||||
<StarFilled /> 推荐
|
||||
</div>
|
||||
<div className="xx-plan-head">
|
||||
<Title level={4} style={{ margin: 0, color: "#7c3aed" }}>
|
||||
<CrownFilled style={{ color: "#f59e0b" }} /> {selectedPlan?.name || "付费会员"}
|
||||
</Title>
|
||||
<div className="xx-plan-price">
|
||||
<span className="currency">¥</span>
|
||||
<span className="amount">
|
||||
{selectedPlan
|
||||
? (selectedPlan.price_cents / 100)
|
||||
.toFixed(selectedPlan.price_cents % 100 === 0 ? 0 : 1)
|
||||
.replace(/\.0$/, "")
|
||||
: "—"}
|
||||
</span>
|
||||
<span className="period">{selectedPlan?.billing_label || ""}</span>
|
||||
</div>
|
||||
<Text type="secondary">
|
||||
折合 ¥{selectedPlan?.per_month_yuan}/月 · 解锁全部 AI 能力
|
||||
</Text>
|
||||
</div>
|
||||
<Divider style={{ margin: "16px 0" }} />
|
||||
<ul className="xx-feature-list">
|
||||
{PAID_FEATURES.map((f, i) => (
|
||||
<li key={i}>
|
||||
<CheckCircleFilled style={{ color: "#7c3aed" }} />
|
||||
<span>{f.text}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Button
|
||||
block
|
||||
size="large"
|
||||
type="primary"
|
||||
loading={subscribing}
|
||||
disabled={isMember && memberPlanId === selectedBilling}
|
||||
onClick={handleSubscribe}
|
||||
icon={<ThunderboltOutlined />}
|
||||
>
|
||||
{isMember && memberPlanId === selectedBilling
|
||||
? "当前方案"
|
||||
: isMember
|
||||
? "续费/升级"
|
||||
: "立即开通"}
|
||||
</Button>
|
||||
<div className="xx-plan-tip">
|
||||
<VideoCameraOutlined /> 虚拟商品不支持退款 · 支付接入中先演示
|
||||
</div>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 积分充值 */}
|
||||
<div id="points-packages">
|
||||
<Title level={4} style={{ marginTop: 40 }}>
|
||||
<ThunderboltOutlined style={{ color: "#8b5cf6", marginRight: 8 }} />
|
||||
积分充值
|
||||
<Tooltip title="积分永久有效,可用于所有 AI 功能;付费会员享折扣">
|
||||
<Text type="secondary" style={{ fontSize: 13, marginLeft: 8, fontWeight: "normal" }}>
|
||||
(永久有效)
|
||||
</Text>
|
||||
</Tooltip>
|
||||
</Title>
|
||||
|
||||
<Row gutter={[16, 16]}>
|
||||
{packages.map((pkg) => {
|
||||
const priceCents = getDiscountPriceCents(pkg, userDiscount)
|
||||
const originalCents = pkg.price_cents
|
||||
const discount =
|
||||
priceCents < originalCents ? Math.round((1 - priceCents / originalCents) * 100) : 0
|
||||
const unit = priceCents / 100 / pkg.points
|
||||
const isHot = pkg.unit_price < 0.1
|
||||
return (
|
||||
<Col xs={24} sm={8} key={pkg.code}>
|
||||
<Card
|
||||
className={`xx-pkg-card ${discount > 0 ? "has-discount" : ""} ${isHot ? "recommended" : ""}`}
|
||||
hoverable
|
||||
>
|
||||
{isHot && <div className="xx-pkg-badge">热门</div>}
|
||||
{discount > 0 && (
|
||||
<Tag color="gold" className="xx-pkg-discount">
|
||||
{Math.round((priceCents / originalCents) * 10) / 1}折
|
||||
</Tag>
|
||||
)}
|
||||
<div className="xx-pkg-name">{pkg.name}</div>
|
||||
<div className="xx-pkg-points">
|
||||
<ThunderboltOutlined /> {pkg.points.toLocaleString()} 积分
|
||||
</div>
|
||||
<div className="xx-pkg-price">
|
||||
<span className="currency">¥</span>
|
||||
<span className="amount">
|
||||
{(priceCents / 100)
|
||||
.toFixed(priceCents % 100 === 0 ? 0 : 1)
|
||||
.replace(/\.0$/, "")}
|
||||
</span>
|
||||
{discount > 0 && (
|
||||
<span className="xx-pkg-origin">¥{(originalCents / 100).toFixed(0)}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="xx-pkg-unit">≈¥{unit.toFixed(3)}/积分</div>
|
||||
<Button
|
||||
block
|
||||
type={isHot ? "primary" : "default"}
|
||||
loading={buying === pkg.code}
|
||||
onClick={() => handleBuyPoints(pkg)}
|
||||
style={{ marginTop: 12 }}
|
||||
>
|
||||
立即购买
|
||||
</Button>
|
||||
</Card>
|
||||
</Col>
|
||||
)
|
||||
})}
|
||||
</Row>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
/**
|
||||
* 升级/降级/续费页面
|
||||
* P1-3: antd Button/Modal/Radio/Spin → 自定义 UI 组件
|
||||
*/
|
||||
import React from "react"
|
||||
import { Modal } from "@/components/ui"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import type { PlanType } from "@/api/subscription"
|
||||
import type { PlanId } from "@/api/subscription/types"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import { Button } from "@/components/ui"
|
||||
import { PLANS_META, getPlanName, getPlanPrice } from "./constants"
|
||||
@@ -13,6 +12,9 @@ import { BillingCycleSwitch, Spinner } from "./components/SubscriptionUI"
|
||||
import { useSubscription } from "./hooks/useSubscription"
|
||||
import "./UpgradeSubscription.css"
|
||||
|
||||
/** 可选择的付费档位(不含 free) */
|
||||
const PAID_PLANS: PlanId[] = ["monthly", "quarterly", "yearly"]
|
||||
|
||||
const UpgradeSubscription: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
@@ -49,12 +51,12 @@ const UpgradeSubscription: React.FC = () => {
|
||||
const handleCancelClick = () => {
|
||||
Modal.confirm({
|
||||
title: "确认取消订阅",
|
||||
content: "取消后,当前周期结束前仍可正常使用,到期后降级为体验版。",
|
||||
content: "取消后,当前周期结束前仍可正常使用,到期后降级为免费版。",
|
||||
okText: "确认取消",
|
||||
cancelText: "再想想",
|
||||
onOk: async () => {
|
||||
const ok = await handleCancel()
|
||||
if (ok) navigate("/app/subscription")
|
||||
if (ok) navigate("/subscription")
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -74,14 +76,22 @@ const UpgradeSubscription: React.FC = () => {
|
||||
<PageHead title="变更订阅方案" description={`当前套餐:${getPlanName(currentPlan)}`} />
|
||||
|
||||
<div className="xx-upgrade-plans">
|
||||
{(["standard", "pro", "enterprise"] as PlanType[]).map((planId) => {
|
||||
{PAID_PLANS.map((planId) => {
|
||||
const plan = PLANS_META[planId]
|
||||
const isCurrent = planId === currentPlan
|
||||
// 年卡显示年价,其他显示月价
|
||||
const monthlyPrice = plan.priceYuan
|
||||
const yearlyPrice = plan.yearlyPriceYuan || plan.priceYuan * 12
|
||||
// 选中季卡时默认切到月付周期;年卡切到年付
|
||||
const resolvedCycle: "monthly" | "yearly" = planId === "yearly" ? "yearly" : "monthly"
|
||||
return (
|
||||
<div
|
||||
key={planId}
|
||||
className={`xx-upgrade-card ${isCurrent ? "current" : ""} ${selectedPlan === planId ? "selected" : ""}`}
|
||||
onClick={() => setSelectedPlan(planId)}
|
||||
onClick={() => {
|
||||
setSelectedPlan(planId)
|
||||
setBillingCycle(resolvedCycle)
|
||||
}}
|
||||
>
|
||||
{isCurrent && <div className="xx-current-badge">当前</div>}
|
||||
<h3>{plan.name}</h3>
|
||||
@@ -89,8 +99,8 @@ const UpgradeSubscription: React.FC = () => {
|
||||
<BillingCycleSwitch
|
||||
value={billingCycle}
|
||||
onChange={setBillingCycle}
|
||||
monthlyPrice={plan.price}
|
||||
yearlyPrice={plan.yearlyPrice}
|
||||
monthlyPrice={monthlyPrice}
|
||||
yearlyPrice={yearlyPrice}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,16 +1,32 @@
|
||||
import type { PlanType, BillingCycle } from "@/api/subscription"
|
||||
/**
|
||||
* 订阅套餐元数据
|
||||
* 价格硬编码兜底,真实价格以 GET /subscription/plans 为准
|
||||
*/
|
||||
import type { PlanId, BillingCycle } from "@/api/subscription/types"
|
||||
|
||||
export const PLANS_META: Record<string, { name: string; price: number; yearlyPrice: number }> = {
|
||||
free: { name: "体验版", price: 0, yearlyPrice: 0 },
|
||||
standard: { name: "标准版", price: 99, yearlyPrice: 990 },
|
||||
pro: { name: "专业版", price: 299, yearlyPrice: 2990 },
|
||||
enterprise: { name: "企业版", price: 0, yearlyPrice: 0 },
|
||||
export const PLANS_META: Record<
|
||||
PlanId,
|
||||
{ name: string; priceYuan: number; yearlyPriceYuan: number }
|
||||
> = {
|
||||
free: { name: "免费版", priceYuan: 0, yearlyPriceYuan: 0 },
|
||||
monthly: { name: "月度会员", priceYuan: 19.9, yearlyPriceYuan: 0 },
|
||||
quarterly: { name: "季度会员", priceYuan: 39.9, yearlyPriceYuan: 0 },
|
||||
yearly: { name: "年度会员", priceYuan: 0, yearlyPriceYuan: 159 },
|
||||
}
|
||||
|
||||
export const getPlanName = (planId: PlanType | string) => PLANS_META[planId]?.name ?? "体验版"
|
||||
export const getPlanName = (planId: PlanId | string): string =>
|
||||
PLANS_META[planId as PlanId]?.name ?? "免费版"
|
||||
|
||||
export const getPlanPrice = (planId: PlanType | string, cycle: BillingCycle) => {
|
||||
const plan = PLANS_META[planId]
|
||||
/**
|
||||
* 获取展示价格(元)
|
||||
* - monthly 周期:月卡/季卡按自身价格,年卡按月折算
|
||||
* - yearly 周期:年卡按年价,其他按年价 * 12
|
||||
*/
|
||||
export const getPlanPrice = (planId: PlanId | string, cycle: BillingCycle): number => {
|
||||
const plan = PLANS_META[planId as PlanId]
|
||||
if (!plan) return 0
|
||||
return cycle === "yearly" ? plan.yearlyPrice : plan.price
|
||||
if (cycle === "yearly") {
|
||||
return plan.yearlyPriceYuan > 0 ? plan.yearlyPriceYuan : plan.priceYuan * 12
|
||||
}
|
||||
return plan.priceYuan
|
||||
}
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
/**
|
||||
* 订阅管理 Hook
|
||||
* 封装订阅信息查询、套餐变更、自动续费切换、取消订阅等逻辑
|
||||
* 对齐最终契约(plan_id=free/monthly/quarterly/yearly + billing_cycle=monthly/yearly)
|
||||
*/
|
||||
import { useState, useEffect, useCallback } from "react"
|
||||
import { message } from "antd"
|
||||
import {
|
||||
@@ -5,20 +10,14 @@ import {
|
||||
changePlan,
|
||||
toggleAutoRenew,
|
||||
cancelSubscription,
|
||||
type SubscriptionInfo,
|
||||
type PlanType,
|
||||
type BillingCycle,
|
||||
} from "@/api/subscription"
|
||||
import type { SubscriptionInfo, PlanId, BillingCycle } from "@/api/subscription/types"
|
||||
|
||||
/**
|
||||
* 订阅管理 Hook
|
||||
* 封装订阅信息查询、套餐变更、自动续费切换、取消订阅等逻辑
|
||||
*/
|
||||
export function useSubscription() {
|
||||
const [subscription, setSubscription] = useState<SubscriptionInfo | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [selectedPlan, setSelectedPlan] = useState<PlanType>("standard")
|
||||
const [selectedPlan, setSelectedPlan] = useState<PlanId>("monthly")
|
||||
const [billingCycle, setBillingCycle] = useState<BillingCycle>("monthly")
|
||||
|
||||
const loadSubscription = useCallback(async () => {
|
||||
@@ -26,6 +25,7 @@ export function useSubscription() {
|
||||
const data = await getCurrentSubscription()
|
||||
setSubscription(data)
|
||||
setSelectedPlan(data.plan_id)
|
||||
setBillingCycle(data.billing_cycle)
|
||||
} catch (err: unknown) {
|
||||
if (!(err as { __msgShown?: boolean })?.__msgShown) message.error("获取订阅信息失败")
|
||||
} finally {
|
||||
@@ -37,45 +37,41 @@ export function useSubscription() {
|
||||
loadSubscription()
|
||||
}, [loadSubscription])
|
||||
|
||||
const handleUpgrade = useCallback(async () => {
|
||||
if (!subscription) return
|
||||
const executeChangePlan = useCallback(async () => {
|
||||
if (!subscription) return false
|
||||
if (selectedPlan === subscription.plan_id && billingCycle === subscription.billing_cycle) {
|
||||
message.info("当前已是该套餐")
|
||||
return
|
||||
return false
|
||||
}
|
||||
// 由调用方决定是否弹确认框
|
||||
}, [subscription, selectedPlan, billingCycle])
|
||||
|
||||
const executeChangePlan = useCallback(async () => {
|
||||
try {
|
||||
setSubmitting(true)
|
||||
const res = await changePlan({
|
||||
target_plan_id: selectedPlan,
|
||||
billing_cycle: billingCycle,
|
||||
})
|
||||
const res = await changePlan({ target_plan_id: selectedPlan, billing_cycle: billingCycle })
|
||||
if (res.success) {
|
||||
message.success(res.message)
|
||||
setSubscription(res.new_subscription ?? null)
|
||||
return true
|
||||
} else {
|
||||
message.error(res.message)
|
||||
return false
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if (!(err as { __msgShown?: boolean })?.__msgShown) message.error("套餐变更失败,请重试")
|
||||
return false
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}, [selectedPlan, billingCycle])
|
||||
}, [subscription, selectedPlan, billingCycle])
|
||||
|
||||
const handleToggleAutoRenew = useCallback(
|
||||
async (enabled: boolean) => {
|
||||
try {
|
||||
const res = await toggleAutoRenew(enabled)
|
||||
const res = await toggleAutoRenew({ enabled })
|
||||
message.success(res.message)
|
||||
if (subscription) {
|
||||
setSubscription({ ...subscription, auto_renew: enabled })
|
||||
}
|
||||
if (subscription) setSubscription({ ...subscription, auto_renew: enabled })
|
||||
return true
|
||||
} catch (err: unknown) {
|
||||
if (!(err as { __msgShown?: boolean })?.__msgShown) message.error("操作失败")
|
||||
return false
|
||||
}
|
||||
},
|
||||
[subscription],
|
||||
@@ -93,7 +89,6 @@ export function useSubscription() {
|
||||
}, [])
|
||||
|
||||
return {
|
||||
// 状态
|
||||
subscription,
|
||||
loading,
|
||||
submitting,
|
||||
@@ -101,9 +96,7 @@ export function useSubscription() {
|
||||
billingCycle,
|
||||
setSelectedPlan,
|
||||
setBillingCycle,
|
||||
// 操作
|
||||
loadSubscription,
|
||||
handleUpgrade,
|
||||
executeChangePlan,
|
||||
handleToggleAutoRenew,
|
||||
handleCancel,
|
||||
|
||||
@@ -96,6 +96,22 @@ const appChildren: RouteObject[] = [
|
||||
path: "subscription/billing",
|
||||
lazy: lazyRoute(() => import("@/pages/subscription/Billing")),
|
||||
},
|
||||
{
|
||||
path: "points",
|
||||
lazy: lazyRoute(() => import("@/pages/points/Center")),
|
||||
},
|
||||
{
|
||||
path: "points/transactions",
|
||||
lazy: lazyRoute(() => import("@/pages/points/Transactions")),
|
||||
},
|
||||
{
|
||||
path: "points/recharge",
|
||||
lazy: lazyRoute(() => import("@/pages/points/Packages")),
|
||||
},
|
||||
{
|
||||
path: "points/rules",
|
||||
lazy: lazyRoute(() => import("@/pages/points/Rules")),
|
||||
},
|
||||
{
|
||||
path: "profile",
|
||||
lazy: lazyRoute(() => import("@/pages/profile/Settings")),
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* 积分 & 会员状态管理
|
||||
* 对齐后端 staging 最终契约(2026-09-16):
|
||||
* - balance: GET /points/balance(无 free_clips_*)
|
||||
* - dailyUsage: GET /usage/daily(每日免费额度)
|
||||
* - membership: GET /points/subscription/membership(聚合会员信息)
|
||||
* - rules: GET /points/rules(base_points + free_user_multiplier)
|
||||
* - subscription: GET /subscription/current(plan_id + billing_cycle)
|
||||
*/
|
||||
import { create } from "zustand"
|
||||
import { getPointsBalance, getPointsRules, getDailyUsage, getMembership } from "@/api/points"
|
||||
import { getCurrentSubscription } from "@/api/subscription"
|
||||
import type {
|
||||
PointsBalance,
|
||||
PointsRulesResponse,
|
||||
DailyUsage,
|
||||
MembershipResponse,
|
||||
} from "@/api/points/types"
|
||||
import type { SubscriptionInfo } from "@/api/subscription/types"
|
||||
|
||||
interface PointsState {
|
||||
balance: PointsBalance | null
|
||||
dailyUsage: DailyUsage | null
|
||||
membership: MembershipResponse | null
|
||||
rules: PointsRulesResponse | null
|
||||
subscription: SubscriptionInfo | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
/** 初始化:并行拉取 balance / rules / subscription / dailyUsage / membership */
|
||||
init: () => Promise<void>
|
||||
/** 刷新余额(充值/消费后调用) */
|
||||
refreshBalance: () => Promise<void>
|
||||
/** 乐观扣减 */
|
||||
optimisticDeduct: (points: number) => void
|
||||
/** 乐观增加 */
|
||||
optimisticAdd: (points: number) => void
|
||||
/** 清除积分状态(退出登录) */
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
export const usePointsStore = create<PointsState>((set, get) => ({
|
||||
balance: null,
|
||||
dailyUsage: null,
|
||||
membership: null,
|
||||
rules: null,
|
||||
subscription: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
|
||||
init: async () => {
|
||||
// 已加载过不重复拉取
|
||||
if (get().balance && get().rules && get().subscription) return
|
||||
set({ loading: true, error: null })
|
||||
try {
|
||||
const [balance, rules, subscription, dailyUsage, membership] = await Promise.all([
|
||||
getPointsBalance().catch(() => null),
|
||||
getPointsRules().catch(() => null),
|
||||
getCurrentSubscription().catch(() => null),
|
||||
getDailyUsage().catch(() => null),
|
||||
getMembership().catch(() => null),
|
||||
])
|
||||
set({
|
||||
balance,
|
||||
rules,
|
||||
subscription,
|
||||
dailyUsage,
|
||||
membership,
|
||||
loading: false,
|
||||
})
|
||||
} catch (err) {
|
||||
set({ error: (err as Error).message || "加载积分信息失败", loading: false })
|
||||
}
|
||||
},
|
||||
|
||||
refreshBalance: async () => {
|
||||
try {
|
||||
const [balance, dailyUsage, membership, subscription] = await Promise.all([
|
||||
getPointsBalance(),
|
||||
getDailyUsage().catch(() => null),
|
||||
getMembership().catch(() => null),
|
||||
getCurrentSubscription().catch(() => get().subscription),
|
||||
])
|
||||
set({ balance, dailyUsage, membership, subscription })
|
||||
} catch (err) {
|
||||
set({ error: (err as Error).message || "刷新积分失败" })
|
||||
}
|
||||
},
|
||||
|
||||
optimisticDeduct: (points: number) => {
|
||||
const { balance, membership } = get()
|
||||
if (!balance) return
|
||||
set({
|
||||
balance: {
|
||||
...balance,
|
||||
balance: Math.max(0, balance.balance - points),
|
||||
total_spent: balance.total_spent + points,
|
||||
},
|
||||
membership: membership
|
||||
? { ...membership, points_balance: Math.max(0, membership.points_balance - points) }
|
||||
: null,
|
||||
})
|
||||
},
|
||||
|
||||
optimisticAdd: (points: number) => {
|
||||
const { balance, membership } = get()
|
||||
if (!balance) return
|
||||
set({
|
||||
balance: {
|
||||
...balance,
|
||||
balance: balance.balance + points,
|
||||
total_earned: balance.total_earned + points,
|
||||
},
|
||||
membership: membership
|
||||
? { ...membership, points_balance: membership.points_balance + points }
|
||||
: null,
|
||||
})
|
||||
},
|
||||
|
||||
reset: () => {
|
||||
set({
|
||||
balance: null,
|
||||
dailyUsage: null,
|
||||
membership: null,
|
||||
rules: null,
|
||||
subscription: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
})
|
||||
},
|
||||
}))
|
||||
@@ -45,49 +45,60 @@ vi.mock("@/config/navigation", () => ({
|
||||
],
|
||||
}))
|
||||
|
||||
// mock antd icons
|
||||
vi.mock("@ant-design/icons", () => ({
|
||||
LogoutOutlined: () => <span data-testid="logout-icon" />,
|
||||
SettingOutlined: () => <span data-testid="setting-icon" />,
|
||||
UserOutlined: () => <span data-testid="user-icon" />,
|
||||
MenuOutlined: () => <span data-testid="menu-icon" />,
|
||||
}))
|
||||
// mock antd icons — 透传未显式 mock 的图标,避免 PointsBadge 等子组件引用新图标时报错
|
||||
vi.mock("@ant-design/icons", async () => {
|
||||
const actual = (await vi.importActual<typeof import("@ant-design/icons")>(
|
||||
"@ant-design/icons",
|
||||
)) as Record<string, unknown>
|
||||
return {
|
||||
...actual,
|
||||
LogoutOutlined: () => <span data-testid="logout-icon" />,
|
||||
SettingOutlined: () => <span data-testid="setting-icon" />,
|
||||
UserOutlined: () => <span data-testid="user-icon" />,
|
||||
MenuOutlined: () => <span data-testid="menu-icon" />,
|
||||
}
|
||||
})
|
||||
|
||||
// mock antd components
|
||||
vi.mock("antd", () => ({
|
||||
Avatar: ({ children, className }: any) => (
|
||||
<span data-testid="mock-avatar" className={className}>
|
||||
{children}
|
||||
</span>
|
||||
),
|
||||
Dropdown: ({ children, menu }: any) => (
|
||||
<div data-testid="mock-dropdown">
|
||||
{children}
|
||||
<div data-testid="dropdown-menu" style={{ display: "none" }}>
|
||||
{menu.items?.map((item: any, idx: number) => (
|
||||
<div key={idx} data-testid={`menu-item-${item.key}`} onClick={item.onClick}>
|
||||
{item.label}
|
||||
</div>
|
||||
))}
|
||||
// mock antd components — 用 importActual 透传未显式覆盖的组件(Popover/Button/Tag/Typography/Badge 等),
|
||||
// 避免 Header 子组件(PointsBadge)使用新 antd 导出时出现 "No xxx export is defined on the antd mock"
|
||||
vi.mock("antd", async () => {
|
||||
const actual = (await vi.importActual<typeof import("antd")>("antd")) as Record<string, unknown>
|
||||
return {
|
||||
...actual,
|
||||
Avatar: ({ children, className }: any) => (
|
||||
<span data-testid="mock-avatar" className={className}>
|
||||
{children}
|
||||
</span>
|
||||
),
|
||||
Dropdown: ({ children, menu }: any) => (
|
||||
<div data-testid="mock-dropdown">
|
||||
{children}
|
||||
<div data-testid="dropdown-menu" style={{ display: "none" }}>
|
||||
{menu.items?.map((item: any, idx: number) => (
|
||||
<div key={idx} data-testid={`menu-item-${item.key}`} onClick={item.onClick}>
|
||||
{item.label}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
Space: ({ children, className }: any) => (
|
||||
<div data-testid="mock-space" className={className}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
Drawer: ({ title, open, children, onClose, placement }: any) =>
|
||||
open ? (
|
||||
<div data-testid="mock-drawer" data-placement={placement}>
|
||||
<div data-testid="drawer-title">{title}</div>
|
||||
<button data-testid="drawer-close" onClick={onClose}>
|
||||
Close
|
||||
</button>
|
||||
),
|
||||
Space: ({ children, className }: any) => (
|
||||
<div data-testid="mock-space" className={className}>
|
||||
{children}
|
||||
</div>
|
||||
) : null,
|
||||
}))
|
||||
),
|
||||
Drawer: ({ title, open, children, onClose, placement }: any) =>
|
||||
open ? (
|
||||
<div data-testid="mock-drawer" data-placement={placement}>
|
||||
<div data-testid="drawer-title">{title}</div>
|
||||
<button data-testid="drawer-close" onClick={onClose}>
|
||||
Close
|
||||
</button>
|
||||
{children}
|
||||
</div>
|
||||
) : null,
|
||||
}
|
||||
})
|
||||
|
||||
// mock CSS
|
||||
vi.mock("@/components/layout/Header.css", () => ({}))
|
||||
|
||||
@@ -6,7 +6,6 @@ import logging
|
||||
import os
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from typing import List
|
||||
|
||||
import ffmpeg
|
||||
from shared.ffmpeg_utils import FFMPEG_ENCODE_CRF, FFMPEG_ENCODE_PRESET
|
||||
@@ -41,7 +40,7 @@ class VideoProcessor:
|
||||
|
||||
def concatenate_videos(
|
||||
self,
|
||||
input_paths: List[str],
|
||||
input_paths: list[str],
|
||||
output_path: str,
|
||||
resolution: tuple[int, int] = (1920, 1080),
|
||||
fps: int = 25,
|
||||
|
||||
@@ -18,9 +18,10 @@ from __future__ import annotations
|
||||
import logging
|
||||
import subprocess
|
||||
import tempfile
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from video_processing.oss_helpers import download_asset, upload_to_oss
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
|
||||
|
||||
def mark_asset_used_for_generation(asset, times: int = 1) -> None:
|
||||
@@ -15,6 +15,6 @@ def mark_asset_used_for_generation(asset, times: int = 1) -> None:
|
||||
asset.metadata = {
|
||||
**asset.metadata,
|
||||
"generation_use_count": int(asset.metadata.get("generation_use_count") or 0) + times,
|
||||
"last_used_at": datetime.now(timezone.utc).isoformat(),
|
||||
"last_used_at": datetime.now(UTC).isoformat(),
|
||||
"review_status": asset.metadata.get("review_status") or "pending_review",
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from packages.adapters.sqlalchemy_impl.models import TitleLibraryModel
|
||||
|
||||
@@ -10,6 +10,6 @@ def mark_title_used_for_generation(db, task) -> None:
|
||||
if title is None:
|
||||
return
|
||||
title.usage_count = int(title.usage_count or 0) + 1
|
||||
title.updated_at = datetime.now(timezone.utc)
|
||||
title.updated_at = datetime.now(UTC)
|
||||
db.add(title)
|
||||
db.commit()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Worker 启动时的初始化任务 — 孤儿任务清理等."""
|
||||
|
||||
import logging
|
||||
from datetime import UTC
|
||||
|
||||
from celery.signals import worker_ready
|
||||
from worker_app.db import SessionLocal
|
||||
@@ -130,14 +131,14 @@ def cleanup_stale_jobs(timeout_minutes: int = ORPHAN_TASK_TIMEOUT_MINUTES) -> in
|
||||
Returns:
|
||||
清理的任务数量
|
||||
"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from packages.adapters.sqlalchemy_impl.models import JobModel
|
||||
from packages.domain.job import JobStatus
|
||||
|
||||
try:
|
||||
session = SessionLocal()
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(minutes=timeout_minutes)
|
||||
cutoff = datetime.now(UTC) - timedelta(minutes=timeout_minutes)
|
||||
stale_jobs = (
|
||||
session.query(JobModel)
|
||||
.filter(
|
||||
|
||||
@@ -12,7 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
# ── 数据类 ───────────────────────────────────────────────────────────────────
|
||||
@@ -322,5 +322,5 @@ def build_error_info(error: Exception, stage: str = "render") -> dict[str, Any]:
|
||||
"message": str(error),
|
||||
"stack_trace": tb_summary,
|
||||
"stage": stage,
|
||||
"failed_at": datetime.now(timezone.utc).isoformat(),
|
||||
"failed_at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user