refactor: rewrite document-type management for new backend API

- API client: switch from /api/v3/document-types to /api/document-types,
  replace group_ids with ruleSetIds, add getEntryModules/getRuleSets
- List page: simplified to code/name/entry_module/rule_sets/status columns
- New/Edit page: code + name + description + entry_module dropdown +
  rule_set multi-select checklist
- Fix DocumentType type import collision in documents.ts
This commit is contained in:
wren
2026-04-30 13:18:24 +08:00
parent 477bcafeb7
commit 81c5e98b53
4 changed files with 421 additions and 1784 deletions
+148 -549
View File
@@ -1,659 +1,258 @@
import { apiRequest } from '../axios-client';
import { formatDate } from '../../utils';
import { getAllEvaluationPointGroups, type RuleGroup } from '../evaluation_points/rule-groups';
import { API_BASE_URL } from '../../config/api-config';
import axios from 'axios';
// ==================== 类型定义 ====================
// 定义文档类型接口
export interface DocumentType {
id: number;
name: string;
code?: string | null;
code: string;
description: string | null;
evaluation_point_groups_ids: number[]; // 评查点分组ID数组
entry_module_id?: number | null;
entry_module?: {
id: number;
name: string;
} | null;
groups?: DocumentTypeGroup[];
llm_extraction_template_id?: number | null;
vlm_extraction_template_id?: number | null;
created_at: string;
updated_at: string;
entryModuleId: number | null;
isEnabled: boolean;
ruleSetIds: number[];
createdAt?: string;
updatedAt?: string;
}
// 定义用于UI展示的文档类型接口
export interface DocumentTypeUI {
id: number;
name: string;
code?: string | null;
description: string;
groups: DocumentTypeGroup[];
entry_module?: {
id: number;
name: string;
} | null;
llm_extraction_template_id?: number | null;
vlm_extraction_template_id?: number | null;
created_at: string;
updated_at: string;
}
// 文档类型创建接口
export interface DocumentTypeCreateDTO {
code: string;
name: string;
description?: string;
group_ids: number[]; // 改为 number[] 数组
code: string | null;
entry_module_id?: number | null;
llm_extraction_template_id?: number | null;
vlm_extraction_template_id?: number | null;
entryModuleId?: number | null;
isEnabled?: boolean;
sortOrder?: number;
ruleSetIds?: number[];
}
// 文档类型更新接口
export interface DocumentTypeUpdateDTO extends DocumentTypeCreateDTO {
export interface DocumentTypeUpdateDTO {
name?: string;
description?: string;
entryModuleId?: number | null;
isEnabled?: boolean;
sortOrder?: number;
ruleSetIds?: number[];
}
export interface RuleSetOption {
id: number;
ruleType: string;
ruleName: string;
status: string;
}
// 文档类型分组关系
export interface DocumentTypeGroup {
id: string | number;
export interface EntryModuleOption {
id: number;
name: string;
code?: string;
}
// 搜索参数
export interface DocumentTypeSearchParams {
name?: string;
group_id?: number; // 按评查点分组ID筛选
entry_module_id?: number; // 按入口模块ID筛选
ids?: number[]; // 按ID列表筛选
entry_module_id?: number;
ids?: number[];
page?: number;
pageSize?: number;
}
// API 响应格式
interface ApiResponse<T> {
code: number;
msg: string;
message: string;
data: T;
}
// 列表响应数据
interface ListResponseData {
total: number;
page: number;
page_size: number;
items: DocumentType[];
// ==================== API 调用 ====================
function authHeaders(token?: string): Record<string, string> {
const headers: Record<string, string> = {};
if (token) headers['Authorization'] = `Bearer ${token}`;
return headers;
}
// 选项数据
interface OptionsResponseData {
items: Array<{ id: number; name: string; code?: string }>;
function extractData<T>(response: any): T | null {
return response?.data?.data ?? response?.data ?? null;
}
/**
* 获取文档类型列表
* @param searchParams 搜索参数
* @param frontendJWT JWT token
* @returns 文档类型列表和总数
*/
export async function getDocumentTypes(
searchParams: DocumentTypeSearchParams = {},
frontendJWT?: string
): Promise<{
data?: { types: DocumentTypeUI[], total: number };
error?: string;
status?: number;
}> {
token?: string
): Promise<{ data?: { types: DocumentType[]; total: number }; error?: string; status?: number }> {
try {
const page = searchParams.page || 1;
const pageSize = searchParams.pageSize || 10;
// 构建查询参数
const params: Record<string, string | number | number[]> = {
page,
page_size: pageSize,
const params: Record<string, string | number> = {
page: searchParams.page || 1,
pageSize: searchParams.pageSize || 50,
};
if (searchParams.ids) params.ids = searchParams.ids.join(",");
if (searchParams.name) {
params.name = searchParams.name;
}
const response = await axios.get(`${API_BASE_URL}/api/document-types`, {
params,
headers: authHeaders(token),
});
if (searchParams.group_id) {
params.group_id = searchParams.group_id;
}
const items = extractData<any[]>(response) || [];
const types: DocumentType[] = items.map((item: any) => ({
id: item.id,
name: item.name,
code: item.code,
description: item.description || null,
entryModuleId: item.entryModuleId || null,
isEnabled: item.isEnabled !== false,
ruleSetIds: item.ruleSetIds || [],
}));
if (searchParams.entry_module_id) {
params.entry_module_id = searchParams.entry_module_id;
}
if (searchParams.ids) {
params.ids = searchParams.ids;
}
const response = await apiRequest<ApiResponse<ListResponseData>>(
'/api/v3/document-types',
{
method: 'GET',
headers: frontendJWT ? { 'Authorization': `Bearer ${frontendJWT}` } : undefined,
},
params
);
if (response.error) {
return { error: response.error, status: response.status };
}
const apiData = response.data?.data;
if (!apiData) {
return { error: '获取文档类型列表失败', status: 500 };
}
// 转换为UI类型
const uiTypes = apiData.items.map(type => convertToUIDocumentType(type));
return {
data: {
types: uiTypes,
total: apiData.total
}
};
return { data: { types, total: types.length } };
} catch (error) {
console.error('获取文档类型列表失败:', error);
return {
error: error instanceof Error ? error.message : '获取文档类型列表失败',
status: 500
};
console.error("获取文档类型列表失败:", error);
return { error: error instanceof Error ? error.message : "获取文档类型列表失败", status: 500 };
}
}
/**
* 获取文档类型详情
* @param id 文档类型ID
* @param frontendJWT JWT token
* @returns 文档类型详情
*/
export async function getDocumentType(
id: string,
frontendJWT?: string
): Promise<{
data?: DocumentTypeUI;
error?: string;
status?: number;
}> {
id: number,
token?: string
): Promise<{ data?: DocumentType; error?: string; status?: number }> {
try {
if (!id) {
return { error: '文档类型ID不能为空', status: 400 };
}
const response = await axios.get(`${API_BASE_URL}/api/document-types/${id}`, {
headers: authHeaders(token),
});
const item = extractData<any>(response);
if (!item) return { error: "文档类型不存在", status: 404 };
const response = await apiRequest<ApiResponse<DocumentType>>(
`/api/v3/document-types/${id}`,
{
method: 'GET',
headers: frontendJWT ? { 'Authorization': `Bearer ${frontendJWT}` } : undefined,
}
);
if (response.error) {
return { error: response.error, status: response.status };
}
const documentType = response.data?.data;
if (!documentType) {
return { error: '未找到文档类型', status: 404 };
}
return { data: convertToUIDocumentType(documentType) };
} catch (error) {
console.error('获取文档类型详情失败:', error);
return {
error: error instanceof Error ? error.message : '获取文档类型详情失败',
status: 500
data: {
id: item.id,
name: item.name,
code: item.code,
description: item.description || null,
entryModuleId: item.entryModuleId || null,
isEnabled: item.isEnabled !== false,
ruleSetIds: item.ruleSetIds || [],
},
};
} catch (error) {
return { error: error instanceof Error ? error.message : "获取文档类型失败", status: 500 };
}
}
/**
* 创建文档类型
* @param documentType 文档类型数据
* @param frontendJWT JWT token
* @returns 创建结果
*/
export async function createDocumentType(
documentType: DocumentTypeCreateDTO,
frontendJWT?: string
): Promise<{
data?: DocumentTypeUI;
error?: string;
status?: number;
}> {
dto: DocumentTypeCreateDTO,
token?: string
): Promise<{ data?: DocumentType; error?: string; status?: number }> {
try {
// 验证必填字段
if (!documentType.name) {
return { error: '文档类型名称不能为空', status: 400 };
}
const response = await axios.post(`${API_BASE_URL}/api/document-types`, dto, {
headers: { ...authHeaders(token), "Content-Type": "application/json" },
});
const item = extractData<any>(response);
if (!item) return { error: "创建失败", status: 500 };
if (!documentType.group_ids || documentType.group_ids.length === 0) {
return { error: '请至少选择一个关联的评查点分组', status: 400 };
}
// 构建请求数据
const requestData = {
name: documentType.name.trim(),
description: documentType.description || '',
entry_module_id: documentType.entry_module_id || null,
code: documentType.code || null,
group_ids: documentType.group_ids,
llm_extraction_template_id: documentType.llm_extraction_template_id || null,
vlm_extraction_template_id: documentType.vlm_extraction_template_id || null,
};
const response = await apiRequest<ApiResponse<DocumentType>>(
'/api/v3/document-types',
{
method: 'POST',
headers: frontendJWT ? { 'Authorization': `Bearer ${frontendJWT}` } : undefined,
data: requestData,
}
);
if (response.error) {
console.error('创建文档类型API返回错误:', response.error, '状态码:', response.status);
return { error: response.error, status: response.status };
}
const newDocumentType = response.data?.data;
if (!newDocumentType) {
return { error: '创建文档类型失败: 无法获取新创建的数据', status: 500 };
}
return { data: convertToUIDocumentType(newDocumentType) };
} catch (error) {
console.error('创建文档类型失败:', error);
return {
error: error instanceof Error ? error.message : '创建文档类型失败',
status: 500
data: {
id: item.id, name: item.name, code: item.code,
description: item.description || null,
entryModuleId: item.entryModuleId || null,
isEnabled: item.isEnabled !== false,
ruleSetIds: item.ruleSetIds || [],
},
};
} catch (error) {
const msg = (error as any)?.response?.data?.message || (error instanceof Error ? error.message : "创建失败");
return { error: msg, status: (error as any)?.response?.status || 500 };
}
}
/**
* 更新文档类型
* @param id 文档类型ID
* @param documentType 文档类型数据
* @param frontendJWT JWT token
* @returns 更新结果
*/
export async function updateDocumentType(
id: string,
documentType: DocumentTypeUpdateDTO,
frontendJWT?: string
): Promise<{
data?: DocumentTypeUI;
error?: string;
status?: number;
}> {
id: number,
dto: DocumentTypeUpdateDTO,
token?: string
): Promise<{ data?: DocumentType; error?: string; status?: number }> {
try {
// 验证必填字段
if (!id) {
return { error: '文档类型ID不能为空', status: 400 };
}
const response = await axios.put(`${API_BASE_URL}/api/document-types/${id}`, dto, {
headers: { ...authHeaders(token), "Content-Type": "application/json" },
});
const item = extractData<any>(response);
if (!item) return { error: "更新失败", status: 500 };
if (!documentType.name) {
return { error: '文档类型名称不能为空', status: 400 };
}
if (!documentType.group_ids || documentType.group_ids.length === 0) {
return { error: '请至少选择一个关联的评查点分组', status: 400 };
}
// 构建请求数据
const requestData = {
name: documentType.name.trim(),
description: documentType.description || '',
entry_module_id: documentType.entry_module_id || null,
code: documentType.code || null,
group_ids: documentType.group_ids,
llm_extraction_template_id: documentType.llm_extraction_template_id || null,
vlm_extraction_template_id: documentType.vlm_extraction_template_id || null,
};
const response = await apiRequest<ApiResponse<DocumentType>>(
`/api/v3/document-types/${id}`,
{
method: 'PUT',
headers: frontendJWT ? { 'Authorization': `Bearer ${frontendJWT}` } : undefined,
data: requestData,
}
);
if (response.error) {
console.error('更新文档类型API返回错误:', response.error, '状态码:', response.status);
return { error: response.error, status: response.status };
}
const updatedDocumentType = response.data?.data;
if (!updatedDocumentType) {
return { error: '更新文档类型失败: 无法获取更新后的数据', status: 500 };
}
return { data: convertToUIDocumentType(updatedDocumentType) };
} catch (error) {
console.error('更新文档类型失败:', error);
return {
error: error instanceof Error ? error.message : '更新文档类型失败',
status: 500
data: {
id: item.id, name: item.name, code: item.code,
description: item.description || null,
entryModuleId: item.entryModuleId || null,
isEnabled: item.isEnabled !== false,
ruleSetIds: item.ruleSetIds || [],
},
};
} catch (error) {
const msg = (error as any)?.response?.data?.message || (error instanceof Error ? error.message : "更新失败");
return { error: msg, status: (error as any)?.response?.status || 500 };
}
}
/**
* 删除文档类型
* @param id 文档类型ID
* @param frontendJWT JWT token
* @returns 删除结果
*/
export async function deleteDocumentType(
id: string,
frontendJWT?: string
): Promise<{
success?: boolean;
error?: string;
status?: number;
}> {
id: number,
token?: string
): Promise<{ success?: boolean; error?: string; status?: number }> {
try {
if (!id) {
return { error: '文档类型ID不能为空', status: 400 };
}
const response = await apiRequest<ApiResponse<{ message: string }>>(
`/api/v3/document-types/${id}`,
{
method: 'DELETE',
headers: frontendJWT ? { 'Authorization': `Bearer ${frontendJWT}` } : undefined,
}
);
if (response.error) {
return { error: response.error, status: response.status };
}
await axios.delete(`${API_BASE_URL}/api/document-types/${id}`, {
headers: authHeaders(token),
});
return { success: true };
} catch (error) {
console.error('删除文档类型失败:', error);
return {
error: error instanceof Error ? error.message : '删除文档类型失败',
status: 500
};
return { error: error instanceof Error ? error.message : "删除失败", status: 500 };
}
}
/**
* 获取入口模块选项
* @param token JWT token
* @returns 入口模块列表
*/
export async function getEntryModules(
token?: string
): Promise<{
data?: Array<{ id: number; name: string }>;
error?: string;
status?: number;
}> {
): Promise<{ data?: EntryModuleOption[]; error?: string }> {
try {
const response = await apiRequest<ApiResponse<OptionsResponseData>>(
'/api/v3/document-types/options/entry-modules',
{
method: 'GET',
headers: token ? { 'Authorization': `Bearer ${token}` } : undefined,
}
);
if (response.error) {
return { error: response.error, status: response.status };
}
const items = response.data?.data?.items;
if (!items) {
return { data: [] };
}
return { data: items };
const response = await axios.get(`${API_BASE_URL}/api/v3/entry-modules`, {
headers: authHeaders(token),
});
const items = extractData<any[]>(response) || [];
return { data: items.map((m: any) => ({ id: m.id, name: m.name })) };
} catch (error) {
console.error('获取入口模块失败:', error);
return { error: error instanceof Error ? error.message : '获取入口模块失败' };
return { error: error instanceof Error ? error.message : "获取入口模块失败" };
}
}
/**
* 将扁平的分组列表转换为树形结构
* @param flatList 扁平列表,每个元素包含 id 和 pid
* @returns 树形结构数组
* 获取规则集选项
*/
function buildGroupTree(flatList: any[]): RuleGroup[] {
const map = new Map<string | number, RuleGroup>();
const roots: RuleGroup[] = [];
// 第一遍:创建所有节点的映射
flatList.forEach(item => {
const node: RuleGroup = {
id: item.id.toString(),
pid: item.pid !== null && item.pid !== undefined ? item.pid.toString() : '0',
name: item.name || '',
code: item.code,
is_enabled: item.is_enabled !== undefined ? item.is_enabled : true,
ruleCount: item.ruleCount || item.rule_count || 0,
children: [],
createdAt: item.created_at || item.createdAt,
description: item.description
};
map.set(item.id, node);
});
// 第二遍:建立父子关系
flatList.forEach(item => {
const node = map.get(item.id);
if (!node) return;
const pid = item.pid !== null && item.pid !== undefined ? item.pid : 0;
// pid 为 0 或 null 的是根节点
if (pid === 0 || pid === '0' || pid === null) {
roots.push(node);
} else {
// 找到父节点并添加到其 children 中
const parent = map.get(pid);
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
} else {
// 如果找不到父节点,作为根节点处理
roots.push(node);
}
}
});
return roots;
}
/**
* 获取所有评查点分组(使用 FastAPI v3 接口)
* @param token JWT token
* @returns 评查点分组列表(树形结构)
*/
export async function getAllEvaluationPointGroups_ForDocTypes(
export async function getRuleSets(
token?: string
): Promise<{
data?: RuleGroup[];
error?: string;
status?: number;
}> {
// 调用原始方法获取扁平数据
const result = await getAllEvaluationPointGroups(false, false, token); // 第二个参数改为 false,不自动构建树
if (result.error || !result.data) {
return result;
}
// 构建树形结构
const treeData = buildGroupTree(result.data);
return {
data: treeData,
error: result.error
};
}
/**
* 获取一级评查点分组(pid=0 的分组)
* @param token JWT token
* @returns 一级评查点分组列表
*/
export async function getRootEvaluationPointGroups_ForDocTypes(
token?: string
): Promise<{
data?: RuleGroup[];
error?: string;
status?: number;
}> {
): Promise<{ data?: RuleSetOption[]; error?: string }> {
try {
// 导入 getEvaluationPointGroups 函数
const { getEvaluationPointGroups } = await import('../evaluation_points/rule-groups');
// 获取一级分组(pid='0' 或 pid=null
const result = await getEvaluationPointGroups(
{
pid: '0',
pageSize: 1000, // 设置较大的页面大小以获取所有一级分组
},
token
);
if (result.error) {
return { error: result.error, status: result.status };
}
const response = await axios.get(`${API_BASE_URL}/api/rule-sets`, {
headers: authHeaders(token),
});
const items = extractData<any[]>(response) || [];
return {
data: result.data || [],
error: result.error
data: items.map((r: any) => ({
id: r.id,
ruleType: r.ruleType,
ruleName: r.ruleName,
status: r.status,
})),
};
} catch (error) {
console.error('获取一级评查点分组失败:', error);
return { error: error instanceof Error ? error.message : '获取一级评查点分组失败' };
return { error: error instanceof Error ? error.message : "获取规则集失败" };
}
}
/**
* 获取父级评查点分组(pid=0的分组)
* @param token JWT token
* @returns 父级评查点分组列表
*/
export async function getParentEvaluationPointGroups(
token?: string
): Promise<{
data?: DocumentTypeGroup[];
error?: string;
status?: number;
}> {
try {
const response = await apiRequest<ApiResponse<OptionsResponseData>>(
'/api/v3/document-types/options/evaluation-point-groups',
{
method: 'GET',
headers: token ? { 'Authorization': `Bearer ${token}` } : undefined,
},
{ root_only: true }
);
if (response.error) {
return { error: response.error, status: response.status };
}
// console.log('文档类型返回的评查点分组父级数据', response.data)
const items = response.data?.data?.items;
if (!items) {
return { data: [] };
}
// 转换为DocumentTypeGroup格式
const groups: DocumentTypeGroup[] = items.map(item => ({
id: item.id,
name: item.name,
code: item.code
}));
return { data: groups };
} catch (error) {
console.error('获取父级评查点分组失败:', error);
return { error: error instanceof Error ? error.message : '获取父级评查点分组失败' };
}
}
/**
* 获取提示词模板选项
* @param templateType 模板类型(LLM_Extraction, VLM_Extraction 等)
* @param token JWT token
* @returns 提示词模板列表
*/
export async function getPromptTemplateOptions(
templateType?: string,
token?: string
): Promise<{
data?: Array<{ id: number; template_name: string; template_code: string; template_type: string }>;
error?: string;
status?: number;
}> {
try {
const params: Record<string, string> = {};
if (templateType) {
params.template_type = templateType;
}
const response = await apiRequest<ApiResponse<OptionsResponseData>>(
'/api/v3/document-types/options/prompt-templates',
{
method: 'GET',
headers: token ? { 'Authorization': `Bearer ${token}` } : undefined,
},
Object.keys(params).length > 0 ? params : undefined
);
if (response.error) {
return { error: response.error, status: response.status };
}
const items = response.data?.data?.items;
if (!items) {
return { data: [] };
}
return { data: items as any };
} catch (error) {
console.error('获取提示词模板选项失败:', error);
return { error: error instanceof Error ? error.message : '获取提示词模板选项失败' };
}
}
/**
* 将API返回的文档类型转换为UI文档类型
*/
function convertToUIDocumentType(type: DocumentType): DocumentTypeUI {
return {
id: type.id,
name: type.name,
code: type.code,
description: type.description || '',
groups: type.groups?.map(g => ({
id: g.id,
name: g.name,
code: g.code
})) || [],
entry_module: type.entry_module || null,
llm_extraction_template_id: type.llm_extraction_template_id,
vlm_extraction_template_id: type.vlm_extraction_template_id,
created_at: formatDate(type.created_at),
updated_at: formatDate(type.updated_at),
};
}
+1 -1
View File
@@ -2,7 +2,7 @@ import { postgrestGet, postgrestDelete, postgrestPut, postgrestPost } from '../p
import { getDocumentTypes } from '../document-types/document-types';
import { formatDate } from '../../utils';
import { API_BASE_URL } from '~/config/api-config';
import type { DocumentType } from './files-upload';
import type { DocumentType } from '../document-types/document-types';
/**
* 从不同格式的 API 响应中提取数据