feat: 完成阶段1核心基础设施优化
✅ 任务1: 完善模板验证工具 - 添加详细的错误代码和错误信息 - 添加性能监控(记录验证耗时) - 添加模板状态检查 - 添加批量验证功能 - 添加结构化日志记录 ✅ 任务2: 优化上传API的模板验证 - 集成增强的validateTemplateId函数 - 添加详细的验证日志 - 返回错误代码便于前端处理 ✅ 任务3: 增强字段池同步机制 - 添加增量同步支持 - 添加同步失败重试机制(指数退避) - 添加详细的同步统计信息 - 添加同步日志和监控 - 优化错误处理 相关需求: 1.1-1.4, 3.1-3.4, 6.1-6.4, 24.1-24.5
This commit is contained in:
parent
542c7bcc49
commit
6756d5e72c
@ -0,0 +1,909 @@
|
||||
# 自定义上传模板系统优化 - 技术设计文档
|
||||
|
||||
## 概述
|
||||
|
||||
本文档描述了FLNXI素材库自定义上传模板系统的优化设计方案。该系统是整个平台的核心基础设施,负责定义素材的上传表单结构、元数据字段、分类筛选和共享展示。
|
||||
|
||||
### 设计目标
|
||||
|
||||
1. **稳定性**: 确保模板系统在各种场景下都能可靠运行,不会因为数据异常导致系统崩溃
|
||||
2. **性能**: 优化模板加载、字段同步、分类筛选等关键操作的性能
|
||||
3. **可维护性**: 提供清晰的代码结构和完善的错误处理,便于后续维护和扩展
|
||||
4. **向后兼容**: 确保优化不会破坏现有功能,支持旧数据的平滑迁移
|
||||
|
||||
## 架构设计
|
||||
|
||||
### 系统架构图
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 前端层 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ UploadModal │ TemplateManager │ CategoriesTab │ 首页 │
|
||||
│ (上传表单) │ (模板管理) │ (分类管理) │ (筛选) │
|
||||
└────────┬──────────────┬──────────────┬──────────────┬───────┘
|
||||
│ │ │ │
|
||||
▼ ▼ ▼ ▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ API层 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ /api/materials/upload │
|
||||
│ /api/upload-templates │
|
||||
│ /api/admin/upload-templates │
|
||||
│ /api/template-categories │
|
||||
│ /api/category-fields │
|
||||
└────────┬──────────────┬──────────────┬──────────────────────┘
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 业务逻辑层 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ template-validator.ts │ field-pool.ts │ upload-template-│
|
||||
│ (模板验证) │ (字段池管理) │ presets.ts │
|
||||
│ │ │ (内置模板) │
|
||||
└────────┬────────────────┬─────────────────┬─────────────────┘
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 数据访问层 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ Prisma ORM │
|
||||
│ - UploadTemplate │
|
||||
│ - UploadField │
|
||||
│ - FieldDefinition │
|
||||
│ - FieldOption │
|
||||
│ - Material │
|
||||
└────────┬────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 数据库层 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ PostgreSQL │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 核心组件
|
||||
|
||||
#### 1. 模板验证器 (template-validator.ts)
|
||||
|
||||
**职责**: 统一处理内置模板和自定义模板的验证逻辑
|
||||
|
||||
**核心函数**:
|
||||
```typescript
|
||||
// 验证模板ID是否有效
|
||||
validateTemplateId(templateId: string | null): Promise<TemplateValidationResult>
|
||||
|
||||
// 检查是否为内置模板
|
||||
isBuiltinTemplate(templateId: string): boolean
|
||||
|
||||
// 提取内置模板key
|
||||
extractBuiltinTemplateKey(templateId: string): BuiltinTemplateKey | null
|
||||
|
||||
// 获取模板完整信息(包括字段)
|
||||
getTemplateWithFields(templateId: string): Promise<Template | null>
|
||||
```
|
||||
|
||||
**验证流程**:
|
||||
```
|
||||
输入: templateId
|
||||
│
|
||||
├─ 是否为空? ──Yes──> 返回 valid=true (向后兼容)
|
||||
│
|
||||
└─ No
|
||||
│
|
||||
├─ 是否以 "builtin-" 开头?
|
||||
│ │
|
||||
│ ├─ Yes (内置模板)
|
||||
│ │ │
|
||||
│ │ └─ 验证 key 是否在预设列表中
|
||||
│ │ │
|
||||
│ │ ├─ Yes ──> 返回 valid=true
|
||||
│ │ └─ No ──> 返回 valid=false, error="无效的内置模板"
|
||||
│ │
|
||||
│ └─ No (自定义模板)
|
||||
│ │
|
||||
│ └─ 从数据库查询
|
||||
│ │
|
||||
│ ├─ 存在且状态为active ──> 返回 valid=true
|
||||
│ └─ 不存在或状态非active ──> 返回 valid=false, error="模板不存在或未启用"
|
||||
```
|
||||
|
||||
#### 2. 字段池管理器 (field-pool.ts)
|
||||
|
||||
**职责**: 管理模板字段与字段池之间的同步
|
||||
|
||||
**核心函数**:
|
||||
```typescript
|
||||
// 从模板同步字段到字段池
|
||||
syncFieldPoolFromTemplates(): Promise<void>
|
||||
|
||||
// 获取所有字段池记录
|
||||
getFieldPoolRecords(): Promise<FieldDefinition[]>
|
||||
|
||||
// 获取已启用的筛选字段
|
||||
getEnabledFilterFields(): Promise<FilterField[]>
|
||||
|
||||
// 更新字段的启用状态
|
||||
updateFieldFilterState(fieldKey: string, enabled: boolean): Promise<void>
|
||||
|
||||
// 规范化字段选项值
|
||||
normalizeFieldOptionValue(option: string): string
|
||||
|
||||
// 解析静态选项
|
||||
parseOptionsStatic(raw: string): string[]
|
||||
|
||||
// 格式化字段选项值
|
||||
formatFieldOptionValues(optionRecords: FieldOption[]): string[]
|
||||
```
|
||||
|
||||
**同步流程**:
|
||||
```
|
||||
触发: 模板创建/更新/删除
|
||||
│
|
||||
├─ 1. 扫描所有模板的 addToCategory=true 字段
|
||||
│ │
|
||||
│ └─ 聚合相同key的字段
|
||||
│ │
|
||||
│ └─ 合并选项列表
|
||||
│
|
||||
├─ 2. 更新 FieldDefinition 表
|
||||
│ │
|
||||
│ ├─ 新增字段: 创建记录
|
||||
│ ├─ 已存在字段: 更新 sourceTemplateIds
|
||||
│ └─ 孤立字段: 删除记录
|
||||
│
|
||||
├─ 3. 同步 FieldOption 表
|
||||
│ │
|
||||
│ ├─ 清洗选项值 (去括号、trim、去重)
|
||||
│ ├─ 新增选项: 创建记录
|
||||
│ ├─ 已存在选项: 更新 orderIndex
|
||||
│ └─ 废弃选项: 删除记录
|
||||
│
|
||||
└─ 4. 返回结果
|
||||
```
|
||||
|
||||
#### 3. 内置模板预设 (upload-template-presets.ts)
|
||||
|
||||
**职责**: 定义和生成内置模板
|
||||
|
||||
**内置模板列表**:
|
||||
- `builtin-3dmax-material`: 3DMAX 素材模板
|
||||
- `builtin-psd-material`: PSD 素材模板
|
||||
- `builtin-ai-material`: AI 工作流
|
||||
- `builtin-video-material`: 视频素材模板
|
||||
- `builtin-model-material`: 模特素材模板
|
||||
- `builtin-other-material`: 其他素材模板
|
||||
|
||||
**标准字段**:
|
||||
```typescript
|
||||
{
|
||||
productModel: SPU型号 (text, required)
|
||||
categoryName: 使用店铺 (select, required, addToCategory)
|
||||
sceneName: 场景类别 (select, required, addToCategory)
|
||||
platformName: 平台分类 (text, addToCategory)
|
||||
renderer: 渲染器 (select, addToCategory)
|
||||
brandName: 品牌名称 (text)
|
||||
seriesName: 系列/产品线 (text)
|
||||
skuCode: SKU编码 (text)
|
||||
materialTexture: 材质/工艺 (text)
|
||||
renderTime: 渲染耗时 (text)
|
||||
imageResolution: 输出分辨率 (text)
|
||||
colorMode: 颜色模式 (text)
|
||||
authorName: 作者 (text)
|
||||
}
|
||||
```
|
||||
|
||||
## 数据模型
|
||||
|
||||
### UploadTemplate (上传模板)
|
||||
|
||||
```typescript
|
||||
{
|
||||
id: string // UUID
|
||||
name: string // 模板名称
|
||||
description: string? // 描述
|
||||
status: string // draft | active | archived
|
||||
materialType: string // 素材类型文案
|
||||
materialKind: string // 素材大类: IMAGE | VIDEO | OTHER
|
||||
version: int // 版本号(用于并发控制)
|
||||
fieldGroups: string? // 字段分组配置 (JSON)
|
||||
displayConfig: string? // 显示配置 (JSON)
|
||||
createdAt: DateTime
|
||||
updatedAt: DateTime
|
||||
fields: UploadField[] // 关联字段
|
||||
}
|
||||
```
|
||||
|
||||
### UploadField (上传字段)
|
||||
|
||||
```typescript
|
||||
{
|
||||
id: string // UUID
|
||||
templateId: string // 所属模板ID
|
||||
key: string // 字段键名
|
||||
label: string // 字段标签
|
||||
type: string // 字段类型: text | textarea | select | number | date | checkbox | file | image
|
||||
required: boolean // 是否必填
|
||||
orderIndex: int // 排序索引
|
||||
layoutWidth: string? // 布局宽度: full | half
|
||||
validations: string? // 验证规则 (JSON)
|
||||
optionsSource: string? // 选项来源
|
||||
optionsStatic: string? // 静态选项 (JSON字符串)
|
||||
allowedExtensions: string? // 允许的文件扩展名
|
||||
visibleOnHomeFilter: boolean // 首页筛选可见
|
||||
isSearchable: boolean // 可搜索
|
||||
isReadOnly: boolean // 只读
|
||||
addToCategory: boolean // 添加到分类管理
|
||||
conditions: string? // 显示条件 (JSON)
|
||||
createdAt: DateTime
|
||||
updatedAt: DateTime
|
||||
}
|
||||
```
|
||||
|
||||
### FieldDefinition (字段池定义)
|
||||
|
||||
```typescript
|
||||
{
|
||||
id: string // UUID
|
||||
key: string // 字段键名 (unique)
|
||||
label: string // 字段标签
|
||||
type: string // 字段类型
|
||||
description: string? // 描述
|
||||
source: string // 来源: standard | custom
|
||||
sourceTemplateIds: string? // 引用此字段的模板ID列表 (JSON数组)
|
||||
isStandard: boolean // 是否标准字段
|
||||
isFilterEnabled: boolean // 是否启用筛选
|
||||
filterDisplayName: string? // 筛选显示名称
|
||||
filterOrder: int // 筛选排序
|
||||
createdAt: DateTime
|
||||
updatedAt: DateTime
|
||||
options: FieldOption[] // 关联选项
|
||||
}
|
||||
```
|
||||
|
||||
### FieldOption (字段选项)
|
||||
|
||||
```typescript
|
||||
{
|
||||
id: string // UUID
|
||||
fieldId: string // 所属字段ID
|
||||
value: string // 选项值
|
||||
label: string // 选项标签
|
||||
orderIndex: int // 排序索引
|
||||
createdAt: DateTime
|
||||
updatedAt: DateTime
|
||||
|
||||
// 联合唯一约束: [fieldId, value]
|
||||
}
|
||||
```
|
||||
|
||||
### Material (素材)
|
||||
|
||||
```typescript
|
||||
{
|
||||
id: string // 素材ID
|
||||
templateId: string? // 关联的模板ID (可为null)
|
||||
metadata: string? // 自定义字段数据 (JSON)
|
||||
|
||||
// 标准字段
|
||||
productModel: string
|
||||
categoryName: string
|
||||
sceneName: string
|
||||
platformName: string
|
||||
materialType: string
|
||||
materialKind: string
|
||||
renderer: string
|
||||
brandName: string?
|
||||
seriesName: string?
|
||||
skuCode: string?
|
||||
materialTexture: string?
|
||||
renderTime: string?
|
||||
imageResolution: string?
|
||||
colorMode: string?
|
||||
authorName: string
|
||||
|
||||
// ... 其他字段
|
||||
}
|
||||
```
|
||||
|
||||
## 组件接口
|
||||
|
||||
### API接口
|
||||
|
||||
#### 1. 获取上传模板列表
|
||||
|
||||
```typescript
|
||||
GET /api/upload-templates
|
||||
|
||||
Response: {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
status: string
|
||||
materialType: string
|
||||
materialKind: string
|
||||
isBuiltin: boolean
|
||||
materialCount: number
|
||||
fields: UploadField[]
|
||||
}[]
|
||||
```
|
||||
|
||||
#### 2. 创建自定义模板
|
||||
|
||||
```typescript
|
||||
POST /api/admin/upload-templates
|
||||
|
||||
Request: {
|
||||
name: string
|
||||
description?: string
|
||||
status?: string
|
||||
materialType: string
|
||||
materialKind: string
|
||||
fieldGroups?: string
|
||||
displayConfig?: string
|
||||
fields: {
|
||||
key: string
|
||||
label: string
|
||||
type: string
|
||||
required: boolean
|
||||
orderIndex: number
|
||||
layoutWidth?: string
|
||||
validations?: string
|
||||
optionsStatic?: string
|
||||
visibleOnHomeFilter: boolean
|
||||
isSearchable: boolean
|
||||
isReadOnly: boolean
|
||||
addToCategory: boolean
|
||||
conditions?: string
|
||||
}[]
|
||||
}
|
||||
|
||||
Response: UploadTemplate
|
||||
```
|
||||
|
||||
#### 3. 更新自定义模板
|
||||
|
||||
```typescript
|
||||
PUT /api/admin/upload-templates/[id]
|
||||
|
||||
Request: {
|
||||
name?: string
|
||||
description?: string
|
||||
status?: string
|
||||
materialType?: string
|
||||
materialKind?: string
|
||||
fieldGroups?: string
|
||||
displayConfig?: string
|
||||
version: number // 用于并发控制
|
||||
fields?: UploadField[]
|
||||
}
|
||||
|
||||
Response: UploadTemplate
|
||||
|
||||
Error (409): {
|
||||
error: "模板已被其他人修改,请刷新后重试"
|
||||
}
|
||||
```
|
||||
|
||||
#### 4. 删除自定义模板
|
||||
|
||||
```typescript
|
||||
DELETE /api/admin/upload-templates/[id]
|
||||
|
||||
Response: {
|
||||
success: boolean
|
||||
}
|
||||
```
|
||||
|
||||
#### 5. 获取分类字段
|
||||
|
||||
```typescript
|
||||
GET /api/template-categories
|
||||
|
||||
Response: {
|
||||
key: string
|
||||
label: string
|
||||
defaultLabel: string
|
||||
filterOrder: number
|
||||
options: string[]
|
||||
}[]
|
||||
```
|
||||
|
||||
#### 6. 更新分类字段
|
||||
|
||||
```typescript
|
||||
PUT /api/category-fields
|
||||
|
||||
Request: {
|
||||
fields: {
|
||||
key: string
|
||||
filterOrder: number
|
||||
filterDisplayName: string
|
||||
}[]
|
||||
}
|
||||
|
||||
Response: {
|
||||
success: boolean
|
||||
}
|
||||
```
|
||||
|
||||
#### 7. 上传素材
|
||||
|
||||
```typescript
|
||||
POST /api/materials/upload
|
||||
|
||||
Request (FormData): {
|
||||
templateId?: string
|
||||
templateFields?: string // JSON字符串
|
||||
previewImages: File[]
|
||||
displayImage?: File
|
||||
zipFile?: File
|
||||
|
||||
// 标准字段
|
||||
productModel: string
|
||||
categoryName: string
|
||||
sceneName: string
|
||||
platformName?: string
|
||||
materialType: string
|
||||
materialKind: string
|
||||
renderer?: string
|
||||
brandName?: string
|
||||
seriesName?: string
|
||||
skuCode?: string
|
||||
materialTexture?: string
|
||||
renderTime?: string
|
||||
imageResolution?: string
|
||||
colorMode?: string
|
||||
}
|
||||
|
||||
Response: {
|
||||
id: string
|
||||
previewUrl: string
|
||||
// ... 其他字段
|
||||
}
|
||||
|
||||
Error (400): {
|
||||
error: "模板不存在:builtin-xxx" | "无效的内置模板:builtin-xxx" | "模板未启用"
|
||||
}
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
### 错误类型
|
||||
|
||||
1. **模板验证错误**
|
||||
- 内置模板key无效
|
||||
- 自定义模板不存在
|
||||
- 模板状态非active
|
||||
|
||||
2. **字段验证错误**
|
||||
- 字段key重复
|
||||
- 字段类型无效
|
||||
- 必填字段为空
|
||||
- 验证规则不满足
|
||||
|
||||
3. **数据完整性错误**
|
||||
- 版本冲突
|
||||
- 外键约束违反
|
||||
- 唯一约束违反
|
||||
|
||||
4. **字段池同步错误**
|
||||
- 选项解析失败
|
||||
- 数据库操作失败
|
||||
|
||||
### 错误处理策略
|
||||
|
||||
```typescript
|
||||
// 1. API层错误处理
|
||||
try {
|
||||
// 业务逻辑
|
||||
} catch (error) {
|
||||
console.error('[API] Error:', {
|
||||
endpoint: '/api/xxx',
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
context: { /* 相关上下文 */ }
|
||||
})
|
||||
|
||||
// 返回用户友好的错误信息
|
||||
return NextResponse.json(
|
||||
{ error: getUserFriendlyMessage(error) },
|
||||
{ status: getStatusCode(error) }
|
||||
)
|
||||
}
|
||||
|
||||
// 2. 业务逻辑层错误处理
|
||||
async function validateTemplateId(templateId: string) {
|
||||
try {
|
||||
// 验证逻辑
|
||||
} catch (error) {
|
||||
console.error('[TemplateValidator] Error:', error)
|
||||
return {
|
||||
valid: false,
|
||||
error: `验证模板时发生错误:${error.message}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 字段池同步错误处理
|
||||
async function syncFieldPoolFromTemplates() {
|
||||
try {
|
||||
// 同步逻辑
|
||||
} catch (error) {
|
||||
console.error('[FieldPool] Sync error:', error)
|
||||
// 记录错误但不抛出,避免影响模板保存
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 测试策略
|
||||
|
||||
### 单元测试
|
||||
|
||||
**模板验证器测试**:
|
||||
```typescript
|
||||
describe('template-validator', () => {
|
||||
test('应该验证内置模板ID', async () => {
|
||||
const result = await validateTemplateId('builtin-video-material')
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.isBuiltin).toBe(true)
|
||||
})
|
||||
|
||||
test('应该拒绝无效的内置模板ID', async () => {
|
||||
const result = await validateTemplateId('builtin-invalid')
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.error).toContain('无效的内置模板')
|
||||
})
|
||||
|
||||
test('应该验证自定义模板ID', async () => {
|
||||
// Mock数据库查询
|
||||
const result = await validateTemplateId('custom-template-id')
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.isBuiltin).toBe(false)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
**字段池管理器测试**:
|
||||
```typescript
|
||||
describe('field-pool', () => {
|
||||
test('应该规范化字段选项值', () => {
|
||||
expect(normalizeFieldOptionValue('[[[选项]]]')).toBe('选项')
|
||||
expect(normalizeFieldOptionValue(' 选项 ')).toBe('选项')
|
||||
expect(normalizeFieldOptionValue('"选项"')).toBe('选项')
|
||||
})
|
||||
|
||||
test('应该解析静态选项', () => {
|
||||
const options = parseOptionsStatic('["选项1", "选项2"]')
|
||||
expect(options).toEqual(['选项1', '选项2'])
|
||||
})
|
||||
|
||||
test('应该去重选项', () => {
|
||||
const options = parseOptionsStatic('["选项1", "选项1", "选项2"]')
|
||||
expect(options).toEqual(['选项1', '选项2'])
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
### 集成测试
|
||||
|
||||
**模板创建流程测试**:
|
||||
```typescript
|
||||
describe('Template Creation Flow', () => {
|
||||
test('应该创建自定义模板并同步字段池', async () => {
|
||||
// 1. 创建模板
|
||||
const template = await createTemplate({
|
||||
name: '测试模板',
|
||||
fields: [
|
||||
{ key: 'testField', label: '测试字段', addToCategory: true }
|
||||
]
|
||||
})
|
||||
|
||||
// 2. 验证模板创建成功
|
||||
expect(template.id).toBeDefined()
|
||||
|
||||
// 3. 验证字段池同步
|
||||
const fieldDef = await getFieldDefinition('testField')
|
||||
expect(fieldDef).toBeDefined()
|
||||
expect(fieldDef.sourceTemplateIds).toContain(template.id)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
**素材上传流程测试**:
|
||||
```typescript
|
||||
describe('Material Upload Flow', () => {
|
||||
test('应该使用内置模板上传素材', async () => {
|
||||
const material = await uploadMaterial({
|
||||
templateId: 'builtin-video-material',
|
||||
productModel: '测试产品',
|
||||
categoryName: '测试分类',
|
||||
sceneName: '测试场景'
|
||||
})
|
||||
|
||||
expect(material.id).toBeDefined()
|
||||
expect(material.templateId).toBe('builtin-video-material')
|
||||
})
|
||||
|
||||
test('应该使用自定义模板上传素材', async () => {
|
||||
const template = await createTemplate({ /* ... */ })
|
||||
const material = await uploadMaterial({
|
||||
templateId: template.id,
|
||||
templateFields: { testField: '测试值' }
|
||||
})
|
||||
|
||||
expect(material.metadata).toContain('testField')
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## 性能优化
|
||||
|
||||
### 1. 数据库查询优化
|
||||
|
||||
**使用索引**:
|
||||
```sql
|
||||
-- Material表索引
|
||||
CREATE INDEX idx_material_template_id ON materials(templateId);
|
||||
CREATE INDEX idx_material_category_name ON materials(categoryName);
|
||||
CREATE INDEX idx_material_scene_name ON materials(sceneName);
|
||||
|
||||
-- FieldDefinition表索引
|
||||
CREATE INDEX idx_field_definition_key ON field_definitions(key);
|
||||
CREATE INDEX idx_field_definition_filter_enabled ON field_definitions(isFilterEnabled);
|
||||
CREATE INDEX idx_field_definition_filter_order ON field_definitions(filterOrder);
|
||||
|
||||
-- FieldOption表索引
|
||||
CREATE INDEX idx_field_option_field_id ON field_options(fieldId);
|
||||
CREATE INDEX idx_field_option_order ON field_options(orderIndex);
|
||||
```
|
||||
|
||||
**批量操作**:
|
||||
```typescript
|
||||
// ❌ 不好的做法:逐个插入
|
||||
for (const option of options) {
|
||||
await prisma.fieldOption.create({ data: option })
|
||||
}
|
||||
|
||||
// ✅ 好的做法:批量插入
|
||||
await prisma.fieldOption.createMany({
|
||||
data: options
|
||||
})
|
||||
```
|
||||
|
||||
**使用事务**:
|
||||
```typescript
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// 1. 更新模板
|
||||
await tx.uploadTemplate.update({ /* ... */ })
|
||||
|
||||
// 2. 删除旧字段
|
||||
await tx.uploadField.deleteMany({ /* ... */ })
|
||||
|
||||
// 3. 创建新字段
|
||||
await tx.uploadField.createMany({ /* ... */ })
|
||||
})
|
||||
```
|
||||
|
||||
### 2. 前端性能优化
|
||||
|
||||
**虚拟滚动**:
|
||||
```typescript
|
||||
// 当字段数量超过30个时使用虚拟滚动
|
||||
{fields.length > 30 ? (
|
||||
<VirtualList
|
||||
items={fields}
|
||||
itemHeight={60}
|
||||
renderItem={(field) => <FieldCard field={field} />}
|
||||
/>
|
||||
) : (
|
||||
fields.map(field => <FieldCard key={field.id} field={field} />)
|
||||
)}
|
||||
```
|
||||
|
||||
**防抖**:
|
||||
```typescript
|
||||
// 用户输入时使用防抖减少验证频率
|
||||
const debouncedValidate = useMemo(
|
||||
() => debounce((value) => validateField(value), 300),
|
||||
[]
|
||||
)
|
||||
```
|
||||
|
||||
**缓存**:
|
||||
```typescript
|
||||
// 缓存模板列表
|
||||
const { data: templates, isLoading } = useSWR(
|
||||
'/api/upload-templates',
|
||||
fetcher,
|
||||
{ revalidateOnFocus: false }
|
||||
)
|
||||
```
|
||||
|
||||
### 3. 字段池同步优化
|
||||
|
||||
**增量同步**:
|
||||
```typescript
|
||||
// 只同步变更的字段,而不是全量同步
|
||||
async function syncChangedFields(templateId: string, changedFields: string[]) {
|
||||
for (const fieldKey of changedFields) {
|
||||
await syncSingleField(fieldKey)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**异步同步**:
|
||||
```typescript
|
||||
// 模板保存后异步同步字段池,不阻塞响应
|
||||
await prisma.uploadTemplate.update({ /* ... */ })
|
||||
|
||||
// 异步同步
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await syncFieldPoolFromTemplates()
|
||||
} catch (error) {
|
||||
console.error('[FieldPool] Async sync error:', error)
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json(template)
|
||||
```
|
||||
|
||||
## 部署和迁移
|
||||
|
||||
### 数据库迁移
|
||||
|
||||
**添加版本控制字段**:
|
||||
```sql
|
||||
ALTER TABLE upload_templates ADD COLUMN version INTEGER DEFAULT 1;
|
||||
```
|
||||
|
||||
**添加字段池表**:
|
||||
```sql
|
||||
-- 已存在,无需迁移
|
||||
```
|
||||
|
||||
**数据迁移脚本**:
|
||||
```typescript
|
||||
// 迁移旧素材的templateId
|
||||
async function migrateOldMaterials() {
|
||||
const materials = await prisma.material.findMany({
|
||||
where: { templateId: null }
|
||||
})
|
||||
|
||||
for (const material of materials) {
|
||||
// 根据materialType推断templateId
|
||||
const templateId = inferTemplateId(material.materialType)
|
||||
await prisma.material.update({
|
||||
where: { id: material.id },
|
||||
data: { templateId }
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 部署步骤
|
||||
|
||||
1. **备份数据库**
|
||||
```bash
|
||||
pg_dump -U postgres -d flnxi > backup_$(date +%Y%m%d).sql
|
||||
```
|
||||
|
||||
2. **运行数据库迁移**
|
||||
```bash
|
||||
npm run prisma:migrate deploy
|
||||
```
|
||||
|
||||
3. **同步字段池**
|
||||
```bash
|
||||
npm run sync-field-pool
|
||||
```
|
||||
|
||||
4. **部署新代码**
|
||||
```bash
|
||||
./deploy-new-fixed.ps1
|
||||
```
|
||||
|
||||
5. **验证部署**
|
||||
```bash
|
||||
curl http://localhost:3000/api/health
|
||||
```
|
||||
|
||||
## 监控和日志
|
||||
|
||||
### 关键指标
|
||||
|
||||
1. **模板操作**
|
||||
- 模板创建/更新/删除次数
|
||||
- 模板验证失败次数
|
||||
- 平均响应时间
|
||||
|
||||
2. **字段池同步**
|
||||
- 同步成功/失败次数
|
||||
- 同步耗时
|
||||
- 字段数量变化
|
||||
|
||||
3. **素材上传**
|
||||
- 使用各模板的上传次数
|
||||
- 上传失败次数(按错误类型分类)
|
||||
- 平均上传时间
|
||||
|
||||
### 日志格式
|
||||
|
||||
```typescript
|
||||
// 结构化日志
|
||||
console.log(JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: 'info',
|
||||
module: 'template-validator',
|
||||
action: 'validate',
|
||||
templateId: 'builtin-video-material',
|
||||
result: 'success',
|
||||
duration: 15
|
||||
}))
|
||||
```
|
||||
|
||||
## 安全考虑
|
||||
|
||||
### 1. 权限控制
|
||||
|
||||
```typescript
|
||||
// 只有管理员可以创建/修改/删除模板
|
||||
async function requireAdmin(session: Session | null) {
|
||||
if (!session || session.user.role !== 'ADMIN') {
|
||||
throw new Error('Unauthorized')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 输入验证
|
||||
|
||||
```typescript
|
||||
// 验证字段key格式
|
||||
const FIELD_KEY_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/
|
||||
|
||||
if (!FIELD_KEY_PATTERN.test(fieldKey)) {
|
||||
throw new Error('字段key只能包含字母、数字和下划线,且必须以字母开头')
|
||||
}
|
||||
```
|
||||
|
||||
### 3. SQL注入防护
|
||||
|
||||
```typescript
|
||||
// 使用Prisma ORM,自动防护SQL注入
|
||||
await prisma.uploadTemplate.findUnique({
|
||||
where: { id: templateId } // 参数化查询
|
||||
})
|
||||
```
|
||||
|
||||
### 4. XSS防护
|
||||
|
||||
```typescript
|
||||
// React自动转义,但对于动态HTML需要额外处理
|
||||
import DOMPurify from 'dompurify'
|
||||
|
||||
const sanitizedHtml = DOMPurify.sanitize(userInput)
|
||||
```
|
||||
|
||||
## 未来扩展
|
||||
|
||||
### 1. 模板版本历史
|
||||
|
||||
记录模板的每次修改,支持回滚到历史版本。
|
||||
|
||||
### 2. 模板市场
|
||||
|
||||
允许用户分享和下载模板配置。
|
||||
|
||||
### 3. 智能字段推荐
|
||||
|
||||
根据素材类型和历史数据,推荐常用字段。
|
||||
|
||||
### 4. 字段依赖关系
|
||||
|
||||
支持更复杂的字段显示条件和联动逻辑。
|
||||
|
||||
### 5. 多语言支持
|
||||
|
||||
支持字段标签和选项的多语言配置。
|
||||
245
.kiro/specs/template-system-optimization/tasks.md
Normal file
245
.kiro/specs/template-system-optimization/tasks.md
Normal file
@ -0,0 +1,245 @@
|
||||
# 自定义上传模板系统优化 - 实施任务列表
|
||||
|
||||
## 阶段 1: 核心基础设施优化
|
||||
|
||||
- [x] 1. 完善模板验证工具
|
||||
|
||||
|
||||
- 已创建 `lib/template-validator.ts` 基础版本
|
||||
- 添加更详细的错误信息和日志
|
||||
- 添加模板状态检查(draft/active/archived)
|
||||
- 添加单元测试
|
||||
- _需求: 1.1, 1.2, 1.3, 1.4_
|
||||
|
||||
- [x] 2. 优化上传API的模板验证
|
||||
|
||||
- 已集成 `validateTemplateId` 函数
|
||||
- 优化错误处理和日志记录
|
||||
- 添加性能监控(记录验证耗时)
|
||||
- _需求: 1.1, 1.2, 1.3, 6.1, 6.4_
|
||||
|
||||
- [x] 3. 增强字段池同步机制
|
||||
|
||||
|
||||
- 优化 `syncFieldPoolFromTemplates` 函数
|
||||
- 添加增量同步支持(只同步变更的字段)
|
||||
- 添加同步失败重试机制
|
||||
- 添加同步日志和监控
|
||||
- _需求: 3.1, 3.2, 3.3, 3.4, 24.1, 24.2, 24.3, 24.4, 24.5_
|
||||
|
||||
- [ ] 4. 优化选项清洗逻辑
|
||||
- 增强 `normalizeFieldOptionValue` 函数
|
||||
- 添加更多边界情况处理
|
||||
- 添加清洗失败的警告日志
|
||||
- 添加单元测试覆盖各种脏数据场景
|
||||
- _需求: 3.4, 28.1, 28.2, 28.3, 28.4, 28.5, 28.6, 28.7_
|
||||
|
||||
## 阶段 2: 模板管理功能增强
|
||||
|
||||
- [ ] 5. 实现模板版本控制
|
||||
- 在模板更新API中添加版本号检查
|
||||
- 检测并发冲突,返回409状态码
|
||||
- 更新成功后自动递增版本号
|
||||
- 添加版本冲突的前端提示
|
||||
- _需求: 4.1, 4.2, 4.3, 4.4_
|
||||
|
||||
- [ ] 6. 增强模板数据完整性验证
|
||||
- 验证必填字段(name, materialType, materialKind)
|
||||
- 检查字段key的唯一性
|
||||
- 自动转换optionsStatic数组为JSON字符串
|
||||
- 规范化materialKind值
|
||||
- 添加删除模板时的警告提示
|
||||
- _需求: 5.1, 5.2, 5.3, 5.4, 5.5_
|
||||
|
||||
- [ ] 7. 优化模板CRUD API的错误处理
|
||||
- 统一错误响应格式
|
||||
- 添加详细的错误日志
|
||||
- 处理Prisma特定错误代码(P2002, P2003等)
|
||||
- 返回用户友好的错误信息
|
||||
- _需求: 6.1, 6.2, 6.3, 6.4_
|
||||
|
||||
- [ ] 8. 实现模板使用统计
|
||||
- 在模板列表API中添加materialCount字段
|
||||
- 创建模板详情页,显示使用该模板的素材列表
|
||||
- 统计每个字段的填写率
|
||||
- 提供低填写率字段的优化建议
|
||||
- _需求: 14.1, 14.2, 14.3, 14.4, 14.5_
|
||||
|
||||
## 阶段 3: 自定义字段功能完善
|
||||
|
||||
- [ ] 9. 优化字段创建和管理UI
|
||||
- 实时验证字段key的唯一性和格式
|
||||
- 添加字段复制功能
|
||||
- 优化拖拽排序的流畅度
|
||||
- 添加字段删除确认对话框
|
||||
- _需求: 16.1, 16.2, 16.3, 16.4, 16.5, 16.6, 16.7_
|
||||
|
||||
- [ ] 10. 增强select字段的选项管理
|
||||
- 支持逐行输入和JSON数组两种格式
|
||||
- 自动清洗和规范化选项值
|
||||
- 自动去重选项
|
||||
- 展开嵌套数组格式
|
||||
- 保存时转换为JSON字符串
|
||||
- _需求: 17.1, 17.2, 17.3, 17.4, 17.5, 17.6, 17.7_
|
||||
|
||||
- [ ] 11. 实现字段验证规则配置
|
||||
- 支持必填验证
|
||||
- 支持最大长度验证(text字段)
|
||||
- 支持范围验证(number字段)
|
||||
- 支持正则表达式验证
|
||||
- 支持自定义错误提示
|
||||
- 前端实时验证和后端验证
|
||||
- _需求: 18.1, 18.2, 18.3, 18.4, 18.5, 18.6, 18.7_
|
||||
|
||||
- [ ] 12. 实现字段条件显示
|
||||
- 创建可视化条件编辑器
|
||||
- 支持简单条件(字段A等于值X)
|
||||
- 支持复杂条件(AND/OR逻辑)
|
||||
- 实时计算条件结果
|
||||
- 检测循环依赖
|
||||
- _需求: 19.1, 19.2, 19.3, 19.4, 19.5, 19.6, 19.7_
|
||||
|
||||
## 阶段 4: 数据存储和兼容性
|
||||
|
||||
- [ ] 13. 优化自定义字段数据存储
|
||||
- 实现字段key到标准字段的映射
|
||||
- 优化metadata JSON字段的存储
|
||||
- 实现数据读取时的合并逻辑
|
||||
- 处理metadata字段超限的情况
|
||||
- _需求: 20.1, 20.2, 20.3, 20.4, 20.5, 20.6, 20.7_
|
||||
|
||||
- [ ] 14. 实现字段迁移工具
|
||||
- 创建字段key修改的迁移工具
|
||||
- 实现字段类型转换验证
|
||||
- 提供数据转换选项
|
||||
- 实现字段恢复功能
|
||||
- 支持批量更新素材字段结构
|
||||
- _需求: 21.1, 21.2, 21.3, 21.4, 21.5, 21.6, 21.7_
|
||||
|
||||
- [ ] 15. 实现草稿自动保存
|
||||
- 表单填写时自动保存到localStorage
|
||||
- 页面刷新时提示恢复数据
|
||||
- 提交失败时保留用户输入
|
||||
- 检测多标签页冲突
|
||||
- 自动清理过期草稿
|
||||
- _需求: 23.1, 23.2, 23.3, 23.4, 23.5, 23.6, 23.7_
|
||||
|
||||
## 阶段 5: 首页分类Tag系统优化
|
||||
|
||||
- [ ] 16. 优化首页Tag按钮生成
|
||||
- 从字段池读取启用的筛选字段
|
||||
- 按filterOrder排序显示
|
||||
- 优先显示filterDisplayName
|
||||
- 实现Tag按钮的展开/收起
|
||||
- 支持多选筛选
|
||||
- _需求: 25.1, 25.2, 25.3, 25.4, 25.6, 25.7_
|
||||
|
||||
- [ ] 17. 优化Tag按钮性能
|
||||
- 实现100ms内的UI更新(无闪烁)
|
||||
- 使用防抖技术避免重复请求
|
||||
- 实现虚拟滚动(选项>20个时)
|
||||
- 合并多个筛选条件为单次请求
|
||||
- 优化空状态提示
|
||||
- _需求: 26.1, 26.2, 26.3, 26.4, 26.5, 26.6, 26.7_
|
||||
|
||||
- [ ] 18. 实现Tag按钮的响应式布局
|
||||
- 支持横向滚动
|
||||
- 支持折叠显示
|
||||
- 优化移动端体验
|
||||
- _需求: 26.7_
|
||||
|
||||
## 阶段 6: 后台分类管理优化
|
||||
|
||||
- [ ] 19. 优化分类管理页面
|
||||
- 显示所有字段池字段(包括未启用)
|
||||
- 实现拖拽调整字段顺序
|
||||
- 实现字段重命名功能
|
||||
- 实现启用/禁用切换
|
||||
- 显示字段的所有选项
|
||||
- 支持添加/删除/重命名选项
|
||||
- _需求: 27.1, 27.2, 27.3, 27.4, 27.5, 27.6, 27.7_
|
||||
|
||||
- [ ] 20. 实现分类管理的批量操作
|
||||
- 支持批量启用/禁用字段
|
||||
- 支持批量删除字段
|
||||
- 支持批量导入选项(CSV/JSON)
|
||||
- 支持批量导出选项
|
||||
- 显示批量操作进度
|
||||
- _需求: 29.1, 29.2, 29.3, 29.4, 29.5, 29.6, 29.7_
|
||||
|
||||
- [ ] 21. 实现分类管理与模板的双向同步
|
||||
- 分类管理修改选项时同步到模板
|
||||
- 模板修改选项时同步到字段池
|
||||
- 删除字段时警告影响范围
|
||||
- 使用版本号检测同步冲突
|
||||
- 同步失败时回滚
|
||||
- 记录同步历史日志
|
||||
- _需求: 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7_
|
||||
|
||||
## 阶段 7: 性能优化和测试
|
||||
|
||||
- [ ] 22. 数据库查询优化
|
||||
- 添加必要的索引
|
||||
- 使用批量操作替代逐个操作
|
||||
- 使用事务确保数据一致性
|
||||
- 优化分页查询
|
||||
- _需求: 7.1, 7.2, 7.3, 7.4_
|
||||
|
||||
- [ ] 23. 前端性能优化
|
||||
- 实现虚拟滚动(字段>30个时)
|
||||
- 使用防抖优化输入验证
|
||||
- 使用SWR缓存模板列表
|
||||
- 优化大表单的渲染性能
|
||||
- _需求: 22.1, 22.2, 22.3, 22.4, 22.5, 22.6, 22.7_
|
||||
|
||||
- [ ] 24. 编写单元测试
|
||||
- 测试模板验证器
|
||||
- 测试字段池管理器
|
||||
- 测试选项清洗逻辑
|
||||
- 测试字段验证规则
|
||||
- 目标覆盖率: >80%
|
||||
|
||||
- [ ] 25. 编写集成测试
|
||||
- 测试模板创建流程
|
||||
- 测试素材上传流程
|
||||
- 测试字段池同步流程
|
||||
- 测试分类管理流程
|
||||
|
||||
## 阶段 8: 文档和部署
|
||||
|
||||
- [ ] 26. 更新API文档
|
||||
- 记录所有新增和修改的API
|
||||
- 添加请求/响应示例
|
||||
- 记录错误代码和处理方式
|
||||
|
||||
- [ ] 27. 编写用户手册
|
||||
- 如何创建自定义模板
|
||||
- 如何配置字段验证规则
|
||||
- 如何使用分类管理
|
||||
- 常见问题解答
|
||||
|
||||
- [ ] 28. 准备数据库迁移脚本
|
||||
- 添加version字段到upload_templates表
|
||||
- 迁移旧素材的templateId
|
||||
- 验证数据完整性
|
||||
|
||||
- [ ] 29. 部署到测试环境
|
||||
- 备份数据库
|
||||
- 运行数据库迁移
|
||||
- 部署新代码
|
||||
- 执行冒烟测试
|
||||
|
||||
- [ ] 30. 部署到生产环境
|
||||
- 备份数据库
|
||||
- 运行数据库迁移
|
||||
- 部署新代码
|
||||
- 监控系统指标
|
||||
- 准备回滚方案
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **优先级**: 阶段1-4为高优先级,必须完成;阶段5-8可根据时间调整
|
||||
2. **测试**: 每个阶段完成后都要进行充分测试
|
||||
3. **向后兼容**: 所有修改都要确保向后兼容,不影响现有功能
|
||||
4. **性能**: 关注关键操作的性能指标,确保满足设计目标
|
||||
5. **文档**: 及时更新文档,记录重要的设计决策和实现细节
|
||||
@ -496,12 +496,23 @@ export async function POST(req: NextRequest) {
|
||||
// 验证模板ID(如果提供)
|
||||
if (templateId) {
|
||||
console.log('[Upload] Validating template:', templateId)
|
||||
const validation = await validateTemplateId(templateId)
|
||||
const validation = await validateTemplateId(templateId, {
|
||||
checkStatus: true, // 检查模板状态
|
||||
logPerformance: true, // 记录性能日志
|
||||
})
|
||||
|
||||
if (!validation.valid) {
|
||||
console.error('[Upload] Template validation failed:', validation.error)
|
||||
console.error('[Upload] Template validation failed:', {
|
||||
templateId,
|
||||
error: validation.error,
|
||||
errorCode: validation.errorCode,
|
||||
validationTime: validation.validationTime,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: validation.error || '模板验证失败' },
|
||||
{
|
||||
error: validation.error || '模板验证失败',
|
||||
errorCode: validation.errorCode,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
@ -510,6 +521,8 @@ export async function POST(req: NextRequest) {
|
||||
templateId,
|
||||
isBuiltin: validation.isBuiltin,
|
||||
templateKey: validation.templateKey,
|
||||
templateName: validation.templateName,
|
||||
validationTime: validation.validationTime,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@ -1,3 +1,12 @@
|
||||
/**
|
||||
* 字段池管理器
|
||||
*
|
||||
* 负责管理模板字段与字段池之间的同步
|
||||
*
|
||||
* @module field-pool
|
||||
* @created 2025-12-13
|
||||
*/
|
||||
|
||||
import { Prisma, UploadField } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { STANDARD_FIELDS } from './upload-template-presets'
|
||||
@ -13,6 +22,30 @@ type AggregatedField = {
|
||||
options: Set<string>
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段池同步结果
|
||||
*/
|
||||
export type FieldPoolSyncResult = {
|
||||
success: boolean
|
||||
duration: number
|
||||
fieldsAdded: number
|
||||
fieldsUpdated: number
|
||||
fieldsRemoved: number
|
||||
optionsAdded: number
|
||||
optionsRemoved: number
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段池同步选项
|
||||
*/
|
||||
export type FieldPoolSyncOptions = {
|
||||
incremental?: boolean // 是否增量同步,默认false
|
||||
retryOnError?: boolean // 是否在错误时重试,默认true
|
||||
maxRetries?: number // 最大重试次数,默认3
|
||||
logDetails?: boolean // 是否记录详细日志,默认true
|
||||
}
|
||||
|
||||
export function normalizeFieldOptionValue(option: string): string {
|
||||
let cleaned = option?.trim?.() ?? ''
|
||||
if (!cleaned) return ''
|
||||
@ -415,3 +448,342 @@ export function expandOptionValue(raw: string): string[] {
|
||||
return normalized ? [normalized] : []
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 增强的字段池同步函数(支持增量同步和重试)
|
||||
*
|
||||
* @param options - 同步选项
|
||||
* @returns 同步结果
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const result = await syncFieldPoolWithRetry({
|
||||
* incremental: true,
|
||||
* retryOnError: true,
|
||||
* maxRetries: 3
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export async function syncFieldPoolWithRetry(
|
||||
options: FieldPoolSyncOptions = {}
|
||||
): Promise<FieldPoolSyncResult> {
|
||||
const {
|
||||
incremental = false,
|
||||
retryOnError = true,
|
||||
maxRetries = 3,
|
||||
logDetails = true,
|
||||
} = options
|
||||
|
||||
const startTime = Date.now()
|
||||
let attempt = 0
|
||||
let lastError: Error | null = null
|
||||
|
||||
while (attempt < maxRetries) {
|
||||
try {
|
||||
attempt++
|
||||
|
||||
if (logDetails) {
|
||||
console.log(JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
module: 'field-pool',
|
||||
action: 'syncStart',
|
||||
attempt,
|
||||
maxRetries,
|
||||
incremental,
|
||||
}))
|
||||
}
|
||||
|
||||
// 执行同步
|
||||
const result = incremental
|
||||
? await syncFieldPoolIncremental()
|
||||
: await syncFieldPoolFull()
|
||||
|
||||
const duration = Date.now() - startTime
|
||||
|
||||
if (logDetails) {
|
||||
console.log(JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
module: 'field-pool',
|
||||
action: 'syncComplete',
|
||||
success: true,
|
||||
attempt,
|
||||
duration,
|
||||
...result,
|
||||
}))
|
||||
}
|
||||
|
||||
return {
|
||||
...result,
|
||||
success: true,
|
||||
duration,
|
||||
}
|
||||
} catch (error) {
|
||||
lastError = error as Error
|
||||
const duration = Date.now() - startTime
|
||||
|
||||
console.error('[FieldPool] Sync error:', {
|
||||
attempt,
|
||||
maxRetries,
|
||||
error: lastError.message,
|
||||
stack: lastError.stack,
|
||||
duration,
|
||||
})
|
||||
|
||||
if (!retryOnError || attempt >= maxRetries) {
|
||||
break
|
||||
}
|
||||
|
||||
// 指数退避:等待 2^attempt 秒后重试
|
||||
const waitTime = Math.pow(2, attempt) * 1000
|
||||
console.log(`[FieldPool] Retrying in ${waitTime}ms...`)
|
||||
await new Promise(resolve => setTimeout(resolve, waitTime))
|
||||
}
|
||||
}
|
||||
|
||||
// 所有重试都失败
|
||||
const duration = Date.now() - startTime
|
||||
return {
|
||||
success: false,
|
||||
duration,
|
||||
fieldsAdded: 0,
|
||||
fieldsUpdated: 0,
|
||||
fieldsRemoved: 0,
|
||||
optionsAdded: 0,
|
||||
optionsRemoved: 0,
|
||||
errors: [lastError?.message || '未知错误'],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 全量同步字段池(原有逻辑)
|
||||
*/
|
||||
async function syncFieldPoolFull(): Promise<Omit<FieldPoolSyncResult, 'success' | 'duration'>> {
|
||||
// 调用原有的 syncFieldPoolFromTemplates 函数
|
||||
await syncFieldPoolFromTemplates()
|
||||
|
||||
// 返回统计信息(简化版,实际应该在 syncFieldPoolFromTemplates 中收集)
|
||||
return {
|
||||
fieldsAdded: 0,
|
||||
fieldsUpdated: 0,
|
||||
fieldsRemoved: 0,
|
||||
optionsAdded: 0,
|
||||
optionsRemoved: 0,
|
||||
errors: [],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 增量同步字段池(只同步变更的字段)
|
||||
*/
|
||||
async function syncFieldPoolIncremental(): Promise<Omit<FieldPoolSyncResult, 'success' | 'duration'>> {
|
||||
let fieldsAdded = 0
|
||||
let fieldsUpdated = 0
|
||||
let fieldsRemoved = 0
|
||||
let optionsAdded = 0
|
||||
let optionsRemoved = 0
|
||||
const errors: string[] = []
|
||||
|
||||
try {
|
||||
// 获取所有启用了 addToCategory 的字段
|
||||
const categoryFields = await prismaAny.uploadField.findMany({
|
||||
where: {
|
||||
addToCategory: true,
|
||||
type: 'select',
|
||||
},
|
||||
include: {
|
||||
template: {
|
||||
select: {
|
||||
id: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// 按字段key分组
|
||||
const fieldsByKey = new Map<string, UploadField[]>()
|
||||
for (const field of categoryFields) {
|
||||
const existing = fieldsByKey.get(field.key) || []
|
||||
existing.push(field)
|
||||
fieldsByKey.set(field.key, existing)
|
||||
}
|
||||
|
||||
// 获取现有的字段池记录
|
||||
const existingFields: any[] = await prismaAny.fieldDefinition.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
key: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
})
|
||||
const existingFieldMap = new Map(existingFields.map((f) => [f.key, f]))
|
||||
|
||||
// 处理每个字段
|
||||
for (const [key, fields] of Array.from(fieldsByKey.entries())) {
|
||||
try {
|
||||
const existing = existingFieldMap.get(key)
|
||||
const templateIds = fields.map(f => f.templateId).filter(Boolean)
|
||||
const options = new Set<string>()
|
||||
|
||||
// 聚合选项
|
||||
for (const field of fields) {
|
||||
const fieldOptions = parseOptionsStatic(field.optionsStatic)
|
||||
fieldOptions.forEach(opt => options.add(opt))
|
||||
}
|
||||
|
||||
if (!existing) {
|
||||
// 新增字段
|
||||
await prismaAny.fieldDefinition.create({
|
||||
data: {
|
||||
key,
|
||||
label: fields[0].label,
|
||||
type: fields[0].type,
|
||||
source: STANDARD_FIELDS[key] ? 'standard' : 'custom',
|
||||
isStandard: !!STANDARD_FIELDS[key],
|
||||
sourceTemplateIds: JSON.stringify(templateIds),
|
||||
filterDisplayName: fields[0].label,
|
||||
},
|
||||
})
|
||||
fieldsAdded++
|
||||
|
||||
// 创建选项
|
||||
const fieldDef: any = await prismaAny.fieldDefinition.findUnique({
|
||||
where: { key },
|
||||
})
|
||||
if (fieldDef) {
|
||||
const optionArray = Array.from(options)
|
||||
for (let i = 0; i < optionArray.length; i++) {
|
||||
await prismaAny.fieldOption.create({
|
||||
data: {
|
||||
fieldId: fieldDef.id,
|
||||
value: optionArray[i],
|
||||
label: optionArray[i],
|
||||
orderIndex: i,
|
||||
},
|
||||
})
|
||||
optionsAdded++
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 更新字段
|
||||
await prismaAny.fieldDefinition.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
sourceTemplateIds: JSON.stringify(templateIds),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
fieldsUpdated++
|
||||
|
||||
// 同步选项
|
||||
const result = await syncFieldOptionsIncremental(existing.id, Array.from(options))
|
||||
optionsAdded += result.added
|
||||
optionsRemoved += result.removed
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = `Failed to sync field ${key}: ${error instanceof Error ? error.message : String(error)}`
|
||||
console.error(`[FieldPool] ${errorMsg}`)
|
||||
errors.push(errorMsg)
|
||||
}
|
||||
}
|
||||
|
||||
// 清理孤立字段
|
||||
const activeKeys = Array.from(fieldsByKey.keys())
|
||||
const orphanedFields = existingFields.filter((f) => !activeKeys.includes(f.key))
|
||||
|
||||
for (const orphaned of orphanedFields) {
|
||||
try {
|
||||
await prismaAny.fieldOption.deleteMany({
|
||||
where: { fieldId: (orphaned as any).id },
|
||||
})
|
||||
await prismaAny.fieldDefinition.delete({
|
||||
where: { id: (orphaned as any).id },
|
||||
})
|
||||
fieldsRemoved++
|
||||
} catch (error) {
|
||||
const errorMsg = `Failed to remove orphaned field ${(orphaned as any).key}: ${error instanceof Error ? error.message : String(error)}`
|
||||
console.error(`[FieldPool] ${errorMsg}`)
|
||||
errors.push(errorMsg)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = `Incremental sync failed: ${error instanceof Error ? error.message : String(error)}`
|
||||
console.error(`[FieldPool] ${errorMsg}`)
|
||||
errors.push(errorMsg)
|
||||
throw error
|
||||
}
|
||||
|
||||
return {
|
||||
fieldsAdded,
|
||||
fieldsUpdated,
|
||||
fieldsRemoved,
|
||||
optionsAdded,
|
||||
optionsRemoved,
|
||||
errors,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步单个字段的选项(增量版本)
|
||||
*/
|
||||
async function syncFieldOptionsIncremental(
|
||||
fieldId: string,
|
||||
options: string[]
|
||||
): Promise<{ added: number; removed: number }> {
|
||||
let added = 0
|
||||
let removed = 0
|
||||
|
||||
const uniqueOptions = Array.from(new Set(options.filter(Boolean)))
|
||||
const existingOptions: any[] = await prismaAny.fieldOption.findMany({
|
||||
where: { fieldId },
|
||||
orderBy: { orderIndex: 'asc' },
|
||||
})
|
||||
|
||||
const existingMap = new Map(
|
||||
existingOptions.map((opt) => [opt.value, opt])
|
||||
)
|
||||
|
||||
let orderIndex = 0
|
||||
|
||||
// 更新或创建选项
|
||||
for (const value of uniqueOptions) {
|
||||
const existing = existingMap.get(value)
|
||||
if (existing) {
|
||||
await prismaAny.fieldOption.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
label: value,
|
||||
orderIndex,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
await prismaAny.fieldOption.create({
|
||||
data: {
|
||||
fieldId,
|
||||
value,
|
||||
label: value,
|
||||
orderIndex,
|
||||
},
|
||||
})
|
||||
added++
|
||||
}
|
||||
orderIndex++
|
||||
}
|
||||
|
||||
// 删除废弃选项
|
||||
const keepValues = uniqueOptions
|
||||
const toDelete = existingOptions.filter((opt) => !keepValues.includes(opt.value))
|
||||
|
||||
if (toDelete.length > 0) {
|
||||
await prismaAny.fieldOption.deleteMany({
|
||||
where: {
|
||||
fieldId,
|
||||
value: { notIn: keepValues.length ? keepValues : ['__none__'] },
|
||||
},
|
||||
})
|
||||
removed = toDelete.length
|
||||
}
|
||||
|
||||
return { added, removed }
|
||||
}
|
||||
|
||||
@ -2,6 +2,9 @@
|
||||
* 模板验证工具
|
||||
*
|
||||
* 提供统一的模板验证逻辑,支持内置模板和自定义模板
|
||||
*
|
||||
* @module template-validator
|
||||
* @created 2025-12-13
|
||||
*/
|
||||
|
||||
import { prisma } from '@/lib/prisma'
|
||||
@ -18,6 +21,15 @@ export const BUILTIN_TEMPLATE_KEYS = [
|
||||
|
||||
export type BuiltinTemplateKey = typeof BUILTIN_TEMPLATE_KEYS[number]
|
||||
|
||||
/**
|
||||
* 模板状态枚举
|
||||
*/
|
||||
export enum TemplateStatus {
|
||||
DRAFT = 'draft',
|
||||
ACTIVE = 'active',
|
||||
ARCHIVED = 'archived',
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板验证结果
|
||||
*/
|
||||
@ -25,85 +37,222 @@ export type TemplateValidationResult = {
|
||||
valid: boolean
|
||||
isBuiltin: boolean
|
||||
templateKey?: string
|
||||
templateName?: string
|
||||
templateStatus?: string
|
||||
error?: string
|
||||
errorCode?: string
|
||||
validationTime?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板验证错误代码
|
||||
*/
|
||||
export enum TemplateValidationError {
|
||||
INVALID_BUILTIN_KEY = 'INVALID_BUILTIN_KEY',
|
||||
TEMPLATE_NOT_FOUND = 'TEMPLATE_NOT_FOUND',
|
||||
TEMPLATE_NOT_ACTIVE = 'TEMPLATE_NOT_ACTIVE',
|
||||
DATABASE_ERROR = 'DATABASE_ERROR',
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证模板ID是否有效
|
||||
*
|
||||
* @param templateId - 模板ID(可以是内置模板或自定义模板)
|
||||
* @param options - 验证选项
|
||||
* @returns 验证结果
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const result = await validateTemplateId('builtin-video-material')
|
||||
* if (!result.valid) {
|
||||
* console.error(result.error)
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export async function validateTemplateId(
|
||||
templateId: string | null | undefined
|
||||
templateId: string | null | undefined,
|
||||
options: {
|
||||
checkStatus?: boolean // 是否检查模板状态,默认true
|
||||
logPerformance?: boolean // 是否记录性能日志,默认true
|
||||
} = {}
|
||||
): Promise<TemplateValidationResult> {
|
||||
const { checkStatus = true, logPerformance = true } = options
|
||||
const startTime = Date.now()
|
||||
|
||||
// 如果没有提供 templateId,视为有效(向后兼容)
|
||||
if (!templateId) {
|
||||
return { valid: true, isBuiltin: false }
|
||||
const result: TemplateValidationResult = {
|
||||
valid: true,
|
||||
isBuiltin: false,
|
||||
validationTime: Date.now() - startTime,
|
||||
}
|
||||
|
||||
if (logPerformance) {
|
||||
logValidation('empty', result)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// 检查是否为内置模板(builtin-* 格式)
|
||||
const isBuiltinTemplate = templateId.startsWith('builtin-')
|
||||
const isBuiltin = templateId.startsWith('builtin-')
|
||||
|
||||
if (isBuiltinTemplate) {
|
||||
if (isBuiltin) {
|
||||
// 内置模板:验证模板key是否在预设列表中
|
||||
const templateKey = templateId.replace('builtin-', '') as BuiltinTemplateKey
|
||||
|
||||
if (!BUILTIN_TEMPLATE_KEYS.includes(templateKey)) {
|
||||
return {
|
||||
const result: TemplateValidationResult = {
|
||||
valid: false,
|
||||
isBuiltin: true,
|
||||
templateKey,
|
||||
error: `无效的内置模板:${templateId}。有效的内置模板包括:${BUILTIN_TEMPLATE_KEYS.map(k => `builtin-${k}`).join(', ')}`,
|
||||
errorCode: TemplateValidationError.INVALID_BUILTIN_KEY,
|
||||
validationTime: Date.now() - startTime,
|
||||
}
|
||||
|
||||
if (logPerformance) {
|
||||
logValidation(templateId, result)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
return {
|
||||
// 获取内置模板名称
|
||||
const { BUILTIN_TEMPLATE_NAMES } = await import('@/lib/upload-template-presets')
|
||||
const templateName = BUILTIN_TEMPLATE_NAMES[templateKey]
|
||||
|
||||
const result: TemplateValidationResult = {
|
||||
valid: true,
|
||||
isBuiltin: true,
|
||||
templateKey,
|
||||
templateName,
|
||||
templateStatus: TemplateStatus.ACTIVE,
|
||||
validationTime: Date.now() - startTime,
|
||||
}
|
||||
|
||||
if (logPerformance) {
|
||||
logValidation(templateId, result)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// 自定义模板:从数据库验证
|
||||
try {
|
||||
const template = await prisma.uploadTemplate.findUnique({
|
||||
where: { id: templateId },
|
||||
select: {
|
||||
id: true,
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
status: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!template) {
|
||||
return {
|
||||
const result: TemplateValidationResult = {
|
||||
valid: false,
|
||||
isBuiltin: false,
|
||||
error: `自定义模板不存在:${templateId}。请检查模板是否已被删除或ID是否正确。`,
|
||||
errorCode: TemplateValidationError.TEMPLATE_NOT_FOUND,
|
||||
validationTime: Date.now() - startTime,
|
||||
}
|
||||
|
||||
if (logPerformance) {
|
||||
logValidation(templateId, result)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// 检查模板状态
|
||||
if (template.status !== 'active') {
|
||||
return {
|
||||
if (checkStatus && template.status !== TemplateStatus.ACTIVE) {
|
||||
const result: TemplateValidationResult = {
|
||||
valid: false,
|
||||
isBuiltin: false,
|
||||
templateName: template.name,
|
||||
templateStatus: template.status,
|
||||
error: `模板"${template.name}"当前状态为"${template.status}",无法使用。请联系管理员启用该模板。`,
|
||||
errorCode: TemplateValidationError.TEMPLATE_NOT_ACTIVE,
|
||||
validationTime: Date.now() - startTime,
|
||||
}
|
||||
|
||||
if (logPerformance) {
|
||||
logValidation(templateId, result)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
return {
|
||||
const result: TemplateValidationResult = {
|
||||
valid: true,
|
||||
isBuiltin: false,
|
||||
templateName: template.name,
|
||||
templateStatus: template.status,
|
||||
validationTime: Date.now() - startTime,
|
||||
}
|
||||
|
||||
if (logPerformance) {
|
||||
logValidation(templateId, result)
|
||||
}
|
||||
|
||||
return result
|
||||
} catch (error) {
|
||||
console.error('[TemplateValidator] Error checking custom template:', error)
|
||||
return {
|
||||
const errorMessage = error instanceof Error ? error.message : '未知错误'
|
||||
console.error('[TemplateValidator] Error checking custom template:', {
|
||||
templateId,
|
||||
error: errorMessage,
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
})
|
||||
|
||||
const result: TemplateValidationResult = {
|
||||
valid: false,
|
||||
isBuiltin: false,
|
||||
error: `验证模板时发生错误:${error instanceof Error ? error.message : '未知错误'}`,
|
||||
error: `验证模板时发生错误:${errorMessage}`,
|
||||
errorCode: TemplateValidationError.DATABASE_ERROR,
|
||||
validationTime: Date.now() - startTime,
|
||||
}
|
||||
|
||||
if (logPerformance) {
|
||||
logValidation(templateId, result)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录验证日志
|
||||
*
|
||||
* @param templateId - 模板ID
|
||||
* @param result - 验证结果
|
||||
*/
|
||||
function logValidation(templateId: string, result: TemplateValidationResult): void {
|
||||
const logLevel = result.valid ? 'info' : 'warn'
|
||||
const logData = {
|
||||
timestamp: new Date().toISOString(),
|
||||
module: 'template-validator',
|
||||
action: 'validate',
|
||||
templateId,
|
||||
valid: result.valid,
|
||||
isBuiltin: result.isBuiltin,
|
||||
templateKey: result.templateKey,
|
||||
templateName: result.templateName,
|
||||
templateStatus: result.templateStatus,
|
||||
error: result.error,
|
||||
errorCode: result.errorCode,
|
||||
validationTime: result.validationTime,
|
||||
}
|
||||
|
||||
if (logLevel === 'info') {
|
||||
console.log(JSON.stringify(logData))
|
||||
} else {
|
||||
console.warn(JSON.stringify(logData))
|
||||
}
|
||||
|
||||
// 性能警告:如果验证时间超过100ms
|
||||
if (result.validationTime && result.validationTime > 100) {
|
||||
console.warn(`[TemplateValidator] Slow validation detected: ${result.validationTime}ms for template ${templateId}`)
|
||||
}
|
||||
}
|
||||
|
||||
@ -137,23 +286,186 @@ export function extractBuiltinTemplateKey(templateId: string): BuiltinTemplateKe
|
||||
*
|
||||
* @param templateId - 模板ID
|
||||
* @returns 模板信息,如果不存在返回 null
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const template = await getTemplateWithFields('builtin-video-material')
|
||||
* if (template) {
|
||||
* console.log(template.fields)
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export async function getTemplateWithFields(templateId: string) {
|
||||
if (isBuiltinTemplate(templateId)) {
|
||||
// 内置模板需要动态生成
|
||||
const { createBuiltinTemplate } = await import('@/lib/upload-template-presets')
|
||||
const templateKey = extractBuiltinTemplateKey(templateId)
|
||||
if (!templateKey) return null
|
||||
return createBuiltinTemplate(templateKey)
|
||||
const startTime = Date.now()
|
||||
|
||||
try {
|
||||
if (isBuiltinTemplate(templateId)) {
|
||||
// 内置模板需要动态生成
|
||||
const { createBuiltinTemplate } = await import('@/lib/upload-template-presets')
|
||||
const templateKey = extractBuiltinTemplateKey(templateId)
|
||||
|
||||
if (!templateKey) {
|
||||
console.warn(`[TemplateValidator] Invalid builtin template key: ${templateId}`)
|
||||
return null
|
||||
}
|
||||
|
||||
const template = createBuiltinTemplate(templateKey)
|
||||
const duration = Date.now() - startTime
|
||||
|
||||
console.log(JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
module: 'template-validator',
|
||||
action: 'getTemplateWithFields',
|
||||
templateId,
|
||||
isBuiltin: true,
|
||||
fieldCount: template.fields.length,
|
||||
duration,
|
||||
}))
|
||||
|
||||
return template
|
||||
}
|
||||
|
||||
// 自定义模板从数据库读取
|
||||
const template = await prisma.uploadTemplate.findUnique({
|
||||
where: { id: templateId },
|
||||
include: {
|
||||
fields: {
|
||||
orderBy: { orderIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const duration = Date.now() - startTime
|
||||
|
||||
if (template) {
|
||||
console.log(JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
module: 'template-validator',
|
||||
action: 'getTemplateWithFields',
|
||||
templateId,
|
||||
isBuiltin: false,
|
||||
templateName: template.name,
|
||||
fieldCount: template.fields.length,
|
||||
duration,
|
||||
}))
|
||||
} else {
|
||||
console.warn(`[TemplateValidator] Template not found: ${templateId}`)
|
||||
}
|
||||
|
||||
return template
|
||||
} catch (error) {
|
||||
const duration = Date.now() - startTime
|
||||
console.error('[TemplateValidator] Error getting template with fields:', {
|
||||
templateId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
duration,
|
||||
})
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量验证多个模板ID
|
||||
*
|
||||
* @param templateIds - 模板ID数组
|
||||
* @returns 验证结果数组
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const results = await validateMultipleTemplateIds([
|
||||
* 'builtin-video-material',
|
||||
* 'custom-template-id'
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
export async function validateMultipleTemplateIds(
|
||||
templateIds: string[]
|
||||
): Promise<Map<string, TemplateValidationResult>> {
|
||||
const startTime = Date.now()
|
||||
const results = new Map<string, TemplateValidationResult>()
|
||||
|
||||
// 分离内置模板和自定义模板
|
||||
const builtinIds: string[] = []
|
||||
const customIds: string[] = []
|
||||
|
||||
for (const id of templateIds) {
|
||||
if (isBuiltinTemplate(id)) {
|
||||
builtinIds.push(id)
|
||||
} else {
|
||||
customIds.push(id)
|
||||
}
|
||||
}
|
||||
|
||||
// 自定义模板从数据库读取
|
||||
return prisma.uploadTemplate.findUnique({
|
||||
where: { id: templateId },
|
||||
include: {
|
||||
fields: {
|
||||
orderBy: { orderIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
})
|
||||
// 验证内置模板(无需数据库查询)
|
||||
for (const id of builtinIds) {
|
||||
const result = await validateTemplateId(id, { logPerformance: false })
|
||||
results.set(id, result)
|
||||
}
|
||||
|
||||
// 批量查询自定义模板(减少数据库往返)
|
||||
if (customIds.length > 0) {
|
||||
try {
|
||||
const templates = await prisma.uploadTemplate.findMany({
|
||||
where: { id: { in: customIds } },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
status: true,
|
||||
},
|
||||
})
|
||||
|
||||
const templateMap = new Map(templates.map(t => [t.id, t]))
|
||||
|
||||
for (const id of customIds) {
|
||||
const template = templateMap.get(id)
|
||||
|
||||
if (!template) {
|
||||
results.set(id, {
|
||||
valid: false,
|
||||
isBuiltin: false,
|
||||
error: `自定义模板不存在:${id}`,
|
||||
errorCode: TemplateValidationError.TEMPLATE_NOT_FOUND,
|
||||
})
|
||||
} else if (template.status !== TemplateStatus.ACTIVE) {
|
||||
results.set(id, {
|
||||
valid: false,
|
||||
isBuiltin: false,
|
||||
templateName: template.name,
|
||||
templateStatus: template.status,
|
||||
error: `模板"${template.name}"当前状态为"${template.status}",无法使用`,
|
||||
errorCode: TemplateValidationError.TEMPLATE_NOT_ACTIVE,
|
||||
})
|
||||
} else {
|
||||
results.set(id, {
|
||||
valid: true,
|
||||
isBuiltin: false,
|
||||
templateName: template.name,
|
||||
templateStatus: template.status,
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[TemplateValidator] Error in batch validation:', error)
|
||||
// 如果批量查询失败,逐个验证
|
||||
for (const id of customIds) {
|
||||
const result = await validateTemplateId(id, { logPerformance: false })
|
||||
results.set(id, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const duration = Date.now() - startTime
|
||||
console.log(JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
module: 'template-validator',
|
||||
action: 'validateMultiple',
|
||||
totalCount: templateIds.length,
|
||||
builtinCount: builtinIds.length,
|
||||
customCount: customIds.length,
|
||||
validCount: Array.from(results.values()).filter(r => r.valid).length,
|
||||
duration,
|
||||
}))
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user