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:
@@ -1,659 +1,258 @@
|
|||||||
import { apiRequest } from '../axios-client';
|
import { apiRequest } from '../axios-client';
|
||||||
import { formatDate } from '../../utils';
|
import { API_BASE_URL } from '../../config/api-config';
|
||||||
import { getAllEvaluationPointGroups, type RuleGroup } from '../evaluation_points/rule-groups';
|
import axios from 'axios';
|
||||||
|
|
||||||
|
// ==================== 类型定义 ====================
|
||||||
|
|
||||||
// 定义文档类型接口
|
|
||||||
export interface DocumentType {
|
export interface DocumentType {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
code?: string | null;
|
code: string;
|
||||||
description: string | null;
|
description: string | null;
|
||||||
evaluation_point_groups_ids: number[]; // 评查点分组ID数组
|
entryModuleId: number | null;
|
||||||
entry_module_id?: number | null;
|
isEnabled: boolean;
|
||||||
entry_module?: {
|
ruleSetIds: number[];
|
||||||
id: number;
|
createdAt?: string;
|
||||||
name: string;
|
updatedAt?: string;
|
||||||
} | null;
|
|
||||||
groups?: DocumentTypeGroup[];
|
|
||||||
llm_extraction_template_id?: number | null;
|
|
||||||
vlm_extraction_template_id?: number | null;
|
|
||||||
created_at: string;
|
|
||||||
updated_at: 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 {
|
export interface DocumentTypeCreateDTO {
|
||||||
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
group_ids: number[]; // 改为 number[] 数组
|
entryModuleId?: number | null;
|
||||||
code: string | null;
|
isEnabled?: boolean;
|
||||||
entry_module_id?: number | null;
|
sortOrder?: number;
|
||||||
llm_extraction_template_id?: number | null;
|
ruleSetIds?: number[];
|
||||||
vlm_extraction_template_id?: number | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 文档类型更新接口
|
export interface DocumentTypeUpdateDTO {
|
||||||
export interface DocumentTypeUpdateDTO extends DocumentTypeCreateDTO {
|
name?: string;
|
||||||
|
description?: string;
|
||||||
|
entryModuleId?: number | null;
|
||||||
|
isEnabled?: boolean;
|
||||||
|
sortOrder?: number;
|
||||||
|
ruleSetIds?: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RuleSetOption {
|
||||||
id: number;
|
id: number;
|
||||||
|
ruleType: string;
|
||||||
|
ruleName: string;
|
||||||
|
status: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 文档类型分组关系
|
export interface EntryModuleOption {
|
||||||
export interface DocumentTypeGroup {
|
id: number;
|
||||||
id: string | number;
|
|
||||||
name: string;
|
name: string;
|
||||||
code?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 搜索参数
|
|
||||||
export interface DocumentTypeSearchParams {
|
export interface DocumentTypeSearchParams {
|
||||||
name?: string;
|
name?: string;
|
||||||
group_id?: number; // 按评查点分组ID筛选
|
entry_module_id?: number;
|
||||||
entry_module_id?: number; // 按入口模块ID筛选
|
ids?: number[];
|
||||||
ids?: number[]; // 按ID列表筛选
|
|
||||||
page?: number;
|
page?: number;
|
||||||
pageSize?: number;
|
pageSize?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// API 响应格式
|
|
||||||
interface ApiResponse<T> {
|
interface ApiResponse<T> {
|
||||||
code: number;
|
code: number;
|
||||||
msg: string;
|
message: string;
|
||||||
data: T;
|
data: T;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 列表响应数据
|
// ==================== API 调用 ====================
|
||||||
interface ListResponseData {
|
|
||||||
total: number;
|
function authHeaders(token?: string): Record<string, string> {
|
||||||
page: number;
|
const headers: Record<string, string> = {};
|
||||||
page_size: number;
|
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||||
items: DocumentType[];
|
return headers;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 选项数据
|
function extractData<T>(response: any): T | null {
|
||||||
interface OptionsResponseData {
|
return response?.data?.data ?? response?.data ?? null;
|
||||||
items: Array<{ id: number; name: string; code?: string }>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取文档类型列表
|
* 获取文档类型列表
|
||||||
* @param searchParams 搜索参数
|
|
||||||
* @param frontendJWT JWT token
|
|
||||||
* @returns 文档类型列表和总数
|
|
||||||
*/
|
*/
|
||||||
export async function getDocumentTypes(
|
export async function getDocumentTypes(
|
||||||
searchParams: DocumentTypeSearchParams = {},
|
searchParams: DocumentTypeSearchParams = {},
|
||||||
frontendJWT?: string
|
token?: string
|
||||||
): Promise<{
|
): Promise<{ data?: { types: DocumentType[]; total: number }; error?: string; status?: number }> {
|
||||||
data?: { types: DocumentTypeUI[], total: number };
|
|
||||||
error?: string;
|
|
||||||
status?: number;
|
|
||||||
}> {
|
|
||||||
try {
|
try {
|
||||||
const page = searchParams.page || 1;
|
const params: Record<string, string | number> = {
|
||||||
const pageSize = searchParams.pageSize || 10;
|
page: searchParams.page || 1,
|
||||||
|
pageSize: searchParams.pageSize || 50,
|
||||||
// 构建查询参数
|
|
||||||
const params: Record<string, string | number | number[]> = {
|
|
||||||
page,
|
|
||||||
page_size: pageSize,
|
|
||||||
};
|
};
|
||||||
|
if (searchParams.ids) params.ids = searchParams.ids.join(",");
|
||||||
|
|
||||||
if (searchParams.name) {
|
const response = await axios.get(`${API_BASE_URL}/api/document-types`, {
|
||||||
params.name = searchParams.name;
|
params,
|
||||||
}
|
headers: authHeaders(token),
|
||||||
|
});
|
||||||
|
|
||||||
if (searchParams.group_id) {
|
const items = extractData<any[]>(response) || [];
|
||||||
params.group_id = searchParams.group_id;
|
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) {
|
return { data: { types, total: types.length } };
|
||||||
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
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('获取文档类型列表失败:', error);
|
console.error("获取文档类型列表失败:", error);
|
||||||
return {
|
return { error: error instanceof Error ? error.message : "获取文档类型列表失败", status: 500 };
|
||||||
error: error instanceof Error ? error.message : '获取文档类型列表失败',
|
|
||||||
status: 500
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取文档类型详情
|
* 获取文档类型详情
|
||||||
* @param id 文档类型ID
|
|
||||||
* @param frontendJWT JWT token
|
|
||||||
* @returns 文档类型详情
|
|
||||||
*/
|
*/
|
||||||
export async function getDocumentType(
|
export async function getDocumentType(
|
||||||
id: string,
|
id: number,
|
||||||
frontendJWT?: string
|
token?: string
|
||||||
): Promise<{
|
): Promise<{ data?: DocumentType; error?: string; status?: number }> {
|
||||||
data?: DocumentTypeUI;
|
|
||||||
error?: string;
|
|
||||||
status?: number;
|
|
||||||
}> {
|
|
||||||
try {
|
try {
|
||||||
if (!id) {
|
const response = await axios.get(`${API_BASE_URL}/api/document-types/${id}`, {
|
||||||
return { error: '文档类型ID不能为空', status: 400 };
|
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 {
|
return {
|
||||||
error: error instanceof Error ? error.message : '获取文档类型详情失败',
|
data: {
|
||||||
status: 500
|
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(
|
export async function createDocumentType(
|
||||||
documentType: DocumentTypeCreateDTO,
|
dto: DocumentTypeCreateDTO,
|
||||||
frontendJWT?: string
|
token?: string
|
||||||
): Promise<{
|
): Promise<{ data?: DocumentType; error?: string; status?: number }> {
|
||||||
data?: DocumentTypeUI;
|
|
||||||
error?: string;
|
|
||||||
status?: number;
|
|
||||||
}> {
|
|
||||||
try {
|
try {
|
||||||
// 验证必填字段
|
const response = await axios.post(`${API_BASE_URL}/api/document-types`, dto, {
|
||||||
if (!documentType.name) {
|
headers: { ...authHeaders(token), "Content-Type": "application/json" },
|
||||||
return { error: '文档类型名称不能为空', status: 400 };
|
});
|
||||||
}
|
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 {
|
return {
|
||||||
error: error instanceof Error ? error.message : '创建文档类型失败',
|
data: {
|
||||||
status: 500
|
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(
|
export async function updateDocumentType(
|
||||||
id: string,
|
id: number,
|
||||||
documentType: DocumentTypeUpdateDTO,
|
dto: DocumentTypeUpdateDTO,
|
||||||
frontendJWT?: string
|
token?: string
|
||||||
): Promise<{
|
): Promise<{ data?: DocumentType; error?: string; status?: number }> {
|
||||||
data?: DocumentTypeUI;
|
|
||||||
error?: string;
|
|
||||||
status?: number;
|
|
||||||
}> {
|
|
||||||
try {
|
try {
|
||||||
// 验证必填字段
|
const response = await axios.put(`${API_BASE_URL}/api/document-types/${id}`, dto, {
|
||||||
if (!id) {
|
headers: { ...authHeaders(token), "Content-Type": "application/json" },
|
||||||
return { error: '文档类型ID不能为空', status: 400 };
|
});
|
||||||
}
|
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 {
|
return {
|
||||||
error: error instanceof Error ? error.message : '更新文档类型失败',
|
data: {
|
||||||
status: 500
|
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(
|
export async function deleteDocumentType(
|
||||||
id: string,
|
id: number,
|
||||||
frontendJWT?: string
|
token?: string
|
||||||
): Promise<{
|
): Promise<{ success?: boolean; error?: string; status?: number }> {
|
||||||
success?: boolean;
|
|
||||||
error?: string;
|
|
||||||
status?: number;
|
|
||||||
}> {
|
|
||||||
try {
|
try {
|
||||||
if (!id) {
|
await axios.delete(`${API_BASE_URL}/api/document-types/${id}`, {
|
||||||
return { error: '文档类型ID不能为空', status: 400 };
|
headers: authHeaders(token),
|
||||||
}
|
});
|
||||||
|
|
||||||
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 };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch (error) {
|
} 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(
|
export async function getEntryModules(
|
||||||
token?: string
|
token?: string
|
||||||
): Promise<{
|
): Promise<{ data?: EntryModuleOption[]; error?: string }> {
|
||||||
data?: Array<{ id: number; name: string }>;
|
|
||||||
error?: string;
|
|
||||||
status?: number;
|
|
||||||
}> {
|
|
||||||
try {
|
try {
|
||||||
const response = await apiRequest<ApiResponse<OptionsResponseData>>(
|
const response = await axios.get(`${API_BASE_URL}/api/v3/entry-modules`, {
|
||||||
'/api/v3/document-types/options/entry-modules',
|
headers: authHeaders(token),
|
||||||
{
|
|
||||||
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 };
|
|
||||||
} catch (error) {
|
|
||||||
console.error('获取入口模块失败:', error);
|
|
||||||
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);
|
|
||||||
});
|
});
|
||||||
|
const items = extractData<any[]>(response) || [];
|
||||||
// 第二遍:建立父子关系
|
return { data: items.map((m: any) => ({ id: m.id, name: m.name })) };
|
||||||
flatList.forEach(item => {
|
} catch (error) {
|
||||||
const node = map.get(item.id);
|
return { error: error instanceof Error ? error.message : "获取入口模块失败" };
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取规则集选项
|
||||||
|
*/
|
||||||
|
export async function getRuleSets(
|
||||||
|
token?: string
|
||||||
|
): Promise<{ data?: RuleSetOption[]; error?: string }> {
|
||||||
|
try {
|
||||||
|
const response = await axios.get(`${API_BASE_URL}/api/rule-sets`, {
|
||||||
|
headers: authHeaders(token),
|
||||||
});
|
});
|
||||||
|
const items = extractData<any[]>(response) || [];
|
||||||
return roots;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取所有评查点分组(使用 FastAPI v3 接口)
|
|
||||||
* @param token JWT token
|
|
||||||
* @returns 评查点分组列表(树形结构)
|
|
||||||
*/
|
|
||||||
export async function getAllEvaluationPointGroups_ForDocTypes(
|
|
||||||
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 {
|
return {
|
||||||
data: treeData,
|
data: items.map((r: any) => ({
|
||||||
error: result.error
|
id: r.id,
|
||||||
};
|
ruleType: r.ruleType,
|
||||||
}
|
ruleName: r.ruleName,
|
||||||
|
status: r.status,
|
||||||
/**
|
})),
|
||||||
* 获取一级评查点分组(pid=0 的分组)
|
|
||||||
* @param token JWT token
|
|
||||||
* @returns 一级评查点分组列表
|
|
||||||
*/
|
|
||||||
export async function getRootEvaluationPointGroups_ForDocTypes(
|
|
||||||
token?: string
|
|
||||||
): Promise<{
|
|
||||||
data?: RuleGroup[];
|
|
||||||
error?: string;
|
|
||||||
status?: number;
|
|
||||||
}> {
|
|
||||||
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 };
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
data: result.data || [],
|
|
||||||
error: result.error
|
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} 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),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { postgrestGet, postgrestDelete, postgrestPut, postgrestPost } from '../p
|
|||||||
import { getDocumentTypes } from '../document-types/document-types';
|
import { getDocumentTypes } from '../document-types/document-types';
|
||||||
import { formatDate } from '../../utils';
|
import { formatDate } from '../../utils';
|
||||||
import { API_BASE_URL } from '~/config/api-config';
|
import { API_BASE_URL } from '~/config/api-config';
|
||||||
import type { DocumentType } from './files-upload';
|
import type { DocumentType } from '../document-types/document-types';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从不同格式的 API 响应中提取数据
|
* 从不同格式的 API 响应中提取数据
|
||||||
|
|||||||
@@ -1,502 +1,152 @@
|
|||||||
import { useState, useEffect, useRef } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { useSearchParams, useNavigate, useLoaderData, useFetcher, useRevalidator } from "@remix-run/react";
|
import { useNavigate, useLoaderData } from "@remix-run/react";
|
||||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
|
import { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
|
||||||
import { Table } from "~/components/ui/Table";
|
|
||||||
import { Card } from "~/components/ui/Card";
|
import { Card } from "~/components/ui/Card";
|
||||||
import { Button } from "~/components/ui/Button";
|
import { Button } from "~/components/ui/Button";
|
||||||
import { Pagination } from "~/components/ui/Pagination";
|
|
||||||
import { FilterPanel, FilterSelect, SearchFilter } from "~/components/ui/FilterPanel";
|
|
||||||
import { toastService } from "~/components/ui/Toast";
|
import { toastService } from "~/components/ui/Toast";
|
||||||
import { messageService } from "~/components/ui/MessageModal";
|
|
||||||
import { usePermission } from "~/hooks/usePermission";
|
|
||||||
import {
|
import {
|
||||||
getDocumentTypes,
|
getDocumentTypes,
|
||||||
deleteDocumentType,
|
deleteDocumentType,
|
||||||
type DocumentTypeUI,
|
getEntryModules,
|
||||||
type DocumentTypeSearchParams,
|
type DocumentType,
|
||||||
type DocumentTypeGroup,
|
type EntryModuleOption,
|
||||||
getParentEvaluationPointGroups
|
|
||||||
} from "~/api/document-types/document-types";
|
} from "~/api/document-types/document-types";
|
||||||
import documentTypesStyles from "~/styles/pages/document-types_index.css?url";
|
import documentTypesStyles from "~/styles/pages/document-types_index.css?url";
|
||||||
|
|
||||||
|
|
||||||
// 引入CSS样式
|
|
||||||
export function links() {
|
export function links() {
|
||||||
return [
|
return [{ rel: "stylesheet", href: documentTypesStyles }];
|
||||||
{ rel: "stylesheet", href: documentTypesStyles }
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 页面元数据
|
|
||||||
export const meta: MetaFunction = () => {
|
export const meta: MetaFunction = () => {
|
||||||
return [
|
return [
|
||||||
{ title: "文档类型管理 - 中国烟草AI合同及卷宗审核系统" },
|
{ title: "文档类型管理 - 中国烟草AI合同及卷宗审核系统" },
|
||||||
{ name: "description", content: "管理文档类型,包括查看、编辑和删除文档类型" },
|
{ name: "description", content: "管理文档类型及其规则集绑定" },
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
// 定义加载器返回的数据类型
|
|
||||||
interface LoaderData {
|
interface LoaderData {
|
||||||
types: DocumentTypeUI[];
|
types: DocumentType[];
|
||||||
total: number;
|
entryModules: EntryModuleOption[];
|
||||||
pageSize: number;
|
|
||||||
currentPage: number;
|
|
||||||
error?: string;
|
|
||||||
parentGroups: DocumentTypeGroup[];
|
|
||||||
frontendJWT?: string | null;
|
frontendJWT?: string | null;
|
||||||
}
|
|
||||||
|
|
||||||
// 定义 action 返回的数据类型
|
|
||||||
interface ActionResponse {
|
|
||||||
success?: boolean;
|
|
||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 加载函数 - 获取文档类型列表
|
|
||||||
export async function loader({ request }: LoaderFunctionArgs) {
|
export async function loader({ request }: LoaderFunctionArgs) {
|
||||||
try {
|
try {
|
||||||
// 获取用户会话信息
|
|
||||||
const { getUserSession } = await import("~/api/login/auth.server");
|
const { getUserSession } = await import("~/api/login/auth.server");
|
||||||
const { frontendJWT } = await getUserSession(request);
|
const { frontendJWT } = await getUserSession(request);
|
||||||
|
|
||||||
const url = new URL(request.url);
|
const [typesRes, modulesRes] = await Promise.all([
|
||||||
const name = url.searchParams.get('name') || undefined;
|
getDocumentTypes({}, frontendJWT),
|
||||||
const groupId = url.searchParams.get('group_id') || undefined;
|
getEntryModules(frontendJWT),
|
||||||
const entryModuleId = url.searchParams.get('entry_module_id') || undefined;
|
|
||||||
const page = parseInt(url.searchParams.get('page') || '1', 10);
|
|
||||||
const pageSize = parseInt(url.searchParams.get('pageSize') || '10', 10);
|
|
||||||
|
|
||||||
// 构建搜索参数
|
|
||||||
const searchParams: DocumentTypeSearchParams = {
|
|
||||||
name,
|
|
||||||
group_id: groupId ? parseInt(groupId, 10) : undefined,
|
|
||||||
entry_module_id: entryModuleId ? parseInt(entryModuleId, 10) : undefined,
|
|
||||||
page,
|
|
||||||
pageSize
|
|
||||||
};
|
|
||||||
|
|
||||||
// 并行获取文档类型数据和父级评查点分组
|
|
||||||
const [parentGroupsResponse, typesResponse] = await Promise.all([
|
|
||||||
getParentEvaluationPointGroups(frontendJWT),
|
|
||||||
getDocumentTypes(searchParams, frontendJWT)
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// 如果获取父级评查点分组失败,返回空数组(不阻塞页面加载)
|
return {
|
||||||
if(parentGroupsResponse.error){
|
types: typesRes.data?.types || [],
|
||||||
console.error("获取父级评查点分组失败:", parentGroupsResponse.error);
|
entryModules: modulesRes.data || [],
|
||||||
}
|
|
||||||
const parentGroups = parentGroupsResponse.error ? [] : (parentGroupsResponse.data || []);
|
|
||||||
|
|
||||||
// 如果获取文档类型失败(如403无权限),返回空数组和错误信息
|
|
||||||
if(typesResponse.error){
|
|
||||||
console.error("获取文档类型失败:", typesResponse.error);
|
|
||||||
return Response.json({
|
|
||||||
types: [],
|
|
||||||
total: 0,
|
|
||||||
pageSize,
|
|
||||||
currentPage: page,
|
|
||||||
parentGroups: [],
|
|
||||||
frontendJWT,
|
frontendJWT,
|
||||||
error: typesResponse.error
|
};
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const typesResult = typesResponse.data?.types || [];
|
|
||||||
|
|
||||||
return Response.json({
|
|
||||||
types: typesResult,
|
|
||||||
total: typesResponse.data?.total || typesResult.length,
|
|
||||||
pageSize,
|
|
||||||
currentPage: page,
|
|
||||||
parentGroups,
|
|
||||||
frontendJWT
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("加载文档类型列表失败:", error);
|
return { types: [], entryModules: [], error: "加载失败" };
|
||||||
const errorMessage = error instanceof Error ? error.message : "加载文档类型列表失败";
|
|
||||||
return Response.json({
|
|
||||||
types: [],
|
|
||||||
total: 0,
|
|
||||||
pageSize: 10,
|
|
||||||
currentPage: 1,
|
|
||||||
parentGroups: [],
|
|
||||||
frontendJWT: null,
|
|
||||||
error: errorMessage
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 动作函数 - 处理删除请求
|
export default function DocumentTypesIndex() {
|
||||||
export async function action({ request }: ActionFunctionArgs) {
|
|
||||||
// 获取表单数据
|
|
||||||
const formData = await request.formData();
|
|
||||||
const id = formData.get("id") as string;
|
|
||||||
const intent = formData.get("intent") as string;
|
|
||||||
const { getUserSession } = await import("~/api/login/auth.server");
|
|
||||||
const { frontendJWT } = await getUserSession(request);
|
|
||||||
|
|
||||||
if (intent === "delete" && id) {
|
|
||||||
try {
|
|
||||||
const result = await deleteDocumentType(id, frontendJWT || undefined);
|
|
||||||
|
|
||||||
if (result.error) {
|
|
||||||
return Response.json({ success: false, error: result.error }, { status: result.status || 500 });
|
|
||||||
}
|
|
||||||
|
|
||||||
return Response.json({ success: true });
|
|
||||||
} catch (error) {
|
|
||||||
return Response.json(
|
|
||||||
{ success: false, error: error instanceof Error ? error.message : "删除文档类型失败" },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Response.json({ success: false, error: "无效的操作" }, { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// 文档类型列表组件
|
|
||||||
export default function DocumentTypesList() {
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [searchParams, setSearchParams] = useSearchParams();
|
const loaderData = useLoaderData<LoaderData>();
|
||||||
const fetcher = useFetcher<ActionResponse>();
|
const [types, setTypes] = useState<DocumentType[]>(loaderData.types || []);
|
||||||
const revalidator = useRevalidator();
|
const entryModules = loaderData.entryModules || [];
|
||||||
const processedResponseRef = useRef<string | null>(null);
|
|
||||||
|
|
||||||
// 获取加载器数据
|
|
||||||
const { types, total, error, parentGroups, frontendJWT } = useLoaderData<LoaderData>();
|
|
||||||
|
|
||||||
// 处理 fetcher 响应
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// 为每个响应生成唯一标识,避免重复处理
|
setTypes(loaderData.types || []);
|
||||||
const responseKey = fetcher.data ? JSON.stringify(fetcher.data) : null;
|
}, [loaderData.types]);
|
||||||
|
|
||||||
if (responseKey && responseKey !== processedResponseRef.current) {
|
const getEntryModuleName = (id: number | null) => {
|
||||||
if (fetcher.data?.success) {
|
if (!id) return "—";
|
||||||
toastService.success('删除成功!');
|
return entryModules.find((m) => m.id === id)?.name || `#${id}`;
|
||||||
processedResponseRef.current = responseKey;
|
};
|
||||||
// 只重新验证数据,不刷新整个页面
|
|
||||||
revalidator.revalidate();
|
|
||||||
} else if (fetcher.data?.error) {
|
|
||||||
toastService.error(`删除失败: ${fetcher.data.error}`);
|
|
||||||
processedResponseRef.current = responseKey;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [fetcher.data, revalidator]);
|
|
||||||
|
|
||||||
// 权限控制
|
const handleDelete = async (type: DocumentType) => {
|
||||||
const { canCreate, canUpdate, canDelete, canView } = usePermission();
|
const confirmed = window.confirm(`确定要删除文档类型「${type.name}」吗?`);
|
||||||
const canCreateType = canCreate('document_type');
|
if (!confirmed) return;
|
||||||
const canUpdateType = canUpdate('document_type');
|
|
||||||
const canDeleteType = canDelete('document_type');
|
|
||||||
// console.log('document_type---canDeleteType',canDeleteType)
|
|
||||||
const canViewType = canView('document_type');
|
|
||||||
|
|
||||||
// 获取搜索参数
|
const result = await deleteDocumentType(type.id, loaderData.frontendJWT ?? undefined);
|
||||||
const name = searchParams.get('name') || '';
|
if (result.success) {
|
||||||
const currentPage = parseInt(searchParams.get('page') || String(1), 10);
|
toastService.success("文档类型已删除");
|
||||||
const pageSize = parseInt(searchParams.get('pageSize') || String(10), 10);
|
setTypes((prev) => prev.filter((t) => t.id !== type.id));
|
||||||
|
|
||||||
// 处理测试loader返回的信息
|
|
||||||
useEffect(() => {
|
|
||||||
// console.log('返回的父级评查点分组数据',parentGroups)
|
|
||||||
}, [parentGroups])
|
|
||||||
|
|
||||||
// 处理loader加载数据的时候的错误
|
|
||||||
useEffect(() => {
|
|
||||||
if(error){
|
|
||||||
// 如果是无权限错误,显示友好提示
|
|
||||||
if(error.includes('Permission denied') || error.includes('无权限') || error.includes('权限不足')){
|
|
||||||
toastService.error('无权限访问文档类型管理,请联系系统管理员');
|
|
||||||
} else {
|
} else {
|
||||||
toastService.error(error);
|
toastService.error(result.error || "删除失败");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}, [error]);
|
|
||||||
|
|
||||||
|
|
||||||
// 处理名称搜索
|
|
||||||
const handleNameSearch = (value: string) => {
|
|
||||||
const newParams = new URLSearchParams(searchParams);
|
|
||||||
if (value) {
|
|
||||||
newParams.set('name', value);
|
|
||||||
} else {
|
|
||||||
newParams.delete('name');
|
|
||||||
}
|
|
||||||
newParams.set('page', '1');
|
|
||||||
setSearchParams(newParams);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 处理筛选变更
|
|
||||||
const handleFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
const newParams = new URLSearchParams(searchParams);
|
|
||||||
|
|
||||||
if (value) {
|
|
||||||
newParams.set(name, value);
|
|
||||||
} else {
|
|
||||||
newParams.delete(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 切换筛选条件时,重置到第一页
|
|
||||||
newParams.set('page', '1');
|
|
||||||
|
|
||||||
setSearchParams(newParams);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 处理重置筛选
|
|
||||||
const handleReset = () => {
|
|
||||||
const nameInput = document.querySelector('input[placeholder="请输入文档类型名称"]');
|
|
||||||
if (nameInput) {
|
|
||||||
(nameInput as HTMLInputElement).value = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
// 重置所有筛选条件
|
|
||||||
setSearchParams(new URLSearchParams());
|
|
||||||
};
|
|
||||||
|
|
||||||
// 处理删除文档类型
|
|
||||||
const handleDelete = (id: number) => {
|
|
||||||
// 权限检查
|
|
||||||
if (!canDeleteType) {
|
|
||||||
toastService.warning('您没有删除权限');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查是否正在加载
|
|
||||||
if (fetcher.state === 'submitting') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
messageService.show({
|
|
||||||
title: "确认删除",
|
|
||||||
message: "确定要删除该文档类型吗?此操作不会影响关联的评查点分组,但可能会影响使用该类型的文档评查。",
|
|
||||||
type: "warning",
|
|
||||||
confirmText: "删除",
|
|
||||||
cancelText: "取消",
|
|
||||||
confirmDelay: 4,
|
|
||||||
onConfirm: () => {
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append('id', id.toString());
|
|
||||||
formData.append('intent', 'delete');
|
|
||||||
|
|
||||||
// 使用 useFetcher 提交请求
|
|
||||||
fetcher.submit(formData, { method: 'post' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// 处理编辑文档类型
|
|
||||||
const handleEdit = (id: number) => {
|
|
||||||
navigate(`/document-types/new?id=${id}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 处理分页变更
|
|
||||||
const handlePageChange = (page: number) => {
|
|
||||||
const newParams = new URLSearchParams(searchParams);
|
|
||||||
newParams.set('page', page.toString());
|
|
||||||
setSearchParams(newParams);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 处理每页条数变更
|
|
||||||
const handlePageSizeChange = (size: number) => {
|
|
||||||
const newParams = new URLSearchParams(searchParams);
|
|
||||||
newParams.set('pageSize', size.toString());
|
|
||||||
newParams.set('page', '1');
|
|
||||||
setSearchParams(newParams);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 定义表格列配置
|
|
||||||
const columns = [
|
|
||||||
{
|
|
||||||
title: "文档类型名称",
|
|
||||||
key: "name",
|
|
||||||
width: "220px",
|
|
||||||
render: (_: unknown, record: DocumentTypeUI) => (
|
|
||||||
<div className="flex items-center">
|
|
||||||
<i className="ri-file-text-line text-primary mr-2"></i>
|
|
||||||
<span>{record.name}</span>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "描述",
|
|
||||||
key: "description",
|
|
||||||
width: "260px",
|
|
||||||
render: (_: unknown, record: DocumentTypeUI) => (
|
|
||||||
<div className="text-secondary text-sm truncate max-w-[300px]" title={record.description}>
|
|
||||||
{record.description || '-'}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "入口模块",
|
|
||||||
key: "entry_module",
|
|
||||||
width: "150px",
|
|
||||||
render: (_: unknown, record: DocumentTypeUI) => (
|
|
||||||
<div className="flex items-center">
|
|
||||||
{record.entry_module ? (
|
|
||||||
<span className="entry-module-badge">{record.entry_module.name}</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-gray-400">-</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "关联的评查点分组",
|
|
||||||
key: "groups",
|
|
||||||
render: (_: unknown, record: DocumentTypeUI) => (
|
|
||||||
<div className="groups-container">
|
|
||||||
{record.groups && record.groups.length > 0 ? (
|
|
||||||
record.groups.map(group => (
|
|
||||||
<span key={group.id} className="type-badge">
|
|
||||||
{group.name}
|
|
||||||
</span>
|
|
||||||
))
|
|
||||||
) : (
|
|
||||||
<span className="text-gray-400">-</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "创建时间",
|
|
||||||
key: "created_at",
|
|
||||||
width: "160px",
|
|
||||||
render: (_: unknown, record: DocumentTypeUI) => record.created_at || '-'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "更新时间",
|
|
||||||
key: "updated_at",
|
|
||||||
width: "160px",
|
|
||||||
render: (_: unknown, record: DocumentTypeUI) => record.updated_at || '-'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "操作",
|
|
||||||
key: "operation",
|
|
||||||
width: "160px",
|
|
||||||
render: (_: unknown, record: DocumentTypeUI) => (
|
|
||||||
<div className="operations-cell">
|
|
||||||
{canViewType && (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
className="operation-btn text-primary"
|
|
||||||
onClick={() => handleEdit(record.id)}
|
|
||||||
>
|
|
||||||
<i className={canUpdateType ? "ri-edit-line" : "ri-eye-line"}></i>
|
|
||||||
{canUpdateType ? '编辑' : '查看'}
|
|
||||||
</button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{canDeleteType && (
|
|
||||||
<button
|
|
||||||
className="operation-btn text-error"
|
|
||||||
onClick={() => handleDelete(record.id)}
|
|
||||||
disabled={fetcher.state === 'submitting'}
|
|
||||||
>
|
|
||||||
<i className="ri-delete-bin-line"></i> 删除
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{!canViewType && !canDeleteType && (
|
|
||||||
<span className="text-gray-400">-</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="document-types-page">
|
<div className="document-types-page">
|
||||||
{error && (
|
|
||||||
<div className="alert alert-error mb-4">
|
|
||||||
<p>{error}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 页面头部 */}
|
|
||||||
<div className="page-header">
|
<div className="page-header">
|
||||||
<h2 className="page-title">文档类型管理</h2>
|
<h2 className="page-title">
|
||||||
<div>
|
<i className="ri-file-list-3-line"></i>
|
||||||
{canCreateType && (
|
文档类型管理
|
||||||
<Button
|
</h2>
|
||||||
type="primary"
|
<Button type="primary" icon="ri-add-line" onClick={() => navigate("/document-types/new")}>
|
||||||
icon="ri-add-line"
|
新建文档类型
|
||||||
onClick={() => navigate("/document-types/new")}
|
|
||||||
>
|
|
||||||
新增文档类型
|
|
||||||
</Button>
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
{types.length === 0 ? (
|
||||||
|
<div className="empty-state">
|
||||||
|
<i className="ri-inbox-line"></i>
|
||||||
|
<p>暂无文档类型</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<table className="data-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>编码</th>
|
||||||
|
<th>名称</th>
|
||||||
|
<th>入口模块</th>
|
||||||
|
<th>规则集</th>
|
||||||
|
<th>状态</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{types.map((type) => (
|
||||||
|
<tr key={type.id}>
|
||||||
|
<td><code>{type.code}</code></td>
|
||||||
|
<td>{type.name}</td>
|
||||||
|
<td>{getEntryModuleName(type.entryModuleId)}</td>
|
||||||
|
<td>
|
||||||
|
<span className="tag">{type.ruleSetIds?.length || 0} 个规则集</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={`status-badge ${type.isEnabled ? "enabled" : "disabled"}`}>
|
||||||
|
{type.isEnabled ? "启用" : "禁用"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div className="row-actions">
|
||||||
|
<button
|
||||||
|
className="btn-icon"
|
||||||
|
title="编辑"
|
||||||
|
onClick={() => navigate(`/document-types/new?id=${type.id}`)}
|
||||||
|
>
|
||||||
|
<i className="ri-edit-line"></i>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn-icon text-error"
|
||||||
|
title="删除"
|
||||||
|
onClick={() => handleDelete(type)}
|
||||||
|
>
|
||||||
|
<i className="ri-delete-bin-line"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 搜索栏 */}
|
|
||||||
<FilterPanel
|
|
||||||
className="mb-4"
|
|
||||||
actions={
|
|
||||||
<>
|
|
||||||
<Button
|
|
||||||
type="default"
|
|
||||||
icon="ri-refresh-line"
|
|
||||||
onClick={handleReset}
|
|
||||||
className="mr-2"
|
|
||||||
>
|
|
||||||
重置
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
}
|
|
||||||
noActionDivider={true}
|
|
||||||
>
|
|
||||||
<FilterSelect
|
|
||||||
label="评查点分组"
|
|
||||||
name="group_id"
|
|
||||||
value={searchParams.get('group_id') || ''}
|
|
||||||
options={[
|
|
||||||
...(parentGroups || []).map(group => ({
|
|
||||||
value: group.id.toString(),
|
|
||||||
label: group.name
|
|
||||||
}))
|
|
||||||
]}
|
|
||||||
onChange={handleFilterChange}
|
|
||||||
className="mr-3 w-[20%]"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<SearchFilter
|
|
||||||
label="类型名称"
|
|
||||||
placeholder="请输入文档类型名称"
|
|
||||||
value={name}
|
|
||||||
onSearch={handleNameSearch}
|
|
||||||
className="min-w-[400px]"
|
|
||||||
instantSearch={true}
|
|
||||||
/>
|
|
||||||
|
|
||||||
</FilterPanel>
|
|
||||||
|
|
||||||
{/* 数据表格 */}
|
|
||||||
<Card bodyClassName="px-0 py-0">
|
|
||||||
<Table
|
|
||||||
columns={columns}
|
|
||||||
dataSource={types}
|
|
||||||
rowKey="id"
|
|
||||||
emptyText="暂无文档类型数据"
|
|
||||||
loading={false}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* 分页 */}
|
|
||||||
<div className="px-4 py-3">
|
|
||||||
<Pagination
|
|
||||||
currentPage={currentPage}
|
|
||||||
total={total}
|
|
||||||
pageSize={pageSize}
|
|
||||||
onChange={handlePageChange}
|
|
||||||
onPageSizeChange={handlePageSizeChange}
|
|
||||||
showTotal={true}
|
|
||||||
showPageSizeChanger={true}
|
|
||||||
pageSizeOptions={[10, 20, 50, 100]}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+145
-757
@@ -1,841 +1,229 @@
|
|||||||
import React, { useState, useEffect, useRef } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { Form, useActionData, useLoaderData, useNavigate, useSearchParams } from "@remix-run/react";
|
import { useNavigate, useSearchParams, useLoaderData } from "@remix-run/react";
|
||||||
import { redirect, type MetaFunction, type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/node";
|
import { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
|
||||||
import { Card } from "~/components/ui/Card";
|
import { Card } from "~/components/ui/Card";
|
||||||
import { Button } from "~/components/ui/Button";
|
import { Button } from "~/components/ui/Button";
|
||||||
import documentTypesNewStyles from "~/styles/pages/document-types_new.css?url";
|
import { toastService } from "~/components/ui/Toast";
|
||||||
import { type RuleGroup } from "~/api/evaluation_points/rule-groups";
|
|
||||||
import {
|
import {
|
||||||
getDocumentType,
|
getDocumentType,
|
||||||
createDocumentType,
|
createDocumentType,
|
||||||
updateDocumentType,
|
updateDocumentType,
|
||||||
getEntryModules,
|
getEntryModules,
|
||||||
getRootEvaluationPointGroups_ForDocTypes,
|
getRuleSets,
|
||||||
getPromptTemplateOptions
|
type DocumentType,
|
||||||
|
type DocumentTypeCreateDTO,
|
||||||
|
type DocumentTypeUpdateDTO,
|
||||||
|
type EntryModuleOption,
|
||||||
|
type RuleSetOption,
|
||||||
} from "~/api/document-types/document-types";
|
} from "~/api/document-types/document-types";
|
||||||
import { getEvaluationPointGroupChildren } from "~/api/evaluation_points/rule-groups";
|
import newStyles from "~/styles/pages/document-types_new.css?url";
|
||||||
import { toastService } from "~/components/ui/Toast";
|
|
||||||
import { usePermission } from "~/hooks/usePermission";
|
|
||||||
|
|
||||||
export function links() {
|
export function links() {
|
||||||
return [{ rel: "stylesheet", href: documentTypesNewStyles }];
|
return [{ rel: "stylesheet", href: newStyles }];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const handle = {
|
export const meta: MetaFunction = () => {
|
||||||
breadcrumb: (data:LoaderData) => {
|
return [{ title: "新建/编辑文档类型 - 中国烟草AI合同及卷宗审核系统" }];
|
||||||
if (data.isEdit) {
|
|
||||||
return "编辑文档类型";
|
|
||||||
} else {
|
|
||||||
return "新增文档类型";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
interface LoaderData {
|
interface LoaderData {
|
||||||
isEdit: boolean;
|
entryModules: EntryModuleOption[];
|
||||||
|
ruleSets: RuleSetOption[];
|
||||||
|
editType: DocumentType | null;
|
||||||
|
frontendJWT?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const meta: MetaFunction = ({ location }) => {
|
|
||||||
const isEdit = new URLSearchParams(location.search).has("id");
|
|
||||||
return [
|
|
||||||
{ title: `${isEdit ? "编辑" : "新增"}文档类型 - 中国烟草AI合同及卷宗审核系统` },
|
|
||||||
{ name: "description", content: `${isEdit ? "编辑" : "新增"}文档类型,设置文档类型名称、描述和关联的评查点分组` }
|
|
||||||
];
|
|
||||||
};
|
|
||||||
|
|
||||||
// 定义模板类型
|
|
||||||
const TEMPLATE_TYPES = {
|
|
||||||
LLM_EXTRACTION: "LLM_Extraction",
|
|
||||||
VLM_EXTRACTION: "VLM_Extraction"
|
|
||||||
};
|
|
||||||
|
|
||||||
// 定义动作返回的数据类型
|
|
||||||
interface ActionData {
|
|
||||||
result?: boolean;
|
|
||||||
errors?: {
|
|
||||||
name?: string;
|
|
||||||
groups?: string;
|
|
||||||
general?: string;
|
|
||||||
llmExtractionTemplate?: string;
|
|
||||||
vlmExtractionTemplate?: string;
|
|
||||||
};
|
|
||||||
values?: Record<string, string | string[]>;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// 获取数据
|
|
||||||
export async function loader({ request }: LoaderFunctionArgs) {
|
export async function loader({ request }: LoaderFunctionArgs) {
|
||||||
try {
|
|
||||||
// 获取用户会话信息
|
|
||||||
const { getUserSession } = await import("~/api/login/auth.server");
|
const { getUserSession } = await import("~/api/login/auth.server");
|
||||||
const { frontendJWT } = await getUserSession(request);
|
const { frontendJWT } = await getUserSession(request);
|
||||||
|
|
||||||
const url = new URL(request.url);
|
const url = new URL(request.url);
|
||||||
const id = url.searchParams.get("id");
|
const editId = url.searchParams.get("id");
|
||||||
const isEdit = id ? true : false;
|
|
||||||
|
|
||||||
// 1. 获取一级评查点分组(后续通过点击展开按钮动态加载子分组)
|
const [modulesRes, setsRes] = await Promise.all([
|
||||||
const ruleGroupsResponse = await getRootEvaluationPointGroups_ForDocTypes(frontendJWT);
|
getEntryModules(frontendJWT),
|
||||||
if (ruleGroupsResponse.error) {
|
getRuleSets(frontendJWT),
|
||||||
console.error("获取一级评查点分组失败:", ruleGroupsResponse.error);
|
|
||||||
}
|
|
||||||
const rootGroups = ruleGroupsResponse.error ? [] : ruleGroupsResponse.data || [];
|
|
||||||
|
|
||||||
// 2. 获取入口模块列表
|
|
||||||
const entryModulesResponse = await getEntryModules(frontendJWT);
|
|
||||||
if (entryModulesResponse.error) {
|
|
||||||
console.error("获取入口模块失败:", entryModulesResponse.error);
|
|
||||||
}
|
|
||||||
const entryModules = entryModulesResponse.error ? [] : (entryModulesResponse.data || []);
|
|
||||||
|
|
||||||
// 3. 获取提示词模板(只获取 LLM 和 VLM)
|
|
||||||
const [llmExtractionTemplatesResponse, vlmExtractionTemplatesResponse] =
|
|
||||||
await Promise.all([
|
|
||||||
getPromptTemplateOptions(TEMPLATE_TYPES.LLM_EXTRACTION, frontendJWT),
|
|
||||||
getPromptTemplateOptions(TEMPLATE_TYPES.VLM_EXTRACTION, frontendJWT)
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// 4. 如果是编辑模式,获取文档类型详情
|
let editType: DocumentType | null = null;
|
||||||
let documentType = undefined;
|
if (editId) {
|
||||||
if (id) {
|
const res = await getDocumentType(parseInt(editId), frontendJWT);
|
||||||
const typeResponse = await getDocumentType(id, frontendJWT);
|
editType = res.data || null;
|
||||||
if (typeResponse.data) {
|
|
||||||
documentType = typeResponse.data;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return Response.json({
|
return { entryModules: modulesRes.data || [], ruleSets: setsRes.data || [], editType, frontendJWT };
|
||||||
isEdit,
|
|
||||||
documentType,
|
|
||||||
ruleGroups: rootGroups,
|
|
||||||
entryModules,
|
|
||||||
llmExtractionTemplates: llmExtractionTemplatesResponse.data || [],
|
|
||||||
vlmExtractionTemplates: vlmExtractionTemplatesResponse.data || []
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error("加载数据失败:", error);
|
|
||||||
return Response.json({
|
|
||||||
isEdit: false,
|
|
||||||
documentType: undefined,
|
|
||||||
ruleGroups: [],
|
|
||||||
entryModules: [],
|
|
||||||
llmExtractionTemplates: [],
|
|
||||||
vlmExtractionTemplates: [],
|
|
||||||
error: error || "加载数据失败"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理表单提交
|
|
||||||
export async function action({ request }: ActionFunctionArgs) {
|
|
||||||
const { getUserSession } = await import("~/api/login/auth.server");
|
|
||||||
const { frontendJWT } = await getUserSession(request);
|
|
||||||
|
|
||||||
const formData = await request.formData();
|
|
||||||
const id = formData.get("id") as string | null;
|
|
||||||
const name = formData.get("name") as string;
|
|
||||||
const code = formData.get("code") as string;
|
|
||||||
const description = formData.get("description") as string;
|
|
||||||
const entryModuleId = formData.get("entry_module_id") as string;
|
|
||||||
const llmExtractionTemplateId = formData.get("llm_extraction_template") as string;
|
|
||||||
const vlmExtractionTemplateId = formData.get("vlm_extraction_template") as string;
|
|
||||||
|
|
||||||
// 获取选中的评查点分组ID列表
|
|
||||||
const selectedGroups = formData.getAll("checkpoint_group_ids") as string[];
|
|
||||||
|
|
||||||
// 表单验证
|
|
||||||
const errors: ActionData["errors"] = {};
|
|
||||||
|
|
||||||
// 收集所有错误
|
|
||||||
if (!name || name.trim() === "") {
|
|
||||||
errors.name = "文档类型名称不能为空";
|
|
||||||
}
|
|
||||||
|
|
||||||
// 验证:如果入口模块为"合同管理",文档类型名称必须包含"合同"
|
|
||||||
if (entryModuleId && name) {
|
|
||||||
// 获取入口模块列表以验证模块名称
|
|
||||||
const entryModulesResponse = await getEntryModules(frontendJWT);
|
|
||||||
if (!entryModulesResponse.error && entryModulesResponse.data) {
|
|
||||||
const selectedModule = entryModulesResponse.data.find(
|
|
||||||
(m: { id: number; name: string }) => m.id.toString() === entryModuleId
|
|
||||||
);
|
|
||||||
if (selectedModule?.name === '合同管理' && !name.includes('合同')) {
|
|
||||||
errors.name = '入口模块为"合同管理"时,文档类型名称必须包含"合同"';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (selectedGroups.length === 0) {
|
|
||||||
errors.groups = "请至少选择一个关联的评查点分组";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!llmExtractionTemplateId) {
|
|
||||||
errors.llmExtractionTemplate = "请选择llm抽取提示词模板";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!vlmExtractionTemplateId) {
|
|
||||||
errors.vlmExtractionTemplate = "请选择vlm抽取提示词模板";
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果有错误,返回错误信息
|
|
||||||
if (Object.keys(errors).length > 0) {
|
|
||||||
return Response.json({ errors, result: false });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 构建文档类型数据 - group_ids 转换为 number[]
|
|
||||||
const documentTypeData = {
|
|
||||||
name,
|
|
||||||
code: code || null,
|
|
||||||
description,
|
|
||||||
group_ids: selectedGroups.map(id => parseInt(id, 10)),
|
|
||||||
entry_module_id: entryModuleId ? parseInt(entryModuleId) : null,
|
|
||||||
llm_extraction_template_id: llmExtractionTemplateId ? parseInt(llmExtractionTemplateId) : null,
|
|
||||||
vlm_extraction_template_id: vlmExtractionTemplateId ? parseInt(vlmExtractionTemplateId) : null
|
|
||||||
};
|
|
||||||
|
|
||||||
// 调用API创建或更新文档类型
|
|
||||||
let response;
|
|
||||||
if (id) {
|
|
||||||
// 更新文档类型
|
|
||||||
response = await updateDocumentType(id, {
|
|
||||||
...documentTypeData,
|
|
||||||
id: parseInt(id),
|
|
||||||
}, frontendJWT);
|
|
||||||
} else {
|
|
||||||
// 创建新文档类型
|
|
||||||
response = await createDocumentType(documentTypeData, frontendJWT);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response.error) {
|
|
||||||
console.error("保存/更新文档类型失败:", response.error);
|
|
||||||
throw new Error(response.error);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 操作成功,重定向到列表页
|
|
||||||
return redirect("/document-types");
|
|
||||||
} catch (error) {
|
|
||||||
console.error("保存文档类型失败:", error);
|
|
||||||
return Response.json({
|
|
||||||
result: false,
|
|
||||||
errors: {
|
|
||||||
general: error instanceof Error ? error.message : "保存文档类型失败"
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function DocumentTypeNew() {
|
export default function DocumentTypeNew() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [searchParams] = useSearchParams();
|
const loaderData = useLoaderData<LoaderData>();
|
||||||
const isEditMode = searchParams.has("id");
|
const editType = loaderData.editType;
|
||||||
|
const isEdit = !!editType;
|
||||||
|
|
||||||
const {
|
const [code, setCode] = useState("");
|
||||||
documentType,
|
const [name, setName] = useState("");
|
||||||
ruleGroups,
|
const [description, setDescription] = useState("");
|
||||||
entryModules,
|
const [entryModuleId, setEntryModuleId] = useState<number | null>(null);
|
||||||
llmExtractionTemplates,
|
const [selectedRuleSetIds, setSelectedRuleSetIds] = useState<number[]>([]);
|
||||||
vlmExtractionTemplates
|
const [saving, setSaving] = useState(false);
|
||||||
} = useLoaderData<typeof loader>();
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
const actionData = useActionData<ActionData>();
|
|
||||||
|
|
||||||
// 权限控制
|
|
||||||
const { canCreate, canUpdate } = usePermission();
|
|
||||||
const canCreateType = canCreate('document_type');
|
|
||||||
const canUpdateType = canUpdate('document_type');
|
|
||||||
|
|
||||||
const urlMode = searchParams.get('mode');
|
|
||||||
const isViewMode = urlMode === 'view';
|
|
||||||
|
|
||||||
const hasEditPermission = isEditMode ? canUpdateType : canCreateType;
|
|
||||||
const isReadOnly = isViewMode || !hasEditPermission;
|
|
||||||
|
|
||||||
// 状态管理
|
|
||||||
const [formData, setFormData] = useState({
|
|
||||||
id: documentType?.id || "",
|
|
||||||
name: documentType?.name || "",
|
|
||||||
code: documentType?.code || "",
|
|
||||||
description: documentType?.description || "",
|
|
||||||
entryModuleId: documentType?.entry_module?.id?.toString() || "",
|
|
||||||
llmExtractionTemplateId: documentType?.llm_extraction_template_id?.toString() || "",
|
|
||||||
vlmExtractionTemplateId: documentType?.vlm_extraction_template_id?.toString() || "",
|
|
||||||
selectedGroups: documentType?.groups?.map((g: { id: string | number }) => g.id.toString()) || []
|
|
||||||
});
|
|
||||||
|
|
||||||
// 添加本地验证错误状态
|
|
||||||
const [formErrors, setFormErrors] = useState<ActionData["errors"]>({} as ActionData["errors"]);
|
|
||||||
|
|
||||||
// 表单引用
|
|
||||||
const formRef = useRef<HTMLFormElement>(null);
|
|
||||||
|
|
||||||
// 字段是否被触摸过(用于确定何时显示错误)
|
|
||||||
const [touchedFields, setTouchedFields] = useState({
|
|
||||||
name: false,
|
|
||||||
llmExtractionTemplate: false,
|
|
||||||
vlmExtractionTemplate: false,
|
|
||||||
groups: false
|
|
||||||
});
|
|
||||||
|
|
||||||
// 客户端调试信息ruleGroups
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.log('返回的评查点分组数据',ruleGroups)
|
if (editType) {
|
||||||
}, [ruleGroups])
|
setCode(editType.code || "");
|
||||||
|
setName(editType.name || "");
|
||||||
// 新增模式下,设置模板的默认值(选择第一个选项)
|
setDescription(editType.description || "");
|
||||||
useEffect(() => {
|
setEntryModuleId(editType.entryModuleId);
|
||||||
if (!isEditMode) {
|
setSelectedRuleSetIds(editType.ruleSetIds || []);
|
||||||
setFormData(prev => ({
|
|
||||||
...prev,
|
|
||||||
llmExtractionTemplateId: prev.llmExtractionTemplateId || (llmExtractionTemplates[0]?.id?.toString() || ""),
|
|
||||||
vlmExtractionTemplateId: prev.vlmExtractionTemplateId || (vlmExtractionTemplates[0]?.id?.toString() || "")
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
}, [isEditMode, llmExtractionTemplates, vlmExtractionTemplates]);
|
}, [editType]);
|
||||||
|
|
||||||
// 从actionData初始化本地错误
|
const validate = (): boolean => {
|
||||||
useEffect(() => {
|
const errs: Record<string, string> = {};
|
||||||
if (!actionData?.result) {
|
if (!code.trim()) errs.code = "编码不能为空";
|
||||||
setFormErrors(actionData?.errors);
|
else if (!/^[a-zA-Z][a-zA-Z0-9_.]*$/.test(code.trim())) errs.code = "编码格式:字母开头,可含字母数字._";
|
||||||
if (actionData?.errors?.general) {
|
if (!name.trim()) errs.name = "名称不能为空";
|
||||||
toastService.error(actionData?.errors?.general || "保存文档类型失败");
|
setErrors(errs);
|
||||||
}
|
return Object.keys(errs).length === 0;
|
||||||
}
|
|
||||||
}, [actionData]);
|
|
||||||
|
|
||||||
// 分组展开状态
|
|
||||||
const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({});
|
|
||||||
|
|
||||||
// 动态加载的子分组数据(groupId -> children[])
|
|
||||||
const [groupChildrenMap, setGroupChildrenMap] = useState<Record<string, RuleGroup[]>>({});
|
|
||||||
|
|
||||||
// 子分组加载状态
|
|
||||||
const [loadingChildren, setLoadingChildren] = useState<Record<string, boolean>>({});
|
|
||||||
|
|
||||||
// 当文档类型数据加载完成时更新表单
|
|
||||||
useEffect(() => {
|
|
||||||
if (documentType) {
|
|
||||||
console.log('documentType', documentType)
|
|
||||||
setFormData({
|
|
||||||
id: documentType.id,
|
|
||||||
name: documentType.name,
|
|
||||||
code: documentType.code || "",
|
|
||||||
description: documentType.description,
|
|
||||||
entryModuleId: documentType.entry_module?.id?.toString() || "",
|
|
||||||
llmExtractionTemplateId: documentType.llm_extraction_template_id?.toString() || "",
|
|
||||||
vlmExtractionTemplateId: documentType.vlm_extraction_template_id?.toString() || "",
|
|
||||||
selectedGroups: documentType.groups.map((g: { id: string | number }) => g.id.toString())
|
|
||||||
});
|
|
||||||
|
|
||||||
// 初始化展开状态 - 如果选中的是一级分组,需要加载子分组并展开
|
|
||||||
const loadInitialChildren = async () => {
|
|
||||||
const newExpandedGroups: Record<string, boolean> = {};
|
|
||||||
const newChildrenMap: Record<string, RuleGroup[]> = {};
|
|
||||||
|
|
||||||
// 获取 frontendJWT
|
|
||||||
let frontendJWT: string | undefined = undefined;
|
|
||||||
if (typeof window !== 'undefined') {
|
|
||||||
const userInfoStr = localStorage.getItem('user_info');
|
|
||||||
if (userInfoStr) {
|
|
||||||
try {
|
|
||||||
const userInfo = JSON.parse(userInfoStr);
|
|
||||||
frontendJWT = userInfo.frontendJWT;
|
|
||||||
} catch (e) {
|
|
||||||
console.error('解析用户信息失败:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 遍历所有一级分组,检查是否被选中
|
|
||||||
for (const parentGroup of ruleGroups) {
|
|
||||||
const isParentSelected = documentType.groups.some((g: { id: string | number }) =>
|
|
||||||
g.id.toString() === parentGroup.id.toString()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isParentSelected) {
|
|
||||||
// 标记为展开
|
|
||||||
newExpandedGroups[parentGroup.id] = true;
|
|
||||||
|
|
||||||
// 加载子分组
|
|
||||||
try {
|
|
||||||
const response = await getEvaluationPointGroupChildren(
|
|
||||||
parentGroup.id,
|
|
||||||
{ pageSize: 1000 },
|
|
||||||
frontendJWT
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!response.error && response.data) {
|
|
||||||
newChildrenMap[parentGroup.id] = response.data;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`加载分组 ${parentGroup.id} 的子分组失败:`, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setExpandedGroups(newExpandedGroups);
|
|
||||||
setGroupChildrenMap(newChildrenMap);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
loadInitialChildren();
|
const toggleRuleSet = (id: number) => {
|
||||||
}
|
setSelectedRuleSetIds((prev) =>
|
||||||
}, [documentType, ruleGroups]);
|
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
|
||||||
|
);
|
||||||
// 验证表单字段
|
|
||||||
const validateField = (field: string, value: string | string[], allFormData?: typeof formData): string => {
|
|
||||||
switch (field) {
|
|
||||||
case 'name':
|
|
||||||
if (!value || (typeof value === 'string' && value.trim() === "")) {
|
|
||||||
return "文档类型名称不能为空";
|
|
||||||
}
|
|
||||||
// 检查入口模块是否为"合同管理",如果是则名称必须包含"合同"
|
|
||||||
const currentEntryModuleId = allFormData?.entryModuleId || formData.entryModuleId;
|
|
||||||
const selectedModule = entryModules.find((m: { id: number; name: string }) => m.id.toString() === currentEntryModuleId);
|
|
||||||
if (selectedModule?.name === '合同管理' && typeof value === 'string' && !value.includes('合同')) {
|
|
||||||
return '入口模块为"合同管理"时,文档类型名称必须包含"合同"';
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
case 'llmExtractionTemplate':
|
|
||||||
return !value || (typeof value === 'string' && value.trim() === "") ? "请选择llm抽取提示词模板" : "";
|
|
||||||
case 'vlmExtractionTemplate':
|
|
||||||
return !value || (typeof value === 'string' && value.trim() === "") ? "请选择vlm抽取提示词模板" : "";
|
|
||||||
case 'groups':
|
|
||||||
return Array.isArray(value) && value.length === 0 ? "请至少选择一个关联的评查点分组" : "";
|
|
||||||
default:
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 处理分组勾选
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
const handleGroupCheckChange = (
|
e.preventDefault();
|
||||||
groupId: string,
|
if (!validate()) return;
|
||||||
isChecked: boolean
|
|
||||||
) => {
|
|
||||||
// 多选模式:添加或移除选中的分组
|
|
||||||
let newSelectedGroups: string[] = [];
|
|
||||||
|
|
||||||
if (isChecked) {
|
setSaving(true);
|
||||||
// 添加当前选中的分组(避免重复)
|
try {
|
||||||
newSelectedGroups = [...formData.selectedGroups, groupId];
|
if (isEdit && editType) {
|
||||||
|
const dto: DocumentTypeUpdateDTO = {
|
||||||
|
name: name.trim(),
|
||||||
|
description: description.trim(),
|
||||||
|
entryModuleId,
|
||||||
|
ruleSetIds: selectedRuleSetIds,
|
||||||
|
};
|
||||||
|
const res = await updateDocumentType(editType.id, dto, loaderData.frontendJWT ?? undefined);
|
||||||
|
if (res.error) { toastService.error(res.error); return; }
|
||||||
|
toastService.success("文档类型已更新");
|
||||||
} else {
|
} else {
|
||||||
// 移除取消选中的分组
|
const dto: DocumentTypeCreateDTO = {
|
||||||
newSelectedGroups = formData.selectedGroups.filter(id => id !== groupId);
|
code: code.trim(),
|
||||||
}
|
name: name.trim(),
|
||||||
|
description: description.trim(),
|
||||||
setFormData(prev => ({ ...prev, selectedGroups: newSelectedGroups }));
|
entryModuleId,
|
||||||
|
ruleSetIds: selectedRuleSetIds,
|
||||||
// 标记字段为已触摸
|
|
||||||
setTouchedFields(prev => ({...prev, groups: true}));
|
|
||||||
|
|
||||||
// 实时验证
|
|
||||||
const error = validateField('groups', newSelectedGroups);
|
|
||||||
setFormErrors(prev => ({...prev, groups: error}));
|
|
||||||
};
|
};
|
||||||
|
const res = await createDocumentType(dto, loaderData.frontendJWT ?? undefined);
|
||||||
// 修复展开/折叠功能 - 动态加载子分组
|
if (res.error) { toastService.error(res.error); return; }
|
||||||
const handleGroupExpand = async (groupId: string, event: React.MouseEvent) => {
|
toastService.success("文档类型已创建");
|
||||||
// 阻止事件冒泡,避免触发checkbox选中
|
|
||||||
event.stopPropagation();
|
|
||||||
|
|
||||||
const isCurrentlyExpanded = expandedGroups[groupId];
|
|
||||||
|
|
||||||
// 如果当前是折叠状态,准备展开
|
|
||||||
if (!isCurrentlyExpanded) {
|
|
||||||
// 检查是否已经加载过子分组
|
|
||||||
if (!groupChildrenMap[groupId]) {
|
|
||||||
// 还未加载,开始加载
|
|
||||||
setLoadingChildren(prev => ({ ...prev, [groupId]: true }));
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 获取用户 token
|
|
||||||
let frontendJWT: string | undefined = undefined;
|
|
||||||
if (typeof window !== 'undefined') {
|
|
||||||
const userInfoStr = localStorage.getItem('user_info');
|
|
||||||
if (userInfoStr) {
|
|
||||||
try {
|
|
||||||
const userInfo = JSON.parse(userInfoStr);
|
|
||||||
frontendJWT = userInfo.frontendJWT;
|
|
||||||
} catch (e) {
|
|
||||||
console.error('解析用户信息失败:', e);
|
|
||||||
}
|
}
|
||||||
}
|
navigate("/document-types");
|
||||||
}
|
|
||||||
|
|
||||||
// 调用 API 获取子分组
|
|
||||||
const response = await getEvaluationPointGroupChildren(
|
|
||||||
groupId,
|
|
||||||
{ pageSize: 1000 }, // 获取所有子分组
|
|
||||||
frontendJWT
|
|
||||||
);
|
|
||||||
|
|
||||||
if (response.error) {
|
|
||||||
console.error('获取子分组失败:', response.error);
|
|
||||||
toastService.error('获取子分组失败');
|
|
||||||
setLoadingChildren(prev => ({ ...prev, [groupId]: false }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 保存子分组数据
|
|
||||||
setGroupChildrenMap(prev => ({
|
|
||||||
...prev,
|
|
||||||
[groupId]: response.data || []
|
|
||||||
}));
|
|
||||||
|
|
||||||
setLoadingChildren(prev => ({ ...prev, [groupId]: false }));
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('获取子分组异常:', error);
|
toastService.error(error instanceof Error ? error.message : "保存失败");
|
||||||
toastService.error('获取子分组失败');
|
} finally {
|
||||||
setLoadingChildren(prev => ({ ...prev, [groupId]: false }));
|
setSaving(false);
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 切换展开/折叠状态
|
|
||||||
setExpandedGroups(prev => ({
|
|
||||||
...prev,
|
|
||||||
[groupId]: !isCurrentlyExpanded
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
// 处理表单输入变化
|
|
||||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
|
|
||||||
// 根据name属性映射到对应的formData字段
|
|
||||||
let fieldName = name;
|
|
||||||
|
|
||||||
if (name === 'llm_extraction_template') {
|
|
||||||
fieldName = 'llmExtractionTemplateId';
|
|
||||||
setTouchedFields(prev => ({...prev, llmExtractionTemplate: true}));
|
|
||||||
} else if (name === 'vlm_extraction_template') {
|
|
||||||
fieldName = 'vlmExtractionTemplateId';
|
|
||||||
setTouchedFields(prev => ({...prev, vlmExtractionTemplate: true}));
|
|
||||||
} else if (name === 'entry_module_id') {
|
|
||||||
fieldName = 'entryModuleId';
|
|
||||||
} else if (name === 'name') {
|
|
||||||
setTouchedFields(prev => ({...prev, name: true}));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 先更新 formData
|
|
||||||
const updatedFormData = { ...formData, [fieldName]: value };
|
|
||||||
setFormData(updatedFormData);
|
|
||||||
|
|
||||||
// 实时验证
|
|
||||||
if (name === 'name') {
|
|
||||||
const error = validateField(name, value, updatedFormData);
|
|
||||||
setFormErrors(prev => ({...prev, name: error}));
|
|
||||||
} else if (name === 'llm_extraction_template') {
|
|
||||||
const error = validateField('llmExtractionTemplate', value);
|
|
||||||
setFormErrors(prev => ({...prev, llmExtractionTemplate: error}));
|
|
||||||
} else if (name === 'vlm_extraction_template') {
|
|
||||||
const error = validateField('vlmExtractionTemplate', value);
|
|
||||||
setFormErrors(prev => ({...prev, vlmExtractionTemplate: error}));
|
|
||||||
} else if (name === 'entry_module_id') {
|
|
||||||
// 入口模块变更时,重新验证名称字段(如果名称已被触摸过)
|
|
||||||
if (touchedFields.name) {
|
|
||||||
const nameError = validateField('name', updatedFormData.name, updatedFormData);
|
|
||||||
setFormErrors(prev => ({...prev, name: nameError}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// 处理表单提交前验证
|
|
||||||
const handleBeforeSubmit = (e: React.FormEvent) => {
|
|
||||||
// 权限检查
|
|
||||||
if (isEditMode && !canUpdateType) {
|
|
||||||
toastService.warning('您没有修改权限,无法保存更改');
|
|
||||||
e.preventDefault();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!isEditMode && !canCreateType) {
|
|
||||||
toastService.warning('您没有创建权限,无法新增文档类型');
|
|
||||||
e.preventDefault();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 标记所有字段为已触摸
|
|
||||||
setTouchedFields({
|
|
||||||
name: true,
|
|
||||||
llmExtractionTemplate: true,
|
|
||||||
vlmExtractionTemplate: true,
|
|
||||||
groups: true
|
|
||||||
});
|
|
||||||
|
|
||||||
// 验证所有字段
|
|
||||||
const errors = {
|
|
||||||
name: validateField('name', formData.name, formData),
|
|
||||||
llmExtractionTemplate: validateField('llmExtractionTemplate', formData.llmExtractionTemplateId),
|
|
||||||
vlmExtractionTemplate: validateField('vlmExtractionTemplate', formData.vlmExtractionTemplateId),
|
|
||||||
groups: validateField('groups', formData.selectedGroups)
|
|
||||||
};
|
|
||||||
|
|
||||||
setFormErrors(errors);
|
|
||||||
|
|
||||||
// 如果有错误,阻止提交
|
|
||||||
if (errors.name || errors.llmExtractionTemplate || errors.vlmExtractionTemplate || errors.groups) {
|
|
||||||
e.preventDefault();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="document-type-new-page">
|
<div className="document-type-new-page">
|
||||||
{/* 页面头部 */}
|
|
||||||
<div className="page-header">
|
<div className="page-header">
|
||||||
<h2 className="page-title">{isEditMode ? (isReadOnly ? "查看文档类型" : "编辑文档类型") : "新增文档类型"}</h2>
|
<h2 className="page-title">
|
||||||
<div>
|
<i className="ri-file-list-3-line"></i>
|
||||||
<Button
|
{isEdit ? `编辑文档类型 — ${editType?.code}` : "新建文档类型"}
|
||||||
type="default"
|
</h2>
|
||||||
icon="ri-arrow-left-line"
|
|
||||||
onClick={() => navigate("/document-types")}
|
|
||||||
className="mr-2"
|
|
||||||
>
|
|
||||||
返回
|
|
||||||
</Button>
|
|
||||||
{!isReadOnly && (
|
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
icon="ri-save-line"
|
|
||||||
form="type-form"
|
|
||||||
>
|
|
||||||
保存
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 表单内容 */}
|
|
||||||
<Card>
|
<Card>
|
||||||
<Form id="type-form" method="post" noValidate ref={formRef} onSubmit={handleBeforeSubmit}>
|
<form className="doc-type-form" onSubmit={handleSubmit}>
|
||||||
{/* 如果是编辑模式,添加隐藏的ID字段 */}
|
<div className="form-row">
|
||||||
{formData.id && <input type="hidden" name="id" value={formData.id} />}
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-6">
|
|
||||||
{/* 错误提示 */}
|
|
||||||
{formErrors?.general && (
|
|
||||||
<div className="error-message general-error">
|
|
||||||
<i className="ri-error-warning-line"></i>
|
|
||||||
{formErrors.general}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 文档类型名称 */}
|
|
||||||
<div className="form-group">
|
<div className="form-group">
|
||||||
<label htmlFor="type-name" className="form-label">
|
<label className="required">类型编码</label>
|
||||||
文档类型名称 <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
id="type-name"
|
className={`form-input ${errors.code ? "error" : ""}`}
|
||||||
name="name"
|
placeholder="如: contract.sale"
|
||||||
className={`form-input ${touchedFields.name && formErrors?.name ? 'input-error' : ''}`}
|
value={code}
|
||||||
placeholder="请输入文档类型名称"
|
onChange={(e) => { setCode(e.target.value); setErrors({ ...errors, code: "" }); }}
|
||||||
value={formData.name}
|
disabled={isEdit}
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
readOnly={isReadOnly}
|
|
||||||
/>
|
/>
|
||||||
{touchedFields.name && formErrors?.name && (
|
{errors.code && <span className="form-error">{errors.code}</span>}
|
||||||
<div className="error-message">{formErrors.name}</div>
|
{isEdit && <span className="form-hint">编码创建后不可修改</span>}
|
||||||
)}
|
|
||||||
<div className="form-tip">例如:销售合同、采购合同、专卖许可证等</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 文档类型编码 */}
|
|
||||||
<div className="form-group">
|
<div className="form-group">
|
||||||
<label htmlFor="type-code" className="form-label">
|
<label className="required">类型名称</label>
|
||||||
文档类型编码
|
|
||||||
</label>
|
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
id="type-code"
|
className={`form-input ${errors.name ? "error" : ""}`}
|
||||||
name="code"
|
placeholder="如: 通用买卖合同"
|
||||||
className="form-input"
|
value={name}
|
||||||
placeholder="请输入文档类型编码"
|
onChange={(e) => { setName(e.target.value); setErrors({ ...errors, name: "" }); }}
|
||||||
value={formData.code}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
readOnly={isReadOnly}
|
|
||||||
/>
|
/>
|
||||||
<div className="form-tip">用于系统内部识别的唯一编码(可选)</div>
|
{errors.name && <span className="form-error">{errors.name}</span>}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 入口模块 */}
|
|
||||||
<div className="form-group">
|
<div className="form-group">
|
||||||
<label htmlFor="entry-module" className="form-label">
|
<label>描述</label>
|
||||||
入口模块
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
id="entry-module"
|
|
||||||
name="entry_module_id"
|
|
||||||
className="form-select"
|
|
||||||
value={formData.entryModuleId}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
disabled={isReadOnly}
|
|
||||||
>
|
|
||||||
<option value="">无</option>
|
|
||||||
{entryModules.map((module: { id: number; name: string }) => (
|
|
||||||
<option key={module.id} value={module.id}>
|
|
||||||
{module.name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<div className="form-tip">选择此文档类型对应的入口模块(可选)</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 类型描述 */}
|
|
||||||
<div className="form-group">
|
|
||||||
<label htmlFor="type-description" className="form-label">类型描述</label>
|
|
||||||
<textarea
|
<textarea
|
||||||
id="type-description"
|
|
||||||
name="description"
|
|
||||||
className="form-textarea"
|
className="form-textarea"
|
||||||
placeholder="请输入类型描述,介绍此类型文档的用途和特点"
|
placeholder="文档类型描述"
|
||||||
value={formData.description}
|
value={description}
|
||||||
onChange={handleInputChange}
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
rows={3}
|
rows={3}
|
||||||
readOnly={isReadOnly}
|
/>
|
||||||
></textarea>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 提示词模板选择区域 */}
|
|
||||||
<div className="form-group flex space-x-4">
|
|
||||||
{/* llm抽取提示词模板 */}
|
|
||||||
<div className="w-full">
|
|
||||||
<label htmlFor="llm-extraction-template" className="form-label">llm抽取提示词模板 <span className="text-red-500">*</span></label>
|
|
||||||
<select
|
|
||||||
id="llm-extraction-template"
|
|
||||||
name="llm_extraction_template"
|
|
||||||
className={`form-select ${touchedFields.llmExtractionTemplate && formErrors?.llmExtractionTemplate ? 'input-error' : ''}`}
|
|
||||||
value={formData.llmExtractionTemplateId}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
disabled={isReadOnly}
|
|
||||||
>
|
|
||||||
{/* <option value="">请选择llm抽取提示词模板</option> */}
|
|
||||||
{llmExtractionTemplates.map((template: { id: number; template_name: string }) => (
|
|
||||||
<option key={template.id} value={template.id}>
|
|
||||||
{template.template_name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
{touchedFields.llmExtractionTemplate && formErrors?.llmExtractionTemplate && (
|
|
||||||
<div className="error-message">{formErrors.llmExtractionTemplate}</div>
|
|
||||||
)}
|
|
||||||
<div className="form-tip">选择用于从此类文档中抽取信息的llm提示词模板</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* vlm抽取提示词模板 */}
|
|
||||||
<div className="w-full">
|
|
||||||
<label htmlFor="vlm-extraction-template" className="form-label">vlm抽取提示词模板 <span className="text-red-500">*</span></label>
|
|
||||||
<select
|
|
||||||
id="vlm-extraction-template"
|
|
||||||
name="vlm_extraction_template"
|
|
||||||
className={`form-select ${touchedFields.vlmExtractionTemplate && formErrors?.vlmExtractionTemplate ? 'input-error' : ''}`}
|
|
||||||
value={formData.vlmExtractionTemplateId}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
disabled={isReadOnly}
|
|
||||||
>
|
|
||||||
{/* <option value="">请选择vlm抽取提示词模板</option> */}
|
|
||||||
{vlmExtractionTemplates.map((template: { id: number; template_name: string }) => (
|
|
||||||
<option key={template.id} value={template.id}>
|
|
||||||
{template.template_name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
{touchedFields.vlmExtractionTemplate && formErrors?.vlmExtractionTemplate && (
|
|
||||||
<div className="error-message">{formErrors.vlmExtractionTemplate}</div>
|
|
||||||
)}
|
|
||||||
<div className="form-tip">选择用于从此类文档中抽取信息的vlm提示词模板</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 关联评查点分组 */}
|
|
||||||
<div className="form-group">
|
<div className="form-group">
|
||||||
<fieldset>
|
<label>入口模块</label>
|
||||||
<legend className="form-label">
|
<select
|
||||||
关联评查点分组 <span className="text-red-500">*</span>
|
className="form-select"
|
||||||
</legend>
|
value={entryModuleId ?? ""}
|
||||||
<div
|
onChange={(e) => setEntryModuleId(e.target.value ? parseInt(e.target.value) : null)}
|
||||||
className={`checkbox-group ${touchedFields.groups && formErrors?.groups ? 'group-error' : ''}`}
|
|
||||||
aria-labelledby="checkpoint-groups-label"
|
|
||||||
role="group"
|
|
||||||
>
|
>
|
||||||
{ruleGroups.map((group: RuleGroup) => (
|
<option value="">不关联</option>
|
||||||
<React.Fragment key={group.id}>
|
{loaderData.entryModules.map((m) => (
|
||||||
{/* 父分组 */}
|
<option key={m.id} value={m.id}>{m.name}</option>
|
||||||
<div
|
))}
|
||||||
className={`checkbox-item parent-checkbox-item ${formData.selectedGroups.includes(group.id) ? 'checked' : ''}`}
|
</select>
|
||||||
>
|
</div>
|
||||||
<button
|
|
||||||
type="button"
|
<div className="form-group">
|
||||||
className="expand-icon"
|
<label>关联规则集</label>
|
||||||
onClick={(e) => handleGroupExpand(group.id, e)}
|
<span className="form-hint">勾选后,该文档类型上传时会自动加载对应规则集执行评查</span>
|
||||||
aria-label={`${expandedGroups[group.id] ? '收起' : '展开'}${group.name}分组`}
|
<div className="rule-set-checklist">
|
||||||
disabled={isReadOnly}
|
{loaderData.ruleSets.length === 0 ? (
|
||||||
>
|
<p className="form-hint">暂无可选规则集</p>
|
||||||
<i className={`ri-arrow-${expandedGroups[group.id] ? 'down' : 'right'}-s-line text-primary`}></i>
|
) : (
|
||||||
</button>
|
loaderData.ruleSets.map((rs) => (
|
||||||
|
<label key={rs.id} className={`rule-set-item ${selectedRuleSetIds.includes(rs.id) ? "checked" : ""}`}>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
id={`group-${group.id}`}
|
checked={selectedRuleSetIds.includes(rs.id)}
|
||||||
name="checkpoint_group_ids"
|
onChange={() => toggleRuleSet(rs.id)}
|
||||||
value={group.id}
|
|
||||||
checked={formData.selectedGroups.includes(group.id)}
|
|
||||||
onChange={(e) => handleGroupCheckChange(group.id, e.target.checked)}
|
|
||||||
className="checkbox-input"
|
|
||||||
disabled={isReadOnly}
|
|
||||||
/>
|
/>
|
||||||
<label
|
<span className="rule-set-name">{rs.ruleName}</span>
|
||||||
htmlFor={`group-${group.id}`}
|
<span className="rule-set-type">{rs.ruleType}</span>
|
||||||
className="checkbox-label"
|
<span className={`rule-set-status ${rs.status}`}>{rs.status}</span>
|
||||||
>
|
|
||||||
{group.name}
|
|
||||||
<span className="group-badge parent-badge">一级分组</span>
|
|
||||||
</label>
|
</label>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 子分组 - 动态加载并展示 */}
|
|
||||||
{expandedGroups[group.id] && (
|
|
||||||
<>
|
|
||||||
{loadingChildren[group.id] ? (
|
|
||||||
<div
|
|
||||||
className="checkbox-item child-checkbox-item"
|
|
||||||
style={{ paddingLeft: '2.5rem', opacity: 0.9 }}
|
|
||||||
>
|
|
||||||
<i className="ri-loader-4-line spin" style={{ marginRight: '8px', color: '#9ca3af' }}></i>
|
|
||||||
<span className="checkbox-label" style={{ color: '#9ca3af' }}>
|
|
||||||
加载中...
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
groupChildrenMap[group.id]?.map((child: RuleGroup) => (
|
|
||||||
<div
|
|
||||||
key={child.id}
|
|
||||||
className="checkbox-item child-checkbox-item"
|
|
||||||
style={{ paddingLeft: '2.5rem', opacity: 0.9 }}
|
|
||||||
>
|
|
||||||
<i className="ri-subtract-line" style={{ marginRight: '8px', color: '#9ca3af' }}></i>
|
|
||||||
<span className="checkbox-label">
|
|
||||||
{child.name}
|
|
||||||
<span className="group-badge child-badge">二级分组</span>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</React.Fragment>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
{touchedFields.groups && formErrors?.groups && (
|
|
||||||
<div className="error-message">{formErrors.groups}</div>
|
|
||||||
)}
|
|
||||||
<div className="form-tip">选择与此文档类型关联的评查点分组,文档上传后将应用这些分组中的评查点进行审核</div>
|
|
||||||
</fieldset>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Form>
|
|
||||||
|
<div className="form-actions">
|
||||||
|
<Button type="default" onClick={() => navigate("/document-types")} disabled={saving}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" onClick={handleSubmit} disabled={saving}>
|
||||||
|
{saving ? "保存中..." : isEdit ? "保存修改" : "创建"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user