Files
xiaoxia-saas/packages/application/recipe/use_cases.py
T
CI Bot 9c6c477f55
CI/CD Pipeline / Validate Code Quality And Tests (pull_request) Failing after 2m22s
CI/CD Pipeline / Unit Tests (pull_request) Failing after 2m24s
CI/CD Pipeline / Integration Tests (pull_request) Failing after 37s
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 4m3s
CI/CD Pipeline / Build & Push Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Build Production Runtime Images (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
fix(backend): Phase 1 后端代码清理与修复
P0 关键修复:
- P0-1: 注册接口添加 RateLimitMiddleware 限流保护
- P0-3: /metrics 端点添加 JWT 认证(移除匿名访问)
- P0-4: 修复 Celery 任务名冲突(generation_task vs generate_video)
- P1-5: JWT logout token 黑名单机制

P1 修复:
- P1-1: forgot_password 硬编码 localhost → 使用 settings.APP_BASE_URL
- P1-2: generation.py 直接创建 DB 连接 → 使用依赖注入
- P1-6: Image.open() 未关闭 → 统一使用 with 语句
- P1-7: 订阅续费事务修复

P2 代码质量:
- P2-1: 修复 EditingMode 枚举重复定义 → 统一引用 shared 包
- P2-2: 修复 SMTP_FRON_NAME → SMTP_FROM_NAME 拼写
- P2-3: UserModel subscription_quota 类型统一为 float
- P2-4: .env.production DATABASE_MAX_OVERFLOW 30 → 10
- 清理 15 处 except:pass(保留 2 处有注释说明的)
- 禁用 SVG 上传(XSS 风险)
- 删除 decode_token_unsafe() 不安全函数
- 简化 /ready 端点
- 删除 8 处死代码、10 个空文件/模块
- 合并 3 对 100% 重复函数
- 对齐 6 个废弃环境变量

v2 修复(代码审查后):
- 修复密码重置路由路径: /password/forgot → /forgot-password,
  /password/reset → /reset-password(与前端 API 对齐)
- 合并 _check_project_access: asset_libraries.py 和 edit_plans.py
  中的重复函数统一到 _helpers.py(含空字符串守卫 + 中文错误信息)
- 顺手修复: HTTPException 统一从 fastapi 导入(替换 starlette 导入)
- OSS_ENDPOINT 拼写修复拆分为单独 PR,本 PR 不包含
2026-07-13 13:50:52 +08:00

185 lines
5.6 KiB
Python

"""Recipe use cases."""
from __future__ import annotations
import uuid
from dataclasses import dataclass
from typing import List, Optional
from packages.adapters.sqlalchemy_impl.recipe_repository import SQLAlchemyRecipeRepository
from packages.application.recipe.commands import (
CreateRecipeCommand,
UpdateRecipeCommand,
)
from packages.domain.recipe import Recipe, RecipeItem
from packages.infrastructure.feature_flags import FeatureScope, feature_flags
class NotFoundError(Exception):
pass
class FeatureDisabledError(Exception):
pass
@dataclass
class MissingAssetWarning:
"""使用配方时缺失的素材警告"""
item_type: str
item_id: str
position: int
class CreateRecipeUseCase:
def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
self.repository = repository
def execute(self, command: CreateRecipeCommand) -> Recipe:
recipe_id = uuid.uuid4().hex
recipe = Recipe(
id=recipe_id,
user_id=command.user_id,
name=command.name,
description=command.description,
template_id=command.template_id,
generation_params=command.generation_params,
metadata_=command.metadata_,
)
recipe = self.repository.create(recipe)
# Create items
if command.items:
items = [
RecipeItem(
id=uuid.uuid4().hex,
recipe_id=recipe.id,
item_type=ic.item_type,
item_id=ic.item_id,
position=ic.position,
metadata_=ic.metadata_,
)
for ic in command.items
]
self.repository.create_items(items)
recipe.items = items
return recipe
class ListRecipesUseCase:
def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
self.repository = repository
def execute(
self,
user_id: str,
*,
skip: int = 0,
limit: int = 50,
) -> List[Recipe]:
return self.repository.list_by_user(user_id, skip=skip, limit=limit)
class GetRecipeUseCase:
def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
self.repository = repository
def execute(self, recipe_id: str, user_id: str) -> Optional[Recipe]:
return self.repository.get(recipe_id, user_id)
class UpdateRecipeUseCase:
def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
self.repository = repository
def execute(self, command: UpdateRecipeCommand) -> Recipe:
existing = self.repository.get(command.recipe_id, command.user_id)
if existing is None:
raise NotFoundError(f"Recipe {command.recipe_id} not found")
if command.name is not None:
existing.name = command.name
if command.description is not None:
existing.description = command.description
if command.template_id is not None:
existing.template_id = command.template_id
if command.generation_params is not None:
existing.generation_params = command.generation_params
if command.metadata_ is not None:
existing.metadata_ = command.metadata_
self.repository.update(existing)
# Replace items if provided
if command.items is not None:
self.repository.delete_items_by_recipe(existing.id)
items = [
RecipeItem(
id=uuid.uuid4().hex,
recipe_id=existing.id,
item_type=ic.item_type,
item_id=ic.item_id,
position=ic.position,
metadata_=ic.metadata_,
)
for ic in command.items
]
self.repository.create_items(items)
existing.items = items
else:
existing.items = self.repository.list_items(existing.id)
return existing
class DeleteRecipeUseCase:
def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
self.repository = repository
def execute(self, recipe_id: str, user_id: str) -> bool:
return self.repository.delete(recipe_id, user_id)
@dataclass
class UseRecipeResult:
"""使用配方的结果"""
recipe: Recipe
warnings: List[MissingAssetWarning]
class UseRecipeUseCase:
"""使用配方 — 校验 Feature Flag + 检查素材可用性"""
def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
self.repository = repository
def execute(
self,
recipe_id: str,
user_id: str,
*,
user_plan: str = "free",
) -> UseRecipeResult:
# 1. 校验 Feature Flag(仅 basic/premium 可用)
if not feature_flags.is_enabled(
FeatureScope.RECIPE_REUSE,
user_plan=user_plan,
):
raise FeatureDisabledError("配方复用功能仅对基础版和高级版用户开放")
# 2. 获取配方
recipe = self.repository.get(recipe_id, user_id)
if recipe is None:
raise NotFoundError(f"Recipe {recipe_id} not found")
# 3. 校验引用的素材/标题/配音是否仍存在
warnings: List[MissingAssetWarning] = []
# Note: 实际项目中这里需要注入 asset/title/voice repository
# 来校验每个 item 是否仍然存在。当前版本返回空警告列表,
# 由调用方(路由层)决定是否传入额外的校验逻辑。
return UseRecipeResult(recipe=recipe, warnings=warnings)