Merge branch 'shiy' into awen-dev
This commit is contained in:
+417
-197
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { MetaFunction, ActionFunctionArgs } from "@remix-run/node";
|
||||
import { MetaFunction, ActionFunctionArgs, json } from "@remix-run/node";
|
||||
import { Form } from "@remix-run/react";
|
||||
import { Card } from "~/components/ui/Card";
|
||||
import { Button } from "~/components/ui/Button";
|
||||
import { Table } from "~/components/ui/Table";
|
||||
@@ -30,10 +31,10 @@ export const meta: MetaFunction = () => {
|
||||
|
||||
// 文件类型定义
|
||||
export enum FileType {
|
||||
CONTRACT = "contract",
|
||||
LICENSE = "license",
|
||||
PUNISHMENT = "punishment",
|
||||
OTHER = "other"
|
||||
CONTRACT = "1",
|
||||
LICENSE = "2",
|
||||
PUNISHMENT = "3",
|
||||
OTHER = "4"
|
||||
}
|
||||
|
||||
// 文件类型标签映射
|
||||
@@ -58,6 +59,13 @@ export const PRIORITY_LABELS: Record<Priority, string> = {
|
||||
[Priority.URGENT]: "紧急"
|
||||
};
|
||||
|
||||
// 优先级中文映射
|
||||
const PRIORITY_TO_CHINESE: Record<Priority, string> = {
|
||||
[Priority.NORMAL]: "普通",
|
||||
[Priority.HIGH]: "优先",
|
||||
[Priority.URGENT]: "紧急"
|
||||
};
|
||||
|
||||
// 处理状态定义
|
||||
export enum ProcessingStatus {
|
||||
WAITING = "waiting",
|
||||
@@ -82,27 +90,148 @@ export interface UploadedFile {
|
||||
};
|
||||
}
|
||||
|
||||
// 文件上传响应接口
|
||||
interface FileUploadResponse {
|
||||
success: boolean;
|
||||
fileId?: string;
|
||||
message?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// 将文件转换为二进制数据
|
||||
async function uploadFileToBinary(file: File): Promise<ArrayBuffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = () => {
|
||||
if (reader.result instanceof ArrayBuffer) {
|
||||
resolve(reader.result);
|
||||
} else {
|
||||
reject(new Error('无法将文件转换为二进制格式'));
|
||||
}
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
reject(new Error('读取文件失败'));
|
||||
};
|
||||
|
||||
// 读取文件为 ArrayBuffer (二进制格式)
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
// 模拟上传文件到服务器的API
|
||||
async function uploadFileToServer(
|
||||
binaryData: ArrayBuffer,
|
||||
fileName: string,
|
||||
fileType: string,
|
||||
documentType: FileType,
|
||||
priority: Priority
|
||||
): Promise<FileUploadResponse> {
|
||||
// 在实际应用中,这里会使用fetch或axios发送请求到后端API
|
||||
console.log(`[模拟API] 上传文件: ${fileName}, 大小: ${binaryData.byteLength} 字节`);
|
||||
|
||||
// 模拟网络延迟
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
|
||||
try {
|
||||
// 创建FormData对象,将文件和其他信息一起提交
|
||||
const formData = new FormData();
|
||||
|
||||
// 将二进制数据转换为Blob并添加到FormData
|
||||
const blob = new Blob([binaryData], { type: fileType });
|
||||
formData.append('file', blob, fileName);
|
||||
|
||||
// 将 type_id 和 priority 添加到一个JSON对象中
|
||||
const uploadInfo = {
|
||||
type_id: Number(documentType), // 确保 type_id 是数字值
|
||||
evaluation_level: PRIORITY_TO_CHINESE[priority] // 转换为中文优先级
|
||||
};
|
||||
|
||||
// 添加 JSON 字符串到 FormData
|
||||
formData.append('upload_info', JSON.stringify(uploadInfo));
|
||||
|
||||
// 创建HTTP请求的参数
|
||||
const requestParams = {
|
||||
method: 'POST',
|
||||
url: 'http://172.16.0.55:8000/admin/documents/upload',
|
||||
headers: {
|
||||
// FormData会自动设置Content-Type为multipart/form-data
|
||||
'X-File-Name': encodeURIComponent(fileName)
|
||||
},
|
||||
body: formData
|
||||
};
|
||||
|
||||
// 打印 FormData 内容的正确方式
|
||||
console.log('[模拟API] 请求参数:', {
|
||||
url: requestParams.url,
|
||||
headers: requestParams.headers,
|
||||
uploadInfo, // 直接打印原始对象更有帮助
|
||||
formDataEntries: Array.from(formData.entries()).map(([key, value]) => {
|
||||
if (!(value instanceof Blob)) {
|
||||
return { key, value };
|
||||
}
|
||||
}),
|
||||
fileName
|
||||
});
|
||||
|
||||
// 实际API调用 - 在生产环境中实现
|
||||
const response = await fetch(requestParams.url, {
|
||||
method: requestParams.method,
|
||||
headers: requestParams.headers,
|
||||
body: requestParams.body
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// 获取更多错误信息
|
||||
const errorText = await response.text();
|
||||
console.error(`上传失败 (${response.status}): ${errorText}`);
|
||||
throw new Error(`上传失败: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('[模拟API] 上传错误:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '上传失败'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// action处理文件上传请求
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
|
||||
// 由于无法直接从Remix的action中处理文件上传,
|
||||
// 实际环境中应使用FormData将文件发送到后端API
|
||||
// 这里我们模拟处理过程,创建一个响应对象
|
||||
|
||||
// 获取文件和其他字段
|
||||
const fileUpload = formData.get("file") as File | null;
|
||||
const fileType = formData.get("fileType") as FileType;
|
||||
const priority = formData.get("priority") as Priority;
|
||||
|
||||
if (!fileType) {
|
||||
return Response.json(
|
||||
return json(
|
||||
{ success: false, error: "请选择文件类型" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!fileUpload) {
|
||||
return json(
|
||||
{ success: false, error: "未找到上传的文件" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// 获取文件信息
|
||||
console.log(`接收到文件: ${fileUpload.name}, 大小: ${fileUpload.size}, 类型: ${fileUpload.type}`);
|
||||
|
||||
// 注意: 在实际的Remix action中,我们无法直接处理文件内容
|
||||
// 这里的代码仅用于模拟。在前端组件中,我们将实现实际的文件处理逻辑。
|
||||
|
||||
// 模拟文件上传成功响应
|
||||
return Response.json({
|
||||
return json({
|
||||
success: true,
|
||||
message: "文件上传请求已接收",
|
||||
fileId: `file_${Date.now()}`,
|
||||
@@ -111,7 +240,7 @@ export async function action({ request }: ActionFunctionArgs) {
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("文件上传失败:", error);
|
||||
return Response.json(
|
||||
return json(
|
||||
{ success: false, error: "文件上传失败,请重试" },
|
||||
{ status: 500 }
|
||||
);
|
||||
@@ -186,6 +315,9 @@ export default function FilesUpload() {
|
||||
// UploadArea组件引用
|
||||
const uploadAreaRef = useRef<UploadAreaRef>(null);
|
||||
|
||||
// 表单提交引用
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
// 清理定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -198,6 +330,28 @@ export default function FilesUpload() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 处理表单提交
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!currentFile || !fileType) {
|
||||
alert('请选择文件和文件类型');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 设置上传状态
|
||||
setUploadStage('uploading');
|
||||
|
||||
// 实际上传 - 通过我们自定义的二进制上传方法
|
||||
await startUpload(currentFile);
|
||||
|
||||
} catch (error) {
|
||||
console.error('提交表单错误:', error);
|
||||
alert(`提交表单失败: ${error instanceof Error ? error.message : '未知错误'}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理文件选择
|
||||
const handleFilesSelected = useCallback((selectedFiles: FileList) => {
|
||||
console.log("selectedFiles", selectedFiles);
|
||||
@@ -213,46 +367,111 @@ export default function FilesUpload() {
|
||||
}
|
||||
|
||||
setCurrentFile(selectedFiles[0]);
|
||||
// 立即开始上传
|
||||
startUpload(selectedFiles[0]);
|
||||
}, [fileType, currentFile]);
|
||||
}, [fileType]);
|
||||
|
||||
// 开始上传文件
|
||||
const startUpload = (file: File) => {
|
||||
setUploadStage("uploading");
|
||||
setUploadProgress(0);
|
||||
|
||||
// 更新步骤状态
|
||||
const updatedSteps = [...processingSteps];
|
||||
updatedSteps[0].status = "active";
|
||||
updatedSteps[0].description = `正在上传文件"${file.name}"到服务器...`;
|
||||
setProcessingSteps(updatedSteps);
|
||||
|
||||
// 模拟上传进度
|
||||
if (progressIntervalRef.current) {
|
||||
clearInterval(progressIntervalRef.current);
|
||||
}
|
||||
|
||||
progressIntervalRef.current = setInterval(() => {
|
||||
setUploadProgress(prev => {
|
||||
const newProgress = prev + 5;
|
||||
// 根据文件大小调整上传速度
|
||||
const speedFactor = Math.min(file.size / (1024 * 1024) + 1, 5);
|
||||
setUploadSpeed(`${Math.floor(Math.random() * 100 * speedFactor) + 50}KB/s`);
|
||||
|
||||
if (newProgress >= 100) {
|
||||
if (progressIntervalRef.current) {
|
||||
clearInterval(progressIntervalRef.current);
|
||||
setUploadSpeed("完成");
|
||||
|
||||
// 完成上传后开始处理流程
|
||||
startProcessing(file);
|
||||
const startUpload = async (file: File) => {
|
||||
try {
|
||||
setUploadStage("uploading");
|
||||
setUploadProgress(0);
|
||||
|
||||
// 更新步骤状态
|
||||
const updatedSteps = [...processingSteps];
|
||||
updatedSteps[0].status = "active";
|
||||
updatedSteps[0].description = `正在上传文件"${file.name}"到服务器...`;
|
||||
setProcessingSteps(updatedSteps);
|
||||
|
||||
// 转换文件为二进制格式
|
||||
console.log("开始转换文件到二进制格式...");
|
||||
|
||||
// 模拟上传进度
|
||||
if (progressIntervalRef.current) {
|
||||
clearInterval(progressIntervalRef.current);
|
||||
}
|
||||
|
||||
progressIntervalRef.current = setInterval(() => {
|
||||
setUploadProgress(prev => {
|
||||
const newProgress = prev + 2;
|
||||
// 根据文件大小调整上传速度
|
||||
const speedFactor = Math.min(file.size / (1024 * 1024) + 1, 5);
|
||||
setUploadSpeed(`${Math.floor(Math.random() * 100 * speedFactor) + 50}KB/s`);
|
||||
|
||||
if (newProgress >= 50) { // 只模拟到50%,剩下的50%留给实际上传
|
||||
if (progressIntervalRef.current) {
|
||||
clearInterval(progressIntervalRef.current);
|
||||
}
|
||||
return 50;
|
||||
}
|
||||
return 100;
|
||||
|
||||
return newProgress;
|
||||
});
|
||||
}, 100);
|
||||
|
||||
// 实际执行二进制转换
|
||||
const binaryData = await uploadFileToBinary(file);
|
||||
console.log(`文件转换为二进制完成,大小: ${binaryData.byteLength} 字节`);
|
||||
|
||||
// 模拟实际上传
|
||||
setUploadProgress(60); // 转换完成,进度到60%
|
||||
setUploadSpeed(`${Math.floor(Math.random() * 200) + 100}KB/s`);
|
||||
|
||||
console.log("开始上传文件到服务器...");
|
||||
const response = await uploadFileToServer(
|
||||
binaryData,
|
||||
file.name,
|
||||
file.type,
|
||||
fileType as FileType,
|
||||
priority
|
||||
);
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(response.error || "上传失败");
|
||||
}
|
||||
|
||||
console.log("文件上传成功:", response);
|
||||
setUploadProgress(100);
|
||||
setUploadSpeed("完成");
|
||||
|
||||
// 创建新的文件对象并添加到队列
|
||||
const newFile: UploadedFile = {
|
||||
id: `file_${Date.now()}`,
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
type: file.type,
|
||||
fileType: fileType as FileType,
|
||||
priority,
|
||||
status: ProcessingStatus.PROCESSING,
|
||||
uploadTime: getCurrentTime(),
|
||||
processingInfo: {
|
||||
progress: 0,
|
||||
currentStep: 0
|
||||
}
|
||||
|
||||
return newProgress;
|
||||
});
|
||||
}, 200);
|
||||
};
|
||||
|
||||
// 添加到队列中
|
||||
setQueueFiles(prev => [newFile, ...prev]);
|
||||
|
||||
// 完成上传后开始处理流程
|
||||
startProcessing(file);
|
||||
} catch (error) {
|
||||
console.error("文件上传错误:", error);
|
||||
|
||||
// 更新步骤状态为错误
|
||||
const errorSteps = [...processingSteps];
|
||||
errorSteps[0].status = "error";
|
||||
errorSteps[0].description = `上传文件"${file.name}"失败: ${error instanceof Error ? error.message : '未知错误'}`;
|
||||
setProcessingSteps(errorSteps);
|
||||
|
||||
// 清除进度定时器
|
||||
if (progressIntervalRef.current) {
|
||||
clearInterval(progressIntervalRef.current);
|
||||
}
|
||||
|
||||
alert(`文件上传失败: ${error instanceof Error ? error.message : '未知错误'}`);
|
||||
resetUpload();
|
||||
}
|
||||
};
|
||||
|
||||
// 开始处理文件
|
||||
@@ -308,13 +527,6 @@ export default function FilesUpload() {
|
||||
|
||||
setProcessingSteps(nextUpdatedSteps);
|
||||
currentStepIndex++;
|
||||
|
||||
// 如果这是最后一个步骤,确保完成
|
||||
// if (currentStepIndex >= processingSteps.length) {
|
||||
// setTimeout(() => {
|
||||
// completeProcessing();
|
||||
// }, 1000);
|
||||
// }
|
||||
}, 2000);
|
||||
|
||||
}, 2500);
|
||||
@@ -514,157 +726,165 @@ export default function FilesUpload() {
|
||||
<h2 className="page-title">待审核文件上传</h2>
|
||||
</div>
|
||||
|
||||
{/* 文件类型选择 */}
|
||||
<Card title={<h3>选择文件类型</h3>} className="mb-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="form-group">
|
||||
<label htmlFor="file-type-select" className="form-label">文件类型 <span className="text-red-500">*</span></label>
|
||||
<select
|
||||
id="file-type-select"
|
||||
className="form-select"
|
||||
value={fileType}
|
||||
onChange={(e) => setFileType(e.target.value as FileType)}
|
||||
disabled={uploadStage !== "idle"}
|
||||
>
|
||||
<option value="">请选择文件类型</option>
|
||||
<option value={FileType.CONTRACT}>合同文档</option>
|
||||
<option value={FileType.LICENSE}>专卖许可证</option>
|
||||
<option value={FileType.PUNISHMENT}>行政处罚决定书</option>
|
||||
<option value={FileType.OTHER}>其他文档</option>
|
||||
</select>
|
||||
<div className="form-tip">不同类型的文档将应用不同的审核规则</div>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label htmlFor="priority-select" className="form-label">审核优先级</label>
|
||||
<select
|
||||
id="priority-select"
|
||||
className="form-select"
|
||||
value={priority}
|
||||
onChange={(e) => setPriority(e.target.value as Priority)}
|
||||
disabled={uploadStage !== "idle"}
|
||||
>
|
||||
<option value={Priority.NORMAL}>普通</option>
|
||||
<option value={Priority.HIGH}>优先</option>
|
||||
<option value={Priority.URGENT}>紧急</option>
|
||||
</select>
|
||||
<div className="form-tip">优先级影响文档在队列中的处理顺序</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* 文件上传区域 */}
|
||||
<Card title={<h3>文件上传</h3>} className="mb-4">
|
||||
{/* 初始上传区域 */}
|
||||
{uploadStage === "idle" && (
|
||||
<UploadArea
|
||||
ref={uploadAreaRef}
|
||||
onFilesSelected={handleFilesSelected}
|
||||
multiple={false}
|
||||
accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png"
|
||||
tipText="支持单个或批量上传,文件格式:PDF、Word、Excel、图片"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 上传进度显示 */}
|
||||
{uploadStage !== "completed" && currentFile && (
|
||||
<FileProgress
|
||||
fileName={currentFile.name}
|
||||
fileSize={formatFileSize(currentFile.size)}
|
||||
progress={uploadProgress}
|
||||
speed={uploadSpeed}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 处理步骤显示 */}
|
||||
{(uploadStage === "processing" || uploadStage === "completed") && (
|
||||
<div className="mt-4 mb-4">
|
||||
<ProcessingSteps steps={processingSteps} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 完成后的文件信息 */}
|
||||
{uploadStage === "completed" && completedFile && (
|
||||
<div className="mt-6">
|
||||
<div className="bg-green-50 p-4 rounded-md mb-4 border border-green-100">
|
||||
<div className="flex items-center text-green-800 mb-2">
|
||||
<i className="ri-checkbox-circle-line text-xl mr-2"></i>
|
||||
<span className="font-medium">评查成功</span>
|
||||
</div>
|
||||
<p className="text-sm text-green-700">文件已成功上传并评查完成,请查看结果</p>
|
||||
{/* 文件类型选择和上传表单 */}
|
||||
<Form method="post" encType="multipart/form-data" onSubmit={handleSubmit} ref={formRef}>
|
||||
{/* 文件类型选择 */}
|
||||
<Card title={<h3>选择文件类型</h3>} className="mb-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="form-group">
|
||||
<label htmlFor="file-type-select" className="form-label">文件类型 <span className="text-red-500">*</span></label>
|
||||
<select
|
||||
id="file-type-select"
|
||||
name="fileType"
|
||||
className="form-select"
|
||||
value={fileType}
|
||||
onChange={(e) => setFileType(e.target.value as FileType)}
|
||||
disabled={uploadStage !== "idle"}
|
||||
>
|
||||
<option value="">请选择文件类型</option>
|
||||
<option value={FileType.CONTRACT}>{FILE_TYPE_LABELS[FileType.CONTRACT]}</option>
|
||||
<option value={FileType.LICENSE}>{FILE_TYPE_LABELS[FileType.LICENSE]}</option>
|
||||
<option value={FileType.PUNISHMENT}>{FILE_TYPE_LABELS[FileType.PUNISHMENT]}</option>
|
||||
<option value={FileType.OTHER}>{FILE_TYPE_LABELS[FileType.OTHER]}</option>
|
||||
</select>
|
||||
<div className="form-tip">不同类型的文档将应用不同的审核规则</div>
|
||||
</div>
|
||||
|
||||
<div className="file-info-grid">
|
||||
<div>
|
||||
<h4 className="font-medium mb-3">文件信息</h4>
|
||||
<ul className="file-info-list">
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">文件名:</span>
|
||||
<span className="file-info-value">{completedFile.name}</span>
|
||||
</li>
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">文件大小:</span>
|
||||
<span className="file-info-value">{formatFileSize(completedFile.size)}</span>
|
||||
</li>
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">上传时间:</span>
|
||||
<span className="file-info-value">{completedFile.uploadTime}</span>
|
||||
</li>
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">文件类型:</span>
|
||||
<span className="file-info-value">{FILE_TYPE_LABELS[completedFile.fileType]}</span>
|
||||
</li>
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">审核规则:</span>
|
||||
<span className="file-info-value">系统自动选择</span>
|
||||
</li>
|
||||
</ul>
|
||||
<div className="form-group">
|
||||
<label htmlFor="priority-select" className="form-label">审核优先级</label>
|
||||
<select
|
||||
id="priority-select"
|
||||
name="priority"
|
||||
className="form-select"
|
||||
value={priority}
|
||||
onChange={(e) => setPriority(e.target.value as Priority)}
|
||||
disabled={uploadStage !== "idle"}
|
||||
>
|
||||
<option value={Priority.NORMAL}>{PRIORITY_LABELS[Priority.NORMAL]}</option>
|
||||
<option value={Priority.HIGH}>{PRIORITY_LABELS[Priority.HIGH]}</option>
|
||||
<option value={Priority.URGENT}>{PRIORITY_LABELS[Priority.URGENT]}</option>
|
||||
</select>
|
||||
<div className="form-tip">优先级影响文档在队列中的处理顺序</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* 文件上传区域 */}
|
||||
<Card title={<h3>文件上传</h3>} className="mb-4">
|
||||
{/* 初始上传区域 */}
|
||||
{uploadStage === "idle" && (
|
||||
<>
|
||||
<UploadArea
|
||||
ref={uploadAreaRef}
|
||||
onFilesSelected={handleFilesSelected}
|
||||
multiple={false}
|
||||
accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png"
|
||||
tipText="支持单个或批量上传,文件格式:PDF、Word、Excel、图片"
|
||||
shouldPreventFileSelect={!fileType}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 上传进度显示 */}
|
||||
{uploadStage !== "completed" && currentFile && (
|
||||
<FileProgress
|
||||
fileName={currentFile.name}
|
||||
fileSize={formatFileSize(currentFile.size)}
|
||||
progress={uploadProgress}
|
||||
speed={uploadSpeed}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 处理步骤显示 */}
|
||||
{(uploadStage === "processing" || uploadStage === "completed") && (
|
||||
<div className="mt-4 mb-4">
|
||||
<ProcessingSteps steps={processingSteps} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 完成后的文件信息 */}
|
||||
{uploadStage === "completed" && completedFile && (
|
||||
<div className="mt-6">
|
||||
<div className="bg-green-50 p-4 rounded-md mb-4 border border-green-100">
|
||||
<div className="flex items-center text-green-800 mb-2">
|
||||
<i className="ri-checkbox-circle-line text-xl mr-2"></i>
|
||||
<span className="font-medium">评查成功</span>
|
||||
</div>
|
||||
<p className="text-sm text-green-700">文件已成功上传并评查完成,请查看结果</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="font-medium mb-3">解析结果预览</h4>
|
||||
<div className="bg-gray-50 p-3 rounded-md border border-gray-200">
|
||||
<div className="mb-2">
|
||||
<span className="text-gray-500 text-sm">合同编号:</span>
|
||||
<span className="pulse-animation">XS-2023-1025-001</span>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<span className="text-gray-500 text-sm">合同名称:</span>
|
||||
<span className="pulse-animation">烟草制品销售合同</span>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<span className="text-gray-500 text-sm">签约日期:</span>
|
||||
<span className="pulse-animation">2023年10月20日</span>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<span className="text-gray-500 text-sm">合同金额:</span>
|
||||
<span className="pulse-animation">¥ 1,580,000.00</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 text-sm">当事人:</span>
|
||||
<span className="pulse-animation">甲方:XX烟草公司,乙方:YY贸易有限公司</span>
|
||||
</div>
|
||||
<div className="file-info-grid">
|
||||
<div>
|
||||
<h4 className="font-medium mb-3">文件信息</h4>
|
||||
<ul className="file-info-list">
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">文件名:</span>
|
||||
<span className="file-info-value">{completedFile.name}</span>
|
||||
</li>
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">文件大小:</span>
|
||||
<span className="file-info-value">{formatFileSize(completedFile.size)}</span>
|
||||
</li>
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">上传时间:</span>
|
||||
<span className="file-info-value">{completedFile.uploadTime}</span>
|
||||
</li>
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">文件类型:</span>
|
||||
<span className="file-info-value">{FILE_TYPE_LABELS[completedFile.fileType]}</span>
|
||||
</li>
|
||||
<li className="file-info-item">
|
||||
<span className="file-info-label">审核规则:</span>
|
||||
<span className="file-info-value">系统自动选择</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex justify-between">
|
||||
<Button
|
||||
type="default"
|
||||
icon="ri-refresh-line"
|
||||
onClick={resetUpload}
|
||||
>
|
||||
上传新文件
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon="ri-file-search-line"
|
||||
>
|
||||
查看详情并审核
|
||||
</Button>
|
||||
<div>
|
||||
<h4 className="font-medium mb-3">解析结果预览</h4>
|
||||
<div className="bg-gray-50 p-3 rounded-md border border-gray-200">
|
||||
<div className="mb-2">
|
||||
<span className="text-gray-500 text-sm">合同编号:</span>
|
||||
<span className="pulse-animation">XS-2023-1025-001</span>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<span className="text-gray-500 text-sm">合同名称:</span>
|
||||
<span className="pulse-animation">烟草制品销售合同</span>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<span className="text-gray-500 text-sm">签约日期:</span>
|
||||
<span className="pulse-animation">2023年10月20日</span>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<span className="text-gray-500 text-sm">合同金额:</span>
|
||||
<span className="pulse-animation">¥ 1,580,000.00</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 text-sm">当事人:</span>
|
||||
<span className="pulse-animation">甲方:XX烟草公司,乙方:YY贸易有限公司</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex justify-between">
|
||||
<Button
|
||||
type="default"
|
||||
icon="ri-refresh-line"
|
||||
onClick={resetUpload}
|
||||
>
|
||||
上传新文件
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon="ri-file-search-line"
|
||||
>
|
||||
查看详情并审核
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
</Card>
|
||||
</Form>
|
||||
|
||||
{/* 上传队列 */}
|
||||
<Card
|
||||
|
||||
+400
-134
@@ -1,6 +1,6 @@
|
||||
import { json, type MetaFunction } from "@remix-run/node";
|
||||
import { type MetaFunction } from "@remix-run/node";
|
||||
import { useLoaderData, Link, useNavigate, useSearchParams } from "@remix-run/react";
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import indexStyles from "~/styles/pages/rule-groups_index.css?url";
|
||||
import { Card } from "~/components/ui/Card";
|
||||
import { Button } from "~/components/ui/Button";
|
||||
@@ -8,23 +8,12 @@ import { StatusDot } from "~/components/ui/StatusDot";
|
||||
import { Table } from "~/components/ui/Table";
|
||||
import { FilterPanel, FilterSelect, SearchFilter } from "~/components/ui/FilterPanel";
|
||||
import { Pagination } from "~/components/ui/Pagination";
|
||||
import { getRuleGroups, getChildGroups, type RuleGroup, deleteRuleGroup } from "~/api/evaluation_points/rule-groups";
|
||||
|
||||
export function links() {
|
||||
return [{ rel: "stylesheet", href: indexStyles }];
|
||||
}
|
||||
|
||||
// 定义数据类型
|
||||
interface RuleGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
ruleCount: number;
|
||||
subGroupCount: number;
|
||||
status: 'active' | 'inactive';
|
||||
createdAt: string;
|
||||
children?: RuleGroup[];
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
{ title: "评查点分组 - 中国烟草AI合同及卷宗审核系统" },
|
||||
@@ -32,98 +21,201 @@ export const meta: MetaFunction = () => {
|
||||
];
|
||||
};
|
||||
|
||||
|
||||
// 模拟数据
|
||||
const MOCK_GROUPS: RuleGroup[] = [
|
||||
{
|
||||
id: "1",
|
||||
name: "合同基本要素检查",
|
||||
code: "contract-base",
|
||||
ruleCount: 18,
|
||||
subGroupCount: 12,
|
||||
status: "active",
|
||||
createdAt: "2023-10-01 14:30",
|
||||
children: [
|
||||
{
|
||||
id: "2",
|
||||
name: "必备要素检查",
|
||||
code: "essential-elements",
|
||||
ruleCount: 7,
|
||||
subGroupCount: 0,
|
||||
status: "active",
|
||||
createdAt: "2023-10-02 10:15",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
name: "合同主体检查",
|
||||
code: "contract-parties",
|
||||
ruleCount: 5,
|
||||
subGroupCount: 0,
|
||||
status: "active",
|
||||
createdAt: "2023-10-03 16:20",
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
name: "销售合同专项检查",
|
||||
code: "contract-sales",
|
||||
ruleCount: 12,
|
||||
subGroupCount: 5,
|
||||
status: "active",
|
||||
createdAt: "2023-10-05 09:30",
|
||||
children: [
|
||||
{
|
||||
id: "6",
|
||||
name: "付款条件检查",
|
||||
code: "payment-terms",
|
||||
ruleCount: 5,
|
||||
subGroupCount: 0,
|
||||
status: "active",
|
||||
createdAt: "2023-10-05 14:45",
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: "5",
|
||||
name: "行政处罚规范性检查",
|
||||
code: "punishment",
|
||||
ruleCount: 8,
|
||||
subGroupCount: 0,
|
||||
status: "inactive",
|
||||
createdAt: "2023-10-08 11:45",
|
||||
}
|
||||
];
|
||||
|
||||
export async function loader() {
|
||||
return json({ groups: MOCK_GROUPS });
|
||||
try {
|
||||
const response = await getRuleGroups();
|
||||
if (response.error) {
|
||||
throw new Error(response.error);
|
||||
}
|
||||
return Response.json({ groups: response.data });
|
||||
} catch (error) {
|
||||
console.error('加载评查点分组失败:', error);
|
||||
return Response.json({ groups: [] });
|
||||
}
|
||||
}
|
||||
|
||||
export default function RuleGroupsIndex() {
|
||||
const { groups } = useLoaderData<typeof loader>();
|
||||
const { groups: initialGroups } = useLoaderData<typeof loader>();
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [expandedGroups, setExpandedGroups] = useState<string[]>([]);
|
||||
const [groups, setGroups] = useState<RuleGroup[]>(initialGroups || []);
|
||||
const [loading, setLoading] = useState<Record<string, boolean>>({});
|
||||
const [filteredChildrenMap, setFilteredChildrenMap] = useState<Record<string, RuleGroup[]>>({});
|
||||
const [initialLoading, setInitialLoading] = useState<boolean>(true);
|
||||
|
||||
// 初始加载时自动加载所有子分组
|
||||
useEffect(() => {
|
||||
const loadAllChildGroups = async () => {
|
||||
if (!initialGroups || initialGroups.length === 0) {
|
||||
setInitialLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 创建一个加载状态对象,标记所有父分组正在加载
|
||||
const loadingState: Record<string, boolean> = {};
|
||||
initialGroups.forEach((group: RuleGroup) => {
|
||||
loadingState[group.id] = true;
|
||||
});
|
||||
setLoading(loadingState);
|
||||
|
||||
// 并行加载所有父分组的子分组
|
||||
const promises = initialGroups.map(async (group: RuleGroup) => {
|
||||
try {
|
||||
const response = await getChildGroups(group.id);
|
||||
if (response.error) {
|
||||
console.error(`加载分组 ${group.id} 的子分组失败:`, response.error);
|
||||
return { parentId: group.id, children: [] };
|
||||
}
|
||||
return { parentId: group.id, children: response.data };
|
||||
} catch (error) {
|
||||
console.error(`加载分组 ${group.id} 的子分组出错:`, error);
|
||||
return { parentId: group.id, children: [] };
|
||||
}
|
||||
});
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
|
||||
// 更新分组数据
|
||||
setGroups(prev => {
|
||||
const newGroups = [...prev];
|
||||
results.forEach(({ parentId, children }) => {
|
||||
const parentIndex = newGroups.findIndex(g => g.id === parentId);
|
||||
if (parentIndex !== -1) {
|
||||
newGroups[parentIndex] = {
|
||||
...newGroups[parentIndex],
|
||||
children
|
||||
};
|
||||
}
|
||||
});
|
||||
return newGroups;
|
||||
});
|
||||
|
||||
// 展开所有父分组
|
||||
setExpandedGroups(initialGroups.map((group: RuleGroup) => group.id));
|
||||
} catch (error) {
|
||||
console.error('自动加载所有子分组失败:', error);
|
||||
} finally {
|
||||
// 清除所有加载状态
|
||||
setLoading({});
|
||||
setInitialLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadAllChildGroups();
|
||||
}, [initialGroups]);
|
||||
|
||||
// 处理展开/收起
|
||||
const toggleGroup = (groupId: string) => {
|
||||
setExpandedGroups(prev =>
|
||||
prev.includes(groupId)
|
||||
? prev.filter(id => id !== groupId)
|
||||
: [...prev, groupId]
|
||||
);
|
||||
const toggleGroup = async (groupId: string) => {
|
||||
if (expandedGroups.includes(groupId)) {
|
||||
// 收起分组
|
||||
setExpandedGroups(prev => prev.filter(id => id !== groupId));
|
||||
return;
|
||||
}
|
||||
|
||||
// 展开分组
|
||||
setLoading(prev => ({ ...prev, [groupId]: true }));
|
||||
try {
|
||||
const parentGroup = groups.find(g => g.id === groupId);
|
||||
|
||||
// 如果已经加载过子分组,直接展开
|
||||
if (parentGroup && parentGroup.children && parentGroup.children.length > 0) {
|
||||
setExpandedGroups(prev => [...prev, groupId]);
|
||||
|
||||
// 应用现有的过滤条件到已加载的子分组
|
||||
const nameFilter = searchParams.get('name') || '';
|
||||
const codeFilter = searchParams.get('code') || '';
|
||||
const statusFilter = searchParams.get('is_enabled') || '';
|
||||
|
||||
if ((nameFilter || codeFilter || statusFilter) && parentGroup.children) {
|
||||
applyFiltersToChildren(groupId, parentGroup.children);
|
||||
}
|
||||
|
||||
setLoading(prev => ({ ...prev, [groupId]: false }));
|
||||
return;
|
||||
}
|
||||
|
||||
// 否则加载子分组
|
||||
const response = await getChildGroups(groupId);
|
||||
if (response.error) {
|
||||
throw new Error(response.error);
|
||||
}
|
||||
|
||||
// 更新分组数据
|
||||
setGroups(prev => prev.map(group => {
|
||||
if (group.id === groupId) {
|
||||
return {
|
||||
...group,
|
||||
children: response.data
|
||||
};
|
||||
}
|
||||
return group;
|
||||
}));
|
||||
|
||||
setExpandedGroups(prev => [...prev, groupId]);
|
||||
|
||||
// 应用现有的过滤条件到新加载的子分组
|
||||
const nameFilter = searchParams.get('name') || '';
|
||||
const codeFilter = searchParams.get('code') || '';
|
||||
const statusFilter = searchParams.get('is_enabled') || '';
|
||||
|
||||
if ((nameFilter || codeFilter || statusFilter) && response.data) {
|
||||
applyFiltersToChildren(groupId, response.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载子分组失败:', error);
|
||||
} finally {
|
||||
setLoading(prev => ({ ...prev, [groupId]: false }));
|
||||
}
|
||||
};
|
||||
|
||||
// 展开/收起全部
|
||||
const toggleAll = (expand: boolean) => {
|
||||
setExpandedGroups(expand ? groups.map(g => g.id) : []);
|
||||
const toggleAll = async (expand: boolean) => {
|
||||
if (expand) {
|
||||
// 展开所有分组
|
||||
const expandedIds = groups.map(g => g.id);
|
||||
setExpandedGroups(expandedIds);
|
||||
} else {
|
||||
setExpandedGroups([]);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理删除分组
|
||||
const handleDeleteGroup = (groupId: string) => {
|
||||
const handleDeleteGroup = async (groupId: string) => {
|
||||
if (confirm("确定要删除该分组吗?此操作将同时删除该分组下的所有评查点,且不可恢复。")) {
|
||||
console.log('删除分组ID:', groupId);
|
||||
// 实际应用中,这里会调用API删除数据
|
||||
try {
|
||||
const result = await deleteRuleGroup(groupId);
|
||||
if (result.success) {
|
||||
// 从本地状态中移除被删除的分组
|
||||
setGroups(prev => {
|
||||
// 如果是一级分组,直接过滤掉
|
||||
const filteredGroups = prev.filter(g => g.id !== groupId);
|
||||
|
||||
// 如果是二级分组,需要从父分组的 children 中移除
|
||||
return filteredGroups.map(group => {
|
||||
if (group.children) {
|
||||
return {
|
||||
...group,
|
||||
children: group.children.filter(child => child.id !== groupId)
|
||||
};
|
||||
}
|
||||
return group;
|
||||
});
|
||||
});
|
||||
|
||||
// 如果被删除的分组当前是展开状态,从展开列表中移除
|
||||
setExpandedGroups(prev => prev.filter(id => id !== groupId));
|
||||
|
||||
// 显示成功消息
|
||||
alert('删除成功');
|
||||
} else {
|
||||
alert(`删除失败: ${result.error}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除分组失败:', error);
|
||||
alert('删除分组失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -156,9 +248,9 @@ export default function RuleGroupsIndex() {
|
||||
const { value } = e.target;
|
||||
const newParams = new URLSearchParams(searchParams);
|
||||
if (value) {
|
||||
newParams.set('status', value);
|
||||
newParams.set('is_enabled', value);
|
||||
} else {
|
||||
newParams.delete('status');
|
||||
newParams.delete('is_enabled');
|
||||
}
|
||||
newParams.set('page', '1');
|
||||
setSearchParams(newParams);
|
||||
@@ -167,10 +259,145 @@ export default function RuleGroupsIndex() {
|
||||
// 处理重置筛选
|
||||
const handleReset = () => {
|
||||
setSearchParams(new URLSearchParams());
|
||||
setFilteredChildrenMap({});
|
||||
|
||||
// 清空输入框内容(通过DOM操作)
|
||||
const nameInput = document.querySelector('input[placeholder="请输入分组名称"]') as HTMLInputElement;
|
||||
const codeInput = document.querySelector('input[placeholder="请输入分组编码"]') as HTMLInputElement;
|
||||
const statusSelect = document.querySelector('select[name="is_enabled"]') as HTMLSelectElement;
|
||||
|
||||
if (nameInput) nameInput.value = '';
|
||||
if (codeInput) codeInput.value = '';
|
||||
if (statusSelect) statusSelect.value = '';
|
||||
};
|
||||
|
||||
// 应用筛选条件到子分组
|
||||
const applyFiltersToChildren = (parentId: string, children: RuleGroup[]) => {
|
||||
const nameFilter = searchParams.get('name') || '';
|
||||
const codeFilter = searchParams.get('code') || '';
|
||||
const statusFilter = searchParams.get('is_enabled') || '';
|
||||
|
||||
|
||||
if (!nameFilter && !codeFilter && !statusFilter) {
|
||||
setFilteredChildrenMap(prev => ({...prev, [parentId]: []}));
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredChildren = children.filter(child => {
|
||||
// 筛选名称
|
||||
if (nameFilter && !child.name.toLowerCase().includes(nameFilter.toLowerCase())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 筛选编码
|
||||
if (codeFilter && (!child.code || !child.code.toLowerCase().includes(codeFilter.toLowerCase()))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 筛选状态
|
||||
if (statusFilter) {
|
||||
const isEnabled = statusFilter === 'true';
|
||||
if (child.is_enabled !== isEnabled) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
setFilteredChildrenMap(prev => ({...prev, [parentId]: filteredChildren}));
|
||||
};
|
||||
|
||||
// 当筛选条件变化时,重新计算过滤结果
|
||||
useEffect(() => {
|
||||
const nameFilter = searchParams.get('name') || '';
|
||||
const codeFilter = searchParams.get('code') || '';
|
||||
const statusFilter = searchParams.get('is_enabled') || '';
|
||||
|
||||
if (!nameFilter && !codeFilter && !statusFilter) {
|
||||
setFilteredChildrenMap({});
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查所有已加载的子分组
|
||||
groups.forEach(group => {
|
||||
if (group.children && group.children.length > 0) {
|
||||
applyFiltersToChildren(group.id, group.children);
|
||||
}
|
||||
});
|
||||
|
||||
// 查找匹配的子分组,自动展开它们的父级
|
||||
const parentsToExpand: string[] = [];
|
||||
|
||||
groups.forEach(group => {
|
||||
if (group.children && group.children.length > 0) {
|
||||
const hasMatchingChild = group.children.some(child => {
|
||||
const nameMatch = !nameFilter || child.name.toLowerCase().includes(nameFilter.toLowerCase());
|
||||
const codeMatch = !codeFilter || (child.code && child.code.toLowerCase().includes(codeFilter.toLowerCase()));
|
||||
const statusMatch = !statusFilter || (statusFilter === 'true' ? child.is_enabled : !child.is_enabled);
|
||||
|
||||
return nameMatch && codeMatch && statusMatch;
|
||||
});
|
||||
|
||||
if (hasMatchingChild && !expandedGroups.includes(group.id)) {
|
||||
parentsToExpand.push(group.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (parentsToExpand.length > 0) {
|
||||
setExpandedGroups(prev => [...prev, ...parentsToExpand]);
|
||||
}
|
||||
}, [searchParams, groups]);
|
||||
|
||||
// 检查父级分组是否匹配筛选条件
|
||||
const parentMatchesFilter = (group: RuleGroup): boolean => {
|
||||
const nameFilter = searchParams.get('name') || '';
|
||||
const codeFilter = searchParams.get('code') || '';
|
||||
const statusFilter = searchParams.get('is_enabled') || '';
|
||||
|
||||
// 筛选名称
|
||||
if (nameFilter && !group.name.toLowerCase().includes(nameFilter.toLowerCase())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 筛选编码
|
||||
if (codeFilter && (!group.code || !group.code.toLowerCase().includes(codeFilter.toLowerCase()))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 筛选状态
|
||||
if (statusFilter) {
|
||||
const isEnabled = statusFilter === 'true';
|
||||
if (group.is_enabled !== isEnabled) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
// 检查父级分组是否有匹配的子分组
|
||||
const hasMatchingChildren = (parentId: string): boolean => {
|
||||
const filteredChildren = filteredChildrenMap[parentId];
|
||||
return filteredChildren && filteredChildren.length > 0;
|
||||
};
|
||||
|
||||
// 处理表格数据,包括父子级关系
|
||||
const processedData = groups.flatMap(group => {
|
||||
const parentMatches = parentMatchesFilter(group);
|
||||
const hasMatched = hasMatchingChildren(group.id);
|
||||
|
||||
// 如果有筛选条件但父级和子级都不匹配,则不显示
|
||||
const nameFilter = searchParams.get('name') || '';
|
||||
const codeFilter = searchParams.get('code') || '';
|
||||
const statusFilter = searchParams.get('is_enabled') || '';
|
||||
const hasFilters = nameFilter || codeFilter || statusFilter;
|
||||
|
||||
if (hasFilters && !parentMatches && !hasMatched) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 先添加父级分组
|
||||
const result: (RuleGroup & { isParent?: boolean, parentId?: string })[] = [
|
||||
{ ...group, isParent: true }
|
||||
@@ -178,21 +405,46 @@ export default function RuleGroupsIndex() {
|
||||
|
||||
// 如果有子级分组并且当前已展开,则添加子级分组
|
||||
if (group.children && expandedGroups.includes(group.id)) {
|
||||
group.children.forEach(child => {
|
||||
result.push({ ...child, parentId: group.id });
|
||||
});
|
||||
// 如果有筛选条件并且有过滤后的子分组,则显示过滤后的子分组
|
||||
if (hasFilters && filteredChildrenMap[group.id]) {
|
||||
filteredChildrenMap[group.id].forEach(child => {
|
||||
result.push({ ...child, parentId: group.id });
|
||||
});
|
||||
}
|
||||
// 否则显示所有子分组
|
||||
else if (!hasFilters) {
|
||||
group.children.forEach(child => {
|
||||
result.push({ ...child, parentId: group.id });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
// 计算一级分组的评查点数量(累加其所有二级分组的评查点数量)
|
||||
const calculateTotalRuleCount = (record: RuleGroup & { isParent?: boolean, parentId?: string }) => {
|
||||
// 如果是二级分组,直接返回其评查点数量
|
||||
if (!record.isParent) {
|
||||
return record.ruleCount || 0;
|
||||
}
|
||||
|
||||
// 如果是一级分组,累加其所有子分组的评查点数量
|
||||
let totalCount = 0;
|
||||
if (record.children && record.children.length > 0) {
|
||||
totalCount = record.children.reduce((sum, child) => sum + (child.ruleCount || 0), 0);
|
||||
}
|
||||
|
||||
return totalCount;
|
||||
};
|
||||
|
||||
// 定义表格列配置
|
||||
const columns = [
|
||||
{
|
||||
title: "分组名称",
|
||||
key: "name",
|
||||
width: "400px",
|
||||
render: (_: unknown, record: (RuleGroup & { isParent?: boolean, parentId?: string })) => (
|
||||
render: (_: unknown, record: RuleGroup & { isParent?: boolean, parentId?: string }) => (
|
||||
<div className={`flex items-center ${!record.isParent ? 'ml-8' : ''}`}>
|
||||
{record.isParent && (
|
||||
<span
|
||||
@@ -207,7 +459,11 @@ export default function RuleGroupsIndex() {
|
||||
}
|
||||
}}
|
||||
>
|
||||
<i className={`ri-arrow-${expandedGroups.includes(record.id) ? 'down' : 'right'}-s-line`}></i>
|
||||
{loading[record.id] ? (
|
||||
<i className="ri-loader-4-line animate-spin"></i>
|
||||
) : (
|
||||
<i className={`ri-arrow-${expandedGroups.includes(record.id) ? 'down' : 'right'}-s-line`}></i>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<Link
|
||||
@@ -225,35 +481,36 @@ export default function RuleGroupsIndex() {
|
||||
{
|
||||
title: "分组编码",
|
||||
key: "code",
|
||||
render: (_: unknown, record: RuleGroup) => record.code
|
||||
render: (_: unknown, record: RuleGroup) => (
|
||||
<span>{record.code || '-'}</span>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: "评查点数量",
|
||||
key: "ruleCount",
|
||||
render: (_: unknown, record: RuleGroup) => (
|
||||
<>
|
||||
<Link to={`/rule-groups/${record.id}/rules`} className="badge bg-primary text-white">
|
||||
{record.ruleCount}
|
||||
</Link>
|
||||
{record.subGroupCount > 0 && (
|
||||
<span className="text-secondary text-sm ml-1">
|
||||
| 子分组: {record.subGroupCount}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
render: (_: unknown, record: RuleGroup & { isParent?: boolean, parentId?: string }) => (
|
||||
<Link to={`/rule-groups/${record.id}/rules`} className="badge bg-primary text-white">
|
||||
{calculateTotalRuleCount(record)}
|
||||
</Link>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: "状态",
|
||||
key: "status",
|
||||
key: "is_enabled",
|
||||
render: (_: unknown, record: RuleGroup) => (
|
||||
<StatusDot status={record.status === 'active' ? 'success' : 'error'} text={record.status === 'active' ? '启用' : '禁用'} />
|
||||
<StatusDot
|
||||
status={record.is_enabled ? 'success' : 'error'}
|
||||
text={record.is_enabled ? '启用' : '禁用'}
|
||||
align="left"
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: "创建时间",
|
||||
key: "createdAt",
|
||||
render: (_: unknown, record: RuleGroup) => record.createdAt
|
||||
render: (_: unknown, record: RuleGroup) => (
|
||||
<span>{record.createdAt || '-'}</span>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
@@ -319,9 +576,9 @@ export default function RuleGroupsIndex() {
|
||||
<Button type="default" icon="ri-refresh-line" onClick={handleReset} className="mr-2">
|
||||
重置
|
||||
</Button>
|
||||
<Button type="primary" icon="ri-search-line">
|
||||
{/* <Button type="primary" icon="ri-search-line" onClick={() => {}}>
|
||||
搜索
|
||||
</Button>
|
||||
</Button> */}
|
||||
</>
|
||||
}
|
||||
noActionDivider={true}
|
||||
@@ -346,11 +603,11 @@ export default function RuleGroupsIndex() {
|
||||
|
||||
<FilterSelect
|
||||
label="状态"
|
||||
name="status"
|
||||
value={searchParams.get('status') || ''}
|
||||
name="is_enabled"
|
||||
value={searchParams.get('is_enabled') || ''}
|
||||
options={[
|
||||
{ value: "active", label: "启用" },
|
||||
{ value: "inactive", label: "禁用" }
|
||||
{ value: "true", label: "启用" },
|
||||
{ value: "false", label: "禁用" }
|
||||
]}
|
||||
onChange={handleStatusChange}
|
||||
className="flex-1 min-w-[200px]"
|
||||
@@ -359,22 +616,31 @@ export default function RuleGroupsIndex() {
|
||||
|
||||
{/* 数据表格 - 使用Table组件 */}
|
||||
<Card bodyClassName="px-4 py-4">
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={processedData}
|
||||
rowKey="id"
|
||||
emptyText="暂无分组数据"
|
||||
className="tree-table"
|
||||
/>
|
||||
|
||||
{/* 分页 - 使用Pagination组件 */}
|
||||
<Pagination
|
||||
currentPage={1}
|
||||
total={groups.length}
|
||||
pageSize={10}
|
||||
onChange={() => {}}
|
||||
showTotal={true}
|
||||
/>
|
||||
{initialLoading ? (
|
||||
<div className="flex justify-center items-center py-10">
|
||||
<i className="ri-loader-4-line animate-spin text-2xl mr-2"></i>
|
||||
<span>正在加载分组数据...</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={processedData}
|
||||
rowKey="id"
|
||||
emptyText="暂无分组数据"
|
||||
className="tree-table"
|
||||
/>
|
||||
|
||||
{/* 分页 - 使用Pagination组件 */}
|
||||
<Pagination
|
||||
currentPage={1}
|
||||
total={processedData.length}
|
||||
pageSize={10}
|
||||
onChange={() => {}}
|
||||
showTotal={true}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,14 @@ import { useEffect, useState } from "react";
|
||||
import { Button } from "~/components/ui/Button";
|
||||
import { Card } from "~/components/ui/Card";
|
||||
import ruleGroupsNewStyles from "~/styles/pages/rule-groups_new.css?url";
|
||||
import {
|
||||
getRuleGroups,
|
||||
getRuleGroup,
|
||||
createRuleGroup,
|
||||
updateRuleGroup,
|
||||
type RuleGroup as ApiRuleGroup,
|
||||
type RuleGroupCreateUpdateDto
|
||||
} from "~/api/evaluation_points/rule-groups";
|
||||
|
||||
// 类型定义
|
||||
interface RuleGroup {
|
||||
@@ -65,6 +73,19 @@ export const meta: MetaFunction = ({ location }) => {
|
||||
];
|
||||
};
|
||||
|
||||
// 将API分组转换为前端分组模型
|
||||
function mapApiToFrontend(apiGroup: ApiRuleGroup): RuleGroup {
|
||||
return {
|
||||
id: apiGroup.id,
|
||||
name: apiGroup.name,
|
||||
code: apiGroup.code || '',
|
||||
description: apiGroup.description,
|
||||
status: apiGroup.is_enabled ? 'active' : 'inactive',
|
||||
parentId: apiGroup.pid === '0' ? null : apiGroup.pid,
|
||||
sortOrder: 0 // API中不存在sortOrder字段,使用默认值
|
||||
};
|
||||
}
|
||||
|
||||
// 数据加载器
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
console.log("rule-groups.new loader被调用,URL:", request.url);
|
||||
@@ -74,85 +95,48 @@ export async function loader({ request }: LoaderFunctionArgs) {
|
||||
console.log("获取到的ID参数:", id);
|
||||
|
||||
// 获取一级分组列表 (用于选择父级分组)
|
||||
const parentGroups: ParentGroup[] = [
|
||||
{ id: "1", name: "合同基本要素检查" },
|
||||
{ id: "4", name: "销售合同专项检查" },
|
||||
{ id: "5", name: "行政处罚规范性检查" }
|
||||
];
|
||||
|
||||
// 简化这里,初始时不获取数据,避免可能的错误
|
||||
let group: RuleGroup | undefined = undefined;
|
||||
|
||||
// 如果有ID才尝试获取数据
|
||||
if (id) {
|
||||
// 简化的模拟数据
|
||||
const demoData: Record<string, RuleGroup> = {
|
||||
"1": {
|
||||
id: "1",
|
||||
name: "合同基本要素检查",
|
||||
code: "contract-base",
|
||||
description: "检查合同基本要素是否完整规范",
|
||||
status: "active",
|
||||
parentId: null,
|
||||
sortOrder: 0
|
||||
},
|
||||
"2": {
|
||||
id: "2",
|
||||
name: "必备要素检查",
|
||||
code: "essential-elements",
|
||||
description: "检查合同中的必要信息项是否齐全",
|
||||
status: "active",
|
||||
parentId: "1",
|
||||
sortOrder: 1
|
||||
},
|
||||
"3": {
|
||||
id: "3",
|
||||
name: "合同主体检查",
|
||||
code: "contract-parties",
|
||||
description: "检查合同主体信息是否规范",
|
||||
status: "active",
|
||||
parentId: "1",
|
||||
sortOrder: 2
|
||||
},
|
||||
"4": {
|
||||
id: "4",
|
||||
name: "销售合同专项检查",
|
||||
code: "contract-sales",
|
||||
description: "针对销售合同的专项合规检查",
|
||||
status: "active",
|
||||
parentId: null,
|
||||
sortOrder: 3
|
||||
},
|
||||
"5": {
|
||||
id: "5",
|
||||
name: "行政处罚规范性检查",
|
||||
code: "punishment",
|
||||
description: "对行政处罚文书的合规性检查",
|
||||
status: "inactive",
|
||||
parentId: null,
|
||||
sortOrder: 4
|
||||
}
|
||||
};
|
||||
|
||||
group = demoData[id];
|
||||
console.log("找到的group数据:", group);
|
||||
const parentGroupsResponse = await getRuleGroups();
|
||||
if (parentGroupsResponse.error) {
|
||||
console.error("获取父分组列表失败:", parentGroupsResponse.error);
|
||||
throw new Error(parentGroupsResponse.error);
|
||||
}
|
||||
|
||||
// 返回简化的数据结构
|
||||
return json<LoaderData>({
|
||||
const parentGroups: ParentGroup[] = parentGroupsResponse.data ? parentGroupsResponse.data.map(group => ({
|
||||
id: group.id,
|
||||
name: group.name
|
||||
})) : [];
|
||||
|
||||
// 初始化分组数据
|
||||
let group: RuleGroup | undefined = undefined;
|
||||
|
||||
// 如果有ID,获取分组详情
|
||||
if (id) {
|
||||
const groupResponse = await getRuleGroup(id);
|
||||
if (groupResponse.error) {
|
||||
console.error("获取分组详情失败:", groupResponse.error);
|
||||
throw new Error(groupResponse.error);
|
||||
}
|
||||
|
||||
if (groupResponse.data) {
|
||||
group = mapApiToFrontend(groupResponse.data);
|
||||
}
|
||||
}
|
||||
|
||||
// 返回加载的数据
|
||||
return Response.json({
|
||||
group,
|
||||
parentGroups,
|
||||
isEdit: !!group,
|
||||
error: undefined // 显式返回error字段,无错误时为undefined
|
||||
error: undefined
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("loader函数出错:", error);
|
||||
// 返回一个基本的响应,避免500错误
|
||||
return json<LoaderData>({
|
||||
return Response.json({
|
||||
group: undefined,
|
||||
parentGroups: [],
|
||||
isEdit: false,
|
||||
error: "加载数据时出错"
|
||||
error: error instanceof Error ? error.message : "加载数据时出错"
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -169,7 +153,6 @@ export async function action({ request }: ActionFunctionArgs) {
|
||||
const status = formData.get("status") as string || "active";
|
||||
const groupType = formData.get("groupType") as string;
|
||||
const parentId = groupType === "secondary" ? formData.get("parentId") as string : null;
|
||||
const sortOrder = parseInt(formData.get("sortOrder") as string || "0", 10);
|
||||
|
||||
// 表单验证
|
||||
const errors: ActionData["errors"] = {};
|
||||
@@ -180,8 +163,8 @@ export async function action({ request }: ActionFunctionArgs) {
|
||||
|
||||
if (!code || code.trim() === "") {
|
||||
errors.code = "分组编码不能为空";
|
||||
} else if (!/^[a-zA-Z0-9-]+$/.test(code)) {
|
||||
errors.code = "分组编码只能包含字母、数字和连字符";
|
||||
} else if (!/^[a-zA-Z0-9-_]+$/.test(code)) {
|
||||
errors.code = "分组编码只能包含字母、数字、连字符和下划线";
|
||||
}
|
||||
|
||||
if (groupType === "secondary" && (!parentId || parentId.trim() === "")) {
|
||||
@@ -189,38 +172,41 @@ export async function action({ request }: ActionFunctionArgs) {
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
return json<ActionData>({
|
||||
return Response.json({
|
||||
errors,
|
||||
values: Object.fromEntries(formData) as Record<string, string>
|
||||
});
|
||||
}
|
||||
|
||||
// 构建保存数据
|
||||
const saveData = {
|
||||
id,
|
||||
const saveData: RuleGroupCreateUpdateDto = {
|
||||
name: name.trim(),
|
||||
code: code.trim(),
|
||||
description: description?.trim() || "",
|
||||
status,
|
||||
parentId,
|
||||
sortOrder
|
||||
is_enabled: status === "active",
|
||||
pid: parentId === null ? "0" : parentId
|
||||
};
|
||||
|
||||
try {
|
||||
// 实际应用中应调用API
|
||||
console.log("保存分组数据:", saveData);
|
||||
// 根据是否有ID决定是创建还是更新
|
||||
let response;
|
||||
if (id) {
|
||||
response = await updateRuleGroup(id, saveData);
|
||||
} else {
|
||||
response = await createRuleGroup(saveData);
|
||||
}
|
||||
|
||||
// const response = await fetch(`${process.env.API_BASE_URL}/api/rule-groups${id ? `/${id}` : ''}`, {
|
||||
// method: id ? "PUT" : "POST",
|
||||
// headers: {
|
||||
// "Content-Type": "application/json",
|
||||
// },
|
||||
// body: JSON.stringify(saveData),
|
||||
// });
|
||||
//
|
||||
// if (!response.ok) {
|
||||
// throw new Error(`保存失败: ${response.status}`);
|
||||
// }
|
||||
// 处理API响应
|
||||
if (response.error) {
|
||||
console.error("保存分组失败:", response.error);
|
||||
return json<ActionData>({
|
||||
success: false,
|
||||
errors: {
|
||||
general: response.error
|
||||
},
|
||||
values: Object.fromEntries(formData) as Record<string, string>
|
||||
});
|
||||
}
|
||||
|
||||
// 保存成功,重定向到列表页
|
||||
return redirect("/rule-groups");
|
||||
@@ -229,7 +215,7 @@ export async function action({ request }: ActionFunctionArgs) {
|
||||
return json<ActionData>({
|
||||
success: false,
|
||||
errors: {
|
||||
general: "保存分组失败,请稍后重试"
|
||||
general: error instanceof Error ? error.message : "保存分组失败,请稍后重试"
|
||||
},
|
||||
values: Object.fromEntries(formData) as Record<string, string>
|
||||
});
|
||||
@@ -384,11 +370,13 @@ export default function RuleGroupNew() {
|
||||
defaultValue={group?.parentId || ""}
|
||||
>
|
||||
<option value="">请选择上级分组</option>
|
||||
{parentGroups.map((parent) => (
|
||||
<option key={parent.id} value={parent.id}>
|
||||
{parent.name}
|
||||
</option>
|
||||
))}
|
||||
{parentGroups
|
||||
.filter((parent: ParentGroup) => !group?.id || parent.id !== group.id) // 过滤掉当前编辑的分组
|
||||
.map((parent: ParentGroup) => (
|
||||
<option key={parent.id} value={parent.id}>
|
||||
{parent.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{actionData?.errors?.parentId && (
|
||||
<div className="form-error">{actionData.errors.parentId}</div>
|
||||
@@ -415,7 +403,7 @@ export default function RuleGroupNew() {
|
||||
{actionData?.errors?.code && (
|
||||
<div className="form-error">{actionData.errors.code}</div>
|
||||
)}
|
||||
<div className="form-tip">编码只能包含字母、数字和连字符,且必须唯一</div>
|
||||
<div className="form-tip">编码只能包含字母、数字、连字符和下划线,且必须唯一</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-col">
|
||||
@@ -477,7 +465,7 @@ export default function RuleGroupNew() {
|
||||
</div>
|
||||
|
||||
{/* 排序 */}
|
||||
<div className="form-group" style={{ maxWidth: "400px" }}>
|
||||
<div className="form-group hidden" style={{ maxWidth: "400px" }}>
|
||||
<label htmlFor="sortOrder" className="form-label">排序</label>
|
||||
<input
|
||||
type="number"
|
||||
|
||||
+14
-34
@@ -6,6 +6,8 @@ import { FileIcon } from "~/components/ui/FileIcon";
|
||||
import { FilterPanel, FilterSelect, SearchFilter } from "~/components/ui/FilterPanel";
|
||||
import { Pagination } from "~/components/ui/Pagination";
|
||||
import { Table } from "~/components/ui/Table";
|
||||
import { FileTypeTag } from "~/components/ui/FileTypeTag";
|
||||
import { StatusBadge } from "~/components/ui/StatusBadge";
|
||||
import rulesFilesStyles from "~/styles/pages/rules-files.css?url";
|
||||
|
||||
export const links = () => [
|
||||
@@ -371,22 +373,6 @@ export default function RulesFiles() {
|
||||
{ value: DateRange.CUSTOM, label: '自定义时间段' }
|
||||
];
|
||||
|
||||
// 获取文件状态对应的图标和类名
|
||||
const getStatusInfo = (status: ReviewStatus) => {
|
||||
switch (status) {
|
||||
case ReviewStatus.PASS:
|
||||
return { icon: "ri-checkbox-circle-line", className: "success" };
|
||||
case ReviewStatus.WARNING:
|
||||
return { icon: "ri-alert-line", className: "warning" };
|
||||
case ReviewStatus.FAIL:
|
||||
return { icon: "ri-close-circle-line", className: "error" };
|
||||
case ReviewStatus.PENDING:
|
||||
return { icon: "ri-time-line", className: "processing" };
|
||||
default:
|
||||
return { icon: "", className: "default" };
|
||||
}
|
||||
};
|
||||
|
||||
// 定义表格列配置
|
||||
const columns = [
|
||||
{
|
||||
@@ -414,14 +400,11 @@ export default function RulesFiles() {
|
||||
key: "fileType",
|
||||
width: "12%",
|
||||
render: (_: unknown, file: ReviewFile) => (
|
||||
<span className={`file-type-tag file-type-tag-${file.fileType}`}>
|
||||
{file.fileType === FileType.CONTRACT && <i className="ri-file-list-3-line"></i>}
|
||||
{file.fileType === FileType.LICENSE && <i className="ri-vip-crown-line"></i>}
|
||||
{file.fileType === FileType.PUNISHMENT && <i className="ri-scales-line"></i>}
|
||||
{file.fileType === FileType.REPORT && <i className="ri-file-chart-line"></i>}
|
||||
{file.fileType === FileType.OTHER && <i className="ri-file-line"></i>}
|
||||
{FILE_TYPE_LABELS[file.fileType]}
|
||||
</span>
|
||||
<FileTypeTag
|
||||
type={file.fileType}
|
||||
text={FILE_TYPE_LABELS[file.fileType]}
|
||||
showIcon={true}
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
@@ -440,16 +423,13 @@ export default function RulesFiles() {
|
||||
title: "评查状态",
|
||||
key: "reviewStatus",
|
||||
width: "12%",
|
||||
render: (_: unknown, file: ReviewFile) => {
|
||||
const statusInfo = getStatusInfo(file.reviewStatus);
|
||||
return (
|
||||
<span className={`status-badge status-badge-${statusInfo.className.replace('status-', '')}`}>
|
||||
<i className={`${statusInfo.icon} mr-1`}></i>
|
||||
{REVIEW_STATUS_LABELS[file.reviewStatus]}
|
||||
{file.issueCount > 0 && ` (${file.issueCount})`}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
render: (_: unknown, file: ReviewFile) => (
|
||||
<StatusBadge
|
||||
status={file.reviewStatus}
|
||||
text={file.issueCount > 0 ? `${REVIEW_STATUS_LABELS[file.reviewStatus]} (${file.issueCount})` : REVIEW_STATUS_LABELS[file.reviewStatus]}
|
||||
showIcon={true}
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: "问题摘要",
|
||||
|
||||
+214
-244
@@ -1,18 +1,26 @@
|
||||
import React, { useState } from 'react';
|
||||
import { json, type MetaFunction, type LoaderFunctionArgs, redirect } from "@remix-run/node";
|
||||
import { useLoaderData, useSearchParams, useSubmit,Link } from "@remix-run/react";
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { type MetaFunction, type LoaderFunctionArgs, redirect } from "@remix-run/node";
|
||||
import { useLoaderData, useSearchParams, useSubmit, Link } from "@remix-run/react";
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { Card } from '~/components/ui/Card';
|
||||
import { Tag } from '~/components/ui/Tag';
|
||||
import { StatusDot } from '~/components/ui/StatusDot';
|
||||
import rulesStyles from "~/styles/pages/rules_index.css?url";
|
||||
import type { Rule } from '~/models/rule';
|
||||
import { RULE_TYPE_LABELS, RULE_TYPE_COLORS, RULE_PRIORITY_LABELS, RULE_PRIORITY_COLORS } from '~/models/rule';
|
||||
import type { Rule, RuleType, RulePriority } from '~/models/rule';
|
||||
import { RULE_TYPE_COLORS, RULE_PRIORITY_LABELS, RULE_PRIORITY_COLORS } from '~/models/rule';
|
||||
import type { TagColor } from '~/components/ui/Tag';
|
||||
import { Table } from '~/components/ui/Table';
|
||||
import { FilterPanel, FilterSelect, SearchFilter } from '~/components/ui/FilterPanel';
|
||||
import { Pagination } from '~/components/ui/Pagination';
|
||||
// import { getRulesList } from '~/api/evaluation_points/rules';
|
||||
import {
|
||||
getRulesList,
|
||||
deleteRule,
|
||||
duplicateRule,
|
||||
getRuleTypes,
|
||||
getRuleGroupsByType,
|
||||
type RuleType as ApiRuleType,
|
||||
type RuleGroup
|
||||
} from '~/api/evaluation_points/rules';
|
||||
|
||||
export const links = () => [
|
||||
{ rel: "stylesheet", href: rulesStyles }
|
||||
@@ -27,159 +35,48 @@ export const meta: MetaFunction = () => {
|
||||
];
|
||||
};
|
||||
|
||||
// 模拟数据 - 用于开发阶段展示UI
|
||||
const mockRules: Rule[] = [
|
||||
{
|
||||
id: '1',
|
||||
code: 'EP001',
|
||||
name: '合同名称要素检查',
|
||||
ruleType: 'essential',
|
||||
ruleGroupId: '1',
|
||||
groupName: '合同基本要素类检查',
|
||||
priority: 'high',
|
||||
description: '检查合同是否包含清晰的合同名称',
|
||||
checkMethod: 'automatic',
|
||||
prompt: '查找文档中的合同名称',
|
||||
isActive: true,
|
||||
createdAt: '2024-03-15T08:30:00Z',
|
||||
updatedAt: '2024-03-15T08:30:00Z'
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
code: 'EP002',
|
||||
name: '合同编号要素检查',
|
||||
ruleType: 'essential',
|
||||
ruleGroupId: '1',
|
||||
groupName: '合同基本要素类检查',
|
||||
priority: 'high',
|
||||
description: '检查合同是否包含唯一的合同编号',
|
||||
checkMethod: 'automatic',
|
||||
prompt: '查找文档中的合同编号',
|
||||
isActive: true,
|
||||
createdAt: '2024-03-15T09:15:00Z',
|
||||
updatedAt: '2024-03-15T09:15:00Z'
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
code: 'EP003',
|
||||
name: '合同主体资格检查',
|
||||
ruleType: 'legal',
|
||||
ruleGroupId: '2',
|
||||
groupName: '销售合同专项检查',
|
||||
priority: 'medium',
|
||||
description: '检查合同签署方是否具有合法的主体资格',
|
||||
checkMethod: 'manual',
|
||||
prompt: '确认合同签署方的法律主体资格',
|
||||
isActive: true,
|
||||
createdAt: '2024-03-16T10:20:00Z',
|
||||
updatedAt: '2024-03-16T10:20:00Z'
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
code: 'EP004',
|
||||
name: '付款条件检查',
|
||||
ruleType: 'content',
|
||||
ruleGroupId: '2',
|
||||
groupName: '销售合同专项检查',
|
||||
priority: 'medium',
|
||||
description: '检查合同中的付款条件是否明确',
|
||||
checkMethod: 'automatic',
|
||||
prompt: '提取文档中的付款条件相关内容',
|
||||
isActive: true,
|
||||
createdAt: '2024-03-17T11:30:00Z',
|
||||
updatedAt: '2024-03-17T11:30:00Z'
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
code: 'EP005',
|
||||
name: '违约责任条款检查',
|
||||
ruleType: 'legal',
|
||||
ruleGroupId: '3',
|
||||
groupName: '采购合同专项检查',
|
||||
priority: 'high',
|
||||
description: '检查合同是否包含违约责任条款',
|
||||
checkMethod: 'mixed',
|
||||
prompt: '提取文档中的违约责任相关条款',
|
||||
isActive: true,
|
||||
createdAt: '2024-03-18T13:45:00Z',
|
||||
updatedAt: '2024-03-18T13:45:00Z'
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
code: 'EP006',
|
||||
name: '合同文本格式检查',
|
||||
ruleType: 'format',
|
||||
ruleGroupId: '1',
|
||||
groupName: '合同基本要素类检查',
|
||||
priority: 'low',
|
||||
description: '检查合同文本格式是否符合规范',
|
||||
checkMethod: 'automatic',
|
||||
prompt: '检查文档的整体格式规范性',
|
||||
isActive: false,
|
||||
createdAt: '2024-03-19T14:50:00Z',
|
||||
updatedAt: '2024-03-19T14:50:00Z'
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
code: 'EP007',
|
||||
name: '专卖许可证有效性检查',
|
||||
ruleType: 'legal',
|
||||
ruleGroupId: '4',
|
||||
groupName: '专卖许可证审核规则',
|
||||
priority: 'high',
|
||||
description: '检查专卖许可证是否在有效期内',
|
||||
checkMethod: 'automatic',
|
||||
prompt: '提取专卖许可证有效期信息并判断有效性',
|
||||
isActive: true,
|
||||
createdAt: '2024-03-20T15:55:00Z',
|
||||
updatedAt: '2024-03-20T15:55:00Z'
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
code: 'EP008',
|
||||
name: '处罚决定书格式检查',
|
||||
ruleType: 'format',
|
||||
ruleGroupId: '5',
|
||||
groupName: '行政处罚规范性检查',
|
||||
priority: 'medium',
|
||||
description: '检查行政处罚决定书格式是否规范',
|
||||
checkMethod: 'automatic',
|
||||
prompt: '检查处罚决定书的格式规范性',
|
||||
isActive: true,
|
||||
createdAt: '2024-03-21T16:00:00Z',
|
||||
updatedAt: '2024-03-21T16:00:00Z'
|
||||
},
|
||||
{
|
||||
id: '9',
|
||||
code: 'EP009',
|
||||
name: '处罚依据合法性检查',
|
||||
ruleType: 'legal',
|
||||
ruleGroupId: '5',
|
||||
groupName: '行政处罚规范性检查',
|
||||
priority: 'high',
|
||||
description: '检查行政处罚依据是否合法',
|
||||
checkMethod: 'manual',
|
||||
prompt: '审核处罚依据的法律合法性',
|
||||
isActive: true,
|
||||
createdAt: '2024-03-22T09:10:00Z',
|
||||
updatedAt: '2024-03-22T09:10:00Z'
|
||||
},
|
||||
{
|
||||
id: '10',
|
||||
code: 'EP010',
|
||||
name: '业务特殊条款检查',
|
||||
ruleType: 'business',
|
||||
ruleGroupId: '3',
|
||||
groupName: '采购合同专项检查',
|
||||
priority: 'medium',
|
||||
description: '检查合同是否包含烟草行业特殊条款',
|
||||
checkMethod: 'mixed',
|
||||
prompt: '识别文档中的烟草行业特殊要求条款',
|
||||
isActive: true,
|
||||
createdAt: '2024-03-23T10:15:00Z',
|
||||
updatedAt: '2024-03-23T10:15:00Z'
|
||||
}
|
||||
];
|
||||
// 声明loader返回的数据类型
|
||||
export type LoaderData = {
|
||||
rules: Rule[];
|
||||
totalCount: number;
|
||||
currentPage: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
ruleTypes: ApiRuleType[]; // 添加评查点类型
|
||||
};
|
||||
|
||||
// API返回的数据映射到前端模型
|
||||
interface ApiRule {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
ruleType: string;
|
||||
groupId: string;
|
||||
groupName: string;
|
||||
priority: string;
|
||||
description: string;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
function mapApiRuleToModel(apiRule: ApiRule): Rule {
|
||||
return {
|
||||
id: apiRule.id,
|
||||
code: apiRule.code,
|
||||
name: apiRule.name,
|
||||
ruleType: apiRule.ruleType as RuleType, // 类型转换
|
||||
ruleGroupId: apiRule.groupId,
|
||||
groupName: apiRule.groupName,
|
||||
priority: apiRule.priority as RulePriority, // 类型转换
|
||||
description: apiRule.description,
|
||||
checkMethod: 'automatic', // 默认值
|
||||
prompt: apiRule.description, // 使用描述作为默认prompt
|
||||
isActive: apiRule.isActive,
|
||||
createdAt: apiRule.createdAt,
|
||||
updatedAt: apiRule.updatedAt
|
||||
};
|
||||
}
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const url = new URL(request.url);
|
||||
@@ -195,34 +92,32 @@ export async function loader({ request }: LoaderFunctionArgs) {
|
||||
};
|
||||
|
||||
try {
|
||||
// 使用模拟数据而不是API调用
|
||||
// const response = await getRulesList(params);
|
||||
// 获取评查点类型列表
|
||||
const typeResponse = await getRuleTypes();
|
||||
|
||||
// 过滤模拟数据
|
||||
let filteredRules = [...mockRules];
|
||||
|
||||
if (params.ruleType) {
|
||||
filteredRules = filteredRules.filter(rule => rule.ruleType === params.ruleType);
|
||||
if (typeResponse.error) {
|
||||
console.error('获取评查点类型失败:', typeResponse.error);
|
||||
}
|
||||
|
||||
if (params.groupId) {
|
||||
filteredRules = filteredRules.filter(rule => rule.ruleGroupId === params.groupId);
|
||||
const ruleTypes = typeResponse.error ? [] : typeResponse.data;
|
||||
|
||||
// 使用API调用获取数据
|
||||
const response = await getRulesList(params);
|
||||
|
||||
// API错误处理集中在rules.ts中,这里只需检查是否有错误
|
||||
if (response.error) {
|
||||
throw new Error(response.error);
|
||||
}
|
||||
|
||||
if (params.isActive !== undefined) {
|
||||
filteredRules = filteredRules.filter(rule => rule.isActive === params.isActive);
|
||||
if (!response.data) {
|
||||
throw new Error('API返回数据为空');
|
||||
}
|
||||
|
||||
if (params.keyword) {
|
||||
const keyword = params.keyword.toLowerCase();
|
||||
filteredRules = filteredRules.filter(
|
||||
rule => rule.name.toLowerCase().includes(keyword) ||
|
||||
rule.code.toLowerCase().includes(keyword)
|
||||
);
|
||||
}
|
||||
const apiRules = response.data.rules;
|
||||
const totalCount = response.data.totalCount;
|
||||
const rules = apiRules.map((apiRule: ApiRule) => mapApiRuleToModel(apiRule));
|
||||
|
||||
// 计算总记录数
|
||||
const totalCount = filteredRules.length;
|
||||
// 计算总页数
|
||||
const totalPages = Math.ceil(totalCount / params.pageSize);
|
||||
|
||||
// 验证页码范围
|
||||
@@ -232,16 +127,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
|
||||
return redirect(newUrl.pathname + newUrl.search);
|
||||
}
|
||||
|
||||
// 分页
|
||||
const offset = (params.page - 1) * params.pageSize;
|
||||
const paginatedRules = filteredRules.slice(offset, offset + params.pageSize);
|
||||
|
||||
return json({
|
||||
rules: paginatedRules,
|
||||
return Response.json({
|
||||
rules,
|
||||
totalCount,
|
||||
currentPage: params.page,
|
||||
pageSize: params.pageSize,
|
||||
totalPages
|
||||
totalPages,
|
||||
ruleTypes
|
||||
}, {
|
||||
headers: {
|
||||
"Cache-Control": "max-age=60, s-maxage=180"
|
||||
@@ -260,46 +152,62 @@ export async function action({ request }: LoaderFunctionArgs) {
|
||||
const ruleId = formData.get('ruleId');
|
||||
|
||||
if (!ruleId) {
|
||||
return json({ success: false, error: "缺少评查点ID" }, { status: 400 });
|
||||
return Response.json({ success: false, error: "缺少评查点ID" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
if (_action === 'delete') {
|
||||
// 实际项目中应调用API删除评查点
|
||||
// 调用API删除评查点
|
||||
console.log(`删除评查点 ${ruleId}`);
|
||||
|
||||
// 模拟API调用
|
||||
// const response = await fetch(`/api/rules/${ruleId}`, {
|
||||
// method: 'DELETE',
|
||||
// });
|
||||
|
||||
// if (!response.ok) {
|
||||
// throw new Error(`删除失败: ${response.status}`);
|
||||
// }
|
||||
|
||||
return json({ success: true });
|
||||
try {
|
||||
const deleteResponse = await deleteRule(ruleId as string);
|
||||
|
||||
if (deleteResponse.error) {
|
||||
throw new Error(deleteResponse.error);
|
||||
}
|
||||
|
||||
// 删除成功,获取当前URL
|
||||
const url = new URL(request.url);
|
||||
// 返回重定向响应,以刷新页面数据
|
||||
return redirect(`${url.pathname}${url.search}`);
|
||||
} catch (error) {
|
||||
console.error('删除评查点失败:', error);
|
||||
return Response.json({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : "删除失败"
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
if (_action === 'duplicate') {
|
||||
// 实际项目中应调用API复制评查点
|
||||
// 复制评查点
|
||||
console.log(`复制评查点 ${ruleId}`);
|
||||
|
||||
// 模拟API调用
|
||||
// const response = await fetch(`/api/rules/${ruleId}/duplicate`, {
|
||||
// method: 'POST',
|
||||
// });
|
||||
|
||||
// if (!response.ok) {
|
||||
// throw new Error(`复制失败: ${response.status}`);
|
||||
// }
|
||||
|
||||
return json({ success: true });
|
||||
try {
|
||||
const duplicateResponse = await duplicateRule(ruleId as string);
|
||||
|
||||
if (duplicateResponse.error) {
|
||||
throw new Error(duplicateResponse.error);
|
||||
}
|
||||
|
||||
// 复制成功,获取当前URL
|
||||
const url = new URL(request.url);
|
||||
// 返回重定向响应,以刷新页面数据
|
||||
return redirect(`${url.pathname}${url.search}`);
|
||||
} catch (error) {
|
||||
console.error('复制评查点失败:', error);
|
||||
return Response.json({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : "复制失败"
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
return json({ success: false, error: "未知操作" }, { status: 400 });
|
||||
return Response.json({ success: false, error: "未知操作" }, { status: 400 });
|
||||
} catch (error) {
|
||||
console.error('操作评查点失败:', error);
|
||||
return json({ success: false, error: "操作失败" }, { status: 500 });
|
||||
return Response.json({ success: false, error: "操作失败" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,15 +221,7 @@ export function ErrorBoundary() {
|
||||
);
|
||||
}
|
||||
|
||||
// 规则类型和优先级的描述标签映射
|
||||
const typeLabels = {
|
||||
'essential': '基本要素类',
|
||||
'content': '内容合规类',
|
||||
'legal': '法律风险类',
|
||||
'format': '格式规范类',
|
||||
'business': '业务专项类'
|
||||
};
|
||||
|
||||
// 规则优先级的描述标签映射
|
||||
const priorityLabels = {
|
||||
'high': '高',
|
||||
'medium': '中',
|
||||
@@ -329,22 +229,81 @@ const priorityLabels = {
|
||||
};
|
||||
|
||||
export default function RulesIndex() {
|
||||
const { rules, totalCount, currentPage, pageSize } = useLoaderData<typeof loader>();
|
||||
const loaderData = useLoaderData<typeof loader>();
|
||||
const { rules, totalCount, currentPage, pageSize } = loaderData;
|
||||
const ruleTypes = loaderData.ruleTypes || []; // 添加默认空数组避免undefined
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const submit = useSubmit();
|
||||
|
||||
// 状态管理
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
||||
const [ruleToDelete, setRuleToDelete] = useState<Rule | null>(null);
|
||||
const [ruleGroups, setRuleGroups] = useState<RuleGroup[]>([]);
|
||||
const [loadingGroups, setLoadingGroups] = useState(false);
|
||||
|
||||
// 判断是否禁用规则组选择
|
||||
const isRuleGroupSelectDisabled = loadingGroups || !searchParams.get('ruleType') || ruleGroups.length === 0;
|
||||
|
||||
// 当评查点类型变化时,加载对应的规则组
|
||||
useEffect(() => {
|
||||
const selectedType = searchParams.get('ruleType');
|
||||
|
||||
// 如果选择了"全部"或未选择,则清空规则组
|
||||
if (!selectedType || selectedType === 'all') {
|
||||
setRuleGroups([]);
|
||||
return;
|
||||
}
|
||||
|
||||
// 加载当前类型的规则组
|
||||
const loadRuleGroups = async () => {
|
||||
setLoadingGroups(true);
|
||||
try {
|
||||
const response = await getRuleGroupsByType(selectedType);
|
||||
if (response.data) {
|
||||
setRuleGroups(response.data);
|
||||
} else if (response.error) {
|
||||
console.error('加载规则组失败:', response.error);
|
||||
setRuleGroups([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载规则组出错:', error);
|
||||
setRuleGroups([]);
|
||||
} finally {
|
||||
setLoadingGroups(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadRuleGroups();
|
||||
}, [searchParams.get('ruleType')]);
|
||||
|
||||
const handleFilterChange = (e: React.ChangeEvent<HTMLSelectElement | HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
const newParams = new URLSearchParams(searchParams);
|
||||
|
||||
// 如果是规则组选择,但是当前应该被禁用,则不处理
|
||||
if (name === 'groupId' && isRuleGroupSelectDisabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (value) {
|
||||
newParams.set(name, value);
|
||||
|
||||
// 如果是评查点类型变更,清空规则组选择
|
||||
if (name === 'ruleType') {
|
||||
newParams.delete('groupId');
|
||||
// 如果选择了"全部"或空值,也清空规则组选择
|
||||
if (value === '' || value === 'all') {
|
||||
setRuleGroups([]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newParams.delete(name);
|
||||
|
||||
// 如果清除评查点类型,也清除规则组
|
||||
if (name === 'ruleType') {
|
||||
newParams.delete('groupId');
|
||||
setRuleGroups([]);
|
||||
}
|
||||
}
|
||||
|
||||
// 切换筛选条件时,重置到第一页
|
||||
@@ -368,6 +327,7 @@ export default function RulesIndex() {
|
||||
};
|
||||
|
||||
const handleDeleteClick = (rule: Rule) => {
|
||||
console.log("handleDELETEclick",rule)
|
||||
setRuleToDelete(rule);
|
||||
setShowDeleteConfirm(true);
|
||||
};
|
||||
@@ -416,24 +376,31 @@ export default function RulesIndex() {
|
||||
title: "评查点编码",
|
||||
dataIndex: "code" as keyof Rule,
|
||||
key: "code",
|
||||
align: "center" as const
|
||||
align: "left" as const,
|
||||
width: "20%",
|
||||
className: "whitespace-normal break-all",
|
||||
render: (value: string) => (
|
||||
<div className="whitespace-normal break-all overflow-visible">{value}</div>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: "评查点名称",
|
||||
dataIndex: "name" as keyof Rule,
|
||||
key: "name",
|
||||
align: "center" as const
|
||||
align: "left" as const,
|
||||
width: "20%"
|
||||
},
|
||||
{
|
||||
title: "评查点类型",
|
||||
key: "ruleType",
|
||||
align: "center" as const,
|
||||
align: "left" as const,
|
||||
width: "12%",
|
||||
render: (_: unknown, record: Rule) => {
|
||||
const typeColor = RULE_TYPE_COLORS[record.ruleType] as TagColor;
|
||||
return (
|
||||
<Tag color={typeColor}>
|
||||
{typeLabels[record.ruleType as keyof typeof typeLabels] || RULE_TYPE_LABELS[record.ruleType]}
|
||||
</Tag>
|
||||
record.ruleType ? <Tag color={typeColor}>
|
||||
{record.ruleType}
|
||||
</Tag> : null
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -441,12 +408,14 @@ export default function RulesIndex() {
|
||||
title: "所属规则组",
|
||||
dataIndex: "groupName" as keyof Rule,
|
||||
key: "groupName",
|
||||
align: "center" as const
|
||||
align: "left" as const,
|
||||
width: "10%"
|
||||
},
|
||||
{
|
||||
title: "优先级",
|
||||
key: "priority",
|
||||
align: "center" as const,
|
||||
align: "left" as const,
|
||||
width: "5%",
|
||||
render: (_: unknown, record: Rule) => {
|
||||
const priorityColor = RULE_PRIORITY_COLORS[record.priority] as TagColor;
|
||||
return (
|
||||
@@ -459,8 +428,8 @@ export default function RulesIndex() {
|
||||
{
|
||||
title: "状态",
|
||||
key: "isActive",
|
||||
align: "center" as const,
|
||||
className: "status-column",
|
||||
align: "left" as const,
|
||||
width: "8%",
|
||||
render: (_: unknown, record: Rule) => (
|
||||
<StatusDot status={record.isActive} text={record.isActive ? "启用" : "禁用"} />
|
||||
)
|
||||
@@ -469,12 +438,14 @@ export default function RulesIndex() {
|
||||
title: "创建时间",
|
||||
dataIndex: "createdAt" as keyof Rule,
|
||||
key: "createdAt",
|
||||
align: "center" as const
|
||||
align: "left" as const,
|
||||
width: "10%"
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
key: "operation",
|
||||
align: "center" as const,
|
||||
align: "left" as const,
|
||||
width: "10%",
|
||||
render: (_: unknown, record: Rule) => (
|
||||
<div className="operations-cell">
|
||||
<Link to={`/rules/${record.id}`} className="operation-btn">
|
||||
@@ -508,11 +479,10 @@ export default function RulesIndex() {
|
||||
name="ruleType"
|
||||
value={searchParams.get('ruleType') || ''}
|
||||
options={[
|
||||
{ value: "essential", label: "基本要素类" },
|
||||
{ value: "content", label: "内容合规类" },
|
||||
{ value: "format", label: "格式规范类" },
|
||||
{ value: "legal", label: "法律风险类" },
|
||||
{ value: "business", label: "业务专项类" }
|
||||
...ruleTypes.map((type: ApiRuleType) => ({
|
||||
value: type.id,
|
||||
label: type.name
|
||||
}))
|
||||
]}
|
||||
onChange={handleFilterChange}
|
||||
className="mr-3 w-60 "
|
||||
@@ -523,14 +493,14 @@ export default function RulesIndex() {
|
||||
name="groupId"
|
||||
value={searchParams.get('groupId') || ''}
|
||||
options={[
|
||||
{ value: "1", label: "合同基本要素类检查" },
|
||||
{ value: "2", label: "销售合同专项检查" },
|
||||
{ value: "3", label: "采购合同专项检查" },
|
||||
{ value: "4", label: "专卖许可证审核规则" },
|
||||
{ value: "5", label: "行政处罚规范性检查" }
|
||||
...(isRuleGroupSelectDisabled ? [{ value: "", label: "请先选择评查点类型" }] : []),
|
||||
...ruleGroups.map(group => ({
|
||||
value: group.id,
|
||||
label: group.name
|
||||
}))
|
||||
]}
|
||||
onChange={handleFilterChange}
|
||||
className="mr-3 w-60"
|
||||
className={`mr-3 w-60 ${isRuleGroupSelectDisabled ? 'opacity-50' : ''}`}
|
||||
/>
|
||||
|
||||
<FilterSelect
|
||||
|
||||
Reference in New Issue
Block a user