更新文档生成逻辑,改用文件ID替代模板编码,增强参数验证和错误处理能力。同时,调整文件配置查询逻辑,确保根据文件ID获取文件配置信息,提升代码可读性和维护性。

This commit is contained in:
python 2025-12-11 09:09:10 +08:00
parent ebc1154beb
commit a320f55da0
4 changed files with 73 additions and 53 deletions

25
app.py
View File

@ -440,19 +440,17 @@ def generate_document():
description: 文件列表
items:
type: object
required:
- fileId
properties:
fileId:
type: integer
description: 文件ID
example: 1
description: 文件配置ID从f_polic_file_config表获取
example: 1765273961563507
fileName:
type: string
description: 文件名称
description: 文件名称可选用于生成文档名称
example: 请示报告卡.doc
templateCode:
type: string
description: 模板编码
example: REPORT_CARD
responses:
200:
description: 生成成功
@ -499,7 +497,7 @@ def generate_document():
type: boolean
example: true
1001:
description: 模板不存在
description: 模板不存在或参数错误
schema:
type: object
properties:
@ -508,7 +506,7 @@ def generate_document():
example: 1001
errorMsg:
type: string
example: 模板不存在
example: 文件ID对应的模板不存在或未启用
isSuccess:
type: boolean
example: false
@ -575,15 +573,14 @@ def generate_document():
for file_info in file_list:
file_id = file_info.get('fileId')
file_name = file_info.get('fileName', '')
template_code = file_info.get('templateCode', '')
if not template_code:
return error_response(1001, f"文件 {file_name} 缺少templateCode参数")
if not file_id:
return error_response(1001, f"文件 {file_name} 缺少fileId参数")
try:
# 生成文档
# 生成文档使用fileId而不是templateCode
result = document_service.generate_document(
template_code=template_code,
file_id=file_id,
input_data=input_data,
file_info=file_info
)

View File

@ -50,55 +50,37 @@ class DocumentService:
secure=self.minio_config['secure']
)
def get_file_config_by_template_code(self, template_code: str) -> Optional[Dict]:
def get_file_config_by_id(self, file_id: int) -> Optional[Dict]:
"""
根据模板编码获取文件配置
根据文件ID获取文件配置
Args:
template_code: 模板编码 'PRELIMINARY_VERIFICATION_APPROVAL'
file_id: 文件配置ID
Returns:
文件配置信息包含: id, name, file_path, template_code
文件配置信息包含: id, name, file_path
"""
import json
conn = self.get_connection()
cursor = conn.cursor(pymysql.cursors.DictCursor)
try:
# 查询文件配置template_code可能存储在template_code列或input_data的JSON字段中
sql = """
SELECT id, name, file_path, input_data, template_code
SELECT id, name, file_path
FROM f_polic_file_config
WHERE tenant_id = %s
WHERE id = %s
AND tenant_id = %s
AND state = 1
"""
cursor.execute(sql, (self.tenant_id,))
configs = cursor.fetchall()
cursor.execute(sql, (file_id, self.tenant_id))
config = cursor.fetchone()
# 查找匹配的template_code优先检查template_code列然后检查input_data JSON
for config in configs:
# 方法1: 检查template_code列
if config.get('template_code') == template_code:
if config:
return {
'id': config['id'],
'name': config['name'],
'file_path': config['file_path'],
'template_code': template_code
'file_path': config['file_path']
}
# 方法2: 从input_data的JSON中查找匹配的template_code
try:
input_data = json.loads(config['input_data']) if config['input_data'] else {}
if input_data.get('template_code') == template_code:
return {
'id': config['id'],
'name': config['name'],
'file_path': config['file_path'],
'template_code': template_code
}
except (json.JSONDecodeError, TypeError):
continue
return None
finally:
@ -218,27 +200,27 @@ class DocumentService:
except S3Error as e:
raise Exception(f"上传文件到MinIO失败: {str(e)}")
def generate_document(self, template_code: str, input_data: List[Dict], file_info: Dict) -> Dict:
def generate_document(self, file_id: int, input_data: List[Dict], file_info: Dict) -> Dict:
"""
生成文档
Args:
template_code: 模板编码
file_id: 文件配置ID
input_data: 输入数据列表格式: [{'fieldCode': 'xxx', 'fieldValue': 'xxx'}]
file_info: 文件信息格式: {'fileId': 1, 'fileName': 'xxx.doc', 'templateCode': 'xxx'}
file_info: 文件信息格式: {'fileId': 1, 'fileName': 'xxx.doc'}
Returns:
生成结果包含: filePath
"""
# 获取文件配置
file_config = self.get_file_config_by_template_code(template_code)
file_config = self.get_file_config_by_id(file_id)
if not file_config:
raise Exception(f"模板编码 {template_code} 不存在")
raise Exception(f"文件ID {file_id} 对应的模板不存在或未启用")
# 检查file_path是否存在
file_path = file_config.get('file_path')
if not file_path:
raise Exception(f"模板编码 {template_code} 的文件路径(file_path)为空,请检查数据库配置")
raise Exception(f"文件ID {file_id} ({file_config.get('name', '')}) 的文件路径(file_path)为空,请检查数据库配置")
# 将input_data转换为字典格式
field_data = {}

View File

@ -0,0 +1,41 @@
"""
测试通过fileId生成文档不再依赖templateCode
"""
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from services.document_service import DocumentService
# 测试通过fileId获取文件配置
print("="*80)
print("Test: Get file config by fileId")
print("="*80)
service = DocumentService()
# 测试查询一个已知的文件ID从之前的查询结果中获取
# "1.请示报告卡(初核谈话)" 的ID是 1765273963893166
test_file_id = 1765273963893166
print(f"\nTest file ID: {test_file_id}")
print("-" * 80)
result = service.get_file_config_by_id(test_file_id)
if result:
print("\n[OK] Found file config:")
print(f" - ID: {result['id']}")
print(f" - Name: {result['name']}")
print(f" - File Path: {result['file_path']}")
else:
print("\n[ERROR] File config not found")
print(" Possible reasons:")
print(" 1. File ID does not exist")
print(" 2. File state is not enabled (state != 1)")
print(" 3. Tenant ID mismatch")
print("\n" + "="*80)
print("Test completed")
print("="*80)