完成文档类型增删改查

This commit is contained in:
2025-04-11 18:45:03 +08:00
parent d54d0f25c6
commit 8177b4195f
18 changed files with 3298 additions and 371 deletions
+764
View File
@@ -0,0 +1,764 @@
import { postgrestGet, postgrestDelete, postgrestPost, postgrestPut, type PostgrestParams } from '../postgrest-client';
import dayjs from 'dayjs';
// 定义文档类型接口
export interface DocumentType {
id: number;
name: string;
description: string | null;
evaluation_point_groups_ids: number[]; // jsonb数组字段
prompt_config?: {
summary_template?: number;
llm_extract_template?: number;
vlm_extract_template?: number;
evaluation_template?: number;
execution_template?: number;
} | null;
created_at: string;
updated_at: string;
code?: string | null;
}
// 定义用于UI展示的文档类型接口
export interface DocumentTypeUI {
id: number;
name: string;
description: string;
groups: DocumentTypeGroup[];
llm_extraction_template_id?: number | null;
vlm_extraction_template_id?: number | null;
evaluation_template_id?: number | null;
summary_template_id?: number | null;
created_at: string;
updated_at: string;
code?: string | null;
}
// 文档类型创建接口
export interface DocumentTypeCreateDTO {
name: string;
description?: string;
group_ids: string[];
llm_extraction_template_id?: number | null;
vlm_extraction_template_id?: number | null;
evaluation_template_id?: number | null;
summary_template_id?: number | null;
code?: string | null;
}
// 文档类型更新接口
export interface DocumentTypeUpdateDTO extends DocumentTypeCreateDTO {
id: number;
}
// 文档类型分组关系
export interface DocumentTypeGroup {
id: string;
name: string;
}
// 搜索参数
export interface DocumentTypeSearchParams {
name?: string;
group_id?: string;
page?: number;
pageSize?: number;
}
/**
* 格式化日期
* @param dateString 日期字符串
* @returns 格式化后的日期字符串
*/
function formatDate(dateString: string): string {
if (!dateString) return '';
try {
return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
} catch (error) {
console.error('日期格式化失败:', error);
return dateString;
}
}
/**
* 从不同格式的 API 响应中提取数据
* @param responseData API 响应数据
* @returns 提取后的数据或 null
*/
function extractApiData<T>(responseData: unknown): T | null {
if (!responseData) return null;
// 格式1: { code: number, msg: string, data: T }
if (typeof responseData === 'object' && responseData !== null &&
'code' in responseData &&
'data' in responseData &&
(responseData as { data: unknown }).data) {
return (responseData as { data: T }).data;
}
// 格式2: 直接是数据对象
return responseData as T;
}
/**
* 获取所有评查点分组
* @returns 评查点分组列表
*/
export async function getAllEvaluationPointGroups(): Promise<{
data?: DocumentTypeGroup[];
error?: string;
status?: number;
}> {
try {
const params: PostgrestParams = {
select: 'id, name'
};
const response = await postgrestGet<Array<{
id: number;
name: string;
}>>('evaluation_point_groups', params);
if (response.error) {
return { error: response.error, status: response.status };
}
// 使用extractApiData提取数据
const extractedData = extractApiData<Array<{
id: number;
name: string;
}>>(response.data);
if (!extractedData) {
return { data: [] };
}
// 转换为DocumentTypeGroup格式
const groups: DocumentTypeGroup[] = extractedData.map(item => ({
id: item.id.toString(),
name: item.name
}));
return { data: groups };
} catch (error) {
console.error('获取所有评查点分组失败:', error);
return { error: error instanceof Error ? error.message : '获取所有评查点分组失败' };
}
}
/**
* 根据ID获取评查点分组信息
* @param ids 评查点分组ID数组
* @returns 评查点分组信息
*/
export async function getEvaluationPointGroupsByIds(ids: number[] | number): Promise<{
data?: DocumentTypeGroup[];
error?: string;
status?: number;
}> {
try {
// 确保ids是数组
if (!ids) {
return { data: [] };
}
// 将单个ID转换为数组
const idsArray = Array.isArray(ids) ? ids : [ids];
if (idsArray.length === 0) {
return { data: [] };
}
// console.log('获取评查点分组,ID类型:', typeof ids, '转换后的ID数组:', idsArray);
const params: PostgrestParams = {
select: 'id, name',
filter: {
'id': `in.(${idsArray.join(',')})`
}
};
// console.log('获取评查点分组,查询参数:', params);
const response = await postgrestGet<Array<{
id: number;
name: string;
}>>('evaluation_point_groups', params);
if (response.error) {
return { error: response.error, status: response.status };
}
// 使用extractApiData提取数据
const extractedData = extractApiData<Array<{
id: number;
name: string;
}>>(response.data);
if (!extractedData) {
return { data: [] };
}
// 转换为DocumentTypeGroup格式
const groups: DocumentTypeGroup[] = extractedData.map(item => ({
id: item.id.toString(),
name: item.name
}));
return { data: groups };
} catch (error) {
console.error('根据ID获取评查点分组失败:', error);
return { error: error instanceof Error ? error.message : '根据ID获取评查点分组失败' };
}
}
/**
* 获取文档类型列表
* @param searchParams 搜索参数
* @returns 文档类型列表和总数
*/
export async function getDocumentTypes(searchParams: DocumentTypeSearchParams = {}): Promise<{
data?: { types: DocumentTypeUI[], total: number };
error?: string;
status?: number;
}> {
try {
const page = searchParams.page || 1;
const pageSize = searchParams.pageSize || 10;
// 构建查询参数
const params: PostgrestParams = {
select: `
id,
name,
description,
evaluation_point_groups_ids,
prompt_config,
created_at,
updated_at,
code
`,
order: 'updated_at.desc',
headers: {
'Prefer': 'count=exact'
},
limit: pageSize,
offset: (page - 1) * pageSize,
filter: {} as Record<string, string>
};
// 添加筛选条件
const filter: Record<string, string> = {};
if (searchParams.name) {
filter['name'] = `ilike.%${searchParams.name}%`;
}
// 如果有分组ID筛选条件
if (searchParams.group_id) {
filter['evaluation_point_groups_ids'] = `cs.{${searchParams.group_id}}`;
}
params.filter = filter;
// console.log('获取文档类型列表,参数:', params);
const response = await postgrestGet<DocumentType[]>('document_types', params);
if (response.error) {
return { error: response.error, status: response.status };
}
// 使用extractApiData提取数据
const extractedData = extractApiData<DocumentType[]>(response.data);
const documentTypes = extractedData || [];
// console.log('提取的文档类型数据:', documentTypes);
// 为每个文档类型获取关联的分组
const typesWithGroups = await Promise.all(documentTypes.map(async (type) => {
// 获取文档类型关联的分组IDs
let groupIds: number[] = [];
try {
// 尝试解析evaluation_point_groups_ids
if (typeof type.evaluation_point_groups_ids === 'string') {
// 如果是JSON字符串,解析它
groupIds = JSON.parse(type.evaluation_point_groups_ids as unknown as string);
} else if (Array.isArray(type.evaluation_point_groups_ids)) {
// 如果已经是数组,直接使用
groupIds = type.evaluation_point_groups_ids;
} else if (type.evaluation_point_groups_ids) {
// 其他情况,尝试将其转换为数组
groupIds = [type.evaluation_point_groups_ids as unknown as number];
}
} catch (error) {
console.error('解析分组ID失败:', error, '原始值:', type.evaluation_point_groups_ids);
groupIds = [];
}
console.log(`文档类型 ${type.id} 的分组IDs:`, groupIds);
// 获取这些ID对应的分组信息
const groupsResponse = await getEvaluationPointGroupsByIds(groupIds);
// 返回包含分组信息的文档类型
return {
...type,
groups: groupsResponse.data || []
};
}));
// 转换为UI类型
const uiTypes = typesWithGroups.map(convertToUIDocumentType);
// 获取总数
let totalCount = 0;
const responseWithHeaders = response as {
data: unknown;
headers: Record<string, string>
};
if (responseWithHeaders.headers) {
const rangeHeader = responseWithHeaders.headers['content-range'];
if (rangeHeader) {
const total = rangeHeader.split('/')[1];
if (total !== '*') {
totalCount = parseInt(total, 10);
}
}
}
return {
data: {
types: uiTypes,
total: totalCount || uiTypes.length
}
};
} catch (error) {
console.error('获取文档类型列表失败:', error);
return {
error: error instanceof Error ? error.message : '获取文档类型列表失败',
status: 500
};
}
}
/**
* 删除文档类型
* @param id 文档类型ID
* @returns 删除结果
*/
export async function deleteDocumentType(id: string): Promise<{
success?: boolean;
error?: string;
status?: number;
}> {
try {
if (!id) {
return { error: '文档类型ID不能为空', status: 400 };
}
// 删除文档类型
const response = await postgrestDelete(
'document_types',
{
filter: {
'id': `eq.${id}`
}
}
);
if (response.error) {
return { error: response.error, status: response.status };
}
return { success: true };
} catch (error) {
console.error('删除文档类型失败:', error);
return {
error: error instanceof Error ? error.message : '删除文档类型失败',
status: 500
};
}
}
/**
* 将API返回的文档类型转换为UI文档类型
*/
function convertToUIDocumentType(type: DocumentType & { groups: DocumentTypeGroup[] }): DocumentTypeUI {
// 提取提示词模板ID,确保安全处理以避免控制台警告
let llmExtractionTemplateId: number | null = null;
let vlmExtractionTemplateId: number | null = null;
let evaluationTemplateId: number | null = null;
let summaryTemplateId: number | null = null;
// 安全地获取prompt_config字段
if (type.prompt_config) {
// 转换为字符串或保持为null
if (type.prompt_config.llm_extract_template !== undefined && type.prompt_config.llm_extract_template !== null) {
llmExtractionTemplateId = type.prompt_config.llm_extract_template;
}
if (type.prompt_config.vlm_extract_template !== undefined && type.prompt_config.vlm_extract_template !== null) {
vlmExtractionTemplateId = type.prompt_config.vlm_extract_template;
}
// 注意: 后端字段可能是 evaluation_template 或 execution_template
// 优先使用 evaluation_template,如果不存在则尝试使用 execution_template
if (type.prompt_config.evaluation_template !== undefined && type.prompt_config.evaluation_template !== null) {
evaluationTemplateId = type.prompt_config.evaluation_template;
} else if (type.prompt_config.execution_template !== undefined && type.prompt_config.execution_template !== null) {
evaluationTemplateId = type.prompt_config.execution_template;
}
if (type.prompt_config.summary_template !== undefined && type.prompt_config.summary_template !== null) {
summaryTemplateId = type.prompt_config.summary_template;
}
}
return {
id: type.id,
name: type.name,
description: type.description || '',
groups: type.groups || [],
llm_extraction_template_id: llmExtractionTemplateId,
vlm_extraction_template_id: vlmExtractionTemplateId,
evaluation_template_id: evaluationTemplateId,
summary_template_id: summaryTemplateId,
created_at: formatDate(type.created_at),
updated_at: formatDate(type.updated_at),
code: type.code
};
}
/**
* 获取文档类型详情
* @param id 文档类型ID
* @returns 文档类型详情
*/
export async function getDocumentType(id: string): Promise<{
data?: DocumentTypeUI;
error?: string;
status?: number;
}> {
try {
if (!id) {
return { error: '文档类型ID不能为空', status: 400 };
}
const params: PostgrestParams = {
select: `
id,
name,
description,
evaluation_point_groups_ids,
prompt_config,
created_at,
updated_at,
code
`,
filter: {
'id': `eq.${id}`
}
};
const response = await postgrestGet<DocumentType[]>('document_types', params);
if (response.error) {
return { error: response.error, status: response.status };
}
// 使用extractApiData提取数据
const extractedData = extractApiData<DocumentType[]>(response.data);
if (!extractedData || extractedData.length === 0) {
return { error: '未找到文档类型', status: 404 };
}
const documentType = extractedData[0];
// 获取关联分组
let groupIds: number[] = [];
try {
// 尝试解析evaluation_point_groups_ids
if (typeof documentType.evaluation_point_groups_ids === 'string') {
// 如果是JSON字符串,解析它
groupIds = JSON.parse(documentType.evaluation_point_groups_ids as unknown as string);
} else if (Array.isArray(documentType.evaluation_point_groups_ids)) {
// 如果已经是数组,直接使用
groupIds = documentType.evaluation_point_groups_ids;
} else if (documentType.evaluation_point_groups_ids) {
// 其他情况,尝试将其转换为数组
groupIds = [documentType.evaluation_point_groups_ids as unknown as number];
}
} catch (error) {
console.error('解析分组ID失败:', error, '原始值:', documentType.evaluation_point_groups_ids);
groupIds = [];
}
console.log(`文档类型 ${id} 的分组IDs:`, groupIds);
const groupsResponse = await getEvaluationPointGroupsByIds(groupIds);
if (groupsResponse.error) {
return { error: groupsResponse.error, status: 500 };
}
// 添加分组信息
const typeWithGroups = {
...documentType,
groups: groupsResponse.data || []
};
return { data: convertToUIDocumentType(typeWithGroups) };
} catch (error) {
console.error('获取文档类型详情失败:', error);
return {
error: error instanceof Error ? error.message : '获取文档类型详情失败',
status: 500
};
}
}
/**
* 创建文档类型
* @param documentType 文档类型数据
* @returns 创建结果
*/
export async function createDocumentType(documentType: DocumentTypeCreateDTO): Promise<{
data?: DocumentTypeUI;
error?: string;
status?: number;
}> {
try {
// 验证必填字段
if (!documentType.name) {
return { error: '文档类型名称不能为空', status: 400 };
}
if (!documentType.group_ids || documentType.group_ids.length === 0) {
return { error: '请至少选择一个关联的评查点分组', status: 400 };
}
// 目前因为关联操作是做单选的,所以传过来的拿第一个值即可。
const groupId = documentType.group_ids[0];
if (!groupId || isNaN(parseInt(groupId, 10))) {
return { error: '无效的评查点分组ID', status: 400 };
}
const groupIds = parseInt(groupId, 10); // 修改为数组形式
// const groupIds = [parseInt(groupId, 10)]; // 修改为数组形式
// 构建提示词配置 - 确保所有字段都有明确的设置
const promptConfig: Record<string, number | null> = {
llm_extract_template: null,
vlm_extract_template: null,
// evaluation_template: null,
execution_template: null,
summary_template: null
};
// 只有当ID存在且不为空字符串时才设置值
if (documentType.llm_extraction_template_id) {
const llmId = documentType.llm_extraction_template_id;
if (isNaN(llmId)) {
return { error: '无效的llm抽取提示词模板ID', status: 400 };
}
promptConfig.llm_extract_template = llmId;
}
if (documentType.vlm_extraction_template_id) {
const vlmId = documentType.vlm_extraction_template_id;
if (isNaN(vlmId)) {
return { error: '无效的vlm抽取提示词模板ID', status: 400 };
}
promptConfig.vlm_extract_template = vlmId;
}
if (documentType.evaluation_template_id) {
const evaluationId = documentType.evaluation_template_id;
if (isNaN(evaluationId)) {
return { error: '无效的评查提示词模板ID', status: 400 };
}
promptConfig.execution_template = evaluationId;
}
if (documentType.summary_template_id) {
const summaryId = documentType.summary_template_id;
if (isNaN(summaryId)) {
return { error: '无效的总结提示词模板ID', status: 400 };
}
promptConfig.summary_template = summaryId;
}
// 构建API请求数据 - 始终包含prompt_config对象
const apiDocumentType = {
name: documentType.name.trim(),
description: documentType.description || '',
evaluation_point_groups_ids: groupIds,
prompt_config: promptConfig,
code: documentType.code || null
};
// console.log('创建文档类型请求数据:', JSON.stringify(apiDocumentType, null, 2));
// console.log('创建文档类型请求数据:', apiDocumentType);
// if(apiDocumentType){
// throw new Error('测试错误');
// }
// 发送创建请求
const response = await postgrestPost<DocumentType, typeof apiDocumentType>(
'document_types',
apiDocumentType
);
if (response.error) {
console.error('创建文档类型API返回错误:', response.error, '状态码:', response.status);
return { error: response.error, status: response.status };
}
console.log('创建文档类型响应数据:', JSON.stringify(response.data, null, 2));
// 处理响应数据
const newDocumentType = extractApiData<DocumentType>(response.data);
if (!newDocumentType) {
return { error: '创建文档类型失败: 无法获取新创建的数据', status: 500 };
}
// 获取关联分组信息
const groupsResponse = await getEvaluationPointGroupsByIds(groupIds);
// 添加分组信息并转换为UI类型
const typeWithGroups = {
...newDocumentType,
groups: groupsResponse.data || []
};
return { data: convertToUIDocumentType(typeWithGroups) };
} catch (error) {
console.error('创建文档类型失败:', error);
return {
error: error instanceof Error ? error.message : '创建文档类型失败',
status: 500
};
}
}
/**
* 更新文档类型
* @param id 文档类型ID
* @param documentType 文档类型数据
* @returns 更新结果
*/
export async function updateDocumentType(id: string, documentType: DocumentTypeUpdateDTO): Promise<{
data?: DocumentTypeUI;
error?: string;
status?: number;
}> {
try {
// 验证必填字段
if (!id) {
return { error: '文档类型ID不能为空', status: 400 };
}
if (!documentType.name) {
return { error: '文档类型名称不能为空', status: 400 };
}
if (!documentType.group_ids || documentType.group_ids.length === 0) {
return { error: '请至少选择一个关联的评查点分组', status: 400 };
}
// 将分组ID转换为数字数组
const groupIds = documentType.group_ids.map(id => parseInt(id, 10));
// 构建提示词配置 - 始终创建一个包含所有字段的对象,并明确设置值
const promptConfig: Record<string, number | null> = {
llm_extract_template: null,
vlm_extract_template: null,
evaluation_template: null,
execution_template: null,
summary_template: null
};
// 只有当ID存在且不为空字符串时才设置值
if (documentType.llm_extraction_template_id) {
const llmId = documentType.llm_extraction_template_id;
if (isNaN(llmId)) {
return { error: '无效的llm抽取提示词模板ID', status: 400 };
}
promptConfig.llm_extract_template = llmId;
}
if (documentType.vlm_extraction_template_id) {
const vlmId = documentType.vlm_extraction_template_id;
if (isNaN(vlmId)) {
return { error: '无效的vlm抽取提示词模板ID', status: 400 };
}
promptConfig.vlm_extract_template = vlmId;
}
if (documentType.evaluation_template_id) {
const evaluationId = documentType.evaluation_template_id;
if (isNaN(evaluationId)) {
return { error: '无效的评查提示词模板ID', status: 400 };
}
promptConfig.execution_template = evaluationId;
}
if (documentType.summary_template_id) {
const summaryId = documentType.summary_template_id;
if (isNaN(summaryId)) {
return { error: '无效的总结提示词模板ID', status: 400 };
}
promptConfig.summary_template = summaryId;
}
// 构建API请求数据 - 始终包含prompt_config对象
const apiDocumentType = {
name: documentType.name.trim(),
description: documentType.description || '',
evaluation_point_groups_ids: groupIds,
prompt_config: promptConfig,
code: documentType.code || null
};
console.log('更新文档类型请求数据:', JSON.stringify(apiDocumentType, null, 2));
// 发送更新请求
const response = await postgrestPut<DocumentType, typeof apiDocumentType>(
'document_types',
apiDocumentType,
{id}
);
if (response.error) {
console.error('更新文档类型API返回错误:', response.error, '状态码:', response.status);
return { error: response.error, status: response.status };
}
console.log('更新文档类型响应数据:', JSON.stringify(response.data, null, 2));
// 处理响应数据
const updatedDocumentType = extractApiData<DocumentType>(response.data);
if (!updatedDocumentType) {
return { error: '更新文档类型失败: 无法获取更新后的数据', status: 500 };
}
// 获取关联分组信息
const groupsResponse = await getEvaluationPointGroupsByIds(groupIds);
// 添加分组信息并转换为UI类型
const typeWithGroups = {
...updatedDocumentType,
groups: groupsResponse.data || []
};
return { data: convertToUIDocumentType(typeWithGroups) };
} catch (error) {
console.error('更新文档类型失败:', error);
return {
error: error instanceof Error ? error.message : '更新文档类型失败',
status: 500
};
}
}
+318
View File
@@ -0,0 +1,318 @@
import { postgrestGet, postgrestDelete, type PostgrestParams } from '../postgrest-client';
import dayjs from 'dayjs';
import { getDocumentTypes } from '../document-types/document-types';
/**
* 从不同格式的 API 响应中提取数据
* @param responseData API 响应数据
* @returns 提取后的数据或 null
*/
function extractApiData<T>(responseData: unknown): T | null {
if (!responseData) return null;
// 格式1: { code: number, msg: string, data: T }
if (typeof responseData === 'object' && responseData !== null &&
'code' in responseData &&
'data' in responseData &&
(responseData as { data: unknown }).data) {
return (responseData as { data: T }).data;
}
// 格式2: 直接是数据对象
return responseData as T;
}
/**
* 格式化日期
* @param dateString 日期字符串
* @returns 格式化后的日期字符串
*/
function formatDate(dateString: string): string {
if (!dateString) return '';
try {
return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
} catch (error) {
console.error('日期格式化失败:', error);
return dateString;
}
}
/**
* 查询参数
*/
export interface DocumentSearchParams {
name?: string;
documentNumber?: string;
documentType?: string;
status?: string;
dateFrom?: string;
dateTo?: string;
page?: number;
pageSize?: number;
}
/**
* 数据库文档结构
*/
export interface Document {
id: number;
user_id: number | null;
type_id: number;
name: string;
document_number: string;
path: string;
storage_type: string;
file_size: number;
upload_time: string;
is_test_document: boolean;
evaluation_level: string;
status: 'pass' | 'warning' | 'waiting' | 'processing' | 'fail';
ocr_result: unknown;
extracted_results: unknown;
summary: unknown;
remark: string;
created_at: string;
updated_at: string;
}
/**
* 前端UI文档结构
*/
export interface DocumentUI {
id: number;
name: string;
documentNumber: string;
type: string;
typeName: string;
size: number;
status: string;
issues: number | null;
uploadTime: string;
fileType: string;
path: string;
isTest: boolean;
}
/**
* 获取文件扩展名
* @param filename 文件名
* @returns 文件扩展名
*/
function getFileExtension(filename: string): string {
const parts = filename.split('.');
return parts.length > 1 ? parts.pop()?.toLowerCase() || '' : '';
}
/**
* 将API文档转换为UI文档
*/
async function convertToUIDocument(doc: Document): Promise<DocumentUI> {
// 获取文档类型信息
const typeResponse = await getDocumentTypes();
const documentTypes = typeResponse.data?.types || [];
const docType = documentTypes.find(type => type.id.toString() === doc.type_id.toString());
return {
id: doc.id,
name: doc.name,
documentNumber: doc.document_number,
type: doc.type_id.toString(),
typeName: docType?.name || '未知类型',
size: doc.file_size,
status: doc.status,
issues: 0, // 固定为0
uploadTime: formatDate(doc.updated_at),
fileType: getFileExtension(doc.name),
path: doc.path,
isTest: doc.is_test_document
};
}
/**
* 获取文档列表
* @param searchParams 搜索参数
* @returns 文档列表和总数
*/
export async function getDocuments(searchParams: DocumentSearchParams = {}): Promise<{
data?: { documents: DocumentUI[], total: number };
error?: string;
status?: number;
}> {
try {
const page = searchParams.page || 1;
const pageSize = searchParams.pageSize || 10;
// 构建查询参数
const params: PostgrestParams = {
select: '*',
order: 'updated_at.desc',
headers: {
'Prefer': 'count=exact'
},
limit: pageSize,
offset: (page - 1) * pageSize,
filter: {} as Record<string, string>
};
// 添加筛选条件
const filter: Record<string, string> = {};
if (searchParams.name) {
filter['name'] = `ilike.%${searchParams.name}%`;
}
if (searchParams.documentNumber) {
filter['document_number'] = `ilike.%${searchParams.documentNumber}%`;
}
if (searchParams.documentType) {
filter['type_id'] = `eq.${searchParams.documentType}`;
}
if (searchParams.status) {
filter['status'] = `eq.${searchParams.status}`;
}
// 处理日期范围
if (searchParams.dateFrom) {
filter['updated_at'] = `gte.${searchParams.dateFrom}`;
}
if (searchParams.dateTo) {
const dateToKey = searchParams.dateFrom ? 'and.updated_at.lte' : 'updated_at';
filter[dateToKey] = `lte.${searchParams.dateTo}`;
}
params.filter = filter;
// 发送请求
const response = await postgrestGet<Document[]>('documents', params);
if (response.error) {
return { error: response.error, status: response.status };
}
// 提取数据
const extractedData = extractApiData<Document[]>(response.data);
if (!extractedData) {
return { error: '获取文档数据失败', status: 500 };
}
// 转换为UI格式
const documents = await Promise.all(extractedData.map(convertToUIDocument));
// 获取总数
let totalCount = 0;
const responseWithHeaders = response as {
data: unknown;
headers?: Record<string, string>
};
if (responseWithHeaders.headers) {
const rangeHeader = responseWithHeaders.headers['content-range'];
if (rangeHeader) {
const total = rangeHeader.split('/')[1];
if (total !== '*') {
totalCount = parseInt(total, 10);
}
}
}
return {
data: {
documents,
total: totalCount || documents.length
}
};
} catch (error) {
console.error('获取文档列表失败:', error);
return {
error: error instanceof Error ? error.message : '获取文档列表失败',
status: 500
};
}
}
/**
* 删除文档
* @param id 文档ID
* @returns 删除结果
*/
export async function deleteDocument(id: string): Promise<{
success?: boolean;
error?: string;
status?: number;
}> {
try {
if (!id) {
return { error: '文档ID不能为空', status: 400 };
}
const response = await postgrestDelete(
'documents',
{
filter: {
'id': `eq.${id}`
}
}
);
if (response.error) {
return { error: response.error, status: response.status };
}
return { success: true };
} catch (error) {
console.error('删除文档失败:', error);
return {
error: error instanceof Error ? error.message : '删除文档失败',
status: 500
};
}
}
/**
* 获取单个文档详情
* @param id 文档ID
* @returns 文档详情
*/
export async function getDocument(id: string): Promise<{
data?: DocumentUI;
error?: string;
status?: number;
}> {
try {
if (!id) {
return { error: '文档ID不能为空', status: 400 };
}
const response = await postgrestGet<Document[]>(
'documents',
{
filter: {
'id': `eq.${id}`
},
limit: 1
}
);
if (response.error) {
return { error: response.error, status: response.status };
}
const extractedData = extractApiData<Document[]>(response.data);
if (!extractedData || extractedData.length === 0) {
return { error: '文档不存在', status: 404 };
}
const documentUI = await convertToUIDocument(extractedData[0]);
return { data: documentUI };
} catch (error) {
console.error('获取文档详情失败:', error);
return {
error: error instanceof Error ? error.message : '获取文档详情失败',
status: 500
};
}
}
+6
View File
@@ -64,16 +64,22 @@ export async function getDocumentType(id: string): Promise<DocumentType> {
}
// 创建文档类型
// 请使用 ~/api/document-types/document-types.ts 中的实现
/*
export async function createDocumentType(documentType: Omit<DocumentType, 'id' | 'createdAt' | 'updatedAt'>): Promise<DocumentType> {
const url = buildUrl('/api/document-types');
return apiRequest<DocumentType>(url, 'POST', documentType);
}
*/
// 更新文档类型
// 请使用 ~/api/document-types/document-types.ts 中的实现
/*
export async function updateDocumentType(id: string, documentType: Partial<Omit<DocumentType, 'id' | 'createdAt' | 'updatedAt'>>): Promise<DocumentType> {
const url = buildUrl(`/api/document-types/${id}`);
return apiRequest<DocumentType>(url, 'PUT', documentType);
}
*/
// 删除文档类型
export async function deleteDocumentType(id: string): Promise<void> {
+3 -3
View File
@@ -20,7 +20,7 @@ export interface PromptTemplate {
export interface PromptTemplateUI {
id: string;
template_name: string;
template_type: 'Extraction' | 'Evaluation' | 'Summary' | 'Common';
template_type: 'LLM_Extraction' | 'VLM_Extraction' | 'Evaluation' | 'Summary' | 'Common';
description: string;
template_content: string;
variables: Record<string, string>; // 变量定义
@@ -112,7 +112,7 @@ export function convertToUITemplate(template: PromptTemplate): PromptTemplateUI
return {
id: template.id ? template.id.toString() : '',
template_name: template.template_name,
template_type: template.template_type as "Extraction" | "Evaluation" | "Summary" | "Common",
template_type: template.template_type as "LLM_Extraction" | "VLM_Extraction" | "Evaluation" | "Summary" | "Common",
description: template.description || '',
template_content: template.template_content,
variables: template.variables,
@@ -207,7 +207,7 @@ export async function getPromptTemplates(searchParams: PromptSearchParams = {}):
return { error: '获取提示词模板数据失败', status: 500 };
}
console.log(`成功获取${extractedData.length}条提示词模板数据`);
// console.log(`成功获取${extractedData.length}条提示词模板数据`);
// 从响应头中获取总数
let totalCount = 0;