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 响应中提取数据
+99 -449
View File
@@ -1,502 +1,152 @@
import { useState, useEffect, useRef } from "react";
import { useSearchParams, useNavigate, useLoaderData, useFetcher, useRevalidator } from "@remix-run/react";
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { Table } from "~/components/ui/Table";
import { useState, useEffect } from "react";
import { useNavigate, useLoaderData } from "@remix-run/react";
import { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { Card } from "~/components/ui/Card";
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 { messageService } from "~/components/ui/MessageModal";
import { usePermission } from "~/hooks/usePermission";
import {
getDocumentTypes,
deleteDocumentType,
type DocumentTypeUI,
type DocumentTypeSearchParams,
type DocumentTypeGroup,
getParentEvaluationPointGroups
getEntryModules,
type DocumentType,
type EntryModuleOption,
} from "~/api/document-types/document-types";
import documentTypesStyles from "~/styles/pages/document-types_index.css?url";
// 引入CSS样式
export function links() {
return [
{ rel: "stylesheet", href: documentTypesStyles }
];
return [{ rel: "stylesheet", href: documentTypesStyles }];
}
// 页面元数据
export const meta: MetaFunction = () => {
return [
{ title: "文档类型管理 - 中国烟草AI合同及卷宗审核系统" },
{ name: "description", content: "管理文档类型,包括查看、编辑和删除文档类型" },
{ name: "description", content: "管理文档类型及其规则集绑定" },
];
};
// 定义加载器返回的数据类型
interface LoaderData {
types: DocumentTypeUI[];
total: number;
pageSize: number;
currentPage: number;
error?: string;
parentGroups: DocumentTypeGroup[];
types: DocumentType[];
entryModules: EntryModuleOption[];
frontendJWT?: string | null;
}
// 定义 action 返回的数据类型
interface ActionResponse {
success?: boolean;
error?: string;
}
// 加载函数 - 获取文档类型列表
export async function loader({ request }: LoaderFunctionArgs) {
try {
// 获取用户会话信息
const { getUserSession } = await import("~/api/login/auth.server");
const { frontendJWT } = await getUserSession(request);
const url = new URL(request.url);
const name = url.searchParams.get('name') || undefined;
const groupId = url.searchParams.get('group_id') || undefined;
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)
const [typesRes, modulesRes] = await Promise.all([
getDocumentTypes({}, frontendJWT),
getEntryModules(frontendJWT),
]);
// 如果获取父级评查点分组失败,返回空数组(不阻塞页面加载)
if(parentGroupsResponse.error){
console.error("获取父级评查点分组失败:", parentGroupsResponse.error);
}
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,
error: typesResponse.error
});
}
const typesResult = typesResponse.data?.types || [];
return Response.json({
types: typesResult,
total: typesResponse.data?.total || typesResult.length,
pageSize,
currentPage: page,
parentGroups,
frontendJWT
});
return {
types: typesRes.data?.types || [],
entryModules: modulesRes.data || [],
frontendJWT,
};
} catch (error) {
console.error("加载文档类型列表失败:", error);
const errorMessage = error instanceof Error ? error.message : "加载文档类型列表失败";
return Response.json({
types: [],
total: 0,
pageSize: 10,
currentPage: 1,
parentGroups: [],
frontendJWT: null,
error: errorMessage
});
return { types: [], entryModules: [], error: "加载失败" };
}
}
// 动作函数 - 处理删除请求
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() {
export default function DocumentTypesIndex() {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const fetcher = useFetcher<ActionResponse>();
const revalidator = useRevalidator();
const processedResponseRef = useRef<string | null>(null);
const loaderData = useLoaderData<LoaderData>();
const [types, setTypes] = useState<DocumentType[]>(loaderData.types || []);
const entryModules = loaderData.entryModules || [];
// 获取加载器数据
const { types, total, error, parentGroups, frontendJWT } = useLoaderData<LoaderData>();
// 处理 fetcher 响应
useEffect(() => {
// 为每个响应生成唯一标识,避免重复处理
const responseKey = fetcher.data ? JSON.stringify(fetcher.data) : null;
setTypes(loaderData.types || []);
}, [loaderData.types]);
if (responseKey && responseKey !== processedResponseRef.current) {
if (fetcher.data?.success) {
toastService.success('删除成功!');
processedResponseRef.current = responseKey;
// 只重新验证数据,不刷新整个页面
revalidator.revalidate();
} else if (fetcher.data?.error) {
toastService.error(`删除失败: ${fetcher.data.error}`);
processedResponseRef.current = responseKey;
}
}
}, [fetcher.data, revalidator]);
const getEntryModuleName = (id: number | null) => {
if (!id) return "—";
return entryModules.find((m) => m.id === id)?.name || `#${id}`;
};
// 权限控制
const { canCreate, canUpdate, canDelete, canView } = usePermission();
const canCreateType = canCreate('document_type');
const canUpdateType = canUpdate('document_type');
const canDeleteType = canDelete('document_type');
// console.log('document_type---canDeleteType',canDeleteType)
const canViewType = canView('document_type');
const handleDelete = async (type: DocumentType) => {
const confirmed = window.confirm(`确定要删除文档类型「${type.name}」吗?`);
if (!confirmed) return;
// 获取搜索参数
const name = searchParams.get('name') || '';
const currentPage = parseInt(searchParams.get('page') || String(1), 10);
const pageSize = parseInt(searchParams.get('pageSize') || String(10), 10);
// 处理测试loader返回的信息
useEffect(() => {
// console.log('返回的父级评查点分组数据',parentGroups)
}, [parentGroups])
// 处理loader加载数据的时候的错误
useEffect(() => {
if(error){
// 如果是无权限错误,显示友好提示
if(error.includes('Permission denied') || error.includes('无权限') || error.includes('权限不足')){
toastService.error('无权限访问文档类型管理,请联系系统管理员');
} else {
toastService.error(error);
}
}
}, [error]);
// 处理名称搜索
const handleNameSearch = (value: string) => {
const newParams = new URLSearchParams(searchParams);
if (value) {
newParams.set('name', value);
const result = await deleteDocumentType(type.id, loaderData.frontendJWT ?? undefined);
if (result.success) {
toastService.success("文档类型已删除");
setTypes((prev) => prev.filter((t) => t.id !== type.id));
} else {
newParams.delete('name');
toastService.error(result.error || "删除失败");
}
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 (
<div className="document-types-page">
{error && (
<div className="alert alert-error mb-4">
<p>{error}</p>
</div>
)}
{/* 页面头部 */}
<div className="page-header">
<h2 className="page-title"></h2>
<div>
{canCreateType && (
<Button
type="primary"
icon="ri-add-line"
onClick={() => navigate("/document-types/new")}
>
</Button>
)}
</div>
<h2 className="page-title">
<i className="ri-file-list-3-line"></i>
</h2>
<Button type="primary" icon="ri-add-line" onClick={() => navigate("/document-types/new")}>
</Button>
</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>
{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>
)}
</Card>
</div>
);
}
File diff suppressed because it is too large Load Diff